Skip to content
pi-c Artifact [681f01ff80]
Login

Artifact [681f01ff80]

Artifact 681f01ff80ae49dd21505857bc67f03beb5a0df5dc126b37025ee4d99e628b2c:


#!/bin/sh
# The inbox and pic attach (docs/design/grapevine.md): a message sent with
# pic send from another process reaches a running request exactly once,
# through the journal; abort cancels it; an expired message and an abort for
# a request that has ended are not run; a key is a message's identity (the
# same command again is one row, another command is refused); a full inbox
# and a journal of another schema refuse. pic attach rebuilds Pi's events
# from committed rows, catches up from a seq and follows, two at once, with
# -i sending stdin lines; it never blocks the run, holds no lease and writes
# nothing but inbox rows. Crashes at both inbox fault points never deliver
# twice. Usage: test/pic/grapevine.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-grapevine.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 grapevine.wake false > /dev/null # on by default: the sections that test waking unset it
spid=
pid=
apids=
cleanup() {
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    [ -n "$pid" ] && kill -9 "$pid" 2>/dev/null
    for a in $apids; do kill "$a" 2>/dev/null; done
    rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export ANTHROPIC_API_KEY=pic-grapevine-test-key PIC_PI_EXPORT=0
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))"
    reserve "$@"
}
reserve() { # SPEC...: a fresh server for the same journal and workspace
    [ -n "$spid" ] && { kill "$spid" 2>/dev/null || true; } # it may have ended already
    n=$((n + 1))
    mkdir "$T/log$n"
    LOG="$T/log$n"
    "$SERVER" "$T/port$n" "$LOG" 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" "$@"; }
await() { # FILE PATTERN: wait up to 30s for the fixed string PATTERN in FILE
    i=0
    until grep -qF -- "$2" "$1" 2>/dev/null; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for $2 in $1: $(cat "$1" 2>/dev/null)"
        sleep 0.05
    done
}
exists() { # FILE: wait up to 30s for it
    i=0
    until [ -e "$1" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for $1: $(cat "$T/err$n" 2>/dev/null)"
        sleep 0.05
    done
}
q() { "$SQLITE3" -cmd ".timeout 10000" "$DB" "$1"; } # waits out a pic's write lock instead of failing
SQLITE3=${SQLITE3:-sqlite3}
until_sql() { # SQL VALUE: wait up to 30s for the query to print VALUE
    i=0
    until [ "$(q "$1")" = "$2" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for [$1] = $2: $(q "$1")"
        sleep 0.05
    done
}
hold() { # ARGS...: pic --json ask 'hold on' ARGS in the background, its bash call holding until release
    rm -f "$WS/started" "$WS/release"
    "$PIC" --db "$DB" --workspace "$WS" --model fake/m --json ask "$@" 'hold on' > "$T/ev$n" 2> "$T/err$n" &
    pid=$!
    exists "$WS/started"
    SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
}
finish() { # wait for pic; its status in rc
    rc=0
    wait "$pid" || rc=$?
    pid=
}
count() { grep -cF -- "$2" "$1" || true; }
# The bytes of text.sse up to its first text delta ("Hello"): served, then held, a reply that
# streams and never ends.
cut=$(awk '/text_delta/ { print total + length($0) + 2; exit } { total += length($0) + 1 }' "$S/text.sse")

# A steer from another process reaches the running request once, after the
# tool result; the same key and command again is the same row; the same key
# with another command is refused and writes nothing.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
hold
out=$(pic send --key k1 steer 'steer one' 2> "$T/k1.err") || fail "send: $out"
[ "$out" = "pending k1" ] || fail "send: printed $out"
grep -qF "Delivered into the request running in conversation $SID" "$T/k1.err" || fail "send: standing: $(cat "$T/k1.err")"
until_sql "SELECT state FROM pic_inbox WHERE msg_key = 'k1'" delivered
out=$(pic send --key k1 steer 'steer one') || fail "retry: $out"
[ "$out" = "delivered k1" ] || fail "retry: printed $out"
if pic send --key k1 steer 'another' 2> "$T/conflict"; then fail "conflict: accepted"; fi
grep -qF 'key k1 was used for another command' "$T/conflict" || fail "conflict: $(cat "$T/conflict")"
[ "$(q "SELECT count(*) FROM pic_inbox")" = 1 ] || fail "conflict: rows $(q 'SELECT count(*) FROM pic_inbox')"
[ "$(q "SELECT response FROM pic_inbox WHERE msg_key = 'k1'")" = '{"type":"response","command":"steer","success":true,"data":{"disposition":"queued"}}' ] ||
    fail "steer: response $(q "SELECT response FROM pic_inbox")"
[ "$(q "SELECT count(*) FROM pic_inbox i JOIN pic_queued u ON u.id = i.queued_id WHERE u.text = 'steer one'")" = 1 ] ||
    fail "steer: queued_id"
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "steer: exit $rc: $(cat "$T/err$n")"
r2="$LOG/2.req"
[ "$(count "$r2" '{"role":"user","content":"steer one"}')" = 1 ] || fail "steer: request 2: $(cat "$r2")"
[ ! -e "$LOG/3.req" ] || fail "steer: an extra request"
[ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body = 'steer one'")" = 1 ] || fail "steer: entries"
[ "$(count "$T/ev$n" '"response"')" = 0 ] || fail "steer: the sender's response went to the owner's stdout"
pic check > /dev/null || fail "steer: integrity"
printf 'PASS: a steer sent from another process reaches the run once; a key is one message, another command under it is refused\n'

# pic send --wait abort cancels the running request.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
hold
out=$(pic send --wait abort) || fail "abort: $out"
[ "$out" = '{"type":"response","command":"abort","success":true}' ] || fail "abort: printed $out"
finish
[ "$rc" != 0 ] || fail "abort: the run was not cancelled"
[ "$(q "SELECT status || ' ' || error FROM pic_submission")" = "failed cancelled" ] || fail "abort: $(q 'SELECT status, error FROM pic_submission')"
pic check > /dev/null || fail "abort: integrity"
printf 'PASS: an abort sent from another process cancels the run\n'

# Sent while nothing runs: a steer stays pending (and expires), an abort
# names no request. When a request next runs there, neither is run.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
pic submit k0 'first' > /dev/null
q "UPDATE pic_submission SET status = 'failed', error = 'set aside'" # no request runs; the conversation stays
SID=$(q "SELECT id FROM pic_session")
pic send --session "$SID" --key late --expires 1 steer 'too late' > /dev/null
[ "$(pic send --session "$SID" --key idle abort)" = "refused idle" ] || fail "idle: an abort with nothing running"
[ "$(q "SELECT group_concat(state) FROM pic_inbox")" = "pending,refused" ] || fail "idle: $(q 'SELECT state FROM pic_inbox')"
sleep 1.2
hold --session "$SID"
until_sql "SELECT group_concat(state, ' ') FROM (SELECT state FROM pic_inbox ORDER BY id)" "expired refused"
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "idle: exit $rc: $(cat "$T/err$n")"
! grep -qF 'too late' "$LOG"/*.req || fail "idle: an expired steer was sent"
q "SELECT response FROM pic_inbox WHERE msg_key = 'late'" | grep -qF '"error":"expired before it was delivered"' ||
    fail "idle: expired response $(q "SELECT response FROM pic_inbox")"
q "SELECT response FROM pic_inbox WHERE msg_key = 'idle'" | grep -qF '"error":"nothing to abort' || fail "idle: abort response"
pic check > /dev/null || fail "idle: integrity"
printf 'PASS: an expired steer and an abort with no request to abort are not run\n'

# A key names one message in the whole journal: the same key and command to
# another conversation is refused, not taken as a retry.
pic submit kB 'other' > /dev/null
SID2=$(q "SELECT session_id FROM pic_submission WHERE request_key = 'kB'")
[ "$SID2" != "$SID" ] || fail "keys: one conversation"
if pic send --session "$SID2" --key late --expires 1 steer 'too late' 2> "$T/xkey"; then fail "keys: reused across conversations"; fi
grep -qF 'key late was used for another command' "$T/xkey" || fail "keys: $(cat "$T/xkey")"
printf 'PASS: a key reused for another conversation is refused\n'

# pic send --wait returns once the message expires, though nothing runs to settle it.
pic send --session "$SID2" --key wexp --wait --expires 1 steer 'never' > "$T/wexp" 2>&1 &
wpid=$!
i=0
while kill -0 "$wpid" 2>/dev/null; do
    i=$((i + 1))
    [ "$i" -lt 200 ] || { kill "$wpid"; fail "--wait: still waiting long after the expiry"; }
    sleep 0.05
done
wrc=0
wait "$wpid" || wrc=$?
[ "$wrc" = 1 ] || fail "--wait: exit $wrc"
grep -qF '"error":"expired before it was delivered"' "$T/wexp" || fail "--wait: $(cat "$T/wexp")"
[ "$(q "SELECT state FROM pic_inbox WHERE msg_key = 'wexp'")" = expired ] || fail "--wait: the row"
printf 'PASS: pic send --wait ends at the expiry\n'

# A full inbox refuses; a journal of another schema is refused untouched; a
# command the inbox does not take is refused.
k=0
while [ "$k" -lt 100 ]; do
    k=$((k + 1))
    printf '{"type":"follow_up","message":"m%s"}\n' "$k"
done > "$T/many"
k=0
while read -r line; do
    pic send --session "$SID" "$line" > /dev/null || fail "full: send $k"
    k=$((k + 1))
done < "$T/many"
if pic send --session "$SID" steer 'one more' 2> "$T/full"; then fail "full: accepted the 101st"; fi
grep -qF 'is full' "$T/full" || fail "full: $(cat "$T/full")"
if pic send --session "$SID" '{"type":"get_state"}' 2> "$T/kind"; then fail "kind: get_state was accepted"; fi
grep -qF 'the inbox takes prompt, steer, follow_up and abort, not get_state' "$T/kind" || fail "kind: $(cat "$T/kind")"
cp "$DB" "$T/old.sqlite"
"$SQLITE3" "$T/old.sqlite" "UPDATE pic_meta SET value = '99' WHERE key = 'schema_version'"
before=$("$SQLITE3" "$T/old.sqlite" "SELECT count(*) FROM pic_inbox")
if "$PIC" --db "$T/old.sqlite" --workspace "$WS" send --session "$SID" steer x 2> "$T/schema"; then fail "schema: accepted"; fi
grep -qF 'written by a newer pic' "$T/schema" || fail "schema: $(cat "$T/schema")"
[ "$("$SQLITE3" "$T/old.sqlite" "SELECT count(*) || value FROM pic_inbox, pic_meta WHERE key = 'schema_version'")" = "${before}99" ] ||
    fail "schema: the journal was changed"
printf 'PASS: a full inbox, another schema and an unsupported command are refused\n'

# A prompt through the inbox follows Pi's rules while a request runs: without streamingBehavior it
# is refused at once, with "steer" it is a steer. Sent while nothing runs, it waits, and the next
# request run there takes it as a follow-up: it runs after that request, once.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
hold
[ "$(pic send --key p1 prompt 'no behavior')" = "refused p1" ] || fail "prompt: accepted while running with no behavior"
q "SELECT response FROM pic_inbox WHERE msg_key = 'p1'" | grep -qF '"command":"prompt","success":false,"error":"Agent is already processing.' ||
    fail "prompt: refusal $(q "SELECT response FROM pic_inbox WHERE msg_key = 'p1'")"
pic send --key p2 '{"type":"prompt","message":"as a steer","streamingBehavior":"steer"}' > /dev/null || fail "prompt: steer send"
until_sql "SELECT state FROM pic_inbox WHERE msg_key = 'p2'" delivered
q "SELECT response FROM pic_inbox WHERE msg_key = 'p2'" | grep -qF '"command":"prompt","success":true' ||
    fail "prompt: steer response $(q "SELECT response FROM pic_inbox WHERE msg_key = 'p2'")"
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "prompt: exit $rc: $(cat "$T/err$n")"
[ "$(count "$LOG/2.req" '{"role":"user","content":"as a steer"}')" = 1 ] || fail "prompt: steer not in request 2"
[ "$(pic send --key p3 prompt 'while idle' 2> "$T/p3.err")" = "pending p3" ] || fail "prompt: idle send"
grep -qF "Waiting: nothing is running in conversation $SID and no request was started as grapevine.wake is off" "$T/p3.err" ||
    fail "prompt: idle standing: $(cat "$T/p3.err")"
[ "$(q "SELECT expires_ms - created_ms FROM pic_inbox WHERE msg_key = 'p3'")" = 86400000 ] || fail "prompt: idle expiry"
pic --model fake/m ask --session "$SID" 'next' > /dev/null 2> "$T/next" || fail "prompt: next request: $(cat "$T/next")"
[ "$(q "SELECT state FROM pic_inbox WHERE msg_key = 'p3'")" = delivered ] || fail "prompt: idle not delivered"
[ "$(count "$LOG/4.req" '{"role":"user","content":"while idle"}')" = 1 ] || fail "prompt: idle prompt not run after: $(ls "$LOG")"
[ "$(count "$LOG/3.req" 'while idle')" = 0 ] || fail "prompt: idle prompt ran inside the next request"
[ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body = 'while idle'")" = 1 ] || fail "prompt: idle entries"
[ ! -e "$LOG/5.req" ] || fail "prompt: an extra request"
pic check > /dev/null || fail "prompt: integrity"
# pic --mode rpc delivers what waits when it next runs a request, as any pic does.
[ "$(pic send --key p4 prompt 'for rpc')" = "pending p4" ] || fail "prompt: rpc send"
printf '{"type":"prompt","message":"rpc asks"}\n' | pic --model fake/m --mode rpc --session "$SID" > "$T/rpc" 2> "$T/rpc.err" &
rpid=$!
until_sql "SELECT state FROM pic_inbox WHERE msg_key = 'p4'" delivered
until_sql "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body = 'for rpc'" 1
until_sql "SELECT count(*) FROM pic_submission WHERE status = 'admitted'" 0
kill "$rpid" 2>/dev/null || :
wait "$rpid" 2>/dev/null || :
printf 'PASS: a prompt through the inbox: refused or a steer while a request runs, the next request after it when sent idle (pic --mode rpc too)\n'

# With the watch disabled, the stat fallback still delivers during a tool call.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
export PIC_NO_WATCH=1
hold
unset PIC_NO_WATCH
pic send --key w steer 'by stat' > /dev/null
until_sql "SELECT state FROM pic_inbox WHERE msg_key = 'w'" delivered
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "stat: exit $rc"
[ "$(count "$LOG/2.req" '{"role":"user","content":"by stat"}')" = 1 ] || fail "stat: request 2"
printf 'PASS: with no file watch, the stat fallback delivers\n'

# Races: eight senders at once each deliver once; a second pic that tries
# to run the conversation leaves it to its owner, which delivers; a
# sender that meets another process's write lock waits for it.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
hold
pic send --key early steer 'to the owner' > /dev/null
"$PIC" --db "$DB" --workspace "$WS" --model fake/m run --session "$SID" > /dev/null 2> "$T/second" || :
[ ! -e "$LOG/2.req" ] || fail "race: a second pic ran the conversation: $(cat "$T/second")"
spids=
for k in 1 2 3 4 5 6 7 8; do
    "$PIC" --db "$DB" --workspace "$WS" send --key "c$k" follow_up "parallel $k" > /dev/null &
    spids="$spids $!"
done
for p in $spids; do wait "$p" || fail "race: a sender failed"; done
rm -f "$T/locked"
(printf '.timeout 30000\nBEGIN IMMEDIATE;\nINSERT INTO pic_meta(key, value) VALUES (%s, %s);\n.shell touch %s\n' "'held'" "'1'" "$T/locked"
    sleep 2; printf 'COMMIT;\n') | "$SQLITE3" "$DB" &
lpid=$!
exists "$T/locked"
t0=$(date +%s)
pic send --key held steer 'after the lock' > /dev/null || fail "race: the sender gave up on a held lock"
t1=$(date +%s)
wait "$lpid"
[ $((t1 - t0)) -ge 1 ] || fail "race: the sender did not wait for the lock"
until_sql "SELECT count(*) FROM pic_inbox WHERE state = 'delivered'" 10
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "race: exit $rc: $(cat "$T/err$n")"
for k in 1 2 3 4 5 6 7 8; do
    [ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body = 'parallel $k'")" = 1 ] || fail "race: parallel $k delivered $(q "SELECT count(*) FROM pic_entry WHERE body = 'parallel $k'") times"
done
[ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body IN ('after the lock', 'to the owner')")" = 2 ] || fail "race: the steers"
pic check > /dev/null || fail "race: integrity"
printf 'PASS: concurrent senders deliver once each; a second pic leaves the run alone; a held write lock is waited for\n'

# pic attach, two at once, follows a run from its start: the committed
# events in order, the run unblocked, no lease held, nothing written.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
hold
"$PIC" --db "$DB" --workspace "$WS" attach --session "$SID" > "$T/a1" 2> "$T/a1.err" &
a1=$!
"$PIC" --db "$DB" --workspace "$WS" attach -c --format text > "$T/a2" 2> "$T/a2.err" &
a2=$!
apids="$a1 $a2"
await "$T/a1" '"type":"tool_execution_start"'
await "$T/a2" '-> bash touch started'
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "attach: the run: exit $rc: $(cat "$T/err$n")"
await "$T/a1" '"type":"agent_end"'
await "$T/a2" '(done)'
# Its lease is free while both are still attached: another request runs.
"$PIC" --db "$DB" --workspace "$WS" --model fake/m ask --session "$SID" 'again' > /dev/null 2> "$T/again" ||
    fail "attach: held the lease: $(cat "$T/again")"
await "$T/a1" '"text":"again"'
# The second request's closing events follow its text: wait for its agent_end before stopping attach.
i=0
until [ "$(grep -c '^{"type":"agent_end"' "$T/a1" 2>/dev/null)" -ge 2 ]; do
    i=$((i + 1))
    [ "$i" -lt 600 ] || fail "attach: the second agent_end never came: $(cat "$T/a1")"
    sleep 0.05
done
kill "$a1" "$a2" 2>/dev/null || :
wait "$a1" 2>/dev/null || :
wait "$a2" 2>/dev/null || :
apids=
# The reply's streamed text (message_start and message_update for it) shows when a pass catches it.
types=$(grep -v '^{"type":"message_update"\|^{"type":"message_start","message":{"role":"assistant"' "$T/a1" |
    sed -n 's/^{"type":"\([a-z_]*\)".*/\1/p' | tr '\n' ' ')
want="agent_start message_start message_end message_end tool_execution_start tool_execution_end message_end agent_end agent_start message_start message_end message_end agent_end "
[ "$types" = "$want" ] || fail "attach: events: $types"
grep -qF '{"type":"tool_execution_end","seq":3,"toolCallId":"toolu_hold","toolName":"bash","result":{"content":[{"type":"text","text":"held' "$T/a1" ||
    fail "attach: tool end: $(cat "$T/a1")"
# The same events the owner sent for them, apart from where attach adds seq.
grep '"type":"tool_execution_start"' "$T/ev$n" > "$T/owner.start"
grep '"type":"tool_execution_start"' "$T/a1" > "$T/attach.start"
cmp -s "$T/owner.start" "$T/attach.start" || fail "attach: tool start differs: $(cat "$T/owner.start") vs $(cat "$T/attach.start")"
grep -qF '[1] you: hold on' "$T/a2" && grep -qF '    = held' "$T/a2" && grep -qF 'pic: ' "$T/a2" || fail "attach: text: $(cat "$T/a2")"
[ ! -s "$T/a1.err" ] && [ ! -s "$T/a2.err" ] || fail "attach: stderr: $(cat "$T/a1.err" "$T/a2.err")"
# Catching up from a seq: only what came after it, the request's end once.
pic attach --no-follow --from 3 > "$T/from"
[ "$(sed -n 's/^{"type":"\([a-z_]*\)".*/\1/p' "$T/from" | tr '\n' ' ')" = "message_end agent_end agent_start message_start message_end message_end agent_end " ] ||
    fail "attach --from: $(cat "$T/from")"
! grep -q '"seq":[123],' "$T/from" || fail "attach --from: repeated an entry"
# Nothing written: the journal's dump is the same before and after.
"$SQLITE3" "$DB" .dump > "$T/dump1"
pic attach --no-follow --from 0 > /dev/null
pic attach --no-follow --format text > /dev/null
"$SQLITE3" "$DB" .dump > "$T/dump2"
cmp -s "$T/dump1" "$T/dump2" || fail "attach: wrote to the journal"
pic check > /dev/null || fail "attach: integrity"
printf 'PASS: two attaches follow a run from committed rows, catch up from a seq, hold no lease and write nothing\n'

# A reader that stops reading never pins the journal: attach writes outside
# its read transactions, so a checkpoint still truncates the WAL. Linux caps one argument at
# 128 KB, so the message stays under that.
big=$(awk 'BEGIN { for (i = 0; i < 3000; i++) printf "padding line %d of a long message. ", i }')
pic submit kbig "$big" > /dev/null
pic submit kbig2 "$big" --session "$(q "SELECT session_id FROM pic_submission WHERE request_key = 'kbig'")" > /dev/null 2>&1 || :
rm -f "$T/stall"
mkfifo "$T/stall"
sleep 600 < "$T/stall" &
stall=$!
"$PIC" --db "$DB" --workspace "$WS" attach --session "$(q "SELECT session_id FROM pic_submission WHERE request_key = 'kbig'")" --from 0 > "$T/stall" 2> /dev/null &
apids="$!"
sleep 1
pic submit kafter 'after' > /dev/null
ck=$(q "PRAGMA wal_checkpoint(TRUNCATE)")
kill "$apids" "$stall" 2>/dev/null || :
wait "$apids" 2>/dev/null || :
wait "$stall" 2>/dev/null || :
apids=
case "$ck" in 0\|*) ;; *) fail "stalled attach: the checkpoint was blocked: $ck" ;; esac
printf 'PASS: a stalled attach reader does not pin the WAL\n'

# Without -i, a pipe on stdin is a lifeline: attach follows while its other
# end is open and exits once it closes (the interface's follower, ssh).
rm -f "$T/life"
mkfifo "$T/life"
"$PIC" --db "$DB" --workspace "$WS" attach < "$T/life" > /dev/null 2>&1 &
lpid=$!
exec 7> "$T/life"
sleep 1
kill -0 "$lpid" 2>/dev/null || fail "lifeline: attach exited while its stdin was open"
exec 7>&-
lw=0
while kill -0 "$lpid" 2>/dev/null && [ $lw -lt 100 ]; do sleep 0.1; lw=$((lw + 1)); done
if kill -0 "$lpid" 2>/dev/null; then kill "$lpid"; fail "lifeline: attach kept following after its stdin closed"; fi
wait "$lpid" 2>/dev/null || :
printf 'PASS: attach without -i ends when the pipe on its stdin closes\n'

# pic attach -i: a line typed is a steer for the running request; it
# exits when its input has ended and the message has settled.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
hold
printf 'look here\n' | pic attach -i --format text > "$T/ai" 2> "$T/ai.err" || fail "attach -i: $(cat "$T/ai.err")"
grep -qF '(steer sent)' "$T/ai" && grep -qF '(steer delivered)' "$T/ai" || fail "attach -i: $(cat "$T/ai")"
[ "$(q "SELECT sender || ' ' || state FROM pic_inbox")" = "attach delivered" ] || fail "attach -i: $(q 'SELECT * FROM pic_inbox')"
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "attach -i: exit $rc"
[ "$(count "$LOG/2.req" '{"role":"user","content":"look here"}')" = 1 ] || fail "attach -i: request 2: $(cat "$LOG/2.req")"
printf '/abort\n' | pic attach -i --format text > "$T/ai2"
grep -qF '(abort not delivered: nothing to abort' "$T/ai2" || fail "attach -i abort when idle: $(cat "$T/ai2")"
pic check > /dev/null || fail "attach -i: integrity"
printf 'PASS: pic attach -i steers the running request from stdin\n'

# pic attach -i on an idle conversation: a line starts a request (a pic ask
# child takes the lease), its output is shown, and /abort cancels it.
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" "sse:$S/text.sse"
pic --model fake/m ask 'first' > /dev/null 2>&1 || fail "idle -i: setup"
printf 'second\n' | pic --model fake/m attach -i --format text > "$T/idle" 2> "$T/idle.err" || fail "idle -i: $(cat "$T/idle.err")"
grep -qF '(starting a request)' "$T/idle" && grep -qF 'you: second' "$T/idle" && grep -qF 'pic: Hello' "$T/idle" &&
    grep -qF '(done)' "$T/idle" || fail "idle -i: $(cat "$T/idle")"
[ "$(q "SELECT group_concat(status) FROM pic_submission")" = "answered,answered" ] || fail "idle -i: $(q 'SELECT status FROM pic_submission')"
[ "$(q "SELECT count(*) FROM pic_session")" = 1 ] || fail "idle -i: another conversation"
rm -f "$T/in" "$WS/started"
mkfifo "$T/in"
"$PIC" --db "$DB" --workspace "$WS" --model fake/m attach -i --format text < "$T/in" > "$T/ab" 2> "$T/ab.err" &
apids=$!
exec 4> "$T/in"
printf 'hold on\n' >&4
exists "$WS/started"
printf '/abort\n' >&4
await "$T/ab" '(request cancelled)'
exec 4>&-
wait "$apids" || fail "idle -i abort: attach exit: $(cat "$T/ab.err")"
apids=
grep -qF '(abort delivered)' "$T/ab" || fail "idle -i abort: $(cat "$T/ab")"
[ "$(q "SELECT status || ' ' || error FROM pic_submission ORDER BY id DESC LIMIT 1")" = "failed cancelled" ] || fail "idle -i abort: status"
touch "$WS/release"
printf '{"type":"prompt","message":"third"}\n' | pic --model fake/m attach -i --format text > "$T/jp" 2> "$T/jp.err" || fail "idle -i prompt: $(cat "$T/jp.err")"
grep -qF '(starting a request)' "$T/jp" && grep -qF 'you: third' "$T/jp" && grep -qF '(done)' "$T/jp" || fail "idle -i prompt: $(cat "$T/jp")"
[ "$(q "SELECT count(*) FROM pic_inbox WHERE json_extract(command, '\$.message') = 'third'")" = 0 ] || fail "idle -i prompt: went to the inbox"
pic check > /dev/null || fail "idle -i: integrity"
printf 'PASS: pic attach -i starts a request on an idle conversation (from a line or Pi'"'"'s prompt), shows it, and /abort cancels it\n'

# A request attach -i started that fails (here: no such model) is reported,
# and what was sent to it meanwhile is not left waiting: attach exits.
pic --model nosuch/model attach -i --format text > "$T/fail" 2>&1 <<'IN' &
first
second
IN
fpid=$!
i=0
while kill -0 "$fpid" 2>/dev/null; do
    i=$((i + 1))
    [ "$i" -lt 600 ] || { kill "$fpid"; fail "failed start: attach -i never exited: $(cat "$T/fail")"; }
    sleep 0.05
done
wait "$fpid" || :
grep -qF '(the request did not finish' "$T/fail" || fail "failed start: no error shown: $(cat "$T/fail")"
[ "$(q "SELECT count(*) FROM pic_inbox WHERE state = 'pending' AND sender = 'attach'")" = 0 ] ||
    fail "failed start: a message left pending: $(q "SELECT msg_key, command FROM pic_inbox WHERE state = 'pending'")"
printf 'PASS: a request attach -i started that fails is reported, and nothing is left waiting for it\n'

# A follower that comes in mid-request (--from end) is told a request runs; the reply's text
# streams to it from the owner's .live file before it is committed; the owner killed mid-reply is
# reported interrupted, and when pic run takes the request up it is started again and ends.
serve "sse:$S/bash_hold.sse" "hang:$S/text.sse:$cut" "sse:$S/text.sse"
hold
"$PIC" --db "$DB" --workspace "$WS" attach --session "$SID" --from end > "$T/live" 2> "$T/live.err" &
apids=$!
await "$T/live" '"type":"agent_start"'
grep -qF "\"conversation\":\"$SID\"" "$T/live" || fail "live: agent_start: $(cat "$T/live")"
pic sessions --json | grep -qF '"live":true' || fail "live: pic sessions --json: $(pic sessions --json)"
touch "$WS/release"
await "$T/live" '"delta":"Hello"'
[ "$(sed -n 's/^{"type":"\([a-z_]*\)".*/\1/p' "$T/live" | tr '\n' ' ')" = "agent_start tool_execution_start tool_execution_end message_start message_update " ] ||
    fail "live: events before the reply is committed: $(cat "$T/live")"
grep -qF '{"type":"message_start","message":{"role":"assistant","content":[]}}' "$T/live" || fail "live: message_start"
kill -9 "$pid"
finish
await "$T/live" '"status":"interrupted"'
grep -qF '{"type":"agent_end","messages":[],"request":' "$T/live" || fail "live: interrupted: $(grep agent_end "$T/live")"
"$PIC" --db "$DB" --workspace "$WS" --model fake/m run --session "$SID" > /dev/null 2> "$T/resume" || fail "live: resume: $(cat "$T/resume")"
await "$T/live" '"status":"answered"'
kill "$apids" 2>/dev/null || :
wait "$apids" 2>/dev/null || :
apids=
[ "$(grep -c '^{"type":"agent_start"' "$T/live")" = 2 ] || fail "live: taken up again: $(cat "$T/live")"
[ ! -s "$T/live.err" ] || fail "live: stderr: $(cat "$T/live.err")"
pic check > /dev/null || fail "live: integrity"
printf 'PASS: a follower from the end sees the running request, its streamed text, its owner'"'"'s death and its resumption\n'

# The terminal on a conversation another pic is running: it shows the request running, a line
# typed steers it, the reply streams in before it is committed, and when the owner is killed the
# terminal offers to resume the request, which Enter does, here.
if [ -n "${DRIVE:-}" ]; then
    # The first delta is written a moment after the request reaches the server; a slow machine does
    # that anyway, and this makes it so (dev build): the owner must not be killed before the
    # terminal has drawn it.
    [ "$FAULTS" = 1 ] && export PIC_RUN_AT="live-first:sleep 1"
    serve "sse:$S/bash_hold.sse" "hang:$S/text.sse:$cut" "sse:$S/text.sse"
    hold
    rm -f "$T/tui.in"
    mkfifo "$T/tui.in"
    "$DRIVE" "$T/tui.tx" 120 40 "$PIC" --db "$DB" --workspace "$WS" --model fake/m --tui-mode regular -c \
        < "$T/tui.in" > "$T/tui.out" 2>&1 &
    tp=$!
    apids=$tp
    exec 4> "$T/tui.in"
    say() { printf '%s\n' "$@" >&4; }
    say 'expect Running in another pic' 'send /resume\r' 'expect running in another pic' 'send \e' 'send steer from the terminal\r'
    until_sql "SELECT state FROM pic_inbox WHERE json_extract(command, '\$.message') = 'steer from the terminal'" delivered
    touch "$WS/release"
    say 'expect Hello'
    await "$LOG/2.req" 'steer from the terminal'
    await "$T/tui.tx" Hello # the reply is drawn while it streams, before its owner is killed (not when it reaches the server)
    [ "$(q "SELECT count(*) FROM pic_submission")" = 1 ] || fail "tui: the steer started a request of its own"
    kill -9 "$pid"
    finish
    say 'expect Enter to resume it here' 'send \r' 'expect world' 'send \x04\x04'
    exec 4>&-
    trc=0
    wait "$tp" || trc=$?
    apids=
    if [ "$trc" != 0 ]; then # what the screen last showed, and the journal, for an intermittent failure
        printf '%s\n' '--- tui: last of the terminal transcript' >&2
        tail -c 4000 "$T/tui.tx" | tr -d '\033' | tr -c '[:print:]\n' ' ' >&2
        printf '\n%s\n' '--- tui: the journal' >&2
        "$PIC" --db "$DB" --workspace "$WS" log 2>&1 | tail -30 >&2
        fail "tui: driver exit $trc: $(cat "$T/tui.out")"
    fi
    [ "$(q "SELECT status FROM pic_submission")" = answered ] || fail "tui: not resumed: $(q 'SELECT status FROM pic_submission')"
    [ "$(count "$LOG/3.req" 'steer from the terminal')" = 1 ] || fail "tui: the resumed request lost the steer"
    pic check > /dev/null || fail "tui: integrity"
    unset PIC_RUN_AT
    printf 'PASS: the terminal on a conversation another pic runs shows it running and streaming, steers it, and resumes it when that pic dies\n'
fi

# Peers (stage 4). tool_sse NAME INPUT: a reply that calls tool NAME with the JSON INPUT.
tool_sse() {
    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_send","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'
}
tool_sse send_message '{"to":"peer-b","message":"found it"}' > "$T/send_b.sse"
tool_sse send_message '{"to":"peer-a","message":"thanks"}' > "$T/send_a.sse"
peer() { "$PIC" --db "$DB" --workspace "$WS" --model fake/m "$@"; } # send_message is a default tool
# A UserPromptSubmit hook that logs each input and, while $T/refuse exists, refuses a peer's.
mkdir -p "$T/h"
cat > "$T/h/ups.sh" <<SH
#!/bin/sh
in=\$(cat)
printf '%s\n' "\$in" >> "$T/h/ups.log"
if [ -e "$T/refuse" ] && printf '%s' "\$in" | grep -q '"origin":"session:'; then echo "no peers today" >&2; exit 2; fi
exit 0
SH
printf '{"hooks":{"UserPromptSubmit":[{"hooks":[{"type":"command","command":"sh %s/h/ups.sh"}]}]}}\n' "$T" > "$HOME/.pic/hooks.json"

# One conversation messages another in its workspace: the row names it as sender with one hop, the
# idle receiver is not woken (grapevine.wake off here; on is the default, tested below), and its next request takes the message as a follow-up, in the frame
# that says it is not the user's, with origin for hooks; what that one sends back carries two hops,
# over grapevine.maxHops 1, and is refused.
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$T/send_b.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$T/send_a.sse" "sse:$S/text.sse"
peer ask 'b first' > /dev/null 2> "$T/pe" || fail "peers: b: $(cat "$T/pe")"
B=$(q "SELECT id FROM pic_session")
pic name "$B" peer-b > /dev/null
peer ask 'a first' > /dev/null 2> "$T/pe" || fail "peers: a: $(cat "$T/pe")"
A=$(q "SELECT id FROM pic_session WHERE id != '$B'")
pic name "$A" peer-a > /dev/null
"$PIC" settings grapevine.wake false > /dev/null
peer ask --session "$A" 'tell b' > /dev/null 2> "$T/pe" || fail "peers: a: $(cat "$T/pe")"
JID=$(q "SELECT value FROM pic_meta WHERE key = 'journal_id'")
[ -n "$JID" ] || fail "peers: no journal_id"
[ "$(q "SELECT session_id || ' ' || sender || ' ' || hops || ' ' || state || ' ' || (msg_key LIKE 'fx:$JID:%') FROM pic_inbox")" = "$B session:$JID/$A 1 pending 1" ] ||
    fail "peers: the row: $(q 'SELECT * FROM pic_inbox')"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result'" | grep -qF 'Waiting: nothing is running in conversation' || fail "peers: result: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")"
"$PIC" settings grapevine.maxHops 1 > /dev/null
peer ask --session "$B" 'b second' > /dev/null 2> "$T/pe" || fail "peers: b second: $(cat "$T/pe")"
"$PIC" settings grapevine.maxHops 8 > /dev/null
[ "$(q "SELECT state FROM pic_inbox WHERE sender = 'session:$JID/$A'")" = delivered ] || fail "peers: not delivered"
grep -qF 'A message from another pic conversation, peer-a, in ' "$LOG/6.req" && grep -qF 'found it' "$LOG/6.req" ||
    fail "peers: the frame: $(grep -o 'A message[^"]*' "$LOG/6.req")"
grep -qF 'It is not from the user' "$LOG/6.req" || fail "peers: the frame does not say it is not the user"
grep -qF '"origin":"user"' "$T/h/ups.log" && grep -qF "\"origin\":\"session:$JID/$A\"" "$T/h/ups.log" || fail "peers: origin: $(cat "$T/h/ups.log")"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' AND submission_id = (SELECT max(id) FROM pic_submission)" |
    grep -qF 'passed through 2 conversations (grapevine.maxHops is 1)' || fail "peers: hops: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")"
[ "$(q "SELECT count(*) FROM pic_inbox")" = 1 ] || fail "peers: the reply over maxHops was written"
pic check > /dev/null || fail "peers: integrity"
grep -qF '{"name":"send_message","description"' "$LOG/1.req" || fail "peers: send_message is not offered by default"
reserve "sse:$S/text.sse"
peer --tools -send_message ask 'without' > /dev/null 2>&1 || fail "peers: -send_message"
"$PIC" settings grapevine.sendMessage false > /dev/null
peer ask 'off' > /dev/null 2>&1 || fail "peers: sendMessage false"
"$PIC" settings --unset grapevine.sendMessage > /dev/null
"$PIC" settings --unset grapevine.wake > /dev/null
! grep -qF '{"name":"send_message","description"' "$LOG/1.req" "$LOG/2.req" || fail "peers: offered though turned off"
grep -qF '{"name":"bash","description"' "$LOG/2.req" || fail "peers: the other defaults went with it"
printf 'PASS: a conversation messages another: framed, a follow-up there, origin for hooks, hops counted and capped; send_message is on by default, off by setting or -send_message\n'

"$PIC" settings --unset grapevine.wake > /dev/null
# Waking, on by default: a message to an idle conversation starts a pic run there; past
# grapevine.maxWakes it is refused until a person prompts there; a UserPromptSubmit hook refuses a
# peer by its origin. Each outcome is said in the sender's tool result.
"$PIC" settings grapevine.maxWakes 1 > /dev/null
reserve "sse:$T/send_b.sse" "sse:$S/text.sse"
peer ask --session "$A" 'wake b' > /dev/null 2> "$T/pe" || fail "wake: a: $(cat "$T/pe")"
until_sql "SELECT count(*) FROM pic_submission WHERE session_id = '$B' AND request_key LIKE 'inbox:fx:%' AND status = 'answered'" 1
[ "$(q "SELECT state FROM pic_inbox ORDER BY id DESC LIMIT 1")" = delivered ] || fail "wake: the row"
[ "$(q "SELECT i.submission_id = u.id FROM pic_inbox i JOIN pic_submission u ON u.request_key = 'inbox:' || i.msg_key ORDER BY i.id DESC LIMIT 1")" = 1 ] ||
    fail "wake: the row does not name its request"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1" | grep -qF 'Woke conversation' || fail "wake: result"
reserve "sse:$T/send_b.sse" "sse:$S/text.sse"
peer ask --session "$A" 'wake b again' > /dev/null 2> "$T/pe" || fail "wake 2: a: $(cat "$T/pe")"
until_sql "SELECT state FROM pic_inbox ORDER BY id DESC LIMIT 1" refused
q "SELECT response FROM pic_inbox ORDER BY id DESC LIMIT 1" | grep -qF 'grapevine.maxWakes is 1' || fail "wake 2: $(q 'SELECT response FROM pic_inbox ORDER BY id DESC LIMIT 1')"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1" | grep -qF 'Refused, not delivered: 1 requests were started by messages' ||
    fail "wake 2: result: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1")"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1" | grep -qF "A person must prompt conversation $B" || fail "wake 2: result names no conversation"
reserve "sse:$S/text.sse" "sse:$T/send_b.sse" "sse:$S/text.sse"
peer ask --session "$B" 'a person here' > /dev/null 2> "$T/pe" || fail "wake: person: $(cat "$T/pe")"
touch "$T/refuse"
peer ask --session "$A" 'wake b once more' > /dev/null 2> "$T/pe" || fail "wake 3: a: $(cat "$T/pe")"
until_sql "SELECT state FROM pic_inbox ORDER BY id DESC LIMIT 1" refused
q "SELECT response FROM pic_inbox ORDER BY id DESC LIMIT 1" | grep -qF 'no peers today' || fail "wake 3: not the hook: $(q 'SELECT response FROM pic_inbox ORDER BY id DESC LIMIT 1')"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1" | grep -qF 'Not delivered to conversation' || fail "wake 3: result"
rm -f "$T/refuse"
reserve "sse:$T/send_b.sse" "sse:$S/text.sse"
peer ask --session "$A" 'and again' > /dev/null 2> "$T/pe" || fail "wake 4: a: $(cat "$T/pe")"
until_sql "SELECT count(*) FROM pic_submission WHERE session_id = '$B' AND request_key LIKE 'inbox:fx:%' AND status = 'answered'" 2
# maxWakes 0 is no limit: the cap of 1 is reached, and the next message still wakes it.
"$PIC" settings grapevine.maxWakes 0 > /dev/null
reserve "sse:$T/send_b.sse" "sse:$S/text.sse"
peer ask --session "$A" 'no limit' > /dev/null 2> "$T/pe" || fail "wake 5: a: $(cat "$T/pe")"
until_sql "SELECT count(*) FROM pic_submission WHERE session_id = '$B' AND request_key LIKE 'inbox:fx:%' AND status = 'answered'" 3
# pic send wakes too: its stdout is the state and key, its stderr says what happened.
reserve "sse:$S/text.sse"
out=$(pic send --session "$B" --key sw prompt 'from the command line' 2> "$T/sw.err") || fail "send wake: $out"
[ "$out" = "pending sw" ] || fail "send wake: printed $out"
# the earlier wake's run may still hold the conversation: delivered into it is as right an outcome
grep -qE "^(Woke conversation $B|Delivered into the request running in conversation $B)" "$T/sw.err" || fail "send wake: stderr: $(cat "$T/sw.err")"
until_sql "SELECT state FROM pic_inbox WHERE msg_key = 'sw'" delivered
# the woken run must be over before the next section starts its own request in B
until_sql "SELECT count(*) FROM pic_submission WHERE session_id = '$B' AND status = 'admitted'" 0
i=0; while pgrep -f "run --session $B" > /dev/null 2>&1; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "send wake: the woken run did not end"; sleep 0.05; done
# A prompt sent after the run's last look at the inbox but while it still holds the conversation
# (PIC_RUN_AT at run-end sends it then, every time) is told it went into the running request. The
# run lets go and starts the next one for it, so it is answered, never left pending (#102).
if [ "$FAULTS" = 1 ]; then
    reserve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse"
    PIC_RUN_AT="run-end:'$PIC' --db '$DB' --workspace '$WS' send --session $B --key race1 prompt 'sent at the end' >> '$T/race.out' 2>&1" \
        pic send --session "$B" --key race0 prompt 'the run that ends' > /dev/null 2> "$T/race0.err" || fail "race: $(cat "$T/race0.err")"
    until_sql "SELECT count(*) FROM pic_inbox WHERE msg_key = 'race1'" 1
    grep -qF 'Delivered into the request running' "$T/race.out" || fail "race: the late prompt was not sent into a running request: $(cat "$T/race.out")"
    until_sql "SELECT state FROM pic_inbox WHERE msg_key = 'race1'" delivered
    until_sql "SELECT count(*) FROM pic_submission WHERE session_id = '$B' AND status = 'admitted'" 0
    [ "$(q "SELECT count(*) FROM pic_submission u JOIN pic_inbox i ON i.submission_id = u.id WHERE i.msg_key = 'race1' AND u.status = 'answered'")" = 1 ] ||
        fail "race: the late prompt was not answered: $(q "SELECT state, response FROM pic_inbox WHERE msg_key = 'race1'")"
    i=0; while pgrep -f "run --session $B" > /dev/null 2>&1; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "race: the run did not end"; sleep 0.05; done
    printf 'PASS: a prompt sent as the run takes its last look is answered by the next run, not left pending\n'
fi
# The sender is told where a message went when the receiver is running a request...
reserve "sse:$S/bash_hold.sse" "sse:$T/send_b.sse" "sse:$S/text.sse" "sse:$S/text.sse"
hold --session "$B"
peer ask --session "$A" 'to a running b' > /dev/null 2> "$T/pe" || fail "running: a: $(cat "$T/pe")"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' AND body LIKE '%conversation%' ORDER BY seq DESC LIMIT 1" |
    grep -qF "Delivered into the request running in conversation $B, which takes it as a follow-up" ||
    fail "running: result: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1")"
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "running: exit $rc: $(cat "$T/err$n")"
# ...and when wake is off: nothing is running there, or it is open in a terminal (a follower holds its watch).
"$PIC" settings grapevine.wake false > /dev/null
reserve "sse:$T/send_b.sse" "sse:$S/text.sse"
peer ask --session "$A" 'wake is off' > /dev/null 2> "$T/pe" || fail "off: a: $(cat "$T/pe")"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1" | grep -qF 'and no request was started as grapevine.wake is off' ||
    fail "off: result: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1")"
rm -f "$T/follow.in"
mkfifo "$T/follow.in"
"$PIC" --db "$DB" --workspace "$WS" attach --session "$B" --from end --format json < "$T/follow.in" > /dev/null 2>&1 &
apids=$!
exec 5> "$T/follow.in"
exists "$DB.pic-leases/$B.watch"
sleep 0.3
reserve "sse:$T/send_b.sse" "sse:$S/text.sse"
peer ask --session "$A" 'it is open' > /dev/null 2> "$T/pe" || fail "open: a: $(cat "$T/pe")"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1" | grep -qF "Waiting: conversation $B is open in a terminal and will see the message on its next turn" ||
    fail "open: result: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1")"
exec 5>&-
wait "$apids" 2>/dev/null || :
apids=
pic check > /dev/null || fail "wake: integrity"
printf 'PASS: a message wakes an idle conversation when grapevine.wake allows, up to grapevine.maxWakes; a person resets it; a hook refuses a peer\n'

# Another workspace: the receiver is found through the workspaces pic has opened, the row is in
# its journal, and pic sessions --all lists both.
reserve "sse:$S/text.sse"
mkdir "$T/other-ws"
DB2="$T/other.sqlite"
WS2=$(cd "$T/other-ws" && pwd -P)
"$PIC" --db "$DB2" --workspace "$WS2" --model fake/m ask 'c first' > /dev/null 2> "$T/pe" || fail "ws2: $(cat "$T/pe")"
C=$("$SQLITE3" "$DB2" "SELECT id FROM pic_session")
"$PIC" --db "$DB2" --workspace "$WS2" name "$C" peer-c > /dev/null
tool_sse send_message "{\"to\":\"peer-c\",\"message\":\"over there\",\"workspace\":\"$WS2\"}" > "$T/send_c.sse"
reserve "sse:$T/send_c.sse" "sse:$S/text.sse"
"$PIC" --db "$DB" --workspace "$WS" --model fake/m ask --session "$A" 'tell c' > /dev/null 2> "$T/pe" ||
    fail "ws2: send: $(cat "$T/pe")"
[ "$("$SQLITE3" "$DB2" "SELECT session_id || ' ' || sender || ' ' || state FROM pic_inbox")" = "$C session:$JID/$A pending" ] ||
    fail "ws2: $("$SQLITE3" "$DB2" 'SELECT * FROM pic_inbox')"
"$PIC" sessions --all > "$T/all" || fail "sessions --all"
grep -qF "$WS2  $C  peer-c" "$T/all" && grep -qF "  $A  peer-a" "$T/all" || fail "sessions --all: $(cat "$T/all")"
printf 'PASS: a conversation messages one in another workspace; pic sessions --all lists them\n'
rm -f "$HOME/.pic/hooks.json"

if [ "$FAULTS" = 0 ]; then
    printf 'SKIP: the inbox fault points (release build)\n'
    exit 0
fi

# A peer's send is replay-safe: crashed after it sent and before its result was journaled, the
# call runs again on recovery and its key (fx:JOURNAL:EFFECT) makes it the same message. A wake that crashed
# after admitting the prompt and before settling its row leaves both; the request's next owner
# settles the row as that request, and the prompt runs once.
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$T/send_b.sse" "sse:$S/text.sse"
peer ask 'b first' > /dev/null 2>&1 || fail "replay: b"
B=$(q "SELECT id FROM pic_session")
pic name "$B" peer-b > /dev/null
peer ask 'a first' > /dev/null 2>&1 || fail "replay: a"
A=$(q "SELECT id FROM pic_session WHERE id != '$B'")
rc=0
env PIC_CRASH_AT=after-exec:1 "$PIC" --db "$DB" --workspace "$WS" --model fake/m ask --session "$A" 'tell b' \
    > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "replay: exit $rc"
[ "$(q "SELECT count(*) FROM pic_inbox")" = 1 ] || fail "replay: not sent before the crash point"
peer run --session "$A" > /dev/null 2> "$T/pe" || fail "replay: recovery: $(cat "$T/pe")"
[ "$(q "SELECT count(*) FROM pic_inbox")" = 1 ] || fail "replay: rows $(q 'SELECT count(*) FROM pic_inbox')"
rc=0
env PIC_CRASH_AT=inbox_wake:1 "$PIC" --db "$DB" --workspace "$WS" --model fake/m run --session "$B" > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "wake crash: exit $rc"
[ "$(q "SELECT state FROM pic_inbox")" = pending ] || fail "wake crash: the row"
[ "$(q "SELECT status FROM pic_submission WHERE request_key LIKE 'inbox:%'")" = admitted ] || fail "wake crash: the request"
pic check > /dev/null || fail "wake crash: integrity before"
peer run --session "$B" > /dev/null 2> "$T/pe" || fail "wake crash: recovery: $(cat "$T/pe")"
[ "$(q "SELECT i.state || ' ' || (i.submission_id = u.id) || ' ' || u.status FROM pic_inbox i, pic_submission u WHERE u.request_key LIKE 'inbox:%'")" = "delivered 1 answered" ] ||
    fail "wake crash: $(q 'SELECT * FROM pic_inbox')"
[ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body LIKE '%found it'")" = 1 ] || fail "wake crash: the prompt ran twice"
pic check > /dev/null || fail "wake crash: integrity"
printf 'PASS: a peer send replays as the same message; a wake cut off before settling runs its prompt once\n'

# Delivery writes nothing outside the journal before it commits: the
# owner's queue_update for a delivered steer comes after the commit, and a
# delivery that fails to settle leaves no event and no queued message.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
export PIC_RUN_AT="inbox_deliver:grep -c queue_update $T/ev$n >> $T/snap; true"
hold
unset PIC_RUN_AT
pic send --key def steer 'deferred' > /dev/null
until_sql "SELECT state FROM pic_inbox WHERE msg_key = 'def'" delivered
await "$T/ev$n" '"steering":["deferred"]'
[ "$(head -1 "$T/snap")" = 0 ] || fail "deferred: an event before the commit: $(cat "$T/snap")"
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "deferred: exit $rc"
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
export PIC_INBOX_FAIL_SETTLE=1
hold
unset PIC_INBOX_FAIL_SETTLE
pic send --key nf steer 'not settled' > /dev/null
await "$T/err$n" 'pic: inbox:'
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "settle failure: exit $rc: $(cat "$T/err$n")"
! grep -qF 'not settled' "$T/ev$n" || fail "settle failure: an event for it: $(grep -F 'not settled' "$T/ev$n")"
[ "$(q "SELECT state FROM pic_inbox WHERE msg_key = 'nf'")" = pending ] || fail "settle failure: the row"
[ "$(q "SELECT count(*) FROM pic_queued")" = 0 ] || fail "settle failure: a queued message"
[ "$(q "SELECT group_concat(status) FROM pic_submission")" = answered ] || fail "settle failure: requests"
pic check > /dev/null || fail "settle failure: integrity"
printf 'PASS: a delivery emits its events after its commit, and none when it fails\n'

# Crashes at accept: before its commit nothing is there and a retry
# inserts it; after it, the row is there and a retry adds nothing.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
pic submit k0 'first' > /dev/null
rc=0
PIC_CRASH_AT=inbox_accept:1 "$PIC" --db "$DB" --workspace "$WS" send --key c1 follow_up x > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "accept crash 1: exit $rc"
[ "$(q "SELECT count(*) FROM pic_inbox")" = 0 ] || fail "accept crash 1: a row"
rc=0
PIC_CRASH_AT=inbox_accept:2 "$PIC" --db "$DB" --workspace "$WS" send --key c1 follow_up x > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "accept crash 2: exit $rc"
[ "$(pic send --key c1 follow_up x)" = "pending c1" ] || fail "accept crash 2: retry"
[ "$(q "SELECT count(*) FROM pic_inbox")" = 1 ] || fail "accept crash 2: rows"
pic check > /dev/null || fail "accept crash: integrity"
printf 'PASS: a crash at either side of accept leaves one row or none, and a retry makes it one\n'

# Crashes at delivery: before its commit the message stays pending and the
# conversation's next owner delivers it; after it, the queued steer
# recovers as any does. Either way it reaches the model once.
for at in 1 2; do
    serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
    export PIC_CRASH_AT="inbox_deliver:$at"
    hold
    unset PIC_CRASH_AT
    pic send --key d steer 'once only' > /dev/null
    finish
    [ "$rc" = 77 ] || fail "deliver crash $at: exit $rc: $(cat "$T/err$n")"
    touch "$WS/release"
    state=$(q "SELECT state FROM pic_inbox")
    [ "$at" = 1 ] && [ "$state" != pending ] && fail "deliver crash 1: $state"
    [ "$at" = 2 ] && [ "$state" != delivered ] && fail "deliver crash 2: $state"
    "$PIC" --db "$DB" --workspace "$WS" --model fake/m run --session "$SID" > /dev/null 2> "$T/rerr" || fail "deliver crash $at: recovery: $(cat "$T/rerr")"
    [ "$(q "SELECT state FROM pic_inbox")" = delivered ] || fail "deliver crash $at: not delivered after recovery"
    [ "$(q "SELECT count(*) FROM pic_queued WHERE text = 'once only'")" = 1 ] || fail "deliver crash $at: queued rows"
    [ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body = 'once only'")" = 1 ] || fail "deliver crash $at: entries"
    [ "$(cat "$LOG"/*.req | grep -cF '{"role":"user","content":"once only"}')" = 1 ] || fail "deliver crash $at: sent $(grep -c 'once only' "$LOG"/*.req)"
    pic check > /dev/null || fail "deliver crash $at: integrity"
done
printf 'PASS: a crash at either side of delivery delivers once\n'

# An abort delivered, its owner dead before the cancel: the next pic to open
# the journal cancels the request; nothing more is asked of the model.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
export PIC_CRASH_AT=before-cancel:1
hold
unset PIC_CRASH_AT
pic send abort > /dev/null
finish
[ "$rc" = 77 ] || fail "abort crash: exit $rc: $(cat "$T/err$n")"
touch "$WS/release"
[ "$(q "SELECT state FROM pic_inbox")" = delivered ] || fail "abort crash: $(q 'SELECT state FROM pic_inbox')"
pic check > /dev/null || fail "abort crash: integrity"
[ "$(q "SELECT status || ' ' || error FROM pic_submission")" = "failed cancelled" ] || fail "abort crash: $(q 'SELECT status, error FROM pic_submission')"
"$PIC" --db "$DB" --workspace "$WS" --model fake/m run > /dev/null 2>&1 || fail "abort crash: run after"
[ ! -e "$LOG/2.req" ] || fail "abort crash: the request went on"
printf 'PASS: an abort delivered before its owner died still cancels the request\n'

# pic rc --ssh: /rc ssh's page on stdout, as text. The workspace is quoted for
# the shell at each end; lookups faked.
mkdir "$T/odd ws'\$x\`b\\c"
PIC_TEST_RC="phone.tail.ts.net|-|1|100.101.102.103" "$PIC" --workspace "$T/odd ws'\$x\`b\\c" rc --ssh > "$T/rc" 2> "$T/rc.err" || fail "rc: $(cat "$T/rc.err")"
grep -qF 'ssh://' "$T/rc" && grep -qF '@phone.tail.ts.net' "$T/rc" || fail "rc: address: $(cat "$T/rc")"
# A phone not on Tailscale's DNS cannot resolve the name: the address is the IP, and the page says
# to use it.
grep -qF "open ssh://[email protected]" "$T/rc" || fail "rc: the ssh:// address is not the IP: $(cat "$T/rc")"
grep -qF "If the name doesn't resolve on your phone, use 100.101.102.103 (or turn on Use Tailscale DNS in the Tailscale app)" "$T/rc" ||
    fail "rc: no IP fallback: $(cat "$T/rc")"
grep -qF "'\\''" "$T/rc" || fail "rc: the quote in the path: $(grep ssh "$T/rc")"
grep -qF 'attach -i -c --format text' "$T/rc" || fail "rc: no command"
grep -qF '✓ Remote Login is on' "$T/rc" && grep -qF '✓ Tailscale is up: phone.tail.ts.net' "$T/rc" || fail "rc: checks: $(cat "$T/rc")"
! grep -q '█' "$T/rc" || fail "rc: a QR code for ssh"
! grep -q "$(printf '\033')" "$T/rc" || fail "rc: colours in piped output"
# The command it prints runs: the remote shell gets back the path as it was.
cmd=$(sed -n 's/^Or, from any ssh client, all at once: ssh -t [^ ]* //p' "$T/rc")
inner=$(eval "printf '%s' $cmd")
dir=$(printf '%s' "$inner" | sed 's/ && .*//; s/^cd //')
[ "$(eval "printf '%s' $dir")" = "$T/odd ws'\$x\`b\\c" ] || [ "$(eval "printf '%s' $dir")" = "$(cd "$T/odd ws'\$x\`b\\c" && pwd -P)" ] ||
    fail "rc: the path comes back as $(eval "printf '%s' $dir")"
printf 'PASS: pic rc --ssh prints the address, a correctly quoted command and the checks, no QR code\n'