#!/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 600 ] || 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

# ---- lapse compaction without a summary (lapseMode trim, the default) ------
# A conversation idle past the cache's lifetime (the floor at 0: the fake
# server reports few tokens) keeps its newest 20000 tokens
# and drops the rest with no summary request; the cut never parts a tool call
# from its result, and SessionStart fires with source compact after it.
kill "$spid" 2>/dev/null || :
spid=
DB="$T/trim.sqlite"
rm -rf "$T/log" "$T/port"
mkdir "$T/log"
awk 'BEGIN { for (i = 0; i < 600; i++) printf "%079d\n", i }' > "$WS/big.txt" # 48000 characters
sed -e 's/"name":"write"/"name":"read"/' \
    -e 's/"partial_json":"{\\"path\\": \\"notes.txt\\", "/"partial_json":"{\\"path\\": \\"big.txt\\"}"/' \
    -e 's/"partial_json":"\\"content\\": \\"hi\\"}"/"partial_json":""/' "$STREAMS/tool_use.sse" > "$T/read.sse"
grep -q '"name":"read"' "$T/read.sse" && grep -q 'big.txt' "$T/read.sse" || fail "trim: read fixture"
# 1 reply to A, 2 the read, 3 reply after it, 4 reply to C, 5 reply after the lapse.
"$SERVER" "$T/port" "$T/log" 120 "$text" "sse:$T/read.sse" "$text" "$text" "$text" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "trim: server did not start"; sleep 0.05; done
URL="http://127.0.0.1:$(cat "$T/port")/v1/messages"
mkdir -p "$HOME/.pic"
cat > "$T/ss.sh" <<'HOOK'
input=$(cat)
printf '%s\n' "$input" >> "$1/ss.log"
case "$input" in *'"source":"compact"'*) echo brief-after-compact ;; *) echo startup-note ;; esac
HOOK
printf '{"hooks": {"SessionStart": [{"hooks": [{"type": "command", "command": "sh %s/ss.sh %s"}]}]}}\n' "$T" "$T" > "$HOME/.pic/hooks.json"
trun() {
    PIC_LAPSE_HOLDOUT=0 "$PIC" --db "$DB" --workspace "$WS" --lapse-floor 0 run --model anthropic/m --api-url "$URL" \
        2>> "$T/stderr" || fail "trim run: $(tail -2 "$T/stderr")"
}
"$PIC" --db "$DB" --workspace "$WS" submit t1 "$(big A)" > /dev/null
trun
ts=$("$PIC" --db "$DB" sessions | awk 'NR == 1 {print $1}')
"$PIC" --db "$DB" --workspace "$WS" submit t2 'read big.txt' --session "$ts" > /dev/null
trun
"$PIC" --db "$DB" --workspace "$WS" submit t3 "$(big C)" --session "$ts" > /dev/null
trun
[ "$(ls "$T/log" | grep -c '\.req$')" = 4 ] || fail "trim: requests before the lapse: $(ls "$T/log")"
sqlite3 "$DB" "UPDATE pic_entry SET created_ms = created_ms - 400000"
"$PIC" --db "$DB" --workspace "$WS" submit t4 'go on' --session "$ts" > /dev/null
trun
[ "$(ls "$T/log" | grep -c '\.req$')" = 5 ] || fail "trim: a summary request was made: $(ls "$T/log")"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_generation WHERE purpose = 'compaction' AND reason = 'lapse' AND state = 'done' AND usage IS NULL")" = 1 ] ||
    fail "trim: $("$PIC" --db "$DB" dump | grep '^generation')"
[ "$(sqlite3 "$DB" "SELECT json_extract(context, '\$.compact') || ',' || json_extract(context, '\$.arm') FROM pic_hook_run WHERE event = 'PreRequest'")" = trim,compact ] ||
    fail "trim: the answer: $(sqlite3 "$DB" "SELECT reason, context FROM pic_hook_run WHERE event = 'PreRequest'")"
# The cut: back from the tool result where 20000 tokens are reached to the start of its turn.
kept=$(sqlite3 "$DB" "SELECT e.kind || ':' || substr(e.body, 1, 200) FROM pic_entry e WHERE e.seq = (SELECT first_kept_seq FROM pic_entry WHERE kind = 'compaction')")
case "$kept" in user:*'read big.txt'*) ;; *) fail "trim: kept from $kept" ;; esac
r5="$T/log/5.req"
grep -q 'were dropped to keep the context small; no summary was made' "$r5" || fail "trim: the entry's text was not sent"
grep -q 'AAAA' "$r5" && fail "trim: the oldest message was kept"
grep -q 'CCCC' "$r5" || fail "trim: the newest messages were dropped"
grep -q '"type":"tool_use","id":"toolu_01"' "$r5" && grep -q '"type":"tool_result","tool_use_id":"toolu_01"' "$r5" ||
    fail "trim: the call and its result were parted"
grep -q '00000000000000000000000000000000000000000000000000000000000000000000000000599' "$r5" || fail "trim: the tool result was cut"
grep -q '"source":"compact"' "$T/ss.log" || fail "trim: SessionStart did not fire with source compact: $(cat "$T/ss.log")"
grep -q 'SessionStart hook additional context: brief-after-compact' "$r5" || fail "trim: the brief did not reach the request"
"$PIC" --db "$DB" check > /dev/null || fail "trim: integrity"
rm -f "$HOME/.pic/hooks.json"
printf 'PASS: a lapse keeps the newest 20000 tokens with no summary request; the brief arrives through SessionStart\n'

# ---- inside one long task, the trim cuts at a reply ------------------------
# One message, then three reads of 12000 tokens each: the start of that turn
# is more than twice 20000 tokens back, so the cut is the reply nearest the
# keep point and the message itself is dropped.
kill "$spid" 2>/dev/null || :
spid=
DB="$T/trim-long.sqlite"
rm -rf "$T/log" "$T/port"
mkdir "$T/log"
"$SERVER" "$T/port" "$T/log" 120 "sse:$T/read.sse" "sse:$T/read.sse" "sse:$T/read.sse" "$text" "$text" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "trim long: server did not start"; sleep 0.05; done
URL="http://127.0.0.1:$(cat "$T/port")/v1/messages"
"$PIC" --db "$DB" --workspace "$WS" submit l1 "$(big A)" > /dev/null
trun
ts=$("$PIC" --db "$DB" sessions | awk 'NR == 1 {print $1}')
sqlite3 "$DB" "UPDATE pic_entry SET created_ms = created_ms - 400000"
"$PIC" --db "$DB" --workspace "$WS" submit l2 'go on' --session "$ts" > /dev/null
trun
[ "$(ls "$T/log" | grep -c '\.req$')" = 5 ] || fail "trim long: requests: $(ls "$T/log")"
kept=$(sqlite3 "$DB" "SELECT e.kind FROM pic_entry e WHERE e.seq = (SELECT first_kept_seq FROM pic_entry WHERE kind = 'compaction')")
[ "$kept" = assistant ] || fail "trim long: kept from a $kept entry"
grep -q 'AAAA' "$T/log/5.req" && fail "trim long: the long task's message was kept"
[ "$(grep -o '"type":"tool_use"' "$T/log/5.req" | wc -l | tr -d ' ')" = "$(grep -o '"type":"tool_result"' "$T/log/5.req" | wc -l | tr -d ' ')" ] ||
    fail "trim long: a call and its result were parted"
"$PIC" --db "$DB" check > /dev/null || fail "trim long: integrity"
printf 'PASS: inside one long task, a lapse trim cuts at a reply, never between a call and its result\n'
