diff --git a/docs/superpowers/plans/2026-11-13-drug-product-tier.md b/docs/superpowers/plans/2026-11-13-drug-product-tier.md new file mode 100644 index 0000000..af6fa69 --- /dev/null +++ b/docs/superpowers/plans/2026-11-13-drug-product-tier.md @@ -0,0 +1,935 @@ +# Products, drugs and diseases tier 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:** Build a cited product registry (HCPCS ↔ NDC ↔ labeler ↔ application holder ↔ `market.entity`) with an all-code quarterly ASP series, drug/product and ICD-10 code lineage, product → disease links (MCD articles), product → procedure links (curated, plus Netter anatomy), Table of Drugs facts, and the market tier's `asp` link basis, price admission and product event windows, ending in the CY2026 skin-substitute flat-rate event study (Organogenesis, MiMedx, Smith & Nephew). + +**Architecture:** +- A new `drugs` package (DuckDB schema `drugs`) with one module per source, built like the market tier: + - an honest-UA fetch through `market.http` (client, pacer, `get`, `Refused`, `save`); + - a hoarded raw cache (`data/cms/asp/…` for the existing ASP hoard, `data/drugs/…` for everything new); + - pure parsers; + - frozen row dataclasses plus writers and readers in `drugs/tables.py`; + - a bib citation per source file and a `cms.ingest_log` row per table write; + - a `gap:` line, plus a `market.source_gap` row, when a source refuses or a file is missing. +- One `stack drugs` CLI group (`src/cli/drugs.py`) fetches first and then writes in one short `duckdb_batch`. +- The market tier is touched in only two places, both in the market lane: `market/tiingo.py` (`universe()` admits `asp` entities) and `market/events.py`, `market/portfolio.py`, `cli/market.py` (product events, `--product`). +- `dev/scripts/ingest_asp.py` becomes a thin consumer of `drugs.asp`. The `skin_subs.*` tables and notebooks are unchanged. + +**Tech Stack:** Python 3.13, uv, httpx, DuckDB (`data/aco.duckdb` via `conf.connect.duckdb_batch("aco")`, replica `data/replica/aco.ro.duckdb`), bib SQLite, stdlib `csv`/`zipfile`/`html.parser`, `xlrd` (core dependency, imported inside functions), `pymupdf` (core dependency, imported inside functions), PyYAML, typer, pytest with xdist, and the local Ollama pool for the one optional labeler suggestion. + +**Spec:** `docs/superpowers/specs/2026-11-12-cms-legal-epi-platform-design.md`, section "Products, drugs and diseases (user, 2026-11-13)" (commit cb59a65), read with "Market and enrichment tier", Constraints and Anti-goals. +- Market plan: `docs/superpowers/plans/2026-11-12-market-tier.md` (Tasks 1–3 done, Task 4 running at this writing, Tasks 5–15 pending). +- Market rulings M1–M18, D1–D5, H1–H2: `.superpowers/sdd/2026-11-12-market-tier/progress.md`. M12 (verbatim quotes), M13 (link windows, AMA guard on quotes), M16–M18 (fts gate) bind this plan wherever it writes `market.*` rows. + +## Global Constraints + +**Repository and commits** +- Commit straight to `main` in `/home/kert/stack`. No branches, worktrees, merge commits, PRs or `git stash`. +- Before every commit, run `git status --short`. If anything you did not stage is staged, stop and ask: Plan A, the lex slice and the market tier share this checkout. `git add` explicit file paths only, never a directory. +- Commit messages take a conventional prefix (`feat(drugs): …`, `feat(market): …`) and no `Co-Authored-By` or any other trailer. +- **Two lanes.** + - The **drug lane** (D1–D12) touches only `src/drugs/*`, `src/cli/drugs.py`, `tests/drugs/*`, `tests/cli/test_drugs_cli.py`, `tests/dev/test_ingest_asp_parity.py`, `dev/scripts/ingest_asp.py`, and `src/cli/__init__.py` (one complete edit, in D1). It runs alongside market Tasks 4–15. Drug-lane tasks run one at a time, in order. + - The **market lane** (D13, D14) edits market files. Each runs alone, between two market tasks, never while a market task is mid-flight (H1). +- No drug-tier task edits `src/pfs/*` or `src/cli/pfs.py`; drug code only imports `pfs.*`. +- Keep the tree importable at every save, and commit right after the scoped tests pass. If the pre-commit hook fails only on another session's uncommitted work, rerun after it commits. Never use `--no-verify`. + +**Running live commands** +- Never run a write or 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 '`, written **ENV** below. +- Before the first live run, `cat .venv/lib/python3*/site-packages/stack.pth` must print `/home/kert/stack/src`; otherwise run `uv sync --frozen`. +- Long runs: `mkdir -p .state/drugs` once, then `setsid nohup ENV … > .state/drugs/.log 2>&1 &` with a Monitor on the log. Rerunning the same command resumes from the hoard. + +**Database and tables** +- Write `data/aco.duckdb` only inside `conf.connect.duckdb_batch("aco")`, opened after all network work, then call `conf.connect.publish_replica("aco")`. +- `drugs.*` modules never open a database at import, and never import numpy or pandas at module level (`tests/drugs/test_imports.py` probes this, as M1 does for market). +- Every `drugs.*` table has its DDL in `drugs.tables._DDL`, a frozen row dataclass, a writer and a reader in `src/drugs/tables.py`, and a case in `tests/drugs/test_tables.py::ROUNDTRIP`. +- Writes to `market.*` tables go only through `market.tables` writers (`write_links`, `retire_links`, `write_entities`, `write_securities`, `write_gap`, `clear_gap`). + +**User-Agent and refusals** +- Every request sends `stack-pfs-dossier/1.0 (ci@mail.fhirworx.io)` (`market.http.USER_AGENT`), never a browser UA. +- A 401/403, an exhausted 429 or a bot/challenge page stops that source and becomes a gap. Never work around it. +- The CMS AMA click-through (`/apps/ama/license.asp?file=`) is a licence page, not a refusal. Its Accept form's action is ``, so fetching `https://www.cms.gov` accepts the CPT end-user licence (internal use). The tier honours it by never storing CPT descriptors (see below). +- No keys are needed. Every source here is keyless. Any future key is registered to ci@mail.fhirworx.io and lives only in `.env`. + +**Gaps** +- A gap's `source` is `:`: `cms-asp:asp`, `cms-asp:xwalk`, `fda-ndc:fda`, `fda-orange:fda`, `fda-purple:fda`, `sec-edgar:registry`, `pfs:links`, `cms-hcpcs:hcpcs`, `cdc-icd:icd`, `cms-icd:icd`, `cms-mcd:mcd`, `zotero:books`, `fr:drug-events`. +- Gaps live in `market.source_gap`, so `stack market gaps` lists both tiers. Every successful `--write` calls `clear_gap(con, source)` in the same batch. +- A missing file, quarter or edition is a gap, never a zero. + +**Hoard** +- Never overwrite a source file. A re-download with different bytes lands beside the old one as `.` (`market.http.save`). +- Readers use the newest copy (`market.http.newest`). One file per (quarter, kind) is read, never two. +- Every hoarded file gets one line in `data/drugs/MANIFEST.jsonl` (url, path relative to `data/`, sha256, bytes, fetched_at). +- Source files are never bib attachments (bib syncs to Zotero). Each file gets a bib `Source` item (url, title, tags `module:drugs`, `source:`, `table:`), and rows carry its `item_key`. + +**Licensed text (the AMA rule applies to every licensed publisher)** +- CPT (Level I) short and long descriptors are never stored in any `drugs.*` table. This covers ASP payment files, crosswalks, MCD article code tables and the codebooks. A Level I row stores `""`. The same holds for CDT (`D` codes). +- HCPCS Level II, ICD-10-CM and ICD-10-PCS titles are public and may be stored. +- Book facts are structured values (codes, units, routes, drug names, anatomy terms, page numbers). Any stored string taken from a book has fewer than 8 words and passes `market.edgar.shares_ama_run` against the CPT descriptor index. A string that fails is dropped (`""`), never trimmed. This tier writes no paraphrases. +- Licensed book text is never in the repo, a fixture, a commit message, an issue or the chat corpus. Imported books carry `llm:skip`. Fixtures are synthetic. +- No test or fixture contains CPT descriptor text (C1, commit 3a18f63). Level I rows in fixtures carry `x`. +- Book facts cite `(item_key, edition, page)`. + +**Data rules** +- Public data only. No ACO/HarmonyCares/WNOT/Wakely material. `pharmacy.*` is CCLF claims-derived (`data_source = 'medicare cclf'`) and is never read. `skin_subs.claims_synthetic` is synthetic and is never read. +- Local models only, and only in D5's optional `--suggest`: + - Ollama through `cli.market._asker` (the single home, M3); + - resumable through `pfs.runlog`; + - stored as `method="model"` with `label_version`; + - never admitted to prices or links until a curated row confirms it. +- Every derived number states its basis. Payment attribution is an apportionment, not company sales. + +**Tests, coverage and lint** +- Tests need no network, live DuckDB, Ollama, books or data. They use httpx `MockTransport`, `duckdb.connect(":memory:")` with `ensure_tables`, `Store(":memory:")`, monkeypatched `cli.drugs._batch/_read/_store/_publish`, synthetic zips built in the test, and synthetic PDFs built with pymupdf in the test. Live tests skip without the replica or the hoard. +- Gate per drug-lane task: `uv run --no-sync pytest -q -p no:cacheprovider -n auto tests/drugs tests/cli/test_drugs_cli.py --cov=src/drugs --cov=src/cli --cov-report=term-missing`. The `src/drugs/*` and `src/cli/drugs.py` lines must read ≥ 99%; CI runs `--cov=src --cov-fail-under=99`. +- Market-lane tasks also run `tests/market tests/cli/test_market_cli.py` with `--cov=src/market`. +- Lint: `uv run --no-sync ruff format && uv run --no-sync ruff check `. + +## Review Focus + +1. **NDC layouts that never join.** FDA lists 10-digit hyphenated NDCs (4-4-2, 5-3-2, 5-4-1); CMS crosswalks use 11-digit 5-4-2. A naive join silently drops every application holder. Expected: every NDC is normalised to 11 digits before any join, and an unnormalisable NDC is kept raw and counted. Pinned in D1 (`test_ndc11_three_layouts`) and D5 (`test_registry_joins_fda_10digit_to_cms_11digit`). +2. **AMA or ADA text leaking through public CMS files.** ASP payment files, crosswalks and MCD article code tables carry CPT short descriptors next to Level II text. Expected: Level I and CDT rows store `""`, and every book string is under 8 words. Pinned in D2 (`test_cpt_short_description_never_stored`), D3 (`test_xwalk_stores_no_short_descriptor`), D9 (`test_mcd_drops_cpt_descriptions`), D10 (`test_book_strings_under_eight_words`), and the D12 acceptance scan. +3. **Licensed files that are not what their Zotero title says.** + - "ICD-10-CM 2019.pdf" and one "ICD-10-CM 2018" file are ICD-10-PCS 2019. + - "ICD-10-CM 2016" is *2017 Principles of ICD-10-CM*. + - "ICD-10-CM 2023" is *Pediatric ICD-10-CM 2023*. + - The "2017" item holds the 2018 codebook. + + Expected: identity comes from the file's sha256 in `books.yaml`, never the title, and an unknown file is a gap that is never parsed. Pinned in D10 (`test_book_identity_from_sha_not_title`, `test_unknown_book_file_is_gap`). +4. **Medicare money counted twice or given to the wrong company.** + - A code with N labelers gets its whole payment counted N times. + - A repackager's labeler name outranks the application holder. + + Expected: the amounts attributed across a code's labelers sum to the code's total, and the holder resolves first. Pinned in D5 (`test_holder_wins_over_repackager_labeler`) and D6 (`test_attributed_payment_sums_to_code_total`). +5. **Re-posted or missing quarters.** + - CMS posts "Updated" files for a quarter. + - A second hoarded copy (`asp_2026-Q2..zip`) is read beside the first and doubles the skin-substitute rows. + - A quarter missing from the page becomes zero. + - Skin substitutes leaving the ASP files in 2026 read as $0. + + Expected: one file per (quarter, kind), the newest; a missing quarter is a gap; no row means no value. Pinned in D2 (`test_one_zip_per_quarter_newest_wins`, `test_updated_posting_lands_beside`, `test_missing_quarter_is_gap_not_zero`). + +## Decisions + +Each item is a planner's call. Nobody was asked; the tasks implement them. + +**Layout and CLI** +- **A new `drugs` package and a `stack drugs` group, not more `stack market` commands** (planner's call). Why: + - Market Tasks 4–14 all append to `cli/market.py`, `market/tables.py` and their tests, and run one at a time (H1). A separate package lets D1–D12 run in parallel with them. + - The registry, lineage and MCD links serve the dossier and S3's coded variables, not only markets. + - The market tier consumes the tier through `asp` links, `drugs.entity_payment` and product events. +- **Schema `drugs`** holds the registry, the ASP series, lineage for every code system and the MCD links (planner's call). +- **Product → procedure links are curated in `src/drugs/curated.yaml`, not `src/pfs/curated.yaml`** (planner's call; a spec deviation). Plan A edits `src/pfs/*` in this shared tree. The file keeps the curated-YAML form and cites every entry. Its sections are `labelers`, `groups`, `procedures` and `events`. +- **`dev/scripts/ingest_asp.py` imports `drugs.asp`** (the parser is shared, DRY) and keeps its pandas output code. Parity is gated on the 1,974 hoarded skin-substitute rows (planner's call). +- **Gaps share `market.source_gap`** (planner's call). + +**Sources and hoard** +- **ASP files.** + - Links come from a hoarded snapshot of the ASP pricing page. Each anchor's text gives ` ` and the kind: `pricing` (Payment Limit / ASP Pricing), `noc`, `crosswalk`, `vaccine` or `other`. `vaccine` and `other` are listed but not fetched (planner's call). + - Paths: `data/cms/asp/asp_-Q.zip` (the existing names), `data/cms/asp/noc/noc_.zip`, `data/cms/asp/xwalk/xwalk_.zip`. + - `data/cms/asp_source_urls.csv` (tracked, read by skin subs) is not edited. +- **Crosswalk kinds.** All four member files in a crosswalk zip are parsed, with `xw_kind ∈ ("asp", "opps", "awp", "prep")`, so more labelers are seen (planner's call). +- **FDA.** + - The NDC Directory is the current snapshot, plus the excluded file. + - The Orange Book is the current zip. + - The Purple Book is the newest monthly CSV; its second section is the full product list. `--all-months` hoards every month from 2020 on (planner's call). + - FDA has no historical NDC directory. Older labelers come only from CMS crosswalks; this is a stated gap. +- **HCPCS lineage.** + - Every quarterly zip linked on the CMS quarterly-update page (2024-01 … 2027-01), plus `january--alpha-numeric-hcpcs-file.zip` for 2017–2023. The 2023 file is verified; each 404 is a gap. + - The newest file alone already carries add dates for every code and terminations back to 2014. +- **ICD lineage.** + - ICD-10-CM: order files from the CDC FTP, FY2016–FY2027. + - ICD-10-PCS: from CMS, `/files/zip/-icd-10-pcs-order-file-long-and-abbreviated-titles.zip` for FY2021+ and `/Medicare/Coding/ICD10/Downloads/-PCS-Long-Abbrev-Titles.zip` for FY2016–2020 (2016 verified). + - Conversion tables come from CMS. April 1 vintages are read where CMS lists them (planner's call). +- **MCD.** `all_article.zip` (current and retired articles) only. LCDs are not parsed (planner's call). +- **Payment.** The payment share comes from `pfs.utilization` (physician/supplier PUF, 2013–2024, `n_services × avg_allowed` per HCPCS, with an `item_key` per year). It excludes hospital-outpatient billing, which is stated as a caveat (planner's call). + +**Registry** +- **Entity resolution order** (planner's call): + 1. the application holder, then the labeler; + 2. per name: curated > subsidiary (latest 10-K EX-21 of a product-SIC company) > exact `alias_match(prefix=False)` > prefix `alias_match(prefix=True)` among `PRODUCT_SICS` entities only; + 3. ambiguity (two or more entities) leaves the name unresolved, with its candidates listed; + 4. a model suggestion is stored but never used. +- `PRODUCT_SICS = ("2833", "2834", "2835", "2836", "3841", "3842", "3844", "3845", "3851", "5047", "5122")`. +- `norm_labeler(name)` is `market.seed.norm_org(name)` with these tail words then dropped repeatedly: `USA, US, PHARMACEUTICALS, PHARMACEUTICAL, PHARMA, LABORATORIES, LABS, HOLDINGS, PLC, LIMITED, SA, AG, NV, GMBH, LP`. +- **Skin-substitute seed.** + - Each distinct manufacturer string of `data/cms/skin_substitute_hcpcs.csv` (69 strings) gets a `labelers` entry with the CIK of the public company that sells the product, or `private: true`. Every entry is cited (M12: a verbatim quote of 400 characters or fewer from a hoarded filing, or a cited non-filing source marked `strength: weak`). + - The required minimum is `Organogenesis`, `Organogenesis (formerly Advanced BioHealing)` → 0001661181; `MiMedx` → 0001376339; `Smith & Nephew (Osiris)`, `Smith & Nephew (Cook Biotek)` → 0000845982. + - An undated curated link holds for all time, with the caveat "ownership not dated". An acquisition with a cited date sets `valid_from`/`valid_to`. +- **Product groups** (the `product` scope vocabulary): + - `PART-B-DRUGS`: every code in any ASP payment file; + - `SKIN-SUBSTITUTES`: the 286 codes in the CSV; + - `BIOSIMILARS`: Q5101–Q5199, plus codes whose crosswalk NDCs carry a 351(k) BLA; + - `CHEMOTHERAPY`: J9000–J9999. + +**Payment and links** +- **Attribution:** `attributed(entity, year) = Σ_code allowed(code, year) / |labeler entities of code in year|`. Labelers of a year are the resolved entities on the code in that year's crosswalk quarters; curated CSV links count every year inside their window. +- `share = attributed / revenue`, where revenue is the `market.revenue` row whose `period_end` falls in that calendar year (market Task 13). It is `None` until that table exists. +- **`asp` links:** `LinkRow(entity_key, scope="product", target=, basis="asp", strength="sole"|"shared", cite_kind="item_key", cite_ref=, item_key=…, valid_from, valid_to)`. + - `sole` means the entity is the only resolved labeler on at least one of the group's codes in the latest year. + - Every resolved entity also gets the `PART-B-DRUGS` link. +- **Price admission (D13):** `ASP_MIN_PAYMENT = 10_000_000.0` (latest PUF year) or `ASP_MIN_SHARE = 0.01`. + - This is an independent fourth tier after the fts tier, ranked by attributed payment. + - M18 stays as is for fts. + - The 450-symbol cap is shared. + +**Lineage and events** +- **HCPCS** (fixed width, 1-based positions): + - fields: code 1–5, recid 11 (`3` first line, `4` continuation), long description 12–91 (continuations concatenated), short description 92–119, XREF 205–229 (5 × 5), BETOS 257–259, TOS 261, add date 269–276, action effective date 277–284, termination date 285–292, action code 293; + - event kinds: + - `added` (A, or the add date), + - `terminated` (effective = termination date + 1 day), + - `reassigned` (terminated with XREF, `to_codes` = the XREF codes), + - `reactivated` (R), + - `description_changed` (C/B/S, or the long description differs from the previous vintage), + - `payment_changed` (P), + - `type_changed` (T); + - `released` = the `_MMDDYYYY` stamp in the member file name. +- **ICD:** + - FY N takes effect on N−1-10-01, and an April vintage `N-04` on N-04-01. + - Kinds: `added`, `deleted`, `title_changed` (vintage diffs; CM billable codes only, header flag 1), and `converted` (conversion tables: `to_codes` = current, `from_codes` = previous). +- **Product events (D14):** + - Curated rule events copy market Task 10's release logic (FR public-inspection `filed_at`; at or after 16:00 ET moves to the next trading day): + - SKIN-SUBSTITUTES: `2025-13271` (proposed, filed 2025-07-14T16:15-04:00 → day 0 2025-07-15) and `2025-19787` (final, filed 2025-10-31T17:10-04:00 → day 0 2025-11-03); + - BIOSIMILARS: `2015-16875`, `2015-28005` (CY2016) and `2017-14639`, `2017-23953` (CY2018); + - PART-B-DRUGS: `2018-14985`, `2018-24170` (CY2019, WAC + 3%). + - Every rule event cites the bib FR item and the paragraph that states the policy. + - `code-reclass` events: one per (group, HCPCS vintage) in which a group code is added, terminated, reassigned, reactivated, payment-changed or type-changed, dated by the file stamp. PART-B-DRUGS is excluded because it changes every quarter. + - The skin-substitute portfolio is ORGO (0001661181), MDXG (0001376339) and SNN (0000845982). + +**Books** +- `src/drugs/books.yaml` keys each usable file by the first 12 hex digits of its sha256. Files present today, verified on the file's own title page or metadata: + + | sha12 | file is | Zotero item (its title) | use | + |---|---|---|---| + | `5e756f143ebb` | HCPCS Level II 2019, EPUB (calibre, `` anchors) | KSHBH7WT | Table of Drugs | + | `d03fe3ca2055` | HCPCS Level II 2019, PDF | KSHBH7WT | none (the EPUB is used) | + | `1a99cf3af7ae` | Netter's Atlas of Surgical Anatomy for CPT Coding 2015, PDF (bib 4KJEJNS6) | 9EV89ZYX | figures | + | `3d145ac62a9b` | ICD-10-CM 2025, EPUB (`page_N` spans) | P7A5PF6H | page index | + | `cc94362a3282` | ICD-10-CM 2025, PDF | P7A5PF6H | none (the EPUB is used) | + | `79b8282392a2` | ICD-10-CM 2022, EPUB | PJANGR68 | page index | + | `91f9afefd1bb` | ICD-10-CM 2020, EPUB | T8CE2D5G | page index | + | `435b688ac01b` | ICD-10-CM **2018**, PDF | 3CPAJAG4 ("2017"), 4SP8BXG7 ("2018") | page index | + | `8fd34710ae4f` | ICD-10-PCS 2019, PDF | 8TWWHBIF | page index | + | `4246d560ddad` | ICD-10-PCS 2019, PDF ("ITPC.book") | 4SP8BXG7 ("ICD-10-CM 2018"), EYF99HNH ("ICD-10-CM 2019") | none (duplicate edition) | + | `ab440dac9093` | ICD-10-PCS 2022, EPUB (`div.tfoot-para` table ids) | HVHA8D28 | page index | + | `5f0461871764` | Coding with Modifiers, 4th ed. (© 2011), PDF | I7ZC2PSW | page index | + | `48d03d9691a7` | *2017 Principles of ICD-10-CM* (not a codebook) | FVWEWFM9 ("ICD-10-CM 2016") | none | + | `b9d6a8b7c02e` | *Pediatric ICD-10-CM 2023* (another book) | SAD5ZIBZ ("ICD-10-CM 2023") | none | + +- Books reach bib through `stack bib import-zotero … --tag source:ama --tag module:coding --tag llm:skip`, the precedent the CPT books set. Netter is already bib 4KJEJNS6. +- **Netter anatomy** is the ICD-10-PCS body-part vocabulary (`terminology.icd10_pcs_cms_ontology.body_part`, Medical and Surgical section; laterality suffixes `, Right` `, Left` `, Bilateral` stripped), matched as whole phrases in a figure's page text. Only matched vocabulary terms are stored, never figure labels (planner's call). + +--- + +## File map + +| File | Responsibility | +|---|---| +| `src/drugs/http.py` | data root, hoard paths, manifest, pacers, bib `cite_file` | +| `src/drugs/codes.py` | code level (I/II/CDT), `ndc11`, `appl_id`, ranges, quarters, FY dates | +| `src/drugs/tables.py` | DDL (`drugs`), row dataclasses, writers, readers | +| `src/drugs/asp.py` | ASP page links, fetch, payment/not-payable/NOC parse (shared with skin subs) | +| `src/drugs/xwalk.py` | NDC–HCPCS crosswalk parse with header drift | +| `src/drugs/fda.py` | NDC Directory, Orange Book, Purple Book | +| `src/drugs/curated.yaml`, `src/drugs/curated.py` | labelers, groups, procedures, events; loader and validator | +| `src/drugs/registry.py` | name normalisation, EX-21 subsidiaries, resolution, products, groups | +| `src/drugs/payment.py` | per-code allowed, attribution, `asp` links | +| `src/drugs/hcpcs.py`, `src/drugs/icd.py` | lineage events and titles | +| `src/drugs/mcd.py` | article ↔ HCPCS ↔ ICD-10 links | +| `src/drugs/books.yaml`, `src/drugs/books.py` | book identity by sha, bib resolution, guard, Table of Drugs | +| `src/drugs/procedures.py`, `src/drugs/netter.py` | curated and route-rule procedure links; Netter figures | +| `src/drugs/codebook.py` | codebook page index; `show` reader | +| `src/drugs/events.py` | product rule and code-reclass `MarketEvent`s (D14) | +| `src/cli/drugs.py`, `src/cli/__init__.py` (one edit, D1) | `stack drugs …` | +| `dev/scripts/ingest_asp.py` (mod, D2) | skin-substitute consumer of `drugs.asp` | +| `src/market/tiingo.py` (mod, D13) | `asp_qualifies`, fourth universe tier | +| `src/market/events.py`, `src/market/portfolio.py`, `src/cli/market.py` (mod, D14) | `product` scope, `code-reclass` kind, `--product` | + +## Where each task sits relative to the market tier + +| Task | Lane | Runs alongside market Tasks 4–15? | Needs | +|---|---|---|---| +| D1–D4, D7–D10 | drug | yes, any of them (no shared file) | D1 (and D2 before D3) | +| D5 | drug | yes; it writes `market.entity`/`security` rows only through `market.tables` (DB rows, no file edit) | D3, D4 | +| D6 | drug | yes; it writes `asp` links through `market.tables.write_links`/`retire_links`. Share stays `None` until market Task 13 lands; rerun D6's live step after Task 13 | D5 | +| D11 | drug | yes | D4, D5, D10 | +| D12 | drug | yes | D7–D11 | +| **D13** | **market** | no: slot it between two market tasks (any slot after market Task 4 commits); it is the only edit to `market/tiingo.py` | D6 | +| **D14** | **market** | no: slot it after market Task 12 (it extends Task 10's vocabularies and Task 12's `car`), before or after Tasks 13–15 | market Tasks 10–12, D6, D7, D13 | + +--- + +### Task D1: Foundation — package, hoard, code helpers, `stack drugs status` + +**Files:** +- Create: `src/drugs/__init__.py`, `src/drugs/http.py`, `src/drugs/codes.py`, `src/drugs/tables.py`, `src/cli/drugs.py`, `tests/drugs/__init__.py`, `tests/drugs/test_codes.py`, `tests/drugs/test_http.py`, `tests/drugs/test_tables.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. +- Modify: `src/cli/__init__.py`, one complete edit: `from cli.drugs import app as drugs_app` and `app.add_typer(drugs_app, name="drugs", help="Products, drugs and diseases: ASP, NDC registry, code lineage, MCD links.")`. + +**Interfaces:** +- Consumes: `market.http.client`, `Pacer`, `get`, `Refused`, `save`, `newest`, `USER_AGENT`; `market.tables.write_gap`, `clear_gap`, `read_gaps`; `cms.ingest_log.log_ingest`; `bib.item.Source`; `bib.tag.Tag`. +- Produces: + - **`drugs.http`** + - `data_root() -> Path` (`conf.path("db.aco").parent`), `path(*parts) -> Path`. + - `manifest(p: Path, url: str, note: str = "") -> None` appends to `data/drugs/MANIFEST.jsonl`, once per `(path, sha256)`. + - `PACE = {"cms": 1.0, "fda": 1.0, "cdc": 1.0, "mcd": 1.0}` and `pacer(provider) -> market.http.Pacer`. + - `fetch(cl, url, dest: Path, *, provider: str, source: str, refresh=False, note="") -> Path`: + - returns the newest hoarded copy when `dest` exists and not `refresh`; + - otherwise GETs through `market.http.get` and saves through `market.http.save`, which writes beside the old copy on different bytes; + - writes the manifest line. + - `cite_file(store, *, url, title, provider, table) -> str` gives a bib `Source` key, deduplicated by url, with tags `module:drugs`, `source:`, `table:
` and no attachment. + - **`drugs.codes`** + - `level(code) -> str`: `"I"` for `^\d{4}[0-9A-Z]$`; `"II"` for `^[ABCEGHJKLMPQRSTUV]\d{4}$`; `"CDT"` for `^D\d{4}$`; else `""`. + - `licensed(code) -> bool`: true when the level is `"I"` or `"CDT"`. + - `ndc11(raw) -> str | None`: + - 4-4-2 → `"0"+a+b+c`; + - 5-3-2 → `a+"0"+b+c`; + - 5-4-1 → `a+b+"0"+c`; + - 5-4-2, or 11 bare digits, → digits; + - anything else → None. + - `appl_id(kind, number) -> str`: `("N","21436")` → `"NDA021436"`, `("A","90123")` → `"ANDA090123"`, `("BLA","125057")` → `"BLA125057"`; `"NDA021436"` passes through. + - `expand(lo, hi) -> list[str]`: same prefix only, else `[lo]`. + - `quarter(year, month) -> str | None` (`{1:1, 4:2, 7:3, 10:4}`); `quarter_start(q) -> date`, `quarter_end(q) -> date`. + - `fy_effective(vintage: str) -> date`: `"2026"` → 2025-10-01; `"2026-04"` → 2026-04-01. + - **`drugs.tables`**: `ensure_tables(con)` (schema `drugs`); helpers `_insert`, `_select`, `_chunks` as in `market.tables`. Later tasks append tables. + - **`cli.drugs`**: indirections `_batch`, `_read`, `_store`, `_publish`; `_gap(source, note, *, write)` (prints `gap: {source}: {note}`; with `write`, `write_gap` in a batch); `stack drugs status` prints the row count per `drugs.*` table and the gap rows whose source is one of this tier's sources. + +- [ ] **Step 1: Write the failing tests** + - `test_level`: `level("90371") == "I"`, `level("0202U") == "I"`, `level("J9035") == "II"`, `level("Q4101") == "II"`, `level("D0120") == "CDT"`, `level("A1") == ""`; `licensed("D0120") is True`. + - `test_ndc11_three_layouts`: `ndc11("0002-1433-80") == "00002143380"`, `ndc11("50242-040-62") == "50242004062"`, `ndc11("60574-4114-1") == "60574411401"`, `ndc11("13533-0636-01") == "13533063601"`, `ndc11("13533063601") == "13533063601"`, `ndc11("1353306360") is None`, `ndc11("ALT-ID 12") is None`. + - `test_appl_id`: the three cases above, and the pass-through. + - `test_expand`: `expand("J0287","J0289") == ["J0287","J0288","J0289"]`; `expand("J0287","K0289") == ["J0287"]`. + - `test_quarters_and_fy`: `quarter(2026, 10) == "2026-Q4"`, `quarter(2026, 3) is None`, `quarter_end("2026-Q4") == date(2026,12,31)`, `fy_effective("2026") == date(2025,10,1)`, `fy_effective("2026-04") == date(2026,4,1)`. + - `test_fetch_hoards_and_reuses`: MockTransport counts requests. The first call writes `dest` and one manifest line; the second call makes no request; `refresh=True` with different bytes writes `.` beside it, and the first file is unchanged. + - `test_fetch_403_raises_refused`: `Refused.status == 403`, nothing written. + - `test_user_agent`: the request header `user-agent == "stack-pfs-dossier/1.0 (ci@mail.fhirworx.io)"`. + - `test_cite_file_dedupes_by_url_no_attachment`: two calls → one key; a fake store's `attach_file` is never called. + - `test_ensure_tables_idempotent`: twice on `:memory:`, and the `drugs` schema exists. + - `test_drugs_modules_import_without_numpy_pandas` (`test_imports.py`): a subprocess probe blocks `numpy` and `pandas` and imports each of `MODULES = ["drugs.http", "drugs.codes", "drugs.tables"]`. Later tasks append their modules. + - CLI: `test_status_prints_counts_and_gaps`; `test_gap_helper_writes_only_gap`. +- [ ] **Step 2: Run** `uv run --no-sync pytest -q -p no:cacheprovider tests/drugs tests/cli/test_drugs_cli.py` → FAIL (`ModuleNotFoundError: drugs`). +- [ ] **Step 3: Implement** the signatures above. +- [ ] **Step 4: Run** → PASS. Run the gate, ruff, and `tests/cli/test_cli_import_without_optional_deps.py`. +- [ ] **Step 5: Live:** run `ENV stack drugs status`. It prints the empty `drugs` tables and the existing market gaps filtered to none. +- [ ] **Step 6: Commit**: + ```bash + git add src/drugs/__init__.py src/drugs/http.py src/drugs/codes.py src/drugs/tables.py src/cli/drugs.py src/cli/__init__.py tests/drugs/__init__.py tests/drugs/test_codes.py tests/drugs/test_http.py tests/drugs/test_tables.py tests/drugs/test_imports.py tests/cli/test_drugs_cli.py + git commit -m "feat(drugs): drug-tier foundation — hoard and manifest, code levels, NDC-11, stack drugs group" + ``` + +--- + +### Task D2: All-code ASP series, not-payable and NOC rows; one parser for skin subs — `stack drugs asp` + +**Files:** +- Create: `src/drugs/asp.py`, `tests/drugs/test_asp.py`, `tests/drugs/fixtures/asp_page_head.html` (eight anchors trimmed from the public page: 2026-Q4 pricing and crosswalk, the 2026–2027 vaccine pair, 2018-01 pricing, 2018-04 NOC, and 2005-01 pricing and crosswalk through `license.asp`), `tests/dev/test_ingest_asp_parity.py`. +- Modify: `src/drugs/tables.py`, `src/cli/drugs.py`, `dev/scripts/ingest_asp.py`, `tests/drugs/test_tables.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. + +**Interfaces:** +- Consumes: D1. +- Produces: + - `ASP_PAGE = "https://www.cms.gov/medicare/payment/part-b-drugs/asp-pricing-files"`, hoarded at `data/drugs/cms/asp-pricing-files.html`. + - `AspLink(quarter: str, kind: str, url: str, text: str)`; `parse_asp_page(html) -> list[AspLink]`, where `kind ∈ ("pricing", "noc", "crosswalk", "vaccine", "other")` and `quarter` is `""` for `vaccine`/`other`. + - `direct_url(href) -> str`: `/apps/ama/license.asp?file=

` → `https://www.cms.gov

`; a relative href → absolute. + - `hoard_path(link) -> Path`: pricing → `data/cms/asp/asp_.zip`, noc → `data/cms/asp/noc/noc_.zip`, crosswalk → `data/cms/asp/xwalk/xwalk_.zip`. + - `newest_per_quarter(paths: Iterable[Path]) -> dict[str, Path]`: one path per quarter, the newest by `market.http.newest`. + - The ported column logic: `COL_MAP` (every key of `dev/scripts/ingest_asp.py`'s map, plus `"co-insurance percentage" → "coinsurance_pct"` and `"notes" → "notes"`), `find_header_row(lines)`, `pick_pricing_file(names)` (identical selection to the dev script), `pick_member(names, kind)` for `"not-payable"` and `"noc"`. + - `read_table(zf, name, *, open_workbook=None) -> list[dict[str, str]]`: a CSV (latin-1, header row found) or an XLS through `xlrd.open_workbook`, which is injectable for tests. + - `AspRow(quarter, hcpcs, level, list_kind, dosage, payment_limit: float | None, coinsurance_pct: float | None, short_desc, notes, source_file, source_url, item_key)` → `drugs.asp_payment`, with `list_kind ∈ ("payment", "not-payable")`. + - `NocRow(quarter, drug_name, dosage, payment_limit, source_file, source_url, item_key)` → `drugs.asp_noc`. + - `parse_quarter_zip(path, quarter, *, source_url, item_key="") -> tuple[list[AspRow], list[NocRow]]`: + - a `licensed(code)` row gets `short_desc=""`; + - `$`, `,` and blanks are cleaned, and an unparseable number is None; + - a code is stripped and upper-cased. + - `expected_quarters(today) -> list[str]` runs from 2005-Q1 to the current quarter. + - Writers and readers: `write_asp(con, quarter, rows)`, `write_noc(con, quarter, rows)` (replace the quarter); `read_asp(con, *, hcpcs=None, quarter=None)`, `read_noc(con, quarter=None)`. + - CLI `stack drugs asp [--fetch] [--refresh] [--quarter Q …] [--dry-run] [--write]`: + - `--fetch` hoards the page and every pricing, NOC and crosswalk link not already hoarded under its manifest URL; + - a parse reads `newest_per_quarter`; + - each source file is cited (`source_url` from the page link, else `data/cms/asp_source_urls.csv`); + - (quarter, kind) pairs with no file become one `cms-asp:asp` gap note; + - it clears `cms-asp:asp`. + - `dev/scripts/ingest_asp.py` reads `drugs.asp.parse_quarter_zip` over `newest_per_quarter(ASP_DIR.glob("asp_*.zip"))`. It keeps its strict skin-code filter, its `asp_per_unit = round(payment_limit / 1.06, 3)`, its output CSV and its `skin_subs.asp_quarterly` table. Its pandas readers go. + +- [ ] **Step 1: Failing tests** + - `test_parse_asp_page_kinds_and_quarters`: the fixture gives + - `("2026-Q4","pricing", "https://www.cms.gov/files/zip/october-2026-medicare-part-b-payment-limit-files-final.zip")`; + - `("2026-Q4","crosswalk", …october-2026-ndc-hcpcs-crosswalk-final.zip)`; + - two `vaccine` links with quarter `""`; + - `("2018-Q2","noc",…)`; + - `("2005-Q1","pricing","https://www.cms.gov/Medicare/Medicare-Fee-for-Service-Part-B-Drugs/McrPartBDrugAvgSalesPrice/downloads/jan05aspbyhcpcsv6_033106.zip")`. + - `test_direct_url_unwraps_license`: the license.asp href maps to the direct path. + - `test_cpt_short_description_never_stored`: a zip built in the test has a 508 CSV with preamble lines, the header `HCPCS Code,Short Description,HCPCS Code Dosage,Payment Limit,Co-insurance Percentage,Vaccine AWP%,Vaccine Limit,Blood AWP%,Blood limit,Clotting Factor,Notes`, and rows `90371,x,1 ML,140.209,20.000,,,,,,` and `J9035,Bevacizumab injection,10 MG,"$66.123",20.000,,,,,,`. Expect `AspRow(hcpcs="90371", level="I", short_desc="")` and `J9035` with `short_desc == "Bevacizumab injection"` and `payment_limit == 66.123`. + - `test_not_payable_rows_kept`: a not-payable member → `list_kind="not-payable"`, `payment_limit is None`. + - `test_noc_member_parsed`: a NOC CSV row `Examplumab,10 MG,12.5` → `NocRow(drug_name="Examplumab", payment_limit=12.5)`. + - `test_xls_member_through_fake_workbook`: a fake `open_workbook` whose sheet has a preamble and the header in row 3 → the same rows as the CSV path. + - `test_pick_pricing_file_matches_dev_script`: for the four name lists from the 2005-Q1, 2015-Q3, 2026-Q1 and 2026-Q2 hoarded zips (literals), it picks the same member the dev script picked (`skin_subs.asp_quarterly.source_file` values, as literals). + - `test_one_zip_per_quarter_newest_wins`: `asp_2026-Q2.zip` (older mtime) and `asp_2026-Q2.ab12cd34.zip` (newer) → one entry, the `.ab12cd34` path. + - `test_updated_posting_lands_beside`: hoarded 2026-Q2 with URL A; the page lists URL B for 2026-Q2 → B is fetched and lands beside, and the old file's bytes are unchanged. + - `test_missing_quarter_is_gap_not_zero`: hoard 2026-Q1 and 2026-Q3 → gap note names `2026-Q2 pricing`; `read_asp(con, quarter="2026-Q2") == []`. + - `test_roundtrip[asp_payment|asp_noc]`. + - `test_skin_rows_match_hoarded_csv` (`tests/dev/test_ingest_asp_parity.py`, skips without `data/cms/asp/`): every row of `data/cms/asp/skin_subs_asp_quarterly.csv` (1,974) has a parsed counterpart with equal `quarter`, `hcpcs_code`, `short_description`, `dosage_or_unit`, `source_file`, and `payment_limit` within 1e-9. No extra skin row appears. + - CLI: `test_asp_cli_fetch_write` (MockTransport page and two zips → rows, ingest_log, one publish); `test_asp_cli_dry_run_lists_links`; `test_asp_cli_refusal_prints_gap` (403 on the page → `gap: cms-asp:asp:`, nothing else). +- [ ] **Step 2: Run** `tests/drugs/test_asp.py tests/dev/test_ingest_asp_parity.py tests/cli/test_drugs_cli.py` → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; the gate; ruff. +- [ ] **Step 5: Live:** + - Run `ENV stack drugs asp --fetch --dry-run`, then `ENV stack drugs asp --fetch --write` (`.state/drugs/asp.log`). Report: + - quarters per kind against `expected_quarters`; + - rows per quarter, which must equal the `all_asp_quarterly.csv` count for each of the 86 hoarded quarters (2005-Q1: 541, 2026-Q2: 903), with every difference listed; + - the new 2026-Q3 and 2026-Q4 rows; + - the gap note. + - Run `uv run --no-sync python dev/scripts/ingest_asp.py`. `skin_subs.asp_quarterly` must still hold 1,974 rows, identical by `(quarter, hcpcs_code, payment_limit)` to the replica copy taken before the run. + - Run the four skin notebooks headless in the notebooks container the way the nightly job does: `nb_integration.py --config `. All must run clean. +- [ ] **Step 6: Commit** `git add src/drugs/asp.py src/drugs/tables.py src/cli/drugs.py dev/scripts/ingest_asp.py tests/drugs/test_asp.py tests/drugs/fixtures/asp_page_head.html tests/drugs/test_tables.py tests/drugs/test_imports.py tests/dev/test_ingest_asp_parity.py tests/cli/test_drugs_cli.py && git commit -m "feat(drugs): all-code quarterly ASP payment, not-payable and NOC rows with provenance; skin subs read the same parser"` + +--- + +### Task D3: NDC–HCPCS crosswalks — `stack drugs xwalk` + +**Files:** +- Create: `src/drugs/xwalk.py`, `tests/drugs/test_xwalk.py`. +- Modify: `src/drugs/tables.py`, `src/cli/drugs.py`, `tests/drugs/test_tables.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. + +**Interfaces:** +- Consumes: D1, D2 (`newest_per_quarter`, `read_table`, hoarded `xwalk_.zip`, and the crosswalk members inside the 2006-Q1/Q2 pricing zips). +- Produces: + - `XW_CODE = re.compile(r"^(_?\d{4}_CODE|HCPCS( CODE)?|HCPCS_CODE)$", re.I)` finds the header row. + - `XW_COLS` maps `LABELER NAME`, `NDC`/`NDC2`/`11-DIGIT NDC`, `Drug Name`, `HCPCS dosage`/`Dosage`, `PKG SIZE`, `PKG QTY`, `BILLUNITS`, `BILLUNITSPKG` (case-insensitive) to fields. Short Description is read and dropped. + - `member_kind(name) -> str | None`: `"asp"`, `"opps"`, `"awp"`, `"prep"` from the member name; `None` for the introduction text. + - `XwalkRow(quarter, xw_kind, hcpcs, ndc11, alt_id, labeler, drug_name, dosage, pkg_size: float | None, pkg_qty: float | None, bill_units: float | None, bill_units_pkg: float | None, source_file, source_url, item_key)` → `drugs.ndc_hcpcs`. `alt_id` holds the raw identifier when `ndc11` is None. + - `parse_xwalk_zip(path, quarter, *, source_url, item_key="") -> list[XwalkRow]`. + - `write_xwalk(con, quarter, rows)`, `read_xwalk(con, *, hcpcs=None, quarter=None, ndc11=None)`. + - CLI `stack drugs xwalk [--quarter Q …] [--write]`. Quarters without any crosswalk become one `cms-asp:xwalk` gap note. It clears `cms-asp:xwalk`. + +- [ ] **Step 1: Failing tests** + - `test_xwalk_header_drift_2026_code_column`: header `_2026_CODE,Short Description,LABELER NAME,NDC,Drug Name,HCPCS dosage,PKG SIZE,PKG QTY,BILLUNITS,BILLUNITSPKG`, row `J0129,abatacept inj,"Bristol-Myers Squibb",00003-2187-10,Orencia,10 MG,250,1,25,25` → `XwalkRow(hcpcs="J0129", ndc11="00003218710", labeler="Bristol-Myers Squibb", drug_name="Orencia", bill_units_pkg=25.0, xw_kind="asp")`. + - `test_xwalk_2005_header`: the header `HCPCS,Short Description,Labeler Name,NDC,Drug Name,Dosage,PKG SIZE,PKG QTY,BILLUNITS,BILLUNITSPKG`, read through a fake workbook → the same mapping. + - `test_xwalk_stores_no_short_descriptor`: `XwalkRow` has no descriptor field; a Level I row `90371,x,…` keeps its code and labeler only. + - `test_alternate_id_kept_raw`: NDC `"ALT 1234"` → `ndc11 is None`, `alt_id == "ALT 1234"`. + - `test_member_kinds`: the four 2026-Q4 member names (literals from the hoarded zip) → `asp`, `opps`, `awp`, `prep`; the introduction text → None. + - `test_crosswalk_inside_2006_pricing_zip`: a pricing zip holding `April06ASPNDC-HCPCSCrosswalk_20Mar06.csv` is parsed for 2006-Q2. + - `test_roundtrip[ndc_hcpcs]`. + - CLI: `test_xwalk_cli_write`, `test_xwalk_cli_missing_quarters_gap`. +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; the gate; ruff. +- [ ] **Step 5: Live:** run `ENV stack drugs xwalk --write`. Report rows and distinct labelers per year, the share of rows with `ndc11` None, and the gap quarters. The 2026-Q4 `asp` member must give the file's own data-row count (7,420 lines less the preamble and header) and its distinct labeler count, both checked with `csv` on the hoarded member. +- [ ] **Step 6: Commit** `git add src/drugs/xwalk.py src/drugs/tables.py src/cli/drugs.py tests/drugs/test_xwalk.py tests/drugs/test_tables.py tests/drugs/test_imports.py tests/cli/test_drugs_cli.py && git commit -m "feat(drugs): NDC-HCPCS crosswalks for every quarter, header drift handled, NDC-11 normalised"` + +--- + +### Task D4: FDA — NDC Directory, Orange Book, Purple Book — `stack drugs fda` + +**Files:** +- Create: `src/drugs/fda.py`, `tests/drugs/test_fda.py`, `tests/drugs/fixtures/purple_head.csv` (synthetic: the title line, a changes section of 2 rows, a blank line, the full-list section of 3 rows including one 351(k) row). +- Modify: `src/drugs/tables.py`, `src/cli/drugs.py`, `tests/drugs/test_tables.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. + +**Interfaces:** +- Consumes: D1. +- Produces: + - Sources: + - `NDC_ZIP = "https://www.accessdata.fda.gov/cder/ndctext.zip"`; + - `NDC_EXCLUDED = "https://www.accessdata.fda.gov/cder/ndc_excluded.zip"`; + - `ORANGE = "https://www.fda.gov/media/76860/download"`, hoarded as `data/drugs/fda/orange-book.zip`; + - `PURPLE_PAGE = "https://purplebooksearch.fda.gov/downloads"`; the monthly CSV links are read from it (their month case varies), hoarded as `data/drugs/fda/purple/-.csv`. + - `FdaNdcRow(ndc11, product_ndc, labeler, proprietary_name, nonproprietary_name, route, dosage_form, marketing_category, application, start_date: date | None, end_date: date | None, excluded: bool, snapshot: date, item_key)` → `drugs.fda_ndc`, one row per package NDC. + - `parse_ndc_zip(data: bytes, *, excluded: bool, snapshot, item_key="") -> list[FdaNdcRow]` joins package to product on `PRODUCTID`; + - columns are keyed by header name (`PRODUCTID`, `PRODUCTNDC`, `NDCPACKAGECODE`, `PROPRIETARYNAME`, `NONPROPRIETARYNAME`, `ROUTENAME`, `DOSAGEFORMNAME`, `MARKETINGCATEGORYNAME`, `APPLICATIONNUMBER`, `LABELERNAME`, `STARTMARKETINGDATE`, `ENDMARKETINGDATE`), so a missing header raises `KeyError` naming it; + - `application` goes through `appl_id`. + - `ApplicationRow(application, appl_type, holder, trade_name, ingredient, license_type, ref_proper_name, ref_proprietary_name, approval_date: date | None, marketing_status, source, snapshot: date, item_key)` → `drugs.fda_application`, with `source ∈ ("orange", "purple")`. + - `parse_orange(zip_bytes, *, snapshot, item_key="")` reads `products.txt`: `~`-delimited, header `Ingredient~DF;Route~Trade_Name~Applicant~Strength~Appl_Type~Appl_No~Product_No~TE_Code~Approval_Date~RLD~RS~Type~Applicant_Full_Name`. `holder = Applicant_Full_Name`. Approval dates like `"Apr 12, 2023"` and `"Approved Prior to Jan 1, 1982"` give None. + - `parse_purple(text, *, snapshot, item_key="")` reads every section headed `N/R/U,Applicant,BLA Number,…`. The full-list section wins on duplicate `(BLA Number, Product Number)`. `license_type` is kept as given (`351(a)`, `351(k) Biosimilar`, `351(k) Interchangeable`). + - Writers and readers: `write_fda_ndc(con, rows)` (replace all), `write_applications(con, source, rows)`, `read_fda_ndc(con, ndc11s=None)`, `read_applications(con, source=None)`. + - CLI `stack drugs fda [--source ndc|orange|purple …] [--all-months] [--refresh] [--write]` clears `fda-ndc:fda`, `fda-orange:fda` and `fda-purple:fda` per source. + +- [ ] **Step 1: Failing tests** + - `test_parse_ndc_zip_joins_package_to_product`: a synthetic product.txt and package.txt (tab-delimited, header names above) → `FdaNdcRow(ndc11="00002143380", product_ndc="0002-1433", application="BLA125057", route="SUBCUTANEOUS")`. + - `test_ndc_missing_header_raises_keyerror`. + - `test_parse_orange`: the synthetic line `BUDESONIDE~AEROSOL, FOAM;RECTAL~UCERIS~SALIX~2MG/ACTUATION~N~205613~001~AB~Oct 7, 2014~Yes~No~RX~SALIX PHARMACEUTICALS INC` → `ApplicationRow(application="NDA205613", holder="SALIX PHARMACEUTICALS INC", approval_date=date(2014,10,7), source="orange")`. + - `test_parse_purple_full_list_wins`: the fixture → 3 rows; the 351(k) row has `ref_proprietary_name == "Exemplar"`; a duplicate from the changes section is not doubled. + - `test_purple_links_from_page`: page HTML with `//www.accessdata.fda.gov/drugsatfda_docs/PurpleBook/2026/purplebook-search-October-data-download.csv` and the lowercase `january` → `(2026, 10)` and `(2026, 1)` with absolute https URLs. + - `test_roundtrip[fda_ndc|fda_application]`. + - CLI: `test_fda_cli_offline_write` (all three sources mocked); `test_fda_cli_refusal_prints_gap` (403 on Orange → `gap: fda-orange:fda:`; NDC and Purple still written). +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; the gate; ruff. +- [ ] **Step 5: Live:** run `ENV stack drugs fda --write`. Report: + - NDC packages (current and excluded); + - Orange Book applications; + - Purple Book products by license type; + - how many crosswalk `ndc11`s (latest 4 quarters) find an FDA row. +- [ ] **Step 6: Commit** `git add src/drugs/fda.py src/drugs/tables.py src/cli/drugs.py tests/drugs/test_fda.py tests/drugs/fixtures/purple_head.csv tests/drugs/test_tables.py tests/drugs/test_imports.py tests/cli/test_drugs_cli.py && git commit -m "feat(drugs): FDA NDC Directory, Orange Book and Purple Book application holders, hoarded and cited"` + +--- + +### Task D5: Product registry and manufacturer resolution — `stack drugs registry`, `stack drugs labelers` + +**Files:** +- Create: `src/drugs/curated.yaml`, `src/drugs/curated.py`, `src/drugs/registry.py`, `tests/drugs/test_curated.py`, `tests/drugs/test_registry.py`. +- Modify: `src/drugs/tables.py`, `src/cli/drugs.py`, `tests/drugs/test_tables.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. + +**Interfaces:** +- Consumes: + - D3 (`read_xwalk`), D4 (`read_fda_ndc`, `read_applications`); + - `market.seed.Cite`, `norm_org`, `alias_match`; `market.tables.read_entities`, `read_securities`, `write_entities`, `write_securities`, `write_links`; + - `market.edgar.fetch_submissions`, `fetch_tickers`, `entity_from_submissions`, `securities_for`, `sic_links`, `filings_from_submissions`, `shares_ama_run`, `cite_registry`, the SEC pacer; + - `market.tiingo.PHARMA_DEVICE_SICS`; + - `cli.market._asker`; `pfs.runlog.RunLog`, `run_units`, `input_hash`, `ledger_path`. +- Produces: + - **`drugs.curated`** + - `LabelerEntry(names: tuple[str, ...], cik: str | None, private: bool, valid_from, valid_to, strength, cite: Cite)`. + - `GroupEntry(key, codes: tuple[str, ...], ranges: tuple[tuple[str, str], ...], cite)`. + - `ProcedureEntry(subject_kind: str, subject: str, family: str, code_lo: str, code_hi: str, hcpcs_lo: str, hcpcs_hi: str, routes: tuple[str, ...], cite: Cite, p_id: int | None)`, used by D11. `subject_kind ∈ ("group", "rule")`; a rule matches the group's codes inside `hcpcs_lo..hcpcs_hi` whose route is in `routes`. + - `EventEntry(group: str, doc: str, kind: str, item_key: str, p_id: int, label: str, must_contain: str)`, used by D14. `kind ∈ ("rule-proposed", "rule-final")`. The loader accepts empty `procedures` and `events` lists until D11 and D14 fill them. + - `load_curated(path=None) -> Curated` is pure. It raises `ValueError(f"{name}: no citation")`, and raises on any of `market.seed.EXCLUDED`. + - `validate_curated(cur, *, entity_ciks: set[str], families: set[str]) -> list[str]`. + - **`drugs.registry`** + - `PRODUCT_SICS` (Decisions); `GROUPS = ("PART-B-DRUGS", "SKIN-SUBSTITUTES", "BIOSIMILARS", "CHEMOTHERAPY")`. + - `norm_labeler(name) -> str` (Decisions). + - `ex21_doc(index_json: dict) -> str | None`: the first item name matching `ex[-_]?21|exhibit[-_]?21` (case-insensitive). `ex21_names(html: str) -> list[str]`: the first non-empty cell of each table row, or each non-empty text line, minus jurisdiction-only lines (a US state, country or "Delaware"-style word list). + - `LabelerRow(name_norm, raw_names, entity_key, method, cite_kind, cite_ref, item_key, valid_from, valid_to, label_version, candidates, note)` → `drugs.labeler_entity`, with `method ∈ ("curated", "private", "subsidiary", "exact", "prefix", "model", "unresolved")`. + - `resolve(names: Iterable[str], *, curated, entities, subsidiaries: Mapping[str, tuple[str, str]]) -> list[LabelerRow]` follows the Decisions order. + - `ProductRow(hcpcs, ndc11, labeler, application, holder, entity_key, entity_via, first_quarter, last_quarter, xwalk_item_key, fda_item_key, holder_item_key, entity_item_key, note)` → `drugs.product`, with `entity_via ∈ ("holder", "labeler", "curated", "")`. + - `build_products(xwalk, fda, apps, labelers, skin_csv_rows) -> list[ProductRow]`: holder first; one row per `(hcpcs, ndc11)` with its first and last quarter; the skin-substitute CSV rows add `(hcpcs, ndc11="")` with `entity_via="curated"`. + - `GroupRow(group_key, hcpcs, source, item_key)` → `drugs.product_group`; `build_groups(asp_codes, skin_codes, xwalk, apps, cur) -> list[GroupRow]`. + - The suggestion step: + - `LABELER_PROMPT_VERSION = "labeler-v1"`; + - `candidates(name, entities, k=5)` gives the top 5 `PRODUCT_SICS` entities by token overlap; + - the schema is `{"choice": int 0..k, "reason": str ≤ 200}` (0 = none); + - `suggest(name, cands, ask) -> str | None`. + - Writers and readers: `write_labelers`, `write_products`, `write_groups` (each replaces all); `read_labelers(con, method=None)`, `read_products(con, *, hcpcs=None, entity_key=None)`, `read_groups(con, group=None)`. + - **CLI** + - `stack drugs registry [--subsidiaries] [--suggest] [--limit N] [--write]`: + - `--subsidiaries` fetches the latest 10-K index and EX-21 of each listed `PRODUCT_SICS` company (hoarded under `data/market/sec/ex21//`), and records refusals and misses as `sec-edgar:registry`; + - a curated CIK missing from `market.entity` is added the way `cli.market._new_entities` does; + - every curated quote passes `shares_ama_run`; + - it clears `sec-edgar:registry`. + - `stack drugs labelers [--unresolved] [--top 40]` prints names ranked by the latest-year allowed amount on their codes (D6's `code_allowed`; before D6, by row count). + +- [ ] **Step 1: Failing tests** + - `test_norm_labeler`: `"Teva Pharmaceuticals USA, Inc."` → `"TEVA"`; `"Amgen Inc"` → `"AMGEN"`; `"Grifols USA, LLC"` → `"GRIFOLS"`; `"Smith & Nephew, Inc."` → `"SMITH AND NEPHEW"`. + - `test_curated_seed_loads_and_cited`: the shipped YAML loads, and every entry has exactly one locator. The five required skin-substitute names map to 0001661181, 0001376339 and 0000845982. + - `test_curated_entry_without_cite_rejected`; `test_curated_excluded_name_rejected`. + - `test_resolution_order`: a curated name beats an exact match; a subsidiary match (`"JANSSEN BIOTECH"` in a fake EX-21 of CIK X) beats exact; prefix applies only to `PRODUCT_SICS` entities (`"AMGEN BIOLOGICS USA"` → `"AMGEN BIOLOGICS"` prefix-matches the entity `AMGEN INC`, SIC 2836; `"HCA SOMETHING"` never matches a hospital, SIC 8062); two exact entities → `unresolved` with both candidates. + - `test_holder_wins_over_repackager_labeler`: NDC labeler `"A-S Medication Solutions"` (repackager, unresolved), FDA application `NDA205613` held by `"SALIX PHARMACEUTICALS INC"` (resolved) → `entity_via == "holder"`, entity Salix. + - `test_registry_joins_fda_10digit_to_cms_11digit`: FDA package `"0002-1433-80"` and crosswalk NDC `"00002-1433-80"` → one product row carrying both `fda_item_key` and `xwalk_item_key`. + - `test_skin_csv_rows_join_curated`: `Q4101` + `Organogenesis` → `ProductRow(hcpcs="Q4101", ndc11="", entity_key="0001661181", entity_via="curated")`; a blank manufacturer → `entity_key=""`, note `"no manufacturer in curation"`. + - `test_ex21_doc_and_names`: index items `["ex21.htm", "d123.htm"]` → `"ex21.htm"`; a two-column HTML table → names only. + - `test_groups`: `J9035` in `CHEMOTHERAPY` and `PART-B-DRUGS`; `Q5107` in `BIOSIMILARS`; a code with a 351(k) BLA NDC in `BIOSIMILARS`; `Q4101` in `SKIN-SUBSTITUTES`. + - `test_suggest_closed_set_marked_model`: a fake ask returns `{"choice": 2}` → the second candidate, with `method="model"` and `label_version="labeler-v1"`; `{"choice": 9}` → None. + - `test_roundtrip[labeler_entity|product|product_group]`. + - CLI: `test_registry_cli_offline_write`; `test_registry_subsidiaries_refusal_gap`; `test_registry_adds_missing_curated_entity` (submissions fixture → `write_entities` called once); `test_labelers_unresolved_ranked`. +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; the gate; ruff. +- [ ] **Step 5: Live:** + - Run `ENV stack drugs registry --subsidiaries --write`, then `ENV stack drugs labelers --unresolved --top 40`. + - Curate the top 40 unresolved names into `curated.yaml` (M12 quotes from hoarded filings; foreign filers cite their 20-F or the company's own investor page as `strength: weak`). + - Rerun `--write`. Report labeler counts by method, products with and without an entity, and the 3 skin-substitute entities' code counts. + - Optional GPU: check `ENV stack llm hosts`, then `ENV stack drugs registry --suggest --limit 100 --write`. Report the model suggestions; none is used. +- [ ] **Step 6: Commit** `git add src/drugs/curated.yaml src/drugs/curated.py src/drugs/registry.py src/drugs/tables.py src/cli/drugs.py tests/drugs/test_curated.py tests/drugs/test_registry.py tests/drugs/test_tables.py tests/drugs/test_imports.py tests/cli/test_drugs_cli.py && git commit -m "feat(drugs): product registry HCPCS-NDC-labeler-holder-entity, curated and EX-21 resolution seeded from the skin-substitute manufacturers"` + +--- + +### Task D6: Payment evidence and the `asp` link basis — `stack drugs links` + +**Files:** +- Create: `src/drugs/payment.py`, `tests/drugs/test_payment.py`. +- Modify: `src/drugs/tables.py`, `src/cli/drugs.py`, `tests/drugs/test_tables.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. + +**Interfaces:** +- Consumes: D5 (`read_products`, `read_groups`, `read_labelers`); `pfs.utilization` (SQL: `year, hcpcs, n_services, avg_allowed, item_key`); `market.revenue` when present (`pfs.codetables.is_missing_table_error` fallback); `market.tables.LinkRow`, `write_links`, `retire_links`, `read_links`. +- Produces: + - `code_allowed(con, year) -> dict[str, tuple[float, str]]`: Σ `n_services × avg_allowed` per HCPCS, with the year's `item_key`. + - `code_labelers(products, year) -> dict[str, set[str]]`. + - `EntityPaymentRow(entity_key, year, attributed_allowed, n_codes, n_sole, unattributed_allowed, revenue: float | None, share: float | None, item_keys, caveat)` → `drugs.entity_payment`, where: + - `CAVEAT = "equal split of physician/supplier Part B allowed amounts across the code's resolved labelers; excludes hospital outpatient billing; not company sales"`; + - `unattributed_allowed` is the same on every row of a year (the total of codes with no resolved labeler). + - `attribute(allowed, labelers, *, year) -> list[EntityPaymentRow]`. + - `asp_links(products, groups, payments, cites) -> list[LinkRow]` (Decisions). + - Writers and readers in `drugs.tables`: `write_entity_payment(con, year, rows)`, `read_entity_payment(con, *, year=None, entity_key=None)`, and `read_latest_payment(con) -> dict[str, EntityPaymentRow]` (the latest year per entity; `{}` when the table is missing). + - CLI `stack drugs links [--year Y …] [--write]`: + - the default is every `pfs.utilization` year; + - it writes the payments, upserts the `asp` links, and calls `retire_links(con, "asp", , keep)`; + - it prints the top 25 entities of the latest year; + - no `pfs.utilization` table → gap `pfs:links`; otherwise it clears `pfs:links`. + +- [ ] **Step 1: Failing tests** + - `test_code_allowed_sums_rows`: two place-of-service rows (10 × 100.0, 5 × 50.0) → `1250.0`. + - `test_attributed_payment_sums_to_code_total`: code A ($900; entities X, Y, Z) and code B ($100; X only) → X 400.0, Y 300.0, Z 300.0, and the sum equals 1000.0; X `n_sole == 1`. + - `test_unattributed_reported`: a $50 code with no labeler → `unattributed_allowed == 50.0` on every row. + - `test_share_uses_revenue_period_end`: an in-memory `market.revenue` with market Task 13's `RevenueRow` columns, holding rows with `period_end` 2024-12-31 = 1e9 and 2023-12-31 = 5e8 → share for 2024 `== attributed / 1e9`; no `market.revenue` table → `share is None`. + - `test_asp_links_scope_product_and_strength`: + - X sole on a SKIN-SUBSTITUTES code → `LinkRow(scope="product", target="SKIN-SUBSTITUTES", basis="asp", strength="sole")`, plus a `PART-B-DRUGS` link; + - Y shared → `strength="shared"`; + - the links carry `valid_from = quarter_start(first_quarter)`, and `valid_to` is None while the product sits in the latest crosswalk quarter. + - `test_asp_links_never_wipe_other_bases`: a stored `fts` link of X survives `write_links` + `retire_links(con, "asp", …)`. + - `test_curated_window_respected`: a curated link valid 2019–2021 gives no labeler in 2024. + - `test_roundtrip[entity_payment]`. + - CLI: `test_links_cli_write`, `test_links_cli_no_utilization_gap`, `test_links_cli_prints_top`. +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; the gate; ruff. +- [ ] **Step 5: Live:** + - Run `ENV stack drugs links --write`. Report per year the attributed and unattributed totals and the top 25 entities for 2024. + - Give ORGO, MDXG and SNN their 2024 attributed amounts and SKIN-SUBSTITUTES links. + - Say which of the 12 single-target pharma/device fts names (M18's parked list) now carry asp evidence. + - After market Task 13 lands, rerun to fill `share`. +- [ ] **Step 6: Commit** `git add src/drugs/payment.py src/drugs/tables.py src/cli/drugs.py tests/drugs/test_payment.py tests/drugs/test_tables.py tests/drugs/test_imports.py tests/cli/test_drugs_cli.py && git commit -m "feat(drugs): Part B payment attributed to product owners and the asp link basis for the market tier"` + +--- + +### Task D7: HCPCS Level II lineage — `stack drugs hcpcs` + +**Files:** +- Create: `src/drugs/hcpcs.py`, `tests/drugs/test_hcpcs.py`. +- Modify: `src/drugs/tables.py`, `src/cli/drugs.py`, `tests/drugs/test_tables.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. + +**Interfaces:** +- Consumes: D1. +- Produces: + - Sources: + - `HCPCS_PAGE = "https://www.cms.gov/medicare/coding-billing/healthcare-common-procedure-system/quarterly-update"`; + - `HCPCS_PATTERN = "https://www.cms.gov/files/zip/january-{year}-alpha-numeric-hcpcs-file.zip"` for 2017–2023; + - hoard `data/drugs/hcpcs/-.zip`. + - `HcpcsRecord(code, long_desc, short_desc, xref: tuple[str, ...], betos, tos, added: date | None, action_effective: date | None, terminated: date | None, action)`. + - `parse_hcpcs_txt(text) -> list[HcpcsRecord]`: the positions in Decisions; lines padded to 320; recid `3` starts a code and `4` continues its long description; modifier lines (recid 7/8) and `D` codes are skipped. + - `member_stamp(name) -> date | None` reads `_(\d{8})\.txt$` as MMDDYYYY. + - `CodeEventRow(system, code, kind, effective: date | None, released: date | None, vintage, from_codes, to_codes, source_file, item_key, note)` → `drugs.code_event`, with `system ∈ ("hcpcs", "icd10cm", "icd10pcs")`. + - `TitleRow(system, code, title_short, title_long, first_vintage, last_vintage, item_key)` → `drugs.code_title`. + - `hcpcs_events(vintages: Sequence[tuple[str, date | None, list[HcpcsRecord], str]]) -> list[CodeEventRow]`: the kinds in Decisions; deduplicated by `(code, kind, effective)`, the earliest `released` kept. + - `hcpcs_titles(vintages) -> list[TitleRow]`. + - Writers and readers: `write_code_events(con, system, rows)`, `write_titles(con, system, rows)` (replace the system); `read_code_events(con, *, system=None, code=None)`, `read_titles(con, system, codes=None)`. + - CLI `stack drugs hcpcs [--fetch] [--refresh] [--write]`: a 404 for a pattern year → one `cms-hcpcs:hcpcs` gap note listing the years; it clears `cms-hcpcs:hcpcs`. + +- [ ] **Step 1: Failing tests** (fixed-width lines built in the test by `fw(code=…, recid=…, long=…, …)`) + - `test_parse_positions`: `Q4101` add `20090101`, effective `20260101`, no termination, action `N` → `added == date(2009,1,1)`, `terminated is None`. + - `test_long_description_continuation`: recid 3 + 4 → one record, joined with a space. + - `test_xref_gives_reassigned_event`: `C9014` terminated `20181231`, XREF `J0567` → `CodeEventRow(kind="reassigned", effective=date(2019,1,1), to_codes="J0567")` plus `terminated`. + - `test_reactivated_not_added`: action `R` → `reactivated`, no second `added`. + - `test_description_change_between_vintages`: the same code with a different long description in 2026-07 → `description_changed`, vintage `2026-07`. + - `test_released_from_member_stamp`: `HCPC2026_OCT_ANWEB_09232026.txt` → `date(2026,9,23)`. + - `test_cdt_and_modifiers_skipped`. + - `test_roundtrip[code_event|code_title]`. + - CLI: `test_hcpcs_cli_fetch_write`, `test_hcpcs_cli_pattern_404_gap`. +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; the gate; ruff. +- [ ] **Step 5: Live:** run `ENV stack drugs hcpcs --fetch --write`. Report vintages hoarded against the gap years, events per kind per year, the SKIN-SUBSTITUTES and BIOSIMILARS events since 2024, and the code count against `terminology.hcpcs_level_2` (8,846 rows, Tuva, undated). +- [ ] **Step 6: Commit** `git add src/drugs/hcpcs.py src/drugs/tables.py src/cli/drugs.py tests/drugs/test_hcpcs.py tests/drugs/test_tables.py tests/drugs/test_imports.py tests/cli/test_drugs_cli.py && git commit -m "feat(drugs): HCPCS Level II lineage from the CMS quarterly files — adds, terminations, reassignments, dated by release"` + +--- + +### Task D8: ICD-10-CM and ICD-10-PCS lineage — `stack drugs icd` + +**Files:** +- Create: `src/drugs/icd.py`, `tests/drugs/test_icd.py`. +- Modify: `src/drugs/tables.py`, `src/cli/drugs.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. + +**Interfaces:** +- Consumes: D1, D7 (`CodeEventRow`, `TitleRow`, their writers). +- Produces: + - Sources: + - `CDC_CM = "https://ftp.cdc.gov/pub/Health_Statistics/NCHS/Publications/ICD10CM/{fy}/"`: the directory listing; the code-descriptions zip is chosen by `re.compile(r"code[ _-]?descriptions", re.I)`; + - `CMS_ICD_PAGE = "https://www.cms.gov/medicare/coding-billing/icd-10-codes"`: PCS order-file zips, CM and PCS conversion tables and the April vintages, with links read from the page; + - `CMS_PCS_OLD = "https://www.cms.gov/Medicare/Coding/ICD10/Downloads/{fy}-PCS-Long-Abbrev-Titles.zip"` for FY2016–2020; + - hoard `data/drugs/icd/{cm,pcs}//`. + - `parse_order(text) -> list[tuple[str, bool, str, str]]`: `(code, billable, short, long)`. Fixed width: order 1–5, code 7–13, header flag 15, short 17–76, long 78–end. + - `parse_cm_conversion(text) -> list[tuple[str, str, tuple[str, ...]]]`: `(current, effective_fy, previous codes)` from the tab-delimited table after the `Current code assignment` header. A cell like `C44.109` that continues on the next line is joined. Dots are removed. + - `parse_pcs_conversion(text)` gives the same shape. + - `icd_events(system, vintages: Sequence[tuple[str, list[tuple[str, bool, str, str]], str]], conversions) -> list[CodeEventRow]`: `added`, `deleted`, `title_changed` between consecutive vintages (CM billable only); `converted` from conversion rows (`effective = fy_effective(fy)`). + - `icd_titles(...) -> list[TitleRow]`. + - CLI `stack drugs icd [--fetch] [--system cm|pcs] [--fy FY …] [--write]`: the default FYs are 2016–2027; a missing vintage goes to `cdc-icd:icd` or `cms-icd:icd`; it clears both on success. + +- [ ] **Step 1: Failing tests** + - `test_parse_order_fixed_width`: the line `00001 A00 0 Cholera…` (built in the test) → `("A00", False, "Cholera", "Cholera")`; a billable line → `True`. + - `test_cm_conversion_cumulative`: rows `A04.71\t2017\tA04.7` and `B88.01\t2025\tB88.0` → `("A0471","2017",("A047",))`; a header preamble is skipped. + - `test_vintage_diff_events`: FY2025 `{A000, B880}` and FY2026 `{A000, B8801, B8809}` → `deleted B880` and `added B8801`, `B8809`, effective 2025-10-01. + - `test_converted_event`: `B88.01 ← B88.0` (2025) → `CodeEventRow(kind="converted", code="B8801", from_codes="B880", effective=date(2024,10,1))`. + - `test_april_vintage_effective`: vintage `2026-04` → `effective == date(2026,4,1)`. + - `test_headers_never_billable_events`: a header-only code change emits no `added`/`deleted`. + - `test_cdc_listing_picks_descriptions_zip`: an HTML listing with `icd10cm-Code Descriptions-2026.zip` and `icd10cm-table and index-2026.zip` → the first. + - CLI: `test_icd_cli_fetch_write`, `test_icd_cli_missing_vintage_gap`. +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; the gate; ruff. +- [ ] **Step 5: Live:** run `ENV stack drugs icd --fetch --write`. Report vintages per system, events per kind per FY, and which FY's billable CM set equals `terminology.icd_10_cm` (98,186 rows, Tuva snapshot): the vintage of the stack's current terminology. +- [ ] **Step 6: Commit** `git add src/drugs/icd.py src/drugs/tables.py src/cli/drugs.py tests/drugs/test_icd.py tests/drugs/test_imports.py tests/cli/test_drugs_cli.py && git commit -m "feat(drugs): ICD-10-CM and ICD-10-PCS lineage FY2016-FY2027 from CDC and CMS files, conversions included"` + +--- + +### Task D9: MCD billing articles — product → disease — `stack drugs mcd` + +**Files:** +- Create: `src/drugs/mcd.py`, `tests/drugs/test_mcd.py`. +- Modify: `src/drugs/tables.py`, `src/cli/drugs.py`, `tests/drugs/test_tables.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. + +**Interfaces:** +- Consumes: D1; `drugs.codes.licensed`. +- Produces: + - `MCD_ALL_ARTICLE = "https://downloads.cms.gov/medicare-coverage-database/downloads/exports/all_article.zip"`, hoarded at `data/drugs/mcd/all_article.zip`. The outer zip holds `all_article_csv.zip` (inner), an `.mdb`, a data-dictionary PDF and `readme_first.txt`. + - `MCD_FILES = {"article": "article.csv", "hcpcs": "article_x_hcpc_code.csv", "icd": "article_x_icd10_covered.csv", "icd_non": "article_x_icd10_noncovered.csv"}`. + - `MCD_COLS`: + - `article_id`, `article_version`, `title` (`article_title`), `status`, `effective` (`article_eff_date`), `retired` (`article_end_date`); + - `hcpc_code_id`, `hcpc_code_group`; + - `icd10_code_id`, `icd10_covered_group` / `icd10_noncovered_group`. + + Verify every name against the data dictionary on the first fetch. A missing file or column raises `KeyError` naming it, and the CLI turns that into a `cms-mcd:mcd` gap. + - Rows and tables: + - `ArticleRow(article_id, version, title, status, effective: date | None, retired: date | None, url, item_key)` → `drugs.mcd_article`, with `url = f"https://www.cms.gov/medicare-coverage-database/view/article.aspx?articleid={id}&ver={version}"`; + - `ArticleCodeRow(article_id, version, hcpcs, grp)` → `drugs.mcd_article_hcpcs`. Codes only: no description is ever read into a row. + - `ArticleIcdRow(article_id, version, icd10, grp, covered: bool)` → `drugs.mcd_article_icd` (dots removed). + - `parse_mcd(outer_zip: bytes, *, item_key="") -> tuple[list[ArticleRow], list[ArticleCodeRow], list[ArticleIcdRow]]` keeps only articles that have both HCPCS and covered ICD-10 rows. + - `DiseaseLink(hcpcs, icd10, article_id, version, strength, url)` with `strength ∈ ("same-group", "same-article")`. + - `diseases_for(con, hcpcs, *, all_versions=False) -> list[DiseaseLink]`: the latest version per article; `same-group` when both group numbers are set and equal and the article has two or more HCPCS groups; covered codes only. + - `products_for(con, icd10) -> list[DiseaseLink]` is the reverse. + - `write_mcd(con, articles, codes, icds)` (replace all); `read_articles(con, ids=None)`. + - CLI `stack drugs mcd [--fetch] [--refresh] [--write]` clears `cms-mcd:mcd`. + +- [ ] **Step 1: Failing tests** (nested zips built in the test) + - `test_parse_mcd_codes_only`: an `article_x_hcpc_code.csv` row carrying `long_description="x"` for `96413` and `J9035` → `ArticleCodeRow`s with `hcpcs` only. + - `test_mcd_drops_cpt_descriptions`: no `drugs.mcd_*` column holds a description; `fields(ArticleCodeRow)` has none. + - `test_same_group_vs_same_article`: an article with HCPCS groups 1 (`J9035`) and 2 (`J9271`) and ICD groups 1 (`C18.9`) and 2 (`C43.9`) → `(J9035, C189)` same-group, and `(J9035, C439)` absent from same-group but present as same-article when asked with `strength="same-article"`. + - `test_latest_version_only`: versions 3 and 4 → only version 4's links; `all_versions=True` → both. + - `test_noncovered_excluded`. + - `test_missing_inner_file_keyerror`. + - `test_roundtrip[mcd_article|mcd_article_hcpcs|mcd_article_icd]`. + - CLI: `test_mcd_cli_write`, `test_mcd_cli_missing_column_gap`. +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; the gate; ruff. +- [ ] **Step 5: Live:** run `ENV stack drugs mcd --fetch --write`. Report articles (current and retired), HCPCS codes with at least one covered ICD-10, and the top diseases (by covered-code count) for `J9035` and for SKIN-SUBSTITUTES codes. +- [ ] **Step 6: Commit** `git add src/drugs/mcd.py src/drugs/tables.py src/cli/drugs.py tests/drugs/test_mcd.py tests/drugs/test_tables.py tests/drugs/test_imports.py tests/cli/test_drugs_cli.py && git commit -m "feat(drugs): MCD billing-and-coding articles tie products to covered ICD-10 diagnoses, codes only"` + +--- + +### Task D10: Licensed books — identity, guard, HCPCS Table of Drugs — `stack drugs books` + +**Files:** +- Create: `src/drugs/books.yaml`, `src/drugs/books.py`, `tests/drugs/test_books.py`, `tests/drugs/fixtures/tod_synthetic.html` (a calibre-style paragraph stream with page anchors, a `TABLE OF DRUGS` heading, 6 synthetic records including a continuation row, a range code and a wrapped dosage, then `LEVEL II NATIONAL CODES`). +- Modify: `src/drugs/tables.py`, `src/cli/drugs.py`, `tests/drugs/test_tables.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. + +**Interfaces:** +- Consumes: D1; `market.edgar.shares_ama_run`, `cpt_grams`; `pfs.codetables.cpt_years`, `read_cpt_codes`; bib attachments of items tagged `source:ama`. +- Produces: + - `BookFile(sha12, book, edition, fmt, uses: tuple[str, ...], item_key, path)`. + - `load_books(path=None) -> dict[str, dict]` reads `books.yaml` (the table in Decisions). + - `book_files(store, *, sha=file_sha12) -> tuple[list[BookFile], list[str]]` returns the known files and one note per unknown `source:ama` attachment (`" : sha not in books.yaml"`). + - Shas are cached in `.state/drugs/book_sha.json`, keyed by `(path, size, mtime)`. + - `book_text_ok(s: str, grams) -> bool`: fewer than 8 words and `not shares_ama_run(s, grams)`. + - `ROUTES = ("IA", "IV", "IM", "IT", "SC", "INH", "VAR", "OTH", "ORAL")`. + - `BookDrugRow(edition, drug_name, dosage, route, code_lo, code_hi, page: int | None, pdf_page: int, item_key)` → `drugs.book_drug`. + - `parse_tod(html_parts: Sequence[str], *, edition, item_key, grams) -> list[BookDrugRow]`: + - the paragraph stream runs from the `TABLE OF DRUGS` heading that follows the front matter up to `LEVEL II NATIONAL CODES`; + - a record ends at a bold `^[A-V]\d{4}(-[A-V]\d{4})?$`; + - in the buffered items, the route is the last item when all its comma parts are in `ROUTES`, and the dosage is the item before it (or the last one) when it contains a digit or a unit word (`mg|ml|unit|vial|mcg|g|iu|each|per`); + - the drug name is the first item when an item remains, else the previous name carries over; + - `pdf_page` comes from the last ``, and `page` from a standalone integer paragraph on that page; + - a name failing `book_text_ok` is stored as `""`. + - `write_book_drugs(con, item_key, rows)`, `read_book_drugs(con, *, hcpcs=None)` (range-aware). + - CLI `stack drugs books [--check] [--tod] [--write]`: + - `--check` lists the known files, the unknown attachments and the books.yaml entries with no bib file; + - `--tod --write` parses `5e756f143ebb`; + - gaps go to `zotero:books`: unknown files, missing editions, and the ICD-10-CM editions 2016, 2017, 2019, 2021, 2023, 2024 and the ICD-10-PCS editions other than 2019 and 2022, which have no codebook file. It clears `zotero:books` only when no gap remains. + +- [ ] **Step 1: Failing tests** (synthetic only, no book text) + - `test_book_identity_from_sha_not_title`: a fake store item titled `"ICD-10-CM 2019"` whose file sha12 is `4246d560ddad` → `BookFile(book="icd10pcs", edition=2019, uses=())`. + - `test_unknown_book_file_is_gap`: sha `000000000000` → no `BookFile`, one note naming the item key. + - `test_book_strings_under_eight_words`: `book_text_ok("Examplumab", grams)` is True; an 8-word string is False; a 5-word string sharing nothing is True. + - `test_parse_tod_fixture`: 6 rows; row 1 `("Examplumab", "10 mg", "IV", "J9998", "J9998")`; the continuation row keeps name `"Examplumab"` with `("250 mg", "IV")`; the range row has `code_lo="J0287"`, `code_hi="J0289"`; the wrapped `vial` stays in the dosage; `pdf_page` 137 and `page` 137 from the fixture anchors. + - `test_read_book_drugs_range_aware`: `J0288` finds the range row. + - `test_roundtrip[book_drug]`. + - CLI: `test_books_check_lists_unknown`, `test_books_tod_write`, `test_books_missing_editions_gap`. +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; the gate; ruff. +- [ ] **Step 5: Live:** + - Import the books (one command per title; `--only` matches a substring): `ENV stack bib import-zotero --collection "AMA Coding Publications" --with-files --only "" --tag source:ama --tag module:coding --tag llm:skip` for `Hcpcs 2019`, `ICD-10-CM 2025 the Complete`, `ICD-10-CM 2022 the Complete`, `ICD-10-CM 2020 the Complete`, `ICD-10-CM 2018`, `ICD-10-PCS 2019 the Complete`, `ICD-10-PCS 2022 the Complete`, `Coding with Modifiers`. Netter is bib 4KJEJNS6 already. + - Run `ENV stack drugs books --check`, then `ENV stack drugs books --tod --write`. + - Report: records (expected near the 1,888 bold codes on PDF pages 137–192), records with an empty name, routes by count, and how many TOD codes are in `drugs.asp_payment`. +- [ ] **Step 6: Commit** `git add src/drugs/books.yaml src/drugs/books.py src/drugs/tables.py src/cli/drugs.py tests/drugs/test_books.py tests/drugs/fixtures/tod_synthetic.html tests/drugs/test_tables.py tests/drugs/test_imports.py tests/cli/test_drugs_cli.py && git commit -m "feat(drugs): licensed books identified by sha, never by title; HCPCS 2019 Table of Drugs as structured facts"` + +--- + +### Task D11: Product → procedure links and Netter anatomy — `stack drugs procedures` + +**Files:** +- Create: `src/drugs/procedures.py`, `src/drugs/netter.py`, `tests/drugs/test_procedures.py`, `tests/drugs/test_netter.py`. +- Modify: `src/drugs/curated.yaml` (the `procedures` section), `src/drugs/tables.py`, `src/cli/drugs.py`, `tests/drugs/test_tables.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. + +**Interfaces:** +- Consumes: D4 (`read_fda_ndc` routes), D5 (`read_groups`, `read_products`, `ProcedureEntry`), D10 (`BookFile`, `book_text_ok`, `read_book_drugs` routes); `pfs.codetables.read_families`; `terminology.icd10_pcs_cms_ontology`; bib `fr_anchors`. +- Produces: + - Curated `procedures` (each cited; family keys validated against `pfs.code_family`): + - `SKIN-SUBSTITUTES` ↔ family `SKIN-SUBSTITUTE-GRAFTS`, codes `15271-15278`; cite bib `NHRGIHGD` (CY2026 PFS final) at the paragraph that names 15271, with its `p_id` recorded; + - rule `CHEMOTHERAPY` with route `INTRAVENOUS` ↔ family `INJECTION-AND-INTRAVENOUS-INFUSION-CHEMOTHERAPY-AND-OTHER-HIGHLY-COMPLEX-DRUG-OR-HIGHLY-COMPLEX-BIOLOGIC-AGENT-ADMINISTRATION`, codes `96413-96417`; cite `SPJB4FX2` (IOM 100-04 ch. 12) with locator `§30.5`; + - rule `PART-B-DRUGS` J0000–J8999, route `INTRAVENOUS` ↔ family `THERAPEUTIC-PROPHYLACTIC-AND-DIAGNOSTIC-INJECTIONS-AND-INFUSIONS-EXCLUDES-CHEMOTHERAPY-AND-OTHER-HIGHLY-COMPLEX-DRUG-OR-HIGHLY-COMPLEX-BIOLOGIC-AGENT-ADMINISTRATION`, codes `96365-96368`; cite `SPJB4FX2` §30.5; + - the same rule with routes `SUBCUTANEOUS`/`INTRAMUSCULAR` ↔ code `96372`; cite `SPJB4FX2` §30.5. + - `code_route(hcpcs, fda_rows, tod_rows) -> str | None`: the majority FDA `ROUTENAME` over the code's current NDCs, else the TOD route mapped (`IV→INTRAVENOUS`, `SC→SUBCUTANEOUS`, `IM→INTRAMUSCULAR`), else None. + - `ProcedureRow(subject_kind, subject, family, code_lo, code_hi, basis, route, cite_kind, cite_ref, item_key, p_id)` → `drugs.product_procedure`, with `subject_kind ∈ ("group", "hcpcs")` and `basis ∈ ("curated", "route-rule")`. + - `procedure_links(cur, groups, routes) -> list[ProcedureRow]`. + - **`drugs.netter`** + - `FigureRow(edition, figure, title, body_system, code_lo, code_hi, codes_named, anatomy, page: int | None, pdf_page, item_key)` → `drugs.book_figure`. + - `pdf_pages(path) -> list[str]` (pymupdf, imported inside). + - `parse_figures(pages: Sequence[str], *, edition, item_key, anatomy_terms: Sequence[str], grams) -> list[FigureRow]`: + - the running header `(?P<sys>[A-Z][A-Za-z ]+ System)\s+(?P<lo>\d{5})—(?P<hi>\d{5})`, in either order; + - `FIGURE (\d+)-\s*(\d+)\.\s+(?P<title>[^\n]+)`; + - `codes_named` are the 5-digit tokens in the caption up to the first blank line; + - `anatomy` holds the whole-phrase, case-insensitive hits of `anatomy_terms` on the page; + - a title failing `book_text_ok` is stored as `""`. + - `anatomy_vocabulary(con) -> list[str]`: distinct base `body_part` values (Decisions). + - Writers and readers: `write_procedures(con, rows)`, `write_figures(con, item_key, rows)`, `read_procedures(con, *, subject=None)`, `read_figures(con, *, code=None)` (range-aware). + - CLI `stack drugs procedures [--netter] [--check] [--write]`: `--check` verifies each curated cite's paragraph names the first code of its range. + +- [ ] **Step 1: Failing tests** + - `test_curated_procedure_cites_resolve`: an in-memory Store with an `fr_anchors` paragraph naming `15271` under `NHRGIHGD` → the check passes; a paragraph without it → error `"SKIN-SUBSTITUTES: cited paragraph does not name 15271"`. + - `test_route_rule_links`: `J9035` (route INTRAVENOUS) → links to `96413-96417`, not `96365-96368`; `J1234` with route SUBCUTANEOUS → `96372`; a code with no route → none. + - `test_code_route_majority_then_tod`: FDA routes `[IV, IV, SC]` → INTRAVENOUS; no FDA rows and TOD `SC` → SUBCUTANEOUS. + - `test_unknown_family_rejected`: a curated family absent from `pfs.code_family` → a validation error. + - `test_parse_figures_synthetic_pdf`: a two-page PDF built with pymupdf. Page 1 has header `Integumentary System 15271—15278`, `FIGURE 1-12. Skin Graft Site`, caption `"(code 15271)"`, the word `Skin` and the footer `17`. Expect `FigureRow(figure="1-12", title="Skin Graft Site", body_system="Integumentary System", code_lo="15271", code_hi="15278", codes_named="15271", anatomy="Skin", page=17)`. + - `test_figure_long_title_dropped`: a 9-word title → `title == ""`, the row kept. + - `test_anatomy_vocabulary_strips_laterality`: `["Kidney, Right", "Kidney", "Breast, Left"]` → `["Breast", "Kidney"]`. + - `test_roundtrip[product_procedure|book_figure]`. + - CLI: `test_procedures_cli_write`, `test_procedures_cli_check_fails_on_bad_cite`, `test_procedures_cli_netter_write`. +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; the gate; ruff. +- [ ] **Step 5: Live:** run `ENV stack drugs procedures --check`, then `ENV stack drugs procedures --netter --write`. Report links per basis, the codes per procedure family, the figure count (near the ~200 distinct `FIGURE n-m` captions), the figures with no anatomy hit, and the figures covering 15271–15278. +- [ ] **Step 6: Commit** `git add src/drugs/procedures.py src/drugs/netter.py src/drugs/curated.yaml src/drugs/tables.py src/cli/drugs.py tests/drugs/test_procedures.py tests/drugs/test_netter.py tests/drugs/test_tables.py tests/drugs/test_imports.py tests/cli/test_drugs_cli.py && git commit -m "feat(drugs): product-procedure links (skin substitutes, infusion and injection administration) and Netter procedure-anatomy facts"` + +--- + +### Task D12: Codebook page index, `stack drugs show`, drug-lane acceptance + +**Files:** +- Create: `src/drugs/codebook.py`, `tests/drugs/test_codebook.py`. +- Modify: `src/drugs/tables.py`, `src/cli/drugs.py`, `tests/drugs/test_tables.py`, `tests/drugs/test_imports.py`, `tests/cli/test_drugs_cli.py`. + +**Interfaces:** +- Consumes: D2–D11 readers; D10 `BookFile`. +- Produces: + - `CodePageRow(book, edition, system, code, page: int | None, pdf_page: int | None, item_key)` → `drugs.book_code_page`. + - Index functions: + - `index_cm_epub(parts: Sequence[str]) -> list[tuple[str, int]]`: a `div` whose class starts `list-para` and whose first `<b>` text begins with `^[A-Z]\d[0-9A-Z](\.[0-9A-Z]{1,4})?`; the page is the last `<span id="page_N"/>`; dots are removed; the first page per code wins. + - `index_pcs_epub(parts) -> list[tuple[str, int]]`: `div.tfoot-para` text `^[0-9A-HJ-NP-Z]{3}$`. + - `index_pdf(pages: Sequence[str], pattern: re.Pattern) -> list[tuple[str, int | None, int]]`. The printed page is the first standalone integer line among a page's first or last 3 lines. The patterns are CM `^[A-Z]\d[0-9A-Z]\.?[0-9A-Z]{0,4}\b`, PCS `^0[0-9A-Z]{2}\b` and modifiers `^Modifier ([0-9A-Z]{2}):` (lines containing `. . .` leaders are skipped). + - `cross_check(con, book, edition, codes) -> list[str]`: codes in the book but absent from that FY's `drugs.code_title` vintage, as notes recorded in the `zotero:books` gap. + - `show(con, code) -> dict[str, list]`. Keys: `registry`, `asp` (last 8 quarters), `lineage`, `diseases` (top 20), `procedures`, `book_drugs`, `figures`, `pages`, `payment` (entities with attributed amounts). + - CLI: + - `stack drugs books --index [--write]` (extends D10's command); + - `stack drugs show CODE` prints each section, with `none` for an empty one, never a zero. + +- [ ] **Step 1: Failing tests** + - `test_index_cm_epub`: synthetic parts with `<span id="page_514"/>` and `<div class="list-para1a"><b>D50.0<span/>x</b></div>` → `("D500", 514)`. + - `test_index_pcs_epub`: `<div class="tfoot-para">0W1</div>` after `page_673` → `("0W1", 673)`. + - `test_index_pdf_modifiers_skips_toc`: pages `["CHAPTER 2\n43\nModifier 24: x\n", "Modifier 24: x . . . . 23\n"]` → `[("24", 43, 1)]`. + - `test_cross_check_flags_unknown_code`. + - `test_show_sections_never_zero`: an empty DB → every section is `[]`, and the CLI prints `none`. + - `test_roundtrip[book_code_page]`. + - CLI: `test_books_index_write`, `test_show_prints_sections`. +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; the full drug gate; ruff. +- [ ] **Step 5: Live and acceptance:** + 1. Run `ENV stack drugs books --index --write`. Report codes per book edition and the cross-check counts. + 2. Run `ENV stack drugs show Q4101`, `ENV stack drugs show J9035` and `ENV stack drugs show C189`, and paste their section counts. + 3. AMA scan: + - Every text column of every `drugs.*` table is checked with `shares_ama_run` against `cpt_grams` of all `pfs.cpt_code` descriptors, and gives 0 hits. + - `drugs.asp_payment` has 0 rows with `level IN ('I','CDT') AND short_desc <> ''`. + - `drugs.code_title` has no Level I or CDT code. + 4. Every `drugs.product` row with an `entity_key` has a non-empty `entity_item_key`, and a non-empty `xwalk_item_key` or `entity_via = 'curated'`. + 5. `ENV stack market gaps` lists only the expected drug gaps: missing quarters, HCPCS pattern years, ICD vintages and books, each with its note. +- [ ] **Step 6: Commit** `git add src/drugs/codebook.py src/drugs/tables.py src/cli/drugs.py tests/drugs/test_codebook.py tests/drugs/test_tables.py tests/drugs/test_imports.py tests/cli/test_drugs_cli.py && git commit -m "feat(drugs): codebook page index for ICD-10-CM/PCS and modifiers, stack drugs show, AMA scan clean"` + +--- + +### Task D13 (market lane): `universe()` admits product evidence + +**Files:** +- Modify: `src/market/tiingo.py`, `tests/market/test_tiingo.py`. + +**Interfaces:** +- Consumes: D6 `drugs.tables.read_latest_payment` (imported inside `universe`; a missing table gives `{}`); `market.tables.read_links(con, basis="asp")`. +- Produces in `market.tiingo`: + - `ASP_MIN_PAYMENT = 10_000_000.0`, `ASP_MIN_SHARE = 0.01`. + - `asp_qualifies(payment: float | None, share: float | None) -> bool`. + - `universe(...)` gains a fourth tier after the fts tier: entities with at least one `asp` link whose latest payment row qualifies, ranked by `attributed_allowed` (descending) and then key. The common-share rule, the supported list, `used` and `cap` apply unchanged. An entity already ranked is skipped. + +- [ ] **Step 1: Failing tests** + - `test_universe_admits_asp_entity_on_payment`: an entity with only an `asp` link and $12M → present after the fts entities. + - `test_universe_asp_below_threshold_absent`: $9M and no share → absent. + - `test_universe_asp_share_admits_small_payment`: $2M with share 0.02 → present. + - `test_universe_asp_tier_after_fts_and_capped`: `cap` counts asp symbols; an entity in both tiers appears once, at its fts rank. + - `test_universe_without_drugs_tables_unchanged`: no `drugs` schema → the same output as before (the existing universe tests still pass). +- [ ] **Step 2: Run** `tests/market/test_tiingo.py` → FAIL. **Step 3: Implement.** **Step 4: Run** `tests/market tests/cli/test_market_cli.py` → PASS; the market coverage gate; ruff. +- [ ] **Step 5: Live:** run `ENV stack market prices --universe --dry-run` and report the asp-tier symbols (ORGO, MDXG and SNN expected) and the remaining budget. Then run `ENV stack market prices --universe --write` (`.state/market/prices.log`). +- [ ] **Step 6: Commit** `git add src/market/tiingo.py tests/market/test_tiingo.py && git commit -m "feat(market): pharma and device makers price on product evidence (asp basis, Part B payment threshold)"` + +--- + +### Task D14 (market lane, after market Task 12): product event windows and the CY2026 skin-substitute study — `stack drugs events`, `stack market car --product` + +**Files:** +- Create: `src/drugs/events.py`, `tests/drugs/test_events.py`, `tests/drugs/fixtures/fr_pi_2025-13271.json`, `tests/drugs/fixtures/fr_pi_2025-19787.json` (the public FR responses, trimmed). +- Modify: `src/drugs/curated.yaml` (the `events` section), `src/cli/drugs.py`, `src/market/events.py` (vocabularies), `src/market/portfolio.py`, `src/cli/market.py`, `tests/market/test_events.py`, `tests/market/test_portfolio.py`, `tests/cli/test_market_cli.py`, `tests/cli/test_drugs_cli.py`, `tests/drugs/test_imports.py`. + +**Interfaces:** +- Consumes: + - market Task 10: `MarketEvent`, `release`, `day0`, `FR_PI`, the PI cache `data/market/fr/pi/<doc>.json`, and the `market.event` writer and reader Task 10 adds to `market.tables` (use the names in its commit); + - market Task 12: `members`, `run_events`, `write_cars`; + - D5 (`read_groups`, `EventEntry`), D7 (`read_code_events`). +- Produces: + - `market.events`: the scope vocabulary gains `"product"`, and the kind vocabulary gains `"code-reclass"`. + - `drugs.events`: + - `rule_events_for(entries: Sequence[EventEntry], pi: Mapping[str, dict], pubs: Mapping[str, date]) -> list[MarketEvent]` gives scope `product`, target = the group, `event_id = f"{kind}:{doc}:{group}"`, and `item_key`/`p_id` from the entry. The note is the entry's one-line policy label (planner text, not FR text). + - `reclass_events(code_events, groups) -> list[MarketEvent]` gives kind `code-reclass`, precision `day`, `event_date = released`, `event_id = f"code-reclass:{group}:{vintage}"` and `note = f"{n} codes: {kinds}"`. PART-B-DRUGS is excluded, and so are events without `released`. + - The curated `events` entries (bib keys verified in the stack): + + | Group | Proposed | Final | + |---|---|---| + | SKIN-SUBSTITUTES | `2025-13271` (2KVJ2HKX) | `2025-19787` (NHRGIHGD) | + | BIOSIMILARS | `2015-16875` (VZW3HXDA), `2017-14639` (2ME9SJ46) | `2015-28005` (3WCV3349), `2017-23953` (73DU6WUG) | + | PART-B-DRUGS | `2018-14985` (CWGP3WJG) | `2018-24170` (9V89NVZG) | + + Each entry records the `p_id` of the paragraph stating the policy. Validation: the paragraph contains `skin substitute`, `biosimilar`, or `wholesale acquisition cost`, respectively. + - `market.portfolio.members` accepts scope `product`. `strict` keeps `curated`, `revenue_exposure` and `sole`. + - `stack market car` gains `--product KEY`: product events and product-linked members. + - CLI `stack drugs events [--write]` fetches missing PI records and writes the product events. Refusals go to `fr:drug-events`; it clears `fr:drug-events`. + +- [ ] **Step 1: Failing tests** + - `test_skin_sub_events_day0`: with the fixtures, + - `2025-13271` → `event_date == date(2025,7,14)`, `after_close is True`, and `day0` on a calendar holding 2025-07-14 and 2025-07-15 → `date(2025,7,15)`; + - `2025-19787` → `date(2025,10,31)`, after close, and `day0` → `date(2025,11,3)` (Friday to Monday). + - `test_rule_events_scope_product`: `event_id == "rule-final:2025-19787:SKIN-SUBSTITUTES"`, scope `product`, target `SKIN-SUBSTITUTES`. + - `test_curated_event_paragraph_check`: a cited paragraph lacking `skin substitute` → a validation error. + - `test_reclass_events_group_and_stamp`: 3 SKIN-SUBSTITUTES codes added in vintage `2026-01` released 2025-11-20 → one event dated 2025-11-20, note `"3 codes: added"`; PART-B-DRUGS gives none. + - `test_members_product_scope` (in `test_portfolio.py`): ORGO and MDXG `asp` links to SKIN-SUBSTITUTES → members on 2025-07-15; a `shared` link is dropped with `strict=True`. + - `test_car_cli_product` (in `test_market_cli.py`): `--product SKIN-SUBSTITUTES` uses only product events and writes CarRows with `unit="portfolio:product:SKIN-SUBSTITUTES"`. + - `test_events_cli_write` and `test_events_cli_refusal_gap` (in `test_drugs_cli.py`). +- [ ] **Step 2: Run** `tests/drugs/test_events.py tests/market/test_portfolio.py tests/cli/test_market_cli.py tests/cli/test_drugs_cli.py` → FAIL. **Step 3: Implement.** **Step 4: Run** `tests/drugs tests/market tests/cli/test_market_cli.py tests/cli/test_drugs_cli.py` → PASS; both coverage gates; ruff. +- [ ] **Step 5: Live, the first study:** + - Run `ENV stack drugs events --write`. + - If ORGO, MDXG or SNN lack prices: `ENV stack market prices --ticker ORGO --ticker MDXG --ticker SNN --write`. + - Run `ENV stack market car --product SKIN-SUBSTITUTES --kind rule-proposed --kind rule-final --window -1,1 --window 0,1 --window -5,5 --write`. + - Report: + - per event (day 0 2025-07-15 and 2025-11-03), each firm's CAR(−1,1) with its CI, the portfolio CAR, and the pooled row; + - n_est and caveats; + - the earnings-in-window flags: MDXG and ORGO file 8-Ks; SNN files 6-Ks, which the 8-K Item 2.02 check cannot see, and this is reported as a caveat. + - Derived analytics may be shown inside the stack (D5); raw prices never leave it. + - Run the full gate: `uv run --no-sync pytest tests/ -x --cov=src --cov-report=term-missing --cov-fail-under=99 -q -n auto -p no:cacheprovider` → PASS. +- [ ] **Step 6: Commit** `git add src/drugs/events.py src/drugs/curated.yaml src/cli/drugs.py src/market/events.py src/market/portfolio.py src/cli/market.py tests/drugs/test_events.py tests/drugs/fixtures/fr_pi_2025-13271.json tests/drugs/fixtures/fr_pi_2025-19787.json tests/drugs/test_imports.py tests/market/test_events.py tests/market/test_portfolio.py tests/cli/test_market_cli.py tests/cli/test_drugs_cli.py && git commit -m "feat(market): product event windows (ASP methodology rules, HCPCS reclassifications) and the CY2026 skin-substitute flat-rate study"` + +--- + +## Self-review (planner) + +- **Spec coverage:** + - ASP payment files, all codes and every quarter, with not-payable files kept: D2; + - CPT short descriptors never stored: D2, D3, D9 and the D12 scan; + - crosswalks: D3; the FDA NDC Directory, Orange Book and Purple Book: D4; + - registry with cited hops and the skin-subs seed: D5; + - quarterly payment per code: D2; the payment share: D6; + - HCPCS lineage: D7; ICD lineage: D8; + - MCD product → disease: D9; + - product → procedure, curated: D11; + - Table of Drugs: D10; Netter: D11; the ICD codebooks and *Coding with Modifiers*: D12 (page index only); + - the `asp` basis: D6; price admission: D13; event windows and the first study: D14; + - skin subs kept as a consumer: D2 parity and the notebook run. +- **Gaps stated rather than built:** + - Part B drug spending billed by hospital outpatient departments (not in `pfs.utilization`; CMS's "Part B Spending by Drug" dataset would add it); + - historical NDC labelers beyond the CMS crosswalks; + - ICD-10-CM codebooks other than 2018, 2020, 2022 and 2025, and ICD-10-PCS codebooks other than 2019 and 2022 (no true file); + - HCPCS Level II books other than 2019 (catalog stubs only); + - HCPCS quarterly files before 2017; + - LCD-level coverage events; + - statutory events (IRA biosimilar ASP + 8%, discarded-drug refunds), which have no FR document to date them; + - SNN's 6-K earnings days. +- **Pre-existing finding, not fixed here (it belongs to the skin-subs consumer):** the tracked `data/cms/skin_substitute_hcpcs_reference.csv` stores CPT short descriptors for 15271–15278 (AMA text in the repo), and `skin_subs.hcpcs_reference` serves them. This tier never reads that column. A scrub needs its own issue, so the skin notebooks keep working. +- **Names:** + - `CodeEventRow`/`TitleRow` are defined in D7 and reused in D8. + - `EventEntry`/`ProcedureEntry` are defined in D5 (curated loader) and used in D11 and D14. + - `read_latest_payment` is defined in D6 and used in D13. + - `book_text_ok` and `BookFile` are defined in D10 and used in D11 and D12. + - `newest_per_quarter` and `read_table` are defined in D2 and used in D3 and the dev script. + - `MarketEvent`, `release`, `day0`, `members` and `run_events` are market Tasks 10 and 12's names, consumed only in D14. +- **Review Focus:** each of the five lines has its pinned tests in the named owning tasks.