Some checks failed
CI / lint (push) Successful in 1m33s
CI / notebooks-smoke (push) Successful in 1m58s
Deploy / changes (push) Successful in 26s
CI / test (push) Successful in 5m27s
Infra CI / zotero (push) Successful in 26s
Infra CI / notebooks (push) Successful in 3m17s
Infra CI / docs (push) Successful in 1m37s
Infra CI / api (push) Successful in 1m59s
Infra CI / bcda (push) Successful in 2m59s
Infra CI / llm (push) Successful in 1m16s
Infra CI / mc (push) Successful in 30s
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Successful in 2m3s
Deploy / report (push) Has been cancelled
Deploy / api (push) Has started running
Deploy / bcda (push) Has been cancelled
Deploy / llm (push) Has been cancelled
Deploy / mc (push) Has been cancelled
Deploy / notebooks (push) Has started running
docker start zotero (KasmVNC) can take over 30 s; the subprocess timeout raised after the sync had already written everything, so bib-refresh-iom exited 1. One helper now waits up to 3 min and reports rather than raises.
1359 lines
47 KiB
Python
1359 lines
47 KiB
Python
"""stack bib — bibliography operations."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from collections.abc import Callable
|
|
from pathlib import Path
|
|
|
|
import typer
|
|
|
|
app = typer.Typer(no_args_is_help=True)
|
|
|
|
|
|
def _zotero_container(action: str) -> None:
|
|
"""``docker stop|start zotero`` around a Zotero SQLite write. The
|
|
KasmVNC container can take well over 30 s to start; waiting longer
|
|
than 3 min is reported, not raised — the container keeps starting,
|
|
and the sync's work is already done."""
|
|
import subprocess
|
|
import sys
|
|
|
|
try:
|
|
subprocess.run(
|
|
["docker", action, "zotero"], capture_output=True, check=False, timeout=180
|
|
)
|
|
except subprocess.TimeoutExpired:
|
|
verb = "still starting" if action == "start" else "still stopping"
|
|
print(f" zotero container {verb} after 180 s", file=sys.stderr)
|
|
|
|
|
|
@app.command()
|
|
def sync(
|
|
dry_run: bool = typer.Option(False, "--dry-run", help="Report without applying."),
|
|
) -> None:
|
|
"""Apply col: tags as DuckDB column comments."""
|
|
import duckdb
|
|
|
|
from bib import connect
|
|
from bib.meta import apply_column_comments, collect_column_comments
|
|
from conf import path
|
|
|
|
store = connect()
|
|
comments = collect_column_comments(store)
|
|
|
|
if not comments:
|
|
typer.echo("No col: tags found. Run seed_col_tags.py first.")
|
|
return
|
|
|
|
if dry_run:
|
|
for ref, desc in sorted(comments.items()):
|
|
typer.echo(f" {ref} = {desc}")
|
|
typer.echo(f"Would apply {len(comments)} column comments.")
|
|
return
|
|
|
|
con = duckdb.connect(str(path("db.aco")), read_only=False)
|
|
stmts = apply_column_comments(con, store)
|
|
con.close()
|
|
|
|
typer.echo(f"Applied {len(stmts)} column comments.")
|
|
|
|
|
|
@app.command()
|
|
def tag(
|
|
pattern: str = typer.Argument("", help="Tag namespace or pattern to filter."),
|
|
) -> None:
|
|
"""List or search bibliography tags."""
|
|
from bib import connect
|
|
|
|
store = connect()
|
|
tags = store.list_tags(namespace=pattern)
|
|
|
|
for t in tags:
|
|
typer.echo(f" {t['name']} ({t['count']} items)")
|
|
|
|
typer.echo(f"{len(tags)} tags found.")
|
|
|
|
|
|
@app.command()
|
|
def query(
|
|
term: str = typer.Argument(help="Search term."),
|
|
) -> None:
|
|
"""Search the bibliography store."""
|
|
from bib import connect
|
|
|
|
store = connect()
|
|
items = store.list_items(query=term)
|
|
|
|
for item in items[:20]:
|
|
tags_str = ", ".join(item.tags[:3]) if item.tags else ""
|
|
typer.echo(f" {item.key}: {item.title[:60]} [{tags_str}]")
|
|
|
|
if len(items) > 20:
|
|
typer.echo(f" ... and {len(items) - 20} more")
|
|
typer.echo(f"{len(items)} items found.")
|
|
|
|
|
|
_UA = "fhirworx-bib/0.1"
|
|
|
|
|
|
def _http_client():
|
|
import httpx
|
|
|
|
return httpx.Client(headers={"User-Agent": _UA})
|
|
|
|
|
|
def _discover_rules(docs, *, module: str, dry_run: bool) -> None:
|
|
"""Upsert Federal Register rule documents under ``module:<module>``."""
|
|
from bib import connect
|
|
from bib.tag import Tag
|
|
from bib.translate import federal_register
|
|
|
|
store = connect() if not dry_run else None
|
|
for doc in docs:
|
|
typer.echo(
|
|
f" {doc.publication_date} {doc.type:14s} "
|
|
f"{doc.document_number:14s} {','.join(doc.dockets) or '(no docket)'}"
|
|
)
|
|
if dry_run or store is None:
|
|
continue
|
|
try:
|
|
rule = federal_register(
|
|
doc.html_url
|
|
or f"https://www.federalregister.gov/documents/{doc.document_number}"
|
|
)
|
|
except Exception as e: # noqa: BLE001
|
|
typer.echo(f" skipped: {e.__class__.__name__}: {e}")
|
|
continue
|
|
rule.add_tag(Tag.source("federal-register").label)
|
|
rule.add_tag(f"module:{module}")
|
|
for d in doc.dockets:
|
|
rule.add_tag(f"docket:{d}")
|
|
store.upsert(rule)
|
|
|
|
|
|
@app.command(name="discover-pfs-rules")
|
|
def discover_pfs_rules(
|
|
since: str = typer.Option("2017-01-01", "--since"),
|
|
until: str = typer.Option("", "--until"),
|
|
dry_run: bool = typer.Option(False, "--dry-run"),
|
|
) -> None:
|
|
"""Walk the Federal Register API for every PFS rule since a date.
|
|
|
|
Upserts each as a bib ``Rule`` record tagged ``module:pfs``,
|
|
``source:federal-register``, ``docket:<cms-id>``. Cheap — the FR API
|
|
has no auth and no rate charge we can trigger at this scale
|
|
(~20 rules since 2017).
|
|
"""
|
|
from bib.federalregister import pfs_rules
|
|
|
|
_discover_rules(
|
|
pfs_rules(since=since, until=until or None), module="pfs", dry_run=dry_run
|
|
)
|
|
|
|
|
|
@app.command(name="discover-ipps-rules")
|
|
def discover_ipps_rules(
|
|
since: str = typer.Option("2017-01-01", "--since"),
|
|
until: str = typer.Option("", "--until"),
|
|
dry_run: bool = typer.Option(False, "--dry-run"),
|
|
) -> None:
|
|
"""Walk the Federal Register API for every annual IPPS/LTCH rule."""
|
|
from bib.federalregister import ipps_rules
|
|
|
|
_discover_rules(
|
|
ipps_rules(since=since, until=until or None), module="ipps", dry_run=dry_run
|
|
)
|
|
|
|
|
|
@app.command(name="discover-opps-rules")
|
|
def discover_opps_rules(
|
|
since: str = typer.Option("2017-01-01", "--since"),
|
|
until: str = typer.Option("", "--until"),
|
|
dry_run: bool = typer.Option(False, "--dry-run"),
|
|
) -> None:
|
|
"""Walk the Federal Register API for every annual OPPS/ASC rule."""
|
|
from bib.federalregister import opps_rules
|
|
|
|
_discover_rules(
|
|
opps_rules(since=since, until=until or None), module="opps", dry_run=dry_run
|
|
)
|
|
|
|
|
|
@app.command(name="discover-dmepos-rules")
|
|
def discover_dmepos_rules(
|
|
since: str = typer.Option("2017-01-01", "--since"),
|
|
until: str = typer.Option("", "--until"),
|
|
dry_run: bool = typer.Option(False, "--dry-run"),
|
|
) -> None:
|
|
"""Walk the Federal Register API for every DMEPOS rule since a date.
|
|
|
|
The benefit moved between the ESRD rule, a standalone HCPCS rule,
|
|
and the home health rule. A title filter keeps those vehicles and
|
|
drops a Physician Fee Schedule title that only mentions DMEPOS.
|
|
"""
|
|
from bib.federalregister import dmepos_rules
|
|
|
|
_discover_rules(
|
|
dmepos_rules(since=since, until=until or None),
|
|
module="dmepos",
|
|
dry_run=dry_run,
|
|
)
|
|
|
|
|
|
def _walk_and_report(store, api, docket, *, attachments, limit, force, echo) -> None:
|
|
from bib.dockets import quiet_days
|
|
from bib.regulations_gov import walk_docket
|
|
|
|
r = walk_docket(
|
|
store,
|
|
api,
|
|
docket,
|
|
attachments=attachments,
|
|
limit=limit,
|
|
force=force,
|
|
quiet_days=quiet_days(),
|
|
echo=echo,
|
|
)
|
|
echo(
|
|
f" {docket.id}: created={r.created} updated={r.updated} "
|
|
f"unchanged={r.unchanged} clean={r.clean}" + (" — sealed" if r.sealed else "")
|
|
)
|
|
|
|
|
|
@app.command(name="fetch-docket-comments")
|
|
def fetch_docket_comments(
|
|
docket: str = typer.Argument(..., help="reg.gov docket id, e.g. CMS-2026-2377"),
|
|
cms_id: str = typer.Option(
|
|
"", "--cms-id", help="Associate comments with a specific CMS rule tag."
|
|
),
|
|
limit: int = typer.Option(
|
|
0, "--limit", "-n", help="Stop after N comments. 0 = all."
|
|
),
|
|
attachments: bool = typer.Option(
|
|
False,
|
|
"--attachments",
|
|
help="Also download each comment's PDF/DOCX attachments.",
|
|
),
|
|
sleep: float = typer.Option(
|
|
1.3, "--sleep", help="Seconds between API calls (rate budget)."
|
|
),
|
|
force: bool = typer.Option(
|
|
False,
|
|
"--force",
|
|
help="Walk from page 1 even if sealed / watermarked. Never unseals.",
|
|
),
|
|
) -> None:
|
|
"""Walk one docket's comments from its stored watermark; upsert as Source items.
|
|
|
|
The first run discovers the docket's commentable FR document (one
|
|
listing call) and stores it; later runs make no discovery calls.
|
|
Sealed dockets are skipped unless --force.
|
|
"""
|
|
from bib import connect
|
|
from bib.regulations_gov import Client, discover_docket
|
|
|
|
store = connect()
|
|
with Client(sleep=sleep) as api:
|
|
d = store.docket_get(docket)
|
|
if d is None:
|
|
d = discover_docket(api, docket, rule_cms_id=cms_id)
|
|
store.docket_upsert(d)
|
|
elif cms_id and not d.rule_cms_id:
|
|
from dataclasses import replace
|
|
|
|
d = replace(d, rule_cms_id=cms_id)
|
|
store.docket_upsert(d)
|
|
if d.sealed and not force:
|
|
typer.echo(
|
|
f" {docket}: sealed {d.sealed_at[:10]} ({d.seal_reason}); skipping — use --force to re-walk"
|
|
)
|
|
return
|
|
if not d.fr_object_id:
|
|
typer.echo(f" {docket}: no commentable FR document found")
|
|
return
|
|
_walk_and_report(
|
|
store,
|
|
api,
|
|
d,
|
|
attachments=attachments,
|
|
limit=limit,
|
|
force=force,
|
|
echo=typer.echo,
|
|
)
|
|
|
|
|
|
@app.command(name="pull-open-dockets")
|
|
def pull_open_dockets(
|
|
attachments: bool = typer.Option(
|
|
True,
|
|
"--attachments/--no-attachments",
|
|
help="Also download each new comment's PDF/DOCX attachments.",
|
|
),
|
|
sleep: float = typer.Option(
|
|
1.3, "--sleep", help="Seconds between listing calls (rate budget)."
|
|
),
|
|
enrich_sleep: float = typer.Option(
|
|
3.7,
|
|
"--enrich-sleep",
|
|
help="Seconds between enrichment calls — 3.7s stays under reg.gov's "
|
|
"1000/hr cap.",
|
|
),
|
|
log_path: Path = typer.Option(
|
|
Path("/tmp/bib-backfill-comments.log"),
|
|
"--log",
|
|
help="Append-only enrichment progress log.",
|
|
),
|
|
) -> None:
|
|
"""Pull and enrich every docket that is not sealed yet — the nightly job.
|
|
|
|
For each unsealed docket in the store: walk its comments from the
|
|
stored watermark (new postings only; a docket quiet long enough after
|
|
its comment period closes seals itself on the way), then enrich the
|
|
new stubs with body + attachments. Sealed dockets cost nothing, so
|
|
the job shrinks to nothing between rulemaking seasons. Register a new
|
|
docket once with ``fetch-docket-comments`` and this keeps it current.
|
|
"""
|
|
from bib import connect
|
|
from bib.regulations_gov import Client, backfill_details
|
|
|
|
store = connect()
|
|
open_dockets = [d for d in store.dockets() if not d.sealed]
|
|
if not open_dockets:
|
|
typer.echo("no open dockets")
|
|
return
|
|
typer.echo(
|
|
f"{len(open_dockets)} open docket(s): " + ", ".join(d.id for d in open_dockets)
|
|
)
|
|
with Client(sleep=sleep) as api:
|
|
for d in open_dockets:
|
|
if not d.fr_object_id:
|
|
typer.echo(f" {d.id}: no commentable FR document found — skipped")
|
|
continue
|
|
_walk_and_report(
|
|
store,
|
|
api,
|
|
d,
|
|
attachments=attachments,
|
|
limit=0,
|
|
force=False,
|
|
echo=typer.echo,
|
|
)
|
|
# force only bypasses the seal (enriched items are still skipped), so a
|
|
# docket that sealed during the walk above still gets its last stubs.
|
|
with Client(sleep=enrich_sleep) as api:
|
|
for d in open_dockets:
|
|
stats = backfill_details(
|
|
store, api, docket=d.id, force=True, limit=None, log_path=log_path
|
|
)
|
|
typer.echo(
|
|
f" {d.id} enrich: " + " ".join(f"{k}={v}" for k, v in stats.items())
|
|
)
|
|
|
|
|
|
def _fetch_rule_comments(
|
|
rules,
|
|
*,
|
|
module: str,
|
|
label: str,
|
|
since: str,
|
|
attachments: bool,
|
|
per_docket_limit: int,
|
|
sleep: float,
|
|
docket: str,
|
|
force: bool,
|
|
title_contains: str | Callable[[object], str] = "",
|
|
) -> None:
|
|
"""Register each proposed rule's reg.gov docket and walk its comments.
|
|
|
|
``title_contains`` is a substring every resolved document must
|
|
carry, or a callable from the rule document to that substring.
|
|
An empty result keeps the PFS first-hit resolve.
|
|
"""
|
|
from bib import connect
|
|
from bib.federalregister import split_docket_ids
|
|
from bib.regulations_gov import Client, discover_docket, pull_titled_siblings
|
|
from bib.tag import Tag
|
|
from bib.translate import federal_register
|
|
|
|
store = connect()
|
|
typer.echo(f"==> {len(rules)} {label} rules since {since}")
|
|
proposed = [r for r in rules if r.type == "Proposed Rule"]
|
|
typer.echo(f" {len(proposed)} proposed rules (the ones with comments)")
|
|
|
|
with Client(sleep=sleep) as api:
|
|
for doc in proposed:
|
|
cms_ids = split_docket_ids(doc.dockets)
|
|
known = {cid: store.docket_for_rule(cid) for cid in cms_ids}
|
|
|
|
# Decide what this rule needs BEFORE touching the network.
|
|
def _wanted(cid: str) -> bool:
|
|
d = known[cid]
|
|
if docket and d is not None and d.id != docket:
|
|
return False
|
|
if d is not None and d.sealed and not force:
|
|
typer.echo(
|
|
f" {d.id}: sealed {d.sealed_at[:10]} ({d.seal_reason}); skipping"
|
|
)
|
|
return False
|
|
return True
|
|
|
|
todo = [cid for cid in cms_ids if _wanted(cid)]
|
|
if not todo:
|
|
continue
|
|
|
|
try:
|
|
rule = federal_register(
|
|
doc.html_url
|
|
or f"https://www.federalregister.gov/documents/{doc.document_number}"
|
|
)
|
|
except Exception as e: # noqa: BLE001
|
|
typer.echo(f" skipped rule meta: {e}")
|
|
continue
|
|
rule.add_tag(Tag.source("federal-register").label)
|
|
rule.add_tag(f"module:{module}")
|
|
for cid in cms_ids:
|
|
rule.add_tag(f"cms-rule:{cid}")
|
|
# Upsert now, before any docket resolution: a CMS id whose
|
|
# docket never resolves (resolve_docket returns nothing) must
|
|
# not cost the rule item its only upsert. Each docket below
|
|
# re-upserts to add its reg-docket tag; upsert_status makes
|
|
# the extra call a no-op when nothing changed.
|
|
store.upsert(rule)
|
|
|
|
needle = title_contains(doc) if callable(title_contains) else title_contains
|
|
for cms_id in todo:
|
|
d = known[cms_id]
|
|
if d is None:
|
|
# An empty needle keeps the PFS first-hit call. Passing
|
|
# title_contains="" would change that signature for every
|
|
# existing caller.
|
|
resolve_kw = {"title_contains": needle} if needle else {}
|
|
reg_docket = api.resolve_docket(cms_id, **resolve_kw)
|
|
if not reg_docket:
|
|
typer.echo(f" skip {cms_id}: no reg.gov docket found")
|
|
continue
|
|
if docket and reg_docket != docket:
|
|
continue
|
|
# A correction (CMS-XXXX-CN) often lives on the same
|
|
# reg.gov docket as the proposed rule. Re-upserting a
|
|
# fresh row would wipe the watermark and the seal.
|
|
d = store.docket_get(reg_docket)
|
|
if d is None:
|
|
d = discover_docket(
|
|
api, reg_docket, rule_cms_id=cms_id, **resolve_kw
|
|
)
|
|
store.docket_upsert(d)
|
|
if d.sealed and not force:
|
|
typer.echo(
|
|
f" {d.id}: sealed {d.sealed_at[:10]} ({d.seal_reason}); skipping"
|
|
)
|
|
rule.add_tag(f"reg-docket:{d.id}")
|
|
store.upsert(rule)
|
|
continue
|
|
typer.echo(f" {cms_id} → {d.id} ({doc.publication_date})")
|
|
rule.add_tag(f"reg-docket:{d.id}")
|
|
store.upsert(rule)
|
|
if not d.fr_object_id:
|
|
typer.echo(f" {d.id}: no commentable FR document; skipping")
|
|
continue
|
|
_walk_and_report(
|
|
store,
|
|
api,
|
|
d,
|
|
attachments=attachments,
|
|
limit=per_docket_limit,
|
|
force=force,
|
|
echo=typer.echo,
|
|
)
|
|
if needle and not per_docket_limit:
|
|
extra = pull_titled_siblings(store, api, d, title_contains=needle)
|
|
if extra:
|
|
typer.echo(f" {d.id}: {extra} comments on sibling documents")
|
|
|
|
|
|
_DOCKET_HELP = (
|
|
"Only pull this reg.gov docket (e.g. CMS-2026-2377). Filtered "
|
|
"before any API call ONLY once the docket is known (a `dockets` "
|
|
"row already exists for its CMS id) — a CMS id with no `dockets` "
|
|
"row yet still costs one Federal Register rule-metadata fetch "
|
|
"plus one resolve_docket call, because the reg.gov docket id "
|
|
"isn't known until those calls resolve it."
|
|
)
|
|
|
|
|
|
@app.command(name="fetch-pfs-comments")
|
|
def fetch_pfs_comments(
|
|
since: str = typer.Option("2017-01-01", "--since"),
|
|
until: str = typer.Option("", "--until"),
|
|
attachments: bool = typer.Option(False, "--attachments"),
|
|
per_docket_limit: int = typer.Option(
|
|
0, "--per-docket-limit", help="Cap comments fetched per docket. 0 = unlimited."
|
|
),
|
|
sleep: float = typer.Option(1.3, "--sleep"),
|
|
docket: str = typer.Option("", "--docket", help=_DOCKET_HELP),
|
|
force: bool = typer.Option(
|
|
False,
|
|
"--force",
|
|
help="Walk every docket from page 1, sealed or not. Never unseals.",
|
|
),
|
|
) -> None:
|
|
"""Discover every PFS proposed rule since *since* and pull new comments
|
|
on each docket from its stored watermark.
|
|
|
|
Sealed dockets (comment period closed + quiet period + an empty pull)
|
|
cost nothing: no rule-metadata fetch, no resolve call, no walk. The
|
|
same is true for a docket already known via `--docket` that resolves
|
|
to a different id. A CMS id with no `dockets` row at all is not free
|
|
even under `--docket`: see that option's help.
|
|
"""
|
|
from bib.federalregister import pfs_rules
|
|
|
|
_fetch_rule_comments(
|
|
pfs_rules(since=since, until=until or None),
|
|
module="pfs",
|
|
label="PFS",
|
|
since=since,
|
|
attachments=attachments,
|
|
per_docket_limit=per_docket_limit,
|
|
sleep=sleep,
|
|
docket=docket,
|
|
force=force,
|
|
)
|
|
|
|
|
|
@app.command(name="fetch-ipps-comments")
|
|
def fetch_ipps_comments(
|
|
since: str = typer.Option("2017-01-01", "--since"),
|
|
until: str = typer.Option("", "--until"),
|
|
attachments: bool = typer.Option(False, "--attachments"),
|
|
per_docket_limit: int = typer.Option(
|
|
0, "--per-docket-limit", help="Cap comments fetched per docket. 0 = unlimited."
|
|
),
|
|
sleep: float = typer.Option(1.3, "--sleep"),
|
|
docket: str = typer.Option("", "--docket", help=_DOCKET_HELP),
|
|
force: bool = typer.Option(
|
|
False,
|
|
"--force",
|
|
help="Walk every docket from page 1, sealed or not. Never unseals.",
|
|
),
|
|
) -> None:
|
|
"""Discover every annual IPPS/LTCH proposed rule and pull its comments."""
|
|
from bib.federalregister import ipps_rules
|
|
|
|
_fetch_rule_comments(
|
|
ipps_rules(since=since, until=until or None),
|
|
module="ipps",
|
|
label="IPPS",
|
|
since=since,
|
|
attachments=attachments,
|
|
per_docket_limit=per_docket_limit,
|
|
sleep=sleep,
|
|
docket=docket,
|
|
force=force,
|
|
title_contains="inpatient prospective payment",
|
|
)
|
|
|
|
|
|
@app.command(name="fetch-opps-comments")
|
|
def fetch_opps_comments(
|
|
since: str = typer.Option("2017-01-01", "--since"),
|
|
until: str = typer.Option("", "--until"),
|
|
attachments: bool = typer.Option(False, "--attachments"),
|
|
per_docket_limit: int = typer.Option(
|
|
0, "--per-docket-limit", help="Cap comments fetched per docket. 0 = unlimited."
|
|
),
|
|
sleep: float = typer.Option(1.3, "--sleep"),
|
|
docket: str = typer.Option("", "--docket", help=_DOCKET_HELP),
|
|
force: bool = typer.Option(
|
|
False,
|
|
"--force",
|
|
help="Walk every docket from page 1, sealed or not. Never unseals.",
|
|
),
|
|
) -> None:
|
|
"""Discover every annual OPPS/ASC proposed rule and pull its comments."""
|
|
from bib.federalregister import opps_rules
|
|
|
|
_fetch_rule_comments(
|
|
opps_rules(since=since, until=until or None),
|
|
module="opps",
|
|
label="OPPS",
|
|
since=since,
|
|
attachments=attachments,
|
|
per_docket_limit=per_docket_limit,
|
|
sleep=sleep,
|
|
docket=docket,
|
|
force=force,
|
|
title_contains="outpatient prospective payment",
|
|
)
|
|
|
|
|
|
@app.command(name="fetch-dmepos-comments")
|
|
def fetch_dmepos_comments(
|
|
since: str = typer.Option("2017-01-01", "--since"),
|
|
until: str = typer.Option("", "--until"),
|
|
attachments: bool = typer.Option(False, "--attachments"),
|
|
per_docket_limit: int = typer.Option(
|
|
0, "--per-docket-limit", help="Cap comments fetched per docket. 0 = unlimited."
|
|
),
|
|
sleep: float = typer.Option(1.3, "--sleep"),
|
|
docket: str = typer.Option("", "--docket", help=_DOCKET_HELP),
|
|
force: bool = typer.Option(
|
|
False,
|
|
"--force",
|
|
help="Walk every docket from page 1, sealed or not. Never unseals.",
|
|
),
|
|
) -> None:
|
|
"""Discover every DMEPOS proposed rule since *since* and pull its comments.
|
|
|
|
Combined ESRD and home-health vehicles come in whole: the comment
|
|
file is the docket's file, not a DMEPOS-only slice. Notices and final
|
|
rules are registered by ``discover-dmepos-rules`` and are not walked.
|
|
|
|
No title needle is passed to regulations.gov. The agency's copy of a
|
|
long title is often truncated (``etc.``) or hyphenated differently
|
|
from the Federal Register, and the short display posting is then
|
|
the only document that still contains "DMEPOS".
|
|
"""
|
|
from bib.federalregister import dmepos_rules
|
|
|
|
_fetch_rule_comments(
|
|
dmepos_rules(since=since, until=until or None),
|
|
module="dmepos",
|
|
label="DMEPOS",
|
|
since=since,
|
|
attachments=attachments,
|
|
per_docket_limit=per_docket_limit,
|
|
sleep=sleep,
|
|
docket=docket,
|
|
force=force,
|
|
)
|
|
|
|
|
|
@app.command(name="ingest-mail")
|
|
def ingest_mail(
|
|
user: str = typer.Option(
|
|
"cmsupdates@mail.fhirworx.io",
|
|
"--user",
|
|
help="Mailbox address to poll (must have a password in .state/mail/credentials.json).",
|
|
),
|
|
host: str = typer.Option("mail.fhirworx.io", "--host"),
|
|
port: int = typer.Option(993, "--port"),
|
|
folder: str = typer.Option("INBOX", "--folder"),
|
|
limit: int = typer.Option(0, "--limit", "-n"),
|
|
) -> None:
|
|
"""Pull UNSEEN mail from a mailbox via IMAPS, upsert as bib Sources.
|
|
|
|
Idempotent: marks each ingested message ``\\Seen`` on the server,
|
|
so re-runs only fetch new mail. Attachments ride along into bib
|
|
storage. After this, ``stack bib sync-zotero`` routes everything
|
|
tagged ``source:email`` into the appropriate Zotero collection.
|
|
"""
|
|
import json
|
|
|
|
from bib import connect
|
|
from bib.email_ingest import Mailbox, ingest
|
|
|
|
creds_path = Path(".state/mail/credentials.json")
|
|
if not creds_path.exists():
|
|
raise typer.BadParameter(
|
|
"no .state/mail/credentials.json — run `stack mail provision` first."
|
|
)
|
|
creds = json.loads(creds_path.read_text())
|
|
pw = creds.get(user) or creds.get(user.split("@", 1)[0])
|
|
if not pw:
|
|
raise typer.BadParameter(
|
|
f"no cached password for {user}.\nRun: stack mail rotate-creds {user}"
|
|
)
|
|
|
|
store = connect()
|
|
stats = ingest(
|
|
store,
|
|
Mailbox(host=host, port=port, username=user, password=pw, folder=folder),
|
|
limit=limit or None,
|
|
)
|
|
for k, v in stats.items():
|
|
typer.echo(f" {k}: {v}")
|
|
|
|
|
|
@app.command(name="backfill-comments")
|
|
def backfill_comments(
|
|
docket: str = typer.Option(
|
|
"",
|
|
"--docket",
|
|
help="Limit to one docket (e.g. CMS-2026-2377). Without it the "
|
|
"walk covers every un-enriched stub in the store — a multi-day "
|
|
"crawl at the reg.gov rate cap.",
|
|
),
|
|
limit: int = typer.Option(
|
|
0,
|
|
"--limit",
|
|
"-n",
|
|
help="Cap items processed this run. 0 = no cap (multi-day crawl).",
|
|
),
|
|
sleep: float = typer.Option(
|
|
3.7,
|
|
"--sleep",
|
|
help="Seconds between API calls. 3.7s ≈ 970/hr — just under the "
|
|
"1000/hr reg.gov hourly cap (the binding limit; the 50/min burst "
|
|
"cap is looser). CDN downloads are concurrent and don't count.",
|
|
),
|
|
log_path: Path = typer.Option(
|
|
Path("/tmp/bib-backfill-comments.log"),
|
|
"--log",
|
|
help="Append-only progress log (survives restarts).",
|
|
),
|
|
mirror: bool = typer.Option(
|
|
False,
|
|
"--mirror",
|
|
help="Pull from the Mirrulations S3 mirror instead of the "
|
|
"reg.gov API — bulk speed, no rate cap, also ingests comments "
|
|
"the original farm never listed. Requires --docket.",
|
|
),
|
|
force: bool = typer.Option(
|
|
False,
|
|
"--force",
|
|
help="Run even if the docket is sealed. Bypasses the docket seal "
|
|
"only: items already tagged enriched:ok (or enriched:gone) are "
|
|
"still skipped, so this resumes an interrupted enrichment — it "
|
|
"never re-enriches an item.",
|
|
),
|
|
) -> None:
|
|
"""Enrich every reg-gov comment stub with body + attachments.
|
|
|
|
Walks items tagged ``source:regulations-gov`` whose ``abstract`` is
|
|
still empty and hits ``/v4/comments/{id}?include=attachments`` for
|
|
each one. Resumable: stop any time, start again, it picks up where
|
|
it left off by skipping already-enriched items. At 1.3s/req the API
|
|
calls run at ~2700/hr; attachment downloads are concurrent on the
|
|
CDN and don't count against the rate limit.
|
|
|
|
``--mirror`` swaps the API for the Mirrulations public S3 mirror
|
|
(#662): no API key, no cap, and mirror-only comments get created.
|
|
"""
|
|
from bib import connect
|
|
|
|
store = connect()
|
|
if mirror:
|
|
if not docket:
|
|
raise typer.BadParameter("--mirror requires --docket")
|
|
from bib.regulations_gov import Mirror, backfill_from_mirror
|
|
|
|
stats = backfill_from_mirror(
|
|
store,
|
|
Mirror(),
|
|
docket=docket,
|
|
force=force,
|
|
limit=limit or None,
|
|
log_path=log_path,
|
|
)
|
|
else:
|
|
from bib.regulations_gov import Client, backfill_details
|
|
|
|
with Client(sleep=sleep) as api:
|
|
stats = backfill_details(
|
|
store,
|
|
api,
|
|
docket=docket,
|
|
force=force,
|
|
limit=limit or None,
|
|
log_path=log_path,
|
|
)
|
|
for k, v in stats.items():
|
|
typer.echo(f" {k}: {v}")
|
|
|
|
|
|
@app.command(name="ingest-iom")
|
|
def ingest_iom(
|
|
pubs: list[str] = typer.Option(
|
|
None,
|
|
"--pub",
|
|
"-p",
|
|
help="Limit to specific pub numbers (e.g. 100-02). Repeat for multiple.",
|
|
),
|
|
) -> None:
|
|
"""Crawl the CMS IOM index and upsert every chapter as a Manual.
|
|
|
|
Idempotent: re-running only adds missing chapters (dedup is by URL
|
|
in the store). Without --pub, ingests every manual the CMS index
|
|
advertises.
|
|
"""
|
|
from bib import connect
|
|
from bib.iom import ingest_all
|
|
|
|
store = connect()
|
|
with _http_client() as client:
|
|
summary = ingest_all(store, client, pubs=pubs)
|
|
|
|
for pub, n in sorted(summary.items()):
|
|
typer.echo(f" {pub}: {n} chapters")
|
|
typer.echo(
|
|
f"Total: {sum(summary.values())} chapters across {len(summary)} manuals."
|
|
)
|
|
|
|
|
|
@app.command(name="attach-iom")
|
|
def attach_iom(
|
|
pubs: list[str] = typer.Option(
|
|
None,
|
|
"--pub",
|
|
"-p",
|
|
help="Limit to specific pub numbers. Repeat for multiple.",
|
|
),
|
|
force: bool = typer.Option(
|
|
False,
|
|
"--force",
|
|
help="Re-download even if local SHA-256 matches.",
|
|
),
|
|
) -> None:
|
|
"""Download the PDF for every Manual and attach it to the record.
|
|
|
|
Idempotent by SHA-256 — only downloads files that have changed on
|
|
CMS since the last run. Safe to schedule on a timer.
|
|
"""
|
|
from bib import connect
|
|
from bib.iom import download_attachments
|
|
|
|
store = connect()
|
|
with _http_client() as client:
|
|
results = download_attachments(store, client, pubs=pubs, force=force)
|
|
|
|
for pub, n in sorted(results.items()):
|
|
typer.echo(f" {pub}: {n} new/updated")
|
|
typer.echo(f"Total: {sum(results.values())} attachments updated.")
|
|
|
|
|
|
@app.command(name="watch-iom")
|
|
def watch_iom() -> None:
|
|
"""Poll the CMS futurepdf.pdf schedule; attach if changed.
|
|
|
|
CMS publishes upcoming IOM transmittals at
|
|
``/manuals/downloads/futurepdf.pdf``. When its checksum changes,
|
|
chapters in the main manuals are probably about to update — run
|
|
``ingest-iom`` + ``attach-iom`` afterward to pick them up.
|
|
"""
|
|
from bib import connect
|
|
from bib.iom import check_future_updates
|
|
|
|
store = connect()
|
|
with _http_client() as client:
|
|
changed, digest = check_future_updates(store, client)
|
|
|
|
status = "CHANGED" if changed else "unchanged"
|
|
typer.echo(f"futurepdf.pdf: {status} (sha256={digest[:12]})")
|
|
|
|
|
|
@app.command(name="import-zotero")
|
|
def import_zotero(
|
|
collection: str = typer.Option(
|
|
..., "--collection", help="Zotero collection name to pull from."
|
|
),
|
|
with_files: bool = typer.Option(
|
|
False,
|
|
"--with-files/--no-with-files",
|
|
help="Only import items that have at least one attachment file.",
|
|
),
|
|
only: str = typer.Option(
|
|
"", "--only", help="Title substring filter (case-insensitive)."
|
|
),
|
|
tag: list[str] = typer.Option(
|
|
None,
|
|
"--tag",
|
|
help="Tag every imported item with this. Repeat for multiple.",
|
|
),
|
|
dry_run: bool = typer.Option(
|
|
False, "--dry-run", help="Report what would happen without writing."
|
|
),
|
|
) -> None:
|
|
"""Pull a Zotero collection's book items (with files) into bib.
|
|
|
|
The reverse of ``sync-zotero``: reads the Zotero SQLite database
|
|
read-only and upserts each book as a bib ``Source`` item (dedup by
|
|
URL), copying its attachment file(s) into bib storage — an ordinary
|
|
corpus document like any other, indexed like everything else in
|
|
bib. ``llm:skip`` is available as a generic opt-out for material
|
|
that should not be embedded (see ``llm.source.iter_corpus_refs``)
|
|
— e.g. a scratch export or a duplicate scan — but it's never added
|
|
automatically here; pass ``--tag llm:skip`` explicitly if it
|
|
applies.
|
|
"""
|
|
from bib import connect
|
|
from bib.zotero_import import import_books, list_collection
|
|
from conf.connect import zotero
|
|
|
|
zcon = zotero()
|
|
try:
|
|
books = list_collection(zcon, collection, with_files=with_files)
|
|
finally:
|
|
zcon.close()
|
|
|
|
if only:
|
|
needle = only.lower()
|
|
books = [b for b in books if needle in b.title.lower()]
|
|
|
|
typer.echo(f"{len(books)} book(s) matched in '{collection}'")
|
|
|
|
store = connect()
|
|
stats = import_books(store, books, tags=tag or [], dry_run=dry_run)
|
|
|
|
prefix = "would-" if dry_run else ""
|
|
for rec in stats["items"]:
|
|
typer.echo(
|
|
f" {rec['zotero_key']} -> {rec['key'] or '(new)'}: "
|
|
f'{prefix}{rec["status"]} "{rec["title"][:60]}" '
|
|
f"attachments={rec['attached']}"
|
|
)
|
|
for missing_path in rec.get("missing_paths", []):
|
|
typer.echo(f"! missing on disk: {missing_path}", err=True)
|
|
|
|
typer.echo(
|
|
f"{prefix}created={stats['created']} {prefix}updated={stats['updated']} "
|
|
f"{prefix}unchanged={stats['unchanged']} {prefix}attached={stats['attached']} "
|
|
f"missing={stats['missing']}"
|
|
)
|
|
|
|
|
|
@app.command(name="sync-zotero")
|
|
def sync_zotero(
|
|
tag: str = typer.Option("", "--tag", help="Only sync items matching a tag."),
|
|
item_type: str = typer.Option("", "--type", help="Only sync one item_type."),
|
|
hold_zotero: bool = typer.Option(
|
|
True,
|
|
"--hold-zotero/--no-hold",
|
|
help="Stop the 'zotero' container during sync so Zotero releases "
|
|
"its exclusive SQLite lock; restart afterwards.",
|
|
),
|
|
dedupe_collection: str = typer.Option(
|
|
"",
|
|
"--dedupe-collection",
|
|
help="DEPRECATED — use --merge-dupes instead, which merges rather "
|
|
"than deletes. After the push, remove title+date duplicates from "
|
|
"this Zotero collection (and from bib, so the next sync can't "
|
|
"resurrect them). CMS listservs re-send identical mail with fresh "
|
|
"Message-IDs, so duplicates otherwise accumulate — e.g. "
|
|
"'Cmsupdates'.",
|
|
),
|
|
merge_dupes: bool = typer.Option(
|
|
False,
|
|
"--merge-dupes/--no-merge-dupes",
|
|
help="After the push, merge same-URL duplicate items library-wide "
|
|
"(union tags/collections/notes/attachments; keep-earliest). "
|
|
"Supersedes --dedupe-collection, which deletes without merging.",
|
|
),
|
|
) -> None:
|
|
"""Push bib items (and their attachments) to the Zotero database.
|
|
|
|
Zotero holds an exclusive write lock on its SQLite file while
|
|
running. By default we stop the 'zotero' compose service for the
|
|
duration of the sync and start it again afterward.
|
|
"""
|
|
|
|
from bib import connect
|
|
from bib.sync import dedupe_collection as run_dedupe
|
|
from bib.sync import push_to_zotero
|
|
from conf import path
|
|
|
|
store = connect()
|
|
items = store.list_items(tag=tag, item_type=item_type)
|
|
zotero_db_path = str(path("db.zotero"))
|
|
|
|
try:
|
|
if hold_zotero:
|
|
_zotero_container("stop")
|
|
stats = push_to_zotero(items, store=store, zotero_db=zotero_db_path)
|
|
if dedupe_collection:
|
|
stats |= run_dedupe(dedupe_collection, store=store)
|
|
if merge_dupes:
|
|
from zot.merge import merge_url_duplicates
|
|
|
|
# Explicit log_dir, not the default ".state/zotero-dedupe": the
|
|
# nightly workflow runs this command via `docker exec api` with
|
|
# WORKDIR /app, and compose mounts only ./data:/app/data — a
|
|
# relative ".state/..." path lands on the container's ephemeral
|
|
# filesystem and is lost on the next recreate. zotero_db_path's
|
|
# parent (data/zotero/data/) is guaranteed to be on the mount
|
|
# since the DB itself lives there.
|
|
merge_log_dir = Path(zotero_db_path).parent / "dedupe-logs"
|
|
stats |= {
|
|
f"merge_{k}": v
|
|
for k, v in merge_url_duplicates(
|
|
zotero_db_path, dry_run=False, log_dir=merge_log_dir
|
|
).items()
|
|
}
|
|
finally:
|
|
if hold_zotero:
|
|
_zotero_container("start")
|
|
|
|
for k, v in stats.items():
|
|
typer.echo(f" {k}: {v}")
|
|
|
|
|
|
@app.command(name="ingest-oig")
|
|
def ingest_oig(
|
|
kinds: list[str] = typer.Option(
|
|
None,
|
|
"--kind",
|
|
"-k",
|
|
help="Restrict to a subset: 'cpg' and/or 'alerts'. Repeat for multiple.",
|
|
),
|
|
) -> None:
|
|
"""Crawl OIG Compliance Program Guidance + fraud alerts indexes."""
|
|
from bib import connect
|
|
from bib.oig import ingest_all
|
|
|
|
store = connect()
|
|
with _http_client() as client:
|
|
summary = ingest_all(store, client, kinds=kinds)
|
|
for k, n in summary.items():
|
|
typer.echo(f" {k}: {n} docs")
|
|
|
|
|
|
@app.command(name="attach-oig")
|
|
def attach_oig(
|
|
force: bool = typer.Option(False, "--force", help="Re-download even if unchanged."),
|
|
) -> None:
|
|
"""Download and attach the PDF/HTML for every OIG guidance record."""
|
|
from bib import connect
|
|
from bib.oig import download_attachments
|
|
|
|
store = connect()
|
|
with _http_client() as client:
|
|
n = download_attachments(store, client, force=force)
|
|
typer.echo(f" {n} attachments updated")
|
|
|
|
|
|
@app.command(name="refresh-oig")
|
|
def refresh_oig() -> None:
|
|
"""One-shot: ingest-oig → attach-oig → sync-zotero (OIG tag)."""
|
|
|
|
from bib import connect
|
|
from bib.oig import download_attachments, ingest_all
|
|
from bib.sync import push_to_zotero
|
|
|
|
store = connect()
|
|
with _http_client() as client:
|
|
typer.echo("==> ingest-oig")
|
|
summary = ingest_all(store, client)
|
|
typer.echo(f" {summary['cpg']} CPGs, {summary['alerts']} alerts")
|
|
|
|
typer.echo("==> attach-oig")
|
|
n = download_attachments(store, client)
|
|
typer.echo(f" {n} attachments new/changed")
|
|
|
|
typer.echo("==> sync-zotero")
|
|
items = store.list_items(tag="agency:oig")
|
|
try:
|
|
_zotero_container("stop")
|
|
stats = push_to_zotero(items, store=store)
|
|
finally:
|
|
_zotero_container("start")
|
|
typer.echo(
|
|
f" created={stats['created']} skipped={stats['skipped']} "
|
|
f"attachments={stats['attachments']}"
|
|
)
|
|
|
|
|
|
@app.command(name="refresh-iom")
|
|
def refresh_iom(
|
|
pubs: list[str] = typer.Option(None, "--pub", "-p"),
|
|
file_issue: bool = typer.Option(
|
|
True,
|
|
"--file-issue/--no-file-issue",
|
|
help="When watch-iom detects a futurepdf.pdf change, auto-file a "
|
|
"Gitea issue tagged 'cms-update'. Disable for local/dev runs.",
|
|
),
|
|
) -> None:
|
|
"""One-shot: ingest-iom → watch-iom → attach-iom → sync-zotero.
|
|
|
|
Safe to put behind a cron. Idempotent at every step:
|
|
- ingest: upserts by URL, prunes stale records
|
|
- watch: re-attaches futurepdf.pdf only when its SHA-256 changes
|
|
- attach: skips PDFs whose checksum matches the stored copy
|
|
- sync: skips Zotero items whose URL already exists
|
|
|
|
Zotero is held (stopped) during the sync phase only.
|
|
"""
|
|
|
|
from bib import connect
|
|
from bib.iom import check_future_updates, download_attachments, ingest_all
|
|
from bib.iom_alert import file_iom_change_alert
|
|
from bib.sync import push_to_zotero
|
|
|
|
store = connect()
|
|
with _http_client() as client:
|
|
typer.echo("==> ingest-iom")
|
|
ingest_summary = ingest_all(store, client, pubs=pubs)
|
|
typer.echo(
|
|
f" {sum(ingest_summary.values())} chapters across "
|
|
f"{len([p for p, n in ingest_summary.items() if n])} manuals"
|
|
)
|
|
|
|
typer.echo("==> watch-iom")
|
|
changed, digest = check_future_updates(store, client)
|
|
typer.echo(
|
|
f" futurepdf.pdf: {'CHANGED' if changed else 'unchanged'} "
|
|
f"(sha256={digest[:12]})"
|
|
)
|
|
if changed and file_issue:
|
|
issue = file_iom_change_alert(sha256=digest)
|
|
if issue:
|
|
typer.echo(f" filed Gitea issue #{issue['number']}")
|
|
|
|
typer.echo("==> attach-iom")
|
|
attach_summary = download_attachments(store, client, pubs=pubs)
|
|
typer.echo(f" {sum(attach_summary.values())} PDFs downloaded or refreshed")
|
|
|
|
typer.echo("==> sync-zotero")
|
|
items = store.list_items(item_type="manual")
|
|
try:
|
|
_zotero_container("stop")
|
|
stats = push_to_zotero(items, store=store)
|
|
finally:
|
|
_zotero_container("start")
|
|
typer.echo(
|
|
f" created={stats['created']} skipped={stats['skipped']} "
|
|
f"attachments={stats['attachments']}"
|
|
)
|
|
|
|
|
|
@app.command(name="fr-grab")
|
|
def fr_grab(
|
|
key: str = typer.Option("", "--key", help="Grab one rule item by bib key."),
|
|
all_rules: bool = typer.Option(
|
|
False, "--all", help="Backfill every rule item with an FR URL."
|
|
),
|
|
force: bool = typer.Option(
|
|
False, "--force", help="Re-grab even if an anchor map already exists."
|
|
),
|
|
remap: list[str] = typer.Option(
|
|
[],
|
|
"--map",
|
|
help="Place a pinned paragraph text matching cannot: p-OLD=p-NEW "
|
|
"(repeatable; --key only).",
|
|
),
|
|
) -> None:
|
|
"""Grab federalregister.gov paragraph/page anchor maps into bib (#634).
|
|
|
|
One body-HTML fetch per rule; anchors persist in ``fr_anchors`` /
|
|
``fr_anchor_docs`` for offline jump-link resolution. A --force
|
|
re-grab moves the item's pincites, pin: tags, fr_links and note
|
|
links to the paragraphs holding the same text, and refuses (writing
|
|
nothing) when one has no confident home — add --map for those.
|
|
"""
|
|
from bib import connect, frlink
|
|
|
|
store = connect()
|
|
if bool(key) == all_rules:
|
|
raise typer.BadParameter("pass exactly one of --key or --all")
|
|
overrides: dict[int, int] = {}
|
|
for spec in remap:
|
|
m = re.fullmatch(r"p-(\d+)=p-(\d+)", spec.strip())
|
|
if not m:
|
|
raise typer.BadParameter(f"--map wants p-OLD=p-NEW, got {spec!r}")
|
|
overrides[int(m.group(1))] = int(m.group(2))
|
|
if key:
|
|
try:
|
|
results = [frlink.grab(store, key, force=force, overrides=overrides)]
|
|
except frlink.UnresolvedAnchors as e:
|
|
typer.echo(f" {key}: refused, nothing written — {e}", err=True)
|
|
raise typer.Exit(1) from e
|
|
else:
|
|
if overrides:
|
|
raise typer.BadParameter("--map needs --key")
|
|
results = frlink.backfill(store, force=force)
|
|
for r in results:
|
|
if r.get("skipped"):
|
|
typer.echo(f" {r['item_key']}: skipped (already grabbed)")
|
|
elif "error" in r:
|
|
typer.echo(f" {r['item_key']}: ERROR {r['error']}")
|
|
else:
|
|
moved = r.get("remapped") or {}
|
|
typer.echo(
|
|
f" {r['item_key']}: {r['document_number']} — "
|
|
f"{r['n_paragraphs']} paragraphs / {r['n_pages']} pages"
|
|
+ (f"; {len(moved)} pinned paragraph ids moved" if moved else "")
|
|
)
|
|
|
|
|
|
@app.command(name="fr-jump")
|
|
def fr_jump(
|
|
ref: str = typer.Argument(
|
|
...,
|
|
help='FR reference: "91 FR 44218", "91 FR 44218 ¶3", "p-3600", or a quote.',
|
|
),
|
|
key: str = typer.Option("", "--key", help="Bib item key to scope resolution."),
|
|
md: bool = typer.Option(False, "--md", help="Print a markdown link."),
|
|
do_place: bool = typer.Option(
|
|
False,
|
|
"--place",
|
|
help="Record the link in fr_links so the next zotero sync carries it "
|
|
"as a child link attachment.",
|
|
),
|
|
label: str = typer.Option("", "--label", help="Label for the placed link."),
|
|
) -> None:
|
|
"""Resolve an FR citation to its web jump link (#637); optionally place it."""
|
|
from bib import connect, frlink
|
|
|
|
store = connect()
|
|
if do_place:
|
|
link = frlink.place(store, ref, item_key=key, label=label)
|
|
typer.echo(f"placed on {link.item_key}: {link.url}")
|
|
else:
|
|
link = frlink.resolve(ref, store=store, item_key=key)
|
|
typer.echo(frlink.md_link(ref, store=store, item_key=key) if md else link.url)
|
|
if link.snippet:
|
|
typer.echo(f' ¶ "{link.snippet[:100]}..."')
|
|
|
|
|
|
@app.command(name="cfr-jump")
|
|
def cfr_jump(
|
|
ref: str = typer.Argument(
|
|
"",
|
|
help='CFR cite: "42 CFR 425.400(c)(1)(iv)" or "42 CFR Part 425".',
|
|
),
|
|
from_url: str = typer.Option(
|
|
"", "--url", help="Reverse mode: print the cite for an eCFR URL."
|
|
),
|
|
md: bool = typer.Option(False, "--md", help="Print a markdown link."),
|
|
do_place: bool = typer.Option(
|
|
False,
|
|
"--place",
|
|
help="Attach the link to its bib regulation item (fr_links) so the "
|
|
"next zotero sync carries it as a child link attachment.",
|
|
),
|
|
label: str = typer.Option("", "--label", help="Label for the placed link."),
|
|
) -> None:
|
|
"""Bidirectional CFR cite ↔ eCFR URL (#640); optionally place the link."""
|
|
from bib import cfrlink, connect
|
|
|
|
if bool(ref) == bool(from_url):
|
|
raise typer.BadParameter("pass exactly one of REF or --url")
|
|
if from_url:
|
|
typer.echo(cfrlink.cite_of(from_url))
|
|
return
|
|
if do_place:
|
|
link = cfrlink.place(connect(), ref, label=label)
|
|
typer.echo(f"placed on {link.item_key}: {link.url}")
|
|
elif md:
|
|
typer.echo(cfrlink.md_link(ref))
|
|
else:
|
|
typer.echo(cfrlink.url(cfrlink.parse_cite(ref)))
|
|
|
|
|
|
@app.command(name="code-tags")
|
|
def code_tags(
|
|
collection: str = typer.Option(
|
|
"all", "--collection", help="Which collection: all | comments | rules | corpus."
|
|
),
|
|
anchors_only: bool = typer.Option(
|
|
False,
|
|
"--anchors-only",
|
|
help="Rules only, straight from fr_anchors text — skip pgvector entirely.",
|
|
),
|
|
dry_run: bool = typer.Option(
|
|
False,
|
|
"--dry-run",
|
|
help="Compute the merged item→codes mapping and report what would "
|
|
"be tagged; write nothing.",
|
|
),
|
|
max_codes_per_item: int = typer.Option(
|
|
200,
|
|
"--max-codes-per-item",
|
|
help="Items with more distinct codes get family: tags only (+ hand-family codes).",
|
|
),
|
|
) -> None:
|
|
"""Stamp code:/family: item tags from chunk anchors and FR paragraphs.
|
|
|
|
Rolls up ``pfs.anchors.anchor_metadata`` — already stamped on
|
|
pgvector chunks by ``stack llm index``/``stack llm restamp`` — to
|
|
the bib item level: every code an item's chunks name becomes a
|
|
``code:<CODE>`` tag, every family a ``family:<KEY>`` tag. Rules also
|
|
get a pgvector-free source (``fr_anchors.text``, the FR paragraph
|
|
anchor map from ``stack bib fr-grab``); pass ``--anchors-only`` to
|
|
use only that and skip pgvector for rules (and skip comments/corpus
|
|
entirely — they have no other source). Additive and idempotent
|
|
(``bib.codetags.apply_code_tags``) — safe to rerun after every
|
|
``stack llm restamp``. Every selected source is merged into one
|
|
``item_key -> (codes, families)`` mapping before tagging (Ruling
|
|
A7), so an item that straddles two collections (e.g. rules and
|
|
corpus) is capped by ``--max-codes-per-item`` once, on its combined
|
|
code set — the printed per-source lines are informational only;
|
|
``tags_added``/``skipped_wide`` in the total come from that one
|
|
merged pass.
|
|
"""
|
|
import os
|
|
|
|
from bib import connect
|
|
from bib.codetags import (
|
|
apply_code_tags,
|
|
item_codes_from_anchors,
|
|
item_codes_from_chunks,
|
|
)
|
|
from llm import config as llm_config
|
|
from llm.index import _engine
|
|
from pfs.anchors import code_family_index
|
|
from pfs.families import FAMILIES, refresh_from
|
|
|
|
collections = ("comments", "rules", "corpus")
|
|
if collection not in ("all", *collections):
|
|
raise typer.BadParameter("collection must be all, comments, rules or corpus")
|
|
targets = collections if collection == "all" else (collection,)
|
|
|
|
store = connect()
|
|
cfg = llm_config.load()
|
|
if os.path.exists(cfg.duckdb_replica):
|
|
import duckdb
|
|
|
|
con = duckdb.connect(cfg.duckdb_replica, read_only=True)
|
|
try:
|
|
refresh_from(con)
|
|
finally:
|
|
con.close()
|
|
code_index = code_family_index(FAMILIES)
|
|
|
|
engine = None
|
|
merged: dict[str, tuple[set[str], set[str]]] = {}
|
|
processed_any = False
|
|
|
|
def _merge(source: dict[str, tuple[set[str], set[str]]]) -> None:
|
|
for key, (codes, fams) in source.items():
|
|
cur_codes, cur_fams = merged.setdefault(key, (set(), set()))
|
|
merged[key] = (cur_codes | codes, cur_fams | fams)
|
|
|
|
for target in targets:
|
|
if anchors_only and target != "rules":
|
|
typer.echo(f"{target}: skipped (--anchors-only)")
|
|
continue
|
|
|
|
if target == "rules":
|
|
anchors_map = item_codes_from_anchors(store, code_index=code_index)
|
|
typer.echo(f"{target} (anchors): items={len(anchors_map)}")
|
|
_merge(anchors_map)
|
|
processed_any = True
|
|
if not anchors_only:
|
|
if engine is None:
|
|
engine = _engine(cfg)
|
|
chunk_map = item_codes_from_chunks(engine, collection=target)
|
|
typer.echo(f"{target} (chunks): items={len(chunk_map)}")
|
|
_merge(chunk_map)
|
|
else:
|
|
if engine is None:
|
|
engine = _engine(cfg)
|
|
chunk_map = item_codes_from_chunks(engine, collection=target)
|
|
typer.echo(f"{target} (chunks): items={len(chunk_map)}")
|
|
_merge(chunk_map)
|
|
processed_any = True
|
|
|
|
if processed_any:
|
|
stats = apply_code_tags(
|
|
store, merged, dry_run=dry_run, max_codes_per_item=max_codes_per_item
|
|
)
|
|
else:
|
|
stats = {"items": 0, "tags_added": 0, "skipped_wide": 0}
|
|
|
|
prefix = "would-" if dry_run else ""
|
|
typer.echo(
|
|
f"total: {prefix}items={stats['items']} {prefix}tags_added={stats['tags_added']} "
|
|
f"capped_wide={stats['skipped_wide']}"
|
|
)
|