Skip to content
pi-c Artifact [65386e5f26]
Login

Artifact [65386e5f26]

Artifact 65386e5f26476d1013c9984dfe81dfe24f5aac6f8c6b0edcb2430282ead13b9d:


#!/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" ;;
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"; }
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\":\"$DB\""
    [ "$(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'

# ---- 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 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'

# ---- 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 'PASS: matchers take Claude Code names (Glob for find) 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 --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 --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 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 hooks end prompt_input_exit || fail "hooks end again"
[ "$(fired SessionEnd)" = 1 ] || fail "hooks end ran twice"
PIC_HOOK_OWNER=tui-test pic --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 '' 2 1
    printf 'PASS: a crash after a PreToolUse decision neither re-runs the hook nor runs a denied tool; before it, the hook runs again\n'
fi