#!/bin/sh
# Compaction, Pi's algorithm: automatic past the window minus the reserve,
# the summary request and its prompts, the context sent after it (summary,
# kept entries without thinking, what followed), an update of a previous
# summary, a split turn with file tracking, pic compact, overflow retry, and
# crashes at each compaction commit point.
# --no-faults skips the crash cases (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-compact.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-compact-test-key
big() { yes "$1$1$1$1" | head -c 50000 | tr -d '\n'; } # 40000 characters: 10000 tokens by chars/4

# Automatic compaction, then an update of the summary, at a fake server.
DB="$T/journal.sqlite"
WS="$T/ws"
mkdir "$WS" "$T/log"
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
printf '{"type":"error","error":{"type":"invalid_request_error","message":"prompt is too long: 300000 tokens > 200000 maximum"}}' \
    > "$T/overflow.json"
text="sse:$STREAMS/text.sse"
# 1 reply, 2 reply with thinking, 3 summary, 4 reply, 5 summary update, 6 reply,
# 7 overflow, 8 summary, 9 reply; the last repeats.
"$SERVER" "$T/port" "$T/log" 120 "$text" "sse:$STREAMS/thinking.sse" "$text" "$text" "$text" "$text" \
    "status:400:$T/overflow.json" "$text" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do
    i=$((i + 1))
    [ "$i" -lt 100 ] || fail "server did not start"
    sleep 0.05
done
URL="http://127.0.0.1:$(cat "$T/port")/v1/messages"
run() { pic --context-window 26000 run --model anthropic/m --api-url "$URL" 2>> "$T/stderr" || fail "run: $(tail -2 "$T/stderr")"; }
req() { printf '%s/log/%s.req' "$T" "$1"; }

pic submit k1 "$(big A)" > /dev/null
run
s1=$(pic sessions | awk '{print $1}')
printf 'rule two\n' > "$WS/AGENTS.md" # an update lands after B, summarized by the second compaction
pic submit k2 "$(big B)" --session "$s1" > /dev/null
run
[ "$(pic dump | grep -c '^entry .* compaction ')" = 0 ] || fail "compacted under the threshold"
pic submit k3 "$(big C)" --session "$s1" > /dev/null
run
grep -q '"system":"You are a context summarization assistant.' "$(req 3)" || fail "summary: system prompt"
grep -q '<conversation>\\n\[User\]: AAAA' "$(req 3)" || fail "summary: conversation not serialized"
grep -q '\[Assistant\]: Hello' "$(req 3)" || fail "summary: assistant text"
grep -q 'BBBB' "$(req 3)" && fail "summary: kept entries summarized too"
grep -q '## Goal' "$(req 3)" || fail "summary: Pi's prompt"
grep -q '"tools"' "$(req 3)" && fail "summary: tools offered"
grep -q '"messages":\[{"role":"user","content":\[{"type":"text","text":"The conversation history before this point was compacted into the following summary:\\n\\n<summary>\\nHello, \\"world\\"\\n\\n</summary>"}\]},{"role":"user","content":"BBBB' "$(req 4)" ||
    fail "after: summary then the kept entries"
grep -q 'AAAA' "$(req 4)" && fail "after: summarized entries still sent"
grep -q '"type":"thinking"' "$(req 4)" && fail "after: thinking kept in a turn from before the compaction"
grep -q 'CCCC' "$(req 4)" || fail "after: the new message"
pic dump | grep -q '^generation .* done compaction' || fail "summary request not journaled"
pic log "$s1" | grep -q 'compacted [0-9]* tokens' || fail "log: compaction"
pic check > /dev/null || fail "integrity"
printf 'PASS: past the window the history is summarized; summary and kept entries go out, thinking dropped\n'

pic submit k4 "$(big D)" --session "$s1" > /dev/null
run
grep -q '<previous-summary>\\nHello' "$(req 5)" || fail "update: previous summary"
grep -q 'PRESERVE all existing information' "$(req 5)" || fail "update: Pi's update prompt"
grep -q '<conversation>\\n\[User\]: BBBB' "$(req 5)" || fail "update: summarizes from the last kept entry"
grep -q 'CCCC' "$(req 5)" && fail "update: kept entries summarized"
grep -q 'BBBB' "$(req 6)" && fail "update: old kept entries still sent"
grep -q '<project_instructions_update>\\n<project_context>.*rule two' "$(req 6)" || fail "update: summarized instructions not sent again"
[ "$(pic dump | grep -c '^entry .* instructions |')" = 2 ] || fail "update: instructions not appended once more"
printf 'PASS: a second compaction updates the previous summary; summarized instructions go out again\n'

# A context overflow from the provider compacts once and retries.
pic submit k5 "$(big E)" --session "$s1" > /dev/null
pic --context-window 0 run --model anthropic/m --api-url "$URL" 2>> "$T/stderr" || fail "overflow: $(tail -2 "$T/stderr")"
grep -q 'You are a context summarization assistant' "$(req 8)" || fail "overflow: no compaction"
pic dump | grep -q '^generation .* failed .*prompt is too long' || fail "overflow: failure not journaled"
[ "$(pic dump | grep -c '^submission .* answered ')" = 5 ] || fail "overflow: not answered"
pic check > /dev/null || fail "overflow: integrity"
printf 'PASS: a context overflow compacts and retries\n'
kill "$spid" 2>/dev/null || :
spid=

# A split turn, file tracking and pic compact, with the scripted provider.
DB="$T/split.sqlite"
cat > "$T/split.txt" <<'EOF'
tool write notes.txt hello
tool bash head -c 40000 /dev/zero | tr '\0' x
tool bash head -c 40000 /dev/zero | tr '\0' y
text done
text again
EOF
pic submit s1 'make notes' > /dev/null
pic --context-window 30000 run --script "$T/split.txt" 2>> "$T/stderr" || fail "split: $(tail -2 "$T/stderr")"
pic log > "$T/c.txt"; grep -q 'compacted [0-9]* tokens' "$T/c.txt" || fail "split: no compaction"
grep -q 'No prior history.' "$T/c.txt" || fail "split: $(cut -c1-200 "$T/c.txt")"
grep -q 'Turn Context (split turn)' "$T/c.txt" || fail "split: not joined as Pi joins it"
grep -q '<modified-files>' "$T/c.txt" && grep -q 'notes.txt' "$T/c.txt" || fail "split: files not tracked"
[ "$(pic dump | grep -c '^entry .* answer ')" = 1 ] || fail "split: no answer"
pic check > /dev/null || fail "split: integrity"
printf 'PASS: a long single task splits its turn; files read and modified are kept\n'

s2=$(pic sessions | awk 'NR==1{print $1}')
[ "$(pic compact "$s2" 'focus on notes')" = "$s2 will be compacted before its next request" ] || fail "compact: request"
pic submit s2 "$(big F)" --session "$s2" > /dev/null
pic --context-window 0 run --script "$T/split.txt" 2>> "$T/stderr" || fail "compact: $(tail -2 "$T/stderr")"
[ "$(pic dump | grep -c '^entry .* compaction ')" = 2 ] || fail "compact: not compacted on request"
pic log "$s2" | grep -q 'scripted summary, updated' || fail "compact: not an update"
pic log "$s2" | awk '/compacted [0-9]* tokens/{n++} n == 2' | grep -q '^notes.txt$' ||
    fail "compact: files from the first compaction not carried forward"
pic check > /dev/null || fail "compact: integrity"
printf 'PASS: pic compact summarizes before the next request\n'

if [ "$FAULTS" = yes ]; then
    for point in after-compaction-started after-summary after-compaction; do
        DB="$T/crash-$point.sqlite"
        pic submit c1 'make notes' > /dev/null
        rc=0
        env PIC_CRASH_AT="$point:1" "$PIC" --db "$DB" --workspace "$WS" --context-window 30000 run --script "$T/split.txt" \
            > /dev/null 2>&1 || rc=$?
        [ "$rc" = 77 ] || fail "crash $point: expected exit 77, got $rc"
        pic --context-window 30000 run --script "$T/split.txt" 2>> "$T/stderr" || fail "crash $point: $(tail -2 "$T/stderr")"
        [ "$(pic dump | grep -c '^entry .* compaction ')" = 1 ] || fail "crash $point: compactions"
        [ "$(pic dump | grep -c '^entry .* answer ')" = 1 ] || fail "crash $point: answer"
        pic check > /dev/null || fail "crash $point: integrity"
    done
    printf 'PASS: a crash at each compaction commit point recovers to one compaction\n'
fi
