ckb/.agents/skills/ckb-add-conversation/scripts/autosave_hook.py
Michał Kopeć aaeabf3071 Template 1.22.1: hooks start from the project root
Claude Code runs a hook in the session's current directory, so the
autosave Stop hook's relative script path followed the shell into
subfolders: a session working inside a nested repo saved its transcript
there. autosave_hook.py and start_hook.py now write
`cd "${CLAUDE_PROJECT_DIR:-.}" && ...`; --check flags an entry from
before the fix as outdated and --install replaces it, keeping other
hooks. Smoke test fires both installed hooks from a subfolder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 19:34:30 +01:00

153 lines
5.4 KiB
Python

#!/usr/bin/env python3
"""Check, install or remove the per-machine Claude Code Stop hook that makes
conversation autosave mechanical.
autosave_hook.py --check # one line of status; exit 0 = nothing to do, 1 = action needed
autosave_hook.py --install # add the hook to .claude/settings.local.json (merge, never overwrite)
autosave_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. It runs save_conversation.py --from-hook after every turn, so the
transcript on disk is always current even if the session dies mid-turn.
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-add-conversation/scripts/save_conversation.py"
MARK = "save_conversation.py --from-hook"
def read_yaml_autosave(path=Path("ckb.yaml")) -> bool:
"""Minimal reader: find `autosave:` under `conversations:`. 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() == "conversations:"
continue
if in_block and line.strip().startswith("autosave:"):
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 and the
# save location both resolve to this KB.
ROOT_CD = 'cd "${CLAUDE_PROJECT_DIR:-.}" && '
def hook_command(python: str) -> str:
return f"{ROOT_CD}{python} {SCRIPT} --from-hook >/dev/null 2>&1 || true"
def outdated(settings) -> bool:
"""An entry installed before hooks started from the project root."""
for group in settings.get("hooks", {}).get("Stop", []) 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("Stop", []) 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("Stop", []).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 Stop 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"]["Stop"]:
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"]["Stop"] = groups
else:
del s["hooks"]["Stop"]
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 Stop hook from {SETTINGS}")
def check() -> int:
auto = read_yaml_autosave()
have = installed(load_settings()) if SETTINGS.exists() else False
if auto and not have:
print(f"autosave: on in ckb.yaml, Stop hook NOT installed in {SETTINGS} — ask the user, then --install")
return 1
if not auto and have:
print(f"autosave: off in ckb.yaml, but a Stop hook is still installed in {SETTINGS} — ask the user, then --remove")
return 1
if have and outdated(load_settings()):
print(f"autosave: Stop hook in {SETTINGS} does not start from the project root, so it can save into "
"the wrong folder — ask the user, then --install to replace it")
return 1
print(f"autosave: {'on, hook installed' if auto 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())