#!/usr/bin/env python3 """Check, install or remove the per-machine Claude Code SessionStart hook that makes the Rule E session-start brief mechanical. start_hook.py --check # one line of status; exit 0 = nothing to do, 1 = action needed start_hook.py --install # add the hook to .claude/settings.local.json (merge, never overwrite) start_hook.py --remove # take it out again, leaving everything else intact The hook lives in .claude/settings.local.json, which is per machine and gitignored: a hook committed to git would run code on every clone. It runs session_start.py --hook on startup, resume, /clear and after every compaction, so the brief is in context before the first message and comes back after the context is compressed. `session: start_hook:` in ckb.yaml says whether this KB wants it; the agent asks before installing. Python 3.8+, standard library only. """ import argparse import json import sys from pathlib import Path SETTINGS = Path(".claude") / "settings.local.json" SCRIPT = ".agents/skills/ckb-lint/scripts/session_start.py" MARK = "session_start.py --hook" EVENT = "SessionStart" def read_yaml_start_hook(path=Path("ckb.yaml")) -> bool: """Minimal reader: find `start_hook:` under `session:`. No YAML parser needed.""" if not path.exists(): return False in_block = False for raw in path.read_text(encoding="utf-8").splitlines(): line = raw.split("#", 1)[0].rstrip() if not line.strip(): continue if not line.startswith((" ", "\t")): in_block = line.strip() == "session:" continue if in_block and line.strip().startswith("start_hook:"): return line.split(":", 1)[1].strip().lower() in ("true", "yes", "on") return False def load_settings(): if not SETTINGS.exists(): return {} try: return json.loads(SETTINGS.read_text(encoding="utf-8") or "{}") except json.JSONDecodeError as e: sys.exit(f"error: {SETTINGS} is not valid JSON ({e}); fix it by hand before installing the hook") # Claude Code runs a hook in the session's current directory, which need not be # the KB root: start from the project root so the relative script path resolves. ROOT_CD = 'cd "${CLAUDE_PROJECT_DIR:-.}" && ' def hook_command(python: str) -> str: # A failing brief must never block the session: no stderr, always exit 0. return f"{ROOT_CD}{python} {SCRIPT} --hook 2>/dev/null || true" def outdated(settings) -> bool: """An entry installed before hooks started from the project root.""" for group in settings.get("hooks", {}).get(EVENT, []) or []: for h in group.get("hooks", []) or []: command = str(h.get("command", "")) if MARK in command and "CLAUDE_PROJECT_DIR" not in command: return True return False def installed(settings) -> bool: for group in settings.get("hooks", {}).get(EVENT, []) or []: for h in group.get("hooks", []) or []: if MARK in str(h.get("command", "")): return True return False def install(python: str): s = load_settings() if installed(s) and not outdated(s): print(f"already installed in {SETTINGS}") return if installed(s): strip(s) s.setdefault("hooks", {}).setdefault(EVENT, []).append( {"hooks": [{"type": "command", "command": hook_command(python)}]}) SETTINGS.parent.mkdir(parents=True, exist_ok=True) SETTINGS.write_text(json.dumps(s, indent=2) + "\n", encoding="utf-8") print(f"installed {EVENT} hook in {SETTINGS}: {hook_command(python)}") def strip(s): """Drop this hook's entries from settings `s`, keeping every other hook.""" groups = [] for group in s["hooks"][EVENT]: kept = [h for h in group.get("hooks", []) if MARK not in str(h.get("command", ""))] if kept: group["hooks"] = kept groups.append(group) if groups: s["hooks"][EVENT] = groups else: del s["hooks"][EVENT] if not s["hooks"]: del s["hooks"] def remove(): s = load_settings() if not installed(s): print(f"not installed in {SETTINGS}") return strip(s) SETTINGS.write_text(json.dumps(s, indent=2) + "\n", encoding="utf-8") print(f"removed {EVENT} hook from {SETTINGS}") def check() -> int: want = read_yaml_start_hook() have = installed(load_settings()) if SETTINGS.exists() else False if want and not have: print(f"on in ckb.yaml, {EVENT} hook NOT installed in {SETTINGS} — ask the user, then --install") return 1 if not want and have: print(f"off in ckb.yaml, but a {EVENT} hook is still installed in {SETTINGS} — ask the user, then --remove") return 1 if have and outdated(load_settings()): print(f"{EVENT} hook in {SETTINGS} does not start from the project root — ask the user, then --install to replace it") return 1 print(f"{'on, hook installed' if want else 'off, no hook'}") return 0 def main(argv=None): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) g = ap.add_mutually_exclusive_group(required=True) g.add_argument("--check", action="store_true") g.add_argument("--install", action="store_true") g.add_argument("--remove", action="store_true") ap.add_argument("--python", default="python3", help="interpreter to put in the hook command (default python3)") a = ap.parse_args(argv) if a.check: return check() if a.install: install(a.python) else: remove() return 0 if __name__ == "__main__": sys.exit(main())