CUDApp
CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.
Brought by drakestapleton
CUDApp / tools / dx / sources.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | # Copied from the Hermes Agent grounded-citations skill (MIT) to check docs/PAIN_POINTS.md: see section 5 there. |
| 4 | """Citation ledger for grounded answers and documents. |
| 5 | |
| 6 | Owns the ``url -> [n]`` mapping used by the ``grounded-citations`` skill. |
| 7 | Ids are assigned at retrieval time and never change, so a draft's ``[3]`` |
| 8 | always resolves to the same page. The model only ever emits integers the |
| 9 | ledger handed it, which is what makes the citations verifiable. |
| 10 | |
| 11 | Subcommands |
| 12 | ----------- |
| 13 | reset start a clean ledger |
| 14 | add URL [URL ...] register source(s), print their ids |
| 15 | ingest FILE|- register every url found in JSON tool output |
| 16 | quote ID --text T --from FILE|- attach verbatim supporting evidence to a source |
| 17 | list show the ledger |
| 18 | render render a Sources block |
| 19 | verify DRAFT check a draft's citations against the ledger |
| 20 | |
| 21 | Fact-checking is evidence-backed citation: ``quote`` only accepts text that |
| 22 | literally appears in the fetched page text you point it at, ``verify |
| 23 | --evidence`` requires every cited source to carry at least one such quote, and |
| 24 | ``render --style evidence`` prints the quotes under each source so the reader |
| 25 | can check the chain themselves. Claims from model knowledge are declared with |
| 26 | an ``[unverified]`` marker rather than silently blended in. |
| 27 | |
| 28 | Ledger path resolution (first wins): |
| 29 | --ledger PATH |
| 30 | $HERMES_CITATION_LEDGER |
| 31 | $HERMES_HOME/cache/citations/ledger.json |
| 32 | """ |
| 33 | |
| 34 | from __future__ import annotations |
| 35 | |
| 36 | import argparse |
| 37 | import json |
| 38 | import os |
| 39 | import re |
| 40 | import sys |
| 41 | import time |
| 42 | from pathlib import Path |
| 43 | from typing import Any, Iterable |
| 44 | |
| 45 | sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| 46 | try: |
| 47 | from _hermes_home import get_hermes_home |
| 48 | except ImportError: # standalone copy in CUDA++ (tools/dx): default ledger under ~/.hermes, or pass --ledger |
| 49 | def get_hermes_home(): |
| 50 | return Path(os.environ.get("HERMES_HOME", Path.home() / ".hermes")) |
| 51 | |
| 52 | SCHEMA_VERSION = 1 |
| 53 | |
| 54 | # A citation marker in prose: [12]. Markdown links ([text](url)) and |
| 55 | # reference-style labels are excluded by requiring digits only and no |
| 56 | # following "(" or ":". |
| 57 | _CITE_RE = re.compile(r"\[(\d{1,4})\](?![(:])") |
| 58 | _SOURCES_HEADER_RE = re.compile(r"^\s*(?:#{1,6}\s*)?(?:\*\*)?sources:?(?:\*\*)?\s*$", re.IGNORECASE) |
| 59 | _SOURCE_LINE_RE = re.compile(r"^\s*\[(\d{1,4})\]\s*[-–:]?\s*(\S+)") |
| 60 | _URL_IN_TEXT_RE = re.compile(r"https?://[^\s\"'<>)\]}]+") |
| 61 | _FENCE_RE = re.compile(r"^\s*(?:```|~~~)") |
| 62 | # Explicit declaration that a claim comes from model knowledge, not a source. |
| 63 | _UNVERIFIED_RE = re.compile(r"\[unverified\]", re.IGNORECASE) |
| 64 | |
| 65 | |
| 66 | # --------------------------------------------------------------------------- |
| 67 | # Ledger I/O |
| 68 | # --------------------------------------------------------------------------- |
| 69 | |
| 70 | |
| 71 | def resolve_ledger_path(explicit: str | None = None) -> Path: |
| 72 | if explicit: |
| 73 | return Path(explicit).expanduser() |
| 74 | env = os.environ.get("HERMES_CITATION_LEDGER", "").strip() |
| 75 | if env: |
| 76 | return Path(env).expanduser() |
| 77 | return get_hermes_home() / "cache" / "citations" / "ledger.json" |
| 78 | |
| 79 | |
| 80 | def normalize_url(url: str) -> str: |
| 81 | """Canonicalize a URL for ledger identity. |
| 82 | |
| 83 | Strips the fragment and a trailing slash so ``/page``, ``/page/`` and |
| 84 | ``/page#section`` are one source. Query strings are significant and are |
| 85 | kept — they usually select different content. |
| 86 | """ |
| 87 | u = (url or "").strip() |
| 88 | if "#" in u: |
| 89 | u = u.split("#", 1)[0] |
| 90 | stripped = u.rstrip("/") |
| 91 | return stripped or u |
| 92 | |
| 93 | |
| 94 | def load_ledger(path: Path) -> dict[str, Any]: |
| 95 | if not path.exists(): |
| 96 | return {"version": SCHEMA_VERSION, "sources": []} |
| 97 | try: |
| 98 | data = json.loads(path.read_text(encoding="utf-8")) |
| 99 | except (json.JSONDecodeError, OSError) as exc: |
| 100 | raise SystemExit(f"error: ledger at {path} is unreadable ({exc}); run `reset` to start over") |
| 101 | if not isinstance(data, dict) or not isinstance(data.get("sources"), list): |
| 102 | raise SystemExit(f"error: ledger at {path} has an unexpected shape; run `reset`") |
| 103 | return data |
| 104 | |
| 105 | |
| 106 | def save_ledger(path: Path, data: dict[str, Any]) -> None: |
| 107 | path.parent.mkdir(parents=True, exist_ok=True) |
| 108 | tmp = path.with_suffix(path.suffix + f".tmp{os.getpid()}") |
| 109 | tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") |
| 110 | os.replace(tmp, path) |
| 111 | |
| 112 | |
| 113 | class _LedgerLock: |
| 114 | """Best-effort cross-process lock (O_EXCL lockfile, stdlib only). |
| 115 | |
| 116 | Parallel subagents can share one ledger via --ledger; without a lock two |
| 117 | concurrent ``add`` calls can assign the same id. Falls through after the |
| 118 | timeout rather than blocking a task forever — a stale lock must never |
| 119 | wedge the ledger. |
| 120 | """ |
| 121 | |
| 122 | def __init__(self, path: Path, timeout: float = 5.0) -> None: |
| 123 | self.lock_path = path.with_suffix(path.suffix + ".lock") |
| 124 | self.timeout = timeout |
| 125 | self.fd: int | None = None |
| 126 | |
| 127 | def __enter__(self) -> _LedgerLock: |
| 128 | self.lock_path.parent.mkdir(parents=True, exist_ok=True) |
| 129 | deadline = time.monotonic() + self.timeout |
| 130 | while True: |
| 131 | try: |
| 132 | self.fd = os.open(str(self.lock_path), os.O_CREAT | os.O_EXCL | os.O_WRONLY) |
| 133 | return self |
| 134 | except FileExistsError: |
| 135 | if time.monotonic() >= deadline: |
| 136 | # Assume a stale lock from a crashed run. |
| 137 | try: |
| 138 | self.lock_path.unlink() |
| 139 | except OSError: |
| 140 | return self |
| 141 | continue |
| 142 | time.sleep(0.05) |
| 143 | |
| 144 | def __exit__(self, *_exc: object) -> None: |
| 145 | if self.fd is not None: |
| 146 | try: |
| 147 | os.close(self.fd) |
| 148 | except OSError: |
| 149 | pass |
| 150 | try: |
| 151 | self.lock_path.unlink() |
| 152 | except OSError: |
| 153 | pass |
| 154 | |
| 155 | |
| 156 | # --------------------------------------------------------------------------- |
| 157 | # Core operations |
| 158 | # --------------------------------------------------------------------------- |
| 159 | |
| 160 | |
| 161 | def _by_url(sources: list[dict[str, Any]]) -> dict[str, dict[str, Any]]: |
| 162 | return {s["url"]: s for s in sources} |
| 163 | |
| 164 | |
| 165 | def add_sources( |
| 166 | path: Path, |
| 167 | urls: Iterable[str], |
| 168 | title: str | None = None, |
| 169 | accessed: str | None = None, |
| 170 | ) -> list[dict[str, Any]]: |
| 171 | """Register urls, returning their ledger entries (existing or new).""" |
| 172 | urls = [u for u in (str(u).strip() for u in urls) if u] |
| 173 | if not urls: |
| 174 | return [] |
| 175 | with _LedgerLock(path): |
| 176 | data = load_ledger(path) |
| 177 | sources = data["sources"] |
| 178 | index = _by_url(sources) |
| 179 | out: list[dict[str, Any]] = [] |
| 180 | changed = False |
| 181 | for raw in urls: |
| 182 | key = normalize_url(raw) |
| 183 | existing = index.get(key) |
| 184 | if existing is not None: |
| 185 | if title and not existing.get("title"): |
| 186 | existing["title"] = title |
| 187 | changed = True |
| 188 | out.append(existing) |
| 189 | continue |
| 190 | entry = { |
| 191 | "id": len(sources) + 1, |
| 192 | "url": key, |
| 193 | "title": (title or "").strip(), |
| 194 | "accessed": accessed or time.strftime("%Y-%m-%d"), |
| 195 | } |
| 196 | sources.append(entry) |
| 197 | index[key] = entry |
| 198 | out.append(entry) |
| 199 | changed = True |
| 200 | if changed: |
| 201 | save_ledger(path, data) |
| 202 | return out |
| 203 | |
| 204 | |
| 205 | def urls_from_json(payload: Any) -> list[tuple[str, str]]: |
| 206 | """Walk arbitrary JSON tool output collecting (url, title) pairs. |
| 207 | |
| 208 | Handles web_search (``data.web[]``), web_extract (``results[]``) and any |
| 209 | other nesting, in document order, deduped. |
| 210 | """ |
| 211 | found: list[tuple[str, str]] = [] |
| 212 | seen: set[str] = set() |
| 213 | |
| 214 | def walk(node: Any) -> None: |
| 215 | if isinstance(node, dict): |
| 216 | url = node.get("url") or node.get("link") or node.get("source_url") |
| 217 | if isinstance(url, str) and url.startswith(("http://", "https://")): |
| 218 | key = normalize_url(url) |
| 219 | if key not in seen: |
| 220 | seen.add(key) |
| 221 | raw_title = node.get("title") or node.get("name") or "" |
| 222 | found.append((url, raw_title if isinstance(raw_title, str) else "")) |
| 223 | for value in node.values(): |
| 224 | walk(value) |
| 225 | elif isinstance(node, list): |
| 226 | for item in node: |
| 227 | walk(item) |
| 228 | |
| 229 | walk(payload) |
| 230 | return found |
| 231 | |
| 232 | |
| 233 | # --------------------------------------------------------------------------- |
| 234 | # Evidence quotes (fact-checking) |
| 235 | # --------------------------------------------------------------------------- |
| 236 | |
| 237 | |
| 238 | def _normalize_ws(text: str) -> str: |
| 239 | """Collapse all whitespace runs to single spaces for verbatim matching.""" |
| 240 | return " ".join((text or "").split()) |
| 241 | |
| 242 | |
| 243 | # Markdown artifacts that retrieval tools inject into otherwise-identical prose. |
| 244 | # ``web_extract`` returns markdown, so the most citation-worthy sentences are |
| 245 | # exactly the ones carrying inline links and emphasis around terms: |
| 246 | # "including _[ERAP1](https://…/erap1/)_, _[IL1A](…)_, have also been…" |
| 247 | # reads identically to the page a human sees. Matching has to see through that |
| 248 | # markup, or the skill pushes the agent toward weaker evidence fragments. |
| 249 | _MD_LINK_RE = re.compile(r"\[([^\]]*)\]\((?:[^()\s]|\([^()]*\))*\)") |
| 250 | _MD_NOISE_RE = re.compile(r"[*_`~]|\\(?=[^\w\s])") |
| 251 | |
| 252 | |
| 253 | def _match_key(text: str) -> str: |
| 254 | """Canonicalize text for verbatim comparison. |
| 255 | |
| 256 | Whitespace-, case-, and markdown-insensitive: inline links collapse to |
| 257 | their label, emphasis/code markers and backslash escapes are dropped. The |
| 258 | stored quote keeps whatever the caller passed, so the rendered evidence |
| 259 | block shows clean prose rather than extractor artifacts. |
| 260 | """ |
| 261 | collapsed = _MD_LINK_RE.sub(r"\1", text or "") |
| 262 | return _normalize_ws(_MD_NOISE_RE.sub("", collapsed)).casefold() |
| 263 | |
| 264 | |
| 265 | def quote_in_evidence(quote: str, evidence: str) -> bool: |
| 266 | """True when ``quote`` appears verbatim in the fetched ``evidence`` text, |
| 267 | ignoring whitespace, case, and markdown markup on either side.""" |
| 268 | q = _match_key(quote) |
| 269 | return bool(q) and q in _match_key(evidence) |
| 270 | |
| 271 | |
| 272 | def attach_quote(path: Path, source_id: int, quote: str, evidence: str) -> dict[str, Any]: |
| 273 | """Attach a verbatim quote to a ledger entry after checking it against |
| 274 | the evidence text. Raises SystemExit on unknown id or non-verbatim text — |
| 275 | a quote the page does not contain is exactly the fabrication this guards |
| 276 | against.""" |
| 277 | quote = (quote or "").strip() |
| 278 | if len(_normalize_ws(quote).split()) < 3: |
| 279 | raise SystemExit("error: quote too short — use at least 3 words of verbatim text") |
| 280 | if not quote_in_evidence(quote, evidence): |
| 281 | raise SystemExit( |
| 282 | "error: quote not found verbatim in the evidence text — " |
| 283 | "copy the exact wording from the fetched page, do not paraphrase" |
| 284 | ) |
| 285 | with _LedgerLock(path): |
| 286 | data = load_ledger(path) |
| 287 | entry = next((s for s in data["sources"] if s["id"] == source_id), None) |
| 288 | if entry is None: |
| 289 | raise SystemExit(f"error: no source [{source_id}] in the ledger") |
| 290 | quotes = entry.setdefault("quotes", []) |
| 291 | norm = _match_key(quote) |
| 292 | if not any(_match_key(q.get("text", "")) == norm for q in quotes): |
| 293 | quotes.append({"text": quote, "added": time.strftime("%Y-%m-%d")}) |
| 294 | save_ledger(path, data) |
| 295 | return entry |
| 296 | |
| 297 | |
| 298 | def render_sources( |
| 299 | sources: list[dict[str, Any]], |
| 300 | style: str = "markdown", |
| 301 | only: set[int] | None = None, |
| 302 | ) -> str: |
| 303 | picked = [s for s in sources if only is None or s["id"] in only] |
| 304 | picked.sort(key=lambda s: s["id"]) |
| 305 | if not picked: |
| 306 | return "" |
| 307 | lines: list[str] = [] |
| 308 | if style == "bibtex": |
| 309 | for s in picked: |
| 310 | key = f"source{s['id']}" |
| 311 | title = s.get("title") or s["url"] |
| 312 | lines.append( |
| 313 | "@misc{{{},\n title = {{{}}},\n howpublished = {{\\url{{{}}}}},\n note = {{Accessed {}}}\n}}".format(key, title, s["url"], s.get("accessed", "")) |
| 314 | ) |
| 315 | return "\n".join(lines) |
| 316 | if style == "footnotes": |
| 317 | for s in picked: |
| 318 | title = s.get("title") |
| 319 | suffix = f" — {title}" if title else "" |
| 320 | lines.append(f"[^{s['id']}]: {s['url']}{suffix}") |
| 321 | return "\n".join(lines) |
| 322 | header = "Sources:" if style == "plain" else "## Sources" |
| 323 | lines.append(header) |
| 324 | if style != "plain": |
| 325 | lines.append("") |
| 326 | for s in picked: |
| 327 | title = s.get("title") |
| 328 | suffix = f" — {title}" if title else "" |
| 329 | lines.append(f"[{s['id']}] {s['url']}{suffix}") |
| 330 | if style == "evidence": |
| 331 | for q in s.get("quotes", []): |
| 332 | lines.append(f' > "{q.get("text", "")}"') |
| 333 | return "\n".join(lines) |
| 334 | |
| 335 | |
| 336 | # --------------------------------------------------------------------------- |
| 337 | # Verification |
| 338 | # --------------------------------------------------------------------------- |
| 339 | |
| 340 | |
| 341 | def _split_draft(text: str) -> tuple[str, dict[int, str]]: |
| 342 | """Split a draft into (prose, sources_block_map). |
| 343 | |
| 344 | The sources block is everything after the last ``Sources`` header; its |
| 345 | ``[n] url`` lines are parsed out so they aren't counted as prose citations. |
| 346 | Fenced code blocks are dropped from prose. |
| 347 | """ |
| 348 | lines = text.splitlines() |
| 349 | header_idx = -1 |
| 350 | for i, line in enumerate(lines): |
| 351 | if _SOURCES_HEADER_RE.match(line): |
| 352 | header_idx = i |
| 353 | listed: dict[int, str] = {} |
| 354 | if header_idx >= 0: |
| 355 | for line in lines[header_idx + 1:]: |
| 356 | m = _SOURCE_LINE_RE.match(line) |
| 357 | if m: |
| 358 | url_match = _URL_IN_TEXT_RE.search(line) |
| 359 | listed[int(m.group(1))] = url_match.group(0) if url_match else m.group(2) |
| 360 | body_lines = lines[:header_idx] |
| 361 | else: |
| 362 | body_lines = lines |
| 363 | prose: list[str] = [] |
| 364 | in_fence = False |
| 365 | for line in body_lines: |
| 366 | if _FENCE_RE.match(line): |
| 367 | in_fence = not in_fence |
| 368 | continue |
| 369 | if not in_fence: |
| 370 | prose.append(line) |
| 371 | return "\n".join(prose), listed |
| 372 | |
| 373 | |
| 374 | def _strip_sources_block(text: str) -> str: |
| 375 | """Return the draft with its trailing Sources block removed. |
| 376 | |
| 377 | Everything from the last Sources header onward goes; a draft with no such |
| 378 | header is returned unchanged. This is what makes ``render --replace-in`` |
| 379 | idempotent instead of stacking duplicate blocks. |
| 380 | """ |
| 381 | lines = text.splitlines() |
| 382 | header_idx = -1 |
| 383 | for i, line in enumerate(lines): |
| 384 | if _SOURCES_HEADER_RE.match(line): |
| 385 | header_idx = i |
| 386 | if header_idx < 0: |
| 387 | return text |
| 388 | return "\n".join(lines[:header_idx]) |
| 389 | |
| 390 | |
| 391 | def _sentences(prose: str) -> list[str]: |
| 392 | """Rough sentence split over prose lines, skipping headings and tables.""" |
| 393 | out: list[str] = [] |
| 394 | for line in prose.splitlines(): |
| 395 | stripped = line.strip() |
| 396 | if not stripped or stripped.startswith("#") or stripped.startswith("|"): |
| 397 | continue |
| 398 | if stripped.startswith(">"): |
| 399 | stripped = stripped.lstrip("> ").strip() |
| 400 | for part in re.split(r"(?<=[.!?])\s+", stripped): |
| 401 | part = part.strip() |
| 402 | if len(part.split()) >= 4: |
| 403 | out.append(part) |
| 404 | return out |
| 405 | |
| 406 | |
| 407 | def verify_draft( |
| 408 | draft_path: Path, |
| 409 | sources: list[dict[str, Any]], |
| 410 | strict: bool = False, |
| 411 | min_coverage: float | None = None, |
| 412 | require_evidence: bool = False, |
| 413 | ) -> tuple[int, list[str], list[str]]: |
| 414 | """Return (exit_code, errors, warnings).""" |
| 415 | text = draft_path.read_text(encoding="utf-8") |
| 416 | prose, listed = _split_draft(text) |
| 417 | by_id = {s["id"]: s for s in sources} |
| 418 | |
| 419 | errors: list[str] = [] |
| 420 | warnings: list[str] = [] |
| 421 | |
| 422 | cited = [int(m) for m in _CITE_RE.findall(prose)] |
| 423 | cited_set = set(cited) |
| 424 | |
| 425 | unknown = sorted(i for i in cited_set if i not in by_id) |
| 426 | if unknown: |
| 427 | errors.append( |
| 428 | "citations not in the ledger (hallucinated or renumbered): " |
| 429 | + ", ".join(f"[{i}]" for i in unknown) |
| 430 | ) |
| 431 | |
| 432 | if cited_set and not listed: |
| 433 | errors.append("draft cites sources but has no `Sources:` block — run `render --cited-in`") |
| 434 | |
| 435 | missing_from_block = sorted(cited_set - set(listed)) if listed else [] |
| 436 | if missing_from_block: |
| 437 | errors.append( |
| 438 | "cited but absent from the Sources block: " |
| 439 | + ", ".join(f"[{i}]" for i in missing_from_block) |
| 440 | ) |
| 441 | |
| 442 | for sid, url in sorted(listed.items()): |
| 443 | entry = by_id.get(sid) |
| 444 | if entry is None: |
| 445 | errors.append(f"Sources block lists [{sid}], which is not in the ledger") |
| 446 | continue |
| 447 | if normalize_url(url) != entry["url"]: |
| 448 | errors.append( |
| 449 | f"Sources block URL for [{sid}] does not match the ledger " |
| 450 | f"(block: {url} / ledger: {entry['url']}) — re-run `render`" |
| 451 | ) |
| 452 | |
| 453 | extra_in_block = sorted(set(listed) - cited_set) |
| 454 | if extra_in_block: |
| 455 | warnings.append( |
| 456 | "listed in Sources but never cited inline: " |
| 457 | + ", ".join(f"[{i}]" for i in extra_in_block) |
| 458 | ) |
| 459 | |
| 460 | registered_uncited = sorted(set(by_id) - cited_set) |
| 461 | if registered_uncited: |
| 462 | warnings.append( |
| 463 | "registered in the ledger but not cited in this draft: " |
| 464 | + ", ".join(f"[{i}]" for i in registered_uncited) |
| 465 | ) |
| 466 | |
| 467 | sentences = _sentences(prose) |
| 468 | cited_sentences = [s for s in sentences if _CITE_RE.search(s)] |
| 469 | unverified_sentences = [s for s in sentences if _UNVERIFIED_RE.search(s)] |
| 470 | covered = [s for s in sentences if _CITE_RE.search(s) or _UNVERIFIED_RE.search(s)] |
| 471 | coverage = (len(covered) / len(sentences)) if sentences else 0.0 |
| 472 | if min_coverage is not None and sentences and coverage < min_coverage: |
| 473 | errors.append( |
| 474 | f"citation coverage {coverage:.0%} is below the required {min_coverage:.0%} " |
| 475 | f"({len(covered)}/{len(sentences)} sentences cited or marked [unverified])" |
| 476 | ) |
| 477 | |
| 478 | if require_evidence: |
| 479 | unevidenced = sorted( |
| 480 | i for i in cited_set if i in by_id and not by_id[i].get("quotes") |
| 481 | ) |
| 482 | if unevidenced: |
| 483 | errors.append( |
| 484 | "cited sources carry no verbatim evidence quote (run `quote` with the " |
| 485 | "fetched page text): " + ", ".join(f"[{i}]" for i in unevidenced) |
| 486 | ) |
| 487 | |
| 488 | over_cited = [s for s in sentences if len(_CITE_RE.findall(s)) > 3] |
| 489 | if over_cited: |
| 490 | warnings.append(f"{len(over_cited)} sentence(s) carry more than 3 citations") |
| 491 | |
| 492 | code = 1 if errors else (1 if (strict and warnings) else 0) |
| 493 | quoted = sum(1 for s in sources if s.get("quotes")) |
| 494 | stats = ( |
| 495 | f"{len(sentences)} prose sentence(s), {len(covered)} with declared provenance " |
| 496 | f"({coverage:.0%}) — {len(cited_sentences)} cited, " |
| 497 | f"{len(unverified_sentences)} marked [unverified] (a sentence may be both); " |
| 498 | f"{len(cited_set)} distinct source(s) cited, " |
| 499 | f"{len(by_id)} in ledger ({quoted} with evidence quotes)" |
| 500 | ) |
| 501 | warnings.insert(0, f"stats: {stats}") |
| 502 | return code, errors, warnings |
| 503 | |
| 504 | |
| 505 | # --------------------------------------------------------------------------- |
| 506 | # CLI |
| 507 | # --------------------------------------------------------------------------- |
| 508 | |
| 509 | |
| 510 | def _parse_only(spec: str | None) -> set[int] | None: |
| 511 | if not spec: |
| 512 | return None |
| 513 | out: set[int] = set() |
| 514 | for chunk in spec.replace(" ", "").split(","): |
| 515 | if not chunk: |
| 516 | continue |
| 517 | if "-" in chunk: |
| 518 | lo, _, hi = chunk.partition("-") |
| 519 | out.update(range(int(lo), int(hi) + 1)) |
| 520 | else: |
| 521 | out.add(int(chunk)) |
| 522 | return out |
| 523 | |
| 524 | |
| 525 | def main(argv: list[str] | None = None) -> int: |
| 526 | parser = argparse.ArgumentParser( |
| 527 | prog="sources.py", description="Citation ledger for grounded answers and documents." |
| 528 | ) |
| 529 | parser.add_argument("--ledger", help="ledger file path (overrides env / default)") |
| 530 | sub = parser.add_subparsers(dest="cmd", required=True) |
| 531 | |
| 532 | sub.add_parser("reset", help="start a clean ledger") |
| 533 | |
| 534 | p_add = sub.add_parser("add", help="register source url(s), print their ids") |
| 535 | p_add.add_argument("urls", nargs="+") |
| 536 | p_add.add_argument("--title", help="title for the source (single-url calls)") |
| 537 | p_add.add_argument("--accessed", help="access date (default: today)") |
| 538 | p_add.add_argument("--json", action="store_true", help="emit JSON instead of ids") |
| 539 | |
| 540 | p_ing = sub.add_parser("ingest", help="register every url in JSON tool output") |
| 541 | p_ing.add_argument("file", help="JSON file, or - for stdin") |
| 542 | |
| 543 | p_q = sub.add_parser("quote", help="attach verbatim supporting evidence to a source") |
| 544 | p_q.add_argument("id", type=int, help="ledger id of the source the quote supports") |
| 545 | p_q.add_argument("--text", required=True, help="the exact quote, copied from the page") |
| 546 | p_q.add_argument( |
| 547 | "--from", |
| 548 | dest="evidence", |
| 549 | required=True, |
| 550 | help="file with the fetched page text (or - for stdin) the quote must appear in", |
| 551 | ) |
| 552 | |
| 553 | p_list = sub.add_parser("list", help="show the ledger") |
| 554 | p_list.add_argument("--json", action="store_true") |
| 555 | |
| 556 | p_render = sub.add_parser("render", help="render a Sources block") |
| 557 | p_render.add_argument( |
| 558 | "--style", default="markdown", choices=["markdown", "plain", "footnotes", "bibtex", "evidence"] |
| 559 | ) |
| 560 | p_render.add_argument("--only", help="ids to include, e.g. 1,3,5-7") |
| 561 | p_render.add_argument("--cited-in", help="include only ids cited in this draft file") |
| 562 | p_render.add_argument( |
| 563 | "--replace-in", |
| 564 | help="rewrite this draft's Sources block in place (implies --cited-in on it)", |
| 565 | ) |
| 566 | |
| 567 | p_ver = sub.add_parser("verify", help="check a draft's citations against the ledger") |
| 568 | p_ver.add_argument("draft") |
| 569 | p_ver.add_argument("--strict", action="store_true", help="treat warnings as failures") |
| 570 | p_ver.add_argument("--min-coverage", type=float, help="required cited-sentence share, e.g. 0.5") |
| 571 | p_ver.add_argument( |
| 572 | "--evidence", |
| 573 | action="store_true", |
| 574 | help="require every cited source to carry at least one verbatim quote", |
| 575 | ) |
| 576 | |
| 577 | args = parser.parse_args(argv) |
| 578 | path = resolve_ledger_path(args.ledger) |
| 579 | |
| 580 | if args.cmd == "reset": |
| 581 | with _LedgerLock(path): |
| 582 | save_ledger(path, {"version": SCHEMA_VERSION, "sources": []}) |
| 583 | print(f"ledger reset: {path}") |
| 584 | return 0 |
| 585 | |
| 586 | if args.cmd == "add": |
| 587 | title = args.title if len(args.urls) == 1 else None |
| 588 | entries = add_sources(path, args.urls, title=title, accessed=args.accessed) |
| 589 | if args.json: |
| 590 | print(json.dumps(entries, indent=2, ensure_ascii=False)) |
| 591 | else: |
| 592 | for e in entries: |
| 593 | print(f"[{e['id']}] {e['url']}") |
| 594 | return 0 |
| 595 | |
| 596 | if args.cmd == "ingest": |
| 597 | raw = sys.stdin.read() if args.file == "-" else Path(args.file).read_text(encoding="utf-8") |
| 598 | try: |
| 599 | payload = json.loads(raw) |
| 600 | except json.JSONDecodeError as exc: |
| 601 | print(f"error: input is not valid JSON ({exc})", file=sys.stderr) |
| 602 | return 2 |
| 603 | pairs = urls_from_json(payload) |
| 604 | if not pairs: |
| 605 | print("no urls found in input", file=sys.stderr) |
| 606 | return 1 |
| 607 | for url, title in pairs: |
| 608 | entry = add_sources(path, [url], title=title or None)[0] |
| 609 | print(f"[{entry['id']}] {entry['url']}") |
| 610 | return 0 |
| 611 | |
| 612 | if args.cmd == "quote": |
| 613 | raw = ( |
| 614 | sys.stdin.read() |
| 615 | if args.evidence == "-" |
| 616 | else Path(args.evidence).read_text(encoding="utf-8") |
| 617 | ) |
| 618 | entry = attach_quote(path, args.id, args.text, raw) |
| 619 | print(f"[{entry['id']}] evidence attached ({len(entry.get('quotes', []))} quote(s))") |
| 620 | return 0 |
| 621 | |
| 622 | data = load_ledger(path) |
| 623 | sources = sorted(data["sources"], key=lambda s: s["id"]) |
| 624 | |
| 625 | if args.cmd == "list": |
| 626 | if args.json: |
| 627 | print(json.dumps(sources, indent=2, ensure_ascii=False)) |
| 628 | elif not sources: |
| 629 | print(f"ledger is empty: {path}") |
| 630 | else: |
| 631 | for s in sources: |
| 632 | title = f" {s['title']}" if s.get("title") else "" |
| 633 | nq = len(s.get("quotes", [])) |
| 634 | mark = f" ({nq} quote{'s' if nq != 1 else ''})" if nq else "" |
| 635 | print(f"[{s['id']}] {s['url']}{title}{mark}") |
| 636 | return 0 |
| 637 | |
| 638 | if args.cmd == "render": |
| 639 | only = _parse_only(args.only) |
| 640 | draft_for_ids = args.replace_in or args.cited_in |
| 641 | if draft_for_ids: |
| 642 | draft = Path(draft_for_ids).read_text(encoding="utf-8") |
| 643 | prose, _ = _split_draft(draft) |
| 644 | cited = {int(m) for m in _CITE_RE.findall(prose)} |
| 645 | only = cited if only is None else (only & cited) |
| 646 | block = render_sources(sources, style=args.style, only=only) |
| 647 | if not block: |
| 648 | print("no sources to render", file=sys.stderr) |
| 649 | return 1 |
| 650 | if args.replace_in: |
| 651 | target = Path(args.replace_in) |
| 652 | body = _strip_sources_block(target.read_text(encoding="utf-8")) |
| 653 | target.write_text(body.rstrip("\n") + "\n\n" + block + "\n", encoding="utf-8") |
| 654 | print(f"Sources block rewritten in {target}") |
| 655 | return 0 |
| 656 | print(block) |
| 657 | return 0 |
| 658 | |
| 659 | if args.cmd == "verify": |
| 660 | draft_path = Path(args.draft) |
| 661 | if not draft_path.is_file(): |
| 662 | print(f"error: no such draft: {draft_path}", file=sys.stderr) |
| 663 | return 2 |
| 664 | code, errors, warnings = verify_draft( |
| 665 | draft_path, |
| 666 | sources, |
| 667 | strict=args.strict, |
| 668 | min_coverage=args.min_coverage, |
| 669 | require_evidence=args.evidence, |
| 670 | ) |
| 671 | for w in warnings: |
| 672 | prefix = "info" if w.startswith("stats: ") else "warn" |
| 673 | print(f"{prefix}: {w}") |
| 674 | for e in errors: |
| 675 | print(f"FAIL: {e}", file=sys.stderr) |
| 676 | print("citations OK" if code == 0 else "verification failed") |
| 677 | return code |
| 678 | |
| 679 | return 2 |
| 680 | |
| 681 | |
| 682 | if __name__ == "__main__": |
| 683 | sys.exit(main()) |