#!/usr/bin/env python3 """ hyperstitionstud_io.ci.citation_sources Complete Grounded-Citations Ledger & Fact-Checking Engine (100% Offline & Local-Config Driven). Implements the full 11-function Python API and all 7 CLI subcommands of grounded-citations (`reset`, `add`, `ingest`, `quote`, `list`, `render`, `verify`) while enforcing: 1. Pure local-configuration URL resolution (`[citations.path_mounts]` in workspace.toml) — zero git/VCS subprocess calls and zero global package namespace URL synthesis. 2. Dual-scheme URL & local-path parsing (`http://`, `https://`, `file://`, and `/workspace/...`, with automatic backtick stripping in `_split_draft`). 3. Backwards-compatible `local_path` handling for existing v1 citation ledgers. 4. Fenced code-block exclusion + Markdown table citation support in `verify_draft()`. """ from __future__ import annotations import argparse import json import os import re import sys import time from pathlib import Path from typing import Any, Iterable from hyperstitionstud_io.config import load_json_cached, load_workspace_config SCHEMA_VERSION = 1 _CITE_RE = re.compile(r"\[(\d{1,4})\](?![(:])") _SOURCES_HEADER_RE = re.compile(r"^\s*(?:#{1,6}\s*)?(?:\*\*)?sources:?(?:\*\*)?\s*$", re.IGNORECASE) _SOURCE_LINE_RE = re.compile(r"^\s*\[(\d{1,4})\]\s*[-–:]?\s*(\S+)") _URL_IN_TEXT_RE = re.compile(r"(?:https?://|file://|/)[^\s\"'`<>)\]}]+") _FENCE_RE = re.compile(r"^\s*(?:```|~~~)") _UNVERIFIED_RE = re.compile(r"\[unverified\]", re.IGNORECASE) _MD_LINK_RE = re.compile(r"\[([^\]]*)\]\((?:[^()\s]|\([^()]*\))*\)") _MD_NOISE_RE = re.compile(r"[*_`~]|\\(?=[^\w\s])") def resolve_ledger_path(explicit: str | None = None) -> Path: if explicit: return Path(explicit).expanduser() env = os.environ.get("HERMES_CITATION_LEDGER", "").strip() if env: return Path(env).expanduser() cfg = load_workspace_config() default_common = cfg.zoology_dir / "taxonomy" / "citations-ledger-common.json" if default_common.is_file(): return default_common return Path.home() / ".hermes" / "cache" / "citations" / "ledger.json" def resolve_citation_target( local_path: str | Path, path_mounts: dict[str, str] | None = None, ) -> str: """ Resolve a local file path to a remote URL ONLY if its directory prefix is explicitly mapped in local configuration (`[citations.path_mounts]`). Otherwise, return the resolved local filesystem path unchanged. Zero VCS subprocess calls; zero global namespace URLs. """ raw_str = str(local_path).strip() if raw_str.startswith(("http://", "https://", "file://")): return normalize_url(raw_str) resolved = Path(raw_str).resolve() resolved_str = resolved.as_posix() mounts = path_mounts if path_mounts is not None else load_workspace_config().citation_path_mounts for local_prefix, remote_base in sorted(mounts.items(), key=lambda kv: -len(kv[0])): norm_prefix = Path(local_prefix).resolve().as_posix().rstrip("/") if resolved_str == norm_prefix or resolved_str.startswith(norm_prefix + "/"): rel_suffix = resolved_str[len(norm_prefix) :].lstrip("/") base = remote_base.rstrip("/") return f"{base}/{rel_suffix}" if rel_suffix else base return resolved_str def resolve_repo_url_or_path( local_full_path: str, prefer_local_if_no_remote: bool = True, path_mounts: dict[str, str] | None = None, ) -> str: """ Backwards-compatible entry point replacing the legacy git-subprocess resolver. Resolves purely from local configuration (`[citations.path_mounts]`) or returns the verified local filesystem path. """ return resolve_citation_target(local_full_path, path_mounts=path_mounts) def normalize_url(url: str) -> str: u = (url or "").strip().strip("`") if "#" in u and u.startswith(("http://", "https://", "file://")): u = u.split("#", 1)[0] stripped = u.rstrip("/") return stripped or u def load_ledger(path: Path) -> dict[str, Any]: if not path.exists(): return {"version": SCHEMA_VERSION, "sources": []} try: data = load_json_cached(path, copy_result=True) except (json.JSONDecodeError, OSError) as exc: raise SystemExit(f"error: ledger at {path} is unreadable ({exc}); run `reset` to start over") if not isinstance(data, dict) or not isinstance(data.get("sources"), list): raise SystemExit(f"error: ledger at {path} has an unexpected shape; run `reset`") cfg = load_workspace_config() for entry in data["sources"]: if "local_path" not in entry and isinstance(entry.get("url"), str) and entry["url"].startswith("/"): raw_u = entry["url"] if Path(raw_u).exists(): entry["local_path"] = raw_u elif raw_u.startswith("/workspace/"): rebased = cfg.workspace_root / raw_u[len("/workspace/") :] entry["local_path"] = rebased.as_posix() if rebased.exists() else raw_u else: entry["local_path"] = raw_u return data def save_ledger(path: Path, data: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + f".tmp{os.getpid()}") tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") os.replace(tmp, path) class _LedgerLock: """Best-effort cross-process lock (O_EXCL lockfile, stdlib only).""" def __init__(self, path: Path, timeout: float = 5.0) -> None: self.lock_path = path.with_suffix(path.suffix + ".lock") self.timeout = timeout self.fd: int | None = None def __enter__(self) -> _LedgerLock: self.lock_path.parent.mkdir(parents=True, exist_ok=True) deadline = time.monotonic() + self.timeout while True: try: self.fd = os.open(str(self.lock_path), os.O_CREAT | os.O_EXCL | os.O_WRONLY) return self except FileExistsError: if time.monotonic() >= deadline: try: self.lock_path.unlink() except OSError: return self continue time.sleep(0.05) def __exit__(self, *_exc: object) -> None: if self.fd is not None: try: os.close(self.fd) except OSError: pass try: self.lock_path.unlink() except OSError: pass def add_sources( path: Path, urls: Iterable[str], title: str | None = None, accessed: str | None = None, path_mounts: dict[str, str] | None = None, ) -> list[dict[str, Any]]: urls = [u for u in (str(u).strip() for u in urls) if u] if not urls: return [] with _LedgerLock(path): data = load_ledger(path) sources = data["sources"] by_url = {s["url"]: s for s in sources} by_local = {s["local_path"]: s for s in sources if s.get("local_path")} out: list[dict[str, Any]] = [] changed = False for raw in urls: is_local = raw.startswith("/") or Path(raw).exists() local_key = Path(raw).resolve().as_posix() if is_local and not raw.startswith(("http://", "https://", "file://")) else None resolved_url = resolve_citation_target(local_key, path_mounts=path_mounts) if local_key else normalize_url(raw) existing = (by_local.get(local_key) if local_key else None) or by_url.get(resolved_url) if existing is not None: if title and not existing.get("title"): existing["title"] = title changed = True if local_key and not existing.get("local_path"): existing["local_path"] = local_key changed = True out.append(existing) continue entry: dict[str, Any] = { "id": len(sources) + 1, "url": resolved_url, "title": (title or "").strip(), "accessed": accessed or time.strftime("%Y-%m-%d"), } if local_key: entry["local_path"] = local_key by_local[local_key] = entry sources.append(entry) by_url[resolved_url] = entry out.append(entry) changed = True if changed: save_ledger(path, data) return out def urls_from_json(payload: Any) -> list[tuple[str, str]]: found: list[tuple[str, str]] = [] seen: set[str] = set() def walk(node: Any) -> None: if isinstance(node, dict): url = node.get("url") or node.get("link") or node.get("source_url") if isinstance(url, str) and url.startswith(("http://", "https://", "/")): key = normalize_url(url) if key not in seen: seen.add(key) raw_title = node.get("title") or node.get("name") or "" found.append((url, raw_title if isinstance(raw_title, str) else "")) for value in node.values(): walk(value) elif isinstance(node, list): for item in node: walk(item) walk(payload) return found def _normalize_ws(text: str) -> str: return " ".join((text or "").split()) def _match_key(text: str) -> str: collapsed = _MD_LINK_RE.sub(r"\1", text or "") return _normalize_ws(_MD_NOISE_RE.sub("", collapsed)).casefold() def quote_in_evidence(quote: str, evidence: str) -> bool: q = _match_key(quote) return bool(q) and q in _match_key(evidence) def attach_quote(path: Path, source_id: int, quote: str, evidence: str | None = None) -> dict[str, Any]: quote = (quote or "").strip() if len(_normalize_ws(quote).split()) < 3: raise SystemExit("error: quote too short — use at least 3 words of verbatim text") with _LedgerLock(path): data = load_ledger(path) entry = next((s for s in data["sources"] if s["id"] == source_id), None) if entry is None: raise SystemExit(f"error: no source [{source_id}] in the ledger") if evidence is None and entry.get("local_path") and Path(entry["local_path"]).is_file(): evidence = Path(entry["local_path"]).read_text(encoding="utf-8") if evidence is None: raise SystemExit("error: no evidence text provided and source has no readable local_path") if not quote_in_evidence(quote, evidence): raise SystemExit(f"error: quote not found verbatim in the evidence text: {quote[:80]}") quotes = entry.setdefault("quotes", []) norm = _match_key(quote) if not any(_match_key(q.get("text", "")) == norm for q in quotes): quotes.append({"text": quote, "added": time.strftime("%Y-%m-%d")}) save_ledger(path, data) return entry def render_sources( sources: list[dict[str, Any]], style: str = "markdown", only: set[int] | None = None, ) -> str: picked = [s for s in sources if only is None or s["id"] in only] picked.sort(key=lambda s: s["id"]) if not picked: return "" lines: list[str] = [] if style == "bibtex": for s in picked: key = f"source{s['id']}" title = s.get("title") or s["url"] lines.append( "@misc{{{},\n title = {{{}}},\n howpublished = {{\\url{{{}}}}},\n note = {{Accessed {}}}\n}}".format( key, title, s["url"], s.get("accessed", "") ) ) return "\n".join(lines) if style == "footnotes": for s in picked: title = s.get("title") suffix = f" — {title}" if title else "" lines.append(f"[^{s['id']}]: {s['url']}{suffix}") return "\n".join(lines) header = "Sources:" if style == "plain" else "## Sources" lines.append(header) if style != "plain": lines.append("") for s in picked: title = s.get("title") suffix = f" — {title}" if title else "" lines.append(f"[{s['id']}] `{s['url']}`{suffix}") if style == "evidence": for q in s.get("quotes", []): lines.append(f' - Verbatim Lock: `"{q.get("text", "")}"`') return "\n".join(lines) def _split_draft(text: str) -> tuple[str, dict[int, str]]: lines = text.splitlines() header_idx = -1 for i, line in enumerate(lines): if _SOURCES_HEADER_RE.match(line): header_idx = i listed: dict[int, str] = {} if header_idx >= 0: for line in lines[header_idx + 1 :]: m = _SOURCE_LINE_RE.match(line) if m: raw_target = m.group(2).strip("`") url_match = _URL_IN_TEXT_RE.search(raw_target) listed[int(m.group(1))] = (url_match.group(0) if url_match else raw_target).strip("`") body_lines = lines[:header_idx] else: body_lines = lines prose: list[str] = [] in_fence = False for line in body_lines: if _FENCE_RE.match(line): in_fence = not in_fence continue if not in_fence: prose.append(line) return "\n".join(prose), listed def _strip_sources_block(text: str) -> str: lines = text.splitlines() header_idx = -1 for i, line in enumerate(lines): if _SOURCES_HEADER_RE.match(line): header_idx = i if header_idx < 0: return text return "\n".join(lines[:header_idx]) def _sentences(prose: str) -> list[str]: out: list[str] = [] for line in prose.splitlines(): stripped = line.strip() if not stripped or stripped.startswith("#") or stripped.startswith("|") or stripped == "---": continue if stripped.startswith(">"): stripped = stripped.lstrip("> ").strip() for part in re.split(r"(?<=[.!?])\s+", stripped): part = part.strip() if len(part.split()) >= 4: out.append(part) return out def verify_draft( draft_path: Path, sources: list[dict[str, Any]], strict: bool = False, min_coverage: float | None = None, require_evidence: bool = False, ) -> tuple[int, list[str], list[str]]: text = draft_path.read_text(encoding="utf-8") prose, listed = _split_draft(text) by_id = {s["id"]: s for s in sources} errors: list[str] = [] warnings: list[str] = [] cited = [int(m) for m in _CITE_RE.findall(prose)] cited_set = set(cited) unknown = sorted(i for i in cited_set if i not in by_id) if unknown: errors.append("citations not in the ledger: " + ", ".join(f"[{i}]" for i in unknown)) if cited_set and not listed: errors.append("draft cites sources but has no `Sources` block") missing_from_block = sorted(cited_set - set(listed)) if listed else [] if missing_from_block: errors.append("cited but absent from the Sources block: " + ", ".join(f"[{i}]" for i in missing_from_block)) for sid, url in sorted(listed.items()): entry = by_id.get(sid) if entry is None: errors.append(f"Sources block lists [{sid}], which is not in the ledger") continue valid_targets = {normalize_url(entry["url"])} if entry.get("local_path"): valid_targets.add(normalize_url(entry["local_path"])) valid_targets.add(normalize_url(resolve_citation_target(entry["local_path"]))) if normalize_url(url) not in valid_targets: errors.append(f"Sources block URL for [{sid}] does not match ledger ({url} vs {entry['url']})") if require_evidence: unevidenced = sorted(i for i in cited_set if i in by_id and not by_id[i].get("quotes")) if unevidenced: errors.append("cited sources carry no verbatim evidence quote: " + ", ".join(f"[{i}]" for i in unevidenced)) sentences = _sentences(prose) covered = [s for s in sentences if _CITE_RE.search(s) or _UNVERIFIED_RE.search(s)] coverage = (len(covered) / len(sentences)) if sentences else 0.0 if min_coverage is not None and sentences and coverage < min_coverage: errors.append(f"citation coverage {coverage:.0%} is below {min_coverage:.0%}") quoted = sum(1 for s in sources if s.get("quotes")) warnings.insert( 0, f"stats: {len(sentences)} prose sentences, {len(covered)} cited ({coverage:.0%}); " f"{len(cited_set)} distinct sources cited, {len(by_id)} in ledger ({quoted} with evidence quotes)", ) code = 1 if errors else (1 if (strict and warnings) else 0) return code, errors, warnings def _parse_only(spec: str | None) -> set[int] | None: if not spec: return None out: set[int] = set() for chunk in spec.replace(" ", "").split(","): if not chunk: continue if "-" in chunk: lo, _, hi = chunk.partition("-") out.update(range(int(lo), int(hi) + 1)) else: out.add(int(chunk)) return out def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="sources.py", description="Citation ledger for grounded answers and documents.") parser.add_argument("--ledger", help="ledger file path (overrides env / default)") sub = parser.add_subparsers(dest="cmd", required=True) sub.add_parser("reset", help="start a clean ledger") p_add = sub.add_parser("add", help="register source url(s) or local paths, print their ids") p_add.add_argument("urls", nargs="+") p_add.add_argument("--title", help="title for the source (single-url calls)") p_add.add_argument("--accessed", help="access date (default: today)") p_add.add_argument("--json", action="store_true", help="emit JSON instead of ids") p_ing = sub.add_parser("ingest", help="register every url in JSON tool output") p_ing.add_argument("file", help="JSON file, or - for stdin") p_q = sub.add_parser("quote", help="attach verbatim supporting evidence to a source") p_q.add_argument("id", type=int, help="ledger id of the source the quote supports") p_q.add_argument("--text", required=True, help="the exact quote, copied from the page") p_q.add_argument("--from", dest="evidence", default=None, help="file with evidence text (or - for stdin; defaults to local_path if available)") p_list = sub.add_parser("list", help="show the ledger") p_list.add_argument("--json", action="store_true") p_render = sub.add_parser("render", help="render a Sources block") p_render.add_argument("--style", default="evidence", choices=["markdown", "plain", "footnotes", "bibtex", "evidence"]) p_render.add_argument("--only", help="ids to include, e.g. 1,3,5-7") p_render.add_argument("--cited-in", help="include only ids cited in this draft file") p_render.add_argument("--replace-in", help="rewrite this draft's Sources block in place") p_ver = sub.add_parser("verify", help="check a draft's citations against the ledger") p_ver.add_argument("draft") p_ver.add_argument("--strict", action="store_true", help="treat warnings as failures") p_ver.add_argument("--min-coverage", type=float, default=None) p_ver.add_argument("--evidence", action="store_true", help="require every cited source to carry at least one verbatim quote") args = parser.parse_args(argv) path = resolve_ledger_path(args.ledger) if args.cmd == "reset": with _LedgerLock(path): save_ledger(path, {"version": SCHEMA_VERSION, "sources": []}) return 0 if args.cmd == "add": title = args.title if len(args.urls) == 1 else None entries = add_sources(path, args.urls, title=title, accessed=args.accessed) if args.json: print(json.dumps(entries, indent=2, ensure_ascii=False)) else: for e in entries: print(f"[{e['id']}] {e['url']}") return 0 if args.cmd == "ingest": raw = sys.stdin.read() if args.file == "-" else Path(args.file).read_text(encoding="utf-8") payload = json.loads(raw) pairs = urls_from_json(payload) if not pairs: print("no urls found in input", file=sys.stderr) return 1 for url, title in pairs: entry = add_sources(path, [url], title=title or None)[0] print(f"[{entry['id']}] {entry['url']}") return 0 if args.cmd == "quote": raw = None if args.evidence == "-": raw = sys.stdin.read() elif args.evidence: raw = Path(args.evidence).read_text(encoding="utf-8") entry = attach_quote(path, args.id, args.text, raw) print(f"[{entry['id']}] evidence attached ({len(entry.get('quotes', []))} quote(s))") return 0 data = load_ledger(path) sources = sorted(data["sources"], key=lambda s: s["id"]) if args.cmd == "list": if args.json: print(json.dumps(sources, indent=2, ensure_ascii=False)) else: for s in sources: title = f" {s['title']}" if s.get("title") else "" nq = len(s.get("quotes", [])) mark = f" ({nq} quote{'s' if nq != 1 else ''})" if nq else "" print(f"[{s['id']}] {s['url']}{title}{mark}") return 0 if args.cmd == "render": only = _parse_only(args.only) draft_for_ids = args.replace_in or args.cited_in if draft_for_ids: draft = Path(draft_for_ids).read_text(encoding="utf-8") prose, _ = _split_draft(draft) cited = {int(m) for m in _CITE_RE.findall(prose)} only = cited if only is None else (only & cited) block = render_sources(sources, style=args.style, only=only) if not block: print("no sources to render", file=sys.stderr) return 1 if args.replace_in: target = Path(args.replace_in) body = _strip_sources_block(target.read_text(encoding="utf-8")) target.write_text(body.rstrip("\n") + "\n\n---\n\n" + block + "\n", encoding="utf-8") print(f"Rendered {len(only or sources)} cited sources into {target}") return 0 print(block) return 0 if args.cmd == "verify": code, errors, warnings = verify_draft( Path(args.draft), sources, strict=args.strict, min_coverage=args.min_coverage, require_evidence=args.evidence, ) for w in warnings: print(w) for e in errors: print(f"FAIL: {e}", file=sys.stderr) print("citations OK" if code == 0 else "verification failed") return code return 0 if __name__ == "__main__": raise SystemExit(main())