Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SP Boucher Development Standard7# File : payload/standards/lib/spstd/hooks.py8# Module : Engine9# Repository : https://git.spboucher.ai/sp-development-standard10# Project Website : https://git.spboucher.ai/sp-development-standard11# Created : 2026-12-0212# Last Modified : 2026-12-0213#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Claude Code hook dispatcher of the SP Boucher development standard.4243Usage: python3 -m spstd.hooks <session-start|pre-tool-use|post-tool-use|subagent-stop|stop> (hook JSON on stdin)4445Design rules: never raise, never hang (the settings carry a timeout too), stay silent when there is nothing to say,46never loop (stop_hook_active), never write outside the file Claude just edited."""47import json48import os49import re50import shlex51import sys52import time5354from . import common as C5556AUTH_TOKEN = "SP_AUTHORIZED=1" # sp-allow-secret (a flag name, not a credential)575859def emit(obj):60 sys.stdout.write(json.dumps(obj, ensure_ascii=False))61 sys.stdout.flush()626364def context(event, text):65 emit({"hookSpecificOutput": {"hookEventName": event, "additionalContext": text}})666768# ----------------------------------------------------------------------------- session state69def state_path(session):70 return os.path.join(C.STATE_DIR, re.sub(r"[^A-Za-z0-9_.-]", "_", session or "nosession") + ".json")717273def load_state(session):74 try:75 with open(state_path(session), encoding="utf-8") as f:76 return json.load(f)77 except (OSError, ValueError):78 return {"touched": [], "notified": []}798081def save_state(session, st):82 try:83 os.makedirs(C.STATE_DIR, exist_ok=True)84 tmp = state_path(session) + ".%d.tmp" % os.getpid()85 with open(tmp, "w", encoding="utf-8") as f:86 json.dump(st, f)87 os.replace(tmp, state_path(session))88 except OSError:89 pass909192def prune_state():93 try:94 now = time.time()95 for n in os.listdir(C.STATE_DIR):96 p = os.path.join(C.STATE_DIR, n)97 if now - os.path.getmtime(p) > 14 * 86400:98 os.remove(p)99 except OSError:100 pass101102103# ----------------------------------------------------------------------------- SessionStart104def session_start(inp):105 cwd = inp.get("cwd") or os.getcwd()106 prune_state()107 lines = ["SP BOUCHER GLOBAL DEVELOPMENT STANDARD v%s is active (policy: ~/.claude/CLAUDE.md; details: ~/.claude/standards/)." % C.version(),108 "Tools: sp-header (source headers), sp-git (init/commit/push/verify/release on SPB Git), sp-security-scan, sp-dev-doctor "109 "— in ~/.claude/bin. Skills: sp-source-header, sp-git-governance, sp-development-standard.",110 "Cycle: implement → headers → review diff → tests → secret scan → Conventional Commit (English) → push to SPB Git → verify. "111 "Commit and push each finished step; never force-push; never attribute third-party code to Simon-Pierre Boucher."]112 root = C.git_root(cwd)113 if root and not C.in_ignored_root(root):114 o = C.origin_info(root)115 own, why = C.ownership(root)116 dirty = len(C.porcelain(root))117 br = C.git_out(["symbolic-ref", "--short", "-q", "HEAD"], root, 10)118 desc = "Repository %s — branch %s — origin %s — ownership %s (%s) — %d uncommitted file(s)" % (119 os.path.basename(root), br or "detached", o["raw"] or "NONE", own, why, dirty)120 if o["kind"] != "none":121 from . import secscan122 n = C.git_out(["rev-list", "--count"] + secscan.unpushed_range(root), root, 15)123 if n.isdigit() and int(n):124 desc += " — %s unpushed commit(s)" % n125 lines.append(desc + ".")126 behind = C.git_out(["rev-list", "--count", "HEAD..@{u}"], root, 10)127 if behind.isdigit() and int(behind):128 lines.append("This checkout is %s commit(s) BEHIND its upstream (as of the last fetch): pull before editing, "129 "otherwise header and content conflicts are likely." % behind)130 if dirty:131 lines.append("Uncommitted changes predate this session: commit them separately (or report them) rather than mixing them with new work.")132 if o["kind"] == "none" and own != "restricted":133 lines.append("No remote: an eligible SP Boucher project is published with `sp-git init` (public by default; --private or "134 "--no-remote for confidential, research-protected or third-party material).")135 if own in ("foreign", "restricted"):136 lines.append("Headers and publication are NOT automatic here: %s." % why)137 else:138 pr = None if C.in_ignored_root(cwd) else C.project_root(cwd)139 if pr:140 lines.append("Project directory %s is not under git: an eligible SP Boucher project starts with `sp-git init`." % os.path.basename(pr))141 missing = [t for t in ("sp-header", "sp-git", "sp-security-scan", "sp-dev-doctor")142 if not os.path.exists(os.path.join(C.HOME, ".claude", "bin", t))]143 if missing:144 lines.append("WARNING: missing tools %s — run the installer of sp-development-standard." % ", ".join(missing))145 context("SessionStart", "\n".join(lines))146147148# ----------------------------------------------------------------------------- PreToolUse (Bash)149def split_segments(cmd):150 try:151 lex = shlex.shlex(cmd, posix=True, punctuation_chars=True)152 lex.whitespace_split = True153 toks = list(lex)154 except ValueError:155 toks = cmd.split()156 segs, cur = [], []157 for t in toks:158 if t and set(t) <= set(";&|()"):159 if cur:160 segs.append(cur)161 cur = []162 else:163 cur.append(t)164 if cur:165 segs.append(cur)166 return segs167168169def git_calls(cmd, cwd, depth=0):170 """Yield (directory, subcommand, args) for each git invocation found in a shell command line."""171 here = cwd172 for seg in split_segments(cmd.replace("\\\n", " ").replace("\n", " ; ")):173 if seg and seg[0] == "cd" and len(seg) > 1:174 here = os.path.normpath(os.path.join(here, os.path.expanduser(seg[1]))) if here else None175 continue176 if depth == 0 and seg and os.path.basename(seg[0]) in ("ssh", "bash", "sh", "zsh") and len(seg) > 1:177 inner = seg[-1]178 if " " in inner and "git" in inner:179 for call in git_calls(inner, None, depth + 1):180 yield call181 continue182 for i, t in enumerate(seg):183 if t == "git" or t.endswith("/git"):184 if i > 0 and not (re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", seg[i - 1]) or seg[i - 1] in ("sudo", "command", "exec", "time", "then", "do", "xargs", "env", "nohup")):185 continue186 d, j = here, i + 1187 while j < len(seg):188 if seg[j] == "-C" and j + 1 < len(seg):189 d = os.path.normpath(os.path.join(d or "/", os.path.expanduser(seg[j + 1]))) if d else None190 j += 2191 elif seg[j] == "-c" and j + 1 < len(seg):192 j += 2193 elif seg[j].startswith("-"):194 j += 1195 else:196 break197 if j < len(seg):198 yield d, seg[j], seg[j + 1:]199 break200201202def destructive_reason(d, sub, args):203 flags = [a for a in args if a.startswith("-")]204 pos = [a for a in args if not a.startswith("-")]205 if sub == "push":206 if any(f in ("--force", "--mirror", "--delete", "--prune") or f.startswith("--force-with-lease") or f.startswith("--force-if-includes")207 or (re.match(r"^-[A-Za-z]+$", f) and ("f" in f or "d" in f)) for f in flags):208 return "force push / remote deletion (`git push %s`)" % " ".join(flags)209 if any(p.startswith("+") or (p.startswith(":") and len(p) > 1) for p in pos[1:]):210 return "forced or deleting refspec in `git push`"211 if sub in ("filter-branch", "filter-repo"):212 return "history rewriting (`git %s`)" % sub213 if sub == "remote" and pos and pos[0] in ("set-url", "remove", "rm", "rename") and d and os.path.isdir(d):214 if C.git_out(["remote", "get-url", "origin"], d, 10) and (len(pos) < 2 or pos[1] == "origin"):215 return "changing or removing the existing origin remote"216 if sub == "reset" and "--hard" in flags and d and os.path.isdir(d):217 if C.git_out(["status", "--porcelain", "--untracked-files=no"], d, 15):218 return "`git reset --hard` with uncommitted changes in the working tree"219 if sub == "clean" and any(re.match(r"^-[A-Za-z]*f", f) for f in flags) and not any("n" in f for f in flags if re.match(r"^-[A-Za-z]+$", f)) \220 and "--dry-run" not in flags and d and os.path.isdir(d):221 if C.git_out(["ls-files", "-o", "--exclude-standard"], d, 15):222 return "`git clean -f` would delete untracked files"223 if sub == "update-ref" and "-d" in flags:224 return "deleting a ref (`git update-ref -d`)"225 return ""226227228def pre_tool_use(inp):229 if inp.get("tool_name") != "Bash":230 return231 cmd = (inp.get("tool_input") or {}).get("command") or ""232 if "git" not in cmd and "srv/git" not in cmd:233 return234 cwd = inp.get("cwd") or os.getcwd()235 authorized = AUTH_TOKEN in cmd236237 def deny(reason):238 emit({"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": reason}})239240 if not authorized and re.search(r"\brm\s+(-[A-Za-z]+\s+)+[^|;&]*srv/git(-private)?/[\w.-]+", cmd):241 return deny("SP Boucher standard §18: deleting a repository of SPB Git needs Simon-Pierre Boucher's explicit authorization. "242 "If he gave it in this conversation, re-run the command prefixed with %s." % AUTH_TOKEN)243 from . import secscan244 scanned = set()245 for d, sub, args in git_calls(cmd, cwd):246 if not authorized:247 why = destructive_reason(d, sub, args)248 if why:249 return deny("SP Boucher standard §18 (repository integrity): %s is forbidden without Simon-Pierre Boucher's explicit "250 "authorization. Prefer a non-destructive path (new commit, revert, dedicated branch, `sp-git sync`). If he "251 "explicitly authorized it in this conversation, re-run prefixed with %s." % (why, AUTH_TOKEN))252 if sub in ("commit", "push") and d and os.path.isdir(d):253 root = C.git_root(d)254 if not root or (root, sub) in scanned or C.in_ignored_root(root):255 continue256 scanned.add((root, sub))257 if sub == "push" and C.ownership(root)[0] == "foreign":258 continue259 findings, _ = secscan.scan(root, "changes" if sub == "commit" else "unpushed")260 hi = secscan.high(findings)261 if hi:262 return deny("SP Boucher standard §17: secret scan blocked this `git %s` in %s — %d high-severity finding(s):\n%s\n"263 "Remove the secret from the change (rotate it if it was already committed) and make sure the file is "264 "git-ignored. Verified false positive: append `%s` to the line, or add `rule:<id>` / `path:<glob>` to "265 ".sp-security-allow. This control must not be bypassed to make a push succeed."266 % (sub, os.path.basename(root), len(hi), secscan.format_findings(hi, 8), secscan.ALLOW_MARK))267268269# ----------------------------------------------------------------------------- PostToolUse (Write / Edit / MultiEdit)270def post_tool_use(inp):271 tool = inp.get("tool_name") or ""272 ti = inp.get("tool_input") or {}273 path = ti.get("file_path") or ti.get("notebook_path")274 if tool not in ("Write", "Edit", "MultiEdit", "NotebookEdit") or not path:275 return276 path = os.path.abspath(os.path.join(inp.get("cwd") or os.getcwd(), os.path.expanduser(path)))277 if not os.path.isfile(path) or C.in_ignored_root(path):278 return279 session = inp.get("session_id") or ""280 st = load_state(session)281 if path not in st["touched"]:282 st["touched"].append(path)283 st["touched"] = st["touched"][-800:]284 notes = []285 from . import header as H286 from . import secscan287 root = C.project_root(path)288 rel = C.rel_to(path, root) if root else os.path.basename(path)289 for rule, sev in secscan.scan_name(rel, secscan.load_allow(root)):290 if sev == "high" and root and C.git_root(root):291 rc, _, _ = C.git(["check-ignore", "-q", "--", rel], root, 10)292 if rc != 0:293 notes.append("SECURITY: %s looks like a secret file (%s) and is NOT git-ignored — add it to .gitignore before any commit." % (rel, rule))294 resp = inp.get("tool_response") or {}295 created = tool == "Write" and (isinstance(resp, dict) and resp.get("type") == "create")296 if root and tool != "NotebookEdit":297 try:298 r = H.process(path, "touch", is_new=created, automatic=True)299 except Exception as e: # the hook must never break an edit300 r = {"status": "error", "reason": "engine error: %s" % e}301 if r["status"] == "added":302 notes.append("SP Boucher source header added to %s by the PostToolUse hook (the file changed on disk: re-read it before "303 "the next edit; do not write a second header)." % rel)304 elif r["status"] == "updated":305 pass # Last Modified refreshed: not worth a message306 elif r["status"] == "deferred":307 key = "deferred:" + (root or "")308 if key not in st["notified"]:309 st["notified"].append(key)310 notes.append("%s has no SP Boucher header yet and this project has no established ownership (%s). If it is an "311 "SP Boucher-owned project: `sp-git init` (creates the SPB Git repository and applies headers) or "312 "`sp-header apply <file>`. If it is third-party, a client's or a co-author's work: add no header."313 % (rel, r["reason"]))314 elif r["status"] == "error":315 notes.append("sp-header could not stamp %s: %s" % (rel, r["reason"]))316 save_state(session, st)317 if notes:318 context("PostToolUse", "\n".join(notes))319320321# ----------------------------------------------------------------------------- Stop / SubagentStop322def review_session(session, final):323 """Look at what this session touched. Returns a list of findings (strings)."""324 from . import header as H325 from . import secscan326 st = load_state(session)327 touched = [p for p in st.get("touched", []) if os.path.isfile(p)]328 if not touched:329 return []330 by_root, loose = {}, {}331 for p in touched:332 r = C.git_root(p)333 if r:334 by_root.setdefault(r, []).append(p)335 else:336 pr = C.project_root(p)337 if pr:338 loose.setdefault(pr, []).append(p)339 out = []340 for root, files in by_root.items():341 own, why = C.ownership(root)342 if own in ("foreign", "restricted"):343 continue344 name = os.path.basename(root)345 if own == "owned":346 bad = []347 for p in files:348 r = H.process(p, "check", automatic=True)349 if r["status"] in ("missing", "drift"):350 r2 = H.process(p, "ensure", automatic=True)351 if r2["status"] not in ("added", "updated", "ok"):352 bad.append(r["rel"])353 if bad:354 out.append("[%s] source header missing on: %s (sp-header apply)" % (name, ", ".join(bad[:6])))355 dirty = set(C.porcelain(root))356 mine = [C.rel_to(p, root) for p in files if C.rel_to(p, root) in dirty or any(C.rel_to(p, root).startswith(d) for d in dirty if d.endswith("/"))]357 if mine:358 findings, _ = secscan.scan(root, "files", [os.path.join(root, m) for m in mine])359 hi = secscan.high(findings)360 if hi:361 out.append("[%s] SECRET RISK in files you edited:\n%s" % (name, secscan.format_findings(hi, 6)))362 if not final:363 continue364 o = C.origin_info(root)365 v2 = C.repo_policy(root)["v2"] or {}366 if mine:367 out.append("[%s] %d file(s) edited in this session are not committed (%s%s). Commit each finished step "368 "(`sp-git commit -m \"type(scope): …\" <files>`), then push." % (name, len(mine), ", ".join(mine[:5]), " …" if len(mine) > 5 else ""))369 if v2.get("publish", True) is False:370 continue371 if o["kind"] == "none":372 if own in ("owned", "unknown") and C.git_out(["rev-parse", "--verify", "-q", "HEAD"], root, 10):373 out.append("[%s] no SPB Git remote. Eligible SP Boucher project → `sp-git init` (public by default). Confidential, "374 "protected research or third-party material → keep it local/private and say why." % name)375 else:376 n = C.git_out(["rev-list", "--count"] + secscan.unpushed_range(root), root, 20)377 if n.isdigit() and int(n):378 out.append("[%s] %s validated commit(s) not pushed to %s → `sp-git push` (scan, push, verify)." % (name, n, o["raw"]))379 if final:380 for pr, files in loose.items():381 if any(H.classify(p, pr)["eligible"] for p in files[:40]):382 out.append("[%s] project directory without git: an eligible SP Boucher project starts with `sp-git init` "383 "(skip for scratch, confidential or third-party work, and say so)." % os.path.basename(pr))384 return out385386387def stop(inp, event):388 if inp.get("stop_hook_active"):389 return390 session = inp.get("session_id") or ""391 final = event == "Stop"392 findings = review_session(session, final)393 if not findings:394 return395 if not final:396 findings = [f for f in findings if "header missing" in f or "SECRET RISK" in f]397 if not findings:398 return399 head = ("SP Boucher development standard — completion check before stopping:\n" if final400 else "SP Boucher development standard — fix before handing back to the main agent:\n")401 tail = ("\nComplete the applicable steps now (review diff, tests, secret scan, commit, push, verify). If a step is deliberately "402 "not done (work in progress, confidential project, missing authorization, unreachable forge), state the blocker "403 "explicitly in your final message and preserve the local work." if final else "")404 emit({"decision": "block", "reason": head + "\n".join("- " + f for f in findings) + tail})405406407def main(argv=None):408 argv = argv if argv is not None else sys.argv[1:]409 event = argv[0] if argv else ""410 try:411 raw = sys.stdin.read()412 inp = json.loads(raw) if raw.strip() else {}413 except ValueError:414 inp = {}415 try:416 if event == "session-start":417 session_start(inp)418 elif event == "pre-tool-use":419 pre_tool_use(inp)420 elif event == "post-tool-use":421 post_tool_use(inp)422 elif event == "subagent-stop":423 stop(inp, "SubagentStop")424 elif event == "stop":425 stop(inp, "Stop")426 except Exception as e: # a governance hook must never break the session427 if os.environ.get("SP_HOOK_DEBUG"):428 raise429 C.eprint("sp-standard hook %s: %s" % (event, e))430 return 0431432433if __name__ == "__main__":434 sys.exit(main())435