#!/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") def hook_command(python: str) -> str: return f"{python} {SCRIPT} --from-hook >/dev/null 2>&1 || true" 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): print(f"already installed in {SETTINGS}") return 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 remove(): s = load_settings() if not installed(s): print(f"not installed in {SETTINGS}") return 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"] 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 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())