docs(lead): design the kernel, loop, and tool surface

This commit is contained in:
kert
2026-10-31 22:00:04 -04:00
parent 9788f95ede
commit 289649b3ff
2 changed files with 408 additions and 0 deletions

View File

@@ -0,0 +1,268 @@
# LEAD Kernel, Loop, and Tools Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Close the eight Part 1 review minors and build the computable Parts 2–4 of the LEAD chassis on public data, without inventing CMS coefficients.
**Architecture:** Pure functions implement the published thresholds, the existing benchmark cap, and the promotion gates. DuckDB ledger rows record rules, releases, runs, and findings. The agent surface is a Python module that writes only those rows. Databricks and model training stay behind an injected transport and a recorded gap.
**Tech Stack:** Python, Typer, DuckDB, pytest. No new service. No MCP SDK. No MLflow client.
**Spec:** `docs/superpowers/specs/2026-10-31-lead-evidence-chassis-design.md` and `docs/superpowers/specs/2026-10-31-lead-kernel-and-loop-design.md`
## Global Constraints
- Public data only. No PHI, CCLF, or client data. No live HTTP in unit tests.
- Do not invent V28, concurrent, ESRD, Kim, Appendix B, DAH, TFU, or CAHPS coefficients.
- A rule-tier claim's number must be one the kernel tests against a literal.
- Ledger inserts stay append-only. The same content hash inserts nothing. Claim hashes ignore the actor.
- `schema_sql("delta")` must not contain the substring `aco`.
- An API or transport failure writes no screening decision and no run row.
- `stack prisma search due` still exits 0.
- Work on `feat/lead-evidence-chassis-part1` in the existing worktree. Do not remove `.claude/worktrees/`.
- Do not install a crontab. Do not train a model. Do not spend Databricks.
## Review Focus
- An A&D score of exactly 3.0 meets HN.4 and does not meet HN.6. An ESRD score of exactly 0.35 meets HN.5 and does not meet HN.6.
- A suspect with equal demographic weights raises. The care delta is not multiplied by the weight ratio.
- `runs_start(..., where_ran="databricks")` raises on an exhausted budget and on a missing transport, and the transport is not called in either case.
- `load_manifest` stores a row whose `path` does not exist and does not open `url`.
- `agreed_excludes` raises when an id is present only in the second pass. Undated near-titles are not borderline. Identical undated titles with the same author still merge.
---
### Task 1: Part 1 review minors
**Files:**
- Modify: `src/prisma/search/base.py` (`bare_doi`, `_doi_item_id`)
- Modify: `src/prisma/dedup.py` (`_doi_key`, borderline year compare)
- Modify: `src/prisma/audit.py` (`agreed_excludes`, `audit_sample`)
- Modify: `src/prisma/search/pubmed.py` (`parse_pubmed_xml`)
- Modify: `src/prisma/search/openalex.py`, `crossref.py`, `semanticscholar.py`, `arxiv.py`
- Modify: `src/econ/fred.py` (`SeriesRow.year`)
- Modify: `src/cli/lead.py` (status printer)
- Test: `tests/prisma/test_dedup.py`, `tests/prisma/test_audit.py`, `tests/prisma/test_search_pubmed.py`, `tests/prisma/test_search_others.py`, `tests/econ/test_fred_irs.py`, `tests/lead/test_ledger_store.py`
**Interfaces:**
- Consumes: `zot.fetch.select.normalise_doi(raw: str) -> str`. `status()` already returns `TargetStatus`.
- Produces: `bare_doi` delegates to `normalise_doi` and keeps a trailing period. `pmid_of(value: object) -> str` in `prisma.search.base`. Status stdout line: `{id}\t{gaps}\t{last_run or ""}\t{open_contradictions}\t{rule}\t{aggregate}\t{literature}\t{synthetic}`.
- [ ] **Step 1: Write the failing tests**
DOI URL and bare DOI are one dedup group. `bare_doi("https://dx.doi.org/10.1/ab.")` stays `10.1/ab.`. Import of a bare DOI finds an item stored as `https://dx.doi.org/10.1/alpha` and returns 0. OpenAlex `ids.pmid` URL `https://pubmed.ncbi.nlm.nih.gov/42` yields pmid `42`. Semantic Scholar `externalIds.PubMed` `"999"` yields `999`. Crossref `"pmid": "12345"` yields `12345`. An arXiv `arxiv:pmid` of `77` yields `77`. Nine agreed-exclude ids at rate 0.10 draw one member of that list. An id only in the second pass raises `KeyError` from `agreed_excludes`. Blank PubMed XML `" \n"` returns no hits and `sha256` of that payload. A FRED observation with `date: ""` has `year is None`. Undated near-titles `High needs frailty index` and `High-need frailty index` have an empty borderline list. Identical undated titles with author `Kim` are one group. Empty-ledger status stdout contains `Q.ACR\t1\t\t0\t0\t0\t0\t0`.
- [ ] **Step 2: Run the new tests and confirm they fail**
Run the new test names with `uv run pytest` from the worktree. Expected: assertion failures, not collection errors.
- [ ] **Step 3: Implement the minors**
`pmid_of` keeps digits after a PubMed URL or a `pmid:` prefix, else `""`. Parsers call it only when the source field exists. `agreed_excludes` uses the same key-set check as `disagreements`. `audit_sample` draws 1 when the floored count is 0, the list is nonempty, and the rate is positive. Blank PubMed XML returns a log with interface `eutils` and database `pubmed`. FRED year is `int | None`. Borderline comparison skips a missing year. Status prints the eight fields in the order above.
- [ ] **Step 4: Re-run the touched tests**
Expected: PASS.
- [ ] **Step 5: Commit**
`fix: close the part 1 review minors`
### Task 2: High Needs criteria and suspect moves
**Files:**
- Create: `src/lead/high_needs.py`
- Create: `src/lead/suspect.py`
- Test: `tests/lead/test_high_needs.py`, `tests/lead/test_suspect.py`
**Interfaces:**
- Consumes: nothing from Task 1.
- Produces: `QuarterFlags`, `criteria_met(flags) -> frozenset[str]`, `alignment_year(quarters) -> frozenset[str]`, `persists(prior, this_year) -> frozenset[str]`. `SuspectMove(coding_delta, care_delta, coding_after_reweight)`. `suspect_move(*, before_status, after_status, score_before, score_coding, score_care, weight_before, weight_after) -> SuspectMove`.
- [ ] **Step 1: Write the failing tests**
`QuarterFlags(quarter="2027Q1", ad_score=3.0)` meets `HN.4` and not `HN.6`. `ad_score=2.0` and `unplanned_admissions=2` meets `HN.6`. `ad_score=2.0` and one admission meets neither. `esrd_score=0.35` meets `HN.5` and not `HN.6`. `esrd_score=0.24` and two admissions meets `HN.6`. `snf_days=45` meets `HN.7`; 44 does not. `hn1_diagnosis=True` meets `HN.1`. `hn2_dme=True` meets `HN.2`. `kim_index=0.2, kim_cutoff=0.2` meets `HN.3`. A missing index or a missing cutoff does not. One quarter of four meeting `HN.7` sets `HN.7` for the year. `persists(frozenset({"HN.1"}), frozenset())` is `{HN.1}`.
`suspect_move` with before `standard`, after `high_needs`, scores 1.0, 1.2, and 1.5, weights 1.0 and 0.5 returns `SuspectMove(0.2, 0.5, 0.1)`. The same status raises `ValueError`. Equal weights raise `ValueError`. `weight_before=0` raises `ValueError`.
- [ ] **Step 2: Run the tests**
Expected: import or attribute error because the modules do not exist.
- [ ] **Step 3: Implement the two modules**
Thresholds are literals `3.0`, `0.35`, `2.0`, `0.24`, `2`, and `45` in the module. Bands are half-open at the top. `suspect_move` subtracts `score_before` from each score and scales only `coding_delta`.
- [ ] **Step 4: Re-run the tests**
Expected: PASS.
- [ ] **Step 5: Commit**
`feat(lead): score High Needs criteria and separate suspect moves`
### Task 3: Limits calculator and rule-tier claims
**Files:**
- Create: `src/lead/limits.py`
- Create: `src/lead/rules.py`
- Test: `tests/lead/test_limits.py`, `tests/lead/test_rules.py`
**Interfaces:**
- Consumes: `capped_risk_score`, `CAPPED`, `WITHIN_CAP` from `lead.benchmark`. `append` and `open_ledger`. `criteria_met` is not required. Targets `RA.CAP`, `HN.4`, `HN.5`, `HN.6`, `HN.7`.
- Produces: `Headroom(scored, status, forgone)`. `earlier_qualification_headroom(prior, caught) -> Headroom`. `normalization_sensitivity(benchmark, factor) -> float`. `shrinkage_weight(aco_n, prior_n) -> float`. `publish_rules(con, *, actor) -> int`.
- [ ] **Step 1: Write the failing tests**
`earlier_qualification_headroom(1.0, 1.05)` is `Headroom(1.04, CAPPED, 0.01)`. `earlier_qualification_headroom(1.0, 1.035)` is `Headroom(1.035, WITHIN_CAP, 0.0)`. `normalization_sensitivity(1000.0, 1.25)` is `800.0`. Factor `0` raises `ValueError`. `shrinkage_weight(100, 300)` is `0.25`. `aco_n + prior_n == 0` raises `ValueError`.
`publish_rules` on an empty ledger inserts claims whose `tiers` is `rule` and whose `effect_value` values include `0.04` on `RA.CAP`, `3.0` on `HN.4`, `0.35` on `HN.5`, `2.0` on `HN.6`, and `45.0` on `HN.7`. A second call returns 0. The HN.6 subject says the A&D band stops before 3.0 and the ESRD band stops before 0.35.
- [ ] **Step 2: Run the tests**
Expected: import error.
- [ ] **Step 3: Implement**
Headroom calls `capped_risk_score(prior, caught, "High Needs")`. Forgone is `max(caught - scored, 0)`. Rule claims use a content hash of kind, target, and effect value, not the actor. `publish_rules` counts inserts that returned true.
- [ ] **Step 4: Re-run the tests**
Expected: PASS.
- [ ] **Step 5: Commit**
`feat(lead): add the limits calculator and rule-tier claims`
### Task 4: Quality gaps, manifest loader, geography spine
**Files:**
- Create: `src/lead/quality.py`
- Create: `src/lead/manifest.py`
- Create: `src/lead/spine.py`
- Modify: `src/cli/lead.py` (`manifest load`)
- Test: `tests/lead/test_quality.py`, `tests/lead/test_manifest.py`, `tests/lead/test_spine.py`
**Interfaces:**
- Consumes: `open_ledger`. `uamcc_summary` and `acr_summary` in `aco.express.cms_quality_measures`.
- Produces: `known_gaps() -> tuple[tuple[str, str], ...]`, `reconciled() -> tuple[str, ...]`. `load_manifest(con, csv_path, *, actor) -> int`. `layer_of(source_id, lead_use) -> str`. `geography_key(*, fips="", zcta="") -> str`. `time_key(year, quarter) -> str`. CLI `stack lead manifest load --csv --db`.
- [ ] **Step 1: Write the failing tests**
`reconciled()` is `("Q.UAMCC", "Q.ACR")` and those summary functions import. `known_gaps()` target ids include `Q.DAH`, `Q.TFU`, `Q.CAHPS`, `HN.1`, `HN.2`, `HN.3`, `RA.PROSP`, `RA.CONC`, and `RA.ESRD`.
A two-row CSV inserts 2, and the same file inserts 0 the second time. A row with `lead_use` `synthetic person file` has layer `synthetic`. `source_id` `tuva` is synthetic with a blank `lead_use`. A public row has layer `""`. A blank `sha256` raises `ValueError`. A `path` of `/no/such/lead-file` still inserts, and the stored `url` is the CSV value. The loader DDL string does not contain `aco`. `schema_sql("delta")` still does not contain `aco`.
`geography_key(fips="01001")` is `01001`. A 4-digit FIPS raises. `geography_key(zcta="02138")` is `02138`. Both FIPS and ZCTA raise `ValueError`. `time_key(2027, 4)` is `2027Q4`. Quarter `5` raises.
CLI load prints `inserted\t1` for a one-row file.
- [ ] **Step 2: Run the tests**
Expected: import error, then assertion failures once the modules exist. Watch the first run fail before implementing.
- [ ] **Step 3: Implement**
CSV columns are the enrichment manifest header. The table is `lead_evidence.public_release`, created by the loader. Hash is `source_id`, `release`, `sha256`. Do not open `url` and do not read `path`. Spine validators are the whole geography story.
- [ ] **Step 4: Re-run the tests**
Expected: PASS.
- [ ] **Step 5: Commit**
`feat(lead): load the public manifest and record measure gaps`
### Task 5: Promotion gates, failure record, drift, lineage
**Files:**
- Create: `src/lead/gates.py`
- Modify: `src/aco/lake/lineage.py`
- Test: `tests/lead/test_gates.py`, `tests/lead/test_ledger_lineage.py`
**Interfaces:**
- Consumes: `append`, `open_ledger`, `by_id`. `LineageGraph`.
- Produces: `GateInput`, `GateResult`, `promotion_gates(item) -> GateResult`, `record_outcome(con, *, actor, target_id, model, where_ran, finished_on, metrics, gate, relation, claim_id="") -> tuple[bool, bool]`, `events_in_window(*, window_start, alarm_on, events) -> tuple[str, ...]`. `LineageGraph.table_outputs(table_ref) -> list[str]`. Ledger edges on `build_lineage()`.
- [ ] **Step 1: Write the failing tests**
A gate input that beats both baselines, tests `train_through + 1`, has calibration error `0.01` against tolerance `0.05`, coverage `0.91` against target `0.90`, `subgroup_pass=True`, and a known claim id is promoted with empty reasons. Each single failure adds exactly one of `baseline`, `out_of_time`, `calibration`, `coverage`, `subgroup`, `claim`. An empty feature list is `claim`. A test year two years ahead is `out_of_time`.
`record_outcome` with relation `discarded` and a failing gate inserts one run and one finding. The same call again returns `(False, False)`. Relation `promoted` with a passing gate also inserts both. Relation `other` raises `ValueError` and leaves the tables empty.
An event on the window start and an event on `alarm_on` are returned. The day before and the day after are not.
`build_lineage().table_deps("lead_evidence.claim")` includes `lead_evidence.extraction` and `lead_evidence.source`. `table_outputs("lead_evidence.claim")` includes `lead_evidence.feature`, `lead_evidence.run`, and `lead_evidence.finding`.
- [ ] **Step 2: Run the tests**
Expected: import error for `lead.gates`, and `AttributeError` for `table_outputs` if the lineage test runs first.
- [ ] **Step 3: Implement**
Reason order is the list above. `record_outcome` hashes the target, model, where, finished day, metrics, reasons, and relation, not the actor. Finding `relation` is the caller's relation. `gate_results` on the run is the comma-joined reasons. Lineage edges are added after the pipeline walk.
- [ ] **Step 4: Re-run the tests**
Expected: PASS.
- [ ] **Step 5: Commit**
`feat(lead): gate promotion and record discarded runs`
### Task 6: Agent tool surface
**Files:**
- Create: `src/lead/tools.py`
- Create: `src/lead/model.py`
- Test: `tests/lead/test_tools.py`, `tests/lead/test_model.py`
**Interfaces:**
- Consumes: `append`, `open_ledger`, `by_id`, `due`, `earlier_qualification_headroom`, `normalization_sensitivity`, `shrinkage_weight`, `perf.tracer`.
- Produces: `ledger_search`, `ledger_get_claim`, `targets_list`, `limits_compute`, `features_validate`, `features_propose`, `runs_start`, `runs_get`, `runs_compare`, `failures_check`, `findings_record`, `review_trigger_search`. `stamp(weights_hash, adapter_version) -> str`. `MODEL_GAPS`.
- [ ] **Step 1: Write the failing tests**
`ledger_search` filters by `target_id` and a casefolded subject substring. `ledger_get_claim` returns that claim and `None` for an unknown id. `targets_list()` includes `Q.ACR` and `HN.4`.
`limits_compute("headroom", prior=1.0, caught=1.05).scored` is `1.04`. `limits_compute("normalization", benchmark=1000.0, factor=1.25)` is `800.0`. `limits_compute("shrinkage", aco_n=100, prior_n=300)` is `0.25`. An unknown kind raises `ValueError`.
`features_validate` raises `KeyError` for target `NO.SUCH` and `ValueError` when a claim id is absent or the list is empty. `features_propose` inserts one feature and a second call with the same expression inserts nothing.
`runs_start(..., where_ran="local")` inserts a run and does not call a transport that would raise. `where_ran="databricks"` with `transport=None` raises `RuntimeError`. `where_ran="databricks"` with `spent=1` and `budget=1` raises `RuntimeError` and does not call the transport. A transport and `spent=0`, `budget=1` is called once and the run is stored. `runs_get` returns that run. `runs_compare` returns both metric strings. A missing id raises `KeyError`.
`failures_check` returns the run whose `gate_results` is nonempty and omits a promoted run. `findings_record` inserts one finding. `review_trigger_search` on an empty ledger returns `("nightly",)`.
A recording tracer passed as `tracer_factory` receives the span name `ledger_search`. The default factory is `perf.tracer`.
`stamp("abc", "v1")` is `abc+v1`. An empty hash or an empty version raises `ValueError`. `MODEL_GAPS` is nonempty.
- [ ] **Step 2: Run the tests**
Expected: import error.
- [ ] **Step 3: Implement**
Databricks checks the budget first, then the transport, then calls it, then appends. A raise writes no run. Feature and run hashes ignore the actor. `failures_check` reads `run.gate_results`. `review_trigger_search` calls `due` and does not search. Every public function uses the span helper.
- [ ] **Step 4: Re-run the tests**
Expected: PASS.
- [ ] **Step 5: Commit**
`feat(lead): add the agent tool surface`
### Task 7: Whole-package verification
- [ ] **Step 1: Run the touched packages, then the full suite**
From the worktree: `uv run pytest tests/lead tests/prisma tests/econ tests/aco -q`, then `uv run pytest -q`. Expected: the suite passes. A failure that this work did not cause is still reported by name.
- [ ] **Step 2: Commit any fix the suite required**
Message names the failing test.
- [ ] **Step 3: Final review of this plan's range**
Review `e3def65..HEAD` only for the commits after Part 1's `9788f95`. Do not re-review Part 1. Critical and Important findings get one TDD fix pass. Minors are ledgered.

View File

@@ -0,0 +1,140 @@
# LEAD kernel, modeling loop, and agent tools
Status: builder design for Parts 2–4 of the approved chassis spec
`docs/superpowers/specs/2026-10-31-lead-evidence-chassis-design.md`.
The user told the executor to do the remaining work without another
approval pause. This file records the calls the outline left open.
It does not replace the approved spec.
Public data only. No PHI, CCLF, or client data. No live HTTP and no
Databricks call in unit tests. Unpublished CMS coefficient tables are
not invented. A number enters the `rule` tier only when a function in
this repo reproduces it.
## What is computed
High Needs criteria take caller-supplied quarter flags. The thresholds
are the ones in the approved spec:
- HN.1 and HN.2 are booleans. Appendix B code lists are not in this repo.
- HN.3 is `kim_index >= kim_cutoff`, both supplied by the caller. Kim
weights and the cutoff are not in this repo.
- HN.4 is an A&D score `>= 3.0`. The score is an input. V28 software is
not parsed.
- HN.5 is an ESRD score `>= 0.35`. ESRD model internals are not parsed.
- HN.6 is an A&D score `2.0 <= score < 3.0`, or an ESRD score
`0.24 <= score < 0.35`, plus at least 2 unplanned admissions. The
score 3.0 is HN.4 only. The score 0.35 is HN.5 only.
- HN.7 is at least 45 covered SNF days.
Any quarter that meets a criterion sets it for the whole alignment year.
A criterion met in a prior year stays met. The 12-month counts are
caller-supplied. This module does not read claims.
A suspect is a status change. Coding and care stay separate numbers.
Demographic reweighting multiplies only the coding delta:
`coding_delta * (weight_after / weight_before)`. The same status raises.
Equal weights raise. There is no single collapsed delta.
The limits calculator:
- Headroom calls `lead.benchmark.capped_risk_score` with category
`High Needs`. The published check is prior 1.0 and caught 1.05, which
returns 1.04 and the capped status. Forgone growth is the positive
difference between the uncapped score and the capped score.
- Normalization is `benchmark / factor` for a caller-supplied factor
greater than zero. The CMS normalization factor is not invented.
- Shrinkage is `aco_n / (aco_n + prior_n)`. That is this chassis's
sensitivity formula, not a CMS coefficient, so it is not a rule-tier
claim.
UAMCC and ACR stay in `src/aco/express/cms_quality_measures.py`. DAH,
TFU, and CAHPS are recorded gaps. CAHPS results would be an input.
Rule-tier claims are written for the published identities the kernel
checks: the 4 percent High Needs cap (`RA.CAP`), and the HN.4, HN.5,
HN.6, and HN.7 thresholds. Re-inserting the same claim hash inserts
nothing. The actor is not part of the hash.
## What is loaded
`lead.manifest.load_manifest` reads a caller-supplied CSV with the
enrichment manifest columns. It inserts into `lead_evidence.public_release`
in the local DuckDB file. The table DDL lives with the loader, not in
`lead.ledger.schema.schema_sql`, so the Delta DDL stays free of the
substring `aco`. A row is identified by `source_id`, `release`, and
`sha256`. The same triple inserts nothing. A blank key raises. The
loader does not download, and a missing file at `path` is still stored.
Geography accepts one 5-digit county FIPS or one 5-digit ZCTA, and a
year plus a quarter in 1..4. Supplying both a FIPS and a ZCTA raises.
There is no national crosswalk.
A row is tagged `synthetic` when `lead_use` contains that word or
`source_id` is one of `bcda_sandbox`, `tuva`, `cms_synthetic`,
`de_synpuf`, `synthea`.
## Modeling loop
Promotion is a pure function. A candidate is promoted only when all of
these hold:
- it beats AutoML and it beats a naive or persistence baseline
- `test_year == train_through + 1`
- calibration error is at most the tolerance
- conformal coverage is at least the target
- the caller reports that dual status, SVI quartile, and rurality checks
passed
- every feature lists a claim id that already exists, and there is at
least one feature
A failed or discarded run appends one `run` row and one `finding` row.
The same hashes insert nothing. Drift annotation returns the strand-5
event citations whose `event_on` day falls inside the window, compared
on the `YYYY-MM-DD` prefix, including both ends.
The ledger tables are added to the lakehouse lineage graph so a claim's
inputs and a claim's outputs can both be listed. Pipeline lineage is
unchanged.
## Agent surface
`lead.tools` is the tool surface. The MCP SDK is not a project
dependency, so these are Python functions plus the existing Typer
commands. Each call opens a `lead.tools` span through `perf.tracer`.
The agent writes ledger rows only.
`runs.start` with `where_ran="local"` appends a run and does not call a
transport. `where_ran="databricks"` raises when `spent >= budget`, and
raises when no transport was injected. Both raises happen before a
transport call. A passed transport is called only after those checks.
Unit tests inject the transport. Nothing in this package opens a
Databricks connection or trains a model.
LoRA training, model serving, and the strand-3 model pick are recorded
gaps. `lead.model.stamp` only concatenates a weights hash and an adapter
version. An empty half raises.
`stack lead ledger status` prints, per target,
`id, gaps, last_run, open_contradictions, rule, aggregate, literature,
synthetic`, tab-separated. An empty ledger prints a blank last run and
a gap of 1. `stack lead manifest load` prints how many rows were new.
## Deferred Part 1 minors, now in scope
- DOI keys use `zot.fetch.select.normalise_doi`. `bare_doi` does not
strip a trailing period. Dedup keys do. An existing Zotero DOI stored
as a URL matches a bare DOI.
- PMID is read from OpenAlex `ids.pmid`, Semantic Scholar
`externalIds.PubMed` or `PMID`, a Crossref `pmid` field, and an arXiv
`pmid` element. The value is digits only, after a `pmid:` prefix or a
PubMed URL. Absent fields stay empty.
- The 10 percent audit draws one id when the floored count is zero and
the rate and the list are both nonempty. Rate 0 stays empty.
- `agreed_excludes` raises `KeyError` when the two passes name different
ids.
- Blank PubMed XML returns zero hits and the sha256 of that payload.
- A FRED date whose first four characters are not digits stores year
`None`.
- Near-title borderline pairs require both years to be present and equal.
Identical undated titles with the same author still merge.