docs(pfs): plans for code-family dossiers — home-visit slice and backfills
Some checks failed
CI / lint (push) Successful in 35s
CI / test (push) Failing after 3m4s
CI / notebooks-smoke (push) Successful in 1m42s
Deploy / changes (push) Successful in 15s
Infra CI / zotero (push) Successful in 16s
Infra CI / notebooks (push) Successful in 56s
Infra CI / docs (push) Successful in 20s
Infra CI / api (push) Successful in 23s
Infra CI / bcda (push) Successful in 17s
Infra CI / llm (push) Successful in 19s
Infra CI / mc (push) Successful in 18s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / api (push) Has been skipped
Deploy / bcda (push) Has been skipped
Deploy / llm (push) Has been skipped
Deploy / mc (push) Has been skipped
Deploy / docs (push) Successful in 31s
Deploy / report (push) Successful in 17s
Renovate / renovate (push) Successful in 1m48s
Zotero Sync / zotero-sync (push) Successful in 3m18s
Some checks failed
CI / lint (push) Successful in 35s
CI / test (push) Failing after 3m4s
CI / notebooks-smoke (push) Successful in 1m42s
Deploy / changes (push) Successful in 15s
Infra CI / zotero (push) Successful in 16s
Infra CI / notebooks (push) Successful in 56s
Infra CI / docs (push) Successful in 20s
Infra CI / api (push) Successful in 23s
Infra CI / bcda (push) Successful in 17s
Infra CI / llm (push) Successful in 19s
Infra CI / mc (push) Successful in 18s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / api (push) Has been skipped
Deploy / bcda (push) Has been skipped
Deploy / llm (push) Has been skipped
Deploy / mc (push) Has been skipped
Deploy / docs (push) Successful in 31s
Deploy / report (push) Successful in 17s
Renovate / renovate (push) Successful in 1m48s
Zotero Sync / zotero-sync (push) Successful in 3m18s
Plan A (16 tasks): curated HOME-VISITS registry, lineage for every code ever seen, local extraction ledger, RUC/CMS valuation rounds from FR tables and paragraphs, origin rows, CMS comment summaries, commenter identity, stance per event, money and power stakes with the expected-stance rule, all-years payment table, dossier assembly with the sentence-level citation check, /ui/family/<key>, chat integration, and the home-visit golden test. Plan B (8 tasks): hoard-safe writes and a guarded PFS loader, PFS rule inventory repair, CY2013-CY2017 comment dockets, pre-CY2002 FR rules, 1992-2013 conversion factors, the CMS RVU archive, the governance literature, and the downstream refresh.
This commit is contained in:
@@ -0,0 +1,264 @@
|
||||
# Code-family dossiers — parallel source backfills 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:** Extend the sources every dossier draws on — PFS comment dockets for the CY2013–CY2017 rules, Federal Register PFS rules before CY2002 (as far back as federalregister.gov and govinfo reach), RVU files before 2015 (the CMS archive), conversion factors for those years, and the open-access governance literature on the RUC and fee-setting bodies (paywalled items on a wanted list) — so the home-visit dossier's gap notes shrink as each lands.
|
||||
|
||||
**Architecture:** Reuse the existing ingest tools (`stack bib discover-pfs-rules`, `fr-grab`, `fetch-docket-comments`, `backfill-comments --mirror`, `comments extract`, `llm index`, `zot fetch`, `dev/scripts/fetch_fr_attachments.py`, `dev/scripts/ingest_pfs.py`) and add code only where a gap needs it: a hoard-safe writer and a guarded scratch-DB PFS loader, a PFS rule audit (one bib item holds the wrong rule), HCFA-era discovery and govinfo issue PDFs for pre-1994 rules, a CMS RVU-archive fetcher, pre-2014 `RULES` entries, and a parser/importer for the governance reading list. Each task is independent after Task 1 (Task 2 before 3 and 4; Task 5 before 6) and ends with the dossier's downstream refresh (Task 8).
|
||||
|
||||
**Tech Stack:** Python 3.13, uv, httpx (honest UA), bib SQLite, Zotero SQLite (`zot.db.Db`), DuckDB via `conf.connect`, polars/calamine (existing `pfs.pipe` readers), pymupdf (host only), typer, pytest.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-11-code-family-dossier-design.md` (§Goals "Sign-off and gaps", §Sources, §Governance research, §Left to the builder "how far back public sources actually reach (report it)"). Sibling plan: `docs/superpowers/plans/2026-11-11-code-family-dossier-home-visits.md` (its `pfs.dossier.coverage` computes the gap notes this plan shrinks).
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Commit straight to `main` in `/home/kert/stack`. No branches, worktrees, merge commits, PRs, `git stash`. Before every commit run `git status --short`; if anything you did not stage is staged, stop and ask. `git add` explicit paths only. Conventional messages; no `Co-Authored-By` or any trailer.
|
||||
- Never run a write/ingest command from a worktree. Live commands run from the main checkout via **ENV** = `bash -c 'cd /home/kert/stack && set -a && . ./.env && set +a && uv run --no-sync <cmd>'`. Before the first live run: `cat .venv/lib/python3*/site-packages/stack.pth` prints `/home/kert/stack/src`.
|
||||
- `data/aco.duckdb` is written only through `conf.connect.duckdb_batch("aco")` followed by `publish_replica("aco")`. **`pfs.pipe.load_all` drops every pfs RVU/GPCI/PE/carrier table: never run a `years=`-filtered load against `data/aco.duckdb`.** Dry-run into a scratch DuckDB, diff per year, then do a full reload (Task 1 enforces this in `ingest_pfs.py`). Check no notebook holds the DuckDB lock before a reload.
|
||||
- Honest User-Agent on every client (`stack-backfill/1.0`); never a browser UA; stop on 403/429/bot pages and record the source as unreachable. Pause between requests (FR API ~60/min; reg.gov 1000/hr — the mirror path has no cap).
|
||||
- Hoard: never overwrite a source document. Every download goes through `bib.ingest.save_versioned` (Task 1). Never delete a bib/Zotero item, attachment or anchor map; a mislabelled item is retitled/retagged, not removed.
|
||||
- Public data only; no ACO/HarmonyCares/WNOT/Wakely material. Paywalled works are listed on the wanted list only — fetched solely through the open-access cascade (`stack zot fetch` on main); never through the libgen/Anna's path on `feat/zot-fetch-z1`.
|
||||
- Zotero writes: always scope `stack bib sync-zotero` with `--tag`; host-attached items sync through the one-off container that mounts data at both paths: `docker stop zotero; docker compose run --rm --no-deps -T -v /home/kert/stack/data:/home/kert/stack/data api uv run --no-sync stack bib sync-zotero --tag <tag> --no-hold; docker start zotero`. Use `Store.merge_extra`/`Store.update` for metadata fixes (`Store.upsert` drops unmodeled `extra_json` keys on update).
|
||||
- LLM indexing/tagging is self-hosted only (`stack llm index`, `stack llm tag` on the Ollama pool).
|
||||
- Tests need no network, live DuckDB or Zotero (fixtures: `zotero_db` from `tests/conftest.py`, `Store(":memory:", storage_dir=tmp_path/"s")`, recorded HTTP payloads). CI `--cov-fail-under=99`.
|
||||
- Test: `uv run --no-sync pytest -q -p no:cacheprovider -n auto <paths>`. Lint: `uv run --no-sync ruff format <paths> && uv run --no-sync ruff check <paths>`.
|
||||
- Long downloads/backfills: `setsid nohup … > .state/backfill/<task>.log 2>&1 &` (`mkdir -p .state/backfill .state/pfs` once) + Monitor; each command is idempotent and resumes when rerun.
|
||||
- After CLI changes: `uv run --no-sync python docs/scripts/extract_cli.py`; commit every changed `docs/docs/cli/*` page (Task 8).
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. **A `--years` PFS load against the primary** wipes every other year of `pfs.rvu` and friends. Expected: refused before any connection opens. Pinned in Task 1 (`test_years_refused_without_scratch_db`, `test_years_refused_when_db_is_primary`).
|
||||
2. **HCFA-era rules missed or mis-dated**: pre-2001 documents are filed under "Health Care Finance Administration" and titled "…Physician Fee Schedule for Calendar Year 1999" or "Fee Schedule for Physicians' Services"; a correction published in January belongs to that year, not the next. Pinned in Task 4 (`test_legacy_discovery_includes_hcfa`, `test_rule_year_from_calendar_year_title`, `test_january_correction_keeps_its_year`).
|
||||
3. **A bib rule item holding the wrong rule** (`249JVQFH`, titled "CY 2013 PFS Proposed Rule", holds FR doc 2012-16836 — the CY2013 Home Health PPS NPRM, CMS-1358-P; the real PFS NPRM is 2012-16814, 77 FR 44722, CMS-1590-P). Expected: flagged, retitled to its true title, `module:pfs` removed, the real rule ingested — nothing deleted. Pinned in Task 2 (`test_audit_flags_wrong_rule`, `test_fix_retitles_without_deleting`).
|
||||
4. **Old-docket comments attached to the final rule with comment period**, not the NPRM (the CY2016 FC document alone carries 441). A walk keyed on the NPRM's object id misses them. Expected: docket-wide mirror backfill and a reconciled count. Pinned in Task 3 Step 3 (count table) — operational, no new code.
|
||||
5. **A re-download replacing a stored source** (RVU zips, FR PDFs, governance PDFs with silently changed bytes). Expected: the new bytes land beside the old file. Pinned in Task 1 (`test_save_versioned_keeps_old_bytes`).
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Hoard-safe writer and a guarded scratch-DB PFS loader
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/bib/ingest.py` (`save_versioned`; `download_files(overwrite=True)` routes through it), `src/pfs/pipe.py` (`rvu_year_digest`), `dev/scripts/ingest_pfs.py` (`--db`, `--diff-against`, the `--years` guard; logic moved into `run(argv) -> int`)
|
||||
- Test: `tests/bib/test_ingest.py`, `tests/pfs/test_pipe_helpers.py`, `tests/dev/test_ingest_pfs.py` (new)
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `save_versioned(dest: Path, data: bytes) -> Path` — absent → write `dest`; same sha256 → return `dest` untouched; different → write `dest.with_name(f"{dest.stem}.{sha8}{dest.suffix}")` and return it (never touches `dest`).
|
||||
- `rvu_year_digest(con) -> dict[int, tuple[int, str]]` — per `pfs.rvu.year`: row count and sha256 of the sorted `(hcpcs, mod, status_code, work_rvu, non_fac_pe_rvu, fac_pe_rvu, mp_rvu)` rows.
|
||||
- `ingest_pfs.py`: `--db PATH` loads into `duckdb.connect(PATH)` with no replica publish and no lake; `--years` without `--db`, or with `--db` resolving to `conf.path("db.aco")`, exits 2 with `"--years needs --db <scratch.duckdb>: load_all drops every pfs table"` before opening anything; `--diff-against PATH` prints one line per year `YEAR rows_db rows_other same|DIFF|new|missing` and exits 1 if any year present in both differs.
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `test_save_versioned_new_file`, `test_save_versioned_same_bytes_is_noop`, `test_save_versioned_keeps_old_bytes`, `test_download_overwrite_never_clobbers` (patched urlopen); `test_rvu_year_digest_order_insensitive`; `test_years_refused_without_scratch_db`, `test_years_refused_when_db_is_primary` (monkeypatched `conf.path`), `test_diff_reports_same_and_new` (two temp DuckDBs).
|
||||
- [ ] **Step 2: Run** `tests/bib/test_ingest.py tests/pfs/test_pipe_helpers.py tests/dev/test_ingest_pfs.py` → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Live dry run** — `ENV python dev/scripts/ingest_pfs.py --db /home/kert/stack/.state/pfs/scratch.duckdb --no-lake --diff-against data/replica/aco.ro.duckdb` → every year 2015–2027 `same` (baseline for Task 6).
|
||||
- [ ] **Step 6: Commit** `git add src/bib/ingest.py src/pfs/pipe.py dev/scripts/ingest_pfs.py tests/bib/test_ingest.py tests/pfs/test_pipe_helpers.py tests/dev/test_ingest_pfs.py && git commit -m "feat(bib,pfs): hoard-safe save_versioned; ingest_pfs refuses year-filtered loads outside a scratch DB"`
|
||||
|
||||
---
|
||||
|
||||
### Task 2: PFS rule inventory audit and repair — `stack bib audit-pfs-rules`
|
||||
|
||||
**Files:**
|
||||
- Create: `src/bib/rule_audit.py`
|
||||
- Modify: `src/bib/federalregister.py` (`fetch_document`, `is_pfs_title`), `src/cli/bib.py` (`audit-pfs-rules`)
|
||||
- Test: `tests/bib/test_rule_audit.py`, `tests/bib/test_federalregister.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `fr_anchor_docs.document_number`, `bib.translate.federal_register`, `Store.update/add_tag/remove_tag/merge_extra`, `bib.frlink.rule_kind`.
|
||||
- Produces:
|
||||
- `is_pfs_title(title: str) -> bool` — true for `Payment Policies Under the Physician Fee Schedule`, `Physician Fee Schedule for Calendar Year`, `Fee Schedule for Physicians' Services`, or (`Relative Value Units` and `Physician Fee Schedule`); false for Home Health / OPPS / IPPS titles.
|
||||
- `fetch_document(number: str, *, client: httpx.Client | None = None) -> FRDocument | None` (`/api/v1/documents/<n>.json` with fields `document_number,title,type,agency_names,publication_date,volume,start_page,end_page,docket_ids,html_url,body_html_url`).
|
||||
- `@dataclass(frozen=True) AuditRow(item_key: str, document_number: str, bib_title: str, fr_title: str, fr_type: str, rule_year: int, verdict: str, note: str)`; `verdict ∈ ("ok","not_pfs","missing_doc","type_mismatch")`.
|
||||
- `audit(store, *, fetch=fetch_document) -> list[AuditRow]` — every item tagged `module:pfs` with a `fr_anchor_docs` row; `type_mismatch` when `rule_kind` disagrees with the FR `type`.
|
||||
- `missing_cycles(rows: Sequence[AuditRow], years: range) -> list[tuple[int, str]]` — `(rule_year, "proposed"|"final")` absent among `ok` rows.
|
||||
- CLI `stack bib audit-pfs-rules [--fix] [--since-year 2002]` — prints the table and missing cycles; `--fix` (a) for `not_pfs`: `Store.update(key, title=<FR title>)`, `remove_tag("module:pfs")`, `add_tag("audit:not-pfs")`, `merge_extra(key, {"audit": {...}})`, (b) for each missing cycle: finds the PFS document via `pfs_rules(since, until)` for that year's window and ingests it like `_discover_rules` (tags `source:federal-register`, `module:pfs`, `docket:<cms-id>`), then prints the follow-up commands for the new keys.
|
||||
|
||||
- [ ] **Step 1: Failing tests** (recorded FR API JSON fixtures)
|
||||
|
||||
```python
|
||||
def test_audit_flags_wrong_rule(store_249): # item 249JVQFH, doc 2012-16836, bib title "Medicare Program; CY 2013 PFS Proposed Rule"
|
||||
[row] = audit(store_249, fetch=fake_fetch({"2012-16836": HH_PPS_2013}))
|
||||
assert (row.verdict, row.fr_title.startswith("Medicare Program; Home Health Prospective Payment System")) == ("not_pfs", True)
|
||||
def test_missing_cycles_reports_cy2013_proposed_after_flag(): ...
|
||||
def test_fix_retitles_without_deleting(store_249): ... # item still present, anchors still present, title = FR title,
|
||||
# module:pfs removed, audit:not-pfs added
|
||||
def test_is_pfs_title_eras(): ... # 1991, 1999, 2013, 2027 titles True; HH PPS / OPPS False
|
||||
def test_fix_ingests_missing_proposed(monkeypatch): ... # pfs_rules stub returns 2012-16814 (CMS-1590-P) → upserted with tags
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run** → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Live** — `ENV stack bib audit-pfs-rules` (report the table: expect `249JVQFH not_pfs`, and missing cycles incl. CY2013 proposed and CY2004 proposed), then `ENV stack bib audit-pfs-rules --fix`, then for each new key: `ENV stack bib fr-grab --key <K>`, `ENV python dev/scripts/fetch_fr_attachments.py --key <K>`, `ENV stack llm index --collection rules --key <K>` (in the llm container if the host lacks pgvector access: `docker exec llm uv run --no-sync stack llm index --collection rules --key <K>`), `ENV stack bib code-tags`; sync: the one-off container recipe with `--tag source:federal-register`. Re-run the audit: no `not_pfs`, missing cycles only before CY2002.
|
||||
- [ ] **Step 6: Commit** `git add src/bib/rule_audit.py src/bib/federalregister.py src/cli/bib.py tests/bib/test_rule_audit.py tests/bib/test_federalregister.py && git commit -m "feat(bib): PFS rule inventory audit — flags 249JVQFH (HH PPS under a PFS title), ingests missing cycles"`
|
||||
|
||||
---
|
||||
|
||||
### Task 3: PFS comment dockets for the CY2013–CY2017 rules
|
||||
|
||||
**Files:** none expected (operational). If a step exposes a defect in `bib.regulations_gov` (`discover_docket`, `backfill_from_mirror`) or `cli/bib.py`, fix it test-first in `tests/bib/test_regulations_gov.py` / `tests/cli/test_bib_fetch_sealed.py` and commit with this task.
|
||||
|
||||
**Docket ids (FR API `regulations_dot_gov_info.docket_id`, read 2026-11-11):**
|
||||
|
||||
| Rule | CMS ids | reg.gov docket | FR documents |
|
||||
|---|---|---|---|
|
||||
| CY2013 | CMS-1590-P / -FC | `CMS-2012-0083` | 2012-16814 (NPRM), 2012-26900 (FC) |
|
||||
| CY2014 | CMS-1600-P / -FC | `CMS-2013-0155` | 2013-16547, 2013-28696 |
|
||||
| CY2015 | CMS-1612-P / -FC | `CMS-2014-0094` | 2014-15948, 2014-26183 |
|
||||
| CY2016 | CMS-1631-P / -FC | `CMS-2015-0081` | 2015-16875, 2015-28005 (441 comments on the FC) |
|
||||
| CY2017 | CMS-1654-P / -F | `CMS-2016-0116` | 2016-16097, 2016-26668 |
|
||||
|
||||
- [ ] **Step 1: Register each docket** (one discovery call each; creates the `dockets` row and its `fr_object_id`):
|
||||
`ENV stack bib fetch-docket-comments CMS-2012-0083 --cms-id CMS-1590-P --limit 1` — likewise `CMS-2013-0155 --cms-id CMS-1600-P`, `CMS-2014-0094 --cms-id CMS-1612-P`, `CMS-2015-0081 --cms-id CMS-1631-P`, `CMS-2016-0116 --cms-id CMS-1654-P`. Verify with `ENV stack comments dockets`.
|
||||
- [ ] **Step 2: Mirror backfill** (docket-wide, includes FC-document comments, no rate cap), one docket at a time:
|
||||
`bash -c 'cd /home/kert/stack && set -a && . ./.env && set +a && setsid nohup uv run --no-sync stack bib backfill-comments --mirror --docket CMS-2012-0083 --log .state/backfill/CMS-2012-0083.log > .state/backfill/CMS-2012-0083.out 2>&1 &'`; Monitor until the stats lines; rerun to resume. Then the next docket.
|
||||
- [ ] **Step 3: Reconcile counts** — per docket: mirror comment ids (`ENV python -c "from bib.regulations_gov import Mirror; print(len(Mirror().comment_ids('<D>')))"`), bib items tagged `reg-docket:<D>` (`bib.regulations_gov.docket_counts(store, D)`), and the FR API `comments_count` for each document. Report the table; any shortfall > 1% is investigated before Step 4.
|
||||
- [ ] **Step 4: Text and index** — `ENV stack comments extract --docket <D>`; `docker exec llm uv run --no-sync stack llm index --collection comments --docket <D>` (chunks get `codes`/`families` anchors at index time); optional themes: `docker exec llm uv run --no-sync stack llm tag --docket <D>`.
|
||||
- [ ] **Step 5: Seal** once indexed and counts reconcile: `ENV stack comments seal <D>`.
|
||||
- [ ] **Step 6: Report** — dockets, comments, attachments extracted, chunks indexed; the dossier gap note "Public comment dockets before the CY2018 rule…" now reads CY2013 after Task 8.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Federal Register PFS rules before CY2002
|
||||
|
||||
**Files:**
|
||||
- Create: `src/bib/govinfo.py`
|
||||
- Modify: `src/bib/federalregister.py` (`LEGACY_AGENCIES`, `pfs_rules_legacy`, `document_for_citation`), `src/pfs/descriptors.py` (`rule_year_of`), `src/cli/bib.py` (`discover-pfs-rules --legacy`, `ingest-fr-issue`)
|
||||
- Test: `tests/bib/test_federalregister.py`, `tests/bib/test_govinfo.py`, `tests/pfs/test_descriptors.py`, `tests/cli/test_bib_deep.py`
|
||||
|
||||
**Reach (probed 2026-11-11, report it in the commit):** federalregister.gov serves PFS rules with `body_html_url` (paragraph anchors) from 1994 on, filed under agency `health-care-finance-administration` until mid-2001 (slug verified: HTTP 200); the earliest PFS hit is 94-32286 (published 1995-01-03), proposed rules from 95-18144 (CY1996). Before 1994 only govinfo's issue PDFs: `https://www.govinfo.gov/link/fr/56/59502` → `FR-1991-11-25.pdf` (the original fee schedule final rule, 56 FR 59502, cited 49× in later rules). Later rules also cite 57 FR 55896/55917/55938 (CY1993) and 59 FR 63410 (CY1995).
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `LEGACY_AGENCIES = ("health-care-finance-administration", "centers-for-medicare-medicaid-services")`; `pfs_rules_legacy(*, since: str = "1994-01-01", until: str = "2001-12-31", client=None) -> list[FRDocument]` — `search` with both agencies, types RULE/PRORULE, term `"physician fee schedule"`, kept when `is_pfs_title` (Task 2); deduped by document number.
|
||||
- `document_for_citation(volume: int, page: int, *, client=None) -> FRDocument | None` — volume ≥ 59 only: documents published in year `1935 + volume` by either agency with fields `volume,start_page,end_page`; the one with `start_page ≤ page ≤ end_page`.
|
||||
- `rule_year_of(title, date_published)` also reads `Calendar Year (\d{4})` (and still `CY \d{4}`); publication-year fallback unchanged.
|
||||
- `bib.govinfo`: `issue_pdf_url(volume: int, page: int, *, client) -> str` (follows the `/link/fr/<v>/<p>` redirect, strips the fragment); `fr_page_index(pdf_path: Path) -> dict[int, int]` (printed FR page → 1-based PDF page, from page-header numbers found with pymupdf; pages without a header number omitted); `issue_documents(pdf_path: Path) -> list[tuple[int, str]]` (`(first FR page, title)` for each document — the `Medicare Program; …` title line preceding an `AGENCY:` block); `ingest_issue_rule(store, volume: int, page: int, *, client) -> str | None` — downloads the issue (`save_versioned` → `data/fr_downloads/govinfo/FR-<date>.pdf`), finds the document containing `page`, returns `None` unless `is_pfs_title(title)`, else upserts a bib `Rule` (title, `date_published`, url = the govinfo link, `extra_json` `fr_volume`, `fr_page`, `fr_page_index`), attaches the PDF, tags `module:pfs`, `source:govinfo`, `era:pre-1994`.
|
||||
- `harvest_fr_citations(store, *, volumes: range = range(56, 59), min_count: int = 3) -> list[tuple[int, int, int]]` — `(volume, page, count)` of FR citations found in `fr_anchors` paragraphs that also mention `fee schedule`, most cited first.
|
||||
- CLI: `stack bib discover-pfs-rules --legacy [--since 1994-01-01] [--until 2001-12-31] [--dry-run]`; `stack bib ingest-fr-issue --harvest [--dry-run]` and `stack bib ingest-fr-issue --cite "56 FR 59502"`.
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `test_legacy_discovery_includes_hcfa` (recorded search JSON with 95-18144 under HCFA and a non-PFS HCFA rule → only the PFS one), `test_document_for_citation_picks_containing_doc`, `test_rule_year_from_calendar_year_title` ("…Physician Fee Schedule for Calendar Year 1999", 1998-06-05 → 1999), `test_january_correction_keeps_its_year` ("…for Calendar Year 1998; Correction", 1998-01-30 → 1998), `test_issue_pdf_url_follows_redirect` (httpx MockTransport 302 → `…/FR-1991-11-25.pdf`), `test_fr_page_index_and_issue_documents` (a 3-page PDF generated in `tmp_path` with pymupdf: headers "59502"/"59503", a "Medicare Program; Fee Schedule for Physicians' Services" title + "AGENCY:" line), `test_ingest_issue_rule_skips_non_pfs`, `test_harvest_counts_citations`.
|
||||
- [ ] **Step 2: Run** → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Live, 1994–2001** — `ENV stack bib discover-pfs-rules --legacy --dry-run` (report the list), then without `--dry-run`; for each new key: `ENV stack bib fr-grab --key <K>`, `ENV python dev/scripts/fetch_fr_attachments.py --key <K>`; `docker exec llm uv run --no-sync stack llm index --collection rules --key <K> …`; `ENV stack bib code-tags`; sync with `--tag source:federal-register` (one-off container recipe). Spot-check one 1998 rule's `rule_kind` and `rule_year_of`.
|
||||
- [ ] **Step 6: Live, before 1994** — `ENV stack bib ingest-fr-issue --harvest --dry-run` (report the candidates and which resolve to PFS documents), then without `--dry-run`; index the issue PDFs into the corpus: `docker exec llm uv run --no-sync stack llm index --collection corpus --key <K> …`. Report the earliest rule captured and that `/link/fr/56/59502` resolves into it.
|
||||
- [ ] **Step 7: Commit** `git add src/bib/govinfo.py src/bib/federalregister.py src/pfs/descriptors.py src/cli/bib.py tests/bib/test_federalregister.py tests/bib/test_govinfo.py tests/pfs/test_descriptors.py tests/cli/test_bib_deep.py && git commit -m "feat(bib): PFS rules before CY2002 — HCFA-era FR discovery, Calendar Year titles, govinfo issue PDFs back to 1991"`
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Conversion factors for 1992–2013 in `pfs.rules.RULES`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/pfs/rules/__init__.py` (entries 1992–2013; `RuleYear.cf_categories`), `src/pfs/valuation.py` (multi-CF years not priced)
|
||||
- Test: `tests/pfs/test_rules.py`, `tests/pfs/test_valuation.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: the AMA "History of Medicare Physician Payment Schedule Conversion Factors" (Zotero `VVBEVYLC`, the source every existing entry cites); each year's final-rule FR citation (bib `fr_anchor_docs` `fr_volume`/`start_page`, or Task 4's items for pre-2002).
|
||||
- Produces:
|
||||
- `RULES[1992 … 2013]` — `RuleYear(year, conversion_factor, cf_segments, federal_register_citation, …)`; 2010 keeps the documented split (`36.0791` 1 Jan–31 May, `36.8729` 1 Jun–31 Dec, dominant `36.8729`).
|
||||
- `RuleYear.cf_categories: dict[str, float] = {}` — set for years the AMA table lists separate surgical / primary-care / other conversion factors; `conversion_factor` holds the "other nonsurgical" value there.
|
||||
- `pfs.valuation.valuation`: a final row in a year with non-empty `cf_categories` has `pay_nf = pay_f = None` and `cf_note = f"CY{y}: separate {', '.join(sorted(cf_categories))} conversion factors — payment not computed"`.
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `test_rules_cover_1992_to_2027` (no gaps), `test_cf_2010_segments` (values and boundaries above), `test_pre2014_values_match_transcription` (a dict `AMA_CF` in the test, transcribed from `VVBEVYLC`'s table — the reviewer checks it against the PDF page; the test pins it), `test_citations_are_fr_cites` (`^\d{2,3} FR \d+$` for 1992–2013), `test_multi_cf_year_not_priced` (1995 row → `pay_nf is None` and the note).
|
||||
- [ ] **Step 2: Run** `tests/pfs/test_rules.py tests/pfs/test_valuation.py` → FAIL.
|
||||
- [ ] **Step 3: Implement** — read the CF table from the `VVBEVYLC` attachment (`ENV python -c` opening it from Zotero storage, read-only) and transcribe; one comment per entry citing `:pincite:\`VVBEVYLC\``.
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Commit** `git add src/pfs/rules/__init__.py src/pfs/valuation.py tests/pfs/test_rules.py tests/pfs/test_valuation.py && git commit -m "feat(pfs): conversion factors 1992–2013 from the AMA CF history; multi-CF years flagged, not priced"`
|
||||
|
||||
---
|
||||
|
||||
### Task 6: RVU files before 2015 — the CMS archive (CY2003–CY2014)
|
||||
|
||||
**Reach (probed 2026-11-11):** the CMS "PFS Relative Value Files" listing (`https://www.cms.gov/medicare/payment/fee-schedules/physician/pfs-relative-value-files?items_per_page=All`, 112 links) reaches back to `RVU03A` (CY2003); release names include `RVU05AR`, `PRREV05D`, `RVU13AR`, `RVU18AR1`; item pages for older releases live under `/medicare/medicare-fee-for-service-payment/physicianfeesched/pfs-relative-value-files-items/cms0448NN`. Nothing earlier is published as a file; CY1992–CY2002 values exist only as Addendum B inside the FR rules (Task 4) — out of scope here, reported as the remaining gap.
|
||||
|
||||
**Files:**
|
||||
- Create: `src/pfs/rvu_archive.py`, `dev/scripts/fetch_pfs_rvu_archive.py`
|
||||
- Modify: `src/pfs/pipe.py` (`_RELEASE_RANK`; legacy recognizers/readers only as Step 5 requires), `dev/scripts/add_pprrvu_historical_to_zotero.py` (calls `add_release`)
|
||||
- Test: `tests/pfs/test_rvu_archive.py`, `tests/pfs/test_pipe_loaders.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1 (`save_versioned`, guarded `ingest_pfs.py`), Task 5 (`RULES` for pre-2015 CF matching in `_load_rvu_files`), `zot.db.Db`, `TYPE_MAP`, `generate_key`, `now_iso`.
|
||||
- Produces:
|
||||
- `@dataclass(frozen=True) Release(name: str, year: int, quarter: str, item_url: str, zip_urls: tuple[str, ...])`.
|
||||
- `parse_listing(html: str) -> list[tuple[str, str]]` — `(name, absolute item url)` for anchors whose text matches `^(?:RVU|PRREV)\d{2}[A-Z]{1,2}\d?$`.
|
||||
- `parse_item(html: str, base: str) -> list[str]` — absolute `.zip` links.
|
||||
- `release_of(name: str) -> tuple[int, str]` — year `2000 + yy`; suffix `A`/`B`/`C`/`D` → `q1`…`q4`; `AR`/`BR`/`CR`/`DR` (+digits) → `q1r`…`q4r`; `PRREV..D` → `q4r`; anything else → `x`.
|
||||
- `download_release(client, release: Release, root: Path) -> list[Path]` (`root/"zips"/<name>.zip` via `save_versioned`); `extract_release(zip_path: Path, dest: Path) -> list[Path]`; `zip_members(zip_path: Path) -> list[str]`.
|
||||
- `add_release(db, *, year: int, quarter: str, url: str, extracted_dir: Path, storage_dir: Path) -> int` — the body of today's `add_quarter` (one Zotero parent per release, tags `module:pfs`, `year:<y>`, `file:rvu`, `source:cms-website`, `release:<quarter>`, each extracted file attached); `add_pprrvu_historical_to_zotero.py` keeps working by calling it.
|
||||
- `pfs.pipe._RELEASE_RANK = {"q1": 10, "q1r": 11, "q2": 20, "q2r": 21, "q3": 30, "q3r": 31, "q4": 40, "q4r": 41}`; unknown → 50.
|
||||
- `dev/scripts/fetch_pfs_rvu_archive.py list|download|extract|members|zotero [--years FROM TO] [--root data/cms/rvu_archive]` — `list` writes `manifest.csv` (`name,year,quarter,item_url,zip_url`); `zotero` stops/starts the `zotero` container around the write (same hold as `stack zot fetch`).
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `test_parse_listing_recorded_page` (fixture = the saved listing HTML trimmed to 10 anchors incl. `RVU03A` and `PRREV05D`), `test_parse_item_zip_links`, `test_release_of_suffixes` (`RVU03A`→(2003,"q1"), `RVU13AR`→(2013,"q1r"), `RVU18AR1`→(2018,"q1r"), `PRREV05D`→(2005,"q4r"), `RVU05E`→(2005,"x")), `test_add_release_creates_tagged_parent` (`zotero_db` fixture), `test_release_rank_orders_revisions`.
|
||||
- [ ] **Step 2: Run** `tests/pfs/test_rvu_archive.py tests/pfs/test_pipe_loaders.py` → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Probe formats** — `ENV python dev/scripts/fetch_pfs_rvu_archive.py list --years 2003 2014`, `download`, `extract`, `members`. For any year whose members include no file `_is_pprrvu`/`_is_addendum_b` accepts (or whose layout `_read_pprrvu` cannot parse), add a recognizer/reader in `pfs/pipe.py` with a fixture test cut from that real file (≤ 30 lines of public CMS data) before Step 6; commit those with this task.
|
||||
- [ ] **Step 6: Zotero items** — `ENV python dev/scripts/fetch_pfs_rvu_archive.py zotero --years 2003 2014`; report items created per year.
|
||||
- [ ] **Step 7: Scratch load and diff** — `ENV python dev/scripts/ingest_pfs.py --db /home/kert/stack/.state/pfs/scratch.duckdb --no-lake --diff-against data/replica/aco.ro.duckdb` → 2015–2027 all `same`, 2003–2014 `new` with plausible row counts (~10–15k per year). Any `DIFF` stops the task.
|
||||
- [ ] **Step 8: Full reload** (no `--years`; confirm no notebook holds the lock): `ENV python dev/scripts/ingest_pfs.py`; then `ENV python -c "import duckdb; c=duckdb.connect('data/replica/aco.ro.duckdb', read_only=True); print(c.execute('select min(year), max(year), count(distinct year) from pfs.rvu').fetchall())"` → `(2003, 2027, 25)`.
|
||||
- [ ] **Step 9: Commit** `git add src/pfs/rvu_archive.py src/pfs/pipe.py dev/scripts/fetch_pfs_rvu_archive.py dev/scripts/add_pprrvu_historical_to_zotero.py tests/pfs/test_rvu_archive.py tests/pfs/test_pipe_loaders.py && git commit -m "feat(pfs): CMS RVU archive back to CY2003 — fetch, hoard, Zotero items, release ranks"` (plus any legacy-reader fixtures from Step 5).
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Governance literature — open-access items into bib/Zotero, paywalled onto a wanted list
|
||||
|
||||
**Files:**
|
||||
- Create: `src/bib/govlit.py`, `dev/scripts/import_governance_lit.py`
|
||||
- Modify: `src/bib/sync.py` (`_zotero_collection_path`)
|
||||
- Test: `tests/bib/test_govlit.py`, `tests/bib/test_sync.py`
|
||||
|
||||
**Input:** the reading list compiled 2026-11-11 (50 numbered entries + 41 companions, sections A–E, access OA/Paywalled/Unknown). **First step of the task:** copy it out of the session scratchpad, which does not persist: `mkdir -p data/governance_lit && cp /tmp/claude-1000/-home-kert-stack/ff67059d-a1a3-40dd-b7e9-7b24ef9ffce5/scratchpad/recon/ruc-literature.md data/governance_lit/ruc-literature.md` (`data/` is gitignored; this is a hoarded input).
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1 (`save_versioned`), `bib.item.Source`, `Store.upsert/attach_file`, `stack zot fetch`, `stack bib sync-zotero`.
|
||||
- Produces:
|
||||
- `@dataclass(frozen=True) LitEntry(entry_id: str, section: str, section_title: str, star: bool, citation: str, title: str, authors: str, year: int | None, venue: str, doi: str, url: str, oa_url: str, access: str, basis: str)`; `access ∈ ("oa","paywalled","unknown")`; companions get ids `"<n>.a"`, `"<n>.b"`… in order.
|
||||
- `parse_recon(md: str) -> list[LitEntry]` — numbered entries `**<n>. [★ ]<citation>**`; `- **DOI:**`/`- **URL:**`/`- **Access:**`/`- **Basis:**` lines; `*See also:*` companions (inline or bulleted) with their own DOI/URL and `(paywalled)`/`(OA)`/`OA:` marks; section from the preceding `## <X>. <title>` heading. Title = the quoted title, or the italic title for books/reports.
|
||||
- `to_item(e: LitEntry) -> Source` — `doc_type="journal-article"` when `doi` and a quoted article title exist, else `""`; `extra` lines `DOI: …`, `Journal: …`, `Authors: …`; `url` = `oa_url or url or doi url`; tags `source:governance-lit`, `gov-lit:entry-<id>`, `gov-lit:section-<x>`, `gov-lit:access-<access>`, plus `gov-lit:top10` when starred.
|
||||
- `WANTED_COLUMNS = ("title","authors","year","why_wanted","legal_options","doi","url","entry")`; `wanted_rows(entries, outcomes: Mapping[str, str]) -> list[dict]` — paywalled, unknown-and-not-found, and `refused` entries; `why_wanted` = `"governance literature, section <x>"`; `legal_options` = `"library loan; buy; author copy"` (`"court record (PACER)"` for case entries, `"publisher site"` for reports).
|
||||
- `bib.sync._zotero_collection_path`: `source:governance-lit` → `["Governance literature", <section title>]` (title from the item's `gov-lit:section-<x>` tag via a fixed map A–E).
|
||||
- `dev/scripts/import_governance_lit.py parse|import|fetch-direct|wanted [--md data/governance_lit/ruc-literature.md]` — `parse` writes `data/governance_lit/manifest.csv` and prints counts by section and access; `import` upserts items (idempotent: matching DOI or URL reuses the key); `fetch-direct` downloads `oa_url`s that are not DOI landing pages (GAO, MedPAC, NASEM, Urban, RAND, OECD, WHO, EFK, court opinions, government reports) to `data/governance_lit/files/<entry>-<slug><ext>` via `save_versioned` and `Store.attach_file`; HTML pages are saved as `.html`; a 403/429/bot page records outcome `refused` in `data/governance_lit/outcomes.jsonl`; `wanted` writes `data/governance_lit/wanted.csv`.
|
||||
|
||||
- [ ] **Step 1: Copy the input** (command above) and confirm `wc -l` = 394.
|
||||
- [ ] **Step 2: Failing tests** — synthetic markdown fixture in the test (two sections; a starred OA journal entry with DOI + PMC URL; a paywalled book; a numbered entry with one inline and one bulleted companion; a government report with URL only): `test_parse_counts_and_ids` (entries `1`, `2`, `2.a`, `2.b`, `3`), `test_access_and_oa_url`, `test_to_item_tags_and_extra`, `test_wanted_rows_for_paywalled_and_refused`, `test_collection_path_by_section`, `test_parse_live_list_counts` (skips unless `data/governance_lit/ruc-literature.md` exists: 50 numbered, 41 companions).
|
||||
- [ ] **Step 3: Run** `tests/bib/test_govlit.py tests/bib/test_sync.py` → FAIL.
|
||||
- [ ] **Step 4: Implement.**
|
||||
- [ ] **Step 5: Run** → PASS; ruff.
|
||||
- [ ] **Step 6: Live** — `ENV python dev/scripts/import_governance_lit.py parse` (report counts), `import`, `fetch-direct`; Zotero: one-off container sync with `--tag source:governance-lit`; open-access cascade on the DOI items: `ENV stack zot fetch --tag source:governance-lit` (dry run first with `--dry-run`); then `ENV python dev/scripts/import_governance_lit.py wanted`. Index: `docker exec llm uv run --no-sync stack llm index --collection corpus --key <every governance key with a file>`. Report: items imported, with full text (direct + cascade), refused, wanted-list size.
|
||||
- [ ] **Step 7: Commit** `git add src/bib/govlit.py src/bib/sync.py dev/scripts/import_governance_lit.py tests/bib/test_govlit.py tests/bib/test_sync.py && git commit -m "feat(bib): governance literature import — tagged items, open-access full text, wanted list for paywalled works"`
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Downstream refresh, gap check, docs
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/docs/cli/*` (regenerated)
|
||||
|
||||
- [ ] **Step 1: Refresh derived tables** (each rerun is idempotent; ledgers skip finished model work):
|
||||
|
||||
```
|
||||
ENV stack pfs lineage --all-seen --write # new RVU years (2003–2014) and FR rules (1991–2001, CY2013 NPRM)
|
||||
ENV stack bib code-tags # code:/family: tags on new rule and comment items
|
||||
ENV stack pfs families --write
|
||||
ENV stack pfs rounds --family HOME-VISITS --write # GPU: only new FR paragraphs/tables
|
||||
ENV stack pfs origin --family HOME-VISITS --write # GPU: 1990s rules now included
|
||||
ENV stack pfs cms-summaries --family HOME-VISITS --write
|
||||
ENV stack pfs reaction --family HOME-VISITS --write
|
||||
ENV stack pfs dossier --family HOME-VISITS --write
|
||||
```
|
||||
|
||||
For each CY2013–CY2017 docket where the dossier's family codes or phrases occur (`ENV stack pfs commenters --family HOME-VISITS --docket <D> --dry-run` prints the item count), run `commenters` and `stance` for that docket as in the home-visit plan's runbook.
|
||||
- [ ] **Step 2: Gap check** — `ENV python -c "from pfs.dossier import read_dossier; import duckdb; d=read_dossier(duckdb.connect('data/replica/aco.ro.duckdb', read_only=True), 'HOME-VISITS'); print('\n'.join(d.gaps))"`. Expected: the FR note names the earliest captured rule year (CY1992 if Task 4 Step 6 landed the 1991 rule), the RVU note names 2003, the docket note names CY2013, no "no conversion factor" note for 2003–2014, the governance note gone. Report the before/after lines and where each source's reach ends (FR anchors from 1995, govinfo PDFs from 1991, RVU files from 2003, dockets from CY2013).
|
||||
- [ ] **Step 3: Docs** — `uv run --no-sync python docs/scripts/extract_cli.py`; `git add docs/docs/cli && git commit -m "docs(cli): backfill commands — audit-pfs-rules, discover-pfs-rules --legacy, ingest-fr-issue"`; `git push gitea main`.
|
||||
- [ ] **Step 4: Roll** the images only if a nightly workflow invokes a changed CLI inside a container (the api image runs `stack bib …` in Comment Pull): follow the deploy procedure from `/home/kert/stack` (`COMMIT_SHA` in `.env`; `docker compose build api llm bcda docs mc`; `docker compose up -d --no-build --pull never --no-deps api mail-poller llm docs bcda lead mc`) and verify `docker exec api uv run --no-sync stack bib audit-pfs-rules --help`.
|
||||
|
||||
---
|
||||
|
||||
## Self-review
|
||||
|
||||
**Spec coverage.** Dockets before CY2018 (CY2013–CY2017; docket ids found) → T3. FR PFS rules before CY2002, as far back as federalregister.gov/govinfo reach (reported: anchored HTML from 1994/95, issue PDFs to 1991) → T4, with the inventory audit that the docket and FR work depend on → T2. RVU files before 2015 (CMS archive reaches CY2003; earlier only FR Addendum B — reported, not loaded) → T6, with the CFs that make those years payable in the dossier → T5. Governance literature: OA into bib/Zotero tagged with full text, paywalled on a wanted list → T7. "A dossier fills in as backfilled sources land" → T8 (computed gap notes from the sibling plan). Hoarding, honest UA, scratch-only filtered loads → T1 + Global Constraints.
|
||||
|
||||
**Not in this plan:** RVU values for CY1992–CY2002 from FR Addendum B tables (the only public source for those years; a follow-up once T4's rule texts are in); NPRM Addendum B (proposed RVUs) for years before CY2026 — the dossier's proposed-vs-final payment rows stay limited to the two captured NPRMs; stance runs for families other than HOME-VISITS on the new dockets (primary-care fan-out).
|
||||
|
||||
**Type consistency.** `save_versioned` (T1) is used by T4, T6, T7; `is_pfs_title` (T2) by T4; `RULES` entries (T5) are read by `pfs.pipe._load_rvu_files` (T6) and `pfs.valuation` (dossier); `release_of` quarter strings (T6) match `_RELEASE_RANK` keys; `LitEntry.section` letters (T7) match the `gov-lit:section-<x>` tags `_zotero_collection_path` reads and the `source:governance-lit` tag the dossier's `governance_excerpts` filters on.
|
||||
@@ -0,0 +1,700 @@
|
||||
# Code-family dossier — home and residence visits (proof family) 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:** A cited, browsable dossier for the HOME-VISITS family (99341–99350, the deleted domiciliary codes 99324–99328/99334–99340 and 99343, with G2211/B1/B2/G0318 links) — origin, formation, every valuation round, every change, payment over all years, and the politics (who commented how, what they stood to gain or lose) — on a page in the llm service and in chat, built only from stored rows.
|
||||
|
||||
**Architecture:** Each dossier ingredient is a `pfs.*` DuckDB table filled by one `stack pfs` command: deterministic parsers first (FR tables, regex, RVU/PSPS files, CMS impact files), then the self-hosted model through a resumable JSONL ledger for what only reading can extract (valuation narratives, origin, stance, identity). `pfs/dossier.py` turns rows into numbered, cited facts, lets the model write connective prose only over those facts, and rejects any sentence without a citation or with a number its cited facts don't carry; the result is stored as JSON in `pfs.dossier`, served at `/ui/family/<key>`, and fed to chat as a `dossier` SSE event + prompt block with an uncapped payment table.
|
||||
|
||||
**Tech Stack:** Python 3.13, uv, DuckDB (primary `data/aco.duckdb` via `duckdb_batch`, replica `data/replica/aco.ro.duckdb`), bib SQLite (`fr_anchors`, `items`, `dockets`), pgvector via SQLAlchemy `text()`, Ollama pool (`llm.pool.HostPool`, `cfg.instruct_model` = qwen2.5:14b), httpx, FastAPI + framework-free HTML, typer, pytest (xdist).
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-11-code-family-dossier-design.md` (builds on `docs/superpowers/specs/2026-09-09-code-family-longitudinal-design.md`). Backfills run in parallel under `docs/superpowers/plans/2026-11-11-code-family-dossier-backfills.md`; this plan never waits for them — its gap notes are computed from data and shrink as they land.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Commit straight to `main` in `/home/kert/stack`. No branches, worktrees, merge commits, PRs, `git stash`. Before every commit run `git status --short`; if anything you did not stage is staged, stop and ask (another session shares this checkout). `git add` explicit paths only.
|
||||
- Commit messages: conventional prefix (`feat(pfs): …`); no `Co-Authored-By` or any other trailer.
|
||||
- Never run a write/ingest command from a worktree. Every live command runs from the main checkout through the env wrapper: `bash -c 'cd /home/kert/stack && set -a && . ./.env && set +a && uv run --no-sync <cmd>'` (written **ENV** below). Before the first live run: `cat .venv/lib/python3*/site-packages/stack.pth` must print `/home/kert/stack/src` (else `uv sync --frozen`).
|
||||
- Local models only: every model call goes to Ollama through `llm.pool.HostPool` with `cfg.instruct_model` (qwen2.5:14b, the judge model; the pool picks the largest live host — the rig 4090 when up). Never a cloud LLM API; never `prisma.llm` or `rex.comments.classify` (they default to a cloud provider).
|
||||
- GPU is shared with tagging and chat: every model-backed command is resumable through `pfs.runlog` (unit id + input hash + model + prompt version), takes `--limit N` and `--dry-run`, and a long run goes `setsid nohup … > .state/dossier/<task>.log 2>&1 &` (`mkdir -p .state/dossier` once) with a Monitor on the log; rerunning the same command resumes. Check hosts first with `ENV stack llm hosts`.
|
||||
- DuckDB: write `data/aco.duckdb` only inside `conf.connect.duckdb_batch("aco")`, opened after the slow work (extract first, then a short batch that only writes), then `conf.connect.publish_replica("aco")`. Never run `pfs.pipe.load_all` or `dev/scripts/ingest_pfs.py` in this plan.
|
||||
- `pfs.*` modules never open a database at import. New tables: DDL in `pfs.codetables._DDL`, a frozen dataclass, delete-then-insert writer and a reader in `pfs/codetables.py`; a column added to an existing table also gets `ALTER TABLE … ADD COLUMN IF NOT EXISTS` in `ensure_tables` and a trailing defaulted dataclass field.
|
||||
- Network clients send an honest User-Agent (`stack-pfs-dossier/1.0`); never a browser UA. A 403/429/bot page stops that source and becomes a gap note; never work around it.
|
||||
- Hoard: never overwrite a source document; a re-download with different bytes is saved beside the old file as `<stem>.<sha8><suffix>`.
|
||||
- Public data only; no ACO/HarmonyCares/WNOT/Wakely material.
|
||||
- Individual commenters appear only as counts and organization types: no person's name is stored in a new table, shown on the page, sent in an SSE payload or put in a prompt. Comment items are displayed by regulations.gov id, never by bib title (`"First Last: CMS-…"`).
|
||||
- Every dossier statement cites a stored row; a sentence without a citation, or carrying a number that its cited rows don't, is rejected before the page renders.
|
||||
- Licensed AMA text (CPT codebooks, CPT Changes, E/M Compendium): store and show only paraphrase ≤ 240 characters with (edition, page); never store book text in a table, the dossier JSON, the page or chat; the copy guard rejects any 8-word run shared with the page.
|
||||
- Proposed and final values are separate fields everywhere; CMS's own summary of commenters (`pfs.cms_comment_summary`) is never merged into our classified counts (`pfs.comment_stance`) and is always labelled as CMS's.
|
||||
- Tests need no live DuckDB file, pgvector, Ollama or network (fakes as in `tests/pfs/test_reaction.py`, `tests/llm/test_rag.py`; temp DuckDB via `duckdb.connect(":memory:")` + `ensure_tables`; `Store(":memory:")` for bib). Live tests skip without the replica / `LLM_DB_PASSWORD`. CI runs `--cov-fail-under=99`: test every branch of new code.
|
||||
- Test: `uv run --no-sync pytest -q -p no:cacheprovider -n auto <paths>`. Lint: `uv run --no-sync ruff format <paths> && uv run --no-sync ruff check <paths>`.
|
||||
- Proof family key `HOME-VISITS`, name "Home or Residence Services". Proof-family FR anchors used as fixtures (verified 2026-11-11 in `fr_anchors`): `PETM225D` (CY2023 final, 87 FR) ¶1672, ¶1674–¶1686; `54GTKR5G` (CY2008 final, FR doc 07-5506) ¶2240–¶2242 and Table 14 at 72 FR 66361; `NHRGIHGD` (CY2026 final) ¶1469; `JCWARTJD` (CY2027 final) ¶1168, ¶1205; CY2023 NPRM docket `CMS-2022-0113`.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. **Model prose carrying a neighbour's number or a reformatted one** (99342's 1.65 cited to 99341's round; "1.0" for "1.00"; "$131" for "$131.17") — the check must reject the first and accept equivalent formatting of the same value. Pinned in Task 13 (`test_number_from_uncited_fact_rejected`, `test_equivalent_number_formats_accepted`).
|
||||
2. **A final rule recounting the proposal** ("We proposed a work RVU of 1.00 for CPT code 99341" in `PETM225D` ¶1676) stored or shown as the final value. Pinned in Task 5 (`test_final_rule_we_proposed_is_proposed`) and Task 14 (`proposed` rows marked).
|
||||
3. **CMS's characterization merged with our counts** ("The majority of commenters supported", ¶1679, added to or displayed as classified stance counts). Pinned in Task 9 (`test_rollup_ignores_cms_summaries`) and Task 13 (`test_cms_summary_and_stance_split_are_separate_facts`).
|
||||
4. **A private person's name leaking** through bib comment titles, regulations.gov first/last-name fields, a letterhead signature, or a model's `organization` answer. Pinned in Task 8 (`test_no_person_names_survive`), Task 13 (`test_dossier_json_has_no_person_names`), Task 15 (`test_dossier_payload_has_no_person_names`).
|
||||
5. **Deleted and merged codes going missing**: ranges ("99324-99328"), a deletion verb > 120 characters before the code (¶1672), codes whose RVU rows stop in 2022, codes absent from the newest RVU year. They must get lineage, show in the payment table only for their own years, and be labelled deleted. Pinned in Task 2 (`test_family_wide_deletion_sentence`, `test_seen_codes_includes_deleted`) and Task 12 (`test_deleted_code_rows_stop_at_last_year`).
|
||||
|
||||
---
|
||||
|
||||
## File map
|
||||
|
||||
| File | Responsibility |
|
||||
|---|---|
|
||||
| `src/pfs/curated.yaml`, `src/pfs/curated.py` | Hand-checked family membership + links, each with a citation |
|
||||
| `src/pfs/lineage.py` (mod) | Lineage for every code ever seen; `cpt_panel`, `misvalued` kinds |
|
||||
| `src/llm/structured.py` | JSON-schema extraction on the local pool |
|
||||
| `src/pfs/runlog.py` | Resumable JSONL ledger for model work |
|
||||
| `src/pfs/rounds.py` | Valuation rounds: FR tables, regex, model |
|
||||
| `src/pfs/origin.py` (+ `rex/comments/epub_text.py`) | Origin rows: FR, CPT Changes pages, guidance |
|
||||
| `src/pfs/cms_summaries.py` (+ `pfs/reaction.py`) | CMS Comment:/Response: summaries |
|
||||
| `src/pfs/commenters.py` | Commenter organization, type, specialty, form letters |
|
||||
| `src/pfs/stance.py` | Stance per family event; reaction roll-up |
|
||||
| `src/pfs/psps.py`, `src/pfs/stakes.py`, `src/pfs/seats.py` | Money and power stakes, expected stance |
|
||||
| `src/pfs/valuation.py` (mod) | All years, every NPRM vintage |
|
||||
| `src/pfs/cite.py`, `src/pfs/citecheck.py`, `src/pfs/dossier.py` | Citations, the sentence check, assembly |
|
||||
| `src/llm/api.py`, `src/llm/web/family.html` | The dossier page |
|
||||
| `src/llm/dossier.py`, `src/llm/rag.py`, `src/llm/evidence.py`, `src/llm/web/chat.html` | Chat |
|
||||
| `src/pfs/codetables.py` (mod), `src/cli/pfs.py` (mod) | Tables and commands for all of the above |
|
||||
|
||||
Order: Tasks 1–3 first; 4–12 depend only on 1–3 and may run in any order (their GPU steps share the pool — run them one at a time); 13 needs 4–12; 14–15 need 13; 16 last.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Curated family registry — HOME-VISITS
|
||||
|
||||
**Files:**
|
||||
- Create: `src/pfs/curated.yaml`, `src/pfs/curated.py`
|
||||
- Modify: `src/pfs/families.py` (`Family.curated`, `CURATED_FAMILIES`, seed/priority), `src/cli/pfs.py` (`families --write` applies curated rows)
|
||||
- Test: `tests/pfs/test_curated.py`, `tests/pfs/test_families.py`, `tests/cli/test_pfs_cli.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `pfs.codetables.FamilyRow`, `pfs.families.normalize_key`, `CODE_RE`, `Family`, `HAND_FAMILIES`, `refresh_from`, `_build_registry_index`.
|
||||
- Produces:
|
||||
- YAML schema per family key: `name`, `synonyms` (lower-case), `members: [{code, role, since, until, cite}]`, `links: [{kind, target, since, until, cite}]`; `cite` is exactly one of `{item_key, p_id}` (FR paragraph), `{item_key, page}` (FR page/book page), `{rvu_last_year}` (the RVU file the code last appears in).
|
||||
- `@dataclass(frozen=True) CuratedMember(code: str, role: str, since: int | None, until: int | None, item_key: str, p_id: int, page: int, rvu_year: int)`; roles ∈ `("base", "add-on", "predecessor", "successor", "member")`.
|
||||
- `@dataclass(frozen=True) CuratedLink(kind: str, target: str, since: int | None, until: int | None, item_key: str, p_id: int, page: int, rvu_year: int)`; kinds ∈ `("add-on", "modifier", "prolonged-add-on")`; `target` may be a modifier (`B1`).
|
||||
- `@dataclass(frozen=True) CuratedFamily(key: str, name: str, synonyms: tuple[str, ...], members: tuple[CuratedMember, ...], links: tuple[CuratedLink, ...])` with property `codes -> tuple[str, ...]` (sorted member codes).
|
||||
- `load_curated(path: Path | None = None) -> dict[str, CuratedFamily]` — packaged YAML via `importlib.resources.files("pfs").joinpath("curated.yaml")`; keys through `normalize_key`; `ValueError` naming the entry for a missing/ambiguous cite, unknown role/kind, or a member code failing `CODE_RE.fullmatch`.
|
||||
- `curated_rows(families: Mapping[str, CuratedFamily]) -> list[FamilyRow]` (`item_key`/`p_id` from the cite, `note=""`).
|
||||
- `apply_curated(derived: Sequence[FamilyRow], curated: Mapping[str, CuratedFamily]) -> list[FamilyRow]` — drops derived rows whose code is a curated member, appends `curated_rows`, sorted `(key, code)`.
|
||||
- `pfs.families`: `Family.curated: bool = False` (trailing default); `CURATED_FAMILIES: dict[str, Family]` built at import from `load_curated()` (`curated=True`, synonyms from YAML); `curated_family(key: str) -> CuratedFamily | None`; `FAMILIES` starts as `HAND_FAMILIES | CURATED_FAMILIES`; `_key_order` ranks hand 0, curated 1, derived 2; curated families match by synonym like hand families; `refresh_from` re-applies `CURATED_FAMILIES` after merging derived rows, so a derived key never replaces a curated one.
|
||||
|
||||
**HOME-VISITS content (binding):**
|
||||
- `synonyms`: `home visit`, `home visits`, `home or residence`, `residence visit`, `domiciliary`, `rest home visit`, `house call`, `house calls`.
|
||||
- base, cite `PETM225D` ¶1672: 99341 99342 99344 99345 99347 99348 99349 99350.
|
||||
- predecessor, `until: 2022`, cite `PETM225D` ¶1672: 99343 99324 99325 99326 99327 99328 99334 99335 99336 99337.
|
||||
- predecessor, `until: 2022`, cite `{rvu_last_year: 2022}`: 99339 99340 (no FR paragraph names their deletion — verified).
|
||||
- links: `add-on` G2211 since 2026 (`NHRGIHGD` ¶1469); `modifier` B1 since 2027 (`JCWARTJD` ¶1168); `modifier` B2 since 2027 (`JCWARTJD` ¶1205); `prolonged-add-on` G0318 since 2023 (`PETM225D` ¶1686).
|
||||
- 20 member codes (= `MAX_FAMILY_EXPAND`), so chat expands the family into codes.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
```python
|
||||
# tests/pfs/test_curated.py
|
||||
def test_packaged_home_visits_loads():
|
||||
fam = load_curated()["HOME-VISITS"]
|
||||
assert len(fam.codes) == 20 and "99343" in fam.codes and "G2211" not in fam.codes
|
||||
assert {(l.kind, l.target) for l in fam.links} >= {("add-on", "G2211"), ("modifier", "B1"), ("modifier", "B2"), ("prolonged-add-on", "G0318")}
|
||||
m = next(m for m in fam.members if m.code == "99343")
|
||||
assert (m.role, m.until, m.item_key, m.p_id) == ("predecessor", 2022, "PETM225D", 1672)
|
||||
|
||||
def test_member_without_cite_is_rejected(tmp_path): ... # ValueError mentions the code
|
||||
def test_unknown_role_rejected(tmp_path): ...
|
||||
def test_apply_curated_claims_codes():
|
||||
derived = [FamilyRow("NEW-PATIENT", "New Patient", "99341", "base", 2015, None, "", 0, "E/M > Home")]
|
||||
rows = apply_curated(derived, load_curated())
|
||||
assert [r.key for r in rows if r.code == "99341"] == ["HOME-VISITS"]
|
||||
|
||||
# tests/pfs/test_families.py
|
||||
def test_curated_detected_by_synonym(restore_families):
|
||||
d = detect_codes("how have home visits been valued?")
|
||||
assert "HOME-VISITS" in d.families and "99343" in d.codes
|
||||
def test_curated_survives_refresh(restore_families): ... # derived table has key HOME-VISITS with 1 code → FAMILIES["HOME-VISITS"] still has 20
|
||||
def test_family_of_prefers_curated_over_derived(restore_families): ... # 99341 in NEW-PATIENT and HOME-VISITS → HOME-VISITS
|
||||
|
||||
# tests/cli/test_pfs_cli.py
|
||||
def test_families_write_applies_curated(con): ... # read_families: 99341 only under HOME-VISITS
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to confirm failures** — `uv run --no-sync pytest -q -p no:cacheprovider tests/pfs/test_curated.py tests/pfs/test_families.py tests/cli/test_pfs_cli.py` → FAIL (`ModuleNotFoundError: pfs.curated`).
|
||||
- [ ] **Step 3: Implement** `curated.py`, the YAML, the `families.py` seeding/priority, and `apply_curated` inside `families --write` (after `_derive_rows`, before `write_families`). Before committing, verify every cite: `ENV python -c "…SELECT p_id, substr(text,1,120) FROM fr_anchors WHERE item_key=? AND p_id=?…"` for each `(item_key, p_id)` in the YAML; each must name the cited code(s) or family.
|
||||
- [ ] **Step 4: Run** the same tests → PASS; ruff.
|
||||
- [ ] **Step 5: Live** — `ENV stack pfs families --write` then `ENV stack pfs guidance --family HOME-VISITS --write` — report the HOME-VISITS row count (20) and the guidance rows found.
|
||||
- [ ] **Step 6: Commit** `git add src/pfs/curated.py src/pfs/curated.yaml src/pfs/families.py src/cli/pfs.py tests/pfs/test_curated.py tests/pfs/test_families.py tests/cli/test_pfs_cli.py && git commit -m "feat(pfs): curated family registry with cited membership — HOME-VISITS"`
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Lineage for every code ever seen; CPT Panel and misvalued events
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/pfs/lineage.py` (`seen_codes`, `deleted` window, `FR_KINDS` + patterns), `src/cli/pfs.py` (`_codes_for(..., all_seen=False)`, `lineage --all-seen`, `lineage --family`), `src/llm/lineage.py` (`_KIND_ORDER`, `_KIND_TEXT`)
|
||||
- Test: `tests/pfs/test_lineage.py`, `tests/cli/test_pfs_cli.py`, `tests/llm/test_lineage.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `lineage_all(con, store, codes)`, `_patterns(code)`, `rvu_events`, `write_events`, `pfs.curated.load_curated`.
|
||||
- Produces:
|
||||
- `seen_codes(con) -> list[str]` — distinct `pfs.rvu.hcpcs` over all years ∪ `pfs.cpt_code.code` over all editions ∪ curated member codes; keeps codes matching `CODE_RE.fullmatch` or `^\d{4}[A-Z]$`; missing CPT tables tolerated (`is_missing_table_error`).
|
||||
- `deleted` pattern window widened from 120 to 240 characters (both directions).
|
||||
- `FR_KINDS` gains, appended in this order: `"cpt_panel"` — `CPT Editorial Panel[^.]{0,240}\b(?:creat|delet|revis|merg|establish|replac)\w*[^.]{0,240}{c}`; `"misvalued"` — `potentially misvalued[^.]{0,200}{c}|{c}[^.]{0,200}potentially misvalued`.
|
||||
- CLI: `stack pfs lineage --all-seen [--limit N] [--write]`; `stack pfs lineage --family KEY [--write]` (curated or registered family's codes); `_codes_for(con, codes, families, all_payable, *, all_seen: bool = False, warn_slow: bool = True)`.
|
||||
- `llm.lineage`: `_KIND_ORDER` gets `"cpt_panel"` and `"misvalued"` after `"deleted"`; `_KIND_TEXT["cpt_panel"] = "was acted on by the CPT Editorial Panel"`, `_KIND_TEXT["misvalued"] = "was named as potentially misvalued"`.
|
||||
|
||||
- [ ] **Step 1: Failing tests**
|
||||
|
||||
```python
|
||||
P1672 = ("More specifically, in its February 2021 meeting, effective beginning in 2023, the CPT Editorial Panel "
|
||||
"deleted the nine CPT codes in the Domiciliary, Rest Home (for example, Boarding Home), or Custodial Care "
|
||||
"Services code family (CPT codes 99324-99328, and 99334-99337), and one CPT code in the Home Services family "
|
||||
"(CPT code 99343), to merge these services with the eight remaining home visit services.")
|
||||
|
||||
def test_family_wide_deletion_sentence(store): # store fixture gets PETM225D ¶1672 = P1672, title "CY 2023 PFS Final Rule"
|
||||
for code in ("99324", "99328", "99337", "99343"):
|
||||
kinds = {(e.kind, e.item_key, e.p_id) for e in fr_events(store, code)}
|
||||
assert ("deleted", "PETM225D", 1672) in kinds
|
||||
assert ("cpt_panel", "PETM225D", 1672) in kinds
|
||||
|
||||
def test_misvalued_event(store): ... # "…identified CPT code 99350 as potentially misvalued…" → kind misvalued
|
||||
def test_seen_codes_includes_deleted(): ... # pfs.rvu: 99343 only 2022, 99341 2022+2027, '\x1a' junk → ['99341','99343', …] no junk
|
||||
def test_rvu_disappeared_for_deleted_code(): ... # years 2015–2027, 99343 last 2022 → disappeared 2023
|
||||
def test_bucketed_equals_per_code_for_new_kinds(store): ... # fr_events_bucketed(store,[c])[c] == fr_events(store,c)
|
||||
# tests/cli/test_pfs_cli.py
|
||||
def test_lineage_all_seen_targets_deleted_codes(con, monkeypatch): ... # targets include a 2022-only code; batch opened after lineage_all
|
||||
def test_lineage_family_targets_curated_members(con, monkeypatch): ... # --family HOME-VISITS → 20 targets
|
||||
# tests/llm/test_lineage.py
|
||||
def test_cpt_panel_event_line(): ... # "2023: 99343 was acted on by the CPT Editorial Panel [label]"
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run** `tests/pfs/test_lineage.py tests/cli/test_pfs_cli.py tests/llm/test_lineage.py` → FAIL.
|
||||
- [ ] **Step 3: Implement** the signatures above (patterns appended last so existing `FR_KINDS.index` order holds).
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Live** — `ENV stack pfs lineage --all-seen --limit 50` (dry, timing), then `ENV stack pfs lineage --all-seen --write`. Report codes targeted, events per source, `disappeared` count (was 3), and events for 99324, 99339, 99343.
|
||||
- [ ] **Step 6: Commit** `git add src/pfs/lineage.py src/cli/pfs.py src/llm/lineage.py tests/pfs/test_lineage.py tests/cli/test_pfs_cli.py tests/llm/test_lineage.py && git commit -m "feat(pfs): lineage for every code ever seen; CPT Panel and misvalued events"`
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Local structured extraction + resumable ledger
|
||||
|
||||
**Files:**
|
||||
- Create: `src/llm/structured.py`, `src/pfs/runlog.py`
|
||||
- Modify: `src/cli/pfs.py` (`_asker()` indirection)
|
||||
- Test: `tests/llm/test_structured.py`, `tests/pfs/test_runlog.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `HostPool.check/acquire_generation/drop/hosts`, `llm.classify._default_post`, `conf.ROOT`.
|
||||
- Produces:
|
||||
- `class JsonExtractor` — `model: str`; `__call__(system: str, user: str, schema: Mapping[str, Any]) -> dict | None`. Built by `json_extractor(cfg, pool, *, post=None) -> JsonExtractor`: `pool.check(cfg.instruct_model)` once; each call POSTs `{host}/api/chat` with `{"model": cfg.instruct_model, "messages": [system, user], "stream": False, "format": schema, "options": {"num_ctx": cfg.chat_num_ctx, "temperature": 0}}`; `httpx.TransportError` → `pool.drop(host)` and retry on the next host, `RuntimeError` when none is left (same discipline as `llm.tagger.make_judge`); reply content parsed as JSON and checked with `validate`; invalid → `None` + log.
|
||||
- `validate(obj: Any, schema: Mapping[str, Any]) -> list[str]` — the JSON-schema subset used here: `type` (object/array/string/number/integer/boolean/null and lists of these), `enum`, `required`, `properties`, `items`, `maxLength`, `maxItems`. Returns error strings, `[]` when valid.
|
||||
- `pfs.runlog`: `@dataclass(frozen=True) Entry(unit: str, input_hash: str, model: str, version: str, output: dict | None, ts: str)`; `class RunLog(path: Path)` with `get(unit, input_hash, model, version) -> Entry | None` (latest match), `put(unit, input_hash, model, version, output) -> Entry` (append, flush, fsync), `outputs(model, version) -> dict[str, dict]` (latest non-null output per unit); `input_hash(*parts: str) -> str` (sha256, 16 hex); `ledger_path(task: str, family: str) -> Path` = `ROOT / "data/pfs/ledger" / f"{task}-{family}.jsonl"`; `Unit = tuple[str, str, Callable[[], dict | None]]`; `run_units(units: Iterable[Unit], log: RunLog, *, model: str, version: str, limit: int = 0, retry_failed: bool = False, progress: Callable[[str, str], None] | None = None) -> dict[str, int]` — counts `done`, `skipped` (same hash/model/version already logged), `failed` (output `None`, logged, retried only with `retry_failed`); `limit` caps *new* model calls.
|
||||
- `cli.pfs._asker() -> JsonExtractor` (`llm.config.load()`, `HostPool.from_config`).
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `test_extractor_posts_schema_and_fixed_model` (fake `post` captures json: `format` is the schema, `model == cfg.instruct_model` even when the host is large, temperature 0), `test_extractor_drops_dead_host_and_retries`, `test_extractor_returns_none_on_schema_violation`, `test_validate_enum_required_maxlength`; `test_runlog_resume_skips_logged_units` (second `run_units` over the same units → `skipped == 3`, no fn called), `test_runlog_new_hash_reruns`, `test_failed_units_retry_only_when_asked`, `test_limit_caps_new_calls`, `test_ledger_path_under_data`.
|
||||
- [ ] **Step 2: Run** `tests/llm/test_structured.py tests/pfs/test_runlog.py` → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Live smoke** — `ENV stack llm hosts`; then `ENV python -c "from cli.pfs import _asker; a=_asker(); print(a.model, a('Reply in JSON.', 'Say ok.', {'type':'object','properties':{'ok':{'type':'boolean'}},'required':['ok']}))"` → prints `qwen2.5:14b {'ok': True}`.
|
||||
- [ ] **Step 6: Commit** `git add src/llm/structured.py src/pfs/runlog.py src/cli/pfs.py tests/llm/test_structured.py tests/pfs/test_runlog.py && git commit -m "feat(llm,pfs): JSON-schema extraction on the local pool and a resumable run ledger"`
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Valuation rounds from Federal Register tables
|
||||
|
||||
**Files:**
|
||||
- Create: `src/pfs/rounds.py`, `tests/pfs/fixtures/fr_table_cy2008_t14.txt` (≤ 40 lines cut from `data/fr_downloads/07-5506.txt`: the `[[Page 66361]]` marker, Table 14 title, header, the 99326/99343/99350 and 92557 rows with their continuation lines, closing rule and footnote)
|
||||
- Modify: `src/pfs/codetables.py` (`RoundRow`, DDL `pfs.valuation_round`, `write_rounds`, `read_rounds`)
|
||||
- Test: `tests/pfs/test_rounds.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: bib `Store` attachments / `fr_anchor_docs.document_number`, `pfs.descriptors.rule_year_of`, `bib.frlink.rule_kind`.
|
||||
- Produces:
|
||||
- `@dataclass(frozen=True) RoundRow(family: str, code: str, rule_year: int, item_key: str, rule_kind: str, p_id: int, page: int, source: str, table_title: str, ruc_work_rvu: float | None, ruc_percentile: str, survey_intra_min: float | None, survey_total_min: float | None, comparators: str, surveying_societies: str, requested_work_rvu: float | None, proposed_work_rvu: float | None, final_work_rvu: float | None, decision: str, rationale_p_id: int, rationale_quote: str, pe_note: str, extractor: str)`; `source ∈ {"fr-table","fr-para"}`; `decision ∈ {"accept","refine","reject","interim",""}`; `write_rounds(con, family, rows)` delete-then-insert per family; `read_rounds(con, family) -> list[RoundRow]` ordered `(code, rule_year, rule_kind, source)`.
|
||||
- `fr_text_path(store, item_key) -> Path | None` — the rule's `.txt` attachment, else `ROOT/"data/fr_downloads"/f"{document_number}.txt"`, else `None`.
|
||||
- `split_pages(text: str) -> list[tuple[int, str]]` — on `[[Page N]]`; text before the first marker gets page 0.
|
||||
- `@dataclass(frozen=True) FrTable(title: str, page: int, header: tuple[str, ...], rows: tuple[tuple[str, ...], ...])`; `find_tables(text: str) -> list[FrTable]` — govinfo fixed-width tables: title line `Table \d+[.—-]+…`, dashed rule, stacked header lines joined column-wise by character span, dashed rule, body to the next dashed rule; dot leaders stripped; a continuation line (no code in column 1) appends to the previous row's descriptor.
|
||||
- `table_rounds(table: FrTable, *, family: str, item_key: str, rule_year: int, rule_kind: str, codes: set[str]) -> list[RoundRow]` — header roles by regex: `RUC` + `rec` → `ruc_work_rvu`; `proposed` → `proposed_work_rvu`; `request` → `requested_work_rvu`; `20\d\d work RVU|final|CMS` → `final_work_rvu`; `basis|decision` → decision text; tables with no RUC/proposed/final role are skipped; only rows whose code ∈ `codes`.
|
||||
- `decision_of(ruc: float | None, final: float | None, basis_text: str) -> str` — `interim` if basis/title says interim; `accept` if `Agree` or `ruc == final`; `refine` if `Refinement`/`Disagree` or both known and different; `reject` if basis says `reject`; else `""`.
|
||||
|
||||
- [ ] **Step 1: Failing tests**
|
||||
|
||||
```python
|
||||
def test_table_rounds_cy2008_home_visits():
|
||||
[t] = [t for t in find_tables(FIXTURE) if t.title.startswith("Table 14")]
|
||||
rows = {r.code: r for r in table_rounds(t, family="HOME-VISITS", item_key="54GTKR5G",
|
||||
rule_year=2008, rule_kind="final", codes={"99326", "99343", "99350"})}
|
||||
r = rows["99343"]
|
||||
assert (r.proposed_work_rvu, r.requested_work_rvu, r.ruc_work_rvu, r.final_work_rvu) == (2.27, 2.65, 2.27, 2.53)
|
||||
assert (r.decision, r.page, r.source) == ("refine", 66361, "fr-table")
|
||||
assert rows["99326"].final_work_rvu == 2.63 and rows["99350"].final_work_rvu == 3.28
|
||||
assert "92557" not in rows
|
||||
def test_continuation_lines_do_not_create_rows(): ...
|
||||
def test_agree_maps_to_accept(): ... # synthetic row "Agree" ruc 2.35 final 2.35 → accept
|
||||
def test_split_pages_numbers_text(): ...
|
||||
def test_fr_text_path_prefers_attachment(tmp_path): ...
|
||||
def test_rounds_roundtrip(): ... # write_rounds/read_rounds on :memory:
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run** `tests/pfs/test_rounds.py` → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Live (read-only)** — for every PFS rule item in `fr_anchor_docs`, report `fr_text_path` presence; fetch any missing text with `ENV python dev/scripts/fetch_fr_attachments.py --key <KEY>` (PETM225D's `2022-23873.txt` is missing today). Then count Table rounds per rule for the HOME-VISITS codes with a one-off `ENV python -c` loop — expect CY2008 rows for 99324–99350.
|
||||
- [ ] **Step 6: Commit** `git add src/pfs/rounds.py src/pfs/codetables.py tests/pfs/test_rounds.py tests/pfs/fixtures/fr_table_cy2008_t14.txt && git commit -m "feat(pfs): valuation rounds from Federal Register RUC/CMS tables"`
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Valuation rounds from FR paragraphs (regex + local model) — `stack pfs rounds`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/pfs/rounds.py`, `src/cli/pfs.py` (`rounds` command)
|
||||
- Test: `tests/pfs/test_rounds.py`, `tests/cli/test_pfs_cli.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 3 (`JsonExtractor`, `RunLog`, `run_units`, `ledger_path`, `input_hash`), Task 4 (`RoundRow`, `find_tables`, `table_rounds`, `fr_text_path`, `decision_of`), `CuratedFamily`, `pfs.families.code_pattern/codes_in`.
|
||||
- Produces:
|
||||
- `para_values(text: str, codes: set[str], *, rule_kind: str) -> list[tuple[str, str, float]]` — `(code, field, value)` from `work RVU of (\d+\.\d+) for (?:CPT|HCPCS) code (\w{5})` and `(\d+\.\d+) work RVUs (?:to|for) (?:CPT|HCPCS) code (\w{5})`; field by the clause verb: `We are proposing|we propose` → `proposed_work_rvu`; `We proposed` (any rule kind) → `proposed_work_rvu`; `finaliz\w+|we have assigned|we are assigning` → `final_work_rvu`; `RUC[- ]recommend\w*` → `ruc_work_rvu`.
|
||||
- `family_as_proposed(text: str) -> bool` — `finaliz\w+ the work RVU values? for the .{0,80}code family as proposed`.
|
||||
- `ruc_as_proposed(text: str) -> bool` — `(?:propos\w+|finaliz\w+) the RUC-recommended work RVUs? for all` (¶1676: "We proposed the RUC-recommended work RVU for all eight CPT codes").
|
||||
- `candidate_paragraphs(store, codes: Sequence[str], phrases: Sequence[str]) -> list[dict]` — `fr_anchors` rows (with `title`, `date_published`) naming a family code or phrase **and** matching `RUC|work RVU|survey|percentile|crosswalk|refine|direct PE`; each carries `context` = the two preceding paragraphs of the same item.
|
||||
- `ROUND_SCHEMA: dict`, `ROUND_PROMPT_VERSION = "rounds-v1"`: `{"codes": [{"code", "ruc_work_rvu", "ruc_percentile" ∈ ["25th","median","75th","other","none"], "survey_intra_min", "survey_total_min", "comparators": [str], "proposed_work_rvu", "final_work_rvu", "decision" ∈ ["accept","refine","reject","interim","none"], "pe_note" (maxLength 240)}], "surveying_societies": [str], "rationale_quote" (maxLength 300)}`.
|
||||
- `guard(row: RoundRow, text: str) -> RoundRow` — clears any number that does not literally occur in `text` (formats `1.00`/`1.0` compared numerically); clears `ruc_percentile` unless the text has `25th percentile`/`median`/`75th percentile`; clears `rationale_quote` unless it is a substring of `text`; clears society names not in `text`.
|
||||
- `model_rounds(para: dict, codes: set[str], ask: JsonExtractor, *, family: str) -> list[RoundRow]` (rule year/kind from the paragraph's item; every row passed through `guard`; `extractor=f"model:{ask.model}@{ROUND_PROMPT_VERSION}"`).
|
||||
- `merge_rounds(*sources: Sequence[RoundRow]) -> list[RoundRow]` — keyed `(code, item_key)`; per field, the first non-empty value in source order (table, regex, model) wins; a conflicting later value is appended to `pe_note` as `"conflict: <field> <value> (<extractor>)"`.
|
||||
- `apply_paragraph_rules(rows: Sequence[RoundRow], paras: Sequence[dict]) -> list[RoundRow]` — for a paragraph where `family_as_proposed` holds, every round of that `item_key` lacking a final gets `final_work_rvu = proposed_work_rvu`; where `ruc_as_proposed` holds, the codes that paragraph names (same `item_key`) lacking a RUC value get `ruc_work_rvu = proposed_work_rvu`; finally an empty `decision` is filled by `decision_of`.
|
||||
- `family_rounds(con, store, family: CuratedFamily, *, ask: JsonExtractor | None, log: RunLog | None, limit: int = 0, tables_only: bool = False) -> tuple[list[RoundRow], dict[str, int]]` — `apply_paragraph_rules(merge_rounds(table, regex, model), candidate paragraphs)`.
|
||||
- CLI `stack pfs rounds --family KEY [--tables-only] [--no-llm] [--limit N] [--dry-run] [--retry-failed] [--write]` — ledger `ledger_path("rounds", KEY)`; prints rounds per rule year and the run counts; `--write` writes `pfs.valuation_round` after extraction, then publishes.
|
||||
|
||||
- [ ] **Step 1: Failing tests** (fixture paragraphs = `PETM225D` ¶1676 and ¶1685 text, item title "CY 2023 PFS Final Rule")
|
||||
|
||||
```python
|
||||
def test_final_rule_we_proposed_is_proposed():
|
||||
vals = dict(((c, f), v) for c, f, v in para_values(P1676, {"99341", "99350"}, rule_kind="final"))
|
||||
assert vals[("99341", "proposed_work_rvu")] == 1.00 and vals[("99350", "proposed_work_rvu")] == 3.60
|
||||
assert not any(f == "final_work_rvu" for (_, f) in vals)
|
||||
def test_family_finalize_as_proposed_propagates():
|
||||
rows = apply_paragraph_rules(merge_rounds(regex_rows_1676), [para(1676, P1676), para(1685, P1685)])
|
||||
r = {x.code: x for x in rows}
|
||||
assert (r["99341"].final_work_rvu, r["99350"].final_work_rvu) == (1.00, 3.60)
|
||||
def test_ruc_recommended_proposal_sets_ruc(): # ¶1676 + ¶1685 → 99341 ruc 1.00 == final 1.00 → decision "accept"
|
||||
r = {x.code: x for x in apply_paragraph_rules(merge_rounds(regex_rows_1676), [para(1676, P1676), para(1685, P1685)])}
|
||||
assert (r["99341"].ruc_work_rvu, r["99341"].final_work_rvu, r["99341"].decision) == (1.00, 1.00, "accept")
|
||||
def test_guard_drops_numbers_not_in_text(): ... # fake ask returns 1.75 for 99341 → None
|
||||
def test_guard_keeps_median_only_when_stated(): ... # 99350 'median' kept; '75th' for 99341 cleared
|
||||
def test_merge_prefers_table_over_model(): ... # conflict recorded in pe_note
|
||||
def test_rounds_cli_writes_after_extraction(con, monkeypatch): ... # order: family_rounds → _batch → write_rounds → _publish
|
||||
def test_rounds_dry_run_makes_no_model_calls(con, monkeypatch): ...
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run** `tests/pfs/test_rounds.py tests/cli/test_pfs_cli.py` → FAIL.
|
||||
- [ ] **Step 3: Implement.** System prompt (in `rounds.py`): extract only values stated in the text for the listed codes; null when absent; a final rule's "we proposed" is a proposed value.
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: GPU run (resumable)**
|
||||
1. `ENV stack pfs rounds --family HOME-VISITS --dry-run` — report candidate paragraphs and table rows.
|
||||
2. `ENV stack pfs rounds --family HOME-VISITS --limit 5` — eyeball 5 ledger lines in `data/pfs/ledger/rounds-HOME-VISITS.jsonl`.
|
||||
3. `bash -c 'cd /home/kert/stack && set -a && . ./.env && set +a && setsid nohup uv run --no-sync stack pfs rounds --family HOME-VISITS > .state/dossier/rounds-HOME-VISITS.log 2>&1 &'`; Monitor the log until the summary line; rerun the same command to resume after any interruption.
|
||||
4. `ENV stack pfs rounds --family HOME-VISITS --write` (ledger complete → no model calls) — report rounds per year; confirm CY2023 99341 proposed 1.00 / final 1.00 / 25th / accept (¶1676/¶1685) and CY2008 99343 2.27→2.53 refine.
|
||||
- [ ] **Step 6: Commit** `git add src/pfs/rounds.py src/cli/pfs.py tests/pfs/test_rounds.py tests/cli/test_pfs_cli.py && git commit -m "feat(pfs): valuation rounds from FR paragraphs — regex, local model, number guard; stack pfs rounds"`
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Origin and formation — `stack pfs origin`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/rex/comments/epub_text.py` (`epub_pages`), `src/pfs/codetables.py` (`OriginRow`, `pfs.code_origin`, writers), `src/cli/pfs.py` (`origin`)
|
||||
- Create: `src/pfs/origin.py` (the EPUB in the tests is built in `tmp_path` from synthetic strings — **no AMA text** in the repo)
|
||||
- Test: `tests/pfs/test_origin.py`, `tests/rex/comments/test_epub_text.py`, `tests/cli/test_pfs_cli.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 3, `read_guidance(con, family)`, bib attachment for the CPT Changes 2023 item `3ANRT854` (`data/storage/SQ8I3KSP/…epub`), `fr_anchors`.
|
||||
- Produces:
|
||||
- `epub_pages(path: Path) -> list[tuple[str, str]]` — `(page_label, plain text)` in spine order, split at `<span id="page_<label>"/>` markers; text before the first marker labelled `""`.
|
||||
- `@dataclass(frozen=True) OriginRow(family: str, code: str, kind: str, reference: str, year: int | None, summary: str, cite_kind: str, item_key: str, p_id: int, page_label: str, locator: str, extractor: str)`; `kind ∈ ORIGIN_KINDS = ("statute","regulation","program","demonstration","cpt_panel","cms_gcode","coverage")`; `cite_kind ∈ ("fr_para","cpt_book","iom","cfr","mln")`; `write_origin(con, family, rows)`, `read_origin(con, family)`.
|
||||
- `fr_origin_candidates(store, codes, phrases) -> list[dict]` — paragraphs naming a family code/phrase and matching `section 1\d{3}|of the Act\b|statut|demonstration|Independence at Home|CPT Editorial Panel|establish|creat|benefit|homebound|coverage`.
|
||||
- `book_candidates(path: Path, codes: Sequence[str]) -> list[tuple[str, str]]` — `epub_pages` entries naming a family code.
|
||||
- `ORIGIN_SCHEMA`, `ORIGIN_PROMPT_VERSION = "origin-v1"`: `{"origins": [{"kind" ∈ ORIGIN_KINDS, "reference" (≤120), "year" (int|null), "codes": [str], "summary" (≤240)}]}`.
|
||||
- `shares_run(summary: str, text: str, n: int = 8) -> bool` (case/punctuation-insensitive word n-gram overlap).
|
||||
- `extract_origin(text: str, ask: JsonExtractor, *, source: str) -> list[dict]` — FR source: `reference` must occur in `text` (else dropped); book source: drop any item where `shares_run(summary, text)`; codes outside the family dropped.
|
||||
- `guidance_origins(con, family: str) -> list[OriginRow]` — deterministic `coverage`/`regulation` rows from `pfs.code_guidance` (IOM → `cite_kind="iom"`, CFR → `"cfr"`, MLN → `"mln"`), `extractor="guidance"`.
|
||||
- `family_origin(con, store, family: CuratedFamily, *, ask, log, books: Sequence[tuple[str, str, Path]], limit: int = 0) -> tuple[list[OriginRow], dict[str, int]]` (`books` = `(item_key, edition_label, path)`).
|
||||
- CLI `stack pfs origin --family KEY [--book ITEM_KEY …] [--limit N] [--dry-run] [--write]`; default book `3ANRT854` ("CPT Changes 2023").
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `test_epub_pages_split_on_page_spans` (synthetic EPUB: pages `ix`, `12`, `13` with known text), `test_book_summary_copy_guard` (an 8-word run copied → item dropped; a paraphrase kept), `test_fr_reference_must_appear` ("section 1861(s)(1) of the Act" absent → dropped), `test_guidance_origins_map_kinds`, `test_origin_rows_carry_page_label_for_book`, `test_origin_cli_write_after_extraction`.
|
||||
- [ ] **Step 2: Run** → FAIL.
|
||||
- [ ] **Step 3: Implement.** Prompt: paraphrase, never quote; one origin per distinct statute/program/panel action.
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: GPU run (resumable)** — `ENV stack pfs origin --family HOME-VISITS --dry-run` (report FR candidates and book pages), then `setsid nohup … stack pfs origin --family HOME-VISITS > .state/dossier/origin-HOME-VISITS.log 2>&1 &` (ENV form as in Task 5), Monitor, rerun to resume, then `ENV stack pfs origin --family HOME-VISITS --write`. Report rows by kind and cite kind; read three book rows against the EPUB page by eye for paraphrase quality.
|
||||
- [ ] **Step 6: Commit** `git add src/rex/comments/epub_text.py src/pfs/origin.py src/pfs/codetables.py src/cli/pfs.py tests/pfs/test_origin.py tests/rex/comments/test_epub_text.py tests/cli/test_pfs_cli.py && git commit -m "feat(pfs): origin and formation rows from FR, CPT Changes pages and guidance — stack pfs origin"`
|
||||
|
||||
---
|
||||
|
||||
### Task 7: CMS's own Comment:/Response: summaries — `stack pfs cms-summaries`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/pfs/reaction.py` (`PairSpan`, `fr_pair_spans`; `fr_pairs` rebuilt on spans), `src/pfs/codetables.py` (`CmsSummaryRow`, `pfs.cms_comment_summary`), `src/cli/pfs.py`
|
||||
- Create: `src/pfs/cms_summaries.py`
|
||||
- Test: `tests/pfs/test_cms_summaries.py`, `tests/pfs/test_reaction.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Ruling A12 pairing in `fr_pairs`, `llm.classify.closed_vocab_classifier` (via `cli.pfs._classifier`), `bib.frlink.rule_kind`.
|
||||
- Produces:
|
||||
- `@dataclass(frozen=True) PairSpan(item_key: str, rule_year: int, comment_p_id: int, response_p_id: int, comment_text: str, response_text: str, codes: tuple[str, ...])`; `fr_pair_spans(store, codes: Sequence[str], phrases: Sequence[str] = ()) -> list[PairSpan]` — same pairing as `fr_pairs`; a span qualifies by code or (when given) phrase; `fr_pairs(store, codes)` output unchanged (counts derived from spans).
|
||||
- `quantifier_of(comment_text: str) -> str` — first match in order: `all` (`\ball (?:of the )?commenters\b`), `majority` (`majority of (?:the )?commenters|most commenters`), `many` (`many|numerous commenters`), `several`, `some`, `few` (`(?:a )?few commenters`), `one` (`\b(?:one|a|another) commenter\b` — must not fire on "a few commenters"), else `unspecified`.
|
||||
- `response_action_of(response_text: str) -> str` — `finalize_as_proposed` (`finaliz\w+[^.]{0,120}as proposed|continue to believe|maintain`), `finalize_modified` (`finaliz\w+[^.]{0,120}(?:with (?:a )?modification|revis)|we have assigned|we are assigning`), `not_finalized` (`not (?:to )?finaliz|are not adopting|decline`), `acknowledged` (only thanks/appreciation), else `unclear`.
|
||||
- `SUMMARY_STANCES = ("support","modify","oppose","mixed","unclear")`; `summary_stance(comment_text: str, classify) -> str` (prompt prefix `"CMS's summary of public comments:"`; outside vocab → `unclear`).
|
||||
- `@dataclass(frozen=True) CmsSummaryRow(family: str, item_key: str, rule_year: int, rule_kind: str, comment_p_id: int, response_p_id: int, codes: str, quantifier: str, stance: str, response_action: str, extractor: str)`; `write_cms_summaries(con, family, rows)`, `read_cms_summaries(con, family)`.
|
||||
- `summaries(store, family: CuratedFamily, *, classify=None) -> list[CmsSummaryRow]` (`classify=None` → stance `unclear`, extractor `regex`).
|
||||
- CLI `stack pfs cms-summaries --family KEY [--no-llm] [--write]`.
|
||||
|
||||
- [ ] **Step 1: Failing tests** (fixture `PETM225D` ¶1673–¶1685 and `54GTKR5G` ¶2241–¶2242 texts)
|
||||
|
||||
```python
|
||||
@pytest.mark.parametrize("p,q", [(1679, "majority"), (1681, "few"), (1674, "unspecified"), (2241, "unspecified")])
|
||||
def test_quantifier(p, q): assert quantifier_of(TEXT[p]) == q
|
||||
@pytest.mark.parametrize("p,a", [(1675, "finalize_as_proposed"), (1680, "acknowledged"),
|
||||
(1682, "finalize_as_proposed"), (2242, "finalize_modified")])
|
||||
def test_response_action(p, a): assert response_action_of(TEXT[p]) == a
|
||||
def test_a_few_is_not_one(): assert quantifier_of("A few commenters said") == "few"
|
||||
def test_summaries_pair_and_classify(store): ... # fake classify → 'support' for ¶1679; rows carry (1679, 1680)
|
||||
def test_fr_pairs_unchanged_by_refactor(store_with_pairs): ... # existing expectations
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run** `tests/pfs/test_cms_summaries.py tests/pfs/test_reaction.py` → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Live (light GPU)** — `ENV stack pfs cms-summaries --family HOME-VISITS --write`; report rows per rule year and the ¶1679 row (`majority`, stance, response ¶1680).
|
||||
- [ ] **Step 6: Commit** `git add src/pfs/reaction.py src/pfs/cms_summaries.py src/pfs/codetables.py src/cli/pfs.py tests/pfs/test_cms_summaries.py tests/pfs/test_reaction.py && git commit -m "feat(pfs): CMS comment/response summaries with quantifier, action and stance — kept apart from our counts"`
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Commenter identity — `stack pfs commenters`
|
||||
|
||||
**Files:**
|
||||
- Create: `src/pfs/commenters.py`
|
||||
- Modify: `src/pfs/codetables.py` (`CommenterRow`, `pfs.commenter`), `src/cli/pfs.py`
|
||||
- Test: `tests/pfs/test_commenters.py`, `tests/cli/test_pfs_cli.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `bib.regulations_gov.Mirror.get_json`, `rex.comments.coordination.find_groups/form_letter_groups`, `pfs.anchors.code_or_family_predicate`, Task 3, `terminology.cms_acceptable_provider_specialty_codes` (replica).
|
||||
- Produces:
|
||||
- `ORG_TYPES = ("specialty_society","health_system","vendor","payer","patient_group","individual_clinician","individual","other","unknown")`.
|
||||
- `specialty_key(name: str) -> str` (upper-case, `&`→`AND`, non-alphanumerics → single space, stripped); `specialty_vocab(con) -> tuple[str, ...]` = sorted `specialty_key(specialty_description)` ∪ `("MULTISPECIALTY",)`.
|
||||
- `@dataclass(frozen=True) RegsFields(category: str, organization: str)`; `regs_fields(mirror, docket: str, comment_id: str) -> RegsFields` — reads `data.attributes.category`/`organization` only; first/last name fields are never read into any variable that outlives the call.
|
||||
- `CATEGORY_MAP: dict[str, str]` regulations.gov category → org type (`"Individual"`→`individual`, `"Physician"`→`individual_clinician`, `"Health Care Provider/Association: Hospital"`-style → `health_system`, `"Insurance"`→`payer`, `"Consumer Group"`→`patient_group`; categories the live dry run reports and this map lacks are added there before `--write`); an ambiguous category maps to `""` (defer to letterhead).
|
||||
- `IDENTITY_SCHEMA`, `IDENTITY_PROMPT_VERSION = "identity-v1"`: `{"organization" (≤160), "org_type" ∈ ORG_TYPES, "specialty" ∈ vocab ∪ ["NONE"], "on_behalf_of_organization": bool}`; `letterhead_identity(text: str, ask, *, specialties: Sequence[str], reg_org: str = "") -> dict | None` — input is the first 1,200 characters; `organization` is blanked unless `on_behalf_of_organization` is true, `org_type` is not `individual`/`individual_clinician`, and the name occurs (whitespace/case-normalized) in `text` or `reg_org`.
|
||||
- `form_groups(texts: Mapping[str, str]) -> dict[str, tuple[str, int]]` — item_key → (group id, group size) for groups ≥ `FORM_LETTER_MIN_SIZE`.
|
||||
- `family_comment_items(engine, codes: Sequence[str], family_key: str, phrases: Sequence[str], *, docket: str) -> list[tuple[str, str]]` — `(item_key, text)` one row per item: code/family predicate OR `document ~* :phrase_re`, lowest `seq` chunk first, up to 3 matching chunks concatenated ≤ 3,000 chars.
|
||||
- `@dataclass(frozen=True) CommenterRow(item_key: str, docket: str, comment_id: str, org_name: str, org_type: str, specialty: str, form_group: str, form_size: int, basis: str, reg_category: str, extractor: str)`; `basis ∈ ("regs_gov_fields","letterhead_model","both")`; `comment_id` from the item url `…/comment/<id>`; `write_commenters(con, rows)` (delete by item_key), `read_commenters(con, item_keys: Sequence[str] | None = None)`.
|
||||
- `identify(engine, store, con, family: CuratedFamily, *, docket: str, mirror, ask, log, limit: int = 0) -> tuple[list[CommenterRow], dict[str, int]]`.
|
||||
- CLI `stack pfs commenters --family KEY --docket D [--limit N] [--dry-run] [--write]`; `--dry-run` prints item count and the distinct regulations.gov categories with counts.
|
||||
|
||||
- [ ] **Step 1: Failing tests**
|
||||
|
||||
```python
|
||||
def test_no_person_names_survive(monkeypatch):
|
||||
mirror = FakeMirror({"data": {"attributes": {"category": "Physician", "organization": "",
|
||||
"firstName": "Jane", "lastName": "Doe"}}})
|
||||
ask = FakeAsk({"organization": "Jane Doe MD", "org_type": "individual_clinician",
|
||||
"specialty": "FAMILY PRACTICE", "on_behalf_of_organization": False})
|
||||
rows, _ = identify(engine_with([("K1", "Dear Administrator … Sincerely, Jane Doe, MD")]), store, con, HOME,
|
||||
docket="CMS-2022-0113", mirror=mirror, ask=ask, log=RunLog(tmp_path / "l.jsonl"))
|
||||
assert "Doe" not in repr(rows) and "Jane" not in repr(rows)
|
||||
assert (rows[0].org_type, rows[0].org_name) == ("individual_clinician", "")
|
||||
assert "Doe" not in (tmp_path / "l.jsonl").read_text()
|
||||
def test_org_must_appear_in_text(): ... # model invents "AAFP" not in text → org_name ""
|
||||
def test_category_map_precedence(): ... # reg 'Insurance' + letterhead 'vendor' → payer, basis regs_gov_fields
|
||||
def test_form_groups_marks_campaign(): ... # three ≥200-char near-identical letters → same group, size 3
|
||||
def test_specialty_key_normalizes(): assert specialty_key("Allergy/Immunology") == "ALLERGY IMMUNOLOGY"
|
||||
def test_commenters_cli_dry_run_lists_categories(con, monkeypatch): ...
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run** → FAIL.
|
||||
- [ ] **Step 3: Implement.** The ledger output dict holds only `organization` (post-guard), `org_type`, `specialty`, `on_behalf_of_organization` — never the raw reply.
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: GPU run (resumable), per docket, in this order** — `CMS-2022-0113` (CY2023), `CMS-2025-0304` (CY2026), `CMS-2026-2377` (CY2027), then every other PFS docket in `store.dockets()`:
|
||||
`ENV stack pfs commenters --family HOME-VISITS --docket CMS-2022-0113 --dry-run` (extend `CATEGORY_MAP` for unmapped categories, commit with this task), then the `setsid nohup … stack pfs commenters --family HOME-VISITS --docket <D> > .state/dossier/commenters-<D>.log 2>&1 &` form, Monitor, rerun to resume, then `--write`. Report per docket: items, org-type counts, form groups ≥ 3.
|
||||
- [ ] **Step 6: Commit** `git add src/pfs/commenters.py src/pfs/codetables.py src/cli/pfs.py tests/pfs/test_commenters.py tests/cli/test_pfs_cli.py && git commit -m "feat(pfs): commenter organization, type, specialty and form-letter groups — names never stored"`
|
||||
|
||||
---
|
||||
|
||||
### Task 9: Comment stance per family event — `stack pfs stance`
|
||||
|
||||
**Files:**
|
||||
- Create: `src/pfs/stance.py`
|
||||
- Modify: `src/pfs/codetables.py` (`StanceRow`, `pfs.comment_stance`; `ReactionRow.events_json: str = "{}"` + `ALTER TABLE pfs.code_reaction ADD COLUMN IF NOT EXISTS events_json VARCHAR`; `read_reaction` maps NULL → `"{}"`), `src/llm/rag.py` (`_docket_rule_year` delegates to `pfs.stance.docket_rule_year`), `src/cli/pfs.py`
|
||||
- Test: `tests/pfs/test_stance.py`, `tests/pfs/test_reaction.py`, `tests/cli/test_pfs_cli.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 3, Task 5 (`read_rounds`), Task 2 (`read_events`), Task 1 (`CuratedFamily.links`), Task 8 (`family_comment_items`, `read_commenters`), `pfs.reaction.series`, `Store.dockets()`.
|
||||
- Produces:
|
||||
- `docket_rule_year(comment_end_date: str) -> int` — same rule as today's `llm.rag._docket_rule_year`.
|
||||
- `@dataclass(frozen=True) EventChoice(event_key: str, text: str, rule_year: int)`; `event_key = f"{family}:{year}:{slug}"` with slugs `valuation`, `coding`, `telehealth`, `<link target>` (e.g. `G0318`), `other`.
|
||||
- `docket_events(con, family: CuratedFamily, rule_year: int) -> list[EventChoice]` — `valuation` when rounds exist for that year (text names codes and RUC/proposed values), `coding` from created/deleted/cpt_panel/descriptor events that year, `telehealth` from telehealth_list events, one per link with `since == rule_year`, always `other` last; deterministic text.
|
||||
- `stance_schema(events: Sequence[EventChoice]) -> dict`, `STANCE_PROMPT_VERSION = "stance-v1"`: `{"positions": [{"event" ∈ keys, "stance" ∈ ["support","modify","oppose","unclear"], "reason" (≤200), "evidence" (≤200)}]}`.
|
||||
- `@dataclass(frozen=True) StanceRow(family: str, item_key: str, docket: str, event_key: str, stance: str, reason: str, evidence: str, extractor: str)`; `write_stances(con, family, docket, rows)`, `read_stances(con, family)`.
|
||||
- `classify_comment(text: str, events: Sequence[EventChoice], ask, *, family: str, item_key: str, docket: str) -> list[StanceRow]` — positions with unknown events dropped; `evidence` kept only if ≥ 6 consecutive words of it occur in `text`.
|
||||
- `rollup(stances: Sequence[StanceRow], *, base: ReactionRow) -> ReactionRow` — `stance_*` = distinct commenters by their first non-`unclear` position in event order (all-unclear → `unclear`); `events_json` = `{event_key: {"support": n, "modify": n, "oppose": n, "unclear": n}}`; `sample_json` unchanged from `base`.
|
||||
- CLI `stack pfs stance --family KEY --docket D [--limit N] [--dry-run] [--write]` — `--write` writes `pfs.comment_stance` for (family, docket) and replaces that docket's `pfs.code_reaction` row with `rollup(…, base=<row from reaction series>)`, keeping every other row.
|
||||
- `stack pfs reaction --write` (existing) overlays `rollup(<stored stances for that docket>, base=row)` on every docket row it writes, so a reaction rerun never zeroes classified counts; `--stance-sample` is refused for a family that has stored stances (the sample would be a second, weaker count).
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `test_docket_events_cy2023_home_visits` (rounds for 2023, cpt_panel events 2023, link G0318 since 2023 → keys `HOME-VISITS:2023:valuation`, `HOME-VISITS:2023:coding`, `HOME-VISITS:2023:G0318`, `HOME-VISITS:2023:other` in that order), `test_unknown_event_in_reply_dropped`, `test_evidence_must_occur_in_text`, `test_rollup_counts_distinct_commenters`, `test_rollup_ignores_cms_summaries` (rollup signature accepts only `StanceRow`s; a fixture with `pfs.cms_comment_summary` rows saying "majority supported" leaves counts equal to the stance rows), `test_reaction_events_json_roundtrip_and_null_tolerated`, `test_docket_rule_year_matches_rag`, CLI write keeps fr-pairs rows, `test_reaction_rerun_keeps_stance_counts`, `test_stance_sample_refused_when_stances_stored`.
|
||||
- [ ] **Step 2: Run** → FAIL.
|
||||
- [ ] **Step 3: Implement.** Prompt lists the events with their text and asks for positions only on events the comment addresses.
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: GPU run (resumable)** — same docket order as Task 8: `ENV stack pfs stance --family HOME-VISITS --docket <D> --dry-run`, `setsid nohup … stack pfs stance --family HOME-VISITS --docket <D> > .state/dossier/stance-<D>.log 2>&1 &`, Monitor, rerun to resume, `--write`. Report per docket: commenters classified, per-event counts; read 10 random CY2023 positions against their comments by eye and report agreement.
|
||||
- [ ] **Step 6: Commit** `git add src/pfs/stance.py src/pfs/codetables.py src/llm/rag.py src/cli/pfs.py tests/pfs/test_stance.py tests/pfs/test_reaction.py tests/cli/test_pfs_cli.py && git commit -m "feat(pfs): comment stance per family event with reasons and evidence; reaction roll-up"`
|
||||
|
||||
---
|
||||
|
||||
### Task 10: Money stakes — by-specialty utilization (PSPS) and CMS specialty impacts
|
||||
|
||||
**Files:**
|
||||
- Create: `src/pfs/psps.py`, `src/pfs/stakes.py`, `tests/pfs/fixtures/impact_cy2027_508.txt` (header + 6 rows of the CY2027 final 508 file), `tests/pfs/fixtures/impact_cy2017_fr.txt` (title + 4 dot-leader rows from `data/fr_downloads/2016-26668.txt`)
|
||||
- Modify: `src/pfs/codetables.py` (`ImpactRow`, `pfs.specialty_impact`, writers), `src/cli/pfs.py` (`psps`, `impacts`)
|
||||
- Test: `tests/pfs/test_psps.py`, `tests/pfs/test_stakes.py`, `tests/cli/test_pfs_cli.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `pfs.utilization` patterns (`fetch_year`/`cite`/`write`, `cms.ingest_log.log_ingest`), `pfs.valuation.ValuationRow`, `specialty_key` (Task 8).
|
||||
- Produces:
|
||||
- `pfs.psps.DATASETS: dict[int, str]` — "Physician/Supplier Procedure Summary" Data API ids from `https://data.cms.gov/data.json` (read 2026-11-11): 2010 `f4344bd9-ac34-43f0-b144-0186f6fa099f`, 2011 `1e9f7a5a-5550-4525-bbbf-ef66115184b8`, 2012 `b597d146-81bc-43f7-80b1-c2e85168170d`, 2013 `53027e7f-1b1d-4628-a286-03b0bc0b5f2f`, 2014 `3d28f6b0-e9df-48ea-b2eb-5cac10eaaf45`, 2015 `f8392bbd-981b-4ea6-b9f9-0891825105d7`, 2016 `b8a1bee7-62b2-44eb-8585-0c257a3d8c3f`, 2017 `3060244e-269e-4442-a983-8c190adfe7f1`, 2018 `6056deb7-17a7-49bc-a5b3-c799b4f91568`, 2019 `0ce67ad8-524b-4d4f-8ac8-55f4a68f0711`, 2020 `5eb3eebe-20cb-405c-864f-444873134f24`, 2021 `72200613-6706-4ad2-8219-e200cc4391cc`, 2022 `e4786716-10e9-40f2-b936-7444177474d5`, 2023 `b72adfb6-22cf-4241-9c64-050ad9061e03`, 2024 `647c8fa8-5dd6-460d-a2ec-18faf15b3fb2` (2025 lists two distributions — leave it out until one is confirmed as the full year).
|
||||
- `@dataclass(frozen=True) PspsRow(year: int, hcpcs: str, specialty_cd: str, specialty: str, services: float | None, allowed: float | None, paid: float | None, dataset_id: str, item_key: str)`; table `pfs.utilization_specialty`.
|
||||
- `fetch_code_year(client, year: int, code: str, *, page_size: int = 5000) -> list[dict]` (`filter[HCPCS_CD]=<code>`, paged until short page); `cache_path(year, code) -> Path` = `data/cms/psps/<year>/<code>.json` (hoard rule applies); `to_rows(year, code, records, *, dataset_id, item_key, names: Mapping[str, str]) -> list[PspsRow]` — national sum by `PROVIDER_SPEC_CD` of `PSPS_SUBMITTED_SERVICE_CNT`, `PSPS_ALLOWED_CHARGE_AMT`, `PSPS_NCH_PAYMENT_AMT`, rows with `PSPS_ERROR_IND_CD != "0"` excluded, `"*"` → `None` (a sum with any `None` part is `None`), names from `terminology.cms_acceptable_provider_specialty_codes`; `cite(store, year) -> str` (bib Source per year, tags `module:pfs`, `table:pfs.utilization_specialty`, `source:cms-website`, `year:<y>`); `write(con, year, code, rows) -> int`; `read_by_specialty(con, codes, *, years=None) -> list[PspsRow]`.
|
||||
- `pfs.stakes`: `@dataclass(frozen=True) ImpactRow(rule_year: int, vintage: str, specialty: str, setting: str, allowed_mil: float | None, impact_work: float | None, impact_pe: float | None, impact_mp: float | None, impact_combined: float | None, source: str, item_key: str, page: int)`; `parse_impact_508(path, *, rule_year, vintage, item_key="") -> list[ImpactRow]`; `parse_impact_fr_text(text, *, rule_year, vintage, item_key) -> list[ImpactRow]` (rows under a title containing `Impact on Total Allowed Charges by Specialty`; page from the nearest `[[Page N]]`; setting `TOTAL`); percent `"-2%"` → `-0.02`; `"$1,672"` → `1672.0`; `write_impacts(con, rule_year, vintage, rows)`, `read_impacts(con, rule_years)`.
|
||||
- `@dataclass(frozen=True) SpecialtyMoney(specialty: str, services: float, delta_per_service: float | None, delta_total: float | None, share: float)`; `money_by_specialty(payment: Sequence[ValuationRow], psps: Sequence[PspsRow], *, year: int) -> list[SpecialtyMoney]` — per code Δ = `pay_nf` (final, `year`) − `pay_nf` (final, `year-1`); services from the latest PSPS year ≤ `year-1`; summed per `specialty_key`; `share` = specialty services ÷ family services; codes lacking either year contribute `None` deltas but still count in `share`; `billing_share(psps, *, year) -> dict[str, float]`.
|
||||
- CLI `stack pfs psps --family KEY [--year Y …] [--write] [--offline]`; `stack pfs impacts --scan [--write]` (every bib attachment matching `Impact on Total Allowed Charges by Specialty.*_508\.txt` + every PFS final rule `.txt`) and `stack pfs impacts --path P --year Y --vintage final|proposed [--write]`.
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `test_parse_impact_508` (ALLERGY/IMMUNOLOGY TOTAL allowed 240.0, PE −0.02, combined −0.02; ANESTHESIOLOGY TOTAL 1672.0), `test_parse_impact_fr_text` (ALLERGY/IMMUNOLOGY 231, combined 0.01, page from marker), `test_psps_aggregates_by_specialty` (three records incl. a modifier row and a `"*"` → summed, `None` propagation, error-indicator row skipped), `test_money_by_specialty_exact` (code pay 100→90; services FP 10, NP 30 → FP −100.0, NP −300.0, shares 0.25/0.75), `test_psps_cli_offline_uses_cache`, `test_impacts_scan_finds_508`.
|
||||
- [ ] **Step 2: Run** → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Live (network, no GPU)** — `ENV stack pfs psps --family HOME-VISITS --write` (20 codes × 2010–2024; report rows, services by top 5 specialties for 99350 in 2023); `ENV stack pfs impacts --scan --write` (report rule years and vintages loaded; CY2027 final from `data/cms/pfs_final/2027/files/…_508.txt` must be among them).
|
||||
- [ ] **Step 6: Commit** `git add src/pfs/psps.py src/pfs/stakes.py src/pfs/codetables.py src/cli/pfs.py tests/pfs/test_psps.py tests/pfs/test_stakes.py tests/cli/test_pfs_cli.py tests/pfs/fixtures/impact_cy2027_508.txt tests/pfs/fixtures/impact_cy2017_fr.txt && git commit -m "feat(pfs): money stakes — PSPS utilization by specialty and CMS specialty impact tables"`
|
||||
|
||||
---
|
||||
|
||||
### Task 11: Power stakes and the expected-stance rule
|
||||
|
||||
**Files:**
|
||||
- Create: `src/pfs/seats.py`
|
||||
- Modify: `src/pfs/stakes.py` (`expected_stance`, `StakeholderUnit`, `stakeholder_units`), `src/pfs/codetables.py` (`SeatRow`, `pfs.governance_seat`), `src/cli/pfs.py` (`seats`)
|
||||
- Test: `tests/pfs/test_seats.py`, `tests/pfs/test_stakes.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 3, Task 8 (`ORG_TYPES`, `specialty_vocab`, `CommenterRow`), Task 9 (`StanceRow`), Task 10 (`SpecialtyMoney`, `billing_share`), `pfs.utilization`-style hoarded downloads.
|
||||
- Produces:
|
||||
- `@dataclass(frozen=True) SeatRow(body: str, year: int, organization: str, specialty: str, seat_type: str, source_url: str, item_key: str, snapshot: str)`; `body ∈ ("RUC","CPT_PANEL")`; `seat_type ∈ ("permanent","rotating","chair","hcpac","other","")`; organizations only — never a person; `write_seats(con, body, rows)`, `read_seats(con)`.
|
||||
- `cdx_snapshots(client, url: str, years: range) -> list[tuple[int, str]]` — one 200-status snapshot per year from `http://web.archive.org/cdx/search/cdx?url=<url>&output=json&from=<y>&to=<y>&filter=statuscode:200&limit=1`; snapshot URL `https://web.archive.org/web/<ts>id_/<url>`.
|
||||
- `SEAT_SCHEMA`, `SEAT_PROMPT_VERSION = "seats-v1"`: `{"seats": [{"organization" (≤160), "seat_type", "specialty" ∈ vocab ∪ ["NONE"]}]}`; `extract_seats(text: str, ask, *, specialties) -> list[dict]` — organization must occur in `text`.
|
||||
- CLI `stack pfs seats --body RUC|CPT_PANEL --url URL --from 2005 --to 2026 [--limit N] [--dry-run] [--write]` — each snapshot saved as a bib Download (tags `source:ama`, `doc:<body>-roster`, `year:<y>`; hoard rule); a refused fetch (403/bot page) stops and prints `gap: <body> roster not captured (<status>)`.
|
||||
- `@dataclass(frozen=True) Expectation(stance: str, reason: str)`; `expected_stance(*, org_type: str, share: float, delta_pct: float | None, new_payment: bool) -> Expectation` — rule (phase 1, explicit): org_type ∈ {`payer`,`patient_group`,`other`,`unknown`} → `n/a`; `share < 0.01` → `n/a`; `new_payment` → `support`; `delta_pct is None` → `unclear`; `delta_pct <= -0.005` → `oppose`; `delta_pct >= 0.005` → `support`; else `unclear`. `reason` copy: `"payment {delta_pct:+.1%} per service for a specialty billing {share:.0%} of the family"` / `"new payment for a specialty billing {share:.0%} of the family"` / `"not a billing stakeholder"`.
|
||||
- `@dataclass(frozen=True) StakeholderUnit(org_type: str, specialty: str, organizations: tuple[str, ...], n_commenters: int, stance: dict[str, int], expected: Expectation, share: float, delta_total: float | None, seats: int)`; `stakeholder_units(commenters, stances, money, seats, *, event_key: str, year: int) -> list[StakeholderUnit]` — unit = org type × specialty; `organizations` empty for `individual`/`individual_clinician`; seats = rows for that specialty and year.
|
||||
|
||||
- [ ] **Step 1: Failing tests** — table-driven `test_expected_stance_rule` (8 cases incl. payer→n/a, share 0.005→n/a, −3% → oppose with exact reason text, new payment → support), `test_stakeholder_units_never_list_individuals`, `test_units_group_by_org_type_and_specialty`, `test_cdx_snapshots_parse` (fixture CDX JSON), `test_extract_seats_drops_unseen_org`, `test_seats_cli_records_gap_on_403`.
|
||||
- [ ] **Step 2: Run** → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Live** — find the AMA's public RUC composition page and CPT Editorial Panel member page (AMA site; record the two URLs in the commit message), then `ENV stack pfs seats --body RUC --url <url> --from 2005 --to 2026 --dry-run` and, if snapshots exist and are readable, run without `--dry-run` (resumable, small) and `--write`. If refused, report the gap line — the dossier states it (Task 13).
|
||||
- [ ] **Step 6: Commit** `git add src/pfs/seats.py src/pfs/stakes.py src/pfs/codetables.py src/cli/pfs.py tests/pfs/test_seats.py tests/pfs/test_stakes.py && git commit -m "feat(pfs): RUC/CPT Panel seats from public rosters and an explicit stakes-to-stance rule"`
|
||||
|
||||
---
|
||||
|
||||
### Task 12: Complete payment table — every year, every NPRM vintage
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/pfs/valuation.py`
|
||||
- Test: `tests/pfs/test_valuation.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `pfs.rvu`, `pfs.rvu_proposed`, `RULES`, `NPRM_SOURCES`, `proposed_for`.
|
||||
- Produces:
|
||||
- `valuation(con, codes, *, years: int = 4, all_proposed: bool = False) -> tuple[list[ValuationRow], list[str]]` — `years <= 0` → every final year in `pfs.rvu` that has a `RULES` entry (no `dense_rank` cap); `all_proposed=True` → one proposed row per code for **every** `NPRM_SOURCES` year whose `cms_rule_id` has rows in `pfs.rvu_proposed` and `proposed_for(year)` is not `None`; default arguments return exactly today's rows.
|
||||
- `skipped_years(con, codes: Sequence[str]) -> list[int]` — `pfs.rvu` years for these codes with no `RULES` entry (feeds the dossier's gap notes).
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `test_valuation_all_years` (fixture 99341 rows 2015–2027 → 13 final rows), `test_all_proposed_rows_per_nprm_year` (rvu_proposed rows for CMS-1832-P and CMS-1848-P → vintages `"CY2026 proposed"`, `"CY2027 proposed"`, CFs from `proposed_for`), `test_default_unchanged` (years=4 output equals a recorded expectation), `test_deleted_code_rows_stop_at_last_year` (99343 rows 2015–2022 only; no 2023+ rows, no proposed rows), `test_skipped_years` (monkeypatched `RULES` without 2014 + a 2014 rvu row → `[2014]`).
|
||||
- [ ] **Step 2: Run** `tests/pfs/test_valuation.py` → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** `tests/pfs/test_valuation.py tests/llm/test_evidence.py` → PASS (chat behavior unchanged); ruff.
|
||||
- [ ] **Step 5: Live** — `ENV python -c "import duckdb; from pfs.valuation import valuation; c=duckdb.connect('data/replica/aco.ro.duckdb', read_only=True); r,u=valuation(c, ['99341','99343'], years=0, all_proposed=True); print(len(r), u, [(x.code, x.vintage) for x in r][-4:])"`.
|
||||
- [ ] **Step 6: Commit** `git add src/pfs/valuation.py tests/pfs/test_valuation.py && git commit -m "feat(pfs): valuation over every year and every captured NPRM vintage"`
|
||||
|
||||
---
|
||||
|
||||
### Task 13: Dossier assembly and the citation check — `stack pfs dossier`
|
||||
|
||||
**Files:**
|
||||
- Create: `src/pfs/cite.py`, `src/pfs/citecheck.py`, `src/pfs/dossier.py`, `tests/pfs/home_visits_fixture.py`, `tests/pfs/fixtures/home_visits_fr.jsonl` (public-domain FR paragraphs: every anchor listed in Global Constraints, with `item_key, p_id, page, text, title, date_published`), `tests/pfs/fixtures/home_visits_rvu.csv` (`pfs.rvu` base rows for the 20 member codes, all years)
|
||||
- Modify: `src/llm/lineage.py` (`rule_label` moves to `pfs.cite`, re-exported), `src/llm/search.py` (`search(..., item_keys=None)` → `{"item_key": {"$in": [...]}}`), `src/pfs/codetables.py` (`pfs.dossier`), `src/cli/pfs.py` (`dossier`)
|
||||
- Test: `tests/pfs/test_cite.py`, `tests/pfs/test_citecheck.py`, `tests/pfs/test_dossier.py`, `tests/llm/test_search.py`, `tests/cli/test_pfs_cli.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: every table from Tasks 1–12, `pfs.utilization.read_series`, `bib.frlink.resolve/rule_kind`, `pfs.descriptors.rule_year_of`, Task 3.
|
||||
- Produces:
|
||||
- `pfs.cite`: `@dataclass(frozen=True) Cite(kind: str, label: str, url: str, item_key: str = "", p_id: int = 0, page: int = 0, locator: str = "")`; kinds `fr_para`, `fr_page`, `comment`, `cms_file`, `cpt_book`, `iom`, `cfr`, `mln`, `statute`, `study`, `rvu_file`, `dataset`. Builders: `rule_label(title, date_published, p_id, *, vol="", page=0, kind="") -> str` (moved verbatim); `fr_para_cite(store, item_key, p_id) -> Cite` (url via `frlink.resolve(f"p-{p_id}", store=store, item_key=item_key).url`, `""` on failure); `fr_page_cite(store, item_key, page, *, table="") -> Cite` (label `"CY2008 PFS final 72 FR 66361 Table 14"`); `comment_cite(comment_id) -> Cite` (label `"Comment <id>"`, url `https://www.regulations.gov/comment/<id>`); `rvu_cite(year, *, proposed=False) -> Cite` (label `"PFS CY<year> RVU file"`); `book_cite(item_key, edition_label, page_label) -> Cite` (label `"<edition> p. <page>"`); `dataset_cite(item_key, label, url) -> Cite`; `guidance_cite(row: GuidanceRow) -> Cite`; `ssa_section_url(reference: str) -> str` (`section 18NN…of the Act` → `https://www.ssa.gov/OP_Home/ssact/title18/18NN.htm`, else `""`).
|
||||
- `pfs.citecheck`: `split_sentences(text) -> list[str]` (does not split on `U.S.`, `e.g.`, `i.e.`, `No.`, `¶`, decimals); `number_tokens(text) -> set[str]` — bracketed segments removed first; tokens normalized: `$`/`,`/leading `+` dropped, `−`/`–` → `-`, trailing decimal zeros dropped (`1.00`→`1`, `3.60`→`3.6`), `%` and ordinal suffixes kept; `@dataclass(frozen=True) Problem(sentence: str, kind: str, detail: str)` with `kind ∈ ("uncited","unknown_fact","number_mismatch")`; `check_prose(prose: str, facts: Mapping[str, Fact]) -> list[Problem]` — every sentence needs ≥ 1 `[F<n>]` tag; every tag must exist; `number_tokens(sentence) ⊆ ⋃ number_tokens(fact.text) ∪ normalized(fact.values)` over the sentence's cited facts.
|
||||
- `pfs.dossier`: `@dataclass(frozen=True) Fact(id: str, kind: str, year: int | None, codes: tuple[str, ...], text: str, values: Mapping[str, float | str], cite: Cite)`; kinds `origin`, `formation`, `event`, `round`, `pe`, `cms_summary`, `stance_split`, `link`, `payment`, `impact`, `money`, `seat`, `finding`.
|
||||
- Fixed template copy (binding; `{}` filled from the row):
|
||||
- round, final rule with both values: `"For CY{Y}, the RUC recommended a work RVU of {ruc} for {code} and CMS finalized {final} ({decision})."`
|
||||
- round, proposed only: `"For CY{Y}, CMS proposed a work RVU of {proposed} for {code}."`
|
||||
- cms_summary: `"CMS reported that {q} commenters {stance_phrase} (CY{Y} {kind} rule)."` with `q`: majority→`a majority of`, many→`many`, several→`several`, some→`some`, few→`a few`, one→`one`, all→`all`, unspecified→`` (collapse the double space); stance_phrase: support→`supported the proposal`, modify→`asked for changes`, oppose→`opposed the proposal`, mixed→`were divided`, unclear→`commented`.
|
||||
- stance_split: `"Of {n} CY{Y} commenters we classified on {event_text}, {s} supported, {m} asked for modifications, {o} opposed and {u} were unclear."`
|
||||
- event deleted/cpt_panel/disappeared: `"{code} was deleted for CY{Y}."`; link: `"From CY{Y}, {target} can be reported with this family ({kind})."`
|
||||
- `TimelineEvent(year: int, kind: str, codes: tuple[str, ...], what_changed: str, fact_ids: tuple[str, ...], stance_fact_ids: tuple[str, ...], cms_summary_fact_ids: tuple[str, ...])`; `Excerpt(text: str, cite: Cite)`; `Dossier(family, name, codes, status, years_active, summary, timeline, rounds, payment, utilization, stakeholders, governance, sources, gaps, facts: dict[str, Fact], built_at, check_passed, extractor)` with `to_json() -> str` / `Dossier.from_json(s) -> Dossier`.
|
||||
- `collect_facts(con, store, family: CuratedFamily) -> list[Fact]` — ids `F1…` in order (year, kind order, code); every fact has a `Cite` with a `url` or a `locator`.
|
||||
- `coverage(con, store, family: CuratedFamily) -> list[str]` — computed, never constant: `"Federal Register PFS rules before CY{y} not yet captured."` (earliest PFS rule year in `fr_anchors`); `"RVU files before {y} not yet loaded."` (min `pfs.rvu` year); `"Public comment dockets before the CY{y} rule not yet captured."` (earliest PFS docket with comment chunks); `"No conversion factor on file for {years}; payment not computed."` (`skipped_years`); `"RUC/CPT Panel seat data not captured."` (empty seats); `"Governance literature not yet ingested."` (no `source:governance-lit` items); `"Specialty impact rows not matched to a specialty: {names}."`.
|
||||
- `governance_excerpts(cfg, pool, store, family_name: str, *, k: int = 6) -> list[Excerpt]` — item keys tagged `source:governance-lit`; `llm.search.search(q, cfg=cfg, pool=pool, collection="corpus", item_keys=keys, limit=3)` for queries `[f"{family_name} valuation", "RUC recommendations accepted by CMS", "RUC survey data and time estimates", "specialty representation on the RUC and prices", "international physician fee setting governance"]`; excerpt ≤ 300 characters; cite kind `study` with page when the chunk has one.
|
||||
- `write_prose(facts: Sequence[Fact], events: Sequence[TimelineEvent], ask: JsonExtractor | None) -> tuple[str, dict[int, str], str, bool]` — model drafts the summary (≤ 5 sentences) and one line per event with `[F#]` tags; `check_prose` each; one retry with the problems listed; still failing (or `ask=None`) → template text (`template_summary`, `template_event_line`), returning `(summary, lines_by_event_index, extractor, check_passed=True)`; anything unchecked is never returned.
|
||||
- `build_dossier(con, store, family: CuratedFamily, *, ask=None, excerpts: Sequence[Excerpt] = ()) -> Dossier`.
|
||||
- `pfs.dossier` table `(family VARCHAR, built_at TIMESTAMP, version INTEGER, json VARCHAR, check_passed BOOLEAN, extractor VARCHAR)`; `write_dossier(con, d: Dossier)` (delete-then-insert per family), `read_dossier(con, family) -> Dossier | None`, `dossier_families(con) -> tuple[str, ...]` (missing table → `()`).
|
||||
- CLI `stack pfs dossier (--family KEY | --all) [--no-llm] [--write]` — builds (prose ledger `ledger_path("prose", KEY)`), prints fact count, gaps and the check result, writes on `--write`.
|
||||
|
||||
- [ ] **Step 1: Failing tests**
|
||||
|
||||
```python
|
||||
# tests/pfs/test_citecheck.py
|
||||
F = {"F1": fact("For CY2023, the RUC recommended a work RVU of 1.00 for 99341 and CMS finalized 1.00 (accept).", {"final": 1.0}),
|
||||
"F2": fact("For CY2023, the RUC recommended a work RVU of 1.65 for 99342 and CMS finalized 1.65 (accept).", {"final": 1.65})}
|
||||
def test_uncited_sentence_rejected(): assert check_prose("CMS accepted the RUC values.", F)[0].kind == "uncited"
|
||||
def test_number_from_uncited_fact_rejected(): assert check_prose("99341 was finalized at 1.65 [F1].", F)[0].kind == "number_mismatch"
|
||||
def test_equivalent_number_formats_accepted(): assert check_prose("In CY2023 99341 was set at 1.0 work RVUs [F1].", F) == []
|
||||
def test_unknown_fact_rejected(): ...
|
||||
def test_abbreviations_do_not_split(): ... # "The U.S. statute … [F1]." is one sentence
|
||||
def test_money_and_percent_normalized(): ... # "$131.17" ≡ 131.17; "−16.5%" ≡ "-16.5%"
|
||||
# tests/pfs/test_dossier.py
|
||||
def test_every_fact_has_cite_url_or_locator(home_fixture): ...
|
||||
def test_prose_rejected_twice_falls_back_to_templates(home_fixture): ... # fake ask returns uncited prose → extractor "template", check_passed True
|
||||
def test_cms_summary_and_stance_split_are_separate_facts(home_fixture): ...
|
||||
def test_coverage_notes_from_data(home_fixture): ... # earliest rule CY2002 → "Federal Register PFS rules before CY2002 not yet captured."
|
||||
def test_dossier_json_has_no_person_names(home_fixture): ... # bib comment titles "Jane Doe: CMS-2022-0113-0001" → "Doe" not in to_json()
|
||||
def test_json_roundtrip(home_fixture): ...
|
||||
def test_round_template_copy(): ... # exact template strings above
|
||||
# tests/pfs/test_cite.py — labels/urls per builder; ssa_section_url("section 1834(m) of the Act")
|
||||
# tests/llm/test_search.py — item_keys → {"item_key": {"$in": [...]}} pushed into the store filter
|
||||
```
|
||||
|
||||
Before writing these tests, export the two fixture files once: `ENV python -c` selecting the listed `fr_anchors` rows (joined to `items` for title/date) into `home_visits_fr.jsonl` and the 20 codes' `pfs.rvu` base rows from the replica into `home_visits_rvu.csv`. `home_fixture` (pytest fixture in `tests/pfs/home_visits_fixture.py`, imported by `tests/pfs/conftest.py` or directly) returns `(con, store, family, ask)`: a `:memory:` DuckDB with `ensure_tables`, `pfs.rvu` from the CSV, rows for every table of Tasks 2–11 produced by running those tasks' functions over the fixture (fake `JsonExtractor` with canned replies keyed by unit id), plus three bib comment items titled `"Jane Doe: CMS-2022-0113-0001"`-style; a `Store(":memory:")` with the paragraphs; `load_curated()["HOME-VISITS"]`; and the fake extractor.
|
||||
|
||||
- [ ] **Step 2: Run** `tests/pfs/test_citecheck.py tests/pfs/test_cite.py tests/pfs/test_dossier.py tests/llm/test_search.py tests/llm/test_lineage.py` → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Live** — `ENV stack pfs dossier --family HOME-VISITS --no-llm` (report fact counts by kind, gaps, timeline years), then the prose run on the GPU: `ENV stack pfs dossier --family HOME-VISITS --write` (one model call per event + summary, resumable). Report the extractor (`model:…` or `template`) and any events that fell back to templates.
|
||||
- [ ] **Step 6: Commit** `git add src/pfs/cite.py src/pfs/citecheck.py src/pfs/dossier.py src/llm/lineage.py src/llm/search.py src/pfs/codetables.py src/cli/pfs.py tests/pfs/test_cite.py tests/pfs/test_citecheck.py tests/pfs/test_dossier.py tests/pfs/home_visits_fixture.py tests/pfs/fixtures/home_visits_fr.jsonl tests/pfs/fixtures/home_visits_rvu.csv tests/llm/test_search.py tests/cli/test_pfs_cli.py && git commit -m "feat(pfs): dossier assembly — cited facts, computed gaps, model prose behind a sentence-level citation check"`
|
||||
|
||||
---
|
||||
|
||||
### Task 14: The dossier page in the llm service
|
||||
|
||||
**Files:**
|
||||
- Create: `src/llm/web/family.html`
|
||||
- Modify: `src/llm/api.py`
|
||||
- Test: `tests/llm/test_api.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `read_dossier`, `dossier_families` (Task 13), `llm.evidence._connect/_replica_path`, `normalize_key`.
|
||||
- Produces:
|
||||
- `GET /families` → `{"families": [{"family", "name", "built_at"}]}`; `GET /family/{key:path}` → the stored dossier JSON (key through `normalize_key`, must match `^[A-Z0-9][A-Z0-9@/_.-]{0,120}$`, else 404); 404 when no row or no table; `GET /ui/family/` and `GET /ui/family/{key:path}` → `family.html`.
|
||||
- `family.html` (framework-free, theme tokens copied from `search.html` `:root`, light/dark): fetches `/family/<key>`; sections in this order with these ids: `#header` (name, key, codes, status, years active, built at), `#summary` (prose; `[F#]` rendered as superscript links to the fact's cite url), `#gaps`, `#timeline` (year, what changed, source link, `.stance-split` "our classification: …" and, separately, `.cms-summary` "CMS reported: …"), `#valuation` (per code per round: RUC rec, percentile, proposed, final, decision, rationale link), `#payment` (code × year; proposed rows `tr.proposed`; years after a code's last year show "deleted" once, then nothing; services column from utilization), `#stakeholders` (org type × specialty: commenters, stance split, expected stance with reason, money Δ, billing share, seats; organizations listed only for organization types), `#governance` (excerpts with cites), `#sources` (every cite grouped by kind). `/ui/family/` lists `/families`.
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `test_family_json_404_without_table`, `test_family_json_serves_row` (temp replica with a `pfs.dossier` row; patch `llm.evidence._replica_path`), `test_family_key_with_slash_routes`, `test_bad_key_404`, `test_families_lists_rows`, `test_family_page_markers` (served HTML contains `fetch('/family/'`, `id="timeline"`, `id="payment"`, `id="gaps"`, `class="cms-summary"`, `class="stance-split"`, `tr.proposed`).
|
||||
- [ ] **Step 2: Run** `tests/llm/test_api.py` → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** → PASS; ruff.
|
||||
- [ ] **Step 5: Headless check** — DOM-stub or playwright probe per `dev/scripts/nb_fe_smoke.py --url http://llm:8000/ui/family/HOME-VISITS --network gateway` after the roll in Task 16; now: `uv run --no-sync python -c` with FastAPI `TestClient` against the live replica path, print the section ids found.
|
||||
- [ ] **Step 6: Commit** `git add src/llm/api.py src/llm/web/family.html tests/llm/test_api.py && git commit -m "feat(llm): family dossier page — /ui/family/<key> and /family/<key> JSON"`
|
||||
|
||||
---
|
||||
|
||||
### Task 15: Chat — dossier evidence, uncapped payment table, link to the page
|
||||
|
||||
**Files:**
|
||||
- Create: `src/llm/dossier.py`
|
||||
- Modify: `src/llm/rag.py` (`_stream_answer`, `build_messages`, `_SYSTEM`), `src/llm/evidence.py` (`valuation_evidence`), `src/llm/config.py` + `stack.toml` (`dossier_max_rows = 30`), `src/llm/web/chat.html`
|
||||
- Test: `tests/llm/test_dossier.py`, `tests/llm/test_rag.py`, `tests/llm/test_evidence.py`, `tests/llm/test_api.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `read_dossier`, `dossier_families` (Task 13), `valuation(..., years=0, all_proposed=True)` (Task 12), `detect_codes`, `llm.evidence.warm/_connect/_replica_path`.
|
||||
- Produces:
|
||||
- `@dataclass(frozen=True) DossierEvidence(family: str, name: str, url: str, summary: str, facts: tuple[Fact, ...], gaps: tuple[str, ...], max_prompt_rows: int = 30)`; `payload() -> dict` = `{"type": "dossier", "family", "name", "url": "/ui/family/<key>", "summary", "facts": [{"label", "text", "url", "year", "kind"}], "gaps"}` (summary with `[F#]` replaced by the facts' labels); `prompt_block(max_rows: int | None = None) -> str` — header `"Dossier — cited facts about the {name} family (authoritative for its history, valuation rounds and who commented). Each line ends with the label to copy:"`, then `"{fact.text} [{fact.cite.label}]"`, priority `round`, `event`, `cms_summary`, `stance_split`, `link`, `origin`, `money`, `impact`, `seat`, `finding`, capped.
|
||||
- `dossier_evidence(question: str, cfg) -> DossierEvidence | None` — first detected family (curated before derived) with a `pfs.dossier` row; never raises (log + `None`).
|
||||
- `_stream_answer` order: `dossier? → lineage? → valuation? → token* → sources → done`; `sources` gains a first entry `{"kind": "dossier", "label": "Dossier: <name>", "url": "/ui/family/<key>"}` when a dossier was used; `build_messages(question, sources, evidence=None, lineage=None, dossier=None, …)` puts the dossier block before the lineage block and trims it like the lineage block (floor 8 rows); `_SYSTEM` gains: the Dossier block is authoritative; cite its labels; always attribute "CMS reported …" separately from the dossier's own classified counts.
|
||||
- `valuation_evidence`: when `det.families ∩ dossier_families(cur)` is non-empty → `valuation(cur, codes, years=0, all_proposed=True)` (payload carries every row; the prompt block keeps `cfg.valuation_rows_max`); otherwise unchanged.
|
||||
- `chat.html`: `renderDossier(wrap, ev)` card (name, summary with linked labels, gaps line, "Open the full dossier" → `ev.url`); dispatch `ev.type === 'dossier'` first; `collectLinks` takes dossier fact labels; the valuation table marks `tr.proposed` and groups rows per code in `<details>` when `rows.length > 40`.
|
||||
|
||||
- [ ] **Step 1: Failing tests** — `test_dossier_evidence_for_home_visit_question` (temp replica with the fixture dossier; "how were home visits valued?" → family `HOME-VISITS`, url `/ui/family/HOME-VISITS`), `test_none_without_dossier_row`, `test_dossier_payload_has_no_person_names`, `test_prompt_block_lines_end_with_labels`; rag: `test_event_order_with_dossier`, `test_control_question_byte_identical` (no dossier family → events identical to the run with `dossier_evidence` patched to `None`), `test_sources_first_entry_is_dossier`; evidence: `test_valuation_uncapped_for_dossier_family` (13+2 rows for 99341 in payload, prompt rows ≤ `valuation_rows_max`), `test_valuation_unchanged_for_other_families`; api: chat.html markers `function renderDossier`, `ev.type === 'dossier'`, `tr.proposed`.
|
||||
- [ ] **Step 2: Run** `tests/llm` → FAIL.
|
||||
- [ ] **Step 3: Implement.**
|
||||
- [ ] **Step 4: Run** `uv run --no-sync pytest -q -p no:cacheprovider -n auto tests/llm tests/pfs` → PASS; ruff.
|
||||
- [ ] **Step 5: Live (in-process)** — `ENV python -c "from llm import config; from llm.dossier import dossier_evidence; e=dossier_evidence('How have home visits been valued since 2008?', config.load()); print(e.family, len(e.facts), e.prompt_block()[:600])"`.
|
||||
- [ ] **Step 6: Commit** `git add src/llm/dossier.py src/llm/rag.py src/llm/evidence.py src/llm/config.py stack.toml src/llm/web/chat.html tests/llm/test_dossier.py tests/llm/test_rag.py tests/llm/test_evidence.py tests/llm/test_api.py && git commit -m "feat(llm): chat answers from the family dossier — dossier event, full payment history, link to the page"`
|
||||
|
||||
---
|
||||
|
||||
### Task 16: Home-visit golden test, acceptance, docs, roll-out
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/pfs/test_dossier_golden.py`
|
||||
- Modify: `tests/llm/golden_lineage.yaml` (entry `home-visits-history`), `dev/scripts/llm_golden.py` (`check_dossier`), `tests/llm/test_golden.py`, `docs/docs/cli/*` (regenerated)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: everything above.
|
||||
- Produces: `check_dossier(transcript, expect: dict) -> CheckResult` (passes when a `dossier` event with `family == expect["family"]` arrived and a source with `kind == "dossier"` is present); YAML key `expect_dossier: {family}`.
|
||||
|
||||
- [ ] **Step 1: Write the golden test** (uses `home_fixture` from Task 13)
|
||||
|
||||
```python
|
||||
def test_home_visit_dossier_golden(home_fixture): # no network, canned extractor replies
|
||||
d = build_dossier(*home_fixture[:3], ask=home_fixture[3])
|
||||
r = {(x.code, x.item_key): x for x in d.rounds}
|
||||
hv = r["99341", "PETM225D"]
|
||||
assert (hv.rule_year, hv.proposed_work_rvu, hv.final_work_rvu, hv.ruc_percentile, hv.decision) == (2023, 1.0, 1.0, "25th", "accept")
|
||||
assert (r["99350", "PETM225D"].final_work_rvu, r["99350", "PETM225D"].ruc_percentile) == (3.6, "median")
|
||||
old = r["99343", "54GTKR5G"]
|
||||
assert (old.rule_year, old.source, old.ruc_work_rvu, old.final_work_rvu, old.decision, old.page) == (2008, "fr-table", 2.27, 2.53, "refine", 66361)
|
||||
cms = [f for f in d.facts.values() if f.kind == "cms_summary"]
|
||||
assert any(f.cite.p_id == 1679 and "a majority of commenters supported" in f.text for f in cms)
|
||||
assert any(f.cite.p_id == 1681 and "a few commenters" in f.text for f in cms)
|
||||
assert any(f.kind == "event" and "99343 was deleted for CY2023." == f.text and f.cite.p_id == 1672 for f in d.facts.values())
|
||||
assert {(f.kind, f.cite.item_key, f.cite.p_id) for f in d.facts.values()} >= {
|
||||
("link", "JCWARTJD", 1168), ("link", "JCWARTJD", 1205), ("link", "NHRGIHGD", 1469), ("link", "PETM225D", 1686)}
|
||||
assert {(p.code, p.year) for p in d.payment if p.code == "99343"} == {("99343", y) for y in range(2015, 2023)}
|
||||
assert check_prose(d.summary, d.facts) == [] and d.check_passed
|
||||
assert any(g.startswith("Federal Register PFS rules before CY") for g in d.gaps)
|
||||
|
||||
@pytest.mark.skipif(not REPLICA.exists(), reason="live replica")
|
||||
def test_home_visit_dossier_live(): # same assertions against read_dossier(replica, "HOME-VISITS"),
|
||||
... # plus every fact has a non-empty cite.url or locator
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run** `tests/pfs/test_dossier_golden.py` → PASS expected (all producing code exists); a failure is fixed in the owning task's module, never by loosening the test.
|
||||
- [ ] **Step 3: Chat golden** — add `home-visits-history` to `tests/llm/golden_lineage.yaml`: question "What is the history of home visit coding and payment, and how did commenters react to the 2023 revaluation?", `mode: timeline`, `expect_anchors` `PETM225D` ¶1676 and ¶1679, `expect_events` `{code: "99343", kind: "deleted|cpt_panel|disappeared", year: 2023}`, `expect_dossier: {family: HOME-VISITS}`; implement `check_dossier` with tests (pass/fail transcripts).
|
||||
- [ ] **Step 4: Run** full suites in two passes (memory guard): `uv run --no-sync pytest -q -p no:cacheprovider -n 6 tests --ignore=tests/notebooks` then `… tests/notebooks`; ruff on all touched paths.
|
||||
- [ ] **Step 5: Live runbook (resumable; rerun any line to resume)**
|
||||
|
||||
```
|
||||
ENV stack pfs families --write
|
||||
ENV stack pfs guidance --family HOME-VISITS --write
|
||||
ENV stack pfs lineage --all-seen --write
|
||||
ENV stack pfs rounds --family HOME-VISITS --write # GPU
|
||||
ENV stack pfs origin --family HOME-VISITS --write # GPU
|
||||
ENV stack pfs cms-summaries --family HOME-VISITS --write # GPU (light)
|
||||
ENV stack pfs commenters --family HOME-VISITS --docket <D> --write # GPU, per docket
|
||||
ENV stack pfs stance --family HOME-VISITS --docket <D> --write # GPU, per docket
|
||||
ENV stack pfs psps --family HOME-VISITS --write
|
||||
ENV stack pfs impacts --scan --write
|
||||
ENV stack pfs seats --body RUC --url <url> --from 2005 --to 2026 --write
|
||||
ENV stack pfs dossier --family HOME-VISITS --write # GPU (prose)
|
||||
```
|
||||
|
||||
Then `ENV pytest -q -p no:cacheprovider tests/pfs/test_dossier_golden.py::test_home_visit_dossier_live`.
|
||||
- [ ] **Step 6: Docs, push, roll** — `uv run --no-sync python docs/scripts/extract_cli.py`; commit every changed `docs/docs/cli/*` page; `git push gitea main`. Roll per the deploy procedure from `/home/kert/stack`: `sed -i 's/^COMMIT_SHA=.*/COMMIT_SHA=<sha7>/' .env`; `docker compose build api llm bcda docs mc`; `docker compose up -d --no-build --pull never --no-deps api mail-poller llm docs bcda lead mc`. Verify inside the container: `docker exec -i llm sh -c 'cd /app && uv run --no-sync python -'` fetching `/family/HOME-VISITS` (200, JSON with `facts`) and streaming the golden question (first event `dossier`); `dev/scripts/nb_fe_smoke.py --url http://llm:8000/ui/family/HOME-VISITS --network gateway` clean; then `uv run --no-sync python dev/scripts/llm_golden.py run --url http://llm:8000 --set tests/llm/golden_lineage.yaml --only home-visits-history --report .state/dossier/golden.json` (no `--file-issues`).
|
||||
- [ ] **Step 7: Human acceptance (the spec's acceptance test)** — ask the user to read `/ui/family/HOME-VISITS` against the FR text and comments (every fact links to its paragraph or comment). Record each correction as an issue; a correction to membership edits `curated.yaml`, any other correction fixes the owning extractor and re-runs its runbook line — never a hand edit of a stored row.
|
||||
- [ ] **Step 8: Commit** `git add tests/pfs/test_dossier_golden.py tests/llm/golden_lineage.yaml tests/llm/test_golden.py dev/scripts/llm_golden.py docs/docs/cli && git commit -m "test(pfs,llm): home-visit dossier golden (fixture + live) and chat golden entry; CLI docs"`
|
||||
|
||||
---
|
||||
|
||||
## Self-review
|
||||
|
||||
**Spec coverage.** Origin → T6 (+ statute links via `ssa_section_url`, T13). Formation (Panel action, first PFS year) → T2 (`cpt_panel`, `appeared`), T6 (book), T13 (`formation` facts). Valuation (RUC rec, percentile, time, comparators, CMS decision + rationale, PE inputs) → T4/T5 (`pe_note`). Every change since (revaluation, descriptor, misvalued, telehealth, bundling, deletion, replacement) → T2 + existing lineage. Payment over all time, proposed vs final, with utilization → T12, T13 (`payment`, `utilization`), T14/T15. Comment stance per event + evidence + reasons → T9; CMS summaries kept separate → T7, T13, T14. Commenter identity incl. form letters → T8. Money (impact tables, payment × utilization by specialty, proposed-vs-final deltas) → T10 (+ T12 proposed rows). Power (seats, sponsorship via `surveying_societies` in T5, billing share) → T5, T10, T11. Expected vs actual stance → T11 + T13/T14. Governance literature in the dossier → T13 `governance_excerpts` (content arrives with the backfills plan). Curated registry, deleted-code lineage → T1, T2. Citation check → T13. Page → T14. Chat incl. uncapped payment table and link → T15. Golden/acceptance → T16. Gap notes computed so backfills shrink them → T13 `coverage`.
|
||||
|
||||
**Not in this plan (by scope):** the rest of primary care and phases 2–3 (one curated entry + one runbook pass per family once this ships); G2211's own misgrouped family (fixed when office E/M joins the registry); nightly dossier refresh (on demand only here — add `stack pfs dossier --all --no-llm --write` to the Comment Pull workflow after the fan-out); a fitted stance model (spec defers it).
|
||||
|
||||
**Type consistency.** `RoundRow` (T4) is read by T9 `docket_events`, T13 facts; `CommenterRow` (T8) → T11 `stakeholder_units`; `StanceRow` (T9) → T11, T13; `SpecialtyMoney` (T10) → T11, T13; `Fact`/`Cite` (T13) → T14 JSON and T15 `DossierEvidence`; `valuation(years=0, all_proposed=True)` (T12) → T13 payment and T15 evidence; `dossier_families` (T13) → T14, T15; `JsonExtractor`/`RunLog`/`run_units`/`ledger_path` (T3) → T5, T6, T8, T9, T11, T13.
|
||||
Reference in New Issue
Block a user