diff --git a/dev/scripts/dossier_page/build.py b/dev/scripts/dossier_page/build.py index 8324f71..3b58e5b 100644 --- a/dev/scripts/dossier_page/build.py +++ b/dev/scripts/dossier_page/build.py @@ -1,826 +1,48 @@ -"""Build the lex dossier page (HOME-VISITS): a static snapshot, data inlined. +"""Build the lex app shell page: the fhirworx design system inlined, no data. -lex (Latin for law) is the legal-epidemiology workbench. The page is served -by Gitea from its bind-mounted custom directory at ``lex./`` -(Traefik routers ``lex*``, behind ``git-sso``; the old address -``git./dossier`` redirects there; see -infra/traefik/dynamic/services.yml). Run from the primary checkout, -never a worktree (the replica and bib.sqlite live in its data/): +lex (Latin for law) is the legal-epidemiology workbench at ``lex.``. +Gitea serves this page from its bind-mounted custom directory (Traefik +routers ``lex*``, behind ``git-sso``; see infra/traefik/dynamic/services.yml). +The page carries no data: ``app.js`` and the other ES modules next to it in +``infra/gitea/custom/public/assets/dossier/`` load the stored dossiers from +the policy API (``/api/policy/…``, lex S1 D2/D5) and render each view. - bash -c 'cd /home/kert/stack && set -a && . ./.env && set +a && \ - uv run --no-sync python -I dev/scripts/dossier_page/build.py' + uv run --no-sync python -I dev/scripts/dossier_page/build.py [--out PATH] -Reads the DuckDB replica and bib.sqlite read-only, and the public -regulations.gov mirror (Mirrulations, AWS Open Data) for submitter names -(public record). Writes nothing to any database. Writes one complete HTML -document (template.html with the data inlined) to --out, by default -infra/gitea/custom/public/assets/dossier/index.html (gitignored: the data -is rebuilt, never committed). --json also writes the raw data. +Writes one HTML document (template.html, filled) to --out, by default the +served page infra/gitea/custom/public/assets/dossier/index.html (gitignored), +atomically, and prints ``wrote ( bytes) v=``. Stdlib only: +it reads no database. -Design: lex is a fhirworx (HTI-5) page built from the system's sources, so -it follows them on every rebuild. The page inlines assets/css/fhirworx.css -(palette, fonts, base classes), the fhirworx dark palette from the Gitea -theme (infra/gitea/theme/theme-fhirworx-dark.css) mapped onto the same token -names (opt-in, as in Gitea), the logo (assets/icons/logo.svg, as an SVG -symbol) and the favicon set (assets/icons). The template uses only those -tokens. +Design (R85): lex is a fhirworx (HTI-5) page built from the system's sources, +so it follows them on every rebuild. The page inlines assets/css/fhirworx.css +(palette, fonts, base classes), the fhirworx dark palette from the Gitea theme +(infra/gitea/theme/theme-fhirworx-dark.css) mapped onto the same token names +(opt-in, as in Gitea), the logo (assets/icons/logo.svg, as an SVG symbol) and +the favicon set (assets/icons). The template uses only those tokens. -AMA license: CPT descriptors never ship. The RVU-file short descriptors -are not read at all, and descriptor_change events carry a fixed note in -place of the RVU-file text. +Cache: ``/*__VERSION__*/`` is the first 12 hex digits of a sha256 over the +sorted (name, bytes) of the ``*.js`` modules, stamped on the entry script +(``app.js?v=…``), so a new module set is a new URL; the modules it imports +revalidate through the ``dossier-nocache`` middleware. """ from __future__ import annotations import argparse import base64 +import hashlib import html -import json import os import re -import sqlite3 import sys -from concurrent.futures import ThreadPoolExecutor -from datetime import datetime from pathlib import Path -import duckdb - -from bib import cfrlink, frlink -from bib.regulations_gov import Mirror -from pfs.commenters import _COMMENT_ID -from pfs.descriptors import rule_year_of -from pfs.families import curated_family -from pfs.rules import RULES, proposed_for -from pfs.valuation import ( - _PROPOSED_SQL, - _pay, - _sum, - final_cf_note, - proposed_cf_note, - valuation, -) - HERE = Path(__file__).resolve().parent ROOT = HERE.parents[2] -DOMAIN = os.environ.get("DOMAIN", "fhirworx.io") -FAMILY = "HOME-VISITS" -DOCKET = "CMS-2022-0113" - -ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) -ap.add_argument( - "--out", - type=Path, - default=ROOT / "infra/gitea/custom/public/assets/dossier/index.html", - help="page to write (default: %(default)s)", -) -ap.add_argument("--json", type=Path, default=None, help="also write the raw data here") -args = ap.parse_args() - -BUILT = datetime.now().astimezone() - -duck = duckdb.connect(str(ROOT / "data/replica/aco.ro.duckdb"), read_only=True) -bibc = sqlite3.connect(f"file:{ROOT / 'data/bib.sqlite'}?mode=ro", uri=True) -bibc.row_factory = sqlite3.Row - - -class ROStore: - """The slice of bib.store.Store that frlink needs, over a read-only - connection (frlink only calls ``_con()``).""" - - def __init__(self, con: sqlite3.Connection) -> None: - self._c = con - - def _con(self) -> sqlite3.Connection: - return self._c - - -store = ROStore(bibc) - -fam = curated_family(FAMILY) -assert fam is not None -BASE = sorted(m.code for m in fam.members if m.role == "base") -PRED = sorted(m.code for m in fam.members if m.role == "predecessor") -LINKED = ["G0318"] -CODES = BASE + PRED -ALL_CODES = CODES + LINKED - -# ── sources and citations ─────────────────────────────────────────── - -SOURCES: dict[str, dict] = {} -PARAS: dict[str, str] = {} - - -def item(key: str) -> dict | None: - if not key: - return None - if key in SOURCES: - return SOURCES[key] - r = bibc.execute( - "SELECT key, item_type, title, url, date_published, institution FROM items WHERE key = ?", - (key,), - ).fetchone() - if r is None: - return None - src = { - "key": r["key"], - "type": r["item_type"], - "title": r["title"], - "url": r["url"] or "", - "date": r["date_published"] or "", - "publisher": r["institution"] or "", - } - doc = bibc.execute( - "SELECT document_number, html_url, fr_volume, start_page, end_page FROM fr_anchor_docs WHERE item_key = ?", - (key,), - ).fetchone() - if doc is not None: - src["fr"] = { - "doc": doc["document_number"], - "html": doc["html_url"], - "vol": doc["fr_volume"], - "start": doc["start_page"], - "end": doc["end_page"], - } - src["kind"] = frlink.rule_kind(store, key, title=r["title"]) - src["cy"] = rule_year_of(r["title"], r["date_published"] or "") - src["label"] = f"CY{src['cy']} PFS {src['kind']} rule" - src["cite"] = f"{doc['fr_volume']} FR {doc['start_page']}" - SOURCES[key] = src - return src - - -def fr_cite(key: str, p_id: int | None = None, page: int | None = None) -> dict | None: - """A Federal Register jump link: paragraph anchor via frlink.resolve, - else a printed-page link. Label "87 FR 69608 ¶1676" (¶ = paragraph - anchor id, as the dossier spec cites it).""" - src = item(key) - if src is None or "fr" not in src: - return None - vol = src["fr"]["vol"] - if p_id: - try: - link = frlink.resolve(f"p-{p_id}", store=store, item_key=key) - except ValueError: - link = None - if link is not None: - PARAS.setdefault(f"{key}:{p_id}", excerpt(para_text(key, p_id), "", 520)) - return { - "k": key, - "p": p_id, - "pg": link.page, - "label": f"{vol} FR {link.page} ¶{p_id}", - "url": link.url, - } - if page: - return { - "k": key, - "p": 0, - "pg": page, - "label": f"{vol} FR {page}", - "url": f"{src['fr']['html']}#page-{page}", - } - return { - "k": key, - "p": 0, - "pg": src["fr"]["start"], - "label": src["cite"], - "url": src["fr"]["html"], - } - - -def para_text(key: str, p_id: int) -> str: - r = bibc.execute( - "SELECT text FROM fr_anchors WHERE item_key = ? AND p_id = ?", (key, p_id) - ).fetchone() - return " ".join((r["text"] or "").split()) if r else "" - - -_SENT = re.compile(r"(?<=[.;:!?])\s+(?=[A-Z(“\"])") - - -def excerpt(text: str, kw: str = "", maxlen: int = 420) -> str: - """Verbatim: from the sentence containing *kw* (or the start), cut at a - word boundary near *maxlen*.""" - if not text: - return "" - if kw: - i = text.lower().find(kw.lower()) - if i > 0: - starts = [0] + [m.end() for m in _SENT.finditer(text)] - s = max(x for x in starts if x <= i) - text = ("… " if s else "") + text[s:] - if len(text) <= maxlen: - return text - cut = text[:maxlen].rsplit(" ", 1)[0].rstrip(",;:") - return cut + " …" - - -def keep_para(key: str, p_id: int, kw: str = "", maxlen: int = 520) -> str: - t = excerpt(para_text(key, p_id), kw, maxlen) - if t: - PARAS[f"{key}:{p_id}"] = t - return t - - -# ── membership and links ──────────────────────────────────────────── - -members = [] -for m in fam.members: - c = fr_cite(m.item_key, m.p_id) if m.item_key else None - members.append( - { - "code": m.code, - "role": m.role, - "since": m.since, - "until": m.until, - "cite": c, - "rvu_year": m.rvu_year or None, - } - ) -links = [] -for ln in fam.links: - links.append( - { - "kind": ln.kind, - "target": ln.target, - "since": ln.since, - "cite": fr_cite(ln.item_key, ln.p_id), - "aliases": list(ln.aliases), - "alias_cite": fr_cite(ln.alias_item_key, ln.alias_p_id) - if ln.alias_item_key - else None, - } - ) - keep_para(ln.item_key, ln.p_id, maxlen=360) - if ln.alias_item_key: - keep_para(ln.alias_item_key, ln.alias_p_id, maxlen=300) -keep_para("PETM225D", 1672, maxlen=520) - -# ── valuation rounds ──────────────────────────────────────────────── - -rounds = [] -for r in duck.execute( - """SELECT code, rule_year, item_key, rule_kind, p_id, page, source, table_title, - ruc_work_rvu, ruc_percentile, survey_intra_min, survey_total_min, - requested_work_rvu, proposed_work_rvu, final_work_rvu, decision, - rationale_p_id, rationale_quote, pe_note, extractor, final_p_id, ruc_p_id, field_cites - FROM pfs.valuation_round WHERE family = ? ORDER BY rule_year, code, rule_kind""", - [FAMILY], -).fetchall(): - ( - code, - ry, - key, - kind, - p_id, - page, - source, - ttitle, - ruc, - pct, - intra, - total, - req, - prop, - fin, - dec, - rat_p, - rat_q, - pe_note, - extractor, - fin_p, - ruc_p, - field_cites, - ) = r - fc = json.loads(field_cites or "{}") - cites = {} - for field, v in fc.items(): - if isinstance(v, list): - cites[field] = [fr_cite(key, int(x)) for x in v] - elif isinstance(v, str) and v.startswith("page:"): - cites[field] = [fr_cite(key, None, int(v.split(":")[1]))] - elif v: - cites[field] = [fr_cite(key, int(v))] - rounds.append( - { - "code": code, - "cy": ry, - "key": key, - "kind": kind, - "source": source, - "table": ttitle or "", - "ruc": ruc, - "pct": pct or "", - "intra": intra, - "total": total, - "req": req, - "prop": prop, - "fin": fin, - "decision": dec, - "quote": rat_q or "", - "pe_note": pe_note or "", - "extractor": extractor, - "cite": fr_cite(key, p_id or None, page or None), - "cites": cites, - } - ) -for k, p, kw, n in [ - ("PETM225D", 1676, "The RUC recommended the survey 25th", 420), - ("PETM225D", 1685, "", 300), - ("MZ24MX5S", 878, "", 160), - ("MZ24MX5S", 877, "", 420), - ("54GTKR5G", 2241, "", 520), - ("54GTKR5G", 2242, "", 260), -]: - keep_para(k, p, kw, n) - -# ── origins ───────────────────────────────────────────────────────── - -origins = [] -groups: dict[tuple, dict] = {} -for r in duck.execute( - """SELECT kind, reference, year, cite_kind, item_key, p_id, page_label, locator, extractor, ref_p_id, - summary, code - FROM pfs.code_origin WHERE family = ? - ORDER BY kind, year NULLS LAST, reference, code""", - [FAMILY], -).fetchall(): - ( - kind, - ref, - year, - ck, - key, - p_id, - page_label, - locator, - extractor, - ref_p, - summary, - code, - ) = r - gk = (kind, ref, year, ck, key, p_id, page_label) - g = groups.get(gk) - if g is None: - cite = ( - fr_cite(key, p_id) - if (ck in ("fr_para", "iom", "cfr") and key and p_id) - else None - ) - book = None - if ck == "cpt_book": - src = item(key) - book = { - "key": key, - "title": src["title"] if src else key, - "page": page_label, - } - target = None - if ck == "cfr": - try: - c = cfrlink.parse_cite(ref) - target = {"label": cfrlink.canonical(c), "url": cfrlink.url(c)} - except ValueError: - target = None - g = groups[gk] = { - "kind": kind, - "ref": ref, - "year": year, - "cite_kind": ck, - "cite": cite, - "book": book, - "target": target, - "extractors": [], - "codes": [], - "summaries": {}, - "ref_cite": fr_cite(key, ref_p) if (ref_p and ck != "cpt_book") else None, - } - g["codes"].append(code) - if extractor not in g["extractors"]: - g["extractors"].append(extractor) - g["summaries"].setdefault(summary or "", []).append(code) -for g in groups.values(): - sums = g.pop("summaries") - # per-code templated summaries ("... for 99324 points to ...") say nothing - # the reference does not; keep a summary only when few distinct ones exist - g["summaries"] = ( - [{"text": t, "codes": c} for t, c in sums.items() if t] - if len(sums) <= 2 - else [] - ) - g["n_rows"] = len(g["codes"]) - g["codes"] = sorted(set(g["codes"])) - origins.append(g) - -# ── lineage events ────────────────────────────────────────────────── - -events = [] -review_rows = [] -for r in duck.execute( - """SELECT year, kind, source, item_key, p_id, page, from_codes, to_codes, note, - string_agg(code, ',' ORDER BY code) AS codes - FROM pfs.code_event WHERE code IN (SELECT unnest(?)) - GROUP BY ALL ORDER BY year, kind""", - [ALL_CODES], -).fetchall(): - year, kind, source, key, p_id, page, fcodes, tcodes, note, codes = r - ev = { - "year": year, - "kind": kind, - "source": source, - "codes": codes.split(","), - "from": fcodes or "", - "to": tcodes or "", - # AMA license: RVU-file short descriptors are CPT text; never ship them. - "note": ( - "Short descriptor revised in the RVU file (AMA text not reproduced)" - if kind == "descriptor_change" - else (note or "") - ), - } - if source == "fr": - ev["cite"] = fr_cite(key, p_id, page) - text = para_text(key, p_id) - if ev["codes"] == ["G0318"] and year < 2023 and "ESRD" in text: - # G0318 named a different (ESRD) service before CY2023: keep it off - # the family timeline; it is a real row for the review queue sketch. - review_rows.append( - { - "what": f"lineage event: {kind} {codes} CY{year}", - "cite": ev["cite"], - "quote": excerpt(text, "G0318", 260), - "why": "The cited paragraph uses G0318 for an ESRD service, before the code numbered the CY2023 prolonged home visit add-on.", - } - ) - continue - elif source == "cpt": - src = item(key) - ev["book"] = {"key": key, "title": src["title"] if src else key} - elif source == "rvu": - rule = RULES.get(int(year)) - ev["rvu"] = { - "label": f"PFS CY{year} Addendum B (RVU file)", - "cite": rule.federal_register_citation if rule else "", - "url": f"https://www.federalregister.gov/citation/{rule.federal_register_citation.replace(' ', '-')}" - if rule - else "", - } - events.append(ev) -for k, p in [ - ("2AZVKTCE", 2404), - ("PETM225D", 1694), - ("PETM225D", 390), - ("PETM225D", 497), -]: - keep_para(k, p, maxlen=300) - -# ── CMS's own comment summaries ───────────────────────────────────── - -summaries = [] -for r in duck.execute( - """SELECT item_key, rule_year, rule_kind, comment_p_id, response_p_id, codes, quantifier, stance, - response_action, extractor - FROM pfs.cms_comment_summary WHERE family = ? ORDER BY rule_year, comment_p_id""", - [FAMILY], -).fetchall(): - key, ry, rk, cp, rp, codes, q, st, act, extractor = r - summaries.append( - { - "key": key, - "cy": ry, - "kind": rk, - "q": q, - "stance": st, - "action": act, - "extractor": extractor, - "codes": [c for c in (codes or "").split(",") if c], - "comment": fr_cite(key, cp), - "response": fr_cite(key, rp), - "ctext": excerpt(para_text(key, cp), "", 360), - "rtext": excerpt(para_text(key, rp), "", 260), - } - ) - -# ── commenters (CY2023 docket) + submitter names from the mirror ──── - -commenters = [] -rows = duck.execute( - """SELECT item_key, docket, comment_id, org_name, org_type, specialty, form_group, form_size, basis, - reg_category, extractor - FROM pfs.commenter WHERE family = ? AND docket = ? ORDER BY org_type, specialty, org_name""", - [FAMILY, DOCKET], -).fetchall() -mirror = Mirror() - - -ITEM_URL = ( - { - r["key"]: r["url"] or "" - for r in bibc.execute( - "SELECT key, url FROM items WHERE key IN (%s)" % ",".join("?" * len(rows)), - [r[0] for r in rows], - ).fetchall() - } - if rows - else {} -) - - -def submitter(row) -> dict: - url = ITEM_URL.get(row[0], "") - m = _COMMENT_ID.search(url) - cid = m.group(1) if m else (row[2] or "") - out = { - "cid": cid, - "url": f"https://www.regulations.gov/comment/{cid}" if cid else url, - "first": "", - "last": "", - "org": "", - "posted": "", - "ok": False, - } - if not cid: - return out - for _ in range(3): - try: - a = mirror.get_json(row[1], cid)["data"]["attributes"] - out.update( - first=(a.get("firstName") or "").strip(), - last=(a.get("lastName") or "").strip(), - org=(a.get("organization") or "").strip(), - posted=(a.get("postedDate") or "")[:10], - ok=True, - ) - return out - except Exception as exc: # noqa: BLE001 - out["err"] = type(exc).__name__ - return out - - -with ThreadPoolExecutor(8) as pool: - subs = list(pool.map(submitter, rows)) -for row, sub in zip(rows, subs, strict=True): - key, docket, cid, org, otype, spec, fg, fs, basis, regcat, extractor = row - commenters.append( - { - "key": key, - "cid": sub["cid"] or cid, - "url": sub["url"], - "org": org or "", - "type": otype or "", - "specialty": spec or "", - "form_group": fg or "", - "form_size": fs or 0, - "basis": basis or "", - "reg_category": regcat or "", - "extractor": extractor, - "name": " ".join(x for x in (sub["first"], sub["last"]) if x), - "reg_org": sub["org"], - "posted": sub["posted"], - "mirror_ok": sub["ok"], - } - ) - -stances = [ - { - "key": k, - "event": e, - "stance": s, - "reason": r or "", - "evidence": ev or "", - "extractor": x, - } - for k, e, s, r, ev, x in duck.execute( - """SELECT item_key, event_key, stance, reason, evidence, extractor FROM pfs.comment_stance - WHERE family = ? AND docket = ? ORDER BY event_key, stance, item_key""", - [FAMILY, DOCKET], - ).fetchall() -] - -reaction = [] -for r in duck.execute( - """SELECT period, period_kind, year, n_items, n_total, stance_support, stance_oppose, stance_modify, - stance_unclear, n_classified, n_commenters, events_json, stance_method, stance_eval - FROM pfs.code_reaction WHERE family = ? ORDER BY year, period""", - [FAMILY], -).fetchall(): - period, pk, year, ni, nt, s_sup, s_opp, s_mod, s_unc, ncl, ncm, ej, smeth, seval = r - d = {"period": period, "pk": pk, "year": year, "n": ni, "total": nt} - if pk == "docket": - dk = bibc.execute( - "SELECT rule_cms_id, comment_end_date FROM dockets WHERE id = ?", (period,) - ).fetchone() - if dk: - d["rule"] = dk["rule_cms_id"] or "" - d["close"] = dk["comment_end_date"] or "" - d["url"] = f"https://www.regulations.gov/docket/{period}" - else: - d["cite"] = fr_cite(period) - if ncm is not None: - d.update( - support=s_sup, - oppose=s_opp, - modify=s_mod, - unclear=s_unc, - classified=ncl, - commenters=ncm, - events=json.loads(ej or "{}"), - method=smeth, - eval=json.loads(seval) if seval else None, - ) - reaction.append(d) - -# ── guidance pointers ─────────────────────────────────────────────── - -guidance = [] -for r in duck.execute( - """SELECT kind, locator, item_key, item_key_src, p_id_src, page_src, page, - string_agg(code, ',' ORDER BY code) AS codes - FROM pfs.code_guidance WHERE family = ? GROUP BY ALL ORDER BY kind, locator, item_key_src""", - [FAMILY], -).fetchall(): - kind, loc, key, ksrc, psrc, pgsrc, page, codes = r - tgt = item(key) if key else None - turl = "" - if kind == "cfr" and key: - try: - turl = cfrlink.url(cfrlink.parse_cite(loc)) - except ValueError: - turl = tgt["url"] if tgt else "" - elif tgt: - turl = tgt["url"] + (f"#page={page}" if page else "") - g = { - "kind": kind, - "locator": loc, - "target": {"title": tgt["title"], "url": turl} if tgt else None, - "src": fr_cite(ksrc, psrc), - "page": page or None, - "codes": codes.split(","), - } - if not key: - review_rows.append( - { - "what": f"guidance pointer: {loc}", - "cite": g["src"], - "quote": "", - "why": "The locator did not resolve to a regulation in the library. The same paragraph is also cited for 42 CFR 425.400(c)(1)(vi).", - } - ) - g["unresolved"] = True - guidance.append(g) - -# ── payment: final (pfs.rvu) and proposed (pfs.rvu_proposed), never blended ── - -pay_rows, missing = valuation(duck, ALL_CODES, years=40) -payment = [ - { - "code": p.code, - "cy": p.year, - "proposed": p.proposed, - "status": p.status, - "work": p.work, - "pe_nf": p.pe_nf, - "mp": p.mp, - "total_nf": p.total_nf, - "cf": p.cf, - "pay_nf": p.pay_nf, - "cite": p.citation, - "url": p.url, - "label": p.label, - "status_note": p.status_note, - } - for p in pay_rows -] -have = {(p["code"], p["cy"], p["proposed"]) for p in payment} -for cy in sorted(RULES): - prop = proposed_for(cy) - if prop is None: - continue - for hcpcs, desc, status, work, pe_nf, pe_f, mp in duck.execute( - _PROPOSED_SQL, [prop.cms_rule_id, ALL_CODES] - ).fetchall(): - if (hcpcs, cy, True) in have: - continue - tot = _sum(work, pe_nf, mp) - payment.append( - { - "code": hcpcs, - "cy": cy, - "proposed": True, - "status": status or "", - "work": work, - "pe_nf": pe_nf, - "mp": mp, - "total_nf": tot, - "cf": prop.conversion_factor, - "pay_nf": _pay(tot, prop.conversion_factor, status or ""), - "cite": prop.federal_register_citation, - "url": f"https://www.federalregister.gov/citation/{prop.federal_register_citation.replace(' ', '-')}", - "label": f"[CY{cy} NPRM Addendum B]", - "status_note": "", - } - ) -payment.sort(key=lambda p: (p["code"], p["cy"], p["proposed"])) -cfs = [] -for cy in sorted(RULES): - rule = RULES[cy] - cfs.append( - { - "cy": cy, - "proposed": False, - "cf": rule.conversion_factor, - "note": final_cf_note(rule), - "cite": rule.federal_register_citation, - } - ) - prop = proposed_for(cy) - if prop is not None: - cfs.append( - { - "cy": cy, - "proposed": True, - "cf": prop.conversion_factor, - "note": proposed_cf_note(prop), - "cite": prop.federal_register_citation, - } - ) - -# ── utilization (national services, all places of service) ───────── - -util = [] -for year, hcpcs, svc, benes, key in duck.execute( - """SELECT year, hcpcs, sum(n_services), sum(n_beneficiaries), any_value(item_key) - FROM pfs.utilization WHERE hcpcs IN (SELECT unnest(?)) GROUP BY 1, 2 ORDER BY 2, 1""", - [ALL_CODES], -).fetchall(): - item(key) - util.append({"cy": year, "code": hcpcs, "services": svc, "key": key}) - -# AMA license: no RVU-file short descriptors (CPT text) are read or shipped. - -for k in ["3ANRT854", "GQGTPGYV", "T6H4ZPEQ"]: - item(k) - -n_fam, n_single = duck.execute( - "SELECT count(*), count(*) FILTER (WHERE n = 1) FROM (SELECT key, count(DISTINCT code) AS n FROM pfs.code_family GROUP BY key)" -).fetchone() - -data = { - "meta": { - "derived_families": n_fam, - "derived_single": n_single, - "built": BUILT.isoformat(timespec="seconds"), - "family": FAMILY, - "name": fam.name, - "docket": DOCKET, - "base": BASE, - "pred": PRED, - "linked": LINKED, - "rvu_years": [min(p["cy"] for p in payment), max(p["cy"] for p in payment)], - "util_years": [min(u["cy"] for u in util), max(u["cy"] for u in util)] - if util - else None, - "missing_payment": missing, - }, - "members": members, - "links": links, - "rounds": rounds, - "origins": origins, - "events": events, - "summaries": summaries, - "commenters": commenters, - "stances": stances, - "reaction": reaction, - "guidance": guidance, - "payment": payment, - "cfs": cfs, - "util": util, - "review": review_rows, - "paras": PARAS, - "sources": SOURCES, -} -blob = json.dumps(data, ensure_ascii=False, separators=(",", ":")) -if args.json: - args.json.write_text(blob, encoding="utf-8") - print(f"wrote {args.json} ({args.json.stat().st_size:,} bytes)", file=sys.stderr) - - -def _fill(tpl: str, marker: str, value: str, count: int = 1) -> str: - if tpl.count(marker) != count: - raise SystemExit( - f"template.html: expected {count} {marker!r}, found {tpl.count(marker)}" - ) - return tpl.replace(marker, value) - - -# ── the fhirworx design system, from its sources ────────────────────────── -FHIRWORX_CSS = ( - ROOT / "assets/css/fhirworx.css" -) # single source of truth for the palette -GITEA_DARK = ( - ROOT / "infra/gitea/theme/theme-fhirworx-dark.css" -) # the system's dark palette +ASSETS = ROOT / "infra/gitea/custom/public/assets/dossier" +FHIRWORX_CSS = ROOT / "assets/css/fhirworx.css" # single source of the palette +GITEA_DARK = ROOT / "infra/gitea/theme/theme-fhirworx-dark.css" # the dark palette ICONS = ROOT / "assets/icons" # fhirworx.css token -> the Gitea fhirworx-dark variable that plays the same @@ -859,6 +81,45 @@ DARK_ROLES = { "chart-5": "--fw-chart-5", } +#: navbar links back to Gitea, the masthead and footer address, the +#: dashboard link +DOMAIN_FILLS = 5 +#: the entry script and the footer +VERSION_FILLS = 2 + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) + ap.add_argument( + "--out", + type=Path, + default=ASSETS / "index.html", + help="page to write (default: %(default)s)", + ) + return ap.parse_args(argv) + + +def _fill(tpl: str, marker: str, value: str, count: int = 1) -> str: + if tpl.count(marker) != count: + raise SystemExit( + f"template.html: expected {count} {marker!r}, found {tpl.count(marker)}" + ) + return tpl.replace(marker, value) + + +def module_version(directory: Path) -> str: + """sha256 over the sorted (name, bytes) of the directory's ``*.js``, [:12].""" + files = sorted(p for p in Path(directory).glob("*.js") if p.is_file()) + if not files: + raise SystemExit(f"{directory}: no *.js modules") + h = hashlib.sha256() + for p in files: + data = p.read_bytes() + name = p.name.encode() + h.update(len(name).to_bytes(4, "big") + name) + h.update(len(data).to_bytes(8, "big") + data) + return h.hexdigest()[:12] + def _root_vars(path: Path) -> dict[str, str]: """Custom properties of the stylesheet's first :root block (raw values).""" @@ -912,41 +173,41 @@ def _logo_symbol() -> str: return f'' -fw_css = FHIRWORX_CSS.read_text(encoding="utf-8") -if "") +def build_page(domain: str, version: str) -> str: + fw_css = FHIRWORX_CSS.read_text(encoding="utf-8") + if "") + page = (HERE / "template.html").read_text(encoding="utf-8") + page = _fill(page, "/*__FHIRWORX_CSS__*/", fw_css) + page = _fill(page, "/*__FHIRWORX_DARK__*/", _dark_palette()) + page = _fill(page, "", _logo_symbol()) + page = _fill( + page, "/*__FAVICON_SVG__*/", _data_uri(ICONS / "favicon.svg", "image/svg+xml") + ) + page = _fill( + page, "/*__FAVICON_PNG__*/", _data_uri(ICONS / "fav32.png", "image/png") + ) + page = _fill( + page, + "/*__APPLE_TOUCH_ICON__*/", + _data_uri(ICONS / "apple-touch-icon.png", "image/png"), + ) + page = _fill(page, "/*__DOMAIN__*/", html.escape(domain), count=DOMAIN_FILLS) + return _fill(page, "/*__VERSION__*/", version, count=VERSION_FILLS) -# Inline the data into the page. Every "<" in the JSON is escaped so no -# string in it can close or confuse the - + + diff --git a/dev/scripts/lex_dump_api.py b/dev/scripts/lex_dump_api.py new file mode 100644 index 0000000..9ce8295 --- /dev/null +++ b/dev/scripts/lex_dump_api.py @@ -0,0 +1,84 @@ +"""Dump one family's policy API slices to files, for the probe's fixture mode. + + bash -c 'cd /home/kert/stack && set -a && . ./.env && set +a && \\ + uv run --no-sync python dev/scripts/lex_dump_api.py --family HOME-VISITS --out DIR' + +Reads through ``llm.policy``'s in-process seam (``load_slice``, +``load_contents``, ``load_fact``: the same bytes the API serves) and writes + + DIR/contents.json + DIR/dossier/
.json every section, the facts index included + DIR/fact/.json every fact the index lists + +``dev/scripts/lex_probe.py --fixture DIR`` serves these to a real Chromium in +place of the API (lex S1 D13). Read-only: it writes nothing but DIR. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any, Callable + +#: llm.policy_slices.SECTIONS (a test keeps the two equal) +SECTIONS = ( + "header", + "timeline", + "valuation", + "payment", + "politics", + "sources", + "facts", +) + + +def _write(path: Path, body: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps(body, ensure_ascii=False, separators=(",", ":")), encoding="utf-8" + ) + + +def dump( + out: Path, + family: str, + *, + load_slice: Callable[[str, str], dict[str, Any]], + load_contents: Callable[[], dict[str, Any]], + load_fact: Callable[[str, str], dict[str, Any]], +) -> dict[str, int]: + _write(out / "contents.json", load_contents()) + slices = {} + for section in SECTIONS: + slices[section] = load_slice(family, section) + _write(out / "dossier" / f"{section}.json", slices[section]) + ids = [f["id"] for f in slices["facts"]["facts"]] + for fid in ids: + _write(out / "fact" / f"{fid}.json", load_fact(family, fid)) + return {"sections": len(SECTIONS), "facts": len(ids)} + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) + ap.add_argument("--family", required=True, help="family key, e.g. HOME-VISITS") + ap.add_argument("--out", type=Path, required=True, help="directory to write") + args = ap.parse_args(argv) + + from llm import config, policy + + cfg = config.load() + n = dump( + args.out, + args.family, + load_slice=lambda family, section: policy.load_slice(cfg, family, section), + load_contents=lambda: policy.load_contents(cfg), + load_fact=lambda family, fid: policy.load_fact(cfg, family, fid), + ) + print(f"wrote {args.out}: contents, {n['sections']} sections, {n['facts']} facts") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/dev/scripts/lex_probe.py b/dev/scripts/lex_probe.py new file mode 100644 index 0000000..04570a3 --- /dev/null +++ b/dev/scripts/lex_probe.py @@ -0,0 +1,379 @@ +"""Drive a real Chromium through the lex app (lex S1 D13). + +Two modes: + +* Fixture mode (``--fixture DIR --assets DIR --page FILE``), before the roll: + ``page.route`` answers every request to ``--base`` the way the three lex + routers would (see :func:`route_target`): ``/api/policy/…`` from the files + ``dev/scripts/lex_dump_api.py`` wrote to DIR, ``/assets/dossier/.js`` + from ``--assets``, and anything else with the page. +* Live mode (``--map HOST=TARGET``): Chromium resolves HOST to TARGET + (``--host-resolver-rules``), e.g. a throwaway Traefik on the gateway network. + +Checks: + +* ``smoke``: every view at 1440×900 and 390×844 must reach + ``main[data-ready=]`` within 15 s, with no page error, no console error + (failed Google Fonts loads aside) and no sideways page scroll. Screenshots go + to ``--shots``. +* ``facts``: every fact of the family's facts index must be rendered on its + view with its citation: the link's href is the fact's url, or the locator + span's text is its locator; each also-url is linked too. When the fact's + element carries no cite, it is clicked and the evidence drawer is checked. + Prints ``facts N rendered N links ok N locator-only M``. + +Exits 1 on any miss. Run in the pinned Playwright image:: + + docker run --rm -v /home/kert/stack:/w:ro -v "$S/lex":/lex \\ + mcr.microsoft.com/playwright/python:v1.61.0-noble bash -c \\ + 'pip install -q playwright==1.61.0 && python /w/dev/scripts/lex_probe.py \\ + --base http://lex.test --fixture /lex/api \\ + --assets /w/infra/gitea/custom/public/assets/dossier \\ + --page /lex/index.html --family HOME-VISITS --check smoke --shots /lex/shots' +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +from collections import OrderedDict +from pathlib import Path +from typing import Any +from urllib.parse import parse_qs, quote, urlsplit + +#: state.js VIEWS (a test keeps the two equal) +VIEWS = ( + "contents", + "dossier", + "timeline", + "valuation", + "payment", + "politics", + "sources", + "grid", + "evaluate", + "predict", + "draft", + "review", +) +VIEWPORTS = ((1440, 900), (390, 844)) +READY_MS = 15_000 +FONT_HOSTS = ("fonts.googleapis.com", "fonts.gstatic.com") + +_API = re.compile(r"^/api/policy/") +_ASSET = re.compile(r"^/assets/dossier/([a-z][a-z0-9-]*[.]js)$") +_SECTION = re.compile(r"^/api/policy/dossier/([a-z]+)$") +_FACT_ID = re.compile(r"^F\d{1,6}$") + +#: the cites inside an element: hrefs of a.cite, texts of .cite.book +_CITES_JS = """el => ({ + links: [...el.querySelectorAll("a.cite")].map((a) => a.getAttribute("href")), + books: [...el.querySelectorAll(".cite.book")].map((s) => s.textContent.trim()), +})""" +_READY_JS = """v => { + const m = document.querySelector("main"); + return !!m && (m.dataset.ready === v || m.dataset.ready === "error"); +}""" + + +def route_target(path: str) -> tuple[str, str]: + """Which lex router takes a request path: ``lex-api`` (PathPrefix + ``/api/policy/``), ``lex-assets`` (flat module names only) or the page.""" + if _API.match(path): + return ("api", path) + m = _ASSET.match(path) + if m: + return ("asset", m.group(1)) + return ("page", "") + + +def view_url(base: str, view: str, family: str) -> str: + return f"{base.rstrip('/')}/{view}?family={quote(family, safe='')}" + + +def host_rules(maps: list[str]) -> str | None: + """``HOST=TARGET`` pairs as a Chromium ``--host-resolver-rules`` value.""" + rules = [] + for m in maps: + host, _, target = m.partition("=") + if not host or not target or " " in m: + raise SystemExit(f"--map {m!r}: expected HOST=TARGET") + rules.append(f"MAP {host} {target}") + return ", ".join(rules) or None + + +def ignorable(url: str) -> bool: + """A console error from a Google Fonts load (no network in the probe).""" + return bool(url) and urlsplit(url).hostname in FONT_HOSTS + + +def _norm(family: str) -> str: + return (family or "").strip().upper() + + +def _missing(message: str, **extra: str) -> tuple[int, dict[str, Any]]: + return (404, {"detail": {"message": message, **extra}}) + + +def fixture_file( + directory: Path, path: str, query: str, family: str +) -> tuple[int, Path | dict[str, Any]]: + """The dump file that answers an API request, or a 404 JSON body.""" + directory = Path(directory) + if path == "/api/policy/contents": + f = directory / "contents.json" + return (200, f) if f.is_file() else _missing("contents not in the dump") + qs = parse_qs(query) + asked = _norm(qs.get("family", [""])[0]) + section = _SECTION.match(path) + if not (section or path == "/api/policy/fact"): + return _missing("not in the dump") + if not asked: + return _missing("family is required") + if asked != _norm(family): + return _missing( + f"No dossier is built for {asked} yet.", family=asked, status="unknown" + ) + if section: + f = directory / "dossier" / f"{section.group(1)}.json" + return (200, f) if f.is_file() else _missing("unknown section") + fid = qs.get("id", [""])[0] + f = directory / "fact" / f"{fid}.json" + if _FACT_ID.match(fid) and f.is_file(): + return (200, f) + return _missing("unknown fact", family=asked, id=fid) + + +def fact_misses(entry: dict[str, Any], links: list[str], books: list[str]) -> list[str]: + """What is missing of one fact's citation among the rendered cites. The + index lists the also-cites by url only; an empty one (a licensed book) + must show as one more locator span.""" + fid = entry["id"] + out = [] + if entry["url"]: + if entry["url"] not in links: + out.append(f"{fid}: link {entry['url']} not rendered") + else: + want = entry["locator"] or entry["label"] + if want not in books: + out.append(f"{fid}: locator {want!r} not rendered") + out += [ + f"{fid}: also {u} not rendered" for u in entry["also"] if u and u not in links + ] + empty = sum(1 for u in entry["also"] if not u) + spans = empty + (0 if entry["url"] else 1) + if empty and len(books) < spans: + out.append(f"{fid}: {spans} locator spans expected, {len(books)} rendered") + return out + + +def facts_line(n: int, rendered: int, links_ok: int, locator_only: int) -> str: + return ( + f"facts {n} rendered {rendered} links ok {links_ok} locator-only {locator_only}" + ) + + +def _origin(url: str) -> str: + u = urlsplit(url) + return f"{u.scheme}://{u.netloc}" + + +def _install_fixture(context: Any, args: argparse.Namespace) -> None: + origin = _origin(args.base) + page_body = Path(args.page).read_bytes() + fixture, assets = Path(args.fixture), Path(args.assets) + + def handle(route: Any) -> None: + u = urlsplit(route.request.url) + if f"{u.scheme}://{u.netloc}" != origin: + route.continue_() + return + kind, arg = route_target(u.path) + if kind == "api": + status, body = fixture_file(fixture, u.path, u.query, args.family) + data = body.read_bytes() if isinstance(body, Path) else json.dumps(body) + route.fulfill(status=status, content_type="application/json", body=data) + elif kind == "asset": + p = assets / arg + if p.is_file(): + route.fulfill( + status=200, + content_type="text/javascript", + body=p.read_bytes(), + headers={"Cache-Control": "no-cache"}, + ) + else: + route.fulfill(status=404, content_type="text/plain", body="not found") + else: + route.fulfill( + status=200, content_type="text/html; charset=utf-8", body=page_body + ) + + context.route("**/*", handle) + + +def _context(browser: Any, args: argparse.Namespace, width: int, height: int) -> Any: + ctx = browser.new_context( + viewport={"width": width, "height": height}, ignore_https_errors=True + ) + if args.fixture: + _install_fixture(ctx, args) + return ctx + + +def _open(page: Any, url: str, view: str, timeout_error: type) -> str | None: + page.goto(url, wait_until="domcontentloaded") + try: + page.wait_for_function(_READY_JS, arg=view, timeout=READY_MS) + except timeout_error: + return None + return page.evaluate("document.querySelector('main').dataset.ready") + + +def smoke(browser: Any, args: argparse.Namespace, timeout_error: type) -> int: + shots = Path(args.shots) if args.shots else None + if shots: + shots.mkdir(parents=True, exist_ok=True) + failed = 0 + for width, height in VIEWPORTS: + ctx = _context(browser, args, width, height) + page = ctx.new_page() + errors: list[str] = [] + page.on("pageerror", lambda e: errors.append(f"page error: {e}")) + + def on_console(msg: Any, errors: list[str] = errors) -> None: + where = (msg.location or {}).get("url", "") + if ( + msg.type == "error" + and not ignorable(where) + and not any(h in msg.text for h in FONT_HOSTS) + ): + errors.append(f"console: {msg.text} ({where})") + + page.on("console", on_console) + for view in VIEWS: + errors.clear() + ready = _open( + page, view_url(args.base, view, args.family), view, timeout_error + ) + page.evaluate("async () => { await document.fonts.ready; return true; }") + sw, iw = page.evaluate( + "[document.documentElement.scrollWidth, window.innerWidth]" + ) + problems = [] + if ready != view: + problems.append(f"main[data-ready] is {ready!r}") + problems += errors + if sw > iw: + problems.append(f"the page scrolls sideways ({sw} > {iw})") + if shots: + page.screenshot(path=str(shots / f"{view}-{width}.png"), full_page=True) + failed += bool(problems) + tag = "FAIL" if problems else "ok " + detail = (": " + "; ".join(problems)) if problems else "" + print(f"{tag} {view:<10} {width}x{height}{detail}", flush=True) + ctx.close() + total = len(VIEWS) * len(VIEWPORTS) + print(f"smoke {total - failed}/{total} ok", flush=True) + return 1 if failed else 0 + + +def facts(browser: Any, args: argparse.Namespace, timeout_error: type) -> int: + ctx = _context(browser, args, *VIEWPORTS[0]) + page = ctx.new_page() + _open(page, view_url(args.base, "contents", args.family), "contents", timeout_error) + path = f"/api/policy/dossier/facts?family={quote(args.family, safe='')}" + index = page.evaluate( + """async (p) => { + const r = await fetch(p, {redirect: "manual"}); + return r.ok ? await r.json() : {status: r.status}; + }""", + path, + ) + if "facts" not in index: + print(f"facts index: {index}", flush=True) + return 1 + entries = index["facts"] + by_view: OrderedDict[str, list[dict[str, Any]]] = OrderedDict() + for e in entries: + by_view.setdefault(e["view"], []).append(e) + misses: list[str] = [] + rendered = links_ok = locator_only = 0 + for view, group in by_view.items(): + ready = _open(page, view_url(args.base, view, args.family), view, timeout_error) + if ready != view: + misses += [f"{e['id']}: view {view} is {ready!r}" for e in group] + continue + for e in group: + node = page.locator(f'[data-fact="{e["id"]}"]') + if node.count() == 0: + misses.append(f"{e['id']}: not rendered on {view}") + continue + rendered += 1 + found = node.first.evaluate(_CITES_JS) + if not found["links"] and not found["books"]: + node.first.click() + try: + page.wait_for_selector( + f'#drawer [data-evidence="{e["id"]}"]', timeout=5_000 + ) + except timeout_error: + misses.append(f"{e['id']}: the drawer did not open") + continue + found = page.locator("#drawer").evaluate(_CITES_JS) + miss = fact_misses(e, found["links"], found["books"]) + misses += miss + if not miss: + if e["url"]: + links_ok += 1 + else: + locator_only += 1 + ctx.close() + print(facts_line(len(entries), rendered, links_ok, locator_only), flush=True) + for m in misses: + print(f"MISS {m}", flush=True) + return 1 if misses or rendered != len(entries) else 0 + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) + ap.add_argument( + "--base", required=True, help="the app's origin, e.g. http://lex.test" + ) + ap.add_argument("--family", required=True, help="family key, e.g. HOME-VISITS") + ap.add_argument("--check", choices=("smoke", "facts"), required=True) + ap.add_argument( + "--map", action="append", default=[], help="HOST=TARGET (repeatable)" + ) + ap.add_argument("--fixture", help="directory written by lex_dump_api.py") + ap.add_argument("--assets", help="directory of the JS modules (fixture mode)") + ap.add_argument("--page", help="the built page (fixture mode)") + ap.add_argument("--shots", help="directory for screenshots (smoke)") + args = ap.parse_args(argv) + given = [x is not None for x in (args.fixture, args.assets, args.page)] + if any(given) and not all(given): + ap.error("--fixture, --assets and --page go together") + return args + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + from playwright.sync_api import TimeoutError as PlaywrightTimeout + from playwright.sync_api import sync_playwright + + rules = host_rules(args.map) + with sync_playwright() as pw: + browser = pw.chromium.launch( + args=[f"--host-resolver-rules={rules}"] if rules else [] + ) + try: + check = smoke if args.check == "smoke" else facts + return check(browser, args, PlaywrightTimeout) + finally: + browser.close() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/infra/gitea/custom/public/assets/dossier/api.js b/infra/gitea/custom/public/assets/dossier/api.js new file mode 100644 index 0000000..40bcf7c --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/api.js @@ -0,0 +1,160 @@ +// lex · the policy API client. +// +// Every failure becomes an error the page renders as a panel: SignedOut (the +// SSO session ended: an opaque redirect to the login, or an HTML page), +// NotFound (no dossier for the family; .status says why), Unavailable (the +// replica or the service is down) and Rebuilt (the dossier changed while the +// page was loading and stayed mixed after one refetch). + +export class SignedOut extends Error { + constructor(message = "The sign-in session has ended.") { + super(message); + this.name = "SignedOut"; + } +} + +export class NotFound extends Error { + constructor(message = "Not found.", { family = "", status = "" } = {}) { + super(message); + this.name = "NotFound"; + this.family = family; + this.status = status; + } +} + +export class Unavailable extends Error { + constructor(message = "The data replica is not available.") { + super(message); + this.name = "Unavailable"; + } +} + +export class Rebuilt extends Error { + constructor(message = "The dossier was rebuilt while this page was loading.") { + super(message); + this.name = "Rebuilt"; + } +} + +export const CONTENTS_PATH = "/api/policy/contents"; +export const sectionPath = (section, family) => `/api/policy/dossier/${section}?family=${encodeURIComponent(family)}`; +export const factPath = (family, id) => `/api/policy/fact?family=${encodeURIComponent(family)}&id=${encodeURIComponent(id)}`; + +/** The six per-family slices that carry the dossier's built_at (S1-P1); + * contents, the facts index and a single fact are not checked. */ +export const CHECKED = ["header", "timeline", "valuation", "payment", "politics", "sources"]; + +const isJSON = (res) => /^application\/([\w.+-]*\+)?json\b/i.test(res.headers.get("content-type") || ""); + +async function detail(res) { + if (!isJSON(res)) return {}; + try { + const body = await res.json(); + return body && typeof body.detail === "object" && body.detail ? body.detail : {}; + } catch { + return {}; + } +} + +/** GET a JSON body, or throw one of the errors above. */ +export async function getJSON(path, fetchImpl = (...a) => fetch(...a)) { + let res; + try { + res = await fetchImpl(path, { redirect: "manual", credentials: "same-origin", headers: { Accept: "application/json" } }); + } catch (e) { + throw new Unavailable(`The policy API did not answer (${e && e.message ? e.message : e}).`); + } + if (res.type === "opaqueredirect" || res.status === 0) throw new SignedOut(); + if (res.status === 401 || res.status === 403) throw new SignedOut(); + if (res.status >= 500) { + const d = await detail(res); + throw new Unavailable(d.message || undefined); + } + if (res.status === 404) { + const d = await detail(res); + throw new NotFound(d.message || "No dossier is built for this family.", { family: d.family || "", status: d.status || "" }); + } + if (!isJSON(res)) throw new SignedOut(); + if (!res.ok) { + const d = await detail(res); + throw new Error(`The policy API answered ${res.status}${d.message ? ": " + d.message : ""}.`); + } + return res.json(); +} + +/** One family's slices, fetched once each and always from one build: every + * checked slice must carry the header's built_at. A mismatch clears the + * cache and refetches once; a second mismatch throws Rebuilt. */ +export class DossierStore { + constructor(family, fetchImpl = (...a) => fetch(...a)) { + this.family = family || ""; + this.fetchImpl = fetchImpl; + this.pending = new Map(); // section -> Promise of its body + this.data = {}; // section -> body, once resolved + this.facts = new Map(); // fact id -> Promise of a fetched fact + } + + path(section) { + if (section === "contents") return CONTENTS_PATH; + return sectionPath(section, this.family); + } + + get(section) { + let p = this.pending.get(section); + if (!p) { + p = getJSON(this.path(section), this.fetchImpl).then( + (body) => { + if (this.pending.get(section) === p) this.data[section] = body; + return body; + }, + (err) => { + if (this.pending.get(section) === p) this.pending.delete(section); + throw err; + }, + ); + this.pending.set(section, p); + } + return p; + } + + clear() { + this.pending.clear(); + this.data = {}; + } + + async fetchAll(needs) { + const bodies = await Promise.all(needs.map((s) => this.get(s))); + return Object.fromEntries(needs.map((s, i) => [s, bodies[i]])); + } + + /** {section: body} for each need; the header is added whenever a checked + * slice is needed, since it is what the others are checked against. */ + async load(needs) { + let want = Array.from(new Set(needs)); + if (want.some((s) => CHECKED.includes(s)) && !want.includes("header")) want = ["header", ...want]; + for (let attempt = 0; attempt < 2; attempt++) { + const out = await this.fetchAll(want); + const built = out.header ? out.header.built_at : undefined; + if (want.every((s) => !CHECKED.includes(s) || out[s].built_at === built)) return out; + this.clear(); + } + throw new Rebuilt(); + } + + /** One fact: from a loaded slice when it is there, else from the API. */ + async fact(id) { + for (const body of Object.values(this.data)) { + const facts = body && body.facts; + if (facts && !Array.isArray(facts) && Object.prototype.hasOwnProperty.call(facts, id)) return facts[id]; + } + let p = this.facts.get(id); + if (!p) { + p = getJSON(factPath(this.family, id), this.fetchImpl).catch((err) => { + this.facts.delete(id); + throw err; + }); + this.facts.set(id, p); + } + return p; + } +} diff --git a/infra/gitea/custom/public/assets/dossier/app.js b/infra/gitea/custom/public/assets/dossier/app.js new file mode 100644 index 0000000..2163d0a --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/app.js @@ -0,0 +1,277 @@ +// lex · boot and DOM wiring: the only module that touches the document. +// +// Reads the URL (D1), loads the slices the view needs from the policy API, +// renders the rail, masthead status, tabs and the view, and runs the +// evidence drawer. Loading sets main[data-ready=""]; a rendered view sets it +// to the view's name; a failure renders a panel and sets it to "error". + +import { DossierStore, NotFound, Rebuilt, SignedOut, Unavailable } from "./api.js"; +import { evidenceHtml } from "./cite.js"; +import { esc } from "./fmt.js"; +import { DRAWER_IDLE, VIEW_TITLE, errorHtml, headHtml, mastHtml, railHtml, tabsHtml } from "./shell.js"; +import { FAMILY_VIEWS, VIEWS, VIEW_MODULE, formatState, parseLocation } from "./state.js"; + +const $ = (s) => document.querySelector(s); +const el = { + main: $("#main"), + mast: $("#mast"), + tabs: $("#tabs"), + view: $("#view"), + rail: $("#rail"), + toc: $("#toc"), + tocBox: $("#toc-d"), + q: $("#q"), + status: $("#status"), + drawer: $("#drawer"), + tip: $("#tip"), + theme: $("#theme-btn"), +}; + +const plain = ({ family = "", view = "contents", code = "", fact = "" }) => ({ family, view, code, fact }); +const here = () => location.pathname + location.search + location.hash; +const expected = (err) => err instanceof SignedOut || err instanceof NotFound || err instanceof Unavailable || err instanceof Rebuilt; + +let state = plain(parseLocation(location)); +const book = new DossierStore(""); +let store = null; +let renderSeq = 0; +let drawerSeq = 0; +let selected = null; + +function writeURL(push) { + const url = formatState(state); + if (url !== here()) history[push ? "pushState" : "replaceState"](null, "", url); +} + +/* ── view modules, loaded on first use ── */ +const modules = {}; +function loadModule(view) { + const name = VIEW_MODULE[view]; + if (!modules[name]) { + modules[name] = import(`./view-${name}.js`).catch((err) => { + delete modules[name]; + throw err; + }); + } + return modules[name]; +} + +/* ── render ── */ +function filterRail() { + const q = el.q.value.trim().toLowerCase(); + el.toc.querySelectorAll("li[data-name]").forEach((li) => { + li.hidden = !!q && !li.dataset.name.includes(q); + }); +} + +function fail(err, s) { + el.status.innerHTML = mastHtml(s, null, null, err); + el.mast.innerHTML = headHtml(s, null); + el.view.innerHTML = errorHtml(err, s, location.href); + el.view.removeAttribute("aria-busy"); + el.main.dataset.ready = "error"; + if (!expected(err)) console.error(err); +} + +async function render() { + const n = ++renderSeq; + const s = state; + el.main.dataset.ready = ""; + el.view.setAttribute("aria-busy", "true"); + el.tabs.innerHTML = tabsHtml(s); + if (s.family && (!store || store.family !== s.family)) store = new DossierStore(s.family); + const family = FAMILY_VIEWS.includes(s.view); + const modP = loadModule(s.view); + const [mod, c, f] = await Promise.allSettled([ + modP, + book.load(["contents"]), + family ? modP.then((m) => store.load(["header", ...m.needs.filter((x) => x !== "contents")])) : Promise.resolve({}), + ]); + if (n !== renderSeq) return; + const contents = c.status === "fulfilled" ? c.value.contents : null; + if (contents) { + el.toc.innerHTML = railHtml(contents, s); + filterRail(); + } else { + el.toc.innerHTML = `

The book could not be loaded.

`; + } + const needsContents = mod.status === "fulfilled" && mod.value.needs.includes("contents"); + const err = mod.status === "rejected" ? mod.reason : f.status === "rejected" ? f.reason : needsContents && c.status === "rejected" ? c.reason : null; + if (err) return fail(err, s); + const data = { ...f.value, contents }; + try { + el.status.innerHTML = mastHtml(s, data.header, contents); + el.mast.innerHTML = headHtml(s, data.header); + el.view.innerHTML = mod.value.render(data, s); + if (mod.value.mount) mod.value.mount(el.view, data, s, nav); + } catch (e) { + return fail(e, s); + } + document.title = ["lex", data.header ? data.header.name : "", VIEW_TITLE[s.view]].filter(Boolean).join(" · "); + el.view.removeAttribute("aria-busy"); + el.main.dataset.ready = s.view; + if (s.fact) openFact(s.fact); +} + +/* ── evidence drawer ── */ +function select(node) { + if (selected) selected.classList.remove("sel"); + selected = node || null; + if (selected) selected.classList.add("sel"); +} + +function showDrawer(html) { + el.drawer.innerHTML = html; + el.drawer.classList.add("open"); + document.body.classList.add("drawer-open"); +} + +/** Back to the idle drawer; the URL is left alone. */ +function resetDrawer() { + drawerSeq++; + el.drawer.classList.remove("open"); + document.body.classList.remove("drawer-open"); + el.drawer.innerHTML = DRAWER_IDLE; + select(null); +} + +function closeDrawer() { + resetDrawer(); + if (state.fact) { + state = { ...state, fact: "" }; + writeURL(false); + } +} + +async function openFact(id, node) { + if (!store || !state.family) return; + const token = ++drawerSeq; + select(node || el.view.querySelector(`[data-fact="${CSS.escape(id)}"]`)); + if (state.fact !== id) { + state = { ...state, fact: id }; + writeURL(false); + } + const head = `
Evidence · ${esc(id)}
`; + showDrawer(head + `

Loading…

`); + try { + const fact = await store.fact(id); + if (token === drawerSeq) showDrawer(evidenceHtml(fact)); + } catch (err) { + if (token === drawerSeq) showDrawer(head + errorHtml(err, state, location.href)); + if (!expected(err)) console.error(err); + } +} + +function openEvidence(html) { + drawerSeq++; + select(null); + if (state.fact) { + state = { ...state, fact: "" }; + writeURL(false); + } + showDrawer(html); +} + +/* ── navigation ── */ +function navigate(next, { push, fromRail = false } = {}) { + const prev = state; + state = plain(next); + const moved = prev.view !== state.view || prev.family !== state.family; + writeURL(push === undefined ? moved : push); + if (moved) { + resetDrawer(); + const narrow = window.matchMedia("(max-width: 760px)").matches; + if (fromRail && narrow) el.tocBox.open = false; + if ((fromRail && narrow) || el.main.getBoundingClientRect().top < 0) el.main.scrollIntoView({ block: "start" }); + } + if (moved || prev.code !== state.code) render(); + else if (state.fact && state.fact !== prev.fact) openFact(state.fact); + else if (!state.fact && prev.fact) closeDrawer(); +} + +/** What a view's mount() may do. */ +const nav = { + go(patch, opts = {}) { + navigate(parseLocation(new URL(formatState({ ...state, ...patch }), location.href)), opts); + }, + openFact: (id) => openFact(id), + openEvidence, +}; + +document.addEventListener("click", (e) => { + const close = e.target.closest("[data-close]"); + if (close && el.drawer.contains(close)) { + e.preventDefault(); + closeDrawer(); + return; + } + if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; + const a = e.target.closest("a[href]"); + if (a) { + if ((a.target && a.target !== "_self") || a.hasAttribute("download")) return; + const u = new URL(a.href, location.href); + if (u.origin !== location.origin || !VIEWS.includes(u.pathname.split("/")[1] || "")) return; + e.preventDefault(); + navigate(parseLocation(u), { fromRail: el.rail.contains(a) }); + return; + } + if (e.target.closest("button, input, select, textarea, label, summary")) return; + const ref = e.target.closest("[data-ref]"); + if (ref) return void openFact(ref.dataset.ref); + const node = e.target.closest("[data-fact]"); + if (node && !el.drawer.contains(node)) openFact(node.dataset.fact, node); +}); + +document.addEventListener("keydown", (e) => { + if (e.key === "Escape" && el.drawer.classList.contains("open")) return void closeDrawer(); + if (e.key !== "Enter" && e.key !== " ") return; + const node = e.target.closest && e.target.closest("[data-fact]"); + if (node && e.target === node) { + e.preventDefault(); + openFact(node.dataset.fact, node); + } +}); + +window.addEventListener("popstate", () => navigate(parseLocation(location), { push: false })); +el.q.addEventListener("input", filterRail); + +/* ── tooltip for charts (data-tip) ── */ +document.addEventListener("pointermove", (evt) => { + const t = evt.target.closest && evt.target.closest("[data-tip]"); + if (!t) { + el.tip.hidden = true; + return; + } + el.tip.textContent = t.getAttribute("data-tip"); + el.tip.hidden = false; + el.tip.style.left = Math.min(evt.clientX + 14, window.innerWidth - 270) + "px"; + el.tip.style.top = evt.clientY + 14 + "px"; +}); + +/* ── theme: light by default; the fhirworx dark palette on request ── */ +function syncTheme() { + const dark = document.documentElement.getAttribute("data-theme") === "dark"; + el.theme.setAttribute("aria-pressed", String(dark)); + el.theme.title = dark ? "Switch to the fhirworx light palette" : "Switch to the fhirworx dark palette"; + el.theme.querySelector("use").setAttribute("href", dark ? "#i-sun" : "#i-moon"); + el.theme.querySelector("span").textContent = dark ? "Light" : "Dark"; +} +el.theme.addEventListener("click", () => { + const dark = document.documentElement.getAttribute("data-theme") !== "dark"; + if (dark) document.documentElement.setAttribute("data-theme", "dark"); + else document.documentElement.removeAttribute("data-theme"); + try { + localStorage.setItem("lex-theme", dark ? "dark" : "light"); + } catch { + /* storage blocked: the choice lasts for this page */ + } + syncTheme(); +}); + +/* ── boot ── */ +const first = parseLocation(location); +if (first.canonical !== here()) history.replaceState(null, "", first.canonical); +syncTheme(); +el.drawer.innerHTML = DRAWER_IDLE; +if (window.matchMedia("(max-width: 760px)").matches) el.tocBox.open = false; +render(); diff --git a/infra/gitea/custom/public/assets/dossier/cite.js b/infra/gitea/custom/public/assets/dossier/cite.js new file mode 100644 index 0000000..561058f --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/cite.js @@ -0,0 +1,102 @@ +// lex · citations, facts and the evidence drawer's markup (pure). +// +// R10: the page never builds a citation URL. It renders cite.url as the API +// gives it, or cite.locator when the url is empty. A licensed book +// (cite.kind "cpt_book") never gets a link. + +import { esc } from "./fmt.js"; + +const BOOK_TITLE = "Cited by edition and page; text not reproduced"; + +export const KIND_LABEL = { + origin: "Origin", + formation: "Formation", + finding: "Governance finding", + event: "Timeline event", + link: "Linked code", + round: "Valuation round", + pe: "Practice expense", + payment: "Payment", + cms_summary: "CMS's summary", + stance_split: "Our classification", + money: "Money", + seat: "Seat", + impact: "Impact", +}; + +export const CITE_KIND = { + fr_para: "Federal Register paragraph", + fr_page: "Federal Register page", + cfr: "Regulation (eCFR)", + statute: "Statute", + iom: "CMS manual", + mln: "CMS MLN booklet", + rvu_file: "RVU file", + dataset: "Data file", + cpt_book: "Licensed book: cited by edition and page; text not reproduced", + study: "Study", + comment: "Public comment", +}; + +const kindLabel = (k) => KIND_LABEL[k] || String(k || "fact").replace(/_/g, " "); +const linkable = (cite) => cite.kind !== "cpt_book" && /^https?:\/\//i.test(cite.url || ""); + +/** A cite as a link that opens apart, or as its locator when it has no url. */ +export function citeHtml(cite, { ref = "" } = {}) { + if (!cite) return ""; + const r = ref ? ` data-ref="${esc(ref)}"` : ""; + if (linkable(cite)) return `${esc(cite.label)}`; + return `${esc(cite.locator || cite.label)}`; +} + +const cites = (fact) => [fact.cite, ...(fact.also || [])].filter(Boolean); + +/** One fact: its note as a flag, its text, its cites and, for a stance + * split, the accuracy line that travels with every count. */ +export function factHtml(fact, { tag = "li" } = {}) { + const parts = []; + if (fact.note) parts.push(`${esc(fact.note)}`); + parts.push(esc(fact.text)); + parts.push(...cites(fact).map((c) => citeHtml(c))); + if (fact.accuracy) parts.push(`${esc(fact.accuracy)}`); + return `<${tag} data-fact="${esc(fact.id)}" data-kind="${esc(fact.kind)}" tabindex="0">${parts.join(" ")}`; +} + +/** Text with [F#] tags turned into the facts' cites; a run of one tag + * collapses to one cite, an unknown tag stays as text. */ +export function tagged(text, facts) { + if (!text) return ""; + return esc(text).replace(/\[(F\d+)\](?:\[\1\])*/g, (m, id) => { + const f = facts && Object.prototype.hasOwnProperty.call(facts, id) ? facts[id] : null; + return f ? citeHtml(f.cite, { ref: id }) : m; + }); +} + +function valueText(v) { + if (Array.isArray(v)) return v.map((x) => (x !== null && typeof x === "object" ? JSON.stringify(x) : String(x))).join(", "); + if (v !== null && typeof v === "object") return JSON.stringify(v); + return String(v); +} + +const filled = (v) => v !== null && v !== undefined && v !== "" && !(Array.isArray(v) && v.length === 0) && !(typeof v === "object" && !Array.isArray(v) && Object.keys(v).length === 0); + +function sourceHtml(cite) { + const what = [cite.locator && cite.locator !== cite.label ? cite.locator : "", CITE_KIND[cite.kind] || ""].filter(Boolean).join(" · "); + return `
${citeHtml(cite)}
${what ? `
${esc(what)}
` : ""}
`; +} + +/** The evidence drawer for one fact. */ +export function evidenceHtml(fact) { + const head = [kindLabel(fact.kind), fact.year ? "CY" + fact.year : ""].filter(Boolean).join(" · "); + const values = Object.entries(fact.values || {}).filter(([, v]) => filled(v)); + let h = `
`; + h += `
Evidence · ${esc(fact.id)}
`; + h += `

${esc(head)}

`; + if (fact.codes && fact.codes.length) h += `
${fact.codes.map((c) => `${esc(c)}`).join("")}
`; + if (fact.note) h += `
${esc(fact.note)}
`; + h += `

${esc(fact.text)}

`; + if (fact.accuracy) h += `

${esc(fact.accuracy)}

`; + if (values.length) h += `
${values.map(([k, v]) => `
${esc(k.replace(/_/g, " "))}
${esc(valueText(v))}
`).join("")}
`; + h += cites(fact).map(sourceHtml).join(""); + return h + "
"; +} diff --git a/infra/gitea/custom/public/assets/dossier/fmt.js b/infra/gitea/custom/public/assets/dossier/fmt.js new file mode 100644 index 0000000..ad1b5dc --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/fmt.js @@ -0,0 +1,37 @@ +// lex · formatting helpers (pure). Ported from the dossier snapshot. + +const ESC = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }; + +/** HTML-escape any value; null and undefined become "". */ +export const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, (c) => ESC[c]); + +export const uniq = (a) => Array.from(new Set(a)); + +export const money = (v) => (v == null ? "—" : "$" + Number(v).toFixed(2)); +export const n2 = (v) => (v == null ? "—" : Number(v).toFixed(2)); +export const int = (v) => (v == null ? "—" : Math.round(v).toLocaleString("en-US")); + +/** Sorted unique codes with runs of three or more consecutive numbers folded: + * 99341–99344, 99350, G0318. */ +export function compact(codes) { + const cs = uniq(codes || []).sort(); + const out = []; + let i = 0; + while (i < cs.length) { + let j = i; + while (j + 1 < cs.length && /^\d+$/.test(cs[j]) && /^\d+$/.test(cs[j + 1]) && +cs[j + 1] === +cs[j] + 1) j++; + if (j - i >= 2) out.push(cs[i] + "–" + cs[j]); + else out.push(...cs.slice(i, j + 1)); + i = j + 1; + } + return out.join(", "); +} + +/** "2026-11-13 05:23 UTC" from a stored built_at. The dossier stores UTC + * without an offset; a value with an offset or Z is converted to UTC. */ +export function builtText(iso) { + if (!iso) return ""; + const s = String(iso); + const t = /(Z|[+-]\d\d:?\d\d)$/.test(s) ? new Date(s).toISOString() : s; + return `${t.slice(0, 10)} ${t.slice(11, 16)} UTC`; +} diff --git a/infra/gitea/custom/public/assets/dossier/shell.js b/infra/gitea/custom/public/assets/dossier/shell.js new file mode 100644 index 0000000..cec9a4d --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/shell.js @@ -0,0 +1,187 @@ +// lex · the shell around a view (pure): tabs, the book rail, the masthead's +// status box, the section header and the error panels. Markup and classes are +// the dossier snapshot's (fhirworx: dashboard.css tiles, health box, badge). + +import { NotFound, Rebuilt, SignedOut, Unavailable } from "./api.js"; +import { builtText, compact, esc } from "./fmt.js"; +import { formatState } from "./state.js"; + +export const VIEW_TITLE = { + contents: "Contents", + dossier: "Dossier", + timeline: "Timeline", + valuation: "Valuation", + payment: "Payment", + politics: "Politics", + sources: "Sources", + grid: "Grid", + evaluate: "Evaluate", + predict: "Predict", + draft: "Draft", + review: "Review", +}; + +// D8: the snapshot's tab set. "family" is labelled with the family key. +const TAB_GROUPS = [ + ["book", ["contents"]], + ["family", ["dossier", "timeline", "valuation", "payment", "politics", "sources"]], + ["coming", ["grid", "evaluate", "predict", "draft", "review"]], +]; + +const PHASE_NAME = { 1: "primary and home-based care" }; + +export const DRAWER_IDLE = `
Evidence

Select a fact to read its evidence here: the text, its values and every source it cites.

`; + +/** One link per view; the family's views only when a family is chosen. */ +export function tabsHtml(state) { + const family = state.family || ""; + return TAB_GROUPS.filter(([g]) => g === "book" || family) + .map(([g, views]) => { + const label = g === "family" ? family : g; + const links = views.map((v) => { + const on = v === state.view; + const cls = [g === "coming" ? "soon" : "", on ? "on" : ""].filter(Boolean).join(" "); + const href = formatState({ family, view: v }); + return `${VIEW_TITLE[v]}`; + }); + return `${esc(label)}` + links.join(""); + }) + .join(""); +} + +const nameKey = (...parts) => esc(parts.filter(Boolean).join(" ").toLowerCase()); + +/** The book: built families link to their dossier, planned ones do not; + * the machine-built tier closes it. */ +export function railHtml(contents, state) { + const c = contents || {}; + const cur = state.family || ""; + const families = c.families || []; + const planned = c.planned || []; + const builtLi = (f) => + `${esc(f.name)}${f.tier === "reviewed" ? "Built" : "Machine"}`; + let h = ""; + const reviewed = families.filter((f) => f.tier === "reviewed"); + const machine = families.filter((f) => f.tier !== "reviewed"); + if (reviewed.length) h += `
Reviewed
    ${reviewed.map(builtLi).join("")}
`; + if (machine.length) h += `
Machine-built · not reviewed
    ${machine.map(builtLi).join("")}
`; + const phases = []; + for (const p of planned) { + const key = p.phase == null ? "" : String(p.phase); + let grp = phases.find((x) => x.key === key); + if (!grp) phases.push((grp = { key, rows: [] })); + grp.rows.push(p); + } + for (const { key, rows } of phases) { + const label = PHASE_NAME[key] || (key ? "phase " + key : "not phased"); + h += `
Planned · ${esc(label)}
    `; + h += rows + .map( + (p) => + `
  • ${esc(p.name)}${p.status === "planned" ? "Planned" : "Curated"}
  • `, + ) + .join(""); + h += `
`; + } + const m = c.machine; + const note = m + ? `The machine-built tier covers everything else: ${m.derived.toLocaleString("en-US")} derived code families, ${m.single_code.toLocaleString("en-US")} of them single codes, built unattended and labeled “machine-built, not reviewed”.` + : "The machine-built tier covers everything else: derived code families built unattended and labeled “machine-built, not reviewed”."; + return h + `

${esc(note)}

`; +} + +const ERR_TITLE = (err) => + err instanceof SignedOut ? "Signed out" : err instanceof NotFound ? "Not built" : err instanceof Unavailable ? "Unavailable" : err instanceof Rebuilt ? "Rebuilt" : "Error"; + +function health(state, k, v, note = "") { + return `
${esc(k)}${esc(v)}${note ? `${esc(note)}` : ""}
`; +} + +/** The masthead's status box: the family's build, the book's, or loading. */ +export function mastHtml(state, header, contents, err = null) { + if (err) return health("bad", ERR_TITLE(err), err.message || String(err)); + if (header && state.view !== "contents") { + const passed = header.check_passed === true; + const tier = header.tier === "reviewed" ? "Reviewed tier." : "This dossier is machine-built, not reviewed."; + return health( + passed ? "ok" : "warn", + "Live", + `${header.family} dossier built ${builtText(header.built_at)} · citation check ${passed ? "passed" : "failed"}`, + `${tier} Every value below comes from a stored row; each carries its source.`, + ); + } + if (contents) { + const fams = contents.families || []; + const latest = fams.map((f) => f.built_at || "").sort().pop() || ""; + const n = fams.length; + return health( + "ok", + "Live", + `${n} ${n === 1 ? "dossier" : "dossiers"} built${latest ? " · latest " + builtText(latest) : ""}`, + "Every value comes from a stored row; each carries its source.", + ); + } + return health("unknown", "Loading", "Reading the stored dossiers…"); +} + +/** The section header above the tabs: the family, or the book. */ +export function headHtml(state, header) { + if (state.view === "contents" || !header) { + if (state.view !== "contents") return ""; + return `
The book · CMS payment and quality regulation

Contents

`; + } + const g = header.code_groups || {}; + const eyebrow = [header.family, "code family dossier", header.phase ? "phase " + header.phase : ""].filter(Boolean).join(" · "); + const badge = header.tier === "reviewed" ? `Reviewed dossier` : `Machine-built · not reviewed`; + const sub = [ + (g.active || []).length ? "Active " + compact(g.active) : "", + (g.deleted || []).length ? "deleted " + compact(g.deleted) : "", + (g.linked || []).length ? "linked " + compact(g.linked) : "", + header.years_active ? "years " + header.years_active : "", + ].filter(Boolean); + return `
${esc(eyebrow)}${badge}

${esc(header.name)}

${sub.length ? `

${esc(sub.join(" · "))}

` : ""}
`; +} + +const NOT_FOUND = { + planned: (f) => `${f} is planned in the book but not built yet.`, + curated: (f) => `${f} is curated but its dossier is not built yet.`, + derived: (f) => `${f} is a derived code family; no dossier is stored for it yet.`, + unknown: (f) => `${f} is unknown: no code family has that key.`, +}; + +/** A panel in place of the view, always with a way on. */ +export function errorHtml(err, state, href) { + const reload = (text) => `${text}`; + let kind; + let title; + let body; + let way; + if (err instanceof SignedOut) { + kind = "signed-out"; + title = "Signed out"; + body = "The sign-in session has ended, so lex cannot read the dossier."; + way = `${reload("Sign in again")}; you come back to this view.`; + } else if (err instanceof NotFound) { + const family = err.family || state.family || "This family"; + kind = "not-found"; + title = "Not built yet"; + body = (NOT_FOUND[err.status] || ((f) => `No dossier is stored for ${f}.`))(family); + way = `Go to the contents for the families that are built.`; + } else if (err instanceof Unavailable) { + kind = "unavailable"; + title = "Unavailable"; + body = `The policy data is not available right now. ${err.message}`; + way = `${reload("Reload this view")} in a minute.`; + } else if (err instanceof Rebuilt) { + kind = "rebuilt"; + title = "Rebuilt"; + body = "The dossier was rebuilt while this page was loading, so its views would mix two builds."; + way = `${reload("Reload this view")} to read the new build.`; + } else { + kind = "failed"; + title = "Something went wrong"; + body = err && err.message ? err.message : String(err); + way = `${reload("Reload this view")}.`; + } + return ``; +} diff --git a/infra/gitea/custom/public/assets/dossier/state.js b/infra/gitea/custom/public/assets/dossier/state.js new file mode 100644 index 0000000..28adb05 --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/state.js @@ -0,0 +1,55 @@ +// lex · URL state (D1, pure). +// +// The path is the view, ?family=KEY is the only query parameter, and the +// fragment holds view-local state: /timeline?family=HOME-VISITS#code=99343. +// The login redirect keeps path and query but drops the fragment, and family +// keys can contain "/", so a family is never a path segment. R98's +// /?family=KEY#dossier and the snapshot's bare #view are read and rewritten. + +export const VIEWS = ["contents", "dossier", "timeline", "valuation", "payment", "politics", "sources", "grid", "evaluate", "predict", "draft", "review"]; +export const FAMILY_VIEWS = VIEWS.filter((v) => v !== "contents"); + +/** The module that renders each view: view-.js. */ +export const VIEW_MODULE = { + contents: "contents", + dossier: "dossier", + timeline: "timeline", + valuation: "valuation", + payment: "payment", + politics: "politics", + sources: "sources", + grid: "coming", + evaluate: "coming", + predict: "coming", + draft: "coming", + review: "review", +}; + +/** {family, view, code, fact, canonical} from a location (or a URL). */ +export function parseLocation({ pathname = "/", search = "", hash = "" } = {}) { + const seg = (pathname || "/").split("/").filter(Boolean)[0] || ""; + const query = new URLSearchParams(search || ""); + const frag = String(hash || "").replace(/^#/, ""); + const legacy = VIEWS.includes(frag) ? frag : ""; + const local = legacy || !frag ? new URLSearchParams() : new URLSearchParams(frag); + const family = (query.get("family") || "").trim().toUpperCase(); + let view = VIEWS.includes(seg) ? seg : legacy || (family ? "dossier" : "contents"); + if (!family && FAMILY_VIEWS.includes(view)) view = "contents"; + const state = { + family, + view, + code: (local.get("code") || query.get("code") || "").trim(), + fact: (local.get("fact") || "").trim(), + }; + return { ...state, canonical: formatState(state) }; +} + +/** The canonical URL (path, query and fragment) of a state. */ +export function formatState({ family = "", view = "", code = "", fact = "" } = {}) { + let url = "/" + (VIEWS.includes(view) ? view : family ? "dossier" : "contents"); + if (family) url += "?family=" + encodeURIComponent(family); + const frag = []; + if (code) frag.push("code=" + encodeURIComponent(code)); + if (fact) frag.push("fact=" + encodeURIComponent(fact)); + return frag.length ? url + "#" + frag.join("&") : url; +} diff --git a/infra/gitea/custom/public/assets/dossier/view-coming.js b/infra/gitea/custom/public/assets/dossier/view-coming.js new file mode 100644 index 0000000..4bf9abd --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/view-coming.js @@ -0,0 +1,10 @@ +// lex · the coming views: Grid, Evaluate, Predict and Draft. A stub until S1 Task 6 fills it in. +// +// A view module exports needs (the API slices it reads), render(data, state) +// returning markup, and optionally mount(root, data, state, nav). + +export const needs = []; + +export function render() { + return `

This view is being built.

`; +} diff --git a/infra/gitea/custom/public/assets/dossier/view-contents.js b/infra/gitea/custom/public/assets/dossier/view-contents.js new file mode 100644 index 0000000..712a6c7 --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/view-contents.js @@ -0,0 +1,10 @@ +// lex · Contents view. A stub until S1 Task 6 fills it in. +// +// A view module exports needs (the API slices it reads), render(data, state) +// returning markup, and optionally mount(root, data, state, nav). + +export const needs = ["contents"]; + +export function render() { + return `

This view is being built.

`; +} diff --git a/infra/gitea/custom/public/assets/dossier/view-dossier.js b/infra/gitea/custom/public/assets/dossier/view-dossier.js new file mode 100644 index 0000000..619d7bd --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/view-dossier.js @@ -0,0 +1,10 @@ +// lex · Dossier view. A stub until S1 Task 6 fills it in. +// +// A view module exports needs (the API slices it reads), render(data, state) +// returning markup, and optionally mount(root, data, state, nav). + +export const needs = ["header"]; + +export function render() { + return `

This view is being built.

`; +} diff --git a/infra/gitea/custom/public/assets/dossier/view-payment.js b/infra/gitea/custom/public/assets/dossier/view-payment.js new file mode 100644 index 0000000..79653cb --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/view-payment.js @@ -0,0 +1,10 @@ +// lex · Payment view. A stub until S1 Task 8 fills it in. +// +// A view module exports needs (the API slices it reads), render(data, state) +// returning markup, and optionally mount(root, data, state, nav). + +export const needs = ["header", "payment"]; + +export function render() { + return `

This view is being built.

`; +} diff --git a/infra/gitea/custom/public/assets/dossier/view-politics.js b/infra/gitea/custom/public/assets/dossier/view-politics.js new file mode 100644 index 0000000..97272cc --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/view-politics.js @@ -0,0 +1,10 @@ +// lex · Politics view. A stub until S1 Task 9 fills it in. +// +// A view module exports needs (the API slices it reads), render(data, state) +// returning markup, and optionally mount(root, data, state, nav). + +export const needs = ["header", "politics"]; + +export function render() { + return `

This view is being built.

`; +} diff --git a/infra/gitea/custom/public/assets/dossier/view-review.js b/infra/gitea/custom/public/assets/dossier/view-review.js new file mode 100644 index 0000000..dc304b8 --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/view-review.js @@ -0,0 +1,10 @@ +// lex · Review view. A stub until S1 Task 6 fills it in. +// +// A view module exports needs (the API slices it reads), render(data, state) +// returning markup, and optionally mount(root, data, state, nav). + +export const needs = ["header"]; + +export function render() { + return `

This view is being built.

`; +} diff --git a/infra/gitea/custom/public/assets/dossier/view-sources.js b/infra/gitea/custom/public/assets/dossier/view-sources.js new file mode 100644 index 0000000..80820b6 --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/view-sources.js @@ -0,0 +1,10 @@ +// lex · Sources view. A stub until S1 Task 10 fills it in. +// +// A view module exports needs (the API slices it reads), render(data, state) +// returning markup, and optionally mount(root, data, state, nav). + +export const needs = ["header", "sources"]; + +export function render() { + return `

This view is being built.

`; +} diff --git a/infra/gitea/custom/public/assets/dossier/view-timeline.js b/infra/gitea/custom/public/assets/dossier/view-timeline.js new file mode 100644 index 0000000..1803869 --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/view-timeline.js @@ -0,0 +1,10 @@ +// lex · Timeline view. A stub until S1 Task 7 fills it in. +// +// A view module exports needs (the API slices it reads), render(data, state) +// returning markup, and optionally mount(root, data, state, nav). + +export const needs = ["header", "timeline"]; + +export function render() { + return `

This view is being built.

`; +} diff --git a/infra/gitea/custom/public/assets/dossier/view-valuation.js b/infra/gitea/custom/public/assets/dossier/view-valuation.js new file mode 100644 index 0000000..7be5c18 --- /dev/null +++ b/infra/gitea/custom/public/assets/dossier/view-valuation.js @@ -0,0 +1,10 @@ +// lex · Valuation view. A stub until S1 Task 7 fills it in. +// +// A view module exports needs (the API slices it reads), render(data, state) +// returning markup, and optionally mount(root, data, state, nav). + +export const needs = ["header", "valuation"]; + +export function render() { + return `

This view is being built.

`; +} diff --git a/tests/dev/test_dossier_page_build.py b/tests/dev/test_dossier_page_build.py new file mode 100644 index 0000000..3c5f697 --- /dev/null +++ b/tests/dev/test_dossier_page_build.py @@ -0,0 +1,209 @@ +"""dev/scripts/dossier_page/build.py: the lex app shell (lex S1 Task 5). + +The page carries no data: build.py inlines the fhirworx design system (R85) +and stamps the module version on the entry script. It imports stdlib only. +""" + +from __future__ import annotations + +import ast +import importlib.util +import os +import re +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +BUILD = ROOT / "dev/scripts/dossier_page/build.py" +TEMPLATE = ROOT / "dev/scripts/dossier_page/template.html" +ASSETS = ROOT / "infra/gitea/custom/public/assets/dossier" + +_spec = importlib.util.spec_from_file_location("_lex_page_build", BUILD) +build = importlib.util.module_from_spec(_spec) +sys.modules["_lex_page_build"] = build +_spec.loader.exec_module(build) + + +def _run(out: Path, **env: str) -> subprocess.CompletedProcess[str]: + e = {k: v for k, v in os.environ.items() if k != "DOMAIN"} | env + return subprocess.run( + [sys.executable, "-I", str(BUILD), "--out", str(out)], + capture_output=True, + text=True, + timeout=60, + check=False, + env=e, + cwd=out.parent, + ) + + +def test_build_writes_shell(tmp_path: Path) -> None: + out = tmp_path / "index.html" + r = _run(out) + assert r.returncode == 0, r.stderr + page = out.read_text(encoding="utf-8") + assert "/*__" not in page and "