#!/bin/sh
# Remote control through a relay (docs/design/remote-protocol.md): pic remote pair and pic remote
# against the test relay (test/pic/fake_relay.c, section 6 with the deployed Worker's deviations)
# and a scripted phone (test/pic/fake_phone.c, the initiator on pic's own Noise module). Pairing:
# the happy path, a wrong secret, a no, an expired offer, an offer used twice, and the phone that
# was not reading when paired was posted. Sessions: an unknown key, the wrong channel, a replayed
# and a reordered record, reconnecting and catching up from a cursor, a steer, an idle prompt, an
# abort, unpairing at the terminal and from the phone, pic remote killed at any moment, and two
# phones at once. Usage: test/pic/remote.sh [--no-faults]
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
RELAY=${RELAY:?set RELAY to the fake_relay binary}
PHONE=${PHONE:?set PHONE to the fake_phone binary}
SQLITE3=${SQLITE3:-sqlite3}
FAULTS=1
[ "${1:-}" = --no-faults ] && FAULTS=0
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-remote.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME/.pic"
unset PIC_KEY_FD
export ANTHROPIC_API_KEY=pic-remote-test-key PIC_PI_EXPORT=0
pids=
cleanup() {
    for p in $pids; do kill -9 "$p" 2>/dev/null || true; done
    rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
fail() {
    printf 'FAIL: %s\n' "$*" >&2
    for f in "$T"/*.out "$T"/*.err "$T"/*.run; do [ -s "$f" ] && { printf -- '--- %s\n' "$f" >&2; tail -20 "$f" >&2; }; done
    exit 1
}
bg() { pids="$pids $1"; }
await() { # FILE PATTERN [TRIES]: wait for the fixed string PATTERN in FILE (50 ms a try, 30 s by default)
    i=0
    until grep -qF -- "$2" "$1" 2>/dev/null; do
        i=$((i + 1))
        [ "$i" -lt "${3:-600}" ] || fail "timed out waiting for $2 in $1"
        sleep 0.05
    done
}
gone() { # PID: wait up to 30 s for it to exit; its status in rc
    rc=0
    wait "$1" || rc=$?
}
uq() { "$SQLITE3" "$HOME/.pic/pic.sqlite" "$1"; }

if [ "$FAULTS" = 0 ]; then
    # The release build reads the passphrase only from a terminal: without one, pic remote says so
    # and pairs nothing. The rest needs PIC_TEST_PASSPHRASE, a dev build's seam.
    if "$PIC" remote < /dev/null > "$T/notty.out" 2> "$T/notty.err"; then fail "release: pic remote ran with no terminal"; fi
    [ -s "$T/notty.err" ] || fail "release: no message"
    printf 'PASS: release: pic remote without a terminal exits with a message\n'
    exit 0
fi
export PIC_TEST_PASSPHRASE=remote-test-pass

# One relay for the whole run; its deadline outlives the script.
"$RELAY" "$T/relay.port" 600 test-invite > "$T/relay.out" 2> "$T/relay.err" &
bg $!
i=0
while [ ! -s "$T/relay.port" ]; do
    i=$((i + 1))
    [ "$i" -lt 600 ] || fail "relay did not start"
    sleep 0.05
done
BASE="http://127.0.0.1:$(cat "$T/relay.port")"
"$PIC" settings remote.relay "$BASE" > /dev/null
state() { curl -s -X POST "$BASE/_test/state"; }
ctl() { curl -s -X POST "$BASE/_test/$1" > /dev/null; }

np=0
offer() { # start pic remote pair --pipe; its output in $PO, its stdin the fifo $PI (fd 3)
    np=$((np + 1))
    PO="$T/pair$np.out"
    PI="$T/pair$np.in"
    mkfifo "$PI"
    "$PIC" remote pair --pipe < "$PI" > "$PO" 2> "$T/pair$np.err" &
    PP=$!
    bg $PP
    exec 3> "$PI"
    await "$PO" '"type":"offer"'
    URL=$(sed -n 's/.*"url":"\([^"]*\)".*/\1/p' "$PO" | head -1)
    [ -n "$URL" ] || fail "offer: no address in $(cat "$PO")"
}
phone_pair() { # DIR NAME [ARGS]: the phone pairs in the background; its output in DIR.out
    mkdir -p "$1"
    "$PHONE" "$1" pair "$URL" "$2" ${3:-} > "$1.out" 2>&1 &
    PH=$!
    bg $PH
}

# ---- pairing -------------------------------------------------------------------------------
# Without the invite the relay refuses a new mailbox (403), and pairing says which setting to set.
if "$PIC" remote pair --pipe < /dev/null > "$T/noinv.out" 2> "$T/noinv.err"; then fail "invite: paired without one"; fi
grep -qF 'remote.invite' "$T/noinv.err" || fail "invite: message: $(cat "$T/noinv.err")"
"$PIC" settings remote.invite test-invite > /dev/null
printf 'PASS: a relay that wants an invite: pairing names the setting\n'

# The happy path: the two codes match, a yes commits one sealed device row, the phone hears paired,
# and the pairing channel is gone at the relay afterwards.
offer
case "$URL" in "$BASE/#p1."*) ;; *) fail "offer: address $URL" ;; esac
phone_pair "$T/ph1" "Phone One"
await "$PO" '"type":"code"'
await "$T/ph1.out" 'code '
want=$(sed -n 's/^code //p' "$T/ph1.out")
grep -qF "\"code\":\"$want\"" "$PO" || fail "pair: the codes differ: $(cat "$PO") / $want"
grep -qF '"name":"Phone One"' "$PO" || fail "pair: name: $(cat "$PO")"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 0 ] || fail "pair: a row before the yes"
echo y >&3
gone $PH
[ "$rc" = 0 ] || fail "pair: phone exit $rc"
grep -qx paired "$T/ph1.out" || fail "pair: phone: $(cat "$T/ph1.out")"
gone $PP
exec 3>&-
[ "$rc" = 0 ] || fail "pair: pic exit $rc"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "pair: rows"
[ "$(uq 'SELECT count(*) FROM picu_remote_key')" = 3 ] || fail "pair: keys"
uq "SELECT sealed FROM picu_remote_device" | grep -qF 'Phone One' && fail "pair: the device row is not sealed"
state | grep -qF 'channels 1 ' || fail "pair: relay channels: $(state)"
"$PIC" remote devices > "$T/devices.out" || fail "devices"
grep -qF 'Phone One' "$T/devices.out" || fail "devices: $(cat "$T/devices.out")"
grep -qF 'not running' "$T/devices.out" || fail "devices: running: $(cat "$T/devices.out")"
printf 'PASS: pairing: matching codes, a yes, one sealed row, the pairing channel deleted\n'

# The same address again: the offer was spent, its channel deleted; the phone hears it is gone.
phone_pair "$T/ph1b" "Phone Again"
gone $PH
[ "$rc" = 4 ] || fail "reused: phone exit $rc: $(cat "$T/ph1b.out")"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "reused: rows"
printf 'PASS: a used pairing address is refused by the relay\n'

# A no at the terminal: the phone hears pair_refused and nothing is written.
offer
phone_pair "$T/ph2" "Phone No"
await "$PO" '"type":"code"'
echo n >&3
gone $PH
[ "$rc" = 3 ] || fail "no: phone exit $rc: $(cat "$T/ph2.out")"
gone $PP
exec 3>&-
[ "$rc" != 0 ] || fail "no: pic exit 0"
grep -qF '"type":"refused"' "$PO" || fail "no: $(cat "$PO")"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "no: rows"
state | grep -qF 'channels 1 ' || fail "no: relay channels: $(state)"
printf 'PASS: a no at the terminal: the phone is refused, nothing is written\n'

# The wrong secret: a first message that does not verify is ignored (the phone hears nothing), and
# five end the offer.
offer
for k in 1 2 3 4 5; do phone_pair "$T/bad$k" "Bad $k" wrong-psk; done
await "$PO" 'too many pairing attempts failed'
gone $PP
exec 3>&-
[ "$rc" != 0 ] || fail "wrong psk: pic exit 0"
grep -qF '"type":"code"' "$PO" && fail "wrong psk: a code was shown"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "wrong psk: rows"
for k in 1 2 3 4 5; do grep -qF 'paired' "$T/bad$k.out" && fail "wrong psk: phone $k paired"; done
printf 'PASS: a first message under the wrong secret is ignored; five end the offer\n'

# An offer that expires: a phone past its time refuses it itself; one that got as far as the code
# hears pair_refused when it ends, and the channel goes.
PIC_TEST_PAIR_TTL=3 offer
phone_pair "$T/ph3" "Phone Slow"
await "$PO" '"type":"code"'
gone $PH
[ "$rc" = 3 ] || fail "expired: phone exit $rc: $(cat "$T/ph3.out")"
gone $PP
exec 3>&-
grep -qF '"type":"expired"' "$PO" || fail "expired: $(cat "$PO")"
sleep 1
phone_pair "$T/ph3b" "Phone Late"
gone $PH
[ "$rc" = 5 ] || fail "expired: late phone exit $rc: $(cat "$T/ph3b.out")"
state | grep -qF 'channels 1 ' || fail "expired: relay channels: $(state)"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "expired: rows"
printf 'PASS: an expired offer: refused to a phone mid-pairing, and by a phone that comes late\n'

# The phone is reconnecting when paired is posted (the relay says Pic-Peer: 0): the pairing channel
# stays until the phone reads again, so paired is not lost with it.
offer
phone_pair "$T/ph4" "Phone Away" "late 2500"
await "$T/ph4.out" away
echo y >&3
gone $PH
[ "$rc" = 0 ] || fail "away: phone exit $rc: $(cat "$T/ph4.out")"
gone $PP
exec 3>&-
[ "$rc" = 0 ] || fail "away: pic exit $rc"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 2 ] || fail "away: rows"
state | grep -qF 'channels 2 ' || fail "away: relay channels: $(state)"
printf 'PASS: paired reaches a phone that was reconnecting; the pairing channel goes after\n'

# ---- pic remote ------------------------------------------------------------------------------
n=0
spid=
serve() { # SPEC...: a fresh scripted model, 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/sport$n" "$LOG" 300 "$@" &
    spid=$!
    bg $spid
    i=0
    while [ ! -s "$T/sport$n" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "model 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/sport$n")" > "$T/models$n.json"
    export PIC_MODELS_FILE="$T/models$n.json"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" --model fake/m "$@"; }
q() { "$SQLITE3" "$DB" "$1"; }
until_sql() { # SQL VALUE: wait up to 30 s 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
}
nr=0
remote() { # start pic remote; its output in $RO
    nr=$((nr + 1))
    RO="$T/remote$nr.out"
    "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
    RP=$!
    bg $RP
    await "$RO" 'pic remote: connected'
}
script() { # DIR: run the phone of DIR on the script on stdin, in the background; output in DIR.run
    cat > "$1.script"
    rm -f "$1"/go* "$1"/at*
    "$PHONE" "$1" run < "$1.script" > "$1.run" 2>&1 &
    PR=$!
    bg $PR
}
done_ok() { # PID WHAT: the phone's script ran to its end
    gone "$1"
    [ "$rc" = 0 ] || fail "$2: phone exit $rc"
}
DEV1=$(uq "SELECT lower(hex(id)) FROM picu_remote_device WHERE paired_ms = (SELECT min(paired_ms) FROM picu_remote_device)")

# A conversation to look at: one request, finished.
# Connections: the first ask, the phone's prompt, the steer's hold, its reply and the follow-up, the
# abort's hold, the cut's hold and reply, then each crash's hold, reply and follow-up.
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" \
    "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse" \
    "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse"
pic ask 'first question' > /dev/null 2> "$T/ask.err" || fail "ask: $(cat "$T/ask.err")"
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
SESS="$DB/$SID"
remote
grep -qF '2 devices' "$RO" || fail "remote: $(cat "$RO")"
"$PIC" remote devices > "$T/devices2.out"
grep -qF 'pic remote is running' "$T/devices2.out" || fail "devices: running: $(cat "$T/devices2.out")"
"$PIC" remote > "$T/second.out" 2> "$T/second.err" && fail "a second pic remote ran"
grep -qF 'already running' "$T/second.err" || fail "second: $(cat "$T/second.err")"
printf 'PASS: pic remote: serves the paired phones; a second one refuses; devices says it runs\n'

# The list, ping and pong, following from the start, the journal's events with their seq and a
# mark; get_state and get_messages answered from the journal.
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$SESS"
send {"type":"ping"}
expect {"type":"pong"}
send {"type":"sync","session":"$SESS","seq":0}
expect "type":"agent_start"
expect "type":"agent_end"
expect {"type":"sync","session":"$SESS"
cmd k-state-0000000001 {"type":"command","session":"$SESS","key":"k-state-0000000001","payload":{"type":"get_state","id":"s1"}}
expect "command":"get_state"
cmd k-msgs-00000000001 {"type":"command","session":"$SESS","key":"k-msgs-00000000001","payload":{"type":"get_messages"}}
expect "first question"
send {"type":"bogus"}
expect "unknown_type"
EOS
done_ok $PR follow
grep -qF '"running":false' "$T/ph1.run" || fail "follow: no idle mark: $(cat "$T/ph1.run")"
grep -qF '"sessionId":"'"$SID"'"' "$T/ph1.run" || fail "follow: get_state: $(grep get_state "$T/ph1.run")"
printf 'PASS: a phone lists conversations, follows one from the journal, and asks for its state\n'

# Replayed and reordered records are dropped before decryption and change nothing.
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "type":"sessions"
replay
expectnot "type":"sessions" 1500
swapsend {"type":"sessions"}
expectnot "type":"sessions" 1500
count {"type":"pong"} 2
count "type":"sessions" 1
EOS
done_ok $PR replay
printf 'PASS: a replayed record and one that arrives after a later one are dropped\n'

# A key from another phone's static key on this phone's channel: no answer.
mkdir -p "$T/thief"
{ sed -n 1p "$T/ph4/pairing"; sed -n 2,4p "$T/ph4/pairing"; sed -n 5p "$T/ph1/pairing"; sed -n 6p "$T/ph4/pairing"; } > "$T/thief/pairing"
script "$T/thief" <<EOS
nosession 3000
EOS
done_ok $PR "wrong channel"
printf 'PASS: a known static key on another device'"'"'s channel gets no answer\n'

# A prompt while nothing runs is a keyed admission: one request under rc:DEVICE:KEY, in a process of
# its own, with the conversation's model; the same key again reports it and starts nothing more.
script "$T/ph1" <<EOS
send {"type":"sync","session":"$SESS","seq":-1}
expect "running":false
cmd k-prompt-000000001 {"type":"command","session":"$SESS","key":"k-prompt-000000001","payload":{"type":"prompt","message":"from the phone"}}
expect "command":"prompt","success":true
expect "status":"answered"
count "text":"from the phone" 2
send {"type":"command","session":"$SESS","key":"k-prompt-000000001","payload":{"type":"prompt","message":"from the phone"}}
expect "command":"prompt","success":true
sleep 1000
EOS
done_ok $PR prompt
[ "$(q "SELECT count(*) FROM pic_submission WHERE request_key LIKE 'rc:%:k-prompt-000000001'")" = 1 ] ||
    fail "prompt: submissions: $(q 'SELECT request_key, status FROM pic_submission')"
[ "$(q "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%'")" = answered ] ||
    fail "prompt: $(q "SELECT status, error FROM pic_submission WHERE request_key LIKE 'rc:%'")"
[ -e "$LOG/2.req" ] || fail "prompt: the conversation's model was not asked"
[ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body = 'from the phone'")" = 1 ] || fail "prompt: entries"
[ "$(q 'SELECT count(*) FROM pic_submission')" = 2 ] || fail "prompt: an extra request"
printf 'PASS: a prompt from the phone starts one request; its key again starts nothing\n'

# While a request runs: a steer goes through the inbox (ack once committed, the response once it is
# delivered, the sender the device); a prompt without streamingBehavior gets Pi's error, and with
# it becomes a follow-up.
rm -f "$WS/started" "$WS/release"
pic ask --session "$SID" 'hold on' > "$T/hold.out" 2> "$T/hold.err" &
HP=$!
bg $HP
i=0
until [ -e "$WS/started" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "hold: did not start"; sleep 0.05; done
script "$T/ph1" <<EOS
send {"type":"sync","session":"$SESS","seq":-1}
expect "running":true
cmd k-steer-0000000001 {"type":"command","session":"$SESS","key":"k-steer-0000000001","payload":{"type":"steer","message":"steer from the phone"}}
expect {"type":"ack","key":"k-steer-0000000001","payload":{"state":"pending"}}
cmd k-prompt-000000002 {"type":"command","session":"$SESS","key":"k-prompt-000000002","payload":{"type":"prompt","message":"too soon"}}
expect Agent is already processing
cmd k-prompt-000000003 {"type":"command","session":"$SESS","key":"k-prompt-000000003","payload":{"type":"prompt","message":"after that","streamingBehavior":"followUp"}}
expect {"type":"ack","key":"k-prompt-000000003"
mark go-release
expect "status":"answered"
sleep 500
count "key":"k-steer-0000000001","payload":{"type":"response","command":"steer","success":true 1
count "message":{"role":"user","content":[{"type":"text","text":"steer from the phone"}]}}} 2
EOS
i=0
until [ -e "$T/ph1/go-release" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "steer: the phone did not get its ack: $(cat "$T/ph1.run")"; sleep 0.05; done
touch "$WS/release"
done_ok $PR steer
gone $HP
[ "$rc" = 0 ] || fail "steer: the held request: exit $rc: $(cat "$T/hold.err")"
[ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-steer-0000000001' AND sender LIKE 'remote:%' AND state = 'delivered'")" = 1 ] ||
    fail "steer: inbox: $(q 'SELECT msg_key, sender, state FROM pic_inbox')"
[ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-prompt-000000003'")" = 1 ] || fail "follow-up: inbox"
[ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-prompt-000000002'")" = 0 ] || fail "too soon: a row"
[ "$(q "SELECT count(*) FROM pic_entry WHERE kind = 'user' AND body = 'steer from the phone'")" = 1 ] || fail "steer: entries"
"$PIC" --db "$DB" check > /dev/null || fail "steer: integrity"
printf 'PASS: a steer from the phone reaches the running request once; a prompt then follows Pi\n'

hold() { # a request in SESS whose bash call waits for $WS/release
    rm -f "$WS/started" "$WS/release"
    pic ask --session "$SID" 'hold on' > "$T/hold.out" 2> "$T/hold.err" &
    HP=$!
    bg $HP
    i=0
    until [ -e "$WS/started" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "hold: did not start: $(cat "$T/hold.err")"; sleep 0.05; done
}

# An abort from the phone cancels the running request.
hold
script "$T/ph1" <<EOS
cmd k-abort-0000000001 {"type":"command","session":"$SESS","key":"k-abort-0000000001","payload":{"type":"abort"}}
expect "key":"k-abort-0000000001","payload":{"type":"response","command":"abort","success":true
EOS
done_ok $PR abort
gone $HP
[ "$rc" != 0 ] || fail "abort: the request was not stopped"
[ "$(q "SELECT status || ' ' || error FROM pic_submission ORDER BY id DESC LIMIT 1")" = "failed cancelled" ] ||
    fail "abort: $(q 'SELECT status, error FROM pic_submission ORDER BY id DESC LIMIT 1')"
printf 'PASS: an abort from the phone stops the running request\n'

# Two phones at once: each has its own session, its own followed conversation and its own answers.
script "$T/ph4" <<EOS
send {"type":"sync","session":"$SESS","seq":-1}
expect "running":false
send {"type":"ping"}
expect {"type":"pong"}
mark go-two
waitfor $T/ph1/go-one
EOS
P4=$PR
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "type":"sessions"
mark go-one
waitfor $T/ph4/go-two
EOS
done_ok $PR "two phones: one"
done_ok $P4 "two phones: four"
grep -qF '"type":"sync"' "$T/ph1.run" && fail "two phones: a mark reached the phone that follows nothing"
grep -qF '"type":"sync"' "$T/ph4.run" || fail "two phones: no mark: $(cat "$T/ph4.run")"
printf 'PASS: two phones at once, each with its own session and conversation\n'

# Mid-follow the relay ends every stream and pic remote is killed: started again, the phone's next
# session catches up from its cursor with no event twice and none missed.
hold
script "$T/ph1" <<EOS
send {"type":"sync","session":"$SESS","seq":-1}
expect "running":true
mark go-cut
waitfor at-cut
newsession
expect "type":"agent_end"
expect "running":false
EOS
i=0; until [ -e "$T/ph1/go-cut" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "cut: $(cat "$T/ph1.run")"; sleep 0.05; done
ctl cut
kill -9 "$RP"
gone "$RP"
touch "$WS/release"
gone $HP
remote
touch "$T/ph1/at-cut"
done_ok $PR "cut"
dups=$(grep -o '"seq":[0-9]*,"payload":{"type":"message_end"' "$T/ph1.run" | sort | uniq -d)
[ -z "$dups" ] || fail "cut: events twice: $dups"
grep -qF '"text":"Hello, \"world\"' "$T/ph1.run" || fail "cut: the reply was missed: $(cat "$T/ph1.run")"
printf 'PASS: a broken stream and a new session: caught up from the cursor, nothing twice or missed\n'

# pic remote killed at the inbox's commit, before and after it: the phone repeats the command until
# it is answered, and it is one row either way.
for at in 1 2; do
    hold
    kill "$RP"
    gone "$RP"
    PIC_CRASH_AT=inbox_accept:$at "$PIC" remote > "$T/crash$at.out" 2> "$T/crash$at.err" &
    RP=$!
    bg $RP
    await "$T/crash$at.out" 'pic remote: connected'
    script "$T/ph1" <<EOS
cmd k-crash-00000000$at {"type":"command","session":"$SESS","key":"k-crash-00000000$at","payload":{"type":"follow_up","message":"crash $at"}}
expect {"type":"ack","key":"k-crash-00000000$at"
EOS
    PC=$PR
    gone "$RP"
    [ "$rc" = 77 ] || fail "crash $at: exit $rc: $(cat "$T/crash$at.err")"
    [ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-crash-00000000$at'")" = $((at - 1)) ] ||
        fail "crash $at: rows before the retry"
    remote
    done_ok $PC "crash $at"
    [ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-crash-00000000$at'")" = 1 ] || fail "crash $at: rows"
    touch "$WS/release"
    gone $HP
    until_sql "SELECT state FROM pic_inbox WHERE msg_key LIKE 'rc:%:k-crash-00000000$at'" delivered
done
"$PIC" --db "$DB" check > /dev/null || fail "crash: integrity"
printf 'PASS: pic remote killed before or after a command'"'"'s commit: the phone'"'"'s retry makes it one row\n'
