name: medical-invoice-medical-audit description: Runs the clinical-pertinence audit of a Colombian medical invoice (valid CIE-10 diagnosis, adherence to MinSalud Guías de Práctica Clínica, signed medical order with RETHUS-registered professional, procedures with indication and operative note, medications with correct dose/duration, justified diagnostic aids, inpatient stay with admission criteria and daily progress, and epicrisis with discharge plan). Generates medical_checklist_output.json with findings cited to the clinical history. Use it when the user asks to audit the clinical side of a case, review procedure pertinence, or run the medical sub-agent of the pipeline. version: 2.0.0 author: claudio@arkangel.ai platforms: [macos, linux] metadata: hermes: tags: [medical, audit, clinical, gpc, cie10, rethus, colombia, eps, hospital] category: medical-insurance-audit requires_toolsets: [terminal]
medical-invoice-medical-audit
Medical sub-agent of the pipeline. Evaluates ~29 PERT-CLIN rules on clinical pertinence against the MinSalud clinical guidelines. Runs independently of the admin and financial auditors.
The question it answers: was what was billed clinically necessary, appropriate, and documented per the GPC? It does not evaluate tariff or documentary formality — that belongs to the other two.
When to Use
- The orchestrator dispatches the clinical leg of a case (task created with
task.context.audit_perspective = "aseguradora", or field absent). - The user asks "audit pertinence for invoice {RAD}" or "run the medical-auditor on case X".
- Re-auditing a case with doubtful clinical findings after human-review.
- Hospital self-audit before billing: the IPS wants to verify its own clinical documentation before submitting to the payer (set
AUDIT_PERSPECTIVE=hospital). All 29 PERT-CLIN rules apply; only M18 framing andcierrelanguage differ.
Do not use: if the case does not have HC or epicrisis attached; if medical_audit is already published and a re-audit was not requested.
Input Contract
Template: same metadata_input.json shape as admin-audit — see ../medical-invoice-gmail-intake/metadata_input.json.
Optional environment variable: GUIAS_CLINICAS_PATH — absolute path to the directory containing INDEX.md and the GPC_*.md clinical practice guideline files. This variable is optional. If it is not defined, empty, or points to a non-existent directory, the skill MUST continue normally: set meta.gpc_aplicada = "n/a", mark all GPC-dependent rules (M04, M06, M10, M14, M19, M22) as resultado = "n/a" with an observation stating that no clinical guidelines directory was provided, and evaluate all remaining rules as usual.
When GUIAS_CLINICAS_PATH is set and valid, the skill resolves the applicable GPC before running rules:
- Extracts
diagnostico_principal(CIE-10) fromfactura.pdf. - Looks up the CIE-10 in
$GUIAS_CLINICAS_PATH/INDEX.mdto find the applicable GPC file. - Loads
$GUIAS_CLINICAS_PATH/{gpc_file}.mdfor criteria, indications, and standard of care. - If no GPC matches →
meta.gpc_aplicada = "n/a". Set rules M04, M06, M10, M14, M19, M22 toresultado = "n/a". Audit continues normally — do not escalate solely because no GPC was found.
Output Contract
Template: references/checklist_base.json in this directory — PERT-CLIN instrument, 29 rules (M01–M29). See references/checklist_base.md for rule descriptions and evidence requirements.
Load the template and fill every rule's nullable fields:
resultado:"pass" | "fail" | "n/a"evidencia:"{file} p.{N}[, section X][, line Y]: <literal quote>"— use absence format when not foundobservaciones: mandatory per-rule explanation stating explicitly why the rule passed, failed, or does not apply — must cite the specific evidence found (or its absence). Generic phrases such as "se verificó", "cumple", or "no aplica" without justification are invalid.confianza: float 0.0–1.0glosa_sugerida: object (only whenresultado = "fail"), elsenull
Then fill meta and append cierre:
{
"meta": { "caso_id": "...", "fecha_auditoria": "...", "agente": "agente-medico-v1", "gpc_aplicada": "<GPC filename or \"n/a\">", "audit_perspective": "aseguradora | hospital" },
"cierre": {
"score_total": null,
"concepto_final": "APTA | NO_APTA",
"en_devolucion": false,
"clasificacion": "Clinico",
"accion_requerida": "Correccion | Rechazo | null",
"resumen_ejecutivo": "<1-2 oraciones con GPC referenciada>"
}
}
Generate medical_checklist_output.json from scratch using references/checklist_base.json as the schema template. Fill every rule. Return the complete filled checklist.
resultado, confianza, and glosa_sugerida follow the same rules as admin-audit. Evidence must cite the clinical document: "HC ingreso p.3: motivo consulta dolor hipocondrio derecho...".
Absence as evidence: If looking for an operative note and it is not found after searching the full HC PDF by content keywords (NOTA OPERATORIA, DESCRIPCIÓN QUIRÚRGICA), the evidence must state: "HC pp.1-40: no se encontro nota operatoria para CUPS {X}".
concepto_final and en_devolucion decision logic:
NO_APTA: any rule withresultado = "fail"(positive evidence of clinical violation) that is not subsanable.DEVOLUCION: any rule withresultado = "fail"that is subsanable by the IPS submitting additional documents or corrections.APTA: all applicable rules haveresultado = "pass"or"n/a". Rules with"n/a"due to missing clinical information are observations — they do NOT prevent an APTA verdict.en_devolucion = true: anycriticafail (positive evidence) subsanable by document resubmission — takes priority even when glosas also exist.accion_requerida = "Rechazo": whenen_devolucion = true.accion_requerida = "Correccion": whenen_devolucion = falseand glosas exist.accion_requerida = null: whenconcepto_final = APTA.- M06 (
failwith positive evidence of GPC deviation) →concepto_final = NO_APTA; if clinical justification is absent from all documents, seten_devolucion = true. - HC OCR failure → emit a single finding noting OCR quality issues, evaluate remaining rules with reduced confidence, note uncertainty in
resumen_ejecutivo. - Note:
ESCALAR_HUMANOis no longer a valid concepto_final value. Rules with low confidence (confianza < 0.75) should still render a verdict and add an observation noting the low confidence.
glosa_sugerida shape (only when resultado = fail):
{
"causal_num": "1 | 2 | 3 | 4 | 5 | 6 | 7",
"causal_nombre": "<nombre causal Res. 3047 Anexo 6>",
"texto": "<1-2 oraciones con cita de HC y regla GPC>",
"valor_glosado": 0,
"moneda": "COP"
}
Procedure
Read audit perspective from task context. Read
task.context.audit_perspectivefrom the current task (viaark tasks get <task_id>).Normalize: trim whitespace and convert to lowercase before comparing. Valid values:
"aseguradora","hospital". If the field is absent, null, empty, or any other value → use"aseguradora"as default and write a warning tometa:"audit_perspective desconocido '{valor}' — usando default aseguradora".Write the resolved value to
meta.audit_perspectivein the output.Value Meaning Output framing aseguradoraPayer audits the IPS invoice Findings are glosas — payment will be denied. concepto_final = NO_APTAmeans the invoice is rejected.resumen_ejecutivois addressed to the billing team of the IPS.hospitalIPS self-audits before billing Findings are riesgos de glosa — internal warnings. concepto_final = NO_APTAmeans "do not submit as-is".resumen_ejecutivomust use actionable internal language ("corrija antes de radicar").glosa_sugeridafields are still filled and represent what the payer would say — useful for the billing team to anticipate objections.M18 under
hospitalperspective: the clinical evaluation is identical — verify that every non-PBS medication has MIPRES or equivalent authorization. The difference is only inobservacionesphrasing: use "riesgo de glosa causal X si se radica sin MIPRES" rather than declaring a glosa. Do NOT changeresultadologic orglosa_sugeridastructure.
0a. Validate GPC environment.
Check if GUIAS_CLINICAS_PATH is defined and non-empty. If set, verify the directory exists and contains INDEX.md. If GUIAS_CLINICAS_PATH is not set, empty, or the directory does not exist, log a warning and continue — set an internal flag gpc_available = false. The audit proceeds without GPC data; GPC-dependent rules (M04, M06, M10, M14, M19, M22) will be marked n/a.
Load inputs. Read
metadata_input.jsonfrom the working directory. Readcase_evidence.json(produced by Step 0 document-understanding skill) for pre-classified documents and extracted clinical facts.Load ALL files listed in
documentos[]regardless of filename or extension. Usecase_evidence.json.clasificacion_documentosto understand what each file contains. Do NOT search for files by document type name — the same clinical information may appear in an epicrisis, a combined HC PDF, or distributed across multiple documents.Use
case_evidence.json.disponibilidad_informacionto determine what clinical information is available before evaluating rules. If information is not available, the corresponding rule becomes an observation (resultado: "n/a"with explanatoryobservaciones), not a fail.If
case_evidence.jsonis not present, fall back to reading all files directly and classifying by content.Load clinical ref_data (if available). Skip this step if
gpc_available = false(from step 0a). Setmeta.gpc_aplicada = "n/a"and mark rules M04, M06, M10, M14, M19, M22 asresultado = "n/a"withobservaciones = "GUIAS_CLINICAS_PATH no configurada — reglas GPC omitidas".When
gpc_available = true:- Load
$GUIAS_CLINICAS_PATH/INDEX.md+$GUIAS_CLINICAS_PATH/{gpc}.md— CIE-10 → GPC routing and full clinical criteria. $GUIAS_CLINICAS_PATH/INDEX.mdMUST be loaded before running any rule. If the CIE-10 maps to a GPC file, that file MUST be loaded from$GUIAS_CLINICAS_PATH/before running M04, M06, M10, M14, M19, M22. If no match is found, setgpc_aplicada = "n/a"and mark those rulesn/a.
- Load
Extract structured clinical data.
diagnostico_principal(CIE-10 + description) and secondaries.procedimientos_realizados[](CUPS + date + professional).medicamentos_administrados[](CUM + dose + duration + route).ayudas_diagnosticas[](CUPS + result + impact on plan).estancia[](admission, daily progress notes, discharge).epicrisis(discharge plan, recommendations, alarm signs).
Run the PERT-CLIN rule checklist.
Load
references/checklist_base.json(29 rules M01–M29) and followreferences/checklist_base.mdfor each rule. Fill the four nullable fields perreferences/checklist_base.md§2.3`:resultado:"pass"·"fail"·"n/a""pass"— the clinical information required by this rule was found and satisfies the criteria."fail"— POSITIVE EVIDENCE of a clinical violation (e.g., procedure contradicts GPC, medication dose is wrong per evidence in the documents, documented clinical trajectory doesn't justify the stay). NEVER mark"fail"because a document type is absent."n/a"— the rule structurally does not apply (e.g. M11 for non-surgical CUPS), OR the clinical information needed to evaluate this rule is not available in any document and there is no evidence of a clinical violation.observacionesmust explain what was searched for and not found.
Information over documents: If the epicrisis contains the clinical information that a "complete HC" would contain (admission diagnosis, clinical trajectory, procedures, medications, discharge), evaluate rules against that information. Do not fail a rule because the information comes from an epicrisis instead of a standalone historia clinica document.
evidencia: unified format —{file} [p.{page}] ["{quoted_text}"] [calc: {formula}]. Reference the loaded GPC for rules M04, M06, M10, M14, M19, M22. Examples:HC p.5 "BNP 380 pg/mL en descenso. Se continúa furosemida IV" [calc: criterio estancia GPC_falla_cardiaca §3.2 cumplido].Ecocardiograma 2026-04-09 "FEVI 32%" [calc: consistente con GPC_falla_cardiaca §2 criterios Framingham].- Absence:
HC pp.1-40 "no se encontró nota operatoria para CUPS {X} (búsqueda: NOTA OPERATORIA, DESCRIPCIÓN QUIRÚRGICA)".
observaciones: mandatory for every rule — state explicitly why the rule ispass,fail, orn/ausing the actual clinical evidence found.pass: cite the document and section that confirms the criterion is met (e.g."HC evolución 2026-04-10: BNP 380 pg/mL — criterio de estancia GPC_falla_cardiaca §3.2 cumplido").fail: cite the specific deficiency and its location (e.g."HC pp.1-40: no se encontró nota de evolución diaria para los días 2026-04-11 y 2026-04-12 — M23 incumplido").n/a: explain structurally why the rule cannot apply (e.g."No hay CUPS quirúrgicos en la factura — M11 nota operatoria no aplica"). Vague phrases ("cumple", "no aplica", "se verifica") with no citation are invalid.confianza: per scale inreferences/checklist_base.md§2.3—0.90+for unambiguous GPC-aligned evidence,<0.75on a critical rule → emit best-guess verdict and document uncertainty inresumen_ejecutivo`.glosa_sugerida: fill only whenresultado = "fail". Use causal map inreferences/checklist_base.md§7`. Causales frecuentes: 3 (soportes), 4 (autorización), 6 (pertinencia).
Special handling:
- M06 (GPC deviation): If the agent finds positive evidence that a procedure deviates from the applicable GPC AND no justification is documented in any available clinical document, mark
resultado = "fail". If the agent cannot determine GPC alignment because clinical documentation is insufficient, markresultado = "n/a"with an observation explaining what clinical information would be needed. Do NOT mark"fail"solely because the justification document is missing. - HC OCR failure → emit a single
conditionalfinding noting OCR quality issues and evaluate remaining rules with reduced confidence. Do not abort all rules.
See
references/checklist_base.md§6` for filled pass/fail examples (including M18 non-PBS without MIPRES).Compute
cierreand publish the checklist.Once all rules are filled, compute and append
cierreperreferences/checklist_base.md§2.4` and §4:concepto_final— follow rule-based decision logic inreferences/checklist_base.md§4. Key overrides: M06 fail →NO_APTA(seten_devolucion = trueif HC justification absent); any critical withconfianza < 0.75→ emit best-guess verdict and document uncertainty inresumen_ejecutivo`.clasificacion:"Clinico".resumen_ejecutivo: 1–2 sentences referencing the GPC applied and any critical finding. IfAUDIT_PERSPECTIVE = hospital: frame every finding as an internal action item — use language like "corrija antes de radicar", "riesgo de glosa causal X", "el pagador objetará este ítem si no se adjunta MIPRES". Avoid language that implies the payer has already decided (no "se glosa", no "se rechaza").
Generate
medical_checklist_output.jsonfrom scratch and write to the working directory.Mandatory evidence citation.
- Format:
{file} p.{N}[, section "X"][, line "Y"]. - Quote literal text when specific.
- If the evidence is absence:
"HC pp.1-40: no operative note found for {CUPS}".
- Format:
Pitfalls
- Symptom: All GPC-dependent rules (M04, M06, M10, M14, M19, M22) are
n/a. Cause:GUIAS_CLINICAS_PATHenvironment variable is not set or points to a non-existent directory. Fix: Set the variable to the absolute path of the directory containingINDEX.mdand theGPC_*.mdfiles. The audit runs without GPC data, but these 6 rules cannot be evaluated. - Symptom: M01 flags a valid CIE-10 as invalid. Cause: outdated CIE-10 catalog (latest 2026 vs. local 2024). Fix: update catalog and retry; meanwhile use
resultado=conditional. - Symptom: M04 false positives — reports "non GPC-adherent" for a legitimate edge case. Cause: the loaded GPC does not capture all accepted exceptions. Fix: if the HC explicitly mentions an accepted exception criterion, mark
resultado=passwith note; otherwiseconditionaland escalate. - Symptom: M11 reports missing operative note when it is present. Cause: the note is embedded inside the main HC PDF, not a separate attachment. Fix: search by content ("NOTA OPERATORIA", "DESCRIPCIÓN QUIRÚRGICA") across the full HC PDF, not by filename.
- Symptom: M08 flags a valid RETHUS professional. Cause: professional is registered but not found in available documents. Fix: set
resultado=conditionaland request online RETHUS validation. - Symptom: M18 denies a non-PBS with a valid MIPRES. Cause: MIPRES is in the authorization attachment but not in the structured field. Fix: also parse authorization PDFs looking for a MIPRES number.
- Symptom: M23 flags an unjustified inpatient day that actually had a criterion (waiting for intervention). Cause: justification is in nursing notes, not the medical record. Fix: consider nursing notes when evaluating stay.
- Symptom: many simultaneous critical findings, exploded
score. Cause: HC PDF parsing (OCR) failed. Fix: before publishing, check that the extracted HC text has >N words; otherwise emit a singleconditionalfinding asking for re-OCR.
Verification
medical_checklist_output.jsonexists in the working directory and contains exactly 1 record with 29 evaluated rules.- Every finding with
resultado=failhasevidenciareferencing a specific file and location. - If
concepto_final ≠ APTA, at least one rule hasresultado=fail; uncertainty (confianza < 0.75on a critical rule) is expressed inresumen_ejecutivo, not via a separate verdict value. - The skill did NOT read
admin_auditnorfinancial_audit(independence). - If HC OCR failed, there is exactly one finding documenting the failure,
concepto_final = NO_APTA,en_devolucion = true, and uncertainty is noted inresumen_ejecutivo.
References
- GPC MinSalud — guidelines per pathology (https://www.minsalud.gov.co/salud/publica/PET/Paginas/Guias-de-Practica-Clinica.aspx).
- Resolución 1995/1999 — clinical history.
- MIPRES regulation — non-PBS prescription.
- RETHUS — registry of health professionals.
- Issue arkangelai/audit-workflow#52.