#!/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'

# ---- the kept size in real tokens ------------------------------------------
# The trim measures what it keeps with chars/4 scaled by the conversation's
# calibration: the provider's reported input on the last reply against
# chars/4 of that request, recorded in the answer. Twelve messages of 2000
# tokens by chars/4: uncalibrated (the fake server reports 25 tokens, so the
# ratio is clamped to 1) the newest ten are kept; at 1.5, the newest seven.
# A resume through pic ask then runs SessionStart with source resume, and
# with source compact after the trim.
msg() { printf '%08000d' 0 | tr 0 "$1"; }
kill "$spid" 2>/dev/null || :
spid=
tserve() { # tserve SPEC...: a fresh fake server, its requests in $T/log
    [ -n "$spid" ] && kill "$spid" 2>/dev/null || :
    rm -rf "$T/log" "$T/port"
    mkdir "$T/log"
    "$SERVER" "$T/port" "$T/log" 120 "$@" &
    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"
}
# usage_ratio DB R: the last reply's reported input set to R times chars/4 of its request.
usage_ratio() {
    sqlite3 "$1" "UPDATE pic_generation SET usage = json_object('input_tokens', CAST($2 * (SELECT
        coalesce(sum((length(body) + 3) / 4), 0) + 4 * (SELECT count(*) FROM pic_entry WHERE kind IN ('assistant','answer')
        AND seq < (SELECT max(seq) FROM pic_entry WHERE kind IN ('assistant','answer')))
        FROM pic_entry WHERE kind IN ('user','tool_result','instructions')
        AND seq < (SELECT max(seq) FROM pic_entry WHERE kind IN ('assistant','answer'))) AS INTEGER), 'output_tokens', 1)
        WHERE id = (SELECT max(id) FROM pic_generation WHERE purpose = 'reply' AND state = 'done')"
}
first_kept() {
    sqlite3 "$1" "SELECT e.kind || ':' || substr(e.body, 1, 1) FROM pic_entry e WHERE e.seq =
        (SELECT first_kept_seq FROM pic_entry WHERE kind = 'compaction' ORDER BY seq DESC LIMIT 1)"
}
calibration() {
    sqlite3 "$1" "SELECT json_extract(context, '\$.calibration') FROM pic_hook_run WHERE event = 'PreRequest'
        AND reason = 'lapse' ORDER BY id DESC LIMIT 1"
}
tserve "$text"
for ratio in 1 1.5; do
    DB="$T/cal-$ratio.sqlite"
    for l in A B C D E F G H I J K L; do
        if [ "$l" = A ]; then
            "$PIC" --db "$DB" --workspace "$WS" submit "c$l" "$(msg "$l")" > /dev/null
        else
            "$PIC" --db "$DB" --workspace "$WS" submit "c$l" "$(msg "$l")" --session "$cs" > /dev/null
        fi
        trun
        cs=$("$PIC" --db "$DB" sessions | awk 'NR == 1 {print $1}')
    done
    [ "$ratio" = 1 ] || usage_ratio "$DB" "$ratio"
    sqlite3 "$DB" "UPDATE pic_entry SET created_ms = created_ms - 400000"
    if [ "$ratio" = 1 ]; then
        "$PIC" --db "$DB" --workspace "$WS" submit cz 'go on' --session "$cs" > /dev/null
        trun
    else
        printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"m"}]}}}' \
            "$(cat "$T/port")" > "$T/models.json"
        printf '{"hooks": {"SessionStart": [{"hooks": [{"type": "command", "command": "sh %s/ss.sh %s"}]}]}}\n' "$T" "$T" > "$HOME/.pic/hooks.json"
        rm -f "$T/ss.log"
        PIC_LAPSE_HOLDOUT=0 PIC_MODELS_FILE="$T/models.json" PIC_MODEL_CATALOG=offline "$PIC" --db "$DB" --workspace "$WS" \
            --model fake/m --lapse-floor 0 ask --session "$cs" 'go on' > /dev/null 2>> "$T/stderr" || fail "calibration: ask: $(tail -2 "$T/stderr")"
        rm -f "$HOME/.pic/hooks.json"
    fi
done
sources=$(sed -n 's/.*"source":"\([a-z]*\)".*/\1/p' "$T/ss.log" | tr '\n' ' ')
[ "$sources" = 'resume compact ' ] || fail "resume through ask: SessionStart sources: $sources"
last=$(ls "$T/log" | grep '\.req$' | sort -n | tail -1)
grep -q 'were dropped to keep the context small.*SessionStart hook additional context: brief-after-compact' "$T/log/$last" ||
    fail "resume through ask: the compact brief did not follow the trim"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_hook_run h JOIN pic_entry e ON e.seq = h.ref AND e.kind = 'compaction'
    WHERE h.event = 'SessionStart' AND h.command IS NOT NULL")" = 1 ] || fail "resume through ask: SessionStart(compact) not tied to the trim"
c=$(calibration "$T/cal-1.sqlite")
[ "$c" = 1 ] || [ "$c" = 1.0 ] || fail "calibration: with too little reported, $c"
[ "$(first_kept "$T/cal-1.sqlite")" = user:C ] || fail "calibration 1: kept from $(first_kept "$T/cal-1.sqlite")"
c=$(calibration "$T/cal-1.5.sqlite")
[ "$(sqlite3 "$T/cal-1.5.sqlite" "SELECT $c BETWEEN 1.45 AND 1.55")" = 1 ] || fail "calibration 1.5: recorded $c"
[ "$(first_kept "$T/cal-1.5.sqlite")" = user:F ] || fail "calibration 1.5: kept from $(first_kept "$T/cal-1.5.sqlite")"
"$PIC" --db "$T/cal-1.5.sqlite" check > /dev/null || fail "calibration: integrity"
printf 'PASS: the trim keeps keepRecentTokens in real tokens, calibrated by the last reply'"'"'s reported input\n'

# The long-task fallback (back only to the nearest reply when the turn's
# start is more than twice the keep back) is measured the same way: a
# 12000-token message and two reads of about 12000 each (after a first
# exchange, so there is something older to drop) keep the message
# uncalibrated, and drop it at 1.5.
printf '%048000d' 0 | tr 0 M > "$T/long.txt"
for ratio in 1 1.5; do
    tserve "$text" "sse:$T/read.sse" "sse:$T/read.sse" "$text"
    DB="$T/calong-$ratio.sqlite"
    "$PIC" --db "$DB" --workspace "$WS" submit m0 'hello' > /dev/null
    trun
    cs=$("$PIC" --db "$DB" sessions | awk 'NR == 1 {print $1}')
    "$PIC" --db "$DB" --workspace "$WS" submit m1 "$(cat "$T/long.txt")" --session "$cs" > /dev/null
    trun
    [ "$ratio" = 1 ] || usage_ratio "$DB" "$ratio"
    sqlite3 "$DB" "UPDATE pic_entry SET created_ms = created_ms - 400000"
    "$PIC" --db "$DB" --workspace "$WS" submit m2 'go on' --session "$cs" > /dev/null
    trun
done
[ "$(first_kept "$T/calong-1.sqlite")" = user:M ] || fail "calibrated fallback 1: kept from $(first_kept "$T/calong-1.sqlite")"
case "$(first_kept "$T/calong-1.5.sqlite")" in assistant:*) ;; *) fail "calibrated fallback 1.5: kept from $(first_kept "$T/calong-1.5.sqlite")" ;; esac
printf 'PASS: the long-task fallback is measured in calibrated tokens too\n'

# ---- a lapse only at the start of a submission ------------------------------
# With a one-second cache lifetime a two-second tool call inside a
# submission is no lapse; the next submission, after idling, is one. A
# holdout draw on a later lapse still holds it out, uncompacted.
sed -e 's/"name":"write"/"name":"bash"/' \
    -e 's/"partial_json":"{\\"path\\": \\"notes.txt\\", "/"partial_json":"{\\"command\\": \\"sleep 2\\"}"/' \
    -e 's/"partial_json":"\\"content\\": \\"hi\\"}"/"partial_json":""/' "$STREAMS/tool_use.sse" > "$T/sleep.sse"
grep -q 'sleep 2' "$T/sleep.sse" || fail "lapse turns: fixture"
tserve "$text" "sse:$T/sleep.sse" "$text"
DB="$T/turns.sqlite"
lrun() {
    "$PIC" --db "$DB" --workspace "$WS" --lapse on --lapse-seconds 1 --lapse-floor 0 run --model anthropic/m --api-url "$URL" \
        2>> "$T/stderr" || fail "lapse run: $(tail -2 "$T/stderr")"
}
"$PIC" --db "$DB" --workspace "$WS" submit u1 "$(big A)" > /dev/null
PIC_LAPSE_HOLDOUT=0 lrun
ls_=$("$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 u2 'run it' --session "$ls_" > /dev/null
PIC_LAPSE_HOLDOUT=0 lrun
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_generation WHERE submission_id = 2 AND purpose = 'reply' AND state = 'done'")" = 2 ] ||
    fail "lapse turns: the tool turn did not run: $("$PIC" --db "$DB" dump | grep '^generation')"
sqlite3 "$DB" "UPDATE pic_entry SET created_ms = created_ms - 400000"
"$PIC" --db "$DB" --workspace "$WS" submit u3 'again' --session "$ls_" > /dev/null
PIC_LAPSE_HOLDOUT=0 lrun
lapses=$(sqlite3 "$DB" "SELECT group_concat(submission_id || ':' || ref, ',') FROM (SELECT submission_id, ref FROM pic_hook_run
    WHERE event = 'PreRequest' AND reason = 'lapse' ORDER BY id)")
[ "$lapses" = 2:0,3:0 ] || fail "lapse turns: lapses at $lapses (submission:turn)"
[ "$(sqlite3 "$DB" "SELECT json_extract(context, '\$.arm') FROM pic_hook_run WHERE event = 'PreRequest' AND submission_id = 3")" = compact ] ||
    fail "lapse turns: the next submission's arm"
printf 'PASS: a lapse is answered only before the first request of a submission, never on a tool turn\n'

tserve "$text"
compactions=$(sqlite3 "$DB" "SELECT count(*) FROM pic_entry WHERE kind = 'compaction'")
sqlite3 "$DB" "UPDATE pic_entry SET created_ms = created_ms - 400000"
"$PIC" --db "$DB" --workspace "$WS" submit u4 'once more' --session "$ls_" > /dev/null
PIC_LAPSE_HOLDOUT=1 lrun
a=$(sqlite3 "$DB" "SELECT json_extract(context, '\$.arm') || ',' || coalesce(json_extract(context, '\$.compact'), '-')
    FROM pic_hook_run WHERE event = 'PreRequest' AND submission_id = 4")
[ "$a" = holdout,- ] || fail "holdout: the answer $a"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_entry WHERE kind = 'compaction'")" = "$compactions" ] || fail "holdout: compacted"
grep -q 'AAAA' "$T/log/1.req" || fail "holdout: the oldest message was not sent"
"$PIC" --db "$DB" check > /dev/null || fail "lapse turns: integrity"
printf 'PASS: a held-out lapse is still held out, uncompacted\n'
