#!/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.
pic name "$first" main-line
pic sessions | grep -q "^$first  main-line " || fail "name: $(pic sessions)"
[ "$(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'
