Files
technocapital-singularity-z…/scripts/sources.py
T

348 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Citation ledger for grounded answers and documents (with local full-path fallback support)."""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
import time
from pathlib import Path
from typing import Any, Iterable
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?://|/)[^\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_repo_url_or_path(local_full_path: str, prefer_local_if_no_remote: bool = True) -> str:
"""
Resolve a local file path to its hosted Git repository HTTPS URL when the owning
repository has a configured git remote, or fall back to the local filesystem full path
when no git remote URL is available.
"""
p = Path(local_full_path).resolve()
cur = p if p.is_dir() else p.parent
repo_root = None
while cur != cur.parent:
if (cur / ".git").exists():
repo_root = cur
break
cur = cur.parent
if repo_root is None:
return str(p)
res = subprocess.run(
["git", "-C", str(repo_root), "remote", "get-url", "origin"],
capture_output=True,
text=True,
)
remote = res.stdout.strip() if res.returncode == 0 else ""
if not remote:
return str(p)
br = subprocess.run(
["git", "-C", str(repo_root), "rev-parse", "--abbrev-ref", "HEAD"],
capture_output=True,
text=True,
)
branch = br.stdout.strip() if br.returncode == 0 and br.stdout.strip() else "main"
rel = p.relative_to(repo_root).as_posix()
if remote.startswith("ssh://git@git.libre.audio:2222/"):
slug = remote.split("ssh://git@git.libre.audio:2222/", 1)[1]
if slug.endswith(".git"):
slug = slug[:-4]
return f"https://git.libre.audio/{slug}/src/branch/{branch}/{rel}"
if "github.com/" in remote:
slug = remote.split("github.com/", 1)[1]
if slug.endswith(".git"):
slug = slug[:-4]
return f"https://github.com/{slug}/blob/{branch}/{rel}"
return str(p)
def normalize_url(url: str) -> str:
u = (url or "").strip()
if "#" in u and u.startswith(("http://", "https://")):
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": []}
return json.loads(path.read_text(encoding="utf-8"))
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)
def add_sources(
path: Path,
urls: Iterable[str],
title: str | None = None,
accessed: 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 []
data = load_ledger(path)
sources = data["sources"]
index = {s["url"]: s for s in sources}
out: list[dict[str, Any]] = []
changed = False
for raw in urls:
key = normalize_url(raw)
existing = index.get(key)
if existing is not None:
if title and not existing.get("title"):
existing["title"] = title
changed = True
out.append(existing)
continue
entry = {
"id": len(sources) + 1,
"url": key,
"title": (title or "").strip(),
"accessed": accessed or time.strftime("%Y-%m-%d"),
}
sources.append(entry)
index[key] = entry
out.append(entry)
changed = True
if changed:
save_ledger(path, data)
return out
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) -> 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")
if not quote_in_evidence(quote, evidence):
raise SystemExit(f"error: quote not found verbatim in the evidence text: {quote[:80]}")
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")
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] = ["## Sources", ""]
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("`")
listed[int(m.group(1))] = raw_target
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] = []
# Collect citations from both prose and markdown tables
body_without_sources = _strip_sources_block(text)
cited = [int(m) for m in _CITE_RE.findall(body_without_sources)]
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
if normalize_url(url) != entry["url"]:
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 0
return code, errors, warnings
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="sources.py")
parser.add_argument("--ledger", required=True)
sub = parser.add_subparsers(dest="cmd", required=True)
sub.add_parser("reset")
p_render = sub.add_parser("render")
p_render.add_argument("--style", default="evidence", choices=["markdown", "evidence"])
p_render.add_argument("--replace-in", required=True)
p_ver = sub.add_parser("verify")
p_ver.add_argument("draft")
p_ver.add_argument("--min-coverage", type=float, default=None)
p_ver.add_argument("--evidence", action="store_true")
args = parser.parse_args(argv)
path = Path(args.ledger)
if args.cmd == "reset":
save_ledger(path, {"version": SCHEMA_VERSION, "sources": []})
return 0
data = load_ledger(path)
sources = sorted(data["sources"], key=lambda s: s["id"])
if args.cmd == "render":
target = Path(args.replace_in)
body = _strip_sources_block(target.read_text(encoding="utf-8"))
cited = {int(m) for m in _CITE_RE.findall(body)}
block = render_sources(sources, style=args.style, only=cited)
target.write_text(body.rstrip("\n") + "\n\n---\n\n" + block + "\n", encoding="utf-8")
print(f"Rendered {len(cited)} cited sources into {target}")
return 0
if args.cmd == "verify":
code, errors, warnings = verify_draft(
Path(args.draft),
sources,
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())