enforcing-nophi-logging
Qué hace
Esta skill añade un filtro de seguridad que quita la información de salud protegida de los registros, las trazas y los informes de error antes de escribirlos o enviarlos. Es para equipos cuyo procesamiento de texto clínico podría filtrar datos de pacientes a los registros.
Cuándo usarla
- ✓Cuando un servicio de OpenMed registra el texto de las solicitudes, la salida del modelo o mensajes de error que pueden contener datos de pacientes.
- ✓Cuando los registros o los rastreadores de errores se envían a un servicio central fuera del límite de desidentificación.
- ✓Cuando necesitas campos de registro estructurados que contengan recuentos o hashes en lugar de texto en bruto.
Link de la skill
https://github.com/maziyarpanahi/openmed/blob/master/skills/enforcing-nophi-logging/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Nuestra API de OpenMed registra el texto de las solicitudes y a veces envía trazas de pila a un rastreador de errores. Añade un filtro para que no se guarde ningún dato de paciente.”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
El agente añade al sistema de registro un filtro rápido de patrones y un modelo de respaldo, para que los registros se limpien antes de emitirse, y bloquea los registros que no puede comprobar.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de GitHub.
Enforcing No-PHI Logging
Logs are a top breach vector: a clinical string lands in a log line, gets shipped to a centralized log store and an error tracker, and is now PHI sitting outside the de-id boundary. OpenMed's local-first stance says no raw PHI in logs, caches, or error reports — this skill enforces it with a redaction guard that runs before any record is emitted.
When to use this skill
- An OpenMed service logs request text, model output, or exception messages.
- You ship logs/traces to a centralized store or error tracker (Sentry, ELK).
- You need a
logging.Filter(or OTel processor) that redacts PHI pre-emit. - You want structured, no-PHI log fields (offsets, hashes, counts) for debugging.
Quick start — a redacting logging.Filter
import logging
import re
import openmed
# Cheap regex pre-filter for the highest-risk structured identifiers. This runs
# on every record, so keep it fast; the model is the fallback for free-text PHI.
_FAST_PATTERNS = [
(re.compile(r"\b\d{3}-\d{2}-\d{4}\b"), "[SSN]"),
(re.compile(r"\b\d{16}\b"), "[CARD]"),
(re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b"), "[EMAIL]"),
(re.compile(r"\b(?:\+?\d[\d().\-\s]{7,}\d)\b"), "[PHONE]"),
]
class NoPHIFilter(logging.Filter):
"""Redact PHI from a log record before it is emitted. Fail closed."""
def __init__(self, model_name: str | None = None, use_model: bool = True):
super().__init__()
self.model_name = model_name
self.use_model = use_model
def filter(self, record: logging.LogRecord) -> bool:
try:
message = record.getMessage()
record.msg = self._scrub(message)
record.args = () # message already rendered & scrubbed
except Exception:
# Never let the logger leak on error — drop the message, keep the level.
record.msg = "[REDACTED: scrub error]"
record.args = ()
return True # keep the (now-clean) record
def _scrub(self, text: str) -> str:
for pattern, tag in _FAST_PATTERNS:
text = pattern.sub(tag, text)
if not self.use_model:
return text
# Model fallback for free-text PHI (names, locations, dates). Replace by
# offset, right-to-left, so earlier offsets stay valid.
spans = openmed.extract_pii(text, model_name=self.model_name) \
if self.model_name else openmed.extract_pii(text)
for e in sorted(spans.entities, key=lambda s: s.start, reverse=True):
text = text[:e.start] + f"[{e.label}]" + text[e.end:]
return text
# Attach to every handler that might emit clinical text.
handler = logging.StreamHandler()
handler.addFilter(NoPHIFilter(model_name="OpenMed/Privacy-PII-Detection"))
logging.getLogger("openmed.service").addHandler(handler)
Prefer structured, no-PHI fields
Don't log the note and scrub it — log about it without the text in the first place:
logger.info(
"deidentified note",
extra={
"doc_id": doc_id, # opaque id, not the text
"phi_entity_count": len(result.entities),
"phi_labels": sorted({e.label for e in result.entities}),
"char_len": len(text),
# offsets/hashes for debugging; never the plaintext span
"phi_offsets": [(e.start, e.end) for e in result.entities],
},
)
Redaction is the safety net; not logging PHI is the actual fix.
OpenTelemetry / error trackers
- Spans: add a
SpanProcessor.on_end(or attribute hook) that runs the same_scrubover string span attributes and events before export. - Error trackers: register a
before_sendhook (e.g. Sentry) that scrubs exception messages, breadcrumbs, and request bodies. Stack traces often embed the offending input — scrub the message, not just the frames.
Workflow
- Inventory sinks. List every place a clinical string can reach: app logs, access logs, OTel spans, error tracker, crash reports, request/response dumps.
- Install the regex pre-filter for structured identifiers (SSN, card, email, phone) — fast, runs on every record.
- Add the model fallback (
openmed.extract_pii) for free-text PHI on the sinks that carry clinical narrative; skip it on hot paths where regex suffices. - Switch to structured fields. Replace "log the text" with "log counts, labels, offsets, ids".
- Fail closed. On any scrub error,
Preguntas frecuentes
¿Filtra cada línea de registro?
Se ejecuta sobre cada registro, con un filtro rápido de patrones para identificadores comunes y un modelo para los datos personales en texto libre.
¿Qué pasa si el filtro falla?
Está diseñado para fallar en modo cerrado, así que los registros no seguros se bloquean en lugar de emitirse.
¿Cubre trazas e informes de error?
Sí. Cubre los tramos de OpenTelemetry y los rastreadores de errores, además de los registros normales.
Detalles
Descripción original del autor
Add a logging and telemetry guard that scrubs or blocks PHI from logs, traces, and error reports around an OpenMed deployment. Use when the user wants a Python logging.Filter that redacts protected health information before records are emitted, wants to keep PHI out of OpenTelemetry spans or error trackers, needs structured no-PHI log fields, or is worried that logs and stack traces are leaking patient data. Trigger on \"scrub logs\", \"redact PHI from logs\", \"no-PHI logging\", \"logging filter\", \"telemetry redaction\", \"logs leaking patient data\", or \"OpenTelemetry redaction\" in an Op
repo: maziyarpanahi/openmed
Popularidad
- Estrellas en GitHub
- 5,8 mil
- Posición en el ranking
- #14693
- Licencia
- Apache-2.0
- Actualizada
- 2/11/2026
Comentarios
- …
Más skills de este repositorio
annotating-variants
5,8 milAyuda a tu agente a predecir qué hace una variante genética, convertir nombres HGVS en posiciones del genoma y añadir frecuencias poblacionales, usando anotadores públicos gratuitos.
ask-openmed
5,8 milAyuda a tu agente a elegir el flujo de trabajo de OpenMed adecuado para una petición de texto clínico, empezando siempre por una comprobación de privacidad si puede haber datos de pacientes.
assembling-fhir-bundles
5,8 milEmpaqueta varios registros de salud FHIR en un único Bundle de transacción listo para enviar a un EHR, con las referencias internas enlazadas correctamente.
auditing-deid-leakage
5,8 milBusca en texto clínico desidentificado restos de identificadores, como números de la seguridad social, de tarjeta, correos y fechas, y bloquea la publicación si queda alguno.
Skills parecidas
reverse-engineer-anything
422 milAyuda a tu agente a revisar apps y paquetes ya publicados para explicar sus funciones, comparar versiones o guiar una reconstrucción, usando la herramienta REA.
1password
394 milAyuda a tu agente a instalar la CLI de 1Password, iniciar sesión y leer o inyectar secretos sin imprimir sus valores en el chat.
healthcheck
394 milAyuda a tu agente a auditar el ordenador o servidor que ejecuta OpenClaw en busca de riesgos de seguridad, como SSH, cortafuegos, actualizaciones y copias de seguridad, y después sugerir arreglos seguros.