-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall_stop_hook.sh
More file actions
executable file
·451 lines (384 loc) · 14.3 KB
/
Copy pathinstall_stop_hook.sh
File metadata and controls
executable file
·451 lines (384 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#!/usr/bin/env bash
#
# install_stop_hook.sh — install/uninstall the task-hypergraph Stop hook for
# Claude Code.
#
# This script GENERATES <root>/stop_hook.sh and (optionally) wires it into a
# Claude Code settings.json as a `hooks.Stop` entry. The generated hook re-runs
# frontier.py over <root>/topology.html on every Stop event; while the
# hypergraph still has ready work it emits {"decision":"block", ...} so Claude
# Code KEEPS GOING, and once the graph is complete it stays silent and lets the
# session stop.
#
# CONSERVATIVE BY DESIGN — this script can edit a real settings.json:
# * Without --apply it NEVER touches a settings file; it only prints the exact
# snippet for you to paste.
# * With --apply it backs the file up to settings.json.bak BEFORE writing,
# refuses to edit a file it cannot parse, and only APPENDS our hook if it is
# absent — it never rewrites, reorders, or removes any pre-existing hook.
# * Editing is delegated to python3 (load -> merge -> dump) so we mutate the
# JSON object rather than text-munging it.
#
# Usage:
# install_stop_hook.sh --root PATH [--scope project|user] [--apply] [--uninstall]
#
# Pure POSIX tooling + python3 standard library. No pip/npm.
set -euo pipefail
PROG="$(basename "$0")"
# ── exit codes ──────────────────────────────────────────────────────────────
# 0 success
# 1 runtime failure (unparseable settings, unresolvable root, ...)
# 2 usage error (bad/missing flags)
USAGE="usage: ${PROG} --root PATH [--scope project|user] [--apply] [--uninstall]"
print_help() {
cat <<EOF
${USAGE}
Install (or remove) the task-hypergraph Stop hook for Claude Code.
Generates <root>/stop_hook.sh, which on every Stop event recomputes the frontier
of <root>/topology.html via frontier.py. While the hypergraph still has READY
nodes (or is otherwise incomplete, done_count < total) the hook prints a
{"decision":"block", ...} JSON object so Claude Code continues working; once the
graph is complete it prints nothing and allows the stop.
Options:
--root PATH Hypergraph root containing topology.html, GOAL.md and
frontier.py. REQUIRED.
--scope SCOPE Which settings.json --apply / --uninstall target:
project ./.claude/settings.json (default)
user ~/.claude/settings.json
--apply Merge the Stop hook into the target settings.json. Backs the
file up to settings.json.bak first and only appends the hook
if it is not already present. Without this flag the settings
snippet is printed to stdout and NO settings file is touched.
--uninstall Reverse an install: remove our Stop hook from the target
settings.json (with a .bak backup) and delete
<root>/stop_hook.sh.
-h, --help Show this help and exit.
Exit codes:
0 success
1 runtime failure
2 usage error
EOF
}
# ── error helpers ───────────────────────────────────────────────────────────
die_usage() {
printf '%s: error: %s\n' "$PROG" "$1" >&2
printf '%s\n' "$USAGE" >&2
exit 2
}
die_runtime() {
printf '%s: error: %s\n' "$PROG" "$1" >&2
exit 1
}
note() {
# Human-facing progress goes to stderr so stdout stays machine-clean
# (the settings snippet, when emitted, is the ONLY thing on stdout).
printf '%s: %s\n' "$PROG" "$1" >&2
}
# ── generate <root>/stop_hook.sh ────────────────────────────────────────────
# The hook resolves its own directory at runtime, so the absolute root is never
# baked in — copy/move the workspace and it still works.
generate_hook() {
local target="$1"
cat > "$target" <<'STOP_HOOK_EOF'
#!/usr/bin/env bash
#
# stop_hook.sh — Claude Code Stop hook for the task-hypergraph skill.
#
# GENERATED by install_stop_hook.sh. Do not hand-edit; re-generate instead.
#
# On every Stop event Claude Code runs this hook. It recomputes the frontier of
# <root>/topology.html via frontier.py and:
# * if there are READY nodes, OR the graph is otherwise incomplete
# (done_count < total), it prints a JSON {"decision":"block","reason":...}
# object on stdout — Claude Code reads that and KEEPS GOING;
# * otherwise it prints nothing and exits 0, allowing the session to stop.
#
# CONSERVATIVE BY DESIGN: on ANY error (missing files, frontier.py failure,
# unparseable output) it stays SILENT and exits 0, so a broken hook can never
# wedge a session permanently open.
set -euo pipefail
# This hook lives at <root>/stop_hook.sh, so its own directory IS the root.
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
# Claude Code delivers the Stop event as JSON on stdin. We don't need it, but we
# drain it so the writer never sees a broken pipe.
cat >/dev/null 2>&1 || true
python3 - "$ROOT" <<'PY'
import json
import os
import re
import subprocess
import sys
root = sys.argv[1]
topology = os.path.join(root, "topology.html")
frontier = os.path.join(root, "frontier.py")
goal_md = os.path.join(root, "GOAL.md")
def allow():
# Print nothing -> Claude Code is free to stop. The conservative default.
sys.exit(0)
if not (os.path.exists(frontier) and os.path.exists(topology)):
allow()
try:
proc = subprocess.run(
[sys.executable, frontier, topology],
capture_output=True,
text=True,
)
except Exception:
allow()
# frontier.py exits 0 normally; non-zero (incl. 3 = deadlock) -> stay silent.
if proc.returncode != 0 or not proc.stdout.strip():
allow()
# Parse frontier.py's plain-text output (no JSON):
# ready: B C D (or "(none)")
# done: 1/4
ready, done_count, total = [], 0, 0
for line in proc.stdout.splitlines():
if line.startswith("ready:"):
rest = line.split(":", 1)[1].strip()
if rest and rest != "(none)":
ready = rest.split()
elif line.startswith("done:"):
m = re.search(r"(\d+)\s*/\s*(\d+)", line)
if m:
done_count, total = int(m.group(1)), int(m.group(2))
# Nothing ready AND the graph is complete -> let Claude stop.
if not ready and done_count >= total:
allow()
try:
with open(goal_md, encoding="utf-8") as fh:
goal = fh.read().strip()
except Exception:
goal = ""
ids = ", ".join(ready)
reason = f"{goal}\n\nContinue the hypergraph; ready nodes: {ids}. Do not pause."
# The Stop-hook protocol expects JSON on stdout — this is Claude Code's hook
# API, not our persisted data format.
print(json.dumps({"decision": "block", "reason": reason}))
sys.exit(0)
PY
STOP_HOOK_EOF
chmod +x "$target"
}
# ── argument parsing ────────────────────────────────────────────────────────
ROOT=""
SCOPE="project"
APPLY=0
UNINSTALL=0
while [ "$#" -gt 0 ]; do
case "$1" in
-h|--help)
print_help
exit 0
;;
--root)
[ "$#" -ge 2 ] || die_usage "--root requires a PATH argument"
ROOT="$2"
shift 2
;;
--root=*)
ROOT="${1#*=}"
shift
;;
--scope)
[ "$#" -ge 2 ] || die_usage "--scope requires a value (project|user)"
SCOPE="$2"
shift 2
;;
--scope=*)
SCOPE="${1#*=}"
shift
;;
--apply)
APPLY=1
shift
;;
--uninstall)
UNINSTALL=1
shift
;;
--)
shift
break
;;
-*)
die_usage "unknown option: $1"
;;
*)
die_usage "unexpected positional argument: $1"
;;
esac
done
[ "$#" -eq 0 ] || die_usage "unexpected extra arguments: $*"
# ── validate ────────────────────────────────────────────────────────────────
[ -n "$ROOT" ] || die_usage "--root PATH is required"
case "$SCOPE" in
project|user) ;;
*) die_usage "--scope must be 'project' or 'user' (got '$SCOPE')" ;;
esac
# Resolve --root to an absolute path WITHOUT requiring it to exist (uninstall
# must work even after the workspace dir is gone). python3 os.path.abspath is
# portable across macOS/Linux where `realpath -m` may be absent.
ROOT_ABS="$(python3 -c 'import os, sys; print(os.path.abspath(sys.argv[1]))' "$ROOT")" \
|| die_runtime "could not resolve --root: $ROOT"
HOOK_PATH="${ROOT_ABS}/stop_hook.sh"
# Pick the target settings file. project = ./.claude (relative to CWD),
# user = ~/.claude.
case "$SCOPE" in
project) SETTINGS="${PWD}/.claude/settings.json" ;;
user) SETTINGS="${HOME}/.claude/settings.json" ;;
esac
# ── uninstall ───────────────────────────────────────────────────────────────
if [ "$UNINSTALL" -eq 1 ]; then
# Remove our hook from the settings file (conservative: backup first, only
# drop the entry that names our command, leave every other hook untouched).
python3 - "$SETTINGS" "$HOOK_PATH" <<'PYREMOVE'
import json
import os
import shutil
import sys
settings_path, cmd = sys.argv[1], sys.argv[2]
if not os.path.exists(settings_path):
print("no settings file to clean: " + settings_path, file=sys.stderr)
sys.exit(0)
try:
with open(settings_path, encoding="utf-8") as fh:
data = json.load(fh)
except Exception as exc:
# Never touch a file we cannot parse.
print("refusing to edit unparseable settings file: %s" % exc, file=sys.stderr)
sys.exit(1)
if not isinstance(data, dict):
print("settings.json is not a JSON object; left unchanged", file=sys.stderr)
sys.exit(0)
hooks = data.get("hooks")
stop = hooks.get("Stop") if isinstance(hooks, dict) else None
if not isinstance(stop, list):
print("no hooks.Stop array present; nothing to remove", file=sys.stderr)
sys.exit(0)
changed = False
new_stop = []
for entry in stop:
if isinstance(entry, dict) and isinstance(entry.get("hooks"), list):
kept = [
h for h in entry["hooks"]
if not (isinstance(h, dict) and h.get("command") == cmd)
]
if len(kept) != len(entry["hooks"]):
changed = True
if kept:
entry = dict(entry)
entry["hooks"] = kept
new_stop.append(entry)
# If kept is now empty, drop the whole entry rather than leaving a husk.
else:
new_stop.append(entry)
if not changed:
print("our Stop hook was not present; settings.json left unchanged", file=sys.stderr)
sys.exit(0)
if new_stop:
hooks["Stop"] = new_stop
else:
del hooks["Stop"]
if not hooks:
del data["hooks"]
shutil.copy2(settings_path, settings_path + ".bak")
print("backed up -> %s.bak" % settings_path, file=sys.stderr)
with open(settings_path, "w", encoding="utf-8") as fh:
json.dump(data, fh, indent=2)
fh.write("\n")
print("removed Stop hook from %s" % settings_path, file=sys.stderr)
PYREMOVE
if [ -f "$HOOK_PATH" ]; then
rm -f "$HOOK_PATH"
note "deleted ${HOOK_PATH}"
else
note "no hook file to delete at ${HOOK_PATH}"
fi
exit 0
fi
# ── install ─────────────────────────────────────────────────────────────────
# (Re)generate the hook. The root must exist to hold it.
[ -d "$ROOT_ABS" ] || die_runtime "root directory does not exist: ${ROOT_ABS}"
generate_hook "$HOOK_PATH"
note "generated ${HOOK_PATH}"
if [ "$APPLY" -eq 1 ]; then
# Merge our hook into the settings file. python3 owns the load/merge/dump so
# the JSON structure is preserved; backup happens only when we actually write.
mkdir -p "$(dirname "$SETTINGS")"
python3 - "$SETTINGS" "$HOOK_PATH" <<'PYAPPLY'
import json
import os
import shutil
import sys
settings_path, cmd = sys.argv[1], sys.argv[2]
data = {}
if os.path.exists(settings_path):
try:
with open(settings_path, encoding="utf-8") as fh:
data = json.load(fh)
except Exception as exc:
# Never overwrite a settings file we cannot parse.
print("refusing to edit unparseable settings file: %s" % exc, file=sys.stderr)
sys.exit(1)
if not isinstance(data, dict):
print("settings.json is not a JSON object; aborting", file=sys.stderr)
sys.exit(1)
hooks = data.get("hooks")
if hooks is None:
hooks = {}
if not isinstance(hooks, dict):
print("settings 'hooks' is not an object; aborting", file=sys.stderr)
sys.exit(1)
stop = hooks.get("Stop")
if stop is None:
stop = []
if not isinstance(stop, list):
print("settings hooks.Stop is not an array; aborting", file=sys.stderr)
sys.exit(1)
# Already wired up? Then leave the file completely untouched (idempotent).
present = False
for entry in stop:
if not isinstance(entry, dict):
continue
inner = entry.get("hooks")
if not isinstance(inner, list):
continue
for h in inner:
if isinstance(h, dict) and h.get("command") == cmd:
present = True
break
if present:
break
if present:
print("Stop hook already present; settings.json left unchanged", file=sys.stderr)
sys.exit(0)
# Append (never replace existing entries).
stop.append({"hooks": [{"type": "command", "command": cmd}]})
hooks["Stop"] = stop
data["hooks"] = hooks
if os.path.exists(settings_path):
shutil.copy2(settings_path, settings_path + ".bak")
print("backed up -> %s.bak" % settings_path, file=sys.stderr)
with open(settings_path, "w", encoding="utf-8") as fh:
json.dump(data, fh, indent=2)
fh.write("\n")
print("installed Stop hook into %s" % settings_path, file=sys.stderr)
PYAPPLY
exit 0
fi
# Default (no --apply): print the EXACT settings snippet and touch NO file.
note "no --apply given; settings file NOT modified."
note "paste the following into ${SETTINGS} (merge under hooks.Stop):"
python3 - "$HOOK_PATH" <<'PYSNIPPET'
import json
import sys
cmd = sys.argv[1]
snippet = {
"hooks": {
"Stop": [
{"hooks": [{"type": "command", "command": cmd}]}
]
}
}
print(json.dumps(snippet, indent=2))
PYSNIPPET