diff --git a/src/medical_coding/agents/classifier.py b/src/medical_coding/agents/classifier.py index a660024..ecef7e6 100644 --- a/src/medical_coding/agents/classifier.py +++ b/src/medical_coding/agents/classifier.py @@ -981,10 +981,36 @@ class PrimarySecondaryClassifier(BaseAgent): # 1. Section / Reason for Admission Context (UHDDS Authority Hierarchy) # Under UHDDS, condition established after study chiefly responsible for occasioning admission # or underlying condition occasioning procedural/medical inpatient therapy + # Function to test whether diag_lower is the direct primary diagnosis mention in a clause + def _check_primary_match(text: str, target_diag: str) -> bool: + for match in re.finditer(rf"\b(?:principal|primary)(?:\s+diagnos[ei]s)?\s*[:\-–—]\s*([^\n.;]+)", text, re.IGNORECASE): + clause = match.group(1).lower().strip() + # Strip subsequent conditions attached by "with", "complicated by", "secondary to", "," + for delim in [" with ", " complicated by ", " secondary to ", ","]: + if delim in clause: + clause = clause[:clause.find(delim)].strip() + if re.search(rf"\b{re.escape(target_diag)}\b", clause): + return True + return False + + def _check_secondary_match(text: str, target_diag: str) -> bool: + for match in re.finditer(rf"\bsecondary(?:\s+diagnos[ei]s)?\s*[:\-–—]\s*([^\n.;]+)", text, re.IGNORECASE): + clause = match.group(1).lower().strip() + if re.search(rf"\b{re.escape(target_diag)}\b", clause): + return True + return False + is_explicit_primary = bool( - re.search(rf"\b(?:principal|primary)\s+diagnos[ei]s\b[^\n\.\;:]*?:\s*[^\n\.\;]*?{re.escape(diag_lower)}", full_context) - or (doc_lower and re.search(rf"\b(?:principal|primary)\s+diagnos[ei]s\b[^\n\.\;:]*?:\s*[^\n\.\;]*?{re.escape(diag_lower)}", doc_lower)) + _check_primary_match(full_context, diag_lower) + or (doc_lower and _check_primary_match(doc_lower, diag_lower)) or sec_lower in ("principal diagnosis", "primary diagnosis", "principal diagnoses", "primary diagnoses") + or getattr(asm, "role", None) in (DiagnosisRole.PRIMARY, "PRIMARY") + or getattr(asm, "is_primary", False) + ) + is_explicit_secondary = bool( + _check_secondary_match(full_context, diag_lower) + or (doc_lower and _check_secondary_match(doc_lower, diag_lower)) + or sec_lower in ("secondary diagnosis", "secondary diagnoses", "additional diagnoses") ) is_admission_driver = False adm_regex = rf"\b(?:admitted\s+(?:for|with|to|in)|reason\s+for\s+admission|admitting\s+diagnosis|principal\s+diagnosis)\b[^\n\.\;]*?(?:due\s+to\s+|for\s+|of\s+|in\s+)?{re.escape(diag_lower)}" @@ -1016,9 +1042,15 @@ class PrimarySecondaryClassifier(BaseAgent): score += 6.0 reasons.append("Identified as principal condition occasioning admission (+6.0)") - if any( - term in full_context + if is_explicit_secondary and not is_explicit_primary: + score -= 5.0 + reasons.append("Explicitly documented as SECONDARY DIAGNOSIS by provider (-5.0)") + + in_final_sec = any( + term in sec_lower for term in [ + "principal diagnosis", + "primary diagnosis", "discharge diagnosis", "discharge diagnoses", "final diagnosis", @@ -1026,11 +1058,13 @@ class PrimarySecondaryClassifier(BaseAgent): "final coding summary", "coding summary", ] - ): + ) or getattr(asm, "section", "") in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS", "DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES") + + if in_final_sec: score += 5.0 reasons.append("Explicitly documented under discharge / final diagnoses (+5.0)") elif any( - term in full_context + term in sec_lower or term in full_context for term in [ "chief complaint", "reason for admission", @@ -1063,8 +1097,8 @@ class PrimarySecondaryClassifier(BaseAgent): ) is_leading_primary = bool( is_explicit_primary and not is_complication and ( - re.search(rf"{re.escape(diag_lower)}[^\n.;]*?\b(?:with|complicated\s+by)\b", full_context) - or (doc_lower and re.search(rf"{re.escape(diag_lower)}[^\n.;]*?\b(?:with|complicated\s+by)\b", doc_lower)) + re.search(rf"\b{re.escape(diag_lower)}\s+(?:with|complicated\s+by)\b", ev_lower) + or (doc_lower and re.search(rf"\b{re.escape(diag_lower)}\s+(?:with|complicated\s+by)\b", doc_lower)) ) ) if is_complication: diff --git a/src/medical_coding/agents/clinical_extractor.py b/src/medical_coding/agents/clinical_extractor.py index fd5a556..2ac1859 100644 --- a/src/medical_coding/agents/clinical_extractor.py +++ b/src/medical_coding/agents/clinical_extractor.py @@ -279,7 +279,7 @@ class EvidenceFirstFactExtractor: # Phase 1: High-yield diagnosis sections (Discharge Diagnoses, Final Diagnoses, Assessment & Plan) for sec in sections: - if sec.section_name in ("DISCHARGE_DIAGNOSES", "PRINCIPAL_DIAGNOSIS", "SECONDARY_DIAGNOSES", "ASSESSMENT", "ASSESSMENT_PLAN"): + if sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES", "PRINCIPAL_DIAGNOSIS", "SECONDARY_DIAGNOSES", "ASSESSMENT", "ASSESSMENT_PLAN"): items = self._parse_diagnosis_items(sec.content, sec) for item in items: self._register_candidate(candidates_by_key, item) @@ -451,8 +451,12 @@ class EvidenceFirstFactExtractor: from medical_coding.validation.clinical_gate import HardClinicalCandidateGate - # Skip absence statements and treatment instructions - if HardClinicalCandidateGate.is_absence_statement(sent_clean) or HardClinicalCandidateGate.is_treatment_instruction(sent_clean): + # Skip absence statements, treatment instructions, and cross-reference boilerplate + if ( + HardClinicalCandidateGate.is_absence_statement(sent_clean) + or HardClinicalCandidateGate.is_treatment_instruction(sent_clean) + or re.search(r"\b(?:symptoms?|complaints?)\s+described\s+in\b|\bdescribed\s+in\s+(?:the\s+)?final\s+diagnosis\b|\babove\s+mentioned\s+complaints\b", sent_clean, re.IGNORECASE) + ): continue # Pattern 2: Explicit admission / diagnosis / condition clauses @@ -463,6 +467,12 @@ class EvidenceFirstFactExtractor: ) if adm_match: clause = adm_match.group(1).strip() + clause = re.sub( + r"^(?:(?:several|\d+)\s+(?:days?|weeks?|months?|hours?)\s+of\s+)", + "", + clause, + flags=re.IGNORECASE, + ).strip() for tail_delim in [" on ", " treated with ", " managed with ", " secondary to ", " requiring ", " with good response", " with symptom"]: if tail_delim in clause.lower(): idx = clause.lower().find(tail_delim) @@ -470,7 +480,7 @@ class EvidenceFirstFactExtractor: # Causal admission: "initiation of chemotherapy for DLBCL" -> "DLBCL" causal_m = re.search( - r"(?:initiation\s+of\s+|cycle\s+\d+\s+of\s+|course\s+of\s+)?(?:chemotherapy|immunotherapy|radiation|treatment|therapy|infusion|management|stenting|surgery)?\s*(?:for|of)\s+([^.,;\n]+)", + r"(?:(?:initiation|cycle\s+\d+|course)\s+of\s+)?(?:chemotherapy|immunotherapy|radiation|treatment|therapy|infusion|management|stenting|surgery)\s+(?:for|of)\s+([^.,;\n]+)", clause, re.IGNORECASE, ) @@ -541,6 +551,14 @@ class EvidenceFirstFactExtractor: lines = [line.strip() for line in content.split("\n") if line.strip()] for line_idx, line in enumerate(lines): + # Check explicit provider-designated PRIMARY role before stripping prefixes + is_explicit_primary_line = bool( + re.match( + r"^\s*(?:primary|principal)\s*(?:diagnosis|diagnoses|condition)?\s*[:\-–—]", + line, + re.IGNORECASE, + ) + ) # Strip list numbering e.g. "1. Acute right emphysematous pyelonephritis - underwent DJ stenting" cleaned_line = re.sub(r"^\d+[\.\)\-]\s*", "", line).strip() # Strip structural role prefixes (e.g., "Primary:", "Principal Diagnosis -", "Secondary:") @@ -606,7 +624,10 @@ class EvidenceFirstFactExtractor: if is_explicit_historical else ( DiagnosisRole.PRIMARY - if (sec.section_name in ("DISCHARGE_DIAGNOSES", "PRINCIPAL_DIAGNOSIS") and line_idx == 0 and sub_idx == 0) + if ( + (is_explicit_primary_line and sub_idx == 0) + or (sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES", "PRINCIPAL_DIAGNOSIS") and line_idx == 0 and sub_idx == 0) + ) else DiagnosisRole.SECONDARY ) ) @@ -625,6 +646,8 @@ class EvidenceFirstFactExtractor: # Explicit PRINCIPAL_DIAGNOSIS gets highest base score (+15.0); DISCHARGE_DIAGNOSES gets +10.0; SECONDARY gets +3.0 if is_explicit_historical: base_admitting = -50.0 + elif is_explicit_primary_line and sub_idx == 0: + base_admitting = 15.0 elif sec.section_name in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS"): base_admitting = 15.0 if (line_idx == 0 and sub_idx == 0) else 5.0 elif sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES"): @@ -677,6 +700,10 @@ class EvidenceFirstFactExtractor: if not cleaned: return [] + # Skip cross-reference boilerplate (e.g. "presented with symptoms described in the final diagnosis") + if re.search(r"\b(?:symptoms?|complaints?)\s+described\s+in\b|\bdescribed\s+in\s+(?:the\s+)?final\s+diagnosis\b|\babove\s+mentioned\s+complaints\b", cleaned, re.IGNORECASE): + return [] + # Split sentences (do not split decimal numbers like 101.4F or 1.5 mg/dL) sentences = [s.strip() for s in re.split(r"\.(?!\d)|[\n;]+", cleaned) if s.strip()] for s in sentences: @@ -684,8 +711,14 @@ class EvidenceFirstFactExtractor: continue cond_term = s + cond_term = re.sub( + r"^(?:(?:several|\d+)\s+(?:days?|weeks?|months?|hours?)\s+of\s+)", + "", + cond_term, + flags=re.IGNORECASE, + ).strip() causal_m = re.search( - r"(?:admitted\s+(?:for|with)|presented\s+with|evaluation\s+of|reason\s+for\s+admission\s*:?)\s*(?:initiation\s+of\s+)?(?:cycle\s+\d+\s+(?:of\s+)?)?(?:course\s+of\s+)?(?:chemotherapy|immunotherapy|radiation|treatment|therapy|infusion|management|stenting|surgery)?\s*(?:for|of|with)?\s*([^.,;\n]+)", + r"(?:admitted\s+(?:for|with)|presented\s+with|evaluation\s+of|reason\s+for\s+admission\s*:?)\s*(?:(?:initiation|cycle\s+\d+|course)\s+of\s+)?(?:chemotherapy|immunotherapy|radiation|treatment|therapy|infusion|management|stenting|surgery)\s+(?:for|of|with)\s+([^.,;\n]+)", s, re.IGNORECASE, ) @@ -1408,7 +1441,7 @@ class EvidenceFirstFactExtractor: cand.treatment_relevance = 1.0 cand.encounter_relevance = 1.0 cand.scores.encounter_relevance = 1.0 - is_from_principal_sec = any(ev.section in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS") for ev in cand.evidence) + is_from_principal_sec = any(ev.section in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS") for ev in cand.evidence) or cand.role == DiagnosisRole.PRIMARY cand.scores.admitting_score += (3.0 if is_from_principal_sec else 1.0) cand.temporality = Temporality.CURRENT cand.assertion_status = AssertionStatus.CONFIRMED diff --git a/src/medical_coding/graph/nodes.py b/src/medical_coding/graph/nodes.py index 673cde9..bec79c7 100644 --- a/src/medical_coding/graph/nodes.py +++ b/src/medical_coding/graph/nodes.py @@ -1233,7 +1233,7 @@ def _extract_conditions_deterministically( primary_ev = cand.primary_evidence_quote primary_sec = cand.evidence[0].section if cand.evidence else "DOCUMENTATION" is_pmh = any(ev.section in ("PAST_MEDICAL_HISTORY", "PAST_SURGICAL_HISTORY") for ev in cand.evidence) - if any(ev.section in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS") for ev in cand.evidence): + if any(ev.section in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS") for ev in cand.evidence) or cand.role == DiagnosisRole.PRIMARY: sec_name = "PRINCIPAL_DIAGNOSIS" elif any(ev.section in ("SECONDARY_DIAGNOSES", "ADDITIONAL_DIAGNOSES") for ev in cand.evidence): sec_name = "SECONDARY_DIAGNOSES" diff --git a/src/medical_coding/ui/components.py b/src/medical_coding/ui/components.py index 36b38b5..b78357c 100644 --- a/src/medical_coding/ui/components.py +++ b/src/medical_coding/ui/components.py @@ -8,6 +8,14 @@ from medical_coding.schemas.response import CodedDiagnosisResponse, CodingResult from medical_coding.schemas.validation import AbstentionRecord +def clean_html(raw_html: str) -> str: + """Strip leading and trailing whitespace from each line of an HTML string. + + Prevents CommonMark from interpreting indented HTML lines as Markdown code blocks (
).
+ """
+ return "\n".join(line.strip() for line in raw_html.strip().splitlines() if line.strip())
+
+
def render_header(
offline_mode: bool = True,
catalog_size: int = 25,
@@ -26,7 +34,7 @@ def render_header(
)
catalog_pill = f'📚 {catalog_size} ICD Codes'
- st.markdown(
+ header_html = clean_html(
f"""
@@ -45,9 +53,9 @@ def render_header(
- """,
- unsafe_allow_html=True,
+ """
)
+ st.markdown(header_html, unsafe_allow_html=True)
def render_kpi_metrics(result: CodingResult) -> None:
@@ -65,37 +73,43 @@ def render_kpi_metrics(result: CodingResult) -> None:
with c1:
st.markdown(
- f"""
-
- Status
-
- {status_str}
+ clean_html(
+ f"""
+
+ Status
+
+ {status_str}
+
-
- """,
+ """
+ ),
unsafe_allow_html=True,
)
with c2:
primary_code = result.primary_diagnosis.code if result.primary_diagnosis else "None"
st.markdown(
- f"""
-
- Primary ICD-10
- {primary_code}
-
- """,
+ clean_html(
+ f"""
+
+ Primary ICD-10
+ {primary_code}
+
+ """
+ ),
unsafe_allow_html=True,
)
with c3:
st.markdown(
- f"""
-
- Secondary Diags
- {len(result.secondary_diagnoses)}
-
- """,
+ clean_html(
+ f"""
+
+ Secondary Diags
+ {len(result.secondary_diagnoses)}
+
+ """
+ ),
unsafe_allow_html=True,
)
@@ -103,23 +117,27 @@ def render_kpi_metrics(result: CodingResult) -> None:
abst_count = len(result.abstentions)
abst_color = "#f87171" if abst_count > 0 else "#94a3b8"
st.markdown(
- f"""
-
- Abstentions
- {abst_count}
-
- """,
+ clean_html(
+ f"""
+
+ Abstentions
+ {abst_count}
+
+ """
+ ),
unsafe_allow_html=True,
)
with c5:
st.markdown(
- f"""
-
- Processing Time
- {result.processing_time_ms:.1f} ms
-
- """,
+ clean_html(
+ f"""
+
+ Processing Time
+ {result.processing_time_ms:.1f} ms
+
+ """
+ ),
unsafe_allow_html=True,
)
@@ -154,7 +172,11 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
codes_pills.append(f'CPT: {primary.cpt}')
codes_html = " ".join(codes_pills)
- st.markdown(
+ documented_row = ""
+ if primary.raw_term and primary.raw_term.lower() != (primary.description or "").lower():
+ documented_row = f'🩺 Documented Clinical Diagnosis: {primary.raw_term}'
+
+ primary_html = clean_html(
f"""
@@ -171,7 +193,7 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
📖 Matched Database Concept:
{primary.description}
- {f'🩺 Documented Clinical Diagnosis: {primary.raw_term}' if primary.raw_term and primary.raw_term.lower() != (primary.description or "").lower() else ''}
+ {documented_row}
{acuity_badge}
{certainty_badge}
@@ -185,9 +207,9 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
"{primary.evidence_quote}"
- """,
- unsafe_allow_html=True,
+ """
)
+ st.markdown(primary_html, unsafe_allow_html=True)
def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> None:
@@ -219,33 +241,37 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
sec_codes_pills.append(f'CPT: {diag.cpt}')
sec_codes_html = " ".join(sec_codes_pills)
- with st.container():
- st.markdown(
- f"""
-
-
-
- #{idx}. {sec_code_display}
- {diag.description}
- {f'🩺 Documented Diagnosis: {diag.raw_term}' if diag.raw_term and diag.raw_term.lower() != (diag.description or "").lower() else ''}
-
-
- {billable_badge}
- {acuity_str}
- {certainty_str}
- {sec_codes_html}
-
+ documented_row = ""
+ if diag.raw_term and diag.raw_term.lower() != (diag.description or "").lower():
+ documented_row = f'🩺 Documented Diagnosis: {diag.raw_term}'
+
+ secondary_html = clean_html(
+ f"""
+
+
+
+ #{idx}. {sec_code_display}
+ {diag.description}
+ {documented_row}
-
-
- Clinical Evidence:
-
- "{diag.evidence_quote}"
+
+ {billable_badge}
+ {acuity_str}
+ {certainty_str}
+ {sec_codes_html}
- """,
- unsafe_allow_html=True,
- )
+
+
+ Clinical Evidence:
+
+ "{diag.evidence_quote}"
+
+
+ """
+ )
+ with st.container():
+ st.markdown(secondary_html, unsafe_allow_html=True)
def render_abstentions(abstentions: list[AbstentionRecord]) -> None:
@@ -261,16 +287,18 @@ def render_abstentions(abstentions: list[AbstentionRecord]) -> None:
raw_term = abst.raw_term or "Unspecified Entity"
st.markdown(
- f"""
-
-
- Condition: {raw_term}
- {reason_str}
+ clean_html(
+ f"""
+
+
+ Condition: {raw_term}
+ {reason_str}
+
+ {abst.detail}
+ Enforced at stage: {stage_str}
- {abst.detail}
- Enforced at stage: {stage_str}
-
- """,
+ """
+ ),
unsafe_allow_html=True,
)
@@ -284,23 +312,25 @@ def render_validation_audit_trail(primary: CodedDiagnosisResponse | None, second
all_codes.extend(secondaries)
st.markdown(
- """
-
- ✔ Catalog Existence Check: All assigned codes exist in the authoritative local ICD-10-CM dataset.
-
-
- ✔ HIPAA Terminal Specificity: Codes are verified billable terminal leaf nodes (non-category headers).
-
-
- ✔ Single-Primary Invariant: Maximum of exactly 1 primary admission diagnosis enforced.
-
-
- ✔ Mutual Excludes1 Constraint: No mutually contradictory codes co-assigned for this encounter.
-
-
- ✔ Anti-Hallucination Bound: Codes were bounded exclusively to the retrieved candidate pool.
-
- """,
+ clean_html(
+ """
+
+ ✔ Catalog Existence Check: All assigned codes exist in the authoritative local ICD-10-CM dataset.
+
+
+ ✔ HIPAA Terminal Specificity: Codes are verified billable terminal leaf nodes (non-category headers).
+
+
+ ✔ Single-Primary Invariant: Maximum of exactly 1 primary admission diagnosis enforced.
+
+
+ ✔ Mutual Excludes1 Constraint: No mutually contradictory codes co-assigned for this encounter.
+
+
+ ✔ Anti-Hallucination Bound: Codes were bounded exclusively to the retrieved candidate pool.
+
+ """
+ ),
unsafe_allow_html=True,
)
diff --git a/src/medical_coding/validation/clinical_gate.py b/src/medical_coding/validation/clinical_gate.py
index a290aa2..ced686c 100644
--- a/src/medical_coding/validation/clinical_gate.py
+++ b/src/medical_coding/validation/clinical_gate.py
@@ -85,6 +85,13 @@ METADATA_PATTERNS = [
r"\babove\s+mentioned\s+complaints\b",
r"\bfeared\s+health\s+complaint\b",
r"\bcomplaint\s+in\s+whom\s+no\s+diagnosis\s+is\s+made\b",
+ # Cross-references, section references, and meta-narrative boilerplate
+ r"\b(?:symptoms?|complaints?|conditions?|diagnos[ei]s)\s+(?:described|mentioned|listed|noted|specified)\s+(?:in|under|above|below)\b",
+ r"\b(?:described|mentioned|listed|noted|specified)\s+(?:in|under)\s+(?:the\s+)?(?:final|discharge|admitting|admission)?\s*diagnos[ei]s\b",
+ r"\b(?:symptoms?|complaints?)\s+as\s+(?:above|below|mentioned)\b",
+ r"\b(?:as\s+described\s+above|as\s+mentioned\s+above|described\s+above|as\s+above)\b",
+ r"\babove\s+mentioned\s+(?:complaints?|symptoms?|conditions?)\b",
+ r"\bseveral\s+days\s+of\s+(?:the\s+)?symptoms\b",
# Allergy statements and negative metadata (Section 3)
r"^\s*(?:drug\s+)?allerg(?:y|ies)(?:\s*:)?\s*(?:none|nkda|no\s+known\s+(?:drug\s+)?allergies|nil|na|n/a)?\s*$",
r"^\s*(?:no\s+known\s+(?:drug\s+)?allergies|nkda)\s*$",
@@ -220,8 +227,14 @@ class HardClinicalCandidateGate:
if re.search(pat, term_lower):
return False, f"Section heading, metadata, allergy, or clinical status artifact: '{clean_term}'"
- # Check 4b: Physical exam, vital signs, systemic examination noise
- if any(w in term_lower for w in ["patient alert", "responsive temperature", "temperature :", "pulse :", "respiratory rate :", "bp :", "spo2 :", "rs :", "cvs :", "cns :", "pa :", "aebe", "s1, s2 heard well", "soft, non tender", "further management", "above mentioned complaints"]):
+ # Check 4b: Physical exam, vital signs, systemic examination noise, and meta-narrative boilerplate
+ if any(w in term_lower for w in [
+ "patient alert", "responsive temperature", "temperature :", "pulse :",
+ "respiratory rate :", "bp :", "spo2 :", "rs :", "cvs :", "cns :", "pa :",
+ "aebe", "s1, s2 heard well", "soft, non tender", "further management",
+ "above mentioned complaints", "symptoms described", "described in the final diagnosis",
+ "described in final diagnosis", "symptoms described in", "several days of the symptoms",
+ ]):
return False, f"Physical exam, vital sign, or administrative boilerplate artifact: '{clean_term}'"
# Check 5: Standalone tumor staging or genetic attributes
diff --git a/tests/test_icd_matching_regression.py b/tests/test_icd_matching_regression.py
index 6908c5c..9e33f6e 100644
--- a/tests/test_icd_matching_regression.py
+++ b/tests/test_icd_matching_regression.py
@@ -153,3 +153,58 @@ async def test_regression_oncology_and_pmh_comorbidities() -> None:
assert "Z71.1" not in sec_codes
assert len(res.secondary_diagnoses) == 2
+
+@pytest.mark.asyncio
+async def test_regression_primary_label_with_meta_reference_narrative() -> None:
+ """Explicit PRIMARY label must win primary diagnosis; meta-references ('symptoms described in...') must be rejected."""
+ doc = """
+ HOSPITAL DISCHARGE SUMMARY
+ CHIEF COMPLAINT:
+ The patient presented with several days of the symptoms described in the final diagnosis.
+
+ FINAL DIAGNOSES:
+ PRIMARY: Acute right pyelonephritis with right renal calculus.
+ SECONDARY: Right renal calculus
+ """
+ res = await process_clinical_document(source=doc, document_id="doc-reg-primary-meta")
+ assert res is not None
+ assert res.primary_diagnosis is not None
+ # Primary must be Acute pyelonephritis (N10), NOT meta-reference noise
+ assert res.primary_diagnosis.code == "N10"
+ assert "pyelonephritis" in res.primary_diagnosis.description.lower()
+ assert "symptoms described" not in res.primary_diagnosis.raw_term.lower()
+
+ # Meta-reference noise must never appear in secondary diagnoses
+ for sec in res.secondary_diagnoses:
+ assert "symptoms described" not in sec.raw_term.lower()
+ assert "symptoms described" not in (sec.description or "").lower()
+
+ # Right renal calculus must be secondary
+ sec_codes = {s.code for s in res.secondary_diagnoses}
+ assert "N20.0" in sec_codes
+
+
+def test_clean_html_removes_indentation_and_prevents_code_blocks() -> None:
+ """Verify that clean_html removes all leading whitespace from multi-line HTML."""
+ from medical_coding.ui.components import clean_html
+
+ sample_html = """
+
+
+ Database Concept:
+ Acute pyelonephritis
+
+
+
+ ACUTE
+
+
+ """
+ cleaned = clean_html(sample_html)
+ for line in cleaned.splitlines():
+ # No line should start with 4 or more spaces (Markdown code block trigger)
+ assert not line.startswith(" "), f"Line starts with 4+ spaces: {line!r}"
+ assert not line.startswith("\t"), f"Line starts with tab: {line!r}"
+ assert cleaned.startswith('')
+
+