Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : SP Boucher Source Governance9# File : spbheader/cli.py10# Description : spb-header command line.11# Module : spbheader12# Repository : https://git.spboucher.ai/spb-source-governance13# Project Website : https://git.spboucher.ai14# Created : 2026-11-2115# Last Modified : 2026-11-2116#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author : Simon-Pierre Boucher22# Position : Professor of Finance23# Institution : Université du Québec en Outaouais (UQO)24# Department : Département des sciences administratives25# Organization : SP Boucher26#27# Website : https://spboucher.ai28# Git : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General : info@spboucher.ai35# Professional : contact@spboucher.ai36# Direct : simon@spboucher.ai37# Research : research@spboucher.ai38# Development : dev@spboucher.ai39# Support : support@spboucher.ai40# Security/Admin : admin@spboucher.ai41# Notifications : notifications@spboucher.ai42#43# Preferred Contact: dev@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification : Public68# Distribution : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License : None specified (no license file in this repository)82# Maintainer : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889"""spb-header command line.9091Two modes:92 * workspace mode (-w DIR): DIR/repos/<visibility>/<slug> clones, DIR/policies, DIR/ledger, DIR/reports93 * repository mode (--repo DIR): one working tree carrying .spb-source-governance.toml (hooks, CI)94"""95from __future__ import annotations9697import argparse98import ast99import collections100import csv101import datetime as dt102import difflib103import json104import os105import re106import subprocess107import sys108import tempfile109from pathlib import Path110111from . import core, repo as R112113COMMIT_MSG = ("chore: standardize SP Boucher source headers and attribution\n\n"114 "Comment-only change produced by spb-header {v}; no executable code modified.\n"115 "Rollback: git revert this commit, or `spb-header rollback`.\n")116CLAUDE_START, CLAUDE_END = "<!-- spb-source-governance:start -->", "<!-- spb-source-governance:end -->"117CLAUDE_SECTION = f"""{CLAUDE_START}118## Source header policy (SP Boucher)119120When creating or modifying eligible first-party source files, follow the SP Boucher Source Header121Policy. Preserve existing copyright and license notices, select the correct language-specific122template, and avoid adding identifying information to anonymous academic submission artifacts.123124- Repository policy: `.spb-source-governance.toml` (project, contact, verified rights, license).125- Add or refresh headers with `spb-header apply --repo .`; verify with `spb-header check --repo .`.126- Never hand-write a header, never add one to generated, vendored, third-party or data files.127{CLAUDE_END}128"""129LEAK = re.compile(r"/Users/|/home/\w|\b(?:10|192\.168|172\.(?:1[6-9]|2\d|3[01]))\.\d+\.\d+|"130 r"\b[mM]\d[a-zA-Z]{1,2}\d{0,2}[a-z]?\.maclustr\.io|"131 r"-----BEGIN|sk-[A-Za-z0-9]{12,}|ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}")132133134# --------------------------------------------------------------------------- scanning135136def scan(repo: Path, policy: dict, cfg: dict, only: set[str] | None = None, want_new: bool = False,137 dates: dict | None = None):138 """Yield one record per tracked file. With want_new, includes the proposed bytes."""139 files = R.tracked(repo)140 listing = R.tex_listing_targets(repo, [p for _, p in files]) if any(p.endswith(".tex") for _, p in files) else set()141 max_bytes = cfg["exclusions"]["files"]["max_bytes"]142 anon = bool(listing is not None) and any(p.endswith(".tex") for _, p in files) \143 and R.has_anonymous_variant(repo, [p for _, p in files])144 for mode, path in files:145 if only is not None and path not in only:146 continue147 rec = {"path": path, "state": "excluded", "reason": "", "variant": "", "action": ""}148 if mode == "120000" or mode == "160000":149 rec["reason"] = "symlink-or-submodule"150 yield rec151 continue152 if path in (R.POLICY_FILE,):153 rec["reason"] = "governance-policy-file"154 yield rec155 continue156 fp = repo / path157 try:158 size = fp.stat().st_size159 except OSError:160 rec["reason"] = "missing-in-working-tree"161 yield rec162 continue163 if size > max_bytes:164 rec["reason"] = "large-file (data, model or generated artefact)"165 yield rec166 continue167 syn0, why = core.syntax_for(path, None, cfg)168 if syn0 is None:169 rec["reason"] = why170 yield rec171 continue172 ex = R.path_exclusion(path, syn0.role, cfg, policy)173 if not ex and syn0.role == "tex" and path.rsplit("/", 1)[-1] in listing:174 ex = "typeset-verbatim-by-another-file"175 if not ex and anon and syn0.role in ("tex", "bib"):176 ex = "anonymous-variant-shares-latex-sources (double-blind review: no identity in LaTeX sources)"177 if ex:178 rec["reason"] = ex179 yield rec180 continue181 data = fp.read_bytes()182 if syn0.style == "notebook":183 meta = {"project": policy["project"], "maintainer": cfg["identity"]["author"]["name"],184 "website": cfg["identity"]["author"]["website"], "contact": policy["contact"],185 "copyright": policy["copyright"]["oneline"], "license": policy["license"]["name"]}186 new, how = core.notebook_apply(data, meta)187 if new is None:188 rec.update(state="manual-review", reason=how)189 else:190 rec.update(state="compliant" if new == data else "eligible", action="notebook-metadata",191 variant="NOTEBOOK-METADATA")192 if want_new:193 rec.update(old=data, new=new, legacy="", sep=False)194 yield rec195 continue196 try:197 text = data.decode("utf-8")198 except UnicodeDecodeError:199 text = None200 syn, _ = core.syntax_for(path, text, cfg)201 plan, tx = core.analyze(path, data, cfg, syn)202 if plan.action == "skip":203 st = "manual-review" if plan.reason.startswith("manual-review") else (204 "third-party" if plan.reason.startswith("third-party") else "excluded")205 rec.update(state=st, reason=plan.reason)206 yield rec207 continue208 variant = R.choose_variant(path, syn, policy)209 values = R.header_values(path, policy, cfg, variant, (dates or {}).get(path))210 new = core.build(tx, plan, variant, values, cfg, syn)211 rec.update(variant=variant, action=plan.action, notes=plan.notes,212 state="compliant" if new == data else "eligible")213 if want_new:214 rec.update(old=data, new=new, legacy=plan.removed_legacy, sep=plan.sep, syn=syn)215 yield rec216217218# --------------------------------------------------------------------------- validation helpers219220def _run(cmd: list[str], cwd: Path | None = None, timeout: int = 300) -> tuple[int, str]:221 try:222 r = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=timeout)223 return r.returncode, (r.stderr or r.stdout).decode("utf-8", errors="replace")[:400]224 except (OSError, subprocess.TimeoutExpired) as e:225 return 127, str(e)226227228def _have(tool: str) -> bool:229 from shutil import which230 return which(tool) is not None231232233def syntax_check(repo: Path, path: str, old: bytes, new: bytes) -> tuple[str, str]:234 """('ok'|'fail'|'pre-existing'|'unchecked', detail). Compares against the baseline bytes."""235 ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""236 if ext in ("py", "pyi"):237 try:238 a = ast.dump(ast.parse(old))239 except (SyntaxError, ValueError):240 return "pre-existing", "baseline does not parse as Python 3"241 try:242 return ("ok", "AST identical") if ast.dump(ast.parse(new)) == a else ("fail", "Python AST changed")243 except (SyntaxError, ValueError) as e:244 return "fail", f"no longer parses: {e}"245 if ext == "toml":246 import tomllib247 try:248 a = tomllib.loads(old.decode())249 except Exception:250 return "pre-existing", "baseline TOML invalid"251 return ("ok", "TOML data identical") if tomllib.loads(new.decode()) == a else ("fail", "TOML data changed")252 if ext in ("yaml", "yml"):253 try:254 import yaml255 except ImportError:256 return "unchecked", "PyYAML not installed"257 try:258 a = list(yaml.safe_load_all(old.decode()))259 except Exception:260 return "pre-existing", "baseline YAML not loadable with safe_load"261 try:262 return ("ok", "YAML data identical") if list(yaml.safe_load_all(new.decode())) == a else ("fail", "YAML data changed")263 except Exception as e:264 return "fail", str(e)[:200]265 if ext == "ipynb":266 a, b = json.loads(old), json.loads(new)267 a.get("metadata", {}).pop(core.NB_KEY, None)268 b.get("metadata", {}).pop(core.NB_KEY, None)269 return ("ok", "cells, outputs and kernel metadata identical") if a == b else ("fail", "notebook content changed")270 tool = {"js": ["node", "--check"], "mjs": ["node", "--check"], "cjs": ["node", "--check"],271 "sh": ["bash", "-n"], "bash": ["bash", "-n"], "zsh": ["zsh", "-n"]}.get(ext)272 if tool and _have(tool[0]):273 fp = repo / path274 rc, err = _run(tool + [str(fp)])275 if rc == 0:276 return "ok", " ".join(tool)277 base = fp.with_name(f".spbbase-{os.getpid()}-{fp.name}")278 try:279 base.write_bytes(old)280 rc0, _ = _run(tool + [str(base)])281 finally:282 base.unlink(missing_ok=True)283 return ("pre-existing", "baseline fails the same check") if rc0 != 0 else ("fail", err)284 return "unchecked", "structural proof only"285286287def batch_swift(repo: Path, paths: list[str]) -> dict[str, tuple[str, str]]:288 out: dict[str, tuple[str, str]] = {}289 if not paths or not _have("swiftc"):290 return {p: ("unchecked", "swiftc unavailable") for p in paths}291 for k in range(0, len(paths), 150):292 chunk = paths[k:k + 150]293 rc, err = _run(["swiftc", "-frontend", "-parse"] + [str(repo / p) for p in chunk], timeout=600)294 if rc == 0:295 out.update({p: ("ok", "swiftc -parse") for p in chunk})296 continue297 for p in chunk: # isolate the failing file(s)298 rc1, e1 = _run(["swiftc", "-frontend", "-parse", str(repo / p)])299 if rc1 == 0:300 out[p] = ("ok", "swiftc -parse")301 else:302 with tempfile.TemporaryDirectory() as td:303 base = Path(td) / Path(p).name304 base.write_bytes(R.git_bytes(repo, "show", f"HEAD:{p}") or b"")305 rc0, _ = _run(["swiftc", "-frontend", "-parse", str(base)])306 out[p] = ("pre-existing", "baseline fails swiftc -parse too") if rc0 != 0 else ("fail", e1)307 return out308309310def batch_r(repo: Path, paths: list[str]) -> dict[str, tuple[str, str]]:311 if not paths or not _have("Rscript"):312 return {p: ("unchecked", "Rscript unavailable") for p in paths}313 with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:314 fh.write("\n".join(str(repo / p) for p in paths))315 code = ("fs <- readLines(commandArgs(TRUE)[1]); for (f in fs) { ok <- tryCatch({parse(f); TRUE}, "316 "error=function(e) FALSE); cat(if (ok) 'OK' else 'BAD', f, '\\n') }")317 r = subprocess.run(["Rscript", "-e", code, fh.name], capture_output=True)318 os.unlink(fh.name)319 res = {}320 for ln in r.stdout.decode(errors="replace").splitlines():321 st, _, f = ln.strip().partition(" ")322 rel = os.path.relpath(f.strip(), repo)323 res[rel] = ("ok", "R parse()") if st == "OK" else ("pre-existing", "R parse() fails (not re-tested on baseline)")324 return {p: res.get(p, ("unchecked", "no R result")) for p in paths}325326327# --------------------------------------------------------------------------- workspace helpers328329class WS:330 def __init__(self, root: Path):331 self.root = root332 for d in ("policies", "ledger", "reports", "reports/audit"):333 (root / d).mkdir(parents=True, exist_ok=True)334335 def repos(self, names: list[str] | None = None):336 for vis in ("public", "private"):337 base = self.root / "repos" / vis338 if not base.is_dir():339 continue340 for p in sorted(base.iterdir()):341 if (p / ".git").exists() and (not names or p.name in names):342 yield vis, p.name, p343344 def key(self, vis: str, slug: str) -> str:345 return slug if vis == "public" else f"private--{slug}"346347 def policy_path(self, vis, slug) -> Path:348 return self.root / "policies" / f"{self.key(vis, slug)}.toml"349350 def ledger_path(self, vis, slug) -> Path:351 return self.root / "ledger" / f"{self.key(vis, slug)}.json"352353354def registry_domains(path: str | None) -> dict:355 if not path or not Path(path).exists():356 return {}357 apps = json.loads(Path(path).read_text()).get("apps", {})358 out = {}359 for a in apps.values():360 dom, remote = (a.get("tunnel") or {}).get("domain") or a.get("domain"), a.get("git_remote", "")361 if dom and remote and a.get("status") == "online":362 out[Path(remote).name.removesuffix(".git")] = f"https://{dom}"363 return out364365366def default_branch(repo: Path) -> str:367 ref = R.git(repo, "symbolic-ref", "--short", "refs/remotes/origin/HEAD", check=False).strip()368 return ref.split("/", 1)[1] if "/" in ref else "main"369370371# --------------------------------------------------------------------------- commands372373def cmd_discover(ws: WS, args):374 rows = [{"slug": s, "visibility": v, "path": str(p.relative_to(ws.root))} for v, s, p in ws.repos()]375 (ws.root / "reports" / "discovery.json").write_text(json.dumps(rows, indent=1))376 print(f"{len(rows)} repositories in workspace "377 f"({sum(r['visibility'] == 'public' for r in rows)} public, {sum(r['visibility'] == 'private' for r in rows)} private)")378379380def cmd_classify(ws: WS, args):381 cfg, doms = core.load_config(), registry_domains(args.registry)382 n = 0383 for vis, slug, path in ws.repos(args.repos):384 pp = ws.policy_path(vis, slug)385 if pp.exists() and not args.force:386 continue387 base = default_branch(path)388 cur = R.git(path, "rev-parse", "--abbrev-ref", "HEAD", check=False).strip()389 if not cur:390 print(f"skip {slug}: no commit checked out (empty or incomplete clone)")391 continue392 if cur != base:393 print(f"skip {slug}: on branch {cur}, classify from {base}")394 continue395 pp.write_text(R.dump_toml(R.draft_policy(slug, path, vis, cfg, doms)), encoding="utf-8")396 n += 1397 print(f"{n} policies written to {ws.root / 'policies'}")398399400def _detect_stack(files: list[str]) -> tuple[str, str]:401 s = set(files)402 names = {f.rsplit("/", 1)[-1] for f in files}403 build = [b for b, mark in (("xcodegen", "project.yml"), ("swiftpm", "Package.swift"), ("npm", "package.json"),404 ("python", "pyproject.toml"), ("pip", "requirements.txt"), ("make", "Makefile"),405 ("latexmk", ".latexmkrc"), ("docker", "Dockerfile"), ("go", "go.mod"),406 ("gradle", "build.gradle.kts"), ("cargo", "Cargo.toml")) if mark in names]407 if any(f.endswith(".xcodeproj/project.pbxproj") for f in files):408 build.append("xcode")409 pm = [p for p, mark in (("pnpm", "pnpm-lock.yaml"), ("npm", "package-lock.json"), ("yarn", "yarn.lock"),410 ("uv", "uv.lock"), ("poetry", "poetry.lock"), ("swiftpm", "Package.resolved")) if mark in names]411 return ",".join(build), ",".join(pm)412413414def cmd_audit(ws: WS, args):415 """File-level audit of every repository (read-only). Feeds inventory, report and status."""416 cfg = core.load_config()417 for vis, slug, path in ws.repos(args.repos):418 pp = ws.policy_path(vis, slug)419 if not pp.exists():420 print(f"no policy for {slug}; run classify")421 continue422 policy = R.load_policy(pp)423 files = [p for _, p in R.tracked(path)]424 states, reasons, variants, langs = collections.Counter(), collections.Counter(), collections.Counter(), collections.Counter()425 review_items = []426 for rec in scan(path, policy, cfg):427 states[rec["state"]] += 1428 if rec["state"] in ("eligible", "compliant"):429 variants[rec["variant"]] += 1430 langs[rec["path"].rsplit(".", 1)[-1].lower() if "." in rec["path"].rsplit("/", 1)[-1] else rec["path"].rsplit("/", 1)[-1]] += 1431 else:432 reasons[rec["reason"].split(":")[0] if rec["state"] == "excluded" else rec["reason"]] += 1433 if rec["state"] in ("manual-review", "third-party"):434 review_items.append({"path": rec["path"], "state": rec["state"], "reason": rec["reason"]})435 build, pm = _detect_stack(files)436 out = {437 "slug": slug, "visibility": vis, "category": policy["category"], "status": policy["status"],438 "branch": R.git(path, "rev-parse", "--abbrev-ref", "HEAD").strip(),439 "commit": R.git(path, "rev-parse", "HEAD").strip(),440 "dirty": bool(R.git(path, "status", "--porcelain").strip()),441 "files_tracked": len(files), "states": dict(states), "exclusion_reasons": dict(reasons),442 "variants": dict(variants), "languages": dict(langs.most_common()), "build_system": build,443 "package_manager": pm, "license": policy["license"], "copyright": policy["copyright"],444 "review": policy.get("review", []), "file_review_items": review_items,445 }446 (ws.root / "reports" / "audit" / f"{ws.key(vis, slug)}.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))447 print(f"{slug:34s} {policy['status']:9s} eligible={states['eligible']:5d} compliant={states['compliant']:5d} "448 f"excluded={states['excluded']:6d} third-party={states['third-party']:3d} review={states['manual-review']:3d}")449450451def _repo_and_policy(args, ws: WS | None):452 cfg = core.load_config()453 if getattr(args, "repo", None):454 path = Path(args.repo).resolve()455 return cfg, [("local", path.name, path, R.load_policy(path / R.POLICY_FILE))]456 out = []457 for vis, slug, path in ws.repos(args.repos):458 pp = ws.policy_path(vis, slug)459 if pp.exists():460 out.append((vis, slug, path, R.load_policy(pp)))461 return cfg, out462463464def cmd_preview(ws, args):465 cfg, targets = _repo_and_policy(args, ws)466 for vis, slug, path, policy in targets:467 dates = R.file_dates(path)468 shown = 0469 for rec in scan(path, policy, cfg, want_new=True, dates=dates):470 if rec["state"] != "eligible":471 continue472 if args.path and not any(rec["path"].endswith(p) for p in args.path):473 continue474 old = rec["old"].decode("utf-8", "replace").splitlines(keepends=True)475 new = rec["new"].decode("utf-8", "replace").splitlines(keepends=True)476 sys.stdout.writelines(difflib.unified_diff(old, new, "a/" + rec["path"], "b/" + rec["path"], n=2))477 shown += 1478 if shown >= args.limit:479 break480 print(f"# {slug}: previewed {shown} file(s); nothing was modified")481482483def _apply_repo(vis: str, slug: str, path: Path, policy: dict, cfg: dict, args, ws: WS | None) -> dict:484 led = {"slug": slug, "visibility": vis, "engine": core.ENGINE_VERSION, "started": dt.datetime.now().isoformat(timespec="seconds"),485 "status": "", "files": [], "validation": {}}486 if policy["status"] != "in-scope" and not args.force:487 led["status"] = f"not-migrated: policy status is '{policy['status']}'"488 return led489 in_place = bool(getattr(args, "repo", None))490 if R.git(path, "status", "--porcelain").strip() and not in_place:491 led["status"] = "blocked: working tree not clean (nothing stashed, nothing changed)"492 return led493 cur = R.git(path, "rev-parse", "--abbrev-ref", "HEAD", check=False).strip()494 if not in_place:495 base = default_branch(path)496 if cur == base:497 R.git(path, "checkout", "-q", "-b", R.BRANCH) if not R.git(path, "branch", "--list", R.BRANCH).strip() \498 else R.git(path, "checkout", "-q", R.BRANCH)499 elif cur != R.BRANCH:500 led["status"] = f"blocked: unexpected branch {cur}"501 return led502 led["base_branch"] = base503 led["baseline_commit"] = R.git(path, "rev-parse", base).strip()504 led["branch"] = R.git(path, "rev-parse", "--abbrev-ref", "HEAD", check=False).strip()505 dates = R.file_dates(path)506 swift, rfiles, counts = [], [], collections.Counter()507 only = set(args.files) if getattr(args, "files", None) else None508 for rec in scan(path, policy, cfg, only=only, want_new=True, dates=dates):509 counts[rec["state"]] += 1510 if rec["state"] != "eligible":511 continue512 p, old, new = rec["path"], rec["old"], rec["new"]513 entry = {"path": p, "variant": rec["variant"], "action": rec["action"], "sha_before": core.sha(old),514 "sha_after": core.sha(new), "legacy": rec["legacy"], "sep": rec["sep"], "notes": rec.get("notes", [])}515 # structural proof: removing the header (and restoring a replaced legacy block) gives the baseline back516 if rec["variant"] != "NOTEBOOK-METADATA" and rec["action"] == "insert":517 back = core.strip_header(new, p, cfg, rec["syn"], rec["legacy"], rec["sep"])518 if back != old:519 entry["result"] = "refused: splice is not reversible"520 led["files"].append(entry)521 continue522 head = new[:6000].decode("utf-8", "replace").split(core.MARK_END)[0]523 if LEAK.search(head.replace(p, "")):524 entry["result"] = "refused: header would disclose a path, host or secret-like value"525 led["files"].append(entry)526 continue527 (path / p).write_bytes(new)528 if p.endswith(".swift"):529 swift.append(p)530 entry["check"] = ["pending", ""]531 elif p.lower().endswith(".r"):532 rfiles.append(p)533 entry["check"] = ["pending", ""]534 else:535 entry["check"] = list(syntax_check(path, p, old, new))536 entry["result"] = "written"537 led["files"].append(entry)538 extra = {**batch_swift(path, swift), **batch_r(path, rfiles)}539 for e in led["files"]:540 if e["path"] in extra:541 e["check"] = list(extra[e["path"]])542 for e in led["files"]: # a failed check restores that file exactly543 if e.get("check", [""])[0] == "fail":544 R.git(path, "checkout", "--", e["path"])545 e["result"] = "reverted: validation failed"546 written = [e for e in led["files"] if e["result"] == "written"]547 # repository-level metadata and agent instructions548 if not in_place:549 (path / R.POLICY_FILE).write_text(R.dump_toml(R.repo_policy_view(policy)), encoding="utf-8")550 if not args.no_claude_md and not in_place:551 cm = path / "CLAUDE.md"552 text = cm.read_text(encoding="utf-8") if cm.exists() else ""553 if CLAUDE_START not in text:554 cm.write_text((text.rstrip("\n") + "\n\n" if text.strip() else "") + CLAUDE_SECTION, encoding="utf-8")555 # idempotency: a second pass must propose nothing556 again = [r["path"] for r in scan(path, policy, cfg, only=only, dates=dates) if r["state"] == "eligible"]557 reverted = {e["path"] for e in led["files"] if e["result"] != "written"}558 led["validation"] = {559 "idempotent": not [p for p in again if p not in reverted],560 "checks": dict(collections.Counter(e.get("check", ["none"])[0] for e in written)),561 "refused_or_reverted": len(led["files"]) - len(written),562 "counts_before": dict(counts),563 }564 changed = R.git(path, "status", "--porcelain").strip()565 if not in_place and changed and not args.no_commit:566 R.git(path, "add", "-A")567 msg = COMMIT_MSG.format(v=core.ENGINE_VERSION) + "\nCo-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>\n"568 R.git(path, "commit", "-q", "-m", msg)569 led["commit"] = R.git(path, "rev-parse", "HEAD").strip()570 stat = R.git(path, "diff", "--numstat", f"{led['baseline_commit']}..HEAD")571 dels = sum(int(x.split("\t")[1]) for x in stat.splitlines() if x.split("\t")[1].isdigit())572 legacy_lines = sum(e["legacy"].count("\n") for e in written)573 led["validation"]["deleted_lines"] = dels574 led["validation"]["deleted_lines_explained_by_legacy_blocks"] = legacy_lines575 led["validation"]["insertion_only"] = dels <= legacy_lines + 0576 ok = led["validation"]["idempotent"] and not led["validation"]["refused_or_reverted"] \577 and led["validation"].get("insertion_only", True)578 led["status"] = "migrated-validated" if ok else "migrated-with-findings"579 led["finished"] = dt.datetime.now().isoformat(timespec="seconds")580 return led581582583def cmd_apply(ws, args):584 cfg, targets = _repo_and_policy(args, ws)585 for vis, slug, path, policy in targets:586 try:587 led = _apply_repo(vis, slug, path, policy, cfg, args, ws)588 except Exception as e: # never hide a failure589 led = {"slug": slug, "visibility": vis, "status": f"error: {e}", "files": [], "validation": {}}590 if ws:591 lp = ws.ledger_path(vis, slug)592 prev = json.loads(lp.read_text()) if lp.exists() else {}593 if prev.get("commit") and led["status"].startswith("migrated"):594 # second pass on an already migrated branch: the first record of each file stays the595 # reference for rollback (hash before, replaced legacy block, separator)596 old = {e["path"]: e for e in prev["files"]}597 for e in led["files"]:598 if e["path"] in old and old[e["path"]].get("result") == "written":599 for k in ("sha_before", "legacy", "sep"):600 e[k] = old[e["path"]][k]601 seen = {e["path"] for e in led["files"]}602 led["files"] += [e for e in prev["files"] if e["path"] not in seen]603 led.setdefault("commit", prev["commit"])604 led["previous_commits"] = prev.get("previous_commits", []) + ([prev["commit"]] if led["commit"] != prev["commit"] else [])605 if led["status"].startswith(("migrated", "error")) or not lp.exists():606 lp.write_text(json.dumps(led, indent=1, ensure_ascii=False))607 sys.stdout.flush()608 v = led.get("validation", {})609 print(f"{slug:34s} {led['status'][:60]:60s} files={sum(e['result'] == 'written' for e in led['files']):5d} "610 f"checks={v.get('checks', {})}")611612613def cmd_validate(ws, args):614 """Re-prove, from git alone, that the migration commit is comment-only."""615 cfg, targets = _repo_and_policy(args, ws)616 bad = 0617 for vis, slug, path, policy in targets:618 lp = ws.ledger_path(vis, slug)619 if not lp.exists():620 continue621 led = json.loads(lp.read_text())622 if "commit" not in led:623 continue624 base, problems, n = led["baseline_commit"], [], 0625 legacy = {e["path"]: e for e in led["files"]}626 names = R.git(path, "diff", "--name-status", "--no-renames", f"{base}..{led['commit']}").splitlines()627 for ln in names:628 st, p = ln.split("\t", 1)629 if p in (R.POLICY_FILE, "CLAUDE.md"):630 continue631 n += 1632 if st != "M":633 problems.append(f"{p}: unexpected change type {st}")634 continue635 old = R.git_bytes(path, "show", f"{base}:{p}")636 new = R.git_bytes(path, "show", f"{led['commit']}:{p}")637 e = legacy.get(p, {})638 if p.endswith(".ipynb"):639 ok = syntax_check(path, p, old, new)[0] == "ok"640 else:641 text = None642 try:643 text = new.decode("utf-8")644 except UnicodeDecodeError:645 pass646 syn, _ = core.syntax_for(p, text, cfg)647 ok = syn is not None and core.strip_header(new, p, cfg, syn, e.get("legacy", ""), e.get("sep", True)) == old648 if not ok:649 problems.append(f"{p}: content differs from baseline beyond the header")650 led["validation"]["reproved_files"] = n651 led["validation"]["reproof_problems"] = problems652 led["validation"]["reproved"] = not problems653 if problems:654 bad += 1655 led["status"] = "migrated-with-findings"656 lp.write_text(json.dumps(led, indent=1, ensure_ascii=False))657 print(f"{slug:34s} files={n:5d} {'comment-only: PROVED' if not problems else 'PROBLEMS: ' + '; '.join(problems[:3])}")658 return 1 if bad else 0659660661def cmd_rollback(ws, args):662 """Remove headers file by file (keeps any later, unrelated edits). `git revert` is the other route."""663 cfg, targets = _repo_and_policy(args, ws)664 for vis, slug, path, policy in targets:665 led = {}666 if ws and ws.ledger_path(vis, slug).exists():667 led = {e["path"]: e for e in json.loads(ws.ledger_path(vis, slug).read_text())["files"]}668 n = 0669 for mode, p in R.tracked(path):670 if mode in ("120000", "160000"):671 continue672 fp = path / p673 if not fp.is_file() or fp.stat().st_size > cfg["exclusions"]["files"]["max_bytes"]:674 continue675 data = fp.read_bytes()676 if p.endswith(".ipynb"):677 if b'"%s"' % core.NB_KEY.encode() in data and p in led:678 nb = json.loads(data)679 nb.get("metadata", {}).pop(core.NB_KEY, None)680 for indent in (1, 2, 4, None):681 cand = (json.dumps(nb, indent=indent, ensure_ascii=False) + "\n").encode()682 if core.sha(cand) == led[p]["sha_before"] or core.sha(cand.rstrip(b"\n")) == led[p]["sha_before"]:683 if not args.dry_run:684 fp.write_bytes(cand if core.sha(cand) == led[p]["sha_before"] else cand.rstrip(b"\n"))685 n += 1686 break687 continue688 if core.MARK_END.encode() not in data[:20000]:689 continue690 try:691 text = data.decode("utf-8")692 except UnicodeDecodeError:693 continue694 syn, _ = core.syntax_for(p, text, cfg)695 if syn is None or syn.style == "notebook":696 continue697 e = led.get(p, {})698 back = core.strip_header(data, p, cfg, syn, e.get("legacy", ""), e.get("sep", True))699 if back is not None and back != data:700 if not args.dry_run:701 fp.write_bytes(back)702 n += 1703 print(f"{slug}: {'would remove' if args.dry_run else 'removed'} headers from {n} file(s); "704 f"{R.POLICY_FILE} and the CLAUDE.md section are left for `git revert` or manual removal")705706707def cmd_check(ws, args):708 """Hook / CI entry point: verify files of one repository against its policy. Modifies nothing."""709 cfg = core.load_config()710 path = Path(args.repo or ".").resolve()711 if not (path / R.POLICY_FILE).exists():712 print(f"spb-header: {R.POLICY_FILE} not found; repository not onboarded (see ONBOARDING.md)")713 return 0 if args.staged else 2714 policy = R.load_policy(path / R.POLICY_FILE)715 only = None716 if args.staged:717 only = set(R.git(path, "diff", "--cached", "--name-only", "--diff-filter=ACM").splitlines())718 elif args.files:719 only = set(args.files)720 problems = []721 for rec in scan(path, policy, cfg, only=only, want_new=True):722 p = rec["path"]723 if rec["state"] == "eligible":724 problems.append(f"{p}: {'header missing' if rec['action'] == 'insert' else 'header out of date'} "725 f"({rec['variant']}) — run: spb-header apply --repo . --files {p}")726 if rec["state"] in ("eligible", "compliant") and rec.get("old"):727 text = rec["old"].decode("utf-8", "replace")728 if text.count(core.MARK_END) > 1 and not p.startswith(("spbheader/", "tests/")):729 problems.append(f"{p}: duplicate SP Boucher header")730 head = text[:6000].split(core.MARK_END)[0]731 if core.MARK_TITLE.search(head) and LEAK.search(head.replace(p, "")):732 problems.append(f"{p}: header contains a local path, private host or secret-like value")733 for pr in problems:734 print("spb-header:", pr)735 print(f"spb-header: {len(problems)} problem(s)")736 return 1 if problems else 0737738739def cmd_report(ws, args):740 audits = [json.loads(p.read_text()) for p in sorted((ws.root / "reports" / "audit").glob("*.json"))]741 ledgers = {}742 for p in (ws.root / "ledger").glob("*.json"):743 d = json.loads(p.read_text())744 ledgers[p.stem] = d745 rows = []746 for a in audits:747 key = ws.key(a["visibility"], a["slug"])748 led = ledgers.get(key, {})749 st, v = a["states"], led.get("validation", {})750 applicable = st.get("eligible", 0) + st.get("compliant", 0)751 written = sum(e["result"] == "written" for e in led.get("files", []))752 rows.append({753 "repository": a["slug"], "visibility": a["visibility"], "category": a["category"], "scope": a["status"],754 "baseline_commit": led.get("baseline_commit", a["commit"])[:12], "migration_commit": led.get("commit", "")[:12],755 "migration_status": led.get("status", "not-started"), "files_tracked": a["files_tracked"],756 "eligible_files": applicable, "modified_files": written,757 "compliant_files": written + (st.get("compliant", 0) if not led.get("commit") else 0),758 "excluded_files": st.get("excluded", 0), "third_party_files": st.get("third-party", 0),759 "manual_review_files": st.get("manual-review", 0),760 "license": a["license"]["name"], "spdx": a["license"].get("spdx", ""), "license_file": a["license"].get("file", ""),761 "copyright_holder": a["copyright"]["holder"], "copyright_basis": a["copyright"].get("basis", ""),762 "checks": json.dumps(v.get("checks", {})), "comment_only_proved": v.get("reproved", ""),763 "idempotent": v.get("idempotent", ""), "build_system": a["build_system"],764 "languages": ",".join(list(a["languages"])[:6]), "review_notes": " | ".join(a["review"]),765 })766 rep = ws.root / "reports"767 (rep / "inventory.json").write_text(json.dumps(rows, indent=1, ensure_ascii=False))768 with open(rep / "inventory.csv", "w", newline="", encoding="utf-8") as fh:769 w = csv.DictWriter(fh, fieldnames=list(rows[0]))770 w.writeheader()771 w.writerows(rows)772 T = lambda k: sum(r[k] for r in rows)773 scope = collections.Counter(r["scope"] for r in rows)774 mig = collections.Counter(r["migration_status"].split(":")[0] for r in rows)775 in_scope = [r for r in rows if r["scope"] == "in-scope"]776 elig_in, mod_in = sum(r["eligible_files"] for r in in_scope), sum(r["modified_files"] for r in in_scope)777 summary = {778 "generated": dt.datetime.now().isoformat(timespec="seconds"), "engine": core.ENGINE_VERSION,779 "repositories_discovered": len(rows), "repositories_in_scope": scope["in-scope"],780 "repositories_requiring_review": scope["review"], "repositories_deferred": scope["deferred"],781 "repositories_audited": len(rows), "repositories_migrated": mig["migrated-validated"] + mig["migrated-with-findings"],782 "repositories_validated": sum(1 for r in rows if r["migration_status"] == "migrated-validated" and r["comment_only_proved"] is True),783 "repositories_with_findings": mig["migrated-with-findings"],784 "files_scanned": T("files_tracked"), "eligible_files_all_repositories": T("eligible_files"),785 "eligible_files_in_scope": elig_in, "modified_files": T("modified_files"),786 "header_compliance_in_scope": round(mod_in / elig_in, 4) if elig_in else None,787 "excluded_files": T("excluded_files"), "third_party_files": T("third_party_files"),788 "manual_review_files": T("manual_review_files"),789 "repositories_without_license_file": sum(1 for r in rows if not r["license_file"]),790 "migration_status": dict(mig), "scope": dict(scope),791 "by_category": {c: {"repositories": sum(1 for r in rows if r["category"] == c),792 "eligible": sum(r["eligible_files"] for r in rows if r["category"] == c),793 "modified": sum(r["modified_files"] for r in rows if r["category"] == c)}794 for c in sorted({r["category"] for r in rows})},795 }796 (rep / "summary.json").write_text(json.dumps(summary, indent=1, ensure_ascii=False))797 md = ["# SP Boucher source governance — ecosystem status", "",798 f"Generated {summary['generated']} by spb-header {core.ENGINE_VERSION}.", "",799 "| Metric | Value |", "|---|---|"]800 md += [f"| {k.replace('_', ' ')} | {v} |" for k, v in summary.items() if not isinstance(v, dict)]801 md += ["", "Header compliance = files carrying a validated header ÷ eligible first-party files, in-scope repositories only.",802 "Excluded, third-party and manual-review files are not in the denominator.", "",803 "## By category", "", "| Category | Repositories | Eligible files | Files with header |", "|---|---|---|---|"]804 md += [f"| {c} | {d['repositories']} | {d['eligible']} | {d['modified']} |" for c, d in summary["by_category"].items()]805 md += ["", "## Repositories", "",806 "| Repository | Vis. | Category | Scope | Migration | Eligible | Modified | Review files | License | Proved |",807 "|---|---|---|---|---|---|---|---|---|---|"]808 md += [f"| {r['repository']} | {r['visibility'][:3]} | {r['category']} | {r['scope']} | {r['migration_status'][:38]} | "809 f"{r['eligible_files']} | {r['modified_files']} | {r['manual_review_files'] + r['third_party_files']} | "810 f"{r['spdx'] or ('file' if r['license_file'] else 'none')} | {r['comment_only_proved']} |" for r in rows]811 (rep / "STATUS.md").write_text("\n".join(md) + "\n", encoding="utf-8")812 print(json.dumps({k: v for k, v in summary.items() if not isinstance(v, dict)}, indent=1))813814815def cmd_status(ws, args):816 p = ws.root / "reports" / "summary.json"817 if not p.exists():818 print("no report yet: run `spb-header report`")819 return 1820 s = json.loads(p.read_text())821 for k, v in s.items():822 if not isinstance(v, dict):823 print(f"{k.replace('_', ' '):42s} {v}")824 print("migration status:", s["migration_status"])825826827def main(argv=None) -> int:828 ap = argparse.ArgumentParser(prog="spb-header", description="SP Boucher source header governance")829 ap.add_argument("-w", "--workspace", default=os.environ.get("SPB_GOVERNANCE_WORKSPACE"))830 sub = ap.add_subparsers(dest="cmd", required=True)831832 def add(name, fn, **kw):833 p = sub.add_parser(name, **kw)834 p.set_defaults(fn=fn)835 p.add_argument("repos", nargs="*", help="repository slugs (default: all)")836 return p837 add("discover", cmd_discover, help="list repositories of the workspace")838 p = add("classify", cmd_classify, help="draft a policy per repository from verifiable facts")839 p.add_argument("--force", action="store_true")840 p.add_argument("--registry", help="mld registry JSON (verified project URLs)")841 add("audit", cmd_audit, help="read-only file-level audit")842 add("inventory", cmd_report, help="write the machine-readable inventory (same as report)")843 p = add("preview", cmd_preview, help="show proposed changes; modifies nothing")844 p.add_argument("--repo")845 p.add_argument("--path", action="append")846 p.add_argument("--limit", type=int, default=3)847 p = add("apply", cmd_apply, help="apply headers on a dedicated branch and validate")848 p.add_argument("--repo", help="repository mode: apply in place, no branch, no commit")849 p.add_argument("--force", action="store_true", help="apply even if the policy status is not in-scope")850 p.add_argument("--no-commit", action="store_true")851 p.add_argument("--no-claude-md", action="store_true")852 p.add_argument("--files", nargs="*", help="limit to these paths (repository mode)")853 add("validate", cmd_validate, help="re-prove from git that migration commits are comment-only")854 p = add("rollback", cmd_rollback, help="remove headers file by file")855 p.add_argument("--repo")856 p.add_argument("--dry-run", action="store_true")857 p = add("check", cmd_check, help="hook / CI check of one repository")858 p.add_argument("--repo")859 p.add_argument("--staged", action="store_true")860 p.add_argument("--files", nargs="*")861 add("report", cmd_report, help="write Markdown / JSON / CSV reports")862 add("status", cmd_status, help="ecosystem compliance summary")863 args = ap.parse_args(argv)864 needs_ws = not (getattr(args, "repo", None) or args.cmd == "check")865 ws = None866 if args.workspace:867 ws = WS(Path(args.workspace).expanduser().resolve())868 elif needs_ws:869 ap.error("workspace required: -w DIR or SPB_GOVERNANCE_WORKSPACE (or use --repo)")870 return args.fn(ws, args) or 0871872873if __name__ == "__main__":874 sys.exit(main())875