#!/bin/sh
# Branch summaries, Pi's /tree with "Summarize": pic fork --at ENTRY
# --summarize asks the model for a summary of the branch left behind (Pi's
# prompt, tool results left out, files tracked), journals it as a generation
# of purpose branch_summary, and starts a new conversation with it, which the
# next request carries as Pi's user message. Custom instructions, the
# branchSummary.reserveTokens budget, a crash during the request, pic log and
# the Pi export.
# --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-branch.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; [ -n "${KEEP:-}" ] && { echo "kept $T" >&2; return; }; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export ANTHROPIC_API_KEY=pic-branch-test-key PIC_PI_EXPORT=0
"$PIC" settings cacheRetention none > /dev/null

DB="$T/journal.sqlite"
WS="$T/ws"
mkdir "$WS" "$T/log"
# 1 reply, 2 a write call, then text for every request after.
"$SERVER" "$T/port" "$T/log" 120 "sse:$STREAMS/text.sse" "sse:$STREAMS/tool_use.sse" "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
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"m","contextWindow":200000}]}}}' \
    "$(cat "$T/port")" > "$T/models.json"
export PIC_MODELS_FILE="$T/models.json"
pic() { "$PIC" --db "$DB" --workspace "$WS" --model fake/m "$@"; }
req() { printf '%s/log/%s.req' "$T" "$1"; }
nreq() { ls "$T/log" | grep -c '\.req$'; }
# The entry that ends conversation $1's first request.
first_end() { pic tree --json "$1" | head -1 | sed 's/.*"end":\([0-9]*\).*/\1/'; }

pic ask 'first question' > /dev/null 2>> "$T/stderr" || fail "ask 1: $(tail -2 "$T/stderr")"
s1=$(pic sessions | awk 'NR==1{print $1}')
pic ask --session "$s1" 'side quest' > /dev/null 2>> "$T/stderr" || fail "ask 2: $(tail -2 "$T/stderr")"
[ -f "$WS/notes.txt" ] || fail "setup: the side quest did not write"
head=$(sqlite3 "$DB" "SELECT head_seq FROM pic_session WHERE id = '$s1'")
at=$(first_end "$s1")
[ -n "$at" ] && [ "$at" -lt "$head" ] || fail "setup: no first request end ($at, head $head)"

# Leaving the side quest for the end of the first request, with a summary.
n=$(nreq)
s2=$(pic fork "$s1" --at "$at" --summarize 2>> "$T/stderr") || fail "summarize: $(tail -2 "$T/stderr")"
[ "$(nreq)" = $((n + 1)) ] || fail "summarize: expected one request"
r=$(req $((n + 1)))
grep -q '"system":"You are a context summarization assistant.' "$r" || fail "summary: system prompt"
grep -q '<conversation>\\n\[User\]: side quest\\n\\n\[Assistant\]: Writing it.\\n\\n\[Assistant tool calls\]: write(path=\\"notes.txt\\", content=\\"hi\\")\\n\\n\[Assistant\]: Hello' "$r" ||
    fail "summary: branch not serialized: $(cut -c1-600 "$r")"
grep -q 'first question' "$r" && fail "summary: the common history was summarized"
grep -q 'Tool result' "$r" && fail "summary: tool results are left out of a branch summary"
grep -q 'Create a structured summary of this conversation branch for context when returning later.' "$r" ||
    fail "summary: Pi's branch prompt"
grep -q 'Additional focus' "$r" && fail "summary: focus without instructions"
grep -q '"tools"' "$r" && fail "summary: tools offered"
[ "$s2" != "$s1" ] || fail "summary: no new conversation"
pic dump | grep -q '^entry .* branch_summary ' || fail "summary: no branch_summary entry"
pic dump | grep -q '^generation .* done branch_summary' || fail "summary: request not journaled"
[ "$(sqlite3 "$DB" "SELECT kind || ' ' || parent_seq || ' ' || from_seq FROM pic_entry e JOIN pic_session s ON s.head_seq = e.seq WHERE s.id = '$s2'")" = \
    "branch_summary $at $head" ] || fail "summary: entry not at the target, from the old head"
[ "$(sqlite3 "$DB" "SELECT json_extract(native, '\$.modifiedFiles[0]') FROM pic_entry WHERE kind = 'branch_summary'")" = notes.txt ] ||
    fail "summary: files not tracked"
sqlite3 "$DB" "SELECT body FROM pic_entry WHERE kind = 'branch_summary'" > "$T/summary.txt"
grep -q '^The user explored a different conversation branch before returning here.$' "$T/summary.txt" ||
    fail "summary: no preamble: $(cat "$T/summary.txt")"
grep -q '^<modified-files>$' "$T/summary.txt" || fail "summary: files not appended"
[ "$(sqlite3 "$DB" "SELECT json_type(usage, '\$.pic_cost') FROM pic_generation WHERE purpose = 'branch_summary' AND state = 'done'")" = object ] ||
    fail "summary: not priced"
[ "$(sqlite3 "$DB" "SELECT head_seq FROM pic_session WHERE id = '$s1'")" = "$head" ] || fail "summary: the old conversation moved"
pic check > /dev/null || fail "summary: integrity"
printf 'PASS: leaving a branch with a summary asks Pi'"'"'s prompt of the branch alone, priced and journaled\n'

# The next request in the new conversation carries the summary as Pi's user message.
pic ask --session "$s2" 'third' > /dev/null 2>> "$T/stderr" || fail "ask 3: $(tail -2 "$T/stderr")"
r=$(req "$(nreq)")
grep -q '{"role":"user","content":\[{"type":"text","text":"The following is a summary of a branch that this conversation came back from:\\n\\n<summary>\\nThe user explored a different conversation branch before returning here.\\nSummary of that exploration:\\n\\nHello, \\"world\\"\\n\\n\\n<modified-files>\\nnotes.txt\\n</modified-files></summary>"}\]}' "$r" ||
    fail "next: no summary message: $(cut -c1-900 "$r")"
grep -q 'first question' "$r" || fail "next: lost the common history"
grep -q 'side quest' "$r" && fail "next: the left branch still sent"
grep -q '"content":"third"' "$r" || fail "next: the new message"
[ "$(awk -v a='first question' -v b='following is a summary' -v c='"third"' '{ i = index($0, a); j = index($0, b); k = index($0, c); print (i < j && j < k) }' "$r" | tail -1)" = 1 ] ||
    fail "next: summary not between the history and the new message"
pic log "$s2" | grep -q 'branch summary (of the branch ending at' || fail "log: branch summary"
pic tree --json "$s1" | grep -q "\"end\":$at," || fail "tree: the summary moved the request's end"
pic tree --json "$s1" | grep -q "$s2" || fail "tree: the new conversation is not listed"
pic check > /dev/null || fail "next: integrity"
printf 'PASS: the next request carries the branch summary between the history and the new message\n'

# The Pi export: a branch_summary entry with fromId, details and usage.
mkdir "$T/pi"
pic export --pi "$T/pi" > /dev/null 2>> "$T/stderr" || fail "export: $(tail -2 "$T/stderr")"
f=$(ls "$T/pi/"*"_$s2.jsonl" 2>/dev/null | head -1)
[ -n "$f" ] || fail "export: no file: $(ls "$T/pi")"
line=$(grep '"type":"branch_summary"' "$f") || fail "export: no branch_summary entry: $(cat "$f")"
sum=$(sqlite3 "$DB" "SELECT seq FROM pic_entry WHERE kind = 'branch_summary'")
printf '%s\n' "$line" | grep -q "^{\"type\":\"branch_summary\",\"id\":\"$sum\",\"parentId\":\"$at\",\"timestamp\":\"[0-9T:.Z-]*\",\"fromId\":\"$head\",\"summary\":\"The user explored" ||
    fail "export: entry shape: $line"
printf '%s\n' "$line" | grep -q '"details":{"readFiles":\[\],"modifiedFiles":\["notes.txt"\]},"usage":{"input":25,"output":12,' ||
    fail "export: details and usage: $line"
printf '%s\n' "$line" | grep -q '"fromHook":false}$' || fail "export: fromHook: $line"
grep -q '"content":\[{"type":"text","text":"third"}\]' "$f" || fail "export: the next message"
printf 'PASS: the Pi export writes Pi'"'"'s branch_summary entry\n'

# Custom instructions are Pi's additional focus.
n=$(nreq)
pic fork "$s1" --at "$at" --summarize --instructions 'focus on notes' > /dev/null 2>> "$T/stderr" || fail "focus: $(tail -2 "$T/stderr")"
grep -q 'error messages.\\n\\nAdditional focus: focus on notes"' "$(req $((n + 1)))" || fail "focus: not appended"
printf 'PASS: custom instructions go in as Pi'"'"'s additional focus\n'

# branchSummary.reserveTokens: the branch's newest messages within the window
# minus the reserve; an older one past it is left out.
"$PIC" settings branchSummary '{"reserveTokens":25000}' > /dev/null
big=$(yes BIGBIG | head -c 80000 | tr -d '\n')
pic ask --session "$s1" "$big" > /dev/null 2>> "$T/stderr" || fail "budget ask: $(tail -2 "$T/stderr")"
pic ask -c 'small one' > /dev/null 2>> "$T/stderr" || fail "budget ask 2: $(tail -2 "$T/stderr")"
s3=$(pic sessions | awk 'NR==1{print $1}')
n=$(nreq)
pic --context-window 40000 fork "$s3" --at "$at" --summarize > /dev/null 2>> "$T/stderr" || fail "budget: $(tail -2 "$T/stderr")"
r=$(req $((n + 1)))
grep -q 'small one' "$r" || fail "budget: the newest message left out"
grep -q 'BIGBIG' "$r" && fail "budget: a message past the budget was sent"
# A budget nothing fits: Pi's "No content to summarize", with no request.
"$PIC" settings branchSummary '{"reserveTokens":39999}' > /dev/null
n=$(nreq)
s6=$(pic --context-window 40000 fork "$s3" --at "$at" --summarize 2>> "$T/stderr") || fail "empty budget: $(tail -2 "$T/stderr")"
[ "$(nreq)" = "$n" ] || fail "empty budget: a request was made"
[ "$(sqlite3 "$DB" "SELECT e.body FROM pic_entry e JOIN pic_session s ON s.head_seq = e.seq WHERE s.id = '$s6'")" = 'No content to summarize' ] ||
    fail "empty budget: summary"
pic check > /dev/null || fail "empty budget: integrity"
"$PIC" settings --unset branchSummary
n=$(nreq)
pic --context-window 40000 fork "$s3" --at "$at" --summarize > /dev/null 2>> "$T/stderr" || fail "budget 2: $(tail -2 "$T/stderr")"
grep -q 'BIGBIG' "$(req $((n + 1)))" || fail "budget: the default reserve left the message out"
pic check > /dev/null || fail "budget: integrity"
printf 'PASS: branchSummary.reserveTokens bounds what a branch summary sends\n'

# Nothing left behind (the target is past the head): a plain fork, no request.
s4=$(pic fork "$s2")
pic ask --session "$s2" 'more' > /dev/null 2>> "$T/stderr" || fail "descendant ask: $(tail -2 "$T/stderr")"
past=$(sqlite3 "$DB" "SELECT head_seq FROM pic_session WHERE id = '$s2'")
n=$(nreq)
s5=$(pic fork "$s4" --at "$past" --summarize 2>> "$T/stderr") || fail "descendant: $(tail -2 "$T/stderr")"
[ "$(nreq)" = "$n" ] || fail "descendant: a request was made"
[ "$(sqlite3 "$DB" "SELECT head_seq FROM pic_session WHERE id = '$s5'")" = "$past" ] || fail "descendant: not at the target"
pic fork "$s2" --at "$past" --summarize > /dev/null 2>&1 && fail "the head itself was taken"
pic fork "$s2" --at "$past" --summarize --bogus x > /dev/null 2>&1 && fail "a bad option was taken"
pic check > /dev/null || fail "descendant: integrity"
printf 'PASS: with nothing left behind there is no summary, as in Pi\n'

if [ "$FAULTS" = yes ]; then
    for point in after-branch-summary-started after-branch-summary; do
        before=$(sqlite3 "$DB" "SELECT count(*) FROM pic_entry WHERE kind = 'branch_summary'")
        sessions=$(sqlite3 "$DB" "SELECT count(*) FROM pic_session")
        rc=0
        env PIC_CRASH_AT="$point:1" "$PIC" --db "$DB" --workspace "$WS" --model fake/m fork "$s1" --at "$at" --summarize \
            > /dev/null 2>&1 || rc=$?
        [ "$rc" = 77 ] || fail "crash $point: expected exit 77, got $rc"
        pic check > /dev/null || fail "crash $point: integrity after the crash"
        [ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_entry WHERE kind = 'branch_summary'")" = "$before" ] ||
            fail "crash $point: an entry survived the crash"
        [ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_session")" = "$sessions" ] || fail "crash $point: a conversation survived"
        sqlite3 "$DB" "SELECT state || ' ' || error FROM pic_generation WHERE purpose = 'branch_summary' ORDER BY id DESC LIMIT 1" |
            grep -q '^failed interrupted' || fail "crash $point: the attempt not failed"
        pic fork "$s1" --at "$at" --summarize > /dev/null 2>> "$T/stderr" || fail "crash $point: retry: $(tail -2 "$T/stderr")"
        [ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_entry WHERE kind = 'branch_summary'")" = $((before + 1)) ] ||
            fail "crash $point: not exactly one summary after the retry"
        [ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_session")" = $((sessions + 1)) ] || fail "crash $point: conversations"
        pic check > /dev/null || fail "crash $point: integrity"
    done
    printf 'PASS: a crash during a branch summary leaves no entry; the retry makes exactly one\n'
fi
