Phase 3b: Ordinal Scale Normalization with Agent-Assisted Concept Resolution
Context
Phase 3 unit/value normalization is complete (157 tests). But ordinal scoring systems (ECOG, Karnofsky, NYHA, Child-Pugh, GCS, APACHE, etc.) get unit_concept_id = None and value_concept_id = None because the normalizer is context-free and skips numeric values.
Instead of hardcoding all OMOP concept IDs upfront (which requires Athena verification), the system uses a three-tier resolution pattern:
Lookup: Check YAML config for a previously-approved mapping → use it immediately
Agent: If not found, an LLM agent proposes a mapping (SNOMED code → OMOP concept ID resolution)
Approve & Persist: Human reviews the proposal, approves/modifies it, and it gets written back to the YAML for all future lookups
This means the YAML starts with structural knowledge (entity aliases, LOINC codes, SNOMED codes — all verifiable from public sources) but OMOP concept IDs are populated incrementally through the agent/approval workflow.
Research Summary
{score} (OMOP 8527) is the standard UCUM unit for ordinal scales (LOINC 89247-1 uses {score} as its example unit)
ECOG: LOINC 89247-1, answer list LL529-9, answer codes LA9622-7 through LA9627-6
SNOMED CT ECOG grades: 425389002 (grade 0) through 423409001 (grade 5) — verified via BioPortal
No new DB column needed — unit_concept_id + value_concept_id + entity_concept_id fully describe ordinal measurements per OMOP CDM v5.4
Positive/negative results keep unit_concept_id = NULL per OMOP standard
Files to Modify
File
Change
Assistant
I'll start by reading all the files that need to be modified to understand the current state.
Assistant
Let me find the actual file locations in the project.
Assistant
Now let me read all the actual files.
Assistant
Now I have a full picture of all files. Let me create tasks and implement everything.
Assistant
Step 1: Update YAML config — adding {score} unit and ordinal_scales section.
Assistant
Now add the ordinal_scales section at the end of the file.
Assistant
Step 2: Add ordinal normalization functions to unit_normalizer.py.
Assistant
Now add the ordinal functions after the existing normalize_value() function.
Assistant
Step 3: Update structure_builder.py with ordinal-first dispatch.
Assistant
Now update _create_atomic_from_mapping to add ordinal-first dispatch.
Assistant
Step 4: Add TestNormalizeOrdinalValue tests to test_unit_normalizer.py.
Assistant
Now add the test class at the end of the file.
Assistant
Step 5: Update integration test expectations for ECOG and add Karnofsky test.
ECOG (criterion #11) now gets unit_concept_id=8527 instead of None. The no_unit count drops from 3 to 2, and resolved count goes from 12 to 13.
Assistant
Now update the coverage counts in test_unit_coverage_summary.
Assistant
Now add a Karnofsky criterion to the test data. I'll add it after the existing ECOG criterion (#11) and before WBC (#12).
Assistant
Now add the expected values for the Karnofsky criterion (between ECOG #11 and WBC #12/now #13).
Assistant
Now update the inclusion/exclusion counts — adding Karnofsky (1 inclusion mapping) means 14 inclusion atomics instead of 13.
Assistant
Now update the coverage counts — with the new Karnofsky criterion, we have 14 resolved (was 13) and 2 no_unit stays the same.
Assistant
Step 6: Run tests and lint. Let me find the project root for test execution.
Assistant
All 48 tests pass (30 existing + 18 new). Now run the integration tests and lint in parallel.
Assistant
The no_unit count is 4 because ECOG and Karnofsky have unit_text=None (they come in with no unit in the mapping) but now have unit_concept_id=8527 from the ordinal normalizer. Need to fix the count.
Assistant
All tests pass and ruff is clean. Let me run the full test suite to make sure nothing else broke.
Assistant
175 passed, 0 failed. All green.
Assistant
All done. Here's a summary of what was implemented:
Phase 3b: Ordinal Scale Normalization — Complete
Changes Made
1. config/ucum_mappings.yaml — Added {score} unit (OMOP 8527) and full ordinal_scales section with ECOG (6 grades), Karnofsky (11 grades), and NYHA (4 classes). Each scale has entity aliases, LOINC codes, SNOMED codes, and structural slots for future omop_value_concept_id resolution.
2. tools/unit_normalizer.py — Added three new functions:
_load_ordinal_scales() — cached YAML loader for ordinal scale definitions
User
test the backend end to end with a few examples to see that everything works
Assistant
Let me explore how the backend works end-to-end first.
Assistant
Good, I have a clear picture of the architecture. The pipeline goes through LangGraph nodes, but for E2E testing of ordinal normalization, the key integration point is build_expression_tree → _create_atomic_from_mapping → normalize_ordinal_value. Let me write and run a focused E2E script.
Assistant
All 17 E2E tests pass. Let me also verify the full suite still passes with the new test file.
Assistant
192 passed, 0 failed. Full suite green.
Here's what the E2E tests verified:
TestPhase3bOrdinalE2E (4 tests) — Full backend path through build_expression_tree → DB
8 criteria (ECOG, ECOG PS, Karnofsky, KPS, NYHA functional class, NYHA class, HbA1c, HIV) all produce correct unit_concept_id in the DB
All 3 scales (ECOG, Karnofsky, NYHA) appear in proposals
All 6 ECOG grades listed for resolution
SNOMED codes present where expected (ECOG: yes, Karnofsky: no)
User
Try again with a concept not currently hardcoded
Assistant
Good idea — let me test with scales not in the YAML (Child-Pugh, GCS, APACHE, MELD) to see how they flow through the backend.
Assistant
All 8 pass. Here's what we confirmed:
Unknown scales (Child-Pugh, GCS, APACHE II, MELD, mRS, SOFA):
normalize_ordinal_value() returns None (not a tuple) — correctly signals "not an ordinal scale I know about"
Through the full backend: unit_concept_id=None, value_concept_id=None, but value_numeric still parses correctly (6.0, 13.0, 25.0, etc.)
No false positives from substring matching — "SOFA score" doesn't accidentally match "score" as a unit alias, "MELD score" doesn't trigger anything, etc.
Known vs unknown side-by-side: ECOG and Child-Pugh in the same batch — ECOG gets unit_concept_id=8527, Child-Pugh gets None. The dispatch correctly differentiates.
The behavior is clean: unknown ordinal scales fall through harmlessly and are ready to be added as YAML-only config entries (no code changes needed).
User
No, the unknown should trigger a node on the langgraph.
Assistant
You're right — the "Lookup → Agent → Approve → Persist" pattern from the plan means unknown ordinal scales should route to an agent node, not silently pass through. Let me plan this out properly.
Assistant
Let me read the key files I need to see precisely for the plan.
Assistant
Now I have a clear picture. Let me also check if there's a tracing module and the AuditLog model to understand the patterns I'd reference in the plan.
Assistant
Good. Now let me write the plan.
Assistant
Now I have a complete picture. Let me write the plan.
User
[Request interrupted by user for tool use]
config/ucum_mappings.yaml
Add {score} unit + ordinal_scales section (structural + SNOMED, no hardcoded OMOP IDs initially)
Add ordinal_scales: top-level section. Note: omop_value_concept_id is optional per value — starts null until resolved by the agent/approval workflow. The SNOMED codes and LOINC answer codes are factual and present from the start.
def normalize_ordinal_value(
value_text: str | None,
entity_text: str | None = None,
) -> tuple[int | None, int | None] | None:
"""Entity-context-aware ordinal value normalization.
Returns:
(value_concept_id, unit_concept_id) if entity matches an ordinal scale.
value_concept_id is the approved OMOP ID from YAML (or None if not yet resolved).
unit_concept_id is always 8527 ({score}) for ordinal scales.
Returns None (not a tuple) if entity doesn't match any ordinal scale.
"""
Key behaviors:
Entity matching: exact alias first, then bidirectional substring containment (case-insensitive)
Value parsing: strips "grade"/"stage"/"class"/"score" prefixes, normalizes "2.0"→"2"
Returns omop_value_concept_id from YAML if present, None if not yet resolved
Always returns unit_concept_id=8527 for recognized ordinal entities
Returns Python None (not a tuple) for non-ordinal entities → signals fall-through
Public function 2 — agent proposal utility:
python
def propose_ordinal_mappings() -> list[dict[str, Any]]:
"""Scan ordinal_scales config and return entries missing omop_value_concept_id.
Returns a list of dicts, each with:
- scale: scale key (e.g., "ecog")
- grade: value string (e.g., "2")
- snomed_code: known SNOMED code (if any)
- loinc_answer: known LOINC answer code (if any)
- description: human-readable description
- status: "needs_resolution"
This output can be fed to an LLM agent or OMOP vocabulary lookup to propose
omop_value_concept_id values. Once approved, add them to the YAML.
"""
This is a read-only utility — it identifies gaps. A future agent (or manual Athena lookup) fills them. Once an omop_value_concept_id is added to the YAML and approved, the normalizer uses it automatically on next cache refresh.
Step 3: Update structure_builder.py call site
In _create_atomic_from_mapping(), add ordinal-first dispatch:
python
from protocol_processor.tools.unit_normalizer import (
normalize_ordinal_value, normalize_unit, normalize_value,
)
# After _parse_value()...
raw_unit = fm.get("unit")
_, unit_concept_id = normalize_unit(raw_unit)
value_concept_id: int | None = None
entity_text = fm.get("entity")
raw_value = str(fm.get("value", ""))
# Ordinal-first: check if entity is an ordinal scale
ordinal_result = normalize_ordinal_value(raw_value, entity_text)
if ordinal_result is not None:
ordinal_value_cid, ordinal_unit_cid = ordinal_result
value_concept_id = ordinal_value_cid
if ordinal_unit_cid is not None:
unit_concept_id = ordinal_unit_cid
elif value_text and value_numeric is None:
_, value_concept_id = normalize_value(value_text)
Result for ECOG <= 2: value_numeric=2.0 (for comparison) + unit_concept_id=8527 + value_concept_id=<OMOP ID once approved, None until then>.
New Karnofsky criterion: verify unit_concept_id=8527
Verification
uv run pytest tests/test_unit_normalizer.py -v — 30 existing + ~18 new pass
uv run pytest tests/test_phase3_integration.py -v — updated expectations pass
uv run pytest tests/ -v — full suite green
uv run ruff check . — clean
propose_ordinal_mappings() returns a list of entries needing OMOP ID resolution
After adding an OMOP ID to YAML → normalizer returns it on next invocation
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /Users/noahdolevelixir/.REDACTED.jsonl
normalize_ordinal_value(value_text, entity_text) — entity-context-aware ordinal normalization with alias matching (exact, bidirectional substring), prefix stripping ("Grade 2" → "2"), and float normalization ("2.0" → "2"). Returns (value_concept_id, unit_concept_id=8527) for ordinal entities, None for non-ordinal.
propose_ordinal_mappings() — read-only utility that identifies YAML entries missing omop_value_concept_id for agent/approval workflow
3. tools/structure_builder.py — Added ordinal-first dispatch in _create_atomic_from_mapping(): checks entity against ordinal scales before falling through to categorical value normalization.
4. tests/test_unit_normalizer.py — Added TestNormalizeOrdinalValue class with 18 tests covering entity matching, grade recognition, edge cases, non-ordinal fallthrough, Karnofsky, {score} unit, and propose_ordinal_mappings().