feat(lex): the app shell — URL state, API client, citations, drawer; probe tooling (S1)

This commit is contained in:
kert
2026-11-13 03:33:19 -05:00
parent cb59a65d86
commit d70dbd2540
27 changed files with 2763 additions and 1760 deletions

View File

@@ -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.<domain>/``
(Traefik routers ``lex*``, behind ``git-sso``; the old address
``git.<domain>/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.<domain>``.
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 <path> (<n> bytes) v=<version>``. 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'<symbol id="fw-logo" viewBox="{vb.group(1)}">{m.group(2).strip()}</symbol>'
fw_css = FHIRWORX_CSS.read_text(encoding="utf-8")
if "</" in fw_css:
raise SystemExit(f"{FHIRWORX_CSS}: '</' would end the inline <style>")
def build_page(domain: str, version: str) -> str:
fw_css = FHIRWORX_CSS.read_text(encoding="utf-8")
if "</" in fw_css:
raise SystemExit(f"{FHIRWORX_CSS}: '</' would end the inline <style>")
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, "<!--__FW_LOGO__-->", _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 <script> element.
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, "<!--__FW_LOGO__-->", _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"),
)
# status line and footer
page = _fill(
page, "/*__BUILT__*/", html.escape(BUILT.strftime("%Y-%m-%d %H:%M %Z")), count=2
)
# navbar links back to Gitea (on lex.<domain>, "/" is this page), the
# masthead and footer address, the dashboard link, the tiles' deep links
page = _fill(page, "/*__DOMAIN__*/", html.escape(DOMAIN), count=6)
page = _fill(page, "/*__DATA__*/{}", blob.replace("<", "\\u003c"))
dst = args.out
dst.parent.mkdir(parents=True, exist_ok=True)
tmp = dst.with_name(f".{dst.name}.tmp")
tmp.write_text(page, encoding="utf-8")
os.replace(tmp, dst) # Gitea serves dst live: never expose a half-written page
print(f"wrote {dst} ({dst.stat().st_size:,} bytes)", file=sys.stderr)
named = sum(1 for c in commenters if c["name"])
print(
f"commenters {len(commenters)}; mirror ok {sum(c['mirror_ok'] for c in commenters)}; with a posted name {named}",
file=sys.stderr,
)
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
version = module_version(ASSETS)
page = build_page(os.environ.get("DOMAIN") or "fhirworx.io", version)
dst: Path = args.out
dst.parent.mkdir(parents=True, exist_ok=True)
tmp = dst.with_name(f".{dst.name}.tmp")
tmp.write_text(page, encoding="utf-8")
os.replace(tmp, dst) # Gitea serves dst live: never expose a half-written page
print(f"wrote {dst} ({dst.stat().st_size:,} bytes) v={version}")
return 0
if __name__ == "__main__":
sys.exit(main())

File diff suppressed because it is too large Load Diff

View File

@@ -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/<section>.json every section, the facts index included
DIR/fact/<id>.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())

379
dev/scripts/lex_probe.py Normal file
View File

@@ -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/<name>.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=<view>]`` 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())

View File

@@ -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;
}
}

View File

@@ -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 = `<p class="note">The book could not be loaded.</p>`;
}
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 = `<div class="d-head"><span class="eyebrow">Evidence · ${esc(id)}</span><button class="close" type="button" data-close>Close</button></div>`;
showDrawer(head + `<p class="small muted">Loading…</p>`);
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();

View File

@@ -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 `<a class="cite"${r} href="${esc(cite.url)}" target="_blank" rel="noopener">${esc(cite.label)}</a>`;
return `<span class="cite book"${r} title="${BOOK_TITLE}">${esc(cite.locator || cite.label)}</span>`;
}
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(`<span class="pill model">${esc(fact.note)}</span>`);
parts.push(esc(fact.text));
parts.push(...cites(fact).map((c) => citeHtml(c)));
if (fact.accuracy) parts.push(`<span class="acc">${esc(fact.accuracy)}</span>`);
return `<${tag} data-fact="${esc(fact.id)}" data-kind="${esc(fact.kind)}" tabindex="0">${parts.join(" ")}</${tag}>`;
}
/** 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 `<div class="ev-src"><div>${citeHtml(cite)}</div>${what ? `<div class="src-t">${esc(what)}</div>` : ""}</div>`;
}
/** 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 = `<div class="ev" data-evidence="${esc(fact.id)}">`;
h += `<div class="d-head"><span class="eyebrow">Evidence · ${esc(fact.id)}</span><button class="close" type="button" data-close>Close</button></div>`;
h += `<h3>${esc(head)}</h3>`;
if (fact.codes && fact.codes.length) h += `<div class="codes ev-codes">${fact.codes.map((c) => `<span class="code">${esc(c)}</span>`).join("")}</div>`;
if (fact.note) h += `<div class="ev-flags"><span class="pill model">${esc(fact.note)}</span></div>`;
h += `<p class="ev-text">${esc(fact.text)}</p>`;
if (fact.accuracy) h += `<p class="acc">${esc(fact.accuracy)}</p>`;
if (values.length) h += `<dl class="ev-dl">${values.map(([k, v]) => `<dt>${esc(k.replace(/_/g, " "))}</dt><dd>${esc(valueText(v))}</dd>`).join("")}</dl>`;
h += cites(fact).map(sourceHtml).join("");
return h + "</div>";
}

View File

@@ -0,0 +1,37 @@
// lex · formatting helpers (pure). Ported from the dossier snapshot.
const ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
/** 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`;
}

View File

@@ -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 = `<div class="d-head"><span class="eyebrow">Evidence</span></div><p class="small muted">Select a fact to read its evidence here: the text, its values and every source it cites.</p>`;
/** 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 `<a href="${esc(href)}" data-tab="${v}"${cls ? ` class="${cls}"` : ""}${on ? ' aria-current="page"' : ""}>${VIEW_TITLE[v]}</a>`;
});
return `<span class="grp">${esc(label)}</span>` + 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) =>
`<li${f.family === cur ? ' class="cur"' : ""} data-name="${nameKey(f.family, f.name, f.codes_text)}"><a href="${esc(formatState({ family: f.family, view: "dossier" }))}">${esc(f.name)}</a><span class="tier">${f.tier === "reviewed" ? "Built" : "Machine"}</span></li>`;
let h = "";
const reviewed = families.filter((f) => f.tier === "reviewed");
const machine = families.filter((f) => f.tier !== "reviewed");
if (reviewed.length) h += `<div class="eyebrow">Reviewed</div><ul class="toc">${reviewed.map(builtLi).join("")}</ul>`;
if (machine.length) h += `<div class="eyebrow toc-h">Machine-built · not reviewed</div><ul class="toc">${machine.map(builtLi).join("")}</ul>`;
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 += `<div class="eyebrow toc-h">Planned · ${esc(label)}</div><ul class="toc">`;
h += rows
.map(
(p) =>
`<li class="planned${p.family === cur ? " cur" : ""}" data-name="${nameKey(p.family, p.name, p.codes)}"><span>${esc(p.name)}</span><span class="tier">${p.status === "planned" ? "Planned" : "Curated"}</span></li>`,
)
.join("");
h += `</ul>`;
}
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 + `<p class="note">${esc(note)}</p>`;
}
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 `<div class="health health-${state}" role="status"><span class="health-k">${esc(k)}</span><span class="health-v">${esc(v)}</span>${note ? `<span class="status-note">${esc(note)}</span>` : ""}</div>`;
}
/** 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 `<div class="section-header"><span class="section-eyebrow">The book · CMS payment and quality regulation</span><h2>Contents</h2></div>`;
}
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" ? `<span class="badge">Reviewed dossier</span>` : `<span class="badge new">Machine-built · not reviewed</span>`;
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 `<div class="section-header"><div class="section-row"><span class="section-eyebrow">${esc(eyebrow)}</span>${badge}</div><h2>${esc(header.name)}</h2>${sub.length ? `<p class="section-sub">${esc(sub.join(" · "))}</p>` : ""}</div>`;
}
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) => `<a href="${esc(href)}">${text}</a>`;
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 = `<a href="/contents">Go to the contents</a> 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 `<div class="panel err" data-err="${kind}" role="alert"><h3>${esc(title)}</h3><p>${esc(body)}</p><p>${way}</p></div>`;
}

View File

@@ -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-<name>.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;
}

View File

@@ -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 `<p class="muted">This view is being built.</p>`;
}

View File

@@ -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 `<p class="muted">This view is being built.</p>`;
}

View File

@@ -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 `<p class="muted">This view is being built.</p>`;
}

View File

@@ -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 `<p class="muted">This view is being built.</p>`;
}

View File

@@ -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 `<p class="muted">This view is being built.</p>`;
}

View File

@@ -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 `<p class="muted">This view is being built.</p>`;
}

View File

@@ -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 `<p class="muted">This view is being built.</p>`;
}

View File

@@ -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 `<p class="muted">This view is being built.</p>`;
}

View File

@@ -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 `<p class="muted">This view is being built.</p>`;
}

View File

@@ -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 "<!--__" not in page
m = re.search(r'src="/assets/dossier/app\.js\?v=([0-9a-f]{12})"', page)
assert m, "entry module with its version"
assert '<script id="data"' not in page
assert "--fhirworx" in page or "--primary" in page
assert m.group(1) == build.module_version(ASSETS)
size = out.stat().st_size
assert r.stdout.strip() == f"wrote {out} ({size:,} bytes) v={m.group(1)}"
assert not list(tmp_path.glob(".*.tmp")), "written atomically"
def test_shell_structure(tmp_path: Path) -> None:
out = tmp_path / "index.html"
assert _run(out).returncode == 0
page = out.read_text(encoding="utf-8")
for el in (
'id="rail"',
'id="q"',
'id="toc"',
'id="main"',
'id="mast"',
'id="tabs"',
'id="view"',
'id="drawer"',
'id="status"',
'id="theme-btn"',
'id="tip"',
):
assert el in page, el
assert 'class="shell"' in page and 'class="masthead"' in page
# the theme bootstrap stays inline; the app is the one module script
assert 'localStorage.getItem("lex-theme")' in page
scripts = re.findall(r"<script\b([^>]*)>", page)
assert len(scripts) == 2, scripts
assert sum('type="module"' in s for s in scripts) == 1
assert not re.search(r'<script[^>]+src="(?!/assets/dossier/app\.js\?v=)', page)
assert "JSON.parse(document.getElementById" not in page
# the fhirworx logo symbol and the three favicons are inlined
assert '<symbol id="fw-logo"' in page
icons = re.findall(
r'<link rel="(?:icon|apple-touch-icon)"[^>]*href="data:image/', page
)
assert len(icons) == 3
assert ':root[data-theme="dark"] {' in page
def test_domain_fills(tmp_path: Path) -> None:
out = tmp_path / "index.html"
assert _run(out, DOMAIN="example.test").returncode == 0
page = out.read_text(encoding="utf-8")
assert "lex.example.test" in page
assert 'href="https://git.example.test/"' in page
assert 'href="https://dashboard.example.test/"' in page
assert "fhirworx.io" not in page
def test_build_imports_only_stdlib() -> None:
tree = ast.parse(BUILD.read_text(encoding="utf-8"))
mods = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
mods |= {a.name.split(".")[0] for a in node.names}
elif isinstance(node, ast.ImportFrom):
mods.add((node.module or "").split(".")[0])
assert mods, "no imports found"
assert mods <= set(sys.stdlib_module_names) | {"__future__"}, mods
def test_module_version(tmp_path: Path) -> None:
(tmp_path / "a.js").write_bytes(b"export const a = 1;\n")
(tmp_path / "b.js").write_bytes(b"export const b = 2;\n")
(tmp_path / "index.html").write_text("<p>page</p>")
v = build.module_version(tmp_path)
assert re.fullmatch(r"[0-9a-f]{12}", v)
(tmp_path / "index.html").write_text("<p>other</p>")
assert build.module_version(tmp_path) == v, "only *.js counts"
(tmp_path / "b.js").write_bytes(b"export const b = 3;\n")
v2 = build.module_version(tmp_path)
assert v2 != v
(tmp_path / "b.js").rename(tmp_path / "c.js")
assert build.module_version(tmp_path) != v2, "names count"
with pytest.raises(SystemExit, match="no \\*.js"):
build.module_version(tmp_path / "empty")
def test_fill_asserts_the_count() -> None:
assert build._fill("a X b", "X", "y") == "a y b"
assert build._fill("X X", "X", "y", count=2) == "y y"
with pytest.raises(SystemExit, match="expected 1 'X', found 2"):
build._fill("X X", "X", "y")
def test_default_out_is_the_served_page() -> None:
assert build.parse_args([]).out == ASSETS / "index.html"
def test_template_css_uses_tokens_only() -> None:
tpl = TEMPLATE.read_text(encoding="utf-8")
styles = re.findall(r"<style>(.*?)</style>", tpl, re.S)
assert len(styles) == 1, "one lex stylesheet besides the two inlined ones"
css = re.sub(r"/\*.*?\*/", "", styles[0], flags=re.S)
assert not re.search(r"#[0-9A-Fa-f]{3,8}\b", css), "a literal colour"
assert not re.search(r"\b(rgb|hsl)a?\(", css), "a literal colour"
for sel in (".err", ".acc", "[data-ref]", "[data-fact]"):
assert sel in css, sel
assert "cdn" not in tpl.lower()
def test_main_in_process(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
) -> None:
monkeypatch.setenv("DOMAIN", "example.test")
out = tmp_path / "sub" / "index.html"
assert build.main(["--out", str(out)]) == 0
v = build.module_version(ASSETS)
assert capsys.readouterr().out.strip() == (
f"wrote {out} ({out.stat().st_size:,} bytes) v={v}"
)
assert f'app.js?v={v}"' in out.read_text(encoding="utf-8")
def test_design_system_guards(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
css = tmp_path / "fw.css"
css.write_text(":root {\n --background: #fff;\n}\n/* </style> */\n")
monkeypatch.setattr(build, "FHIRWORX_CSS", css)
with pytest.raises(SystemExit, match="would end the inline"):
build.build_page("example.test", "0" * 12)
with pytest.raises(SystemExit, match="no :root block"):
build._root_vars(_write(tmp_path / "x.css", "a{}"))
with pytest.raises(SystemExit, match="cannot resolve --b"):
build._resolve({"--a": "var(--b)"}, "--a", css)
with pytest.raises(SystemExit, match="cannot resolve"):
build._resolve({"--a": "var(--a)"}, "--a", css) # a cycle
with pytest.raises(SystemExit, match="token --foreground is gone"):
build._dark_palette()
light = _write(
tmp_path / "light.css",
":root {\n" + "".join(f" --{t}: #000000;\n" for t in build.DARK_ROLES) + "}\n",
)
dark = _write(
tmp_path / "dark.css",
":root {\n"
+ "".join(f" {s}: #111111;\n" for s in set(build.DARK_ROLES.values()))
+ "}\n",
)
monkeypatch.setattr(build, "FHIRWORX_CSS", light)
monkeypatch.setattr(build, "GITEA_DARK", dark)
assert "--background: #111111; /* --fw-background */" in build._dark_palette()
_write(dark, dark.read_text().replace("--fw-card: #111111", "--fw-card: red"))
with pytest.raises(SystemExit, match="expected a hex colour"):
build._dark_palette()
icons = tmp_path / "icons"
icons.mkdir()
_write(icons / "logo.svg", "<svg><g/></svg>")
monkeypatch.setattr(build, "ICONS", icons)
with pytest.raises(SystemExit, match="expected one <svg viewBox"):
build._logo_symbol()
def _write(path: Path, text: str) -> Path:
path.write_text(text, encoding="utf-8")
return path

329
tests/dev/test_lex_probe.py Normal file
View File

@@ -0,0 +1,329 @@
"""dev/scripts/lex_probe.py and lex_dump_api.py: the lex headless probe and
the API dump its fixture mode serves (lex S1 Task 5, D13)."""
from __future__ import annotations
import importlib.util
import json
import re
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
def _load(name: str, path: Path):
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
sys.modules[name] = mod
spec.loader.exec_module(mod)
return mod
probe = _load("_lex_probe", ROOT / "dev/scripts/lex_probe.py")
dump = _load("_lex_dump_api", ROOT / "dev/scripts/lex_dump_api.py")
def test_route_target_mirrors_traefik() -> None:
rt = probe.route_target
assert rt("/api/policy/contents") == ("api", "/api/policy/contents")
assert rt("/api/policy/dossier/header") == ("api", "/api/policy/dossier/header")
assert rt("/assets/dossier/view-payment.js") == ("asset", "view-payment.js")
assert rt("/assets/dossier/app.js") == ("asset", "app.js")
for path in (
"/assets/dossier/%2e%2e/img/logo.svg",
"/assets/dossier/sub/x.js",
"/assets/dossier/X.js",
"/assets/dossier/index.html",
"/assets/dossier/1x.js",
"/api/policyx",
"/api/policy",
"/chat",
"/",
"/dossier",
):
assert rt(path) == ("page", ""), path
def test_probe_imports_without_playwright() -> None:
src = (ROOT / "dev/scripts/lex_probe.py").read_text(encoding="utf-8")
top = src.split("\ndef main(", 1)[0]
assert "playwright" not in re.sub(r'""".*?"""', "", top, flags=re.S)
def test_views_mirror_state_js() -> None:
js = (ROOT / "infra/gitea/custom/public/assets/dossier/state.js").read_text()
m = re.search(r"export const VIEWS = \[(.*?)\];", js, re.S)
assert m
assert list(probe.VIEWS) == re.findall(r'"([a-z]+)"', m.group(1))
def test_view_url() -> None:
assert probe.view_url("http://lex.test/", "timeline", "A/D") == (
"http://lex.test/timeline?family=A%2FD"
)
assert probe.view_url("http://lex.test", "contents", "HOME-VISITS") == (
"http://lex.test/contents?family=HOME-VISITS"
)
def test_host_rules() -> None:
assert probe.host_rules([]) is None
assert probe.host_rules(["lex.test=traefik"]) == "MAP lex.test traefik"
assert (
probe.host_rules(["a.test=b", "c.test=d:8080"])
== "MAP a.test b, MAP c.test d:8080"
)
for bad in ("nohost", "=x", "x=", "a b=c"):
with pytest.raises(SystemExit):
probe.host_rules([bad])
def test_console_noise() -> None:
assert probe.ignorable("https://fonts.googleapis.com/css2?family=x")
assert probe.ignorable("https://fonts.gstatic.com/s/a.woff2")
assert not probe.ignorable("http://lex.test/assets/dossier/app.js")
assert not probe.ignorable("")
def _api_dir(tmp_path: Path) -> Path:
d = tmp_path / "api"
(d / "dossier").mkdir(parents=True)
(d / "fact").mkdir()
(d / "contents.json").write_text("{}")
(d / "dossier/header.json").write_text("{}")
(d / "fact/F1.json").write_text("{}")
return d
def test_fixture_file(tmp_path: Path) -> None:
d = _api_dir(tmp_path)
ff = probe.fixture_file
assert ff(d, "/api/policy/contents", "", "HV") == (200, d / "contents.json")
assert ff(d, "/api/policy/dossier/header", "family=HV", "HV") == (
200,
d / "dossier/header.json",
)
assert ff(d, "/api/policy/dossier/header", "family=hv", "HV")[0] == 200
assert ff(d, "/api/policy/fact", "family=HV&id=F1", "HV") == (
200,
d / "fact/F1.json",
)
# a slash key travels encoded
assert ff(d, "/api/policy/dossier/header", "family=A%2FD", "A/D")[0] == 200
for path, query in (
("/api/policy/dossier/timeline", "family=HV"), # not dumped
("/api/policy/dossier/header", "family=CCM"), # another family
("/api/policy/dossier/header", ""),
("/api/policy/dossier/..", "family=HV"),
("/api/policy/dossier/a/b", "family=HV"),
("/api/policy/fact", "family=HV&id=F2"),
("/api/policy/fact", "family=HV&id=../x"),
("/api/policy/other", "family=HV"),
):
status, body = ff(d, path, query, "HV")
assert status == 404 and isinstance(body, dict), (path, query)
assert body["detail"]["message"]
assert ff(d, "/api/policy/dossier/header", "family=CCM", "HV")[1]["detail"] == {
"message": "No dossier is built for CCM yet.",
"family": "CCM",
"status": "unknown",
}
def test_fact_misses() -> None:
e = {"id": "F1", "url": "https://x.test/a", "locator": "", "label": "A", "also": []}
assert probe.fact_misses(e, ["https://x.test/a"], []) == []
assert probe.fact_misses(e, [], []) == ["F1: link https://x.test/a not rendered"]
b = {"id": "F2", "url": "", "locator": "CPT 2019 p. 20", "label": "x", "also": []}
assert probe.fact_misses(b, [], ["CPT 2019 p. 20"]) == []
assert probe.fact_misses(b, ["CPT 2019 p. 20"], []) == [
"F2: locator 'CPT 2019 p. 20' not rendered"
]
n = {"id": "F3", "url": "", "locator": "", "label": "Comment 1", "also": []}
assert probe.fact_misses(n, [], ["Comment 1"]) == []
a = {**e, "also": ["https://x.test/s", "https://x.test/t"]}
assert probe.fact_misses(a, ["https://x.test/a", "https://x.test/s"], []) == [
"F1: also https://x.test/t not rendered"
]
def test_fact_misses_book_also_cites() -> None:
# a licensed book also-cite has no url: one more locator span
e = {
"id": "F9",
"url": "https://x.test/a",
"locator": "",
"label": "A",
"also": ["", ""],
}
assert probe.fact_misses(e, ["https://x.test/a"], ["B 1", "B 2"]) == []
assert probe.fact_misses(e, ["https://x.test/a"], ["B 1"]) == [
"F9: 2 locator spans expected, 1 rendered"
]
b = {"id": "F8", "url": "", "locator": "B 0", "label": "x", "also": [""]}
assert probe.fact_misses(b, [], ["B 0", "B 1"]) == []
assert probe.fact_misses(b, [], ["B 0"]) == [
"F8: 2 locator spans expected, 1 rendered"
]
def test_facts_line() -> None:
assert probe.facts_line(546, 546, 540, 6) == (
"facts 546 rendered 546 links ok 540 locator-only 6"
)
def test_dump_layout_feeds_fixture_mode(tmp_path: Path) -> None:
calls = []
def load_slice(family: str, section: str) -> dict:
calls.append(section)
if section == "facts":
return {"facts": [{"id": "F1"}, {"id": "F2"}]}
return {"section": section, "family": family}
out = tmp_path / "api"
n = dump.dump(
out,
"HOME-VISITS",
load_slice=load_slice,
load_contents=lambda: {"families": []},
load_fact=lambda family, fid: {"id": fid, "family": family},
)
assert n == {"sections": 7, "facts": 2}
assert calls == list(dump.SECTIONS)
assert json.loads((out / "dossier/header.json").read_text()) == {
"section": "header",
"family": "HOME-VISITS",
}
assert json.loads((out / "fact/F2.json").read_text())["id"] == "F2"
ff = probe.fixture_file
assert ff(out, "/api/policy/contents", "", "HOME-VISITS")[0] == 200
for s in dump.SECTIONS:
assert (
ff(out, f"/api/policy/dossier/{s}", "family=HOME-VISITS", "HOME-VISITS")[0]
== 200
)
for fid in ("F1", "F2"):
assert (
ff(out, "/api/policy/fact", f"family=HOME-VISITS&id={fid}", "HOME-VISITS")[
0
]
== 200
)
def test_dump_sections_match_the_api() -> None:
from llm.policy_slices import SECTIONS
assert tuple(dump.SECTIONS) == tuple(SECTIONS)
class _Route:
def __init__(self, url: str) -> None:
self.request = type("R", (), {"url": url})()
self.done: dict | None = None
def continue_(self) -> None:
self.done = {"continued": True}
def fulfill(self, **kw) -> None:
self.done = kw
def test_fixture_routes(tmp_path: Path) -> None:
api = _api_dir(tmp_path)
(api / "dossier/header.json").write_text('{"name": "H"}')
assets = tmp_path / "assets"
assets.mkdir()
(assets / "app.js").write_text("export {};")
page = tmp_path / "index.html"
page.write_text("<p>page</p>")
args = probe.parse_args(
[
"--base",
"http://lex.test",
"--family",
"HV",
"--check",
"smoke",
"--fixture",
str(api),
"--assets",
str(assets),
"--page",
str(page),
]
)
seen = {}
class Ctx:
def route(self, pattern: str, handler) -> None:
seen[pattern] = handler
probe._install_fixture(Ctx(), args)
handle = seen["**/*"]
def hit(url: str) -> dict:
r = _Route(url)
handle(r)
return r.done
assert hit("https://fonts.googleapis.com/css2?x") == {"continued": True}
d = hit("http://lex.test/api/policy/dossier/header?family=HV")
assert d["status"] == 200 and d["body"] == b'{"name": "H"}'
assert d["content_type"] == "application/json"
d = hit("http://lex.test/api/policy/dossier/payment?family=HV")
assert d["status"] == 404 and json.loads(d["body"])["detail"]["message"]
d = hit("http://lex.test/assets/dossier/app.js?v=abc")
assert (d["status"], d["content_type"], d["body"]) == (
200,
"text/javascript",
b"export {};",
)
assert hit("http://lex.test/assets/dossier/state.js")["status"] == 404
for url in (
"http://lex.test/timeline?family=HV",
"http://lex.test/assets/dossier/X.js",
):
d = hit(url)
assert d["status"] == 200 and d["body"] == b"<p>page</p>", url
assert d["content_type"].startswith("text/html")
def test_parse_args_fixture_trio() -> None:
base = ["--base", "http://lex.test", "--family", "HV", "--check", "facts"]
a = probe.parse_args([*base, "--map", "a.test=b", "--map", "c.test=d"])
assert a.map == ["a.test=b", "c.test=d"] and a.fixture is None
with pytest.raises(SystemExit):
probe.parse_args([*base, "--fixture", "/x"])
with pytest.raises(SystemExit):
probe.parse_args([*base[:4], "--check", "other"])
def test_dump_main(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys) -> None:
from llm import config, policy
cfg = object()
monkeypatch.setattr(config, "load", lambda: cfg)
monkeypatch.setattr(
policy,
"load_slice",
lambda c, family, section: (
{"facts": [{"id": "F1"}]} if section == "facts" else {"s": section}
),
)
monkeypatch.setattr(policy, "load_contents", lambda c: {"families": []})
monkeypatch.setattr(policy, "load_fact", lambda c, family, fid: {"id": fid})
out = tmp_path / "api"
assert dump.main(["--family", "HV", "--out", str(out)]) == 0
assert json.loads((out / "fact/F1.json").read_text()) == {"id": "F1"}
assert json.loads((out / "dossier/valuation.json").read_text()) == {
"s": "valuation"
}
assert capsys.readouterr().out.strip() == (
f"wrote {out}: contents, 7 sections, 1 facts"
)

0
tests/lex/__init__.py Normal file
View File

220
tests/lex/api.test.mjs Normal file
View File

@@ -0,0 +1,220 @@
// lex API client: errors the page can render, and one build per page.
import { test } from "node:test";
import { deepEqual as deq, equal as eq, ok, rejects } from "node:assert/strict";
import { readFileSync } from "node:fs";
import {
CONTENTS_PATH,
DossierStore,
NotFound,
Rebuilt,
SignedOut,
Unavailable,
factPath,
getJSON,
sectionPath,
} from "../../infra/gitea/custom/public/assets/dossier/api.js";
const fx = (name) => JSON.parse(readFileSync(new URL(`./fixtures/${name}.json`, import.meta.url), "utf8"));
/** A fetch Response stand-in (a real Response cannot be an opaque redirect). */
function res({ status = 200, type = "basic", ct = "application/json", body = {} } = {}) {
return {
status,
type,
ok: status >= 200 && status < 300,
headers: new Headers(ct ? { "content-type": ct } : {}),
json: async () => (typeof body === "string" ? JSON.parse(body) : body),
text: async () => (typeof body === "string" ? body : JSON.stringify(body)),
};
}
/** A fetch that answers from a list per path prefix and records each call. */
function fake(routes) {
const calls = [];
const left = Object.fromEntries(Object.entries(routes).map(([k, v]) => [k, Array.isArray(v) ? [...v] : [v]]));
const impl = async (path, init) => {
calls.push({ path, init });
const key = Object.keys(left).find((k) => path.startsWith(k));
if (!key) return res({ status: 404, body: { detail: { message: "no route" } } });
const q = left[key];
const r = q.length > 1 ? q.shift() : q[0];
return typeof r === "function" ? r() : r;
};
impl.calls = calls;
return impl;
}
test("paths: section, contents, fact", () => {
eq(sectionPath("timeline", "A/D"), "/api/policy/dossier/timeline?family=A%2FD");
eq(CONTENTS_PATH, "/api/policy/contents");
eq(factPath("A/D", "F12"), "/api/policy/fact?family=A%2FD&id=F12");
});
test("getJSON asks for a manual redirect and returns the body", async () => {
const f = fake({ "/x": res({ body: { a: 1 } }) });
deq(await getJSON("/x", f), { a: 1 });
eq(f.calls[0].init.redirect, "manual");
});
test("opaque redirect is SignedOut", async () => {
await rejects(getJSON("/x", fake({ "/x": res({ status: 0, type: "opaqueredirect", ct: "" }) })), SignedOut);
});
test("status 0 is SignedOut", async () => {
await rejects(getJSON("/x", fake({ "/x": res({ status: 0, ct: "" }) })), SignedOut);
});
test("html body is SignedOut", async () => {
await rejects(getJSON("/x", fake({ "/x": res({ ct: "text/html; charset=utf-8", body: "<html>sign in</html>" }) })), SignedOut);
});
test("401 and 403 are SignedOut", async () => {
await rejects(getJSON("/x", fake({ "/x": res({ status: 401 }) })), SignedOut);
await rejects(getJSON("/x", fake({ "/x": res({ status: 403, ct: "text/plain" }) })), SignedOut);
});
test("404 is NotFound with the family's status", async () => {
const body = { detail: { message: "No dossier is built for CCM yet.", family: "CCM", status: "planned" } };
const err = await getJSON("/x", fake({ "/x": res({ status: 404, body }) })).catch((e) => e);
ok(err instanceof NotFound);
eq(err.status, "planned");
eq(err.family, "CCM");
eq(err.message, "No dossier is built for CCM yet.");
});
test("a 404 without a JSON detail is NotFound with no status", async () => {
const err = await getJSON("/x", fake({ "/x": res({ status: 404, ct: "application/json", body: "{}" }) })).catch((e) => e);
ok(err instanceof NotFound);
eq(err.status, "");
});
test("503 is Unavailable, as are 502 and 504 from the proxy", async () => {
const body = { detail: { message: "The data replica is not available." } };
const err = await getJSON("/x", fake({ "/x": res({ status: 503, body }) })).catch((e) => e);
ok(err instanceof Unavailable);
eq(err.message, "The data replica is not available.");
await rejects(getJSON("/x", fake({ "/x": res({ status: 502, ct: "text/plain", body: "Bad Gateway" }) })), Unavailable);
await rejects(getJSON("/x", fake({ "/x": res({ status: 504, ct: "" }) })), Unavailable);
});
test("a network failure is Unavailable", async () => {
await rejects(getJSON("/x", async () => { throw new TypeError("Failed to fetch"); }), Unavailable);
});
test("another error status is a plain Error naming it", async () => {
const err = await getJSON("/x", fake({ "/x": res({ status: 400, body: { detail: { message: "invalid family key" } } }) })).catch((e) => e);
ok(err instanceof Error && !(err instanceof NotFound) && !(err instanceof SignedOut));
ok(err.message.includes("400"));
ok(err.message.includes("invalid family key"));
});
const H = fx("header");
const T = fx("timeline");
const at = (slice, built_at) => ({ ...slice, built_at });
test("the store loads what a view needs, adds the header, and caches", async () => {
const f = fake({
"/api/policy/dossier/header": res({ body: H }),
"/api/policy/dossier/timeline": res({ body: T }),
"/api/policy/contents": res({ body: fx("contents") }),
});
const s = new DossierStore("HOME-VISITS", f);
const d = await s.load(["timeline", "contents"]);
eq(d.header.name, H.name);
eq(d.timeline.events.length, T.events.length);
eq(d.contents.families[0].family, "HOME-VISITS");
eq(f.calls.length, 3);
await s.load(["header", "timeline"]);
eq(f.calls.length, 3, "a second load is served from the cache");
ok(f.calls.every((c) => c.init.redirect === "manual"));
ok(f.calls.some((c) => c.path === "/api/policy/dossier/timeline?family=HOME-VISITS"));
});
test("mixed builds refetch", async () => {
const f = fake({
"/api/policy/dossier/header": [res({ body: at(H, "T1") }), res({ body: at(H, "T2") })],
"/api/policy/dossier/timeline": res({ body: at(T, "T2") }),
});
const d = await new DossierStore("HOME-VISITS", f).load(["header", "timeline"]);
eq(d.header.built_at, "T2");
eq(d.timeline.built_at, "T2");
eq(f.calls.filter((c) => c.path.startsWith("/api/policy/dossier/header")).length, 2);
eq(f.calls.filter((c) => c.path.startsWith("/api/policy/dossier/timeline")).length, 2);
});
test("a slice cached from an older build is refetched", async () => {
const f = fake({
"/api/policy/dossier/header": [res({ body: at(H, "T1") }), res({ body: at(H, "T2") })],
"/api/policy/dossier/timeline": res({ body: at(T, "T2") }),
});
const s = new DossierStore("HOME-VISITS", f);
eq((await s.load(["header"])).header.built_at, "T1");
const d = await s.load(["timeline"]);
eq(d.header.built_at, "T2");
});
test("persistent mismatch is Rebuilt", async () => {
const f = fake({
"/api/policy/dossier/header": res({ body: at(H, "T1") }),
"/api/policy/dossier/timeline": res({ body: at(T, "T2") }),
});
await rejects(new DossierStore("HOME-VISITS", f).load(["header", "timeline"]), Rebuilt);
eq(f.calls.length, 4, "one refetch, then Rebuilt");
});
test("contents and the facts index carry no build check (S1-P1)", async () => {
const f = fake({
"/api/policy/dossier/header": res({ body: at(H, "T1") }),
"/api/policy/dossier/facts": res({ body: at(fx("facts"), "T0") }),
"/api/policy/contents": res({ body: fx("contents") }),
});
const d = await new DossierStore("HOME-VISITS", f).load(["header", "facts", "contents"]);
eq(d.facts.built_at, "T0");
eq(f.calls.length, 3);
});
test("every per-family slice is checked: sources too", async () => {
const f = fake({
"/api/policy/dossier/header": res({ body: at(H, "T1") }),
"/api/policy/dossier/sources": res({ body: at(fx("sources"), "T2") }),
});
await rejects(new DossierStore("HOME-VISITS", f).load(["sources"]), Rebuilt);
});
test("a failed slice is not cached", async () => {
const f = fake({
"/api/policy/dossier/header": [res({ status: 503 }), res({ body: H })],
});
const s = new DossierStore("HOME-VISITS", f);
await rejects(s.load(["header"]), Unavailable);
eq((await s.load(["header"])).header.name, H.name);
});
test("the contents store needs no family", async () => {
const f = fake({ "/api/policy/contents": res({ body: fx("contents") }) });
const d = await new DossierStore("", f).load(["contents"]);
deq(Object.keys(d), ["contents"]);
});
test("fact(id) reads a loaded slice before asking the API", async () => {
const f = fake({
"/api/policy/dossier/header": res({ body: H }),
"/api/policy/dossier/timeline": res({ body: T }),
"/api/policy/fact": res({ body: { ...T.facts.F3, id: "F99" } }),
});
const s = new DossierStore("HOME-VISITS", f);
await s.load(["timeline"]);
eq((await s.fact("F3")).text, T.facts.F3.text);
eq((await s.fact("F2")).note, "model paraphrase, unreviewed");
eq(f.calls.length, 2);
eq((await s.fact("F99")).id, "F99");
eq(f.calls[2].path, "/api/policy/fact?family=HOME-VISITS&id=F99");
await s.fact("F99");
eq(f.calls.length, 3, "a fetched fact is cached");
});
test("fact(id) for an unknown id is NotFound", async () => {
const f = fake({ "/api/policy/fact": res({ status: 404, body: { detail: { message: "unknown fact", family: "HOME-VISITS", id: "F404" } } }) });
await rejects(new DossierStore("HOME-VISITS", f).fact("F404"), NotFound);
});

148
tests/lex/cite.test.mjs Normal file
View File

@@ -0,0 +1,148 @@
// lex citations (R10): the page renders cite.url, or cite.locator when the url
// is empty, exactly as the API gives them; a licensed book never links.
import { test } from "node:test";
import { equal as eq, ok } from "node:assert/strict";
import { readFileSync } from "node:fs";
import { citeHtml, evidenceHtml, factHtml, tagged } from "../../infra/gitea/custom/public/assets/dossier/cite.js";
const fx = (name) => JSON.parse(readFileSync(new URL(`./fixtures/${name}.json`, import.meta.url), "utf8"));
const H = fx("header");
const P = fx("politics");
const facts = { ...H.facts, ...fx("timeline").facts, ...fx("valuation").facts, ...P.facts };
const count = (s, sub) => s.split(sub).length - 1;
test("a cite with a url is a link that opens apart", () => {
const c = facts.F4.cite;
eq(citeHtml(c), `<a class="cite" href="${c.url}" target="_blank" rel="noopener">${c.label}</a>`);
});
test("no url renders a locator span", () => {
const h = citeHtml(H.facts.F2.cite);
ok(!h.includes("href"));
ok(h.startsWith('<span class="cite book"'));
ok(h.includes("CPT 2019 p. 20"));
ok(h.includes('title="Cited by edition and page; text not reproduced"'));
});
test("the label stands in when there is neither url nor locator", () => {
ok(citeHtml({ kind: "comment", label: "Comment 9", url: "", locator: "" }).includes(">Comment 9</span>"));
});
test("a licensed book never links, even when a url is set", () => {
const h = citeHtml({ ...H.facts.F2.cite, url: "https://example.test/book" });
ok(!h.includes("href"));
ok(h.includes("CPT 2019 p. 20"));
});
test("a url that is not http(s) is never put in an href", () => {
const h = citeHtml({ kind: "fr_para", label: "x", url: "javascript:alert(1)", locator: "L 1" });
ok(!h.includes("href"));
ok(!h.includes("javascript"));
ok(h.includes("L 1"));
});
test("label <b>& is escaped, and the url is not rewritten", () => {
const h = citeHtml({ kind: "fr_para", label: "<b>&", url: "https://example.test/a?b=1&c=2#p3", locator: "" });
ok(h.includes(">&lt;b&gt;&amp;</a>"));
ok(!h.includes("<b>"));
ok(h.includes('href="https://example.test/a?b=1&amp;c=2#p3"'));
});
test("an empty cite renders nothing", () => {
eq(citeHtml(null), "");
eq(citeHtml(undefined), "");
});
test("also cites render", () => {
const h = factHtml(H.facts.F1);
eq(count(h, 'class="cite"'), 2);
ok(h.includes('href="https://example.test/statute/9999"'));
});
test("factHtml carries the id, kind, note pill and text", () => {
const h = factHtml(H.facts.F2);
ok(h.startsWith("<li "));
ok(h.includes('data-fact="F2"'));
ok(h.includes('data-kind="formation"'));
ok(h.includes('<span class="pill model">model paraphrase, unreviewed</span>'));
ok(h.includes("Invented formation paraphrase."));
ok(h.endsWith("</li>"));
});
test("factHtml without a note has no pill", () => {
ok(!factHtml(H.facts.F1).includes("pill"));
});
test("factHtml takes another tag", () => {
const h = factHtml(H.facts.F1, { tag: "div" });
ok(h.startsWith("<div ") && h.endsWith("</div>"));
});
test("factHtml carries a stance split's accuracy", () => {
const h = factHtml(P.facts.F8);
ok(h.includes(`<span class="acc">${P.facts.F8.accuracy}</span>`));
ok(!factHtml(P.facts.F7).includes('class="acc"'), "the accuracy is in F7's own text");
});
test("factHtml escapes the text", () => {
ok(factHtml({ ...H.facts.F1, text: "a <i>b</i> & c" }).includes("a &lt;i&gt;b&lt;/i&gt; &amp; c"));
});
test("tagged turns each [F#] into its cite, once per run", () => {
const h = tagged("A [F4]. B [F3][F3].", facts);
eq(count(h, "<a "), 2);
eq(count(h, 'data-ref="F4"'), 1);
eq(count(h, 'data-ref="F3"'), 1);
ok(h.startsWith("A <a "));
ok(!h.includes("[F"));
});
test("tagged keeps an unknown tag as text and escapes the rest", () => {
const h = tagged("x [F99] <y>", facts);
ok(h.includes("[F99]"));
ok(h.includes("&lt;y&gt;"));
ok(!h.includes("data-ref"));
});
test("tagged renders a book fact as its locator span", () => {
const h = tagged("formed [F2].", facts);
ok(h.includes('data-ref="F2"'));
ok(!h.includes("href"));
ok(h.includes("CPT 2019 p. 20"));
});
test("tagged of empty text is empty", () => {
eq(tagged("", facts), "");
eq(tagged(null, facts), "");
});
test("evidenceHtml shows kind, year, codes, text, note, cites and values", () => {
const h = evidenceHtml(facts.F4);
ok(h.includes('data-evidence="F4"'));
ok(h.includes("Valuation round") || h.includes("round"));
ok(h.includes("CY2023"));
ok(h.includes("99341"));
ok(h.includes("Invented valuation round text."));
ok(h.includes('href="https://example.test/fr/PETM225D#p1676"'));
ok(h.includes("<dl"));
ok(h.includes("<dt>final work rvu</dt><dd>1.5</dd>"));
ok(h.includes("data-close"));
});
test("evidenceHtml lists every also cite and the note; empty values are left out", () => {
const h = evidenceHtml(H.facts.F1);
eq(count(h, 'class="cite"'), 2);
ok(!h.includes("<dt>"), "F1 has no values, year and codes go in the head");
const b = evidenceHtml({ ...H.facts.F2, values: { a: "", b: null, c: [], d: 0, e: ["x", "y"], f: { g: 1 } } });
ok(b.includes("model paraphrase, unreviewed"));
ok(!b.includes("href"));
ok(!b.includes("<dt>a</dt>") && !b.includes("<dt>b</dt>") && !b.includes("<dt>c</dt>"));
ok(b.includes("<dt>d</dt><dd>0</dd>"));
ok(b.includes("<dt>e</dt><dd>x, y</dd>"));
ok(b.includes("<dt>f</dt><dd>{&quot;g&quot;:1}</dd>"));
});
test("evidenceHtml carries a stance split's accuracy", () => {
ok(evidenceHtml(P.facts.F8).includes(P.facts.F8.accuracy));
});

193
tests/lex/shell.test.mjs Normal file
View File

@@ -0,0 +1,193 @@
// lex shell: tabs, the book rail, masthead status, error panels; fmt helpers;
// the view modules' contract.
import { test } from "node:test";
import { deepEqual as deq, equal as eq, ok } from "node:assert/strict";
import { readFileSync } from "node:fs";
import { NotFound, Rebuilt, SignedOut, Unavailable } from "../../infra/gitea/custom/public/assets/dossier/api.js";
import { builtText, compact, esc, int, money, n2, uniq } from "../../infra/gitea/custom/public/assets/dossier/fmt.js";
import { errorHtml, headHtml, mastHtml, railHtml, tabsHtml } from "../../infra/gitea/custom/public/assets/dossier/shell.js";
import { VIEWS, VIEW_MODULE, parseLocation } from "../../infra/gitea/custom/public/assets/dossier/state.js";
const fx = (name) => JSON.parse(readFileSync(new URL(`./fixtures/${name}.json`, import.meta.url), "utf8"));
const C = fx("contents");
const H = fx("header");
const st = (url) => parseLocation(new URL(url, "https://lex.test"));
test("tabsHtml marks the current tab and links each view", () => {
const h = tabsHtml(st("/timeline?family=HOME-VISITS"));
ok(/<a href="\/timeline\?family=HOME-VISITS"[^>]*class="on"[^>]*aria-current="page"/.test(h), h);
eq((h.match(/aria-current/g) || []).length, 1);
ok(h.includes('href="/dossier?family=HOME-VISITS"'));
ok(h.includes('href="/contents?family=HOME-VISITS"'));
ok(h.includes('<span class="grp">HOME-VISITS</span>'));
});
test("coming tabs are class soon", () => {
const h = tabsHtml(st("/dossier?family=HOME-VISITS"));
for (const v of ["grid", "evaluate", "predict", "draft", "review"]) {
ok(new RegExp(`<a href="/${v}\\?family=HOME-VISITS"[^>]*class="soon"`).test(h), v);
}
for (const v of ["dossier", "timeline", "valuation", "payment", "politics", "sources"]) {
ok(!new RegExp(`<a href="/${v}\\?family=HOME-VISITS"[^>]*soon`).test(h), v);
}
ok(/class="soon on"[^>]*aria-current/.test(tabsHtml(st("/review?family=HOME-VISITS"))));
});
test("without a family only Contents is a tab", () => {
const h = tabsHtml(st("/contents"));
ok(/<a href="\/contents"[^>]*class="on"/.test(h));
eq((h.match(/<a /g) || []).length, 1);
});
test("the family key is encoded in tab links and escaped as the group label", () => {
const h = tabsHtml(st("/dossier?family=A%2FD%3CX"));
ok(h.includes('href="/timeline?family=A%2FD%3CX"'));
ok(h.includes('<span class="grp">A/D&lt;X</span>'));
});
test("signed-out panel links to the current URL", () => {
const href = "https://lex.test/timeline?family=HOME-VISITS#code=99343&fact=F12";
const h = errorHtml(new SignedOut(), st(href), href);
ok(h.includes("Signed out"));
ok(h.includes(`href="${esc(href)}"`));
ok(h.includes('role="alert"'));
ok(h.includes('class="panel err"'));
});
test("not-found panel names the status", () => {
const err = new NotFound("No dossier is built for CCM yet.", { family: "CCM", status: "planned" });
const h = errorHtml(err, st("/dossier?family=CCM"), "https://lex.test/dossier?family=CCM");
ok(h.includes("planned"));
ok(h.includes("CCM"));
ok(h.includes('href="/contents"'));
for (const status of ["curated", "derived", "unknown", ""]) {
const x = errorHtml(new NotFound("m", { family: "X", status }), st("/dossier?family=X"), "u");
ok(x.includes('href="/contents"'), status);
ok(x.includes(status || "No dossier"), status);
}
});
test("unavailable panel", () => {
const href = "https://lex.test/payment?family=HOME-VISITS";
const h = errorHtml(new Unavailable("The data replica is not available."), st(href), href);
ok(h.includes("Unavailable"));
ok(h.includes("not available"));
ok(h.includes(`href="${href}"`));
});
test("rebuilt panel asks for a reload", () => {
const href = "https://lex.test/payment?family=HOME-VISITS";
const h = errorHtml(new Rebuilt(), st(href), href);
ok(h.includes("rebuilt"));
ok(h.includes(`href="${href}"`));
});
test("any other error is a panel with its message escaped, never a blank pane", () => {
const h = errorHtml(new Error("boom <x>"), st("/dossier?family=X"), "u");
ok(h.includes("boom &lt;x&gt;"));
ok(h.includes('href="u"'));
});
test("railHtml links built families and marks the current one", () => {
const h = railHtml(C, st("/payment?family=HOME-VISITS"));
ok(/<li class="cur"[^>]*><a href="\/dossier\?family=HOME-VISITS"/.test(h), h);
ok(h.includes("Home or Residence Services"));
});
test("railHtml: planned rows have no <a>", () => {
const h = railHtml(C, st("/contents"));
const planned = h.match(/<li class="planned[^"]*"[^>]*>.*?<\/li>/g) || [];
eq(planned.length, C.planned.length);
ok(planned.every((li) => !li.includes("<a ")));
ok(!h.includes('class="cur"'), "no current family on the contents");
});
test("railHtml search names cover family, name and codes", () => {
const h = railHtml(C, st("/contents"));
ok(h.includes('data-name="home-visits home or residence services 99341 and 99343"'));
ok(h.includes('data-name="ccm chronic care management (ccm) 99490'));
});
test("railHtml ends with the machine-tier note", () => {
const h = railHtml(C, st("/contents"));
ok(h.trimEnd().endsWith("</p>"));
ok(h.includes('<p class="note">'));
ok(h.includes(`${C.machine.derived.toLocaleString("en-US")} derived code families`));
ok(railHtml({ ...C, machine: null }, st("/contents")).includes("machine-built"));
});
test("railHtml marks a machine-tier family and a planned current family", () => {
const fam = { ...C.families[0], family: "X-1", name: "Derived X", tier: "machine" };
const h = railHtml({ ...C, families: [...C.families, fam] }, st("/dossier?family=CCM"));
ok(/<li[^>]*><a href="\/dossier\?family=X-1">Derived X<\/a><span class="tier">Machine<\/span>/.test(h), h);
ok(/<li class="planned cur"[^>]*><span>Chronic care management \(CCM\)<\/span>/.test(h), h);
});
test("mastHtml: live status of the family's build", () => {
const h = mastHtml(st("/dossier?family=HOME-VISITS"), H, C);
ok(h.includes("Live"));
ok(h.includes("HOME-VISITS dossier built 2026-11-13 05:23 UTC"));
ok(h.includes("citation check passed"));
ok(h.includes("health-ok"));
const bad = mastHtml(st("/dossier?family=HOME-VISITS"), { ...H, check_passed: false, tier: "machine" }, C);
ok(bad.includes("citation check failed") && bad.includes("health-warn"));
ok(bad.includes("machine-built, not reviewed"));
});
test("mastHtml: the book's status on the contents, and while loading", () => {
const h = mastHtml(st("/contents"), null, C);
ok(h.includes("Live"));
ok(h.includes("1 dossier built"));
ok(h.includes("2026-11-13 05:23 UTC"));
ok(mastHtml(st("/contents"), null, null).includes("health-unknown"));
});
test("headHtml: family header and contents header", () => {
const h = headHtml(st("/dossier?family=HOME-VISITS"), H);
ok(h.includes("<h2>Home or Residence Services</h2>"));
ok(h.includes("HOME-VISITS"));
ok(h.includes("Reviewed dossier"));
ok(h.includes("phase 1"));
ok(h.includes("Active 99341 · deleted 99343 · linked G0318 · years 2007–2027"));
ok(headHtml(st("/dossier?family=X"), { ...H, code_groups: { active: ["99341", "99342", "99343", "99345"] } }).includes("Active 99341–99343, 99345"));
ok(headHtml(st("/dossier?family=HOME-VISITS"), { ...H, tier: "machine", phase: null }).includes("Machine-built"));
ok(headHtml(st("/contents"), null).includes("<h2>Contents</h2>"));
});
test("fmt: esc, compact, money, n2, int, uniq", () => {
eq(esc(`<a href="x">'&'</a>`), "&lt;a href=&quot;x&quot;&gt;&#39;&amp;&#39;&lt;/a&gt;");
eq(esc(null), "");
eq(esc(0), "0");
eq(compact(["99343", "99341", "99342", "99344", "G0318", "99350", "99341"]), "99341–99344, 99350, G0318");
eq(compact(["99341", "99342"]), "99341, 99342");
eq(compact([]), "");
eq(money(12.5), "$12.50");
eq(money(null), "—");
eq(n2(1.5), "1.50");
eq(n2(undefined), "—");
eq(int(12106.4), "12,106");
eq(int(null), "—");
deq(uniq(["a", "b", "a"]), ["a", "b"]);
});
test("fmt: builtText", () => {
eq(builtText("2026-11-13T05:23:37"), "2026-11-13 05:23 UTC");
eq(builtText("2026-11-13T05:23:37.123456"), "2026-11-13 05:23 UTC");
eq(builtText("2026-11-13T00:23:37-05:00"), "2026-11-13 05:23 UTC");
eq(builtText("2026-11-13T05:23:37Z"), "2026-11-13 05:23 UTC");
eq(builtText(""), "");
eq(builtText(null), "");
});
test("every view has a module with needs and render", async () => {
deq(Object.keys(VIEW_MODULE), VIEWS);
deq(uniq(Object.values(VIEW_MODULE)).sort(), ["coming", "contents", "dossier", "payment", "politics", "review", "sources", "timeline", "valuation"]);
for (const name of uniq(Object.values(VIEW_MODULE))) {
const m = await import(`../../infra/gitea/custom/public/assets/dossier/view-${name}.js`);
ok(Array.isArray(m.needs), name);
ok(m.needs.every((n) => ["contents", "header", "timeline", "valuation", "payment", "politics", "sources", "facts"].includes(n)), name);
eq(typeof m.render, "function", name);
if (m.mount) eq(typeof m.mount, "function", name);
}
});

88
tests/lex/state.test.mjs Normal file
View File

@@ -0,0 +1,88 @@
// lex URL state (D1): the path is the view, ?family= the only query parameter,
// the fragment holds view-local state. Run: node --test tests/lex/*.test.mjs
import { test } from "node:test";
import { deepEqual as deq, equal as eq, ok } from "node:assert/strict";
import {
FAMILY_VIEWS,
VIEWS,
formatState,
parseLocation,
} from "../../infra/gitea/custom/public/assets/dossier/state.js";
const at = (pathname, search = "", hash = "") => parseLocation({ pathname, search, hash });
test("views and family views", () => {
deq(VIEWS, ["contents", "dossier", "timeline", "valuation", "payment", "politics", "sources", "grid", "evaluate", "predict", "draft", "review"]);
deq(FAMILY_VIEWS, VIEWS.filter((v) => v !== "contents"));
});
test("R98's /?family=KEY#dossier is rewritten to the path form", () => {
eq(at("/", "?family=HOME-VISITS", "#dossier").canonical, "/dossier?family=HOME-VISITS");
});
test("path view, upper-cased family, fragment code and fact", () => {
const s = at("/timeline", "?family=home-visits", "#code=99343&fact=F12");
deq([s.family, s.view, s.code, s.fact], ["HOME-VISITS", "timeline", "99343", "F12"]);
eq(s.canonical, "/timeline?family=HOME-VISITS#code=99343&fact=F12");
});
test("no family and no view is the contents", () => {
eq(at("/").canonical, "/contents");
eq(at("/", "", "").view, "contents");
});
test("an unknown path with a family is the dossier", () => {
eq(at("/nonsense", "?family=X").view, "dossier");
eq(at("/nonsense", "?family=X").canonical, "/dossier?family=X");
});
test("a family view without a family falls back to contents", () => {
eq(at("/", "", "#timeline").view, "contents");
eq(at("/payment").view, "contents");
eq(at("/payment").canonical, "/contents");
});
test("the snapshot's bare #view is read when the path names none", () => {
eq(at("/", "?family=HOME-VISITS", "#payment").view, "payment");
// the path wins over a legacy fragment
eq(at("/politics", "?family=HOME-VISITS", "#payment").view, "politics");
});
test("a stray ?code= moves to the fragment", () => {
eq(at("/payment", "?family=HOME-VISITS&code=99350").canonical, "/payment?family=HOME-VISITS#code=99350");
// the fragment wins over the query
eq(at("/payment", "?family=HOME-VISITS&code=99350", "#code=99341").code, "99341");
});
test("the family is trimmed and upper-cased", () => {
eq(at("/dossier", "?family=%20ccm%20").family, "CCM");
eq(at("/dossier", "?family=").family, "");
});
test("contents keeps the family it came from", () => {
const s = at("/contents", "?family=HOME-VISITS");
deq([s.view, s.family, s.canonical], ["contents", "HOME-VISITS", "/contents?family=HOME-VISITS"]);
});
test("formatState encodes the family and the fragment", () => {
eq(formatState({ family: "A/D-TX", view: "dossier" }), "/dossier?family=A%2FD-TX");
eq(formatState({ view: "contents" }), "/contents");
eq(formatState({ family: "HOME-VISITS", view: "payment", code: "99350" }), "/payment?family=HOME-VISITS#code=99350");
eq(formatState({ family: "HOME-VISITS", view: "dossier", fact: "F2" }), "/dossier?family=HOME-VISITS#fact=F2");
eq(formatState({ family: "HOME-VISITS", view: "dossier", code: "", fact: "" }), "/dossier?family=HOME-VISITS");
});
test("a slash family key round-trips", () => {
const url = formatState({ family: "A/D-TX-PROGRAM-HOUR", view: "timeline", code: "99341" });
const [path, rest] = url.split("?");
const [search, hash] = rest.split("#");
const s = at(path, "?" + search, "#" + hash);
deq([s.family, s.view, s.code, s.canonical], ["A/D-TX-PROGRAM-HOUR", "timeline", "99341", url]);
});
test("parseLocation accepts a URL object", () => {
const s = parseLocation(new URL("https://lex.test/valuation?family=HOME-VISITS#fact=F4"));
deq([s.view, s.family, s.fact], ["valuation", "HOME-VISITS", "F4"]);
ok(s.canonical.startsWith("/valuation?"));
});

69
tests/lex/test_js.py Normal file
View File

@@ -0,0 +1,69 @@
"""The lex JS unit tests (``tests/lex/*.test.mjs``) under pytest.
The modules are ES modules in ``.js`` files with no ``package.json``
``"type": "module"`` (Gitea serves them as they are), which node runs only
from 22.7 on (syntax detection on by default). Ruling S1-P5: this test skips
when the host has no node, or an older one; the gate is the docker run
docker run --rm -v /home/kert/stack:/w:ro -w /w node:22-slim \\
sh -c 'node --test tests/lex/*.test.mjs'
which must print ``# fail 0``.
"""
from __future__ import annotations
import re
import shutil
import subprocess
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
MIN_NODE = (22, 7)
SKIP_REASON = "node ≥ 22.7 not on PATH; run NODE"
def node_version(text: str) -> tuple[int, int] | None:
"""``(major, minor)`` from ``node --version`` output such as ``v22.7.0``."""
m = re.match(r"\s*v(\d+)\.(\d+)", text or "")
return (int(m.group(1)), int(m.group(2))) if m else None
def node_ok(text: str) -> bool:
v = node_version(text)
return v is not None and v >= MIN_NODE
def test_node_gate() -> None:
assert node_version("v22.7.0\n") == (22, 7)
assert node_ok("v22.7.0") and node_ok("v24.1.3") and node_ok("v23.0.0")
assert not node_ok("v22.6.9") and not node_ok("v20.18.0")
assert not node_ok("") and not node_ok("node: not found")
def test_lex_js_unit_tests() -> None:
node = shutil.which("node")
if node is None:
pytest.skip(SKIP_REASON)
probe = subprocess.run(
[node, "--version"], capture_output=True, text=True, check=False
)
if not node_ok(probe.stdout):
pytest.skip(SKIP_REASON)
files = sorted(
str(p.relative_to(ROOT)) for p in (ROOT / "tests/lex").glob("*.test.mjs")
)
assert files, "no tests/lex/*.test.mjs"
r = subprocess.run(
[node, "--test", *files],
cwd=ROOT,
capture_output=True,
text=True,
timeout=300,
check=False,
)
assert r.returncode == 0 and "# fail 0" in r.stdout, (
r.stdout[-6000:] + r.stderr[-2000:]
)