Skip to content
pi-c Artifact [e24f4b1862]
Login

Artifact [e24f4b1862]

Artifact e24f4b186221e27743e6e44f4434ed167502d8ffc890e650a50e43adb302e215:


#!/bin/sh
# Command hooks in Claude Code's shape (~/.pic/hooks.json, and the trusted
# workspace's .pic/hooks.json): each event fires with its JSON on stdin,
# additionalContext reaches the next request, PreToolUse can deny a call,
# exit 2 blocks per event, timeouts and bad output are ignored but recorded,
# matchers take Claude Code's tool names, a Stop hook cannot loop forever,
# and a crash around a PreToolUse decision neither re-runs the hook nor runs
# a denied tool. --no-faults skips the crash cases (release has no crash points).
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
S=$(cd "$(dirname "$0")/streams" && pwd)
T=$(cd "$(mktemp -d "${TMPDIR:-/tmp}/pic-hooks.XXXXXX")" && pwd -P)
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null; [ -n "${KEEP:-}" ] && { echo "kept $T" >&2; return; }; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export HOME="$T/home" ANTHROPIC_API_KEY=pic-hooks-test-key PIC_PI_EXPORT=0 PIC_MODEL_CATALOG=offline
unset PIC_HOOK PIC_HOOK_OWNER 2>/dev/null || :
mkdir -p "$HOME/.pic" "$T/ws" "$T/h"
WS="$T/ws"
DB="$T/j"
pic() { "$PIC" --db "$DB" --workspace "$WS" --model fake/m "$@"; }

# serve SPEC...: a fresh fake server for one scenario, its requests in $T/log.
serve() {
    [ -n "$spid" ] && kill "$spid" 2>/dev/null && wait "$spid" 2>/dev/null || :
    rm -rf "$T/log" "$T/port"
    mkdir "$T/log"
    "$SERVER" "$T/port" "$T/log" 120 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server"; sleep 0.05; done
    printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"m"}]}}}' \
        "$(cat "$T/port")" > "$T/models.json"
}
export PIC_MODELS_FILE="$T/models.json"
# tool_sse FILE ID NAME ESCAPED_JSON: one tool call as an Anthropic stream.
tool_sse() {
    cat > "$1" <<EOF
event: message_start
data: {"type":"message_start","message":{"id":"msg_$2","type":"message","role":"assistant","model":"m","content":[],"stop_reason":null,"usage":{"input_tokens":5,"output_tokens":1}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_$2","name":"$3","input":{}}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"$4"}}

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":9}}

event: message_stop
data: {"type":"message_stop"}

EOF
}
text="sse:$S/text.sse"
tool_sse "$T/read.sse" read read '{\"path\": \"notes.txt\"}'
tool_sse "$T/bash.sse" bash bash '{\"command\": \"touch ran; echo ran >> ledger\"}'
tool_sse "$T/find.sse" find find '{\"pattern\": \"*.txt\"}'
printf 'the notes\n' > "$WS/notes.txt"

# The fake hook: logs its input, environment and directory, then does what
# $T/h/behave/EVENT says.
cat > "$T/h/hook.sh" <<'SH'
ev=$1
d=$(dirname "$0")
mkdir -p "$d/log"
n=$(ls "$d/log" | grep -c "^$ev\..*\.json\$")
n=$((n + 1))
cat > "$d/log/$ev.$n.json"
printf '%s|%s\n' "${PIC_HOOK:-unset}" "$(pwd -P)" > "$d/log/$ev.$n.env"
printf '%s\n' "$ev" >> "$d/order"
b=$(cat "$d/behave/$ev" 2>/dev/null || :)
case "$b" in
ctx:*) printf '{"hookSpecificOutput":{"hookEventName":"%s","additionalContext":"%s"}}\n' "$ev" "${b#ctx:}" ;;
plain:*) printf '%s\n' "${b#plain:}" ;;
deny:*) printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"%s"}}\n' "${b#deny:}" ;;
exit2:*) printf '%s\n' "${b#exit2:}" >&2; exit 2 ;;
block:*) printf '{"decision":"block","reason":"%s"}\n' "${b#block:}" ;;
blockonce:*) grep -q '"stop_hook_active":true' "$d/log/$ev.$n.json" || { printf '{"decision":"block","reason":"%s"}\n' "${b#blockonce:}"; } ;;
sleep) sleep 31.25; touch "$d/slept" ;;
hold) touch "$d/holding"; sleep 7.123; touch "$d/survived" ;;
readdb) tp=$(sed 's/.*"transcript_path":"\([^"]*\)".*/\1/' "$d/log/$ev.$n.json")
    sid=$(sed 's/.*"session_id":"\([^"]*\)".*/\1/' "$d/log/$ev.$n.json")
    sqlite3 "$tp" "SELECT CAST(sqlar_uncompress(line, sz) AS TEXT) FROM picu_pi_session_line WHERE conversation = '$sid' ORDER BY seq DESC LIMIT 1" > "$d/lastline.$ev" 2>&1 ;;
blockon:*) w=${b#blockon:}; if grep -q "$w" "$d/log/$ev.$n.json"; then echo "no $w here" >&2; exit 2; fi
    printf '{"hookSpecificOutput":{"hookEventName":"%s","additionalContext":"ups-q"}}\n' "$ev" ;;
badjson) printf '{"hookSpecificOutput": nope\n' ;;
esac
exit 0
SH
behave() { mkdir -p "$T/h/behave"; printf '%s\n' "$2" > "$T/h/behave/$1"; }
calm() { rm -rf "$T/h/behave" "$T/h/log" "$T/h/order" "$T/h/slept" "$T/h/holding" "$T/h/survived"; }
hooklog() { printf '%s/h/log/%s.%s.json' "$T" "$1" "${2:-1}"; }
fired() { ls "$T/h/log" 2>/dev/null | grep -c "^$1\..*\.json\$" || :; }
has() { grep -q -- "$2" "$1" || fail "$1 lacks $2: $(cat "$1")"; }
hk() { printf '{"type":"command","command":"sh %s/h/hook.sh %s"%s}' "$T" "$1" "${2:-}"; }
# Every event, PreToolUse and PostToolUse only for Bash and Read (and find, as Glob).
write_hooks() {
    cat > "$HOME/.pic/hooks.json" <<EOF
{"hooks": {
 "SessionStart": [{"hooks": [$(hk SessionStart)]}],
 "UserPromptSubmit": [{"hooks": [$(hk UserPromptSubmit)]}],
 "PreToolUse": [{"matcher": "Bash|Read", "hooks": [$(hk PreToolUse ',"timeout":5')]},
                {"matcher": "Glob", "hooks": [$(hk PreGlob)]},
                {"matcher": "Write", "hooks": [$(hk PreWrite)]}],
 "PostToolUse": [{"matcher": "Read|Bash", "hooks": [$(hk PostToolUse)]}],
 "PreCompact": [{"hooks": [$(hk PreCompact)]}],
 "Stop": [{"hooks": [$(hk Stop)]}],
 "SessionEnd": [{"hooks": [$(hk SessionEnd)]}]
}}
EOF
}
write_hooks
REAL_WS=$(cd "$WS" && pwd -P)

# ---- every event, in order, with Claude Code's fields --------------------
serve "sse:$T/read.sse" "$text"
pic ask 'read the notes' > "$T/out" 2> "$T/err" || fail "ask: $(cat "$T/err")"
sid=$(pic sessions | awk 'NR == 1 {print $1}')
[ "$(tr '\n' ' ' < "$T/h/order")" = "SessionStart UserPromptSubmit PreToolUse PostToolUse Stop SessionEnd " ] ||
    fail "order: $(tr '\n' ' ' < "$T/h/order")"
for ev in SessionStart UserPromptSubmit PreToolUse PostToolUse Stop SessionEnd; do
    f=$(hooklog $ev)
    has "$f" "\"hook_event_name\":\"$ev\""
    has "$f" "\"session_id\":\"$sid\""
    has "$f" '"harness":"pic"'
    has "$f" "\"cwd\":\"$REAL_WS\""
    has "$f" "\"transcript_path\":\"$HOME/.pic/pic.sqlite\""
    [ "$(cat "$T/h/log/$ev.1.env")" = "1|$REAL_WS" ] || fail "$ev: env/cwd $(cat "$T/h/log/$ev.1.env")"
done
has "$(hooklog SessionStart)" '"source":"startup"'
has "$(hooklog UserPromptSubmit)" '"prompt":"read the notes"'
has "$(hooklog PreToolUse)" '"tool_name":"Read"'
has "$(hooklog PreToolUse)" '"tool_input":{"path":"notes.txt","file_path":"notes.txt"}'
has "$(hooklog PreToolUse)" '"tool_use_id":"toolu_read"'
has "$(hooklog PostToolUse)" '"tool_response":{"content":"the notes'
has "$(hooklog PostToolUse)" '"is_error":false'
has "$(hooklog Stop)" '"stop_hook_active":false'
has "$(hooklog SessionEnd)" '"reason":"other"'
[ "$(fired PreGlob)$(fired PreWrite)" = 00 ] || fail "a matcher fired for another tool"
pic dump > "$T/dump"
[ "$(grep -c '^hook ' "$T/dump")" = 6 ] || fail "dump: hook runs $(grep '^hook ' "$T/dump")"
grep -q '^hook [0-9]* PreToolUse.* exit=0 ' "$T/dump" || fail "dump: $(grep '^hook ' "$T/dump")"
pic check > /dev/null || fail "check"
printf 'PASS: each event fires in order with session_id, cwd, transcript_path, harness, PIC_HOOK and the file_path alias\n'

# transcript_path is ~/.pic/pic.sqlite: from inside a hook, the
# conversation's Pi lines are there through its latest entry, unlocked.
calm
behave Stop readdb
behave SessionEnd readdb
serve "$text"
pic ask 'read me back' > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
has "$T/h/lastline.Stop" '"role":"assistant".*Hello'
has "$T/h/lastline.SessionEnd" '"role":"assistant".*Hello'
grep -q 'locked' "$T/h/lastline.Stop" && fail "the user database was locked during the hook"
printf 'PASS: a Stop or SessionEnd hook reads the conversation through its last reply from transcript_path (~/.pic/pic.sqlite)\n'

# ---- additionalContext reaches the requests, and a replay sends it again --
calm
behave SessionStart ctx:ss-ctx
behave UserPromptSubmit plain:ups-plain
behave PostToolUse ctx:post-ctx
serve "sse:$T/read.sse" "$text" "$text"
pic ask 'read again' > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
has "$T/log/1.req" 'SessionStart hook additional context: ss-ctx'
has "$T/log/1.req" 'UserPromptSubmit hook additional context: ups-plain'
grep -q 'post-ctx' "$T/log/1.req" && fail "PostToolUse context before its tool ran"
has "$T/log/2.req" '"is_error":false},{"type":"text","text":"<system-reminder>\\nPostToolUse hook additional context: post-ctx'
sid=$(pic sessions | awk 'NR == 1 {print $1}')
pic ask --session "$sid" 'and again' > /dev/null 2> "$T/err" || fail "ask -c: $(cat "$T/err")"
has "$(hooklog SessionStart 2)" '"source":"resume"'
has "$T/log/3.req" 'ss-ctx.*ups-plain.*post-ctx.*ss-ctx'
[ "$(fired PostToolUse)" = 1 ] || fail "PostToolUse ran again"
pic check > /dev/null || fail "check"
printf 'PASS: additionalContext and plain stdout reach the next request; a resumed request sends the journaled context without re-running hooks\n'

# ---- PreToolUse deny, by JSON and by exit 2 --------------------------------
calm
behave PreToolUse 'deny:no bash today'
serve "sse:$T/bash.sse" "$text"
pic ask 'make a file' > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
[ ! -e "$WS/ran" ] || fail "deny: the tool ran"
has "$(hooklog PreToolUse)" '"tool_name":"Bash"'
has "$T/log/2.req" '"tool_use_id":"toolu_bash","content":"no bash today","is_error":true'
[ "$(fired PostToolUse)" = 0 ] || fail "deny: PostToolUse fired for a call that did not run"
behave PreToolUse 'exit2:blocked by policy'
serve "sse:$T/bash.sse" "$text"
pic ask 'make a file' > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
[ ! -e "$WS/ran" ] || fail "exit 2: the tool ran"
has "$T/log/2.req" '"content":"blocked by policy","is_error":true'
pic check > /dev/null || fail "check"
printf 'PASS: a PreToolUse deny (JSON or exit 2) stops the call and the model sees the reason\n'

# ---- exit 2 for the other events ------------------------------------------
calm
behave UserPromptSubmit 'exit2:not that prompt'
serve "$text"
before=$(pic sessions | wc -l | tr -d ' ')
if pic ask 'forbidden words' > /dev/null 2> "$T/err"; then fail "a blocked prompt succeeded"; fi
grep -q 'not that prompt' "$T/err" || fail "blocked prompt: stderr $(cat "$T/err")"
[ "$(ls "$T/log" | wc -l | tr -d ' ')" = 0 ] || fail "blocked prompt reached the model"
[ "$(pic sessions | wc -l | tr -d ' ')" = "$before" ] || fail "blocked prompt made a conversation"
pic dump | grep -q 'forbidden words' && fail "blocked prompt journaled"
behave UserPromptSubmit 'block:json block'
if pic ask 'other words' > /dev/null 2> "$T/err"; then fail "a JSON-blocked prompt succeeded"; fi
grep -q 'json block' "$T/err" || fail "JSON block: stderr $(cat "$T/err")"
printf 'PASS: UserPromptSubmit exit 2 or decision block rejects the prompt, shown to the user, nothing journaled\n'

calm
behave UserPromptSubmit plain:leaked-context
serve "$text"
pic ask 'first' > /dev/null 2>&1 || fail "ask first"
sid=$(pic sessions | awk 'NR == 1 {print $1}')
pic submit k-busy 'queued work' --session "$sid" > /dev/null || fail "submit"
[ "$(fired UserPromptSubmit)" = 2 ] || fail "pic submit did not fire UserPromptSubmit"
if pic ask --session "$sid" 'rejected prompt' > /dev/null 2> "$T/err"; then fail "ask on a busy conversation succeeded"; fi
grep -q 'still working' "$T/err" || fail "busy: $(cat "$T/err")"
[ "$(fired UserPromptSubmit)" = 2 ] || fail "busy: hooks ran for a prompt that could not be admitted"
pic run > /dev/null 2>&1 || fail "run the queued work"
[ "$(grep -o 'leaked-context' "$T/log/2.req" | wc -l | tr -d ' ')" = 2 ] ||
    fail "busy: the second request carries other context: $(grep -o 'leaked-context' "$T/log/2.req" | wc -l)"
grep -q 'rejected prompt' "$T"/log/*.req && fail "busy: the rejected prompt reached the model"
for bad in 'new:abc' 'new:' "new:$(printf '%0100d' 0)"; do
    if pic ask --session "$bad" 'x' > /dev/null 2> "$T/err"; then fail "--session $bad accepted"; fi
    if pic submit "k-$bad" 'x' --session "$bad" > /dev/null 2>&1; then fail "submit --session $bad accepted"; fi
done
pic check > /dev/null || fail "check after new: sessions"
printf 'PASS: pic submit fires the prompt hooks; a prompt to a busy conversation runs none and leaks nothing; new: is no session name\n'

calm
behave UserPromptSubmit blockon:forbidden
serve "sse:$S/bash_hold.sse" "$text" "$text"
rm -f "$WS/started" "$WS/release" "$T/in"
mkfifo "$T/in"
"$PIC" --db "$DB" --workspace "$WS" --model fake/m --json --commands ask 'hold on' < "$T/in" > "$T/ev" 2> "$T/everr" &
rpid=$!
exec 3> "$T/in"
i=0; while [ ! -e "$WS/started" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "rpc: never started"; sleep 0.05; done
printf '%s\n' '{"id":"f1","type":"follow_up","message":"then this"}' '{"id":"s1","type":"steer","message":"forbidden steer"}' >&3
i=0; until grep -q '"id":"s1"' "$T/ev"; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "rpc: no answer to the steer"; sleep 0.05; done
grep -q '"id":"f1","type":"response","command":"follow_up","success":true' "$T/ev" || fail "rpc: follow_up: $(grep f1 "$T/ev")"
grep -q '"id":"s1","type":"response","command":"steer","success":false,"error":"prompt blocked by a UserPromptSubmit hook: no forbidden here"' "$T/ev" ||
    fail "rpc: blocked steer: $(grep s1 "$T/ev")"
touch "$WS/release"
exec 3>&-
wait "$rpid" || fail "rpc: $(cat "$T/everr")"
f=$(grep -l 'then this' "$T"/log/*.req | head -1)
[ -n "$f" ] || fail "rpc: the follow-up never reached the model"
has "$f" 'then this.*UserPromptSubmit hook additional context: ups-q'
grep -q 'forbidden steer' "$T"/log/*.req && fail "rpc: the blocked steer reached the model"
has "$(hooklog UserPromptSubmit 2)" '"prompt":"then this"'
pic check > /dev/null || fail "check"
printf 'PASS: steer and follow_up fire UserPromptSubmit on arrival; a block rejects the command; context goes with the message\n'

calm
behave PostToolUse 'exit2:post says no'
behave SessionStart 'exit2:ignored'
serve "sse:$T/read.sse" "$text"
pic ask 'read' > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
has "$T/log/2.req" 'PostToolUse hook feedback:\\npost says no'
grep -q 'ignored' "$T/log/1.req" && fail "SessionStart exit 2 reached the model"
printf 'PASS: PostToolUse exit 2 feeds stderr to the model; SessionStart exit 2 does not block\n'

calm
behave Stop 'blockonce:keep going'
serve "$text"
pic ask 'finish' > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
[ "$(ls "$T/log" | wc -l | tr -d ' ')" = 2 ] || fail "Stop block: $(ls "$T/log" | wc -l) requests"
has "$T/log/2.req" 'Stop hook feedback:\\nkeep going'
has "$(hooklog Stop 2)" '"stop_hook_active":true'
pic dump | grep -q "^submission .* answered | finish" || fail "Stop: not answered: $(pic dump | grep "^submission\|^hook .* Stop\|^entry" | tail -8)"
calm
behave Stop 'exit2:never done'
serve "$text"
pic ask 'loop' > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
n=$(ls "$T/log" | wc -l | tr -d ' ')
[ "$n" -ge 2 ] && [ "$n" -le 9 ] || fail "Stop loop guard: $n requests"
pic dump | grep -q '^hook .* Stop.*loop' || fail "Stop loop guard not recorded: $(pic dump | grep '^hook .* Stop')"
pic check > /dev/null || fail "check"
printf 'PASS: Stop exit 2 or decision block continues the reply with the feedback; stop_hook_active is set and a loop is cut off\n'

# ---- failures are ignored, but recorded -----------------------------------
calm
behave UserPromptSubmit badjson
cat > "$HOME/.pic/hooks.json" <<EOF
{"hooks": {
 "UserPromptSubmit": [{"hooks": [$(hk UserPromptSubmit)]}],
 "SessionStart": [{"hooks": [$(hk SessionStart ',"timeout":1')]}],
 "Stop": [{"hooks": [{"type":"command","command":"$T/nonexistent-hook"}]}]
}}
EOF
behave SessionStart sleep
serve "$text"
start=$(date +%s)
pic ask 'go' > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
[ $(( $(date +%s) - start )) -lt 10 ] || fail "timeout not enforced"
sleep 1
pgrep -f 'sleep 31.25' > /dev/null && fail "timed-out hook left running"
[ ! -e "$T/h/slept" ] || fail "timed-out hook finished"
pic dump > "$T/dump"
grep -q '^hook .* SessionStart .*timed out' "$T/dump" || fail "timeout not recorded: $(grep '^hook ' "$T/dump")"
grep -q '^hook .* UserPromptSubmit .*JSON' "$T/dump" || fail "bad JSON not recorded: $(grep '^hook ' "$T/dump")"
grep -q '^hook .* Stop .*exit=127' "$T/dump" || fail "missing command not recorded: $(grep '^hook ' "$T/dump")"
pic dump | grep -q "^submission .* answered | go" || fail "a failed hook failed the run"
printf 'PASS: a timeout (process group killed), bad JSON and a missing command are ignored and recorded\n'

# A hook dies with pic (kill -9) and recovery does not run it again; Ctrl-C
# ends a running hook at once and cancels the request.
calm
printf '{"hooks": {"Stop": [{"hooks": [%s]}]}}\n' "$(hk Stop ',"timeout":30')" > "$HOME/.pic/hooks.json"
behave Stop hold
serve "$text"
"$PIC" --db "$DB" --workspace "$WS" --model fake/m ask 'die' > /dev/null 2>&1 &
p=$!
i=0; while [ ! -e "$T/h/holding" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "die: hook never started"; sleep 0.05; done
kill -9 "$p"
wait "$p" 2>/dev/null || :
sleep 1
pgrep -f 'sleep 7.123' > /dev/null && fail "die: the hook outlived pic"
pic run > /dev/null 2>&1 || fail "die: recovery"
[ "$(fired Stop)" = 1 ] || fail "die: Stop ran again on recovery"
pic dump | grep -q '^hook .* Stop .*interrupted' || fail "die: the run is not marked interrupted: $(pic dump | grep '^hook ' | tail -2)"
pic dump | grep -q "^submission .* answered | die" || fail "die: not answered"
pic check > /dev/null || fail "check"
calm
behave Stop hold
"$PIC" --db "$DB" --workspace "$WS" --model fake/m ask 'interrupt' > /dev/null 2>&1 &
p=$!
i=0; while [ ! -e "$T/h/holding" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "ctrl-c: hook never started"; sleep 0.05; done
start=$(date +%s)
kill -INT "$p"
wait "$p" 2>/dev/null || :
[ $(( $(date +%s) - start )) -lt 4 ] || fail "ctrl-c: pic waited for the hook"
sleep 0.5
pgrep -f 'sleep 7.123' > /dev/null && fail "ctrl-c: the hook kept running"
pic dump | grep -q "^submission .* failed | interrupt error=cancelled" || fail "ctrl-c: $(pic dump | grep '^submission' | tail -1)"
pic check > /dev/null || fail "check"
write_hooks
printf 'PASS: a hook dies with pic and is not run again on recovery; Ctrl-C ends it at once\n'

# ---- async hooks do not hold the run --------------------------------------
calm
cat > "$HOME/.pic/hooks.json" <<EOF
{"hooks": {"Stop": [{"hooks": [{"type":"command","command":"sleep 5; touch $T/h/async-done","async":true}]}]}}
EOF
serve "$text"
start=$(date +%s)
pic ask 'quick' > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
[ $(( $(date +%s) - start )) -lt 4 ] || fail "async hook was waited for"
[ ! -e "$T/h/async-done" ] || fail "async hook finished before pic returned"
i=0
while [ ! -e "$T/h/async-done" ]; do i=$((i + 1)); [ "$i" -lt 200 ] || fail "async hook never ran"; sleep 0.1; done
printf 'PASS: an async hook runs without holding the run\n'

# ---- project hooks only when the workspace is trusted ---------------------
calm
rm -f "$HOME/.pic/hooks.json"
mkdir -p "$WS/.pic"
printf '{"hooks": {"SessionStart": [{"hooks": [%s]}]}}\n' "$(hk ProjectStart)" > "$WS/.pic/hooks.json"
serve "$text"
pic ask 'untrusted' > /dev/null 2>&1 || fail "ask untrusted"
[ "$(fired ProjectStart)" = 0 ] || fail "project hook ran untrusted"
pic trust yes > /dev/null
pic ask 'trusted' > /dev/null 2>&1 || fail "ask trusted"
[ "$(fired ProjectStart)" = 1 ] || fail "project hook did not run trusted"
pic trust no > /dev/null
rm -f "$WS/.pic/hooks.json"
printf 'PASS: the workspace hooks run only once it is trusted\n'

# ---- Claude Code tool names in matchers -----------------------------------
calm
write_hooks
serve "sse:$T/find.sse" "$text"
pic ask 'find' > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
[ "$(fired PreGlob)" = 1 ] || fail "Glob did not match find"
has "$(hooklog PreGlob)" '"tool_name":"Glob"'
[ "$(fired PreToolUse)" = 0 ] || fail "Bash|Read matched find"
printf '{"hooks": {"PreToolUse": [{"matcher": "MultiEdit", "hooks": [%s]}]}}\n' "$(hk PreMulti)" > "$HOME/.pic/hooks.json"
tool_sse "$T/edit.sse" edit edit '{\"path\": \"notes.txt\", \"edits\": [{\"oldText\": \"the\", \"newText\": \"our\"}]}'
serve "sse:$T/edit.sse" "$text"
pic ask 'edit' > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
[ "$(fired PreMulti)" = 1 ] || fail "MultiEdit did not match edit"
has "$(hooklog PreMulti)" '"tool_name":"Edit"'
write_hooks
printf 'PASS: matchers take Claude Code names (Glob for find, Edit or MultiEdit for edit) as well as pic names\n'

# ---- the session lifecycle: chat, and a parent that owns it ----------------
calm
serve "$text"
printf 'one\ntwo\n' | pic chat > /dev/null 2> "$T/err" || fail "chat: $(cat "$T/err")"
[ "$(fired SessionStart)$(fired UserPromptSubmit)$(fired SessionEnd)" = 121 ] ||
    fail "chat: SessionStart $(fired SessionStart) UserPromptSubmit $(fired UserPromptSubmit) SessionEnd $(fired SessionEnd)"
has "$(hooklog SessionEnd)" '"reason":"prompt_input_exit"'
calm
PIC_HOOK_OWNER=tui-test "$PIC" --db "$DB" --workspace "$WS" --model fake/m --json ask 'first' > /dev/null 2>&1 || fail "owned ask 1"
sid=$(pic sessions | awk 'NR == 1 {print $1}')
PIC_HOOK_OWNER=tui-test "$PIC" --db "$DB" --workspace "$WS" --model fake/m --json ask --session "$sid" 'second' > /dev/null 2>&1 || fail "owned ask 2"
[ "$(fired SessionStart)$(fired SessionEnd)" = 10 ] || fail "owned: SessionStart $(fired SessionStart) SessionEnd $(fired SessionEnd)"
PIC_HOOK_OWNER=tui-test "$PIC" --db "$DB" --workspace "$WS" --model fake/m hooks end prompt_input_exit || fail "hooks end"
[ "$(fired SessionEnd)" = 1 ] || fail "hooks end: SessionEnd $(fired SessionEnd)"
has "$(hooklog SessionEnd)" "\"session_id\":\"$sid\""
PIC_HOOK_OWNER=tui-test "$PIC" --db "$DB" --workspace "$WS" --model fake/m hooks end prompt_input_exit || fail "hooks end again"
[ "$(fired SessionEnd)" = 1 ] || fail "hooks end ran twice"
PIC_HOOK_OWNER=tui-test "$PIC" --db "$DB" --workspace "$WS" --model fake/m --json ask --session "$sid" 'back again' > /dev/null 2>&1 || fail "owned ask 3"
[ "$(fired SessionStart)" = 2 ] || fail "a conversation ended and resumed did not start again"
has "$(hooklog SessionStart 2)" '"source":"resume"'
pic hooks > "$T/list"
grep -q '^PreToolUse	Bash|Read	5	' "$T/list" || fail "pic hooks: $(cat "$T/list")"
printf 'PASS: chat starts and ends a conversation once; a parent (the terminal) owns the lifecycle of its children\n'

# ---- PreCompact, and SessionStart after a compaction ------------------------
calm
behave PreCompact ctx:keep-the-hooks-in-mind
behave SessionStart ctx:after-compact
big() { yes "$1$1$1$1" | head -c 50000 | tr -d '\n'; }
serve "$text"
pic submit c1 "$(big A)" > /dev/null
pic run > /dev/null 2>&1 || fail "run c1"
csid=$(pic sessions | awk 'NR == 1 {print $1}')
pic submit c2 "$(big B)" --session "$csid" > /dev/null
pic run > /dev/null 2>&1 || fail "run c2"
pic compact "$csid" 'mind the hooks' > /dev/null
calm
behave PreCompact ctx:keep-the-hooks-in-mind
behave SessionStart ctx:after-compact
serve "$text"
pic ask --session "$csid" "$(big D)" > /dev/null 2> "$T/err" || fail "ask: $(cat "$T/err")"
has "$(hooklog PreCompact)" '"trigger":"manual"'
has "$(hooklog PreCompact)" '"custom_instructions":"mind the hooks"'
has "$(hooklog SessionStart 2)" '"source":"compact"'
grep -l 'You are a context summarization assistant' "$T"/log/*.req > "$T/summary" || fail "no summary request"
has "$(head -1 "$T/summary")" 'mind the hooks.*keep-the-hooks-in-mind'
last=$(ls "$T/log" | sort -n | tail -1)
has "$T/log/$last" 'SessionStart hook additional context: after-compact'
pic check > /dev/null || fail "check"
printf 'PASS: PreCompact context joins the summary instructions; SessionStart fires with source compact after it\n'

# ---- crashes around the PreToolUse decision (development builds) -----------
if [ "$FAULTS" = yes ]; then
    printf 'tool exec touch ran; echo ran >> ledger\ntext done\n' > "$T/crash.script"
    crash_case() { # crash_case NAME POINT BEHAVIOUR HOOK_RUNS LEDGER_LINES
        calm
        write_hooks
        [ -n "$3" ] && behave PreToolUse "$3"
        rm -f "$WS/ran" "$WS/ledger" "$T/cj"
        "$PIC" --db "$T/cj" --workspace "$WS" submit job 'go' > /dev/null
        if PIC_CRASH_AT="$2:1" "$PIC" --db "$T/cj" --workspace "$WS" run --script "$T/crash.script" > /dev/null 2>&1; then
            fail "$1: no crash at $2"
        fi
        "$PIC" --db "$T/cj" --workspace "$WS" run --script "$T/crash.script" > /dev/null 2>&1 || fail "$1: recovery run"
        [ "$(fired PreToolUse)" = "$4" ] || fail "$1: PreToolUse ran $(fired PreToolUse) times"
        lines=$( [ -e "$WS/ledger" ] && wc -l < "$WS/ledger" | tr -d ' ' || echo 0)
        [ "$lines" = "$5" ] || fail "$1: the tool ran $lines times"
        "$PIC" --db "$T/cj" --workspace "$WS" check > /dev/null || fail "$1: check"
    }
    crash_case allow-decided after-hook-decision '' 1 1
    crash_case deny-decided after-hook-decision 'deny:nope' 1 0
    "$PIC" --db "$T/cj" --workspace "$WS" dump | grep -q '^effect 1 .* skipped .*| nope$' || fail "deny-decided: effect not skipped with the reason"
    crash_case undecided after-hook-run '' 1 0
    "$PIC" --db "$T/cj" --workspace "$WS" dump | grep -q '^effect 1 .* skipped .*| error: a PreToolUse hook was interrupted' ||
        fail "undecided: $("$PIC" --db "$T/cj" --workspace "$WS" dump | grep '^effect')"
    printf 'PASS: a crash around a PreToolUse decision never runs its hook again, nor a denied or undecided call\n'

    # one_hook EVENT: only that event's hook configured.
    one_hook() { printf '{"hooks": {"%s": [{"hooks": [%s]}]}}\n' "$1" "$(hk "$1")" > "$HOME/.pic/hooks.json"; }
    for ev in Stop PostToolUse; do
        calm
        one_hook $ev
        if [ $ev = Stop ]; then behave Stop 'block:go on'; else behave PostToolUse ctx:post-crash; fi
        rm -f "$WS/ran" "$WS/ledger" "$T/cj" "$T/cj-wal" "$T/cj-shm"
        "$PIC" --db "$T/cj" --workspace "$WS" submit job 'go' > /dev/null
        if PIC_CRASH_AT=after-hook-run:1 "$PIC" --db "$T/cj" --workspace "$WS" run --script "$T/crash.script" > /dev/null 2>&1; then
            fail "$ev: no crash"
        fi
        "$PIC" --db "$T/cj" --workspace "$WS" run --script "$T/crash.script" > /dev/null 2>&1 || fail "$ev: recovery run"
        [ "$(fired $ev)" = 1 ] || fail "$ev: ran $(fired $ev) times"
        "$PIC" --db "$T/cj" --workspace "$WS" dump > "$T/cdump"
        grep -q "^hook .* $ev .*interrupted" "$T/cdump" || fail "$ev: not interrupted: $(grep '^hook' "$T/cdump")"
        grep -q '^submission .* answered' "$T/cdump" || fail "$ev: not answered: $(grep '^submission' "$T/cdump")"
        grep -q 'post-crash\|Stop hook feedback' "$T/cdump" && fail "$ev: an interrupted run's output was used"
        "$PIC" --db "$T/cj" --workspace "$WS" check > /dev/null || fail "$ev: check"
    done
    calm
    one_hook PreCompact
    behave PreCompact ctx:compact-crash
    {
        printf 'tool bash head -c 40000 /dev/zero | tr "\\0" x\n'
        printf 'tool bash head -c 40000 /dev/zero | tr "\\0" y\n'
        printf 'text done\n'
    } > "$T/split.script"
    rm -f "$T/cj" "$T/cj-wal" "$T/cj-shm"
    "$PIC" --db "$T/cj" --workspace "$WS" submit job 'go' > /dev/null
    if PIC_CRASH_AT=after-hook-run:1 "$PIC" --db "$T/cj" --workspace "$WS" --context-window 30000 run --script "$T/split.script" > /dev/null 2>&1; then
        fail "PreCompact: no crash"
    fi
    "$PIC" --db "$T/cj" --workspace "$WS" --context-window 30000 run --script "$T/split.script" > /dev/null 2>&1 || fail "PreCompact: recovery"
    [ "$(fired PreCompact)" = 1 ] || fail "PreCompact ran $(fired PreCompact) times"
    "$PIC" --db "$T/cj" --workspace "$WS" dump > "$T/cdump"
    grep -q '^entry .* compaction ' "$T/cdump" || fail "PreCompact: no compaction after recovery"
    grep -q '^hook .* PreCompact .*interrupted' "$T/cdump" || fail "PreCompact: not interrupted"
    grep -q 'compact-crash' "$T/cdump" && fail "PreCompact: an interrupted run's context was used"
    "$PIC" --db "$T/cj" --workspace "$WS" check > /dev/null || fail "PreCompact: check"
    printf 'PASS: a crash during a Stop, PostToolUse or PreCompact hook leaves it interrupted, never run again or used\n'
fi