#!/bin/sh
# Permission modes (docs/manual/permissions.md, docs/dev/permissions.md): a conversation's mode,
# durable in pic_permission, says which tool calls ask first. allow (the default) asks nothing;
# ask-edits asks before write and edit; ask-all before every call that is not read-only; read-only
# refuses those. A call that asks is a select ask keyed perm:EFFECT (Allow, Allow for this
# conversation, Deny), and the call waits on it durably: a crash or a kill leaves the ask open and
# the call unrun, and the next owner finds the answer. A PreToolUse hook's ask asks in every mode.
# Usage: test/pic/permissions.sh [--no-faults]
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
FAULTS=1
[ "${1:-}" = --no-faults ] && FAULTS=0
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-perm.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME/.pic"
"$PIC" settings cacheRetention none > /dev/null
"$PIC" settings defaultModel fake/m > /dev/null
spid=
pid=
pids= # every pic this script starts in the background, killed on the way out
cleanup() {
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    for p in $pids; do kill -9 "$p" 2>/dev/null; done
    rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM ALRM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export ANTHROPIC_API_KEY=pic-perm-test-key PIC_PI_EXPORT=0
SQLITE3=${SQLITE3:-sqlite3}
n=0
serve() { # SPEC...: a fresh server, journal and workspace
    mkdir "$T/ws$((n + 1))"
    DB="$T/j$((n + 1)).sqlite"
    WS="$T/ws$((n + 1))"
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    n=$((n + 1))
    mkdir "$T/log$n"
    "$SERVER" "$T/port$n" "$T/log$n" 90 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port$n" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "server did not start"
        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$n")" > "$T/models$n.json"
    export PIC_MODELS_FILE="$T/models$n.json"
}
restart() { # SPEC...: a fresh server for the same journal and workspace
    kill "$spid" 2>/dev/null
    n=$((n + 1))
    mkdir "$T/log$n"
    "$SERVER" "$T/port$n" "$T/log$n" 90 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port$n" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "server did not start"
        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$n")" > "$T/models$n.json"
    export PIC_MODELS_FILE="$T/models$n.json"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
bgpic() { # ARGS: pic in the background, its pid in $pid and kept for cleanup
    "$PIC" --db "$DB" --workspace "$WS" "$@" &
    pid=$!
    pids="$pids $pid"
}
q() { "$SQLITE3" -cmd ".timeout 10000" "$DB" "$1"; }
until_sql() { # SQL VALUE: wait up to 30s for the query to print VALUE
    i=0
    until [ "$(q "$1" 2> /dev/null)" = "$2" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for [$1] = $2: $(q "$1" 2>&1)"
        sleep 0.05
    done
}
tool_sse() { # NAME JSON: a reply that calls tool NAME with input JSON
    esc=$(printf '%s' "$2" | sed 's/\\/\\\\/g; s/"/\\"/g')
    printf 'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_01","type":"message","role":"assistant","model":"m","content":[],"stop_reason":null,"usage":{"input_tokens":25,"output_tokens":1}}}\n\n'
    printf 'event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_p","name":"%s","input":{}}}\n\n' "$1"
    printf 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"%s"}}\n\n' "$esc"
    printf 'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n'
    printf 'event: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":40}}\n\n'
    printf 'event: message_stop\ndata: {"type":"message_stop"}\n\n'
}
aid() { q "SELECT id FROM pic_ask ORDER BY rowid LIMIT 1 OFFSET $(($1 - 1))"; } # the Nth ask's id
ask_state() { q "SELECT state || '|' || coalesce(answer, '') || '|' || coalesce(answered_by, '') FROM pic_ask ORDER BY rowid LIMIT 1 OFFSET $(($1 - 1))"; }
result() { q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1"; }
sid() { q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1"; }
LEDGER="$T/ledger" # the workspace is $T/wsN: the command names it relatively, so no title depends on TMPDIR
tool_sse bash '{"command":"echo ran >> ../ledger"}' > "$T/bash.sse"
tool_sse write '{"path":"notes.txt","content":"one\ntwo\n"}' > "$T/write.sse"
tool_sse read '{"path":"seen.txt"}' > "$T/read.sse"
ran() { [ -f "$LEDGER" ] && wc -l < "$LEDGER" | tr -d ' ' || echo 0; }

# allow, the default: nothing asks, and the conversation keeps no row.
serve "sse:$T/bash.sse" "sse:$S/text.sse"
pic ask 'go' > /dev/null 2> "$T/err" || fail "allow: $(cat "$T/err")"
[ "$(ran)" = 1 ] || fail "allow: the command did not run"
[ "$(q 'SELECT count(*) FROM pic_ask')" = 0 ] || fail "allow: asked"
[ "$(q 'SELECT count(*) FROM pic_permission')" = 0 ] || fail "allow: a row: $(q 'SELECT * FROM pic_permission')"
printf '{"id":"g","type":"get_permission_mode"}\n' | pic --mode rpc --session "$(sid)" > "$T/rpc.out" 2> "$T/err" || fail "allow: rpc: $(cat "$T/err")"
grep -qF '"data":{"permissionMode":"allow","allowed":[]}' "$T/rpc.out" || fail "allow: get_permission_mode: $(cat "$T/rpc.out")"
rm -f "$LEDGER"
printf 'PASS: allow asks nothing and keeps no row\n'

# ask-all: the call asks, a select keyed by its effect; Allow runs it once.
serve "sse:$T/bash.sse" "sse:$S/text.sse"
bgpic --permission-mode ask-all ask 'go' > "$T/out" 2> "$T/err"

until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
[ "$(q "SELECT mode FROM pic_permission WHERE session_id = '$(sid)'")" = ask-all ] || fail "ask-all: the row: $(q 'SELECT * FROM pic_permission')"
EFF=$(q "SELECT id FROM pic_effect ORDER BY id DESC LIMIT 1")
[ "$(q "SELECT ask_key, kind, title, body FROM pic_ask")" = "perm:$EFF|select|Allow bash: echo ran >> ../ledger?|echo ran >> ../ledger" ] ||
    fail "ask-all: the ask: $(q 'SELECT ask_key, kind, title, body FROM pic_ask')"
[ "$(q "SELECT json_extract(spec, '\$.options') FROM pic_ask")" = '[{"label":"Allow"},{"label":"Allow for this conversation"},{"label":"Deny"}]' ] ||
    fail "ask-all: options: $(q 'SELECT spec FROM pic_ask')"
[ "$(q "SELECT state FROM pic_effect WHERE id = $EFF")" = intent ] || fail "ask-all: the call started before the answer"
[ "$(ran)" = 0 ] || fail "ask-all: ran before the answer"
[ "$(pic answer "$(aid 1)" Allow)" = "answered $(aid 1)" ] || fail "ask-all: answer"
wait "$pid" || fail "ask-all: the run: $(cat "$T/err")"
pid=
[ "$(ran)" = 1 ] || fail "ask-all: ran $(ran) times"
[ "$(q "SELECT state FROM pic_effect WHERE id = $EFF")" = done ] || fail "ask-all: the effect"
[ "$(q "SELECT json_extract(allowed, '\$') FROM pic_permission")" = '[]' ] || fail "ask-all: Allow allowed for the conversation"
pic check > /dev/null || fail "ask-all: integrity"
printf 'PASS: ask-all asks before a command, and Allow runs it once\n'

# Deny: the model is told, nothing runs. Allow for this conversation: the next call of that tool
# in the conversation runs without asking.
SID=$(sid)
restart "sse:$T/bash.sse" "sse:$S/text.sse" "sse:$T/bash.sse" "sse:$S/text.sse" "sse:$T/bash.sse" "sse:$S/text.sse"
rm -f "$LEDGER"
bgpic ask --session "$SID" 'again' > "$T/out" 2> "$T/err"

until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
[ "$(pic answer "$(q "SELECT id FROM pic_ask WHERE state = 'open'")" Deny)" != "" ] || fail "deny: answer"
wait "$pid" || fail "deny: the run: $(cat "$T/err")"
pid=
[ "$(ran)" = 0 ] || fail "deny: it ran"
[ "$(result)" = "The person denied this bash call; it was not run." ] || fail "deny: the model saw: $(result)"
[ "$(q "SELECT is_error FROM pic_effect ORDER BY id DESC LIMIT 1")" = 1 ] || fail "deny: not an error"
bgpic ask --session "$SID" 'and again' > "$T/out" 2> "$T/err"

until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
pic answer "$(q "SELECT id FROM pic_ask WHERE state = 'open'")" 'Allow for this conversation' > /dev/null || fail "always: answer"
wait "$pid" || fail "always: the run: $(cat "$T/err")"
pid=
[ "$(ran)" = 1 ] || fail "always: it did not run"
[ "$(q "SELECT json_extract(allowed, '\$') FROM pic_permission WHERE session_id = '$SID'")" = '["bash"]' ] || fail "always: the allowance: $(q 'SELECT * FROM pic_permission')"
asks=$(q 'SELECT count(*) FROM pic_ask')
pic ask --session "$SID" 'once more' > /dev/null 2> "$T/err" || fail "always: third: $(cat "$T/err")"
[ "$(ran)" = 2 ] || fail "always: the allowed call did not run"
[ "$(q 'SELECT count(*) FROM pic_ask')" = "$asks" ] || fail "always: asked again"
printf '{"id":"g","type":"get_permission_mode"}\n' | pic --mode rpc --session "$SID" > "$T/rpc.out" 2> "$T/err" || fail "always: rpc: $(cat "$T/err")"
grep -qF '"data":{"permissionMode":"ask-all","allowed":["bash"]}' "$T/rpc.out" || fail "always: get_permission_mode: $(cat "$T/rpc.out")"
pic check > /dev/null || fail "deny: integrity"
rm -f "$LEDGER"
printf 'PASS: Deny tells the model and runs nothing; Allow for this conversation stops asking for that tool\n'

# ask-edits: a command runs, a write asks. read-only: a write is refused with no ask, a read runs.
serve "sse:$T/bash.sse" "sse:$T/write.sse" "sse:$S/text.sse"
bgpic --permission-mode ask-edits ask 'edit' > "$T/out" 2> "$T/err"

until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
[ "$(ran)" = 1 ] || fail "ask-edits: the command asked"
[ "$(q "SELECT title, body FROM pic_ask")" = "$(printf 'Allow write: notes.txt?|notes.txt\n\none\ntwo')" ] || fail "ask-edits: the ask: $(q 'SELECT title, body FROM pic_ask')"
pic answer "$(aid 1)" Allow > /dev/null
wait "$pid" || fail "ask-edits: the run: $(cat "$T/err")"
pid=
[ -f "$WS/notes.txt" ] || fail "ask-edits: not written"
rm -f "$LEDGER"
serve "sse:$T/write.sse" "sse:$T/read.sse" "sse:$S/text.sse"
echo seen > "$WS/seen.txt"
pic --permission-mode read-only ask 'look' > /dev/null 2> "$T/err" || fail "read-only: $(cat "$T/err")"
[ ! -f "$WS/notes.txt" ] || fail "read-only: written"
[ "$(q 'SELECT count(*) FROM pic_ask')" = 0 ] || fail "read-only: asked"
[ "$(q "SELECT result FROM pic_effect WHERE tool = 'write'")" = "This conversation is read-only (its permission mode): write was not run. Read, search and list only, or ask the person to change the mode." ] ||
    fail "read-only: write: $(q "SELECT result FROM pic_effect WHERE tool = 'write'")"
[ "$(q "SELECT state, is_error FROM pic_effect WHERE tool = 'read'")" = "done|0" ] || fail "read-only: read: $(q "SELECT * FROM pic_effect WHERE tool = 'read'")"
printf 'PASS: ask-edits asks before a write and not a command; read-only refuses a write and runs a read\n'

# The setting gives a new conversation its mode; a conversation that has run keeps its own;
# set_permission_mode changes it and refuses a mode that is not one.
serve "sse:$T/bash.sse" "sse:$S/text.sse" "sse:$S/text.sse"
pic ask 'before' > /dev/null 2> "$T/err" || fail "setting: before: $(cat "$T/err")"
OLD=$(sid)
"$PIC" settings permissionMode ask-all > /dev/null || fail "setting: set"
pic ask --session "$OLD" 'after' > /dev/null 2> "$T/err" || fail "setting: old: $(cat "$T/err")"
[ "$(q "SELECT count(*) FROM pic_permission WHERE session_id = '$OLD'")" = 0 ] || fail "setting: the old conversation took it"
pic ask 'new' > /dev/null 2> "$T/err" || fail "setting: new: $(cat "$T/err")"
NEW=$(sid)
[ "$(q "SELECT mode FROM pic_permission WHERE session_id = '$NEW'")" = ask-all ] || fail "setting: the new conversation: $(q 'SELECT * FROM pic_permission')"
"$PIC" settings permissionMode allow > /dev/null
printf '{"id":"s","type":"set_permission_mode","mode":"read-only"}\n{"id":"b","type":"set_permission_mode","mode":"sometimes"}\n{"id":"g","type":"get_permission_mode"}\n' |
    pic --mode rpc --session "$NEW" > "$T/rpc.out" 2> "$T/err" || fail "setting: rpc: $(cat "$T/err")"
grep -F '"id":"s"' "$T/rpc.out" | grep -qF '"success":true' || fail "setting: set_permission_mode: $(cat "$T/rpc.out")"
grep -F '"id":"b"' "$T/rpc.out" | grep -qF 'allow, ask-edits, ask-all or read-only' || fail "setting: a bad mode: $(cat "$T/rpc.out")"
grep -F '"id":"g"' "$T/rpc.out" | grep -qF '"permissionMode":"read-only"' || fail "setting: after set: $(cat "$T/rpc.out")"
if "$PIC" settings permissionMode sometimes > /dev/null 2>&1; then fail "setting: a bad value"; fi
if pic --permission-mode sometimes ask 'x' > /dev/null 2> "$T/err"; then fail "flag: a bad value"; fi
grep -qF 'allow, ask-edits, ask-all or read-only' "$T/err" || fail "flag: refused: $(cat "$T/err")"
rm -f "$LEDGER"
printf 'PASS: permissionMode gives a new conversation its mode, and set_permission_mode changes it\n'

# A PreToolUse hook's ask asks, in allow mode too, with its reason in the body.
cat > "$HOME/.pic/hooks.json" <<'EOF'
{"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "printf '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"ask\",\"permissionDecisionReason\":\"it writes outside\"}}'"}]}]}}
EOF
serve "sse:$T/bash.sse" "sse:$S/text.sse"
bgpic ask 'hooked' > "$T/out" 2> "$T/err"

until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
[ "$(ran)" = 0 ] || fail "hook ask: ran"
[ "$(q "SELECT body FROM pic_ask")" = "$(printf 'A hook asks: it writes outside\n\necho ran >> ../ledger')" ] || fail "hook ask: body: $(q 'SELECT body FROM pic_ask')"
pic answer "$(aid 1)" Allow > /dev/null
wait "$pid" || fail "hook ask: the run: $(cat "$T/err")"
pid=
[ "$(ran)" = 1 ] || fail "hook ask: did not run"
rm -f "$HOME/.pic/hooks.json" "$LEDGER"
printf 'PASS: a PreToolUse hook that asks puts the call to the person, in allow mode too\n'


# A hook's allow does not lift read-only: the write is still refused.
cat > "$HOME/.pic/hooks.json" <<'EOF'
{"hooks": {"PreToolUse": [{"matcher": "Write", "hooks": [{"type": "command", "command": "printf '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\"}}'"}]}]}}
EOF
serve "sse:$T/write.sse" "sse:$S/text.sse"
pic --permission-mode read-only ask 'hooked write' > /dev/null 2> "$T/err" || fail "hook allow: $(cat "$T/err")"
[ ! -f "$WS/notes.txt" ] || fail "hook allow: read-only wrote"
q "SELECT result FROM pic_effect WHERE tool = 'write'" | grep -qF 'read-only' || fail "hook allow: $(q "SELECT result FROM pic_effect")"
printf 'PASS: a hook that allows a write does not lift read-only\n'

# A hook that rewrites the call (updatedInput) and another that asks: the person is asked about the
# call as rewritten, and that is what runs.
cat > "$HOME/.pic/hooks.json" <<'EOF'
{"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [
  {"type": "command", "command": "printf '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"updatedInput\":{\"command\":\"echo rewritten >> ../ledger\"}}}'"},
  {"type": "command", "command": "printf '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"ask\"}}'"}]}]}}
EOF
serve "sse:$T/bash.sse" "sse:$S/text.sse"
bgpic ask 'rewrite' > /dev/null 2> "$T/err"

until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
[ "$(q "SELECT title FROM pic_ask")" = "Allow bash: echo rewritten >> ../ledger?" ] || fail "rewrite: asked about $(q 'SELECT title FROM pic_ask')"
pic answer "$(aid 1)" Allow > /dev/null
wait "$pid" || fail "rewrite: the run: $(cat "$T/err")"
pid=
[ "$(cat "$LEDGER")" = rewritten ] || fail "rewrite: ran $(cat "$LEDGER" 2>&1)"
rm -f "$HOME/.pic/hooks.json" "$LEDGER"
printf 'PASS: a call a hook rewrote is asked about, and run, as rewritten\n'

# The mode changes while a call waits: switched to read-only, an Allow does not run a change.
serve "sse:$T/write.sse" "sse:$S/text.sse"
bgpic --permission-mode ask-all ask 'switch' > /dev/null 2> "$T/err"

until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
printf '{"id":"s","type":"set_permission_mode","mode":"read-only"}\n' | pic --mode rpc --session "$(sid)" > /dev/null 2>&1
pic answer "$(aid 1)" Allow > /dev/null
wait "$pid" || fail "switch: the run: $(cat "$T/err")"
pid=
[ ! -f "$WS/notes.txt" ] || fail "switch: written after read-only"
q "SELECT result FROM pic_effect WHERE tool = 'write'" | grep -qF 'read-only' || fail "switch: $(q "SELECT result FROM pic_effect")"
printf 'PASS: a call waiting when the mode becomes read-only is refused, whatever the answer\n'

# A fork keeps the mode.
pic fork "$(sid)" > "$T/fork.out" 2> "$T/err" || fail "fork: $(cat "$T/err")"
[ "$(q "SELECT count(*) FROM pic_permission WHERE mode = 'read-only'")" = 2 ] || fail "fork: $(q 'SELECT * FROM pic_permission') $(cat "$T/fork.out")"
FORK=$(cat "$T/fork.out")
"$PIC" settings permissionMode ask-edits > /dev/null
restart "sse:$T/write.sse" "sse:$S/text.sse"
# (a dev build's question expires in 3 s, so a fork that wrongly asks fails here instead of waiting)
env PIC_TEST_PERM_EXPIRY_MS=3000 "$PIC" --db "$DB" --workspace "$WS" ask --session "$FORK" 'write on the fork' > /dev/null 2> "$T/err" || fail "fork: its request: $(cat "$T/err")"
"$PIC" settings permissionMode allow > /dev/null
[ "$(q "SELECT mode FROM pic_permission WHERE session_id = '$FORK'")" = read-only ] || fail "fork: the default replaced its mode: $(q 'SELECT * FROM pic_permission')"
[ "$(q "SELECT count(*) FROM pic_ask")" = 1 ] || fail "fork: asked instead of refused"
[ ! -f "$WS/notes.txt" ] || fail "fork: written"
printf 'PASS: a fork keeps the conversation'"'"'s permission mode, at its first request too\n'

# readOnlyTools names MCP tools only (test/pic/mcp.sh runs one): pic's own tools keep their kind,
# and a bare * names nothing, so it cannot open read-only to a command.
"$PIC" settings readOnlyTools '*, bash, mcp__docs__*' > /dev/null || fail "readOnlyTools: set"
serve "sse:$T/bash.sse" "sse:$S/text.sse"
rm -f "$LEDGER"
pic --permission-mode read-only ask 'listed' > /dev/null 2> "$T/err" || fail "readOnlyTools: $(cat "$T/err")"
[ "$(ran)" = 0 ] || fail "readOnlyTools: bash ran under read-only"
q "SELECT result FROM pic_effect WHERE tool = 'bash'" | grep -qF 'read-only' || fail "readOnlyTools: $(q 'SELECT result FROM pic_effect')"
"$PIC" settings --unset readOnlyTools > /dev/null
printf 'PASS: readOnlyTools does not make bash read-only, and a bare * names nothing\n'
[ "$FAULTS" = 1 ] || { printf 'PASS: permissions (release: the fault points and the expiry seam are dev-only)\n'; exit 0; }

# A tool's own calls (the test tool nest, as codemode's) go through the mode too: under ask-all the
# calling tool asks, then its inner command asks, keyed perm:n:ROW. Ctrl-C while the inner one
# waits leaves it a result and the journal whole.
export PIC_TEST_NESTED=1
tool_sse nest '{"rounds":[[{"tool":"bash","input":{"command":"echo inner >> ../ledger"}}]]}' > "$T/nest.sse"
serve "sse:$T/nest.sse" "sse:$S/text.sse"
rm -f "$LEDGER"
bgpic --permission-mode ask-all ask 'nested' > /dev/null 2> "$T/err"

until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
[ "$(q "SELECT title FROM pic_ask")" = "Allow nest?" ] || fail "nested: the outer ask: $(q 'SELECT title FROM pic_ask')"
pic answer "$(aid 1)" Allow > /dev/null
until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open' AND ask_key LIKE 'perm:n:%'" 1
[ "$(q "SELECT title FROM pic_ask WHERE ask_key LIKE 'perm:n:%'")" = "Allow bash: echo inner >> ../ledger?" ] || fail "nested: the inner ask"
[ "$(ran)" = 0 ] || fail "nested: ran before the answer"
pic answer "$(q "SELECT id FROM pic_ask WHERE ask_key LIKE 'perm:n:%'")" Allow > /dev/null
wait "$pid" || fail "nested: the run: $(cat "$T/err")"
pid=
[ "$(ran)" = 1 ] || fail "nested: the inner command ran $(ran) times"
serve "sse:$T/nest.sse" "sse:$S/text.sse"
bgpic --permission-mode ask-all ask 'nested' > /dev/null 2> "$T/err"

until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
pic answer "$(aid 1)" Allow > /dev/null
until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open' AND ask_key LIKE 'perm:n:%'" 1
kill -INT "$pid"
wait "$pid" 2> /dev/null || true
pid=
[ "$(q "SELECT count(*) FROM pic_nested_effect WHERE result IS NULL AND state != 'intent'")" = 0 ] || fail "nested ctrl-c: $(q 'SELECT id, state, result FROM pic_nested_effect')"
[ "$(q "SELECT state FROM pic_ask WHERE ask_key LIKE 'perm:n:%'")" = withdrawn ] || fail "nested ctrl-c: the ask $(q 'SELECT ask_key, state FROM pic_ask')"
pic check > /dev/null || fail "nested ctrl-c: integrity"
unset PIC_TEST_NESTED
rm -f "$LEDGER"
printf 'PASS: a tool'"'"'s own calls ask under ask-all, and Ctrl-C while one waits leaves the journal whole\n'

# With nobody there, the ask waits until it expires, then the call is denied, and pic says so.
serve "sse:$T/bash.sse" "sse:$S/text.sse"
env PIC_TEST_PERM_EXPIRY_MS=1500 "$PIC" --db "$DB" --workspace "$WS" --permission-mode ask-all ask 'alone' > "$T/out" 2> "$T/err" || fail "expiry: $(cat "$T/err")"
[ "$(ran)" = 0 ] || fail "expiry: it ran"
[ "$(result)" = "Nobody answered whether to run this bash call before the question expired; it was not run." ] || fail "expiry: the model saw: $(result)"
grep -qF "nobody answered" "$T/err" || fail "expiry: not said: $(cat "$T/err")"
printf 'PASS: an ask nobody answers expires, and the call is denied and said so\n'

# A crash just after the ask is opened, and one just after its answer is read: the call has not
# run; answered, the next owner runs it once and asks nothing again.
for at in 1 2; do
    serve "sse:$T/bash.sse" "sse:$S/text.sse"
    rm -f "$LEDGER"
    if [ "$at" = 1 ]; then
        rc=0
        env PIC_CRASH_AT="perm_ask:1" "$PIC" --db "$DB" --workspace "$WS" --permission-mode ask-all ask 'crash' > /dev/null 2>&1 || rc=$?
        [ "$rc" = 77 ] || fail "crash 1: exit $rc"
        [ "$(ask_state 1)" = "open||" ] || fail "crash 1: the ask: $(ask_state 1)"
        pic answer "$(aid 1)" Allow > /dev/null || fail "crash 1: answer"
    else
        env PIC_CRASH_AT="perm_ask:2" "$PIC" --db "$DB" --workspace "$WS" --permission-mode ask-all ask 'crash' > /dev/null 2>&1 &
        pid=$!
        pids="$pids $pid"
        until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
        pic answer "$(aid 1)" 'Allow for this conversation' > /dev/null || fail "crash 2: answer"
        rc=0
        wait "$pid" || rc=$?
        pid=
        [ "$rc" = 77 ] || fail "crash 2: exit $rc"
    fi
    [ "$(ran)" = 0 ] || fail "crash $at: ran before the crash"
    [ "$(q "SELECT state FROM pic_effect ORDER BY id DESC LIMIT 1")" = intent ] || fail "crash $at: the effect: $(q 'SELECT state FROM pic_effect')"
    pic run --session "$(sid)" > /dev/null 2> "$T/err" || fail "crash $at: resume: $(cat "$T/err")"
    [ "$(ran)" = 1 ] || fail "crash $at: ran $(ran) times"
    [ "$(q 'SELECT count(*) FROM pic_ask')" = 1 ] || fail "crash $at: asked again"
    if [ "$at" = 2 ]; then
        [ "$(q "SELECT json_extract(allowed, '\$') FROM pic_permission")" = '["bash"]' ] || fail "crash 2: the allowance: $(q 'SELECT * FROM pic_permission')"
    fi
    pic check > /dev/null || fail "crash $at: integrity"
done
printf 'PASS: a crash around the ask leaves the call unrun, and the next owner runs it once on the answer\n'

# Killed while it waits: the ask stays open and the call unrun; answered, the next owner runs it.
serve "sse:$T/bash.sse" "sse:$S/text.sse"
rm -f "$LEDGER"
bgpic --permission-mode ask-all ask 'kill' > /dev/null 2>&1

until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
kill -9 "$pid"
wait "$pid" 2> /dev/null || true
pid=
[ "$(ask_state 1)" = "open||" ] || fail "kill: the ask closed: $(ask_state 1)"
[ "$(ran)" = 0 ] || fail "kill: ran"
pic answer "$(aid 1)" Allow > /dev/null
pic run --session "$(sid)" > /dev/null 2> "$T/err" || fail "kill: resume: $(cat "$T/err")"
[ "$(ran)" = 1 ] || fail "kill: ran $(ran) times"
[ "$(q "SELECT status FROM pic_submission ORDER BY id DESC LIMIT 1")" = answered ] || fail "kill: the request"
pic check > /dev/null || fail "kill: integrity"
printf 'PASS: a run killed while it waits leaves the ask open and the call unrun\n'
# nothing this script started is left running
left=$(ps -eo pid=,args= | grep -F "$T/j" | grep -v grep || true)
[ -z "$left" ] || fail "pics left running: $left"
printf 'PASS: permissions\n'
