#!/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
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
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    n=$((n + 1))
    mkdir "$T/log$n" "$T/ws$n"
    DB="$T/j$n.sqlite"
    WS="$T/ws$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" "$DB" "$1"; }
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; }

# 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') || fail "send: $out"
[ "$out" = "pending k1" ] || fail "send: printed $out"
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":"prompt","message":"x"}' 2> "$T/kind"; then fail "kind: a prompt was accepted"; fi
grep -qF 'the inbox takes steer, follow_up and abort, not prompt' "$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 'not at schema' "$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'

# 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
(printf 'BEGIN IMMEDIATE;\nINSERT INTO pic_meta(key, value) VALUES (%s, %s);\n' "'held'" "'1'"; sleep 2; printf 'COMMIT;\n') |
    "$SQLITE3" "$DB" &
lpid=$!
sleep 0.5
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"'
kill "$a1" "$a2" 2>/dev/null || :
wait "$a1" 2>/dev/null || :
wait "$a2" 2>/dev/null || :
apids=
types=$(sed -n 's/^{"type":"\([a-z_]*\)".*/\1/p' "$T/a1" | 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.
big=$(awk 'BEGIN { for (i = 0; i < 4000; 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'

# 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"
pic check > /dev/null || fail "idle -i: integrity"
printf 'PASS: pic attach -i starts a request on an idle conversation, shows it, and /abort cancels it\n'

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

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