Fixes F7-F11 from the 2.0.0 script review: - UTF-8 stdout/stderr in every script; UTF-8 decoding of git/rg/yt-dlp output and of hook stdin - utf-8-sig reads, so BOM files keep their frontmatter - fingerprints match LF or CRLF checkouts (lint, lint_quick.sh, consolidate); prefix match on the full digest; short ones reported - POSIX paths in lint output; rg --path-separator / - hook installers default to the running interpreter, quote paths, --check reports a missing interpreter, odd settings are an error New tests/unit/test_windows.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
203 lines
7.5 KiB
Python
203 lines
7.5 KiB
Python
#!/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 re
|
|
import shutil
|
|
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-sig").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:
|
|
data = json.loads(SETTINGS.read_text(encoding="utf-8-sig") or "{}")
|
|
except json.JSONDecodeError as e:
|
|
sys.exit(f"error: {SETTINGS} is not valid JSON ({e}); fix it by hand before installing the hook")
|
|
if not isinstance(data, dict) or not isinstance(data.get("hooks", {}), dict):
|
|
sys.exit(f"error: {SETTINGS} is not a settings object with a `hooks` map; fix it by hand first")
|
|
return data
|
|
|
|
|
|
def python_word(python):
|
|
"""The interpreter as one shell word. A path is quoted, with forward
|
|
slashes (Git Bash on Windows takes them); a command such as `py -3` is
|
|
left as typed."""
|
|
if any(c in python for c in "/\\") or Path(python).exists():
|
|
return '"' + python.replace("\\", "/") + '"'
|
|
return python
|
|
|
|
|
|
def entries(settings):
|
|
"""This event's hook entries, skipping anything that isn't the documented shape."""
|
|
groups = (settings.get("hooks") or {}).get(EVENT) or []
|
|
for group in groups if isinstance(groups, list) else []:
|
|
for h in (group.get("hooks") or []) if isinstance(group, dict) else []:
|
|
if isinstance(h, dict):
|
|
yield h
|
|
|
|
|
|
def missing_interpreter(settings):
|
|
"""The interpreter our installed command names, when it can't be found here."""
|
|
for h in entries(settings):
|
|
command = str(h.get("command", ""))
|
|
if MARK not in command:
|
|
continue
|
|
rest = command.split("&& ", 1)[-1]
|
|
m = re.match(r'^"([^"]+)"', rest)
|
|
exe = m.group(1) if m else (rest.split() or [""])[0]
|
|
if not (Path(exe).exists() if m else shutil.which(exe)):
|
|
return exe
|
|
return None
|
|
|
|
|
|
# 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_word(python)} {SCRIPT} --hook 2>/dev/null || true"
|
|
|
|
|
|
def outdated(settings) -> bool:
|
|
"""An entry installed before hooks started from the project root."""
|
|
for h in entries(settings):
|
|
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 h in entries(settings):
|
|
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]:
|
|
if not isinstance(group, dict):
|
|
groups.append(group)
|
|
continue
|
|
kept = [h for h in group.get("hooks", []) if not (isinstance(h, dict) and MARK 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
|
|
exe = missing_interpreter(load_settings()) if have else None
|
|
if exe:
|
|
print(f"{EVENT} hook in {SETTINGS} runs {exe}, which is not found here, so it silently does nothing — "
|
|
"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):
|
|
for stream in (sys.stdout, sys.stderr): # UTF-8 output even on a Windows code page
|
|
if hasattr(stream, "reconfigure"):
|
|
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
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=sys.executable or "python3",
|
|
help="interpreter to put in the hook command (default: the one running this script)")
|
|
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())
|