#!/bin/sh
# Several pic processes on one journal, each working its own conversation
# (docs/design/shared-store.md): a second pic works beside a running one and
# leaves its request alone; a killed pic's work is settled by whoever comes
# next and nobody else's is touched; a request is run by exactly one process;
# a conversation is advanced by one process at a time; an edit or write that
# meets another conversation's change says so. --no-faults skips the crash
# points (the release build has none).
set -eu
PIC=${PIC:?set PIC to the pic binary}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-shared.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME"
pids=
cleanup() {
    for p in $pids; do kill -9 "$p" 2>/dev/null || :; done
    rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
# Nothing here depends on timing: a command signals with a file and holds
# until the test signals back (crash.sh has the reasons).
await() { i=0; while [ ! -e "$1" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "timed out waiting for $1"; sleep 0.1; done; }
hold() { printf 'i=0; while [ ! -e %s ] && [ $i -lt 1200 ]; do sleep 0.1; i=$((i + 1)); done' "$1"; }
n=0
fresh() { # fresh: a new journal, workspace and ledger
    n=$((n + 1))
    DB="$T/j$n.sqlite"
    WS="$T/ws$n"
    mkdir "$WS"
    : > "$T/ledger"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
lines() { wc -l < "$T/ledger" | tr -d ' '; }
latest() { pic sessions | awk 'NR == 1 {print $1}'; }
status() { pic dump | sed -n "s/^submission [0-9]* $1 \([a-z]*\) .*/\1/p"; }
# The conversations a pic is working, as pic sessions shows them (a lease's
# file stays behind; the lock on it is what counts).
leases() { pic sessions | grep -c 'in use' || :; }
SQL=${SQLITE3:-sqlite3}
# holder KEY NAME: a pic, in the background, running request KEY (a new
# conversation) up to a command that appends to the ledger and then waits for
# release-NAME; its pid in $holder.
holder() {
    # The ledger line before the signal: whoever saw the signal may count (or
    # clear) the ledger at once.
    printf 'tool exec echo %s >> "%s"; touch holding-%s; %s; touch late-%s\ntext done\n' "$2" "$T/ledger" "$2" "$(hold "release-$2")" "$2" \
        > "$T/hold-$2.script"
    pic submit "$1" "work $2" > /dev/null || fail "submit $1"
    "$PIC" --db "$DB" --workspace "$WS" run --script "$T/hold-$2.script" 2> "$T/hold-$2.err" &
    holder=$!
    pids="$pids $holder"
    await "$WS/holding-$2"
}
printf 'tool write notes.txt hello\ntext done\n' > "$T/quick.script"

# A side question beside a long task: the second pic is answered in its own
# conversation, the journal can be read and checked, and the first one's
# running call is still its own, and finishes.
fresh
holder a1 a
a_sid=$(latest)
pic submit b1 'side question' > /dev/null || fail "side: submit beside a running pic"
b_sid=$(latest)
[ "$a_sid" != "$b_sid" ] || fail "side: no conversation of its own"
pic run --script "$T/quick.script" 2> "$T/side.err" || fail "side: run beside a running pic: $(cat "$T/side.err")"
[ "$(status b1)" = answered ] || fail "side: not answered: $(pic dump | grep '^submission')"
grep -q "request a1 is being run by another pic process (pid $holder); left to it" "$T/side.err" ||
    fail "side: did not say what it left: $(cat "$T/side.err")"
pic dump | grep -q '^effect 1 .* bash started safe=0 ' || fail "side: the running call was disturbed: $(pic dump | grep '^effect 1 ')"
pic check > /dev/null || fail "side: check beside a running pic"
pic log "$a_sid" > /dev/null || fail "side: log of the live conversation"
pic sessions | grep -q "^$a_sid .*in use by pid $holder" || fail "side: sessions does not show who has it: $(pic sessions)"
pic sessions | grep "^$b_sid " | grep -q 'in use' && fail "side: a finished conversation shown in use"
# With nothing free, pic run changes nothing and says so.
before=$(pic dump)
pic run --script "$T/quick.script" 2> "$T/idle.err" || fail "idle: run with nothing free"
grep -q 'request a1 is being run by another pic process' "$T/idle.err" || fail "idle: $(cat "$T/idle.err")"
[ "$(pic dump)" = "$before" ] || fail "idle: the journal changed"
touch "$WS/release-a"
wait "$holder" || fail "side: the first pic failed: $(cat "$T/hold-a.err")"
[ "$(status a1)" = answered ] || fail "side: the first request: $(status a1)"
pic dump | grep -q '^effect 1 .* bash done safe=0 ' || fail "side: first call not done"
[ "$(lines)" = 1 ] || fail "side: the command ran $(lines) times"
pic check > /dev/null || fail "side: check"
[ "$(leases)" = 0 ] || fail "side: a conversation still shown in use: $(pic sessions)"
printf 'PASS: a second pic is answered beside a running one, which keeps and finishes its own request\n'

# One conversation, one process: a second pic asking into a conversation
# that is being worked is refused, and told who has it.
fresh
holder a1 a
a_sid=$(latest)
if pic submit a2 'me too' --session "$a_sid" > /dev/null 2> "$T/same.err"; then fail "same: admitted into a conversation in use"; fi
grep -q "conversation $a_sid is in use by another pic process (pid $holder)" "$T/same.err" || fail "same: $(cat "$T/same.err")"
if pic ask --session "$a_sid" 'me too' > /dev/null 2> "$T/same.err"; then fail "same: ask into a conversation in use"; fi
grep -q "conversation $a_sid is in use by another pic process (pid $holder)" "$T/same.err" || fail "same ask: $(cat "$T/same.err")"
# No hook runs for a prompt that is refused.
mkdir -p "$HOME/.pic"
printf '{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"touch %s/hook-ran"}]}],"UserPromptSubmit":[{"hooks":[{"type":"command","command":"touch %s/hook-ran"}]}]}}\n' "$T" "$T" \
    > "$HOME/.pic/hooks.json"
if pic ask --session "$a_sid" 'me too' > /dev/null 2> "$T/same.err"; then fail "same: ask with hooks into a conversation in use"; fi
rm -f "$HOME/.pic/hooks.json"
grep -q "conversation $a_sid is in use by another pic process (pid $holder)" "$T/same.err" || fail "same, hooks: $(cat "$T/same.err")"
[ ! -e "$T/hook-ran" ] || fail "same: a hook ran for a refused prompt"
# A symlink to the journal is the same journal, with the same owner.
ln -s "$DB" "$T/link-$n.sqlite"
if "$PIC" --db "$T/link-$n.sqlite" --workspace "$WS" submit a2 'me too' --session "$a_sid" > /dev/null 2> "$T/same.err"; then
    fail "same: admitted through a symlinked path"
fi
grep -q "conversation $a_sid is in use by another pic process (pid $holder)" "$T/same.err" || fail "same, symlink: $(cat "$T/same.err")"
# Its request is its owner's to cancel.
if pic cancel a1 > /dev/null 2> "$T/cancel.err"; then fail "cancel: cancelled under a live owner"; fi
grep -q "request a1 is being run by another pic process (pid $holder); interrupt it there" "$T/cancel.err" ||
    fail "cancel: $(cat "$T/cancel.err")"
[ "$(pic dump | grep -c '^submission ')" = 1 ] || fail "same: something was admitted"
# Killed, it holds nothing: the request can be cancelled, its interrupted
# call is settled first, and its command did not outlive it.
kill -9 "$holder"
wait "$holder" 2>/dev/null || :
[ "$(pic cancel a1)" = cancelled ] || fail "cancel: after its owner died"
pic dump | grep -q '^effect 1 .* bash unknown safe=0 ' || fail "cancel: interrupted call not settled: $(pic dump | grep '^effect')"
pic dump | grep -q '^submission 1 a1 failed | .* error=cancelled' || fail "cancel: $(pic dump | grep '^submission')"
pic check > /dev/null || fail "cancel: check"
touch "$WS/release-a"
sleep 1
[ ! -e "$WS/late-a" ] || fail "cancel: the command outlived its killed pic"
pic submit a3 'again' --session "$a_sid" > /dev/null || fail "same: the conversation is not free again"
pic run --script "$T/quick.script" || fail "same: run"
[ "$(status a3)" = answered ] || fail "same: $(status a3)"
printf 'PASS: a conversation in use refuses a second pic and names its owner; free again once the owner is gone\n'

# kill -9 of one pic while another works: the survivor is not disturbed, and
# the next pic run settles only what the dead one left.
fresh
holder a1 a
victim=$holder
holder b1 b
kill -9 "$victim"
wait "$victim" 2>/dev/null || :
pic run --script "$T/hold-a.script" 2> "$T/kill.err" || fail "kill: run after a kill: $(cat "$T/kill.err")"
[ "$(status a1)" = answered ] || fail "kill: the dead pic's request was not finished: $(status a1)"
pic dump | grep -q '^effect 1 .* bash unknown safe=0 ' || fail "kill: its call is not unknown: $(pic dump | grep '^effect')"
pic dump | grep -q '^effect 2 .* bash started safe=0 ' || fail "kill: the survivor's call was disturbed: $(pic dump | grep '^effect')"
[ "$(status b1)" = admitted ] || fail "kill: the survivor's request: $(status b1)"
pic check > /dev/null || fail "kill: check beside the survivor"
touch "$WS/release-b" "$WS/release-a"
wait "$holder" || fail "kill: the survivor failed: $(cat "$T/hold-b.err")"
[ "$(status b1)" = answered ] || fail "kill: survivor not answered"
pic dump | grep -q '^effect 2 .* bash done safe=0 ' || fail "kill: the survivor's call"
[ "$(lines)" = 2 ] || fail "kill: ledger has $(lines) lines (each command once)"
sleep 1
[ ! -e "$WS/late-a" ] || fail "kill: the dead pic's command outlived it"
pic check > /dev/null || fail "kill: check"
printf 'PASS: a killed pic is settled by the next one; the pic working beside it is untouched\n'

# A lease file a crash left is nobody's: it blocks nothing.
mkdir -p "$DB.pic-leases"
echo 99999999 > "$DB.pic-leases/$(latest)"
pic submit c1 'after a crash' --session "$(latest)" > /dev/null || fail "stale lease: submit"
pic run --script "$T/quick.script" || fail "stale lease: run"
[ "$(status c1)" = answered ] || fail "stale lease: $(status c1)"
[ "$(leases)" = 0 ] || fail "stale lease: still shown in use: $(pic sessions)"
printf 'PASS: a lease file left by a crash blocks nothing\n'

# One request, four pics at once: it is run by exactly one of them.
round=0
while [ "$round" -lt 5 ]; do
    round=$((round + 1))
    fresh
    printf 'tool exec echo ran >> "%s"\ntext done\n' "$T/ledger" > "$T/once.script"
    pic submit job 'once' > /dev/null
    racers=
    for r in 1 2 3 4; do
        "$PIC" --db "$DB" --workspace "$WS" run --script "$T/once.script" 2> "$T/race-$r.err" &
        racers="$racers $!"
    done
    for r in $racers; do wait "$r" || fail "claim race: a racer failed: $(cat "$T"/race-*.err)"; done
    [ "$(lines)" = 1 ] || fail "claim race: the command ran $(lines) times"
    [ "$(status job)" = answered ] || fail "claim race: $(status job)"
    pic check > /dev/null || fail "claim race: check"
done
printf 'PASS: four pics racing for one request: run once\n'

# Two pics admitting into one conversation at once: one request is admitted.
fresh
pic submit first 'first' > /dev/null
pic run --script "$T/quick.script"
sid=$(latest)
round=0
while [ "$round" -lt 5 ]; do
    round=$((round + 1))
    "$PIC" --db "$DB" --workspace "$WS" submit "x$round" 'one' --session "$sid" > "$T/adm-x.out" 2> "$T/adm-x.err" &
    x=$!
    "$PIC" --db "$DB" --workspace "$WS" submit "y$round" 'other' --session "$sid" > "$T/adm-y.out" 2> "$T/adm-y.err" &
    y=$!
    won=0
    wait "$x" && won=$((won + 1))
    wait "$y" && won=$((won + 1))
    [ "$won" = 1 ] || fail "admission race: $won admitted: $(cat "$T/adm-x.err" "$T/adm-y.err")"
    cat "$T/adm-x.err" "$T/adm-y.err" | grep -Eq 'is still working on a request|is in use by another pic process' ||
        fail "admission race: the loser: $(cat "$T/adm-x.err" "$T/adm-y.err")"
    [ "$(pic dump | grep -c '^submission .* admitted ')" = 1 ] || fail "admission race: $(pic dump | grep '^submission')"
    pic run --script "$T/quick.script"
    pic check > /dev/null || fail "admission race: check"
done
printf 'PASS: two pics admitting into one conversation: one request\n'

# Four pics, each with several calls of its own, at once: every write waits
# its turn, none fails.
fresh
printf 'tool write a.txt 1\ntool write b.txt 2\ntool exec true\ntool write c.txt 3\ntool exec true\ntool write d.txt 4\ntext done\n' > "$T/busy.script"
workers=
for w in 1 2 3 4; do
    (
        "$PIC" --db "$DB" --workspace "$WS" submit "w$w" "worker $w" > /dev/null 2> "$T/busy-$w.err" &&
            "$PIC" --db "$DB" --workspace "$WS" run --script "$T/busy.script" 2>> "$T/busy-$w.err"
    ) &
    workers="$workers $!"
done
for w in $workers; do wait "$w" || fail "load: a worker failed: $(cat "$T"/busy-*.err)"; done
cat "$T"/busy-*.err | grep -q 'database is locked' && fail "load: $(cat "$T"/busy-*.err)"
pic run --script "$T/busy.script" 2>/dev/null || fail "load: finishing what was left"
[ "$(pic dump | grep -c '^submission .* answered ')" = 4 ] || fail "load: $(pic dump | grep '^submission')"
pic check > /dev/null || fail "load: check"
printf 'PASS: four pics writing one journal at once\n'

# No write transaction is held while pic waits on anything outside the
# journal: an import whose input is slow to come keeps nobody waiting.
fresh
pic submit one 'first' > /dev/null
pic run --script "$T/quick.script"
pic export --pi - > "$T/one.jsonl" || fail "import: export"
mkfifo "$T/slow-in"
"$PIC" --db "$DB" --workspace "$WS" import - < "$T/slow-in" > "$T/import.out" 2> "$T/import.err" &
importer=$!
pids="$pids $importer"
exec 9> "$T/slow-in"
sleep 1 # let it reach its read; were it early, the checks below would only be weaker
pic submit two 'beside a waiting import' > /dev/null 2> "$T/import-submit.err" || fail "import: submit beside it: $(cat "$T/import-submit.err")"
pic run --script "$T/quick.script" 2> "$T/import-run.err" || fail "import: run beside it: $(cat "$T/import-run.err")"
pic check > /dev/null || fail "import: check beside it"
cat "$T/one.jsonl" >&9
exec 9>&-
wait "$importer" || fail "import: $(cat "$T/import.err")"
[ "$(pic sessions | wc -l | tr -d ' ')" = 3 ] || fail "import: $(pic sessions)"
pic check > /dev/null || fail "import: check"
printf 'PASS: an import waiting on its input keeps no other pic waiting\n'

# A request passed over because its model cannot be had here gives its
# conversation back at once: a pic that has the model takes it while the
# first is still running something else.
if [ -n "${SERVER:-}" ]; then
    fresh
    S=$(cd "$(dirname "$0")/streams" && pwd)
    export PIC_MODELS_FILE="$T/models.json" ANTHROPIC_API_KEY=pic-shared-test-key PIC_MODEL_CATALOG=offline
    mkdir "$T/mlog"
    "$SERVER" "$T/mport" "$T/mlog" 120 "hang:$S/text.sse:200" &
    mspid=$!
    pids="$pids $mspid"
    i=0
    while [ ! -s "$T/mport" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "skip: server"; sleep 0.05; done
    printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"a"}]}}}' \
        "$(cat "$T/mport")" > "$T/models.json"
    pic submit r1 'needs a model not here' > /dev/null
    sid1=$(latest)
    pic --model fake/a submit r2 'hangs in its reply' > /dev/null
    "$SQL" "$DB" "UPDATE pic_submission SET model = 'gone/x', thinking = 'medium' WHERE request_key = 'r1'"
    "$PIC" --db "$DB" --workspace "$WS" --model fake/a run > /dev/null 2> "$T/skip.err" &
    first=$!
    pids="$pids $first"
    await "$T/mlog/1.req"
    pic sessions | grep "^$sid1 " | grep -q 'in use' && fail "skip: the passed-over conversation is still held: $(pic sessions)"
    "$SQL" "$DB" "UPDATE pic_submission SET model = NULL, thinking = NULL WHERE request_key = 'r1'"
    pic run --script "$T/quick.script" 2> "$T/skip2.err" || fail "skip: a second pic could not take it: $(cat "$T/skip2.err")"
    [ "$(status r1)" = answered ] || fail "skip: not finished by the second pic: $(status r1); $(cat "$T/skip2.err")"
    grep -q 'request r2 is being run by another pic process' "$T/skip2.err" || fail "skip: the first pic was not still at work: $(cat "$T/skip2.err")"
    kill -9 "$first" "$mspid" 2>/dev/null || :
    wait "$first" "$mspid" 2>/dev/null || :
    unset PIC_MODELS_FILE PIC_MODEL_CATALOG
    printf 'PASS: a request passed over for its model leaves its conversation free for another pic\n'
fi

# ---- a file another conversation changed -------------------------------------
effect_result() { pic dump | awk -v id="$1" '$1 == "effect" && $2 == id { found = 1 } found && /^(generation|queued|image|hook) / { exit } found { print }'; }

# Conversation A reads two files and waits; B changes both. A's edit no
# longer finds its text: the result says whose change it met and shows the
# file. A's write is refused once, with the file, and goes through when made
# again.
fresh
printf 'one two\n' > "$WS/f.txt"
printf 'ours\n' > "$WS/w.txt"
cat > "$T/a.script" <<EOF
tool raw read {"path":"f.txt"}
tool raw read {"path":"w.txt"}
tool exec touch holding-a; $(hold release-a)
tool raw edit {"path":"f.txt","edits":[{"oldText":"one","newText":"uno"}]}
tool write w.txt mine
tool write w.txt mine
text done
EOF
printf 'tool raw edit {"path":"f.txt","edits":[{"oldText":"one","newText":"eins"}]}\ntool write ./w.txt theirs\ntext done\n' > "$T/b.script"
pic submit a1 'edit f' > /dev/null
"$PIC" --db "$DB" --workspace "$WS" run --script "$T/a.script" 2> "$T/stale-a.err" &
a=$!
pids="$pids $a"
await "$WS/holding-a"
pic submit b1 'edit f too' > /dev/null
b_sid=$(latest)
pic run --script "$T/b.script" 2>/dev/null || fail "stale: the other conversation's changes"
[ "$(cat "$WS/f.txt") $(cat "$WS/w.txt")" = "eins two theirs" ] || fail "stale: the other changes: $(cat "$WS/f.txt" "$WS/w.txt")"
touch "$WS/release-a"
wait "$a" || fail "stale: $(cat "$T/stale-a.err")"
[ "$(status a1)" = answered ] || fail "stale: $(status a1)"
out=$(pic dump)
printf '%s\n' "$out" | grep -q "^effect 6 .* edit done safe=1 | Could not find the exact text in f.txt" || fail "stale edit: $(effect_result 6)"
effect_result 6 | grep -q "f.txt was changed by another pic conversation ($b_sid) after this one last read it" ||
    fail "stale edit: no note: $(effect_result 6)"
effect_result 6 | grep -q '^eins two$' || fail "stale edit: the current text is not in the result: $(effect_result 6)"
printf '%s\n' "$out" | grep -q "^effect 7 .* write skipped safe=1 | Did not write w.txt: it was changed by another pic conversation ($b_sid)" ||
    fail "stale write: not refused: $(effect_result 7)"
effect_result 7 | grep -q '^theirs$' || fail "stale write: the current text is not in the result: $(effect_result 7)"
printf '%s\n' "$out" | grep -q '^effect 8 .* write done safe=1 | Successfully wrote to w.txt' || fail "stale write: the second write: $(effect_result 8)"
[ "$(cat "$WS/w.txt")" = mine ] || fail "stale write: $(cat "$WS/w.txt")"
[ "$(cat "$WS/f.txt")" = "eins two" ] || fail "stale edit: the file changed: $(cat "$WS/f.txt")"
pic check > /dev/null || fail "stale: check"
printf 'PASS: an edit or write that meets another conversation'"'"'s change says so and shows the file; the write goes through when made again\n'

# Alone, nothing changes: a missed edit is Pi's message and no more, and a
# file an earlier conversation wrote is written without a word.
fresh
printf 'one two\n' > "$WS/f.txt"
printf 'tool raw edit {"path":"f.txt","edits":[{"oldText":"three","newText":"3"}]}\ntool write g.txt first\ntext done\n' > "$T/alone.script"
pic submit s1 'alone' > /dev/null
pic run --script "$T/alone.script"
pic dump | grep -q 'another pic conversation' && fail "alone: a note with no other conversation: $(pic dump | grep '^effect')"
pic dump | grep -q '^effect 1 .* edit done safe=1 | Could not find the exact text in f.txt' || fail "alone: $(effect_result 1)"
printf 'tool raw edit {"path":"f.txt","edits":[{"oldText":"three","newText":"3"}]}\ntool write g.txt second\ntext done\n' > "$T/later.script"
pic submit s2 'later' > /dev/null
pic run --script "$T/later.script"
pic dump | grep -q 'another pic conversation' && fail "later: an earlier conversation's write taken for a change since: $(pic dump | grep '^effect')"
[ "$(cat "$WS/g.txt")" = second ] || fail "later: $(cat "$WS/g.txt")"
# A fork is another conversation, and its parent wrote the file after the
# fork point; with one pic that is still nobody else's change.
fresh
printf 'tool write f.txt one\ntool write f.txt two\ntext done\n' > "$T/parent.script"
pic submit p1 'parent' > /dev/null
pic run --script "$T/parent.script"
forked=$(pic fork "$(latest)" --at 3) || fail "fork: $(pic log)"
printf 'tool write f.txt three\ntext done\n' > "$T/child.script"
pic submit c1 'child' --session "$forked" > /dev/null
pic run --script "$T/child.script"
pic dump | grep -q 'another pic conversation' && fail "fork: the parent's write taken for another pic's: $(pic dump | grep '^effect')"
[ "$(cat "$WS/f.txt")" = three ] || fail "fork: $(cat "$WS/f.txt")"
pic submit p2 'parent again' --session "$(pic sessions | awk -v f="$forked" '$1 != f {print $1}')" > /dev/null
pic run --script "$T/child.script"
pic dump | grep -q 'another pic conversation' && fail "fork: the fork's write taken for another pic's: $(pic dump | grep '^effect')"
printf 'PASS: one pic, one conversation at a time, forks included, sees no difference\n'

[ "$FAULTS" = yes ] || exit 0

# The crash matrix with a live neighbour: a pic crashes at each commit and
# effect boundary while another holds a running call; the next pic run
# finishes the crashed request exactly as it would alone, and the neighbour's
# call is its own throughout.
cat > "$T/script" <<EOF
tool write notes.txt hello from pic
tool exec printf 'ran\n' >> "$T/ledger"
text done
EOF
beside() { # beside SCRIPT LABEL < cases
    while read -r point ledger state generations; do
    fresh
    holder n1 n
    : > "$T/ledger"
    if [ "$point" = after-admit:1 ]; then
        if env PIC_CRASH_AT="$point" "$PIC" --db "$DB" --workspace "$WS" submit job-1 'make notes' > /dev/null 2>&1; then
            fail "$point: no crash"
        fi
    else
        pic submit job-1 'make notes' > /dev/null
        if env PIC_CRASH_AT="$point" "$PIC" --db "$DB" --workspace "$WS" run --script "$1" 2>/dev/null; then
            fail "$point: no crash"
        fi
    fi
    pic check > /dev/null || fail "$point: check after the crash"
    pic dump | grep -q '^effect 1 .* bash started safe=0 ' || fail "$point: the neighbour's call after the crash: $(pic dump | grep '^effect 1 ')"
    pic submit job-1 'make notes' > /dev/null
    pic run --script "$1" 2>/dev/null || fail "$point: run after the crash"
    out=$(pic dump)
    printf '%s\n' "$out" | grep -q '^submission 2 job-1 answered ' || fail "$point: not answered: $(printf '%s\n' "$out" | grep '^submission')"
    [ "$(printf '%s\n' "$out" | grep -c ' answer | \[{"type":"text","text":"done"}\]$')" = 1 ] || fail "$point: answer count"
    [ "$(cat "$WS/notes.txt")" = "hello from pic" ] || fail "$point: written file"
    printf '%s\n' "$out" | grep -q "^effect 3 .* bash $state safe=0 " || fail "$point: exec not $state: $(printf '%s\n' "$out" | grep '^effect')"
    [ "$(lines)" = "$ledger" ] || fail "$point: ledger has $(lines) lines, expected $ledger"
    failed=$(printf '%s\n' "$out" | grep -c '^generation .* failed' || true)
    [ "$failed" = "$generations" ] || fail "$point: $failed failed generations, expected $generations"
    printf '%s\n' "$out" | grep -q '^effect 1 .* bash started safe=0 ' || fail "$point: the neighbour's call was disturbed"
    pic check > /dev/null || fail "$point: check"
    touch "$WS/release-n"
    wait "$holder" || fail "$point: the neighbour failed: $(cat "$T/hold-n.err")"
    [ "$(status n1)" = answered ] || fail "$point: the neighbour's request: $(status n1)"
    pic dump | grep -q '^effect 1 .* bash done safe=0 ' || fail "$point: the neighbour's call"
    pic check > /dev/null || fail "$point: check at the end"
    printf 'PASS: beside a live pic, %s crash at %s (ledger=%s exec=%s failed-generations=%s)\n' "$2" "$point" "$ledger" "$state" "$generations"
    done
}
beside "$T/script" serial <<'EOF'
after-admit:1 1 done 0
after-generation-started:1 1 done 1
after-generation-started:2 1 done 1
after-generation-started:3 1 done 1
after-reply:1 1 done 1
after-reply:2 1 done 1
after-reply:3 1 done 1
after-assistant:1 1 done 0
after-assistant:2 1 done 0
after-started:1 1 done 0
after-started:2 0 unknown 0
after-exec:1 1 done 0
after-exec:2 1 unknown 0
after-result:1 1 done 0
after-result:2 1 done 0
after-answer:1 1 done 0
EOF
# One turn's two calls, one after the other (as crash.sh does them).
printf 'tool write notes.txt hello from pic\texec printf '"'"'ran\\n'"'"' >> "%s/ledger"\ntext done\n' "$T" > "$T/two.script"
"$PIC" settings toolExecution sequential
beside "$T/two.script" two-calls <<'EOF'
after-reply:1 1 done 1
after-assistant:1 1 done 0
after-started:1 1 done 0
after-started:2 0 unknown 0
after-exec:2 1 unknown 0
after-result:1 1 done 0
after-result:2 1 done 0
EOF
