#!/bin/sh
# Sessions: follow-ups continue a conversation, forks branch it, one request
# at a time per session, the opening prompt is frozen and edited project
# instructions are appended. Requests are checked at a fake server.
# --no-faults skips the crash case (the release build has no crash hooks).
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
STREAMS=$(cd "$(dirname "$0")/streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-sessions.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME"
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null || :; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export ANTHROPIC_API_KEY=pic-sessions-test-key
DB="$T/journal.sqlite"
WS="$T/ws"
mkdir "$WS" "$T/log"
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
"$SERVER" "$T/port" "$T/log" 120 "sse:$STREAMS/text.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do
i=$((i + 1))
[ "$i" -lt 600 ] || fail "server did not start"
sleep 0.05
done
URL="http://127.0.0.1:$(cat "$T/port")/v1/messages"
run() { pic run --model anthropic/m --api-url "$URL" 2>> "$T/stderr" || fail "run: $(tail -2 "$T/stderr")"; }
req() { ls "$T/log" | sort -n | tail -1 | sed "s|^|$T/log/|"; }
A='{"role":"assistant","content":\[{"type":"text","text":"Hello, \\"world\\"\\n"}\]}'
# A follow-up continues the conversation.
printf 'rule one\n' > "$WS/AGENTS.md"
pic submit k1 'first' > /dev/null
run
first=$(pic sessions | awk '{print $1}')
[ -n "$first" ] || fail "no session listed"
pic submit k2 'second' --session "$first" > /dev/null
run
grep -q "\"messages\":\[{\"role\":\"user\",\"content\":\"first\"},$A,{\"role\":\"user\",\"content\":\[{\"type\":\"text\",\"text\":\"second\",\"cache_control\":{\"type\":\"ephemeral\"}}\]}\]" "$(req)" ||
fail "follow-up: earlier turns not sent"
printf 'PASS: a follow-up carries the conversation so far\n'
# One unfinished request per session.
pic submit k3 'third' --session latest > /dev/null
if pic submit k4 'fourth' --session "$first" 2> "$T/busy.err"; then fail "busy: second request admitted"; fi
grep -q 'still working on a request' "$T/busy.err" || fail "busy: $(cat "$T/busy.err")"
# Edit the project instructions mid-session: the opening prompt stays as it
# was; the update is appended once, at this point of the conversation.
printf 'rule two\n' > "$WS/AGENTS.md"
run
grep -q 'rule one' "$(req)" || fail "frozen: opening prompt changed"
grep -q "{\"role\":\"user\",\"content\":\"third\"},{\"role\":\"user\",\"content\":\[{\"type\":\"text\",\"text\":\"<project_instructions_update>\\\\n<project_context>" "$(req)" ||
fail "instructions: update not appended after the new message"
grep -q 'rule two' "$(req)" || fail "instructions: new text missing"
[ "$(pic dump | grep -c '^entry .* instructions |')" = 1 ] || fail "instructions: not journaled once"
pic submit k4 'fourth' --session "$first" > /dev/null
run
[ "$(pic dump | grep -c '^entry .* instructions |')" = 1 ] || fail "instructions: appended again without a change"
printf 'PASS: one request at a time; prompt frozen, edited instructions appended once\n'
# A fork continues from an earlier point; the other branch is not seen.
answer1=$(pic dump | awk '/^entry [0-9]+ 1 answer /{print $2; exit}')
fork=$(pic fork "$first" --at "$answer1")
[ -n "$fork" ] && [ "$fork" != "$first" ] || fail "fork: no new session"
pic submit k5 'alternative' --session "$fork" > /dev/null
run
grep -q "\"messages\":\[{\"role\":\"user\",\"content\":\"first\"},$A,{\"role\":\"user\",\"content\":\[{\"type\":\"text\",\"text\":\"alternative\",\"cache_control\":{\"type\":\"ephemeral\"}}\]}\]" "$(req)" ||
fail "fork: branch does not continue from its point alone"
if pic fork "$first" --at 1 2> "$T/fork.err"; then fail "fork: allowed at a user entry"; fi
grep -q 'not a point to fork' "$T/fork.err" || fail "fork: $(cat "$T/fork.err")"
grep -q 'the latest are [0-9]' "$T/fork.err" || fail "fork: valid points not named: $(cat "$T/fork.err")"
if pic --bogus sessions 2> "$T/opt.err"; then fail "unknown option accepted"; fi
grep -q 'unknown option --bogus' "$T/opt.err" || fail "unknown option: $(head -1 "$T/opt.err")"
if pic submit k8 x --session nosuch 2> "$T/ns.err"; then fail "unknown conversation accepted"; fi
grep -q 'no session nosuch (pic sessions lists them)' "$T/ns.err" || fail "unknown conversation: $(cat "$T/ns.err")"
printf 'PASS: a fork branches from its point; bad fork points are refused\n'
# Listing, naming and the log. A conversation's title is its first prompt until it is named.
pic sessions | grep -q "^$first .* first\$" || fail "title: first prompt: $(pic sessions)"
pic sessions --json | grep -F "\"id\":\"$first\"" | grep -qF '"title":"first"' || fail "title: json: $(pic sessions --json)"
pic sessions --json | grep -F "\"id\":\"$fork\"" | grep -qF '"title":"alternative"' || fail "title: fork: $(pic sessions --json)"
pic name "$first" main-line
pic sessions | grep -q "^$first .* main-line\$" || fail "name: $(pic sessions)"
pic sessions --json | grep -F "\"id\":\"$first\"" | grep -qF '"title":"main-line"' || fail "name: json: $(pic sessions --json)"
[ "$(pic sessions | wc -l | tr -d ' ')" = 2 ] || fail "sessions: count"
pic log "$fork" | grep -q 'you: alternative' || fail "log: fork"
if pic log "$fork" | grep -q 'you: second'; then fail "log: fork shows the other branch"; fi
pic log "$first" | grep -q 'project instructions updated' || fail "log: instructions"
pic check > /dev/null || fail "integrity"
printf 'PASS: sessions are listed, named and logged along their path\n'
if [ "$FAULTS" = yes ]; then
rc=0
env PIC_CRASH_AT=after-admit:1 "$PIC" --db "$DB" --workspace "$WS" submit k6 'after crash' --session "$first" \
> /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "crash: expected a crash at after-admit, got $rc"
[ "$(pic submit k6 'after crash' --session "$first")" = "duplicate: already admitted" ] || fail "crash: resubmit"
run
pic check > /dev/null || fail "crash: integrity"
grep -q '"content":"fourth"},.*{"role":"user","content":\[{"type":"text","text":"after crash"' "$(req)" || fail "crash: conversation"
printf 'PASS: a crash after joining a session recovers into it\n'
fi
# Export: finished entries as JSON lines; the entry number is the cursor and
# an unfinished request holds back everything from its first entry on.
pic export > "$T/all.jsonl"
n=$(wc -l < "$T/all.jsonl" | tr -d ' ')
[ "$n" = "$(pic dump | grep -c '^entry ')" ] || fail "export: $n lines for $(pic dump | grep -c '^entry ') entries"
while IFS= read -r line; do
printf '%s' "$line" | grep -q '^{"conversation":"[0-9a-f]*","seq":[0-9]*,' || fail "export: record shape: $line"
done < "$T/all.jsonl"
grep -q '"role":"user","time":"20[0-9-]*T[0-9:.]*Z","workspace":"/[^"]*/ws","text":"first"}' "$T/all.jsonl" ||
fail "export: user record"
grep -q '"role":"assistant",.*"model":"anthropic/m","text":"Hello, \\"world\\"\\n","final":true}' "$T/all.jsonl" ||
fail "export: answer record"
last=$(tail -1 "$T/all.jsonl" | sed 's/^{"conversation":"[0-9a-f]*","seq":\([0-9]*\),.*/\1/')
[ -z "$(pic export --since "$last")" ] || fail "export: cursor repeats"
pic submit k9 'pending' --session "$fork" > /dev/null
[ -z "$(pic export --since "$last")" ] || fail "export: unfinished request exported"
run
[ "$(pic export --since "$last" | wc -l | tr -d ' ')" = 2 ] || fail "export: finished request not exported"
printf 'PASS: export hands out finished entries once, by entry number\n'
# A prompt cancelled before its reply and a "!" command each end their
# request, so each is a point to fork from, as Pi's /fork and /tree offer
# them (field test #6); a prompt its reply follows is still not one.
pic submit k10 'cancel me' --session "$fork" > /dev/null
pic cancel k10 > /dev/null
cancelled=$(pic dump | awk '/^entry [0-9]+ [0-9]+ user \| cancel me$/{print $2}')
pic fork "$fork" --at "$cancelled" > /dev/null 2> "$T/fork2.err" || fail "fork: refused at a cancelled prompt: $(cat "$T/fork2.err")"
pic bash --session "$fork" "echo from-bang" > /dev/null
bashed=$(pic dump | awk '/^entry [0-9]+ [0-9]+ user \| /{s=$2} END{print s}')
pic fork "$fork" --at "$bashed" > /dev/null 2> "$T/fork3.err" || fail "fork: refused at a ! command: $(cat "$T/fork3.err")"
if pic fork "$first" --at 1 2> /dev/null; then fail "fork: allowed at a prompt its reply follows"; fi
pic check > /dev/null || fail "fork points: integrity"
printf 'PASS: a cancelled prompt and a ! command are points to fork from\n'
# Deleting: a deleted conversation is listed nowhere and is not "latest"; restoring brings it back;
# a running one is refused; a purge empties it for good, but not what a fork still shows.
SQL=${SQLITE3:-sqlite3}
DB="$T/trash.sqlite"
WS="$T/trash-ws"
mkdir "$WS"
script() { printf '%s\n' "$@" > "$T/tscript"; pic run --script "$T/tscript" > /dev/null 2>> "$T/stderr" || fail "run: $(tail -2 "$T/stderr")"; }
pic submit t1 'beta question' > /dev/null
script 'text beta-reply'
beta=$("$SQL" "$DB" "SELECT session_id FROM pic_submission WHERE request_key = 't1'")
pic submit t2 'alpha-secret question' > /dev/null
script 'tool write a.txt alpha-secret-file' 'tool exec echo alpha-secret-out' 'text alpha-secret-reply'
alpha=$("$SQL" "$DB" "SELECT session_id FROM pic_submission WHERE request_key = 't2'")
pic name "$alpha" alpha
pic sessions delete alpha > "$T/del.out" || fail "delete by name"
grep -q "^deleted $alpha alpha (pic sessions restore $alpha brings it back)\$" "$T/del.out" || fail "delete: $(cat "$T/del.out")"
if pic sessions | grep -q "$alpha"; then fail "delete: still listed: $(pic sessions)"; fi
if pic sessions --json | grep -q "$alpha"; then fail "delete: still in json"; fi
pic sessions trash | grep -q "^$alpha deleted [0-9-]* [0-9:]* alpha (gone for good in 30 days)\$" || fail "trash: $(pic sessions trash)"
pic sessions trash --json | grep -q "\"id\":\"$alpha\",\"name\":\"alpha\",\"title\":\"alpha\",\"deletedMs\":[0-9]*,\"purgeMs\":[0-9]*}" ||
fail "trash json: $(pic sessions trash --json)"
pic submit t3 'to latest' --session latest > /dev/null
[ "$("$SQL" "$DB" "SELECT session_id FROM pic_submission WHERE request_key = 't3'")" = "$beta" ] || fail "latest: went to a deleted one"
pic cancel t3 > /dev/null
if pic submit t4 'into deleted' --session "$alpha" 2> "$T/sub.err"; then fail "submit: a deleted conversation took a request"; fi
grep -q "conversation $alpha is deleted (pic sessions restore $alpha brings it back)" "$T/sub.err" || fail "submit: $(cat "$T/sub.err")"
pic sessions delete "$alpha" > /dev/null || fail "delete: a repeat by id is not a no-op"
pic sessions restore > "$T/res.out" || fail "restore"
grep -q "^restored $alpha alpha\$" "$T/res.out" || fail "restore: $(cat "$T/res.out")"
pic sessions | grep -q "^$alpha " || fail "restore: not listed: $(pic sessions)"
[ -z "$(pic sessions trash)" ] || fail "restore: still in the trash"
if pic sessions restore 2> "$T/res.err"; then fail "restore: an empty trash restored something"; fi
grep -q 'no deleted conversation to restore' "$T/res.err" || fail "restore: $(cat "$T/res.err")"
pic check > /dev/null || fail "delete and restore: integrity"
printf 'PASS: a deleted conversation is hidden everywhere and restored by undo\n'
# Archived: out of pic sessions and its JSON, listed by pic sessions archived (with "archived":true),
# a repeat a no-op; a new message brings it back; pic unarchive too.
pic archive alpha > "$T/arc.out" || fail "archive by name"
grep -q "^archived $alpha alpha (pic unarchive $alpha brings it back)\$" "$T/arc.out" || fail "archive: $(cat "$T/arc.out")"
if pic sessions | grep -q "$alpha"; then fail "archive: still listed: $(pic sessions)"; fi
if pic sessions --json | grep -q "$alpha"; then fail "archive: still in json"; fi
pic sessions archived | grep -q "^$alpha " || fail "archived: $(pic sessions archived)"
pic sessions archived --json | grep -q "\"id\":\"$alpha\",.*\"archived\":true" || fail "archived json: $(pic sessions archived --json)"
pic archive "$alpha" > /dev/null || fail "archive: a repeat is not a no-op"
[ "$("$SQL" "$DB" "SELECT count(*) FROM pic_archive")" = 1 ] || fail "archive: rows $("$SQL" "$DB" "SELECT * FROM pic_archive")"
pic submit t3a 'back again' --session "$alpha" > /dev/null || fail "archive: a request into an archived conversation"
pic cancel t3a > /dev/null
pic sessions | grep -q "^$alpha " || fail "archive: a new message did not bring it back: $(pic sessions)"
[ -z "$(pic sessions archived)" ] || fail "archive: still archived after a message"
pic archive "$alpha" > /dev/null
pic unarchive "$alpha" > "$T/unarc.out" || fail "unarchive"
grep -q "^unarchived $alpha alpha\$" "$T/unarc.out" || fail "unarchive: $(cat "$T/unarc.out")"
pic sessions | grep -q "^$alpha " || fail "unarchive: not listed"
if pic archive nosuchthing 2> "$T/arc.err"; then fail "archive: an unknown conversation"; fi
grep -q 'no conversation nosuchthing' "$T/arc.err" || fail "archive: $(cat "$T/arc.err")"
pic check > /dev/null || fail "archive: integrity"
printf 'PASS: an archived conversation leaves the lists, is listed as archived, and comes back on a message or unarchive\n'
# Running: an unfinished request, or another pic holding it, refuses; the request is untouched.
pic submit t5 'pending' --session "$beta" > /dev/null
if pic sessions delete "$beta" 2> "$T/run.err"; then fail "delete: an unfinished request was deleted"; fi
grep -qx 'pic: "beta question" is running. Stop it, then delete it.' "$T/run.err" || fail "running: $(cat "$T/run.err")"
pic sessions | grep -q "^$beta " || fail "running: not listed"
HOLD='i=0; while [ ! -e release ] && [ $i -lt 1200 ]; do sleep 0.1; i=$((i + 1)); done'
printf 'tool exec touch holding; %s\ntext held\n' "$HOLD" > "$T/slow"
pic run --script "$T/slow" > /dev/null 2>&1 &
holder=$!
i=0; while [ ! -e "$WS/holding" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || { touch "$WS/release"; fail "hold: never started"; }; sleep 0.1; done
if pic sessions delete "$beta" 2> "$T/run2.err"; then touch "$WS/release"; fail "delete: a running conversation was deleted"; fi
grep -q 'is running. Stop it, then delete it.' "$T/run2.err" || { touch "$WS/release"; fail "running: $(cat "$T/run2.err")"; }
touch "$WS/release"
wait "$holder" || fail "hold: the run failed"
pic sessions delete "$beta" > /dev/null || fail "delete: refused once stopped"
pic sessions restore "$beta" > /dev/null || fail "restore by id"
printf 'PASS: a running conversation cannot be deleted until it stops\n'
# Purge: a fork keeps what it shares; once nothing listed shows it, the text is gone for good.
answer=$("$SQL" "$DB" "SELECT max(e.seq) FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id WHERE u.request_key = 't2'")
fork=$(pic fork "$alpha" --at "$answer")
pic submit t6 'fork question' --session "$fork" > /dev/null
script 'text fork-reply'
pic sessions delete "$alpha" > /dev/null
[ "$(pic sessions empty-trash)" = "purged 1 conversation for good" ] || fail "empty-trash: count"
pic check > /dev/null || fail "purge: integrity"
pic log "$fork" | grep -q 'you: alpha-secret question' || fail "purge: the fork lost what it shares: $(pic log "$fork")"
if pic sessions restore "$alpha" 2> /dev/null; then fail "purge: a purged conversation came back"; fi
if pic log "$alpha" > /dev/null 2>&1; then fail "purge: a purged conversation still resolves"; fi
[ -z "$(pic sessions trash)" ] || fail "purge: still in the trash"
pic sessions delete "$fork" > /dev/null
pic sessions empty-trash > /dev/null
pic check > /dev/null || fail "purge: integrity after the fork"
"$SQL" "$DB" 'PRAGMA wal_checkpoint(TRUNCATE)' > /dev/null
if "$SQL" "$DB" .dump | grep -q 'alpha-secret\|fork-reply\|fork question'; then
fail "purge: text left: $("$SQL" "$DB" .dump | grep 'alpha-secret\|fork-reply\|fork question' | head -3)"
fi
"$SQL" "$DB" .dump | grep -q 'beta-reply' || fail "purge: touched a conversation not deleted"
[ "$(pic sessions | wc -l | tr -d ' ')" = 1 ] || fail "purge: $(pic sessions)"
printf 'PASS: a purge keeps a fork whole, then leaves no text and a sound journal\n'
# Thirty days on, the next pic to open the journal purges by itself; a newer one is kept.
pic sessions delete "$beta" > /dev/null
"$SQL" "$DB" "UPDATE pic_trash SET deleted_ms = deleted_ms - 31 * 86400000 WHERE session_id = '$beta';
DELETE FROM pic_meta WHERE key = 'last_prune_ms'"
pic sessions > /dev/null
[ -n "$("$SQL" "$DB" "SELECT purged_ms FROM pic_trash WHERE session_id = '$beta'")" ] || fail "retention: not purged after 30 days"
"$SQL" "$DB" 'PRAGMA wal_checkpoint(TRUNCATE)' > /dev/null
if "$SQL" "$DB" .dump | grep -q 'beta-reply'; then fail "retention: text left"; fi
pic check > /dev/null || fail "retention: integrity"
printf 'PASS: deleted conversations are purged after 30 days\n'