#!/bin/sh
# Images, as Pi sends them: pic ask --image, the RPC images field of steer
# and follow_up, and the read tool on an image file, journaled in SQLite
# (deduplicated, compressed only when that is smaller) and sent in each API's
# own shape, or as Pi's placeholder to a model without image input. Exports
# carry them; a crash around the image write leaves a consistent journal.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
FAULTS=yes # --no-faults: skip cases that need crash hooks (the release build has none)
[ "${1:-}" = --no-faults ] && FAULTS=no
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
C=$here/chat-streams
I=$here/image-streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-images.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME"
# Exact request shapes below: prompt caching (provider.sh) is off here.
"$PIC" settings cacheRetention none > /dev/null
spid=
pid=
cleanup() {
    exec 3>&- 2>/dev/null || :
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    [ -n "$pid" ] && kill -9 "$pid" 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-images-test-key PIC_PI_EXPORT=0 PIC_MODEL_CATALOG=offline

# A 1x1 PNG, and its base64 as every API carries it.
PNG_B64='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=='
printf '%s' "$PNG_B64" | base64 -d > "$T/dot.png" 2>/dev/null || printf '%s' "$PNG_B64" | base64 -D > "$T/dot.png"
[ "$(wc -c < "$T/dot.png" | tr -d ' ')" = 70 ] || fail "fixture: dot.png"

n=0
serve() { # SPEC...: a fresh server, journal and workspace (with dot.png)
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    n=$((n + 1))
    mkdir "$T/log$n" "$T/ws$n"
    DB="$T/j$n.sqlite"
    WS="$T/ws$n"
    LOG="$T/log$n"
    cp "$T/dot.png" "$WS/dot.png"
    "$SERVER" "$T/port$n" "$LOG" 60 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port$n" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "server did not start"
        sleep 0.05
    done
    # One provider per API at the fake server; "see" takes images, "blind" does not (Pi's default).
    port=$(cat "$T/port$n")
    printf '{"providers":{%s,%s,%s}}' \
        "\"va\":{\"baseUrl\":\"http://127.0.0.1:$port\",\"api\":\"anthropic-messages\",\"apiKey\":\"\$ANTHROPIC_API_KEY\",\"models\":[{\"id\":\"see\",\"input\":[\"text\",\"image\"]},{\"id\":\"blind\"}]}" \
        "\"vc\":{\"baseUrl\":\"http://127.0.0.1:$port\",\"api\":\"openai-completions\",\"apiKey\":\"\$ANTHROPIC_API_KEY\",\"models\":[{\"id\":\"see\",\"input\":[\"text\",\"image\"]},{\"id\":\"blind\",\"input\":[\"text\"]}]}" \
        "\"vr\":{\"baseUrl\":\"http://127.0.0.1:$port\",\"api\":\"openai-responses\",\"apiKey\":\"\$ANTHROPIC_API_KEY\",\"models\":[{\"id\":\"see\",\"input\":[\"text\",\"image\"]},{\"id\":\"blind\"}]}" \
        > "$T/models$n.json"
    export PIC_MODELS_FILE="$T/models$n.json"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
has() { grep -qF -- "$2" "$1" || fail "$3: $(grep -o '"messages".*\|"input".*' "$1" | cut -c1-600)"; }
hasnt() { ! grep -qF -- "$2" "$1" || fail "$3"; }
ANT_IMG='{"type":"image","source":{"type":"base64","media_type":"image/png","data":"'$PNG_B64'"}}'
URL_IMG='{"type":"image_url","image_url":{"url":"data:image/png;base64,'$PNG_B64'"}}'
RESP_IMG='{"type":"input_image","detail":"auto","image_url":"data:image/png;base64,'$PNG_B64'"}'
USER_PH='(image omitted: model does not support images)'
TOOL_PH='(tool image omitted: model does not support images)'

# Anthropic, a model with image input: the text, then the image block.
serve "sse:$S/text.sse"
pic --model va/see ask --image "$T/dot.png" 'what is this' > /dev/null 2>> "$T/err" || fail "ask: $(cat "$T/err")"
has "$LOG/1.req" '"messages":[{"role":"user","content":[{"type":"text","text":"what is this"},'"$ANT_IMG"']}]' "anthropic: user image"
pic check > /dev/null || fail "anthropic: integrity"
pic dump | grep -q '^image 1 entry=1.0 image/png 70 [a-z]* | [0-9a-f]\{64\}$' || fail "anthropic: dump: $(pic dump | grep '^image')"
[ "$(sqlite3 "$DB" 'SELECT width || "x" || height FROM pic_image')" = 1x1 ] || fail "anthropic: size not stored"
# The same bytes again are stored once; a highly compressible one is
# deflated, noise (as most image data is) kept raw.
{ printf 'GIF89a\001\0\001\0'; head -c 19996 /dev/zero; } > "$T/flat.gif"
{ cat "$T/dot.png"; head -c 3000 /dev/urandom; } > "$T/noise.png"
pic --model va/see ask -c --image "$T/dot.png" --image "$T/flat.gif" --image "$T/noise.png" 'and these' > /dev/null 2>> "$T/err" || fail "ask 2: $(cat "$T/err")"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_image')" = 3 ] || fail "dedup: $(sqlite3 "$DB" 'SELECT hash, mime, sz FROM pic_image')"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_attachment')" = 4 ] || fail "dedup: attachments"
pic dump | grep -q '^image 3 entry=3.1 image/gif 20006 deflated | ' && pic dump | grep -q '^image 4 entry=3.2 image/png 3070 raw | ' ||
    fail "deflate: $(pic dump | grep '^image')"
GIF_B64=$(base64 < "$T/flat.gif" | tr -d '\n')
has "$LOG/2.req" '{"type":"text","text":"and these"},'"$ANT_IMG"',{"type":"image","source":{"type":"base64","media_type":"image/gif","data":"'"$GIF_B64"'"}},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"'"$(base64 < "$T/noise.png" | tr -d '\n')"'"}}]}]' \
    "anthropic: three images, the deflated one restored"
has "$LOG/2.req" '{"role":"user","content":[{"type":"text","text":"what is this"},'"$ANT_IMG"']}' "anthropic: history keeps its image"
pic check > /dev/null || fail "dedup: integrity"
# pic check holds attachments to their images and owners.
cp "$DB" "$T/broken.sqlite"
sqlite3 "$T/broken.sqlite" "DELETE FROM pic_image WHERE mime = 'image/gif'"
"$PIC" --db "$T/broken.sqlite" --workspace "$WS" check > /dev/null 2> "$T/check" && fail "check: a missing image passed"
grep -q 'integrity violation: attachment without its image' "$T/check" || fail "check: $(cat "$T/check")"
# pic check (not every open) also hashes each image's content.
cp "$DB" "$T/broken.sqlite"
sqlite3 "$T/broken.sqlite" "UPDATE pic_image SET data = X'00', sz = 1 WHERE mime = 'image/gif'"
"$PIC" --db "$T/broken.sqlite" --workspace "$WS" dump > /dev/null || fail "check: open checks the hashes"
"$PIC" --db "$T/broken.sqlite" --workspace "$WS" check > /dev/null 2> "$T/check" && fail "check: a wrong hash passed"
grep -q 'integrity violation: image content does not match its hash' "$T/check" || fail "check: $(cat "$T/check")"
printf 'PASS: anthropic: ask --image sends Pi image blocks; images are stored once, deflated only when smaller\n'

# Pi session lines and the HTML page carry them.
pic export --pi - > "$T/pi.jsonl" || fail "export --pi"
grep -qF '"content":[{"type":"text","text":"what is this"},{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]' "$T/pi.jsonl" ||
    fail "export --pi: $(grep -o '"role":"user".\{0,200\}' "$T/pi.jsonl")"
pic export --html latest - > "$T/page.html" || fail "export --html"
grep -qF '<img src="data:image/png;base64,'"$PNG_B64"'" class="message-image" alt="">' "$T/page.html" || fail "export --html: no image"
printf 'PASS: export: Pi session lines and the HTML page carry the images\n'

# A model without image input gets Pi's placeholder, once for all its images.
serve "sse:$S/text.sse"
pic --model va/blind ask --image "$T/dot.png" --image "$T/dot.png" 'blind' > /dev/null 2>> "$T/err" || fail "blind: $(cat "$T/err")"
has "$LOG/1.req" '"messages":[{"role":"user","content":[{"type":"text","text":"blind"},{"type":"text","text":"'"$USER_PH"'"}]}]' "anthropic: placeholder"
hasnt "$LOG/1.req" "$PNG_B64" "anthropic: image sent to a model without image input"
printf 'PASS: anthropic: a model without image input gets Pi'"'"'s placeholder\n'

# Refused, nothing journaled: not an image, a broken header, over the
# inline limit. A BMP (Pi converts it; pic cannot) becomes Pi's note.
serve "sse:$S/text.sse"
printf 'plain' > "$T/plain.txt"
{ head -c 16 "$T/dot.png"; printf '\177\177\177\177'; tail -c 50 "$T/dot.png"; } > "$T/broken.png"
{ cat "$T/dot.png"; head -c 3600000 /dev/zero; } > "$T/big.png"
for bad in plain.txt:'not a PNG, JPEG, GIF, WebP or BMP image' broken.png:'the image/png header is invalid' big.png:'over the 4.5MB inline limit'; do
    if pic --model va/see ask --image "$T/${bad%%:*}" 'x' > /dev/null 2> "$T/err1"; then fail "${bad%%:*} was attached"; fi
    grep -qF "image $T/${bad%%:*}: ${bad#*:}" "$T/err1" || fail "${bad%%:*}: $(cat "$T/err1")"
done
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_submission')" = 0 ] || fail "refused: a request was journaled"
printf 'BM\0\0\0\0\0\0\0\0\066\0\0\0\050\0\0\0\001\0\0\0\001\0\0\0\001\0\030\0' > "$T/x.bmp"
pic --model va/see ask --image "$T/x.bmp" 'notes' > /dev/null 2>> "$T/err" || fail "notes: $(cat "$T/err")"
has "$LOG/1.req" '"content":"notes\n\n[Image omitted: could not be converted to a supported inline image format.]"' "notes"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_attachment')" = 0 ] || fail "notes: something attached"
printf 'PASS: ask --image refuses non-images, broken headers and oversized images; a BMP becomes Pi'"'"'s note\n'

# The read tool on an image file: Pi's note and the image in the tool result.
serve "sse:$I/read_png.sse" "sse:$S/text.sse"
pic --model va/see --json ask 'look at dot.png' > "$T/readev" 2>> "$T/err" || fail "read: $(cat "$T/err")"
grep -qF '{"type":"tool_execution_end","toolCallId":"toolu_r","toolName":"read","result":{"content":[{"type":"text","text":"Read image file [image/png]"},{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]},"isError":false}' "$T/readev" ||
    fail "read: tool_execution_end: $(grep tool_execution_end "$T/readev")"
has "$LOG/2.req" '{"type":"tool_result","tool_use_id":"toolu_r","content":[{"type":"text","text":"Read image file [image/png]"},'"$ANT_IMG"'],"is_error":false}' "anthropic: read result"
pic dump | grep -q '^image 1 entry=3.0 image/png 70 ' || fail "read: dump: $(pic dump)"
pic check > /dev/null || fail "read: integrity"
serve "sse:$I/read_png.sse" "sse:$S/text.sse"
pic --model va/blind ask 'look at dot.png' > /dev/null 2>> "$T/err" || fail "read blind: $(cat "$T/err")"
has "$LOG/2.req" '{"type":"tool_result","tool_use_id":"toolu_r","content":"Read image file [image/png]\n'"$TOOL_PH"'","is_error":false}' "anthropic: read result, placeholder"
printf 'PASS: anthropic: read on a PNG returns Pi'"'"'s note and the image, or the placeholder\n'

# Chat Completions: image_url parts; a tool's images follow the run of tool
# results in one user message.
serve "sse:$C/text.sse"
pic --model vc/see ask --image "$T/dot.png" 'chat image' > /dev/null 2>> "$T/err" || fail "chat: $(cat "$T/err")"
has "$LOG/1.req" '{"role":"user","content":[{"type":"text","text":"chat image"},'"$URL_IMG"']}' "chat: user image"
serve "sse:$I/chat_read_png.sse" "sse:$C/text.sse"
pic --model vc/see ask 'look' > /dev/null 2>> "$T/err" || fail "chat read: $(cat "$T/err")"
has "$LOG/2.req" '{"role":"tool","tool_call_id":"call_r","content":"Read image file [image/png]"},{"role":"user","content":[{"type":"text","text":"Attached image(s) from tool result:"},'"$URL_IMG"']}]' "chat: tool image"
serve "sse:$I/chat_read_png.sse" "sse:$C/text.sse"
pic --model vc/blind ask --image "$T/dot.png" 'look' > /dev/null 2>> "$T/err" || fail "chat blind: $(cat "$T/err")"
has "$LOG/2.req" '{"role":"user","content":[{"type":"text","text":"look"},{"type":"text","text":"'"$USER_PH"'"}]}' "chat: placeholder"
has "$LOG/2.req" '{"role":"tool","tool_call_id":"call_r","content":"Read image file [image/png]\n'"$TOOL_PH"'"}]' "chat: tool placeholder"
hasnt "$LOG/2.req" "$PNG_B64" "chat: image sent to a model without image input"
printf 'PASS: chat: image_url parts, tool images after the results, placeholders without image input\n'

# Responses: input_image items; a tool's images in its output.
serve "sse:$I/responses_read_png.sse" "sse:$here/responses-streams/reasoning_text.sse"
pic --model vr/see ask --image "$T/dot.png" 'resp' > /dev/null 2>> "$T/err" || fail "responses: $(cat "$T/err")"
has "$LOG/1.req" '{"role":"user","content":[{"type":"input_text","text":"resp"},'"$RESP_IMG"']}' "responses: user image"
has "$LOG/2.req" '{"type":"function_call_output","call_id":"call_r","output":[{"type":"input_text","text":"Read image file [image/png]"},'"$RESP_IMG"']}' "responses: tool image"
serve "sse:$I/responses_read_png.sse" "sse:$here/responses-streams/reasoning_text.sse"
pic --model vr/blind ask --image "$T/dot.png" 'resp' > /dev/null 2>> "$T/err" || fail "responses blind: $(cat "$T/err")"
has "$LOG/2.req" '{"role":"user","content":[{"type":"input_text","text":"resp"},{"type":"input_text","text":"'"$USER_PH"'"}]}' "responses: placeholder"
has "$LOG/2.req" '{"type":"function_call_output","call_id":"call_r","output":"Read image file [image/png]\n'"$TOOL_PH"'"}' "responses: tool placeholder"
hasnt "$LOG/2.req" "$PNG_B64" "responses: image sent to a model without image input"
printf 'PASS: responses: input_image items in messages and tool output, placeholders without image input\n'

# RPC: images on steer and follow_up are journaled with the message and
# delivered with it; a malformed one is an error response.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
rm -f "$T/in"
mkfifo "$T/in"
"$PIC" --db "$DB" --workspace "$WS" --model va/see --json --commands ask 'hold on' < "$T/in" > "$T/ev" 2> "$T/everr" &
pid=$!
exec 3> "$T/in"
i=0
until [ -e "$WS/started" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "rpc: never started: $(cat "$T/everr")"; sleep 0.05; done
printf '%s\n' '{"id":"s","type":"steer","message":"see this","images":[{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]}' >&3
printf '%s\n' '{"id":"f","type":"follow_up","message":"and this","images":[{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/svg+xml"}]}' >&3
printf '%s\n' '{"id":"b0","type":"follow_up","message":"x","images":["not an object"]}' >&3
printf '%s\n' '{"id":"b4","type":"follow_up","message":"x","images":[{"type":"image","data":"aGVsbG8=","mimeType":"image/png"}]}' >&3
printf '%s\n' '{"id":"b1","type":"steer","message":"x","images":"nope"}' >&3
printf '%s\n' '{"id":"b2","type":"steer","message":"x","images":[{"type":"image","data":"%%%","mimeType":"image/png"}]}' >&3
printf '%s\n' '{"id":"b3","type":"follow_up","message":"x","images":[{"data":"aGk="}]}' >&3
i=0
until grep -qF '"id":"b3"' "$T/ev"; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "rpc: responses: $(cat "$T/ev")"; sleep 0.05; done
touch "$WS/release"
rc=0
wait "$pid" || rc=$?
pid=
exec 3>&-
[ "$rc" = 0 ] || fail "rpc: exit $rc: $(cat "$T/everr")"
grep -qF '{"id":"s","type":"response","command":"steer","success":true,"data":{"disposition":"queued"}}' "$T/ev" || fail "rpc: steer response"
grep -qF '{"id":"b1","type":"response","command":"steer","success":false,"error":"images must be an array"}' "$T/ev" || fail "rpc: b1"
grep -qF '{"id":"b2","type":"response","command":"steer","success":false,"error":"image data is not base64"}' "$T/ev" || fail "rpc: b2"
grep -qF '"id":"b3","type":"response","command":"follow_up","success":false,"error":"each image must be' "$T/ev" || fail "rpc: b3"
grep -qF '"id":"b0","type":"response","command":"follow_up","success":false,"error":"each image must be' "$T/ev" || fail "rpc: b0: $(grep b0 "$T/ev")"
grep -qF '{"id":"b4","type":"response","command":"follow_up","success":false,"error":"image 1: not a PNG, JPEG, GIF, WebP or BMP image"}' "$T/ev" || fail "rpc: b4"
# A declared type must be what the data is.
grep -qF '{"id":"f","type":"response","command":"follow_up","success":false,"error":"image 1: declared image/svg+xml but the data is image/png"}' "$T/ev" ||
    fail "rpc: f: $(grep '"id":"f"' "$T/ev")"
has "$LOG/2.req" '{"role":"user","content":[{"type":"text","text":"see this"},'"$ANT_IMG"']}' "rpc: steer image"
grep -qF '{"type":"message_start","message":{"role":"user","content":[{"type":"text","text":"see this"},{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]}}' "$T/ev" ||
    fail "rpc: message_start without the image"
pic check > /dev/null || fail "rpc: integrity"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_attachment WHERE queued_id IS NOT NULL")" = 1 ] || fail "rpc: queued attachment"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_attachment WHERE entry_seq IS NOT NULL")" = 1 ] || fail "rpc: delivered attachment"
printf 'PASS: rpc: images on steer and follow_up are journaled and delivered; malformed ones are refused\n'

# A request's image budget: the newest 20 go as images, older ones as Pi's
# placeholder (one for the run).
serve "sse:$S/text.sse"
set --
for k in $(seq 1 22); do
    { cat "$T/dot.png"; printf 'n%03d' "$k"; } > "$T/many$k.png"
    set -- "$@" --image "$T/many$k.png"
done
pic --model va/see ask "$@" 'many' > /dev/null 2>> "$T/err" || fail "budget: $(cat "$T/err")"
[ "$(grep -o '"type":"image"' "$LOG/1.req" | wc -l | tr -d ' ')" = 20 ] || fail "budget: $(grep -o '"type":"image"' "$LOG/1.req" | wc -l) images sent"
has "$LOG/1.req" '{"type":"text","text":"many"},{"type":"text","text":"'"$USER_PH"'"},{"type":"image"' "budget: the two oldest not one placeholder first"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_attachment')" = 22 ] || fail "budget: all 22 not journaled"
printf 'PASS: a request sends its newest 20 images, older ones as Pi'"'"'s placeholder\n'

# Import keeps a Pi session's user images: export, import, export again.
serve "sse:$S/text.sse"
pic --model va/see ask --image "$T/dot.png" 'round trip' > /dev/null 2>> "$T/err" || fail "import: $(cat "$T/err")"
pic export --pi - > "$T/out.jsonl" || fail "import: export"
pic import "$T/out.jsonl" > /dev/null 2>> "$T/err" || fail "import: $(cat "$T/err")"
pic check > /dev/null || fail "import: integrity"
imported=$(pic sessions | awk 'NR == 1 { print $1 }')
pic export --pi - > "$T/again.jsonl" || fail "import: export again"
[ "$(grep -cF '"content":[{"type":"text","text":"round trip"},{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]' "$T/again.jsonl")" = 2 ] ||
    fail "import: the image did not survive: $(grep -o '"role":"user".\{0,120\}' "$T/again.jsonl")"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_image')" = 1 ] || fail "import: not deduplicated"
[ -n "$imported" ] || fail "import: no session"
printf 'PASS: import keeps the images of a Pi session (export, import, export)\n'

# Retention: past imageRetentionDays an image's bytes go, its row stays, and
# requests, pic log and exports show "[image removed]".
serve "sse:$S/text.sse"
pic --model va/see ask --image "$T/dot.png" 'old picture' > /dev/null 2>> "$T/err" || fail "retention: $(cat "$T/err")"
"$PIC" settings imageRetentionDays 1 > /dev/null
pic prune --dry-run | grep -qx 'would prune 0 images, 0 bytes' || fail "retention: a fresh image is prunable"
sqlite3 "$DB" "UPDATE pic_entry SET created_ms = created_ms - 2 * 86400000"
[ "$(pic prune --dry-run)" = 'would prune 1 image, 70 bytes' ] || fail "retention: dry run: $(pic prune --dry-run)"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_image WHERE data IS NULL')" = 0 ] || fail "retention: dry run pruned"
[ "$(pic prune)" = 'pruned 1 image, 70 bytes' ] || fail "retention: prune"
[ "$(sqlite3 "$DB" "SELECT data IS NULL, mime, width, height, sz FROM pic_image")" = '1|image/png|1|1|70' ] ||
    fail "retention: row: $(sqlite3 "$DB" 'SELECT data IS NULL, mime, width, height, sz FROM pic_image')"
pic check > /dev/null || fail "retention: pic check refuses a pruned image"
pic log | grep -qF 'you: old picture [image removed]' || fail "retention: log: $(pic log)"
pic export --pi - | grep -qF '"content":[{"type":"text","text":"old picture"},{"type":"text","text":"[image removed]"}]' || fail "retention: export --pi"
pic export --html latest - | grep -qF '[image removed]' || fail "retention: export --html"
pic --model va/see ask -c 'next' > /dev/null 2>> "$T/err" || fail "retention: next: $(cat "$T/err")"
has "$LOG/2.req" '{"role":"user","content":[{"type":"text","text":"old picture"},{"type":"text","text":"[image removed]"}]}' "retention: request"
# The same image attached again after its bytes were pruned is stored again.
pic --model va/see ask -c --image "$T/dot.png" 'same picture again' > /dev/null 2>> "$T/err" || fail "retention: again: $(cat "$T/err")"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_image WHERE data IS NULL')" = 0 ] || fail "retention: re-attached image still pruned"
grep -qF "$PNG_B64" "$LOG/3.req" || fail "retention: the re-attached image was not sent"
# It also runs at open, at most hourly.
pic --model va/see ask -c --image "$T/flat.gif" 'another' > /dev/null 2>> "$T/err" || fail "retention: another: $(cat "$T/err")"
sqlite3 "$DB" "UPDATE pic_entry SET created_ms = created_ms - 2 * 86400000"
pic dump > /dev/null
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_image WHERE data IS NULL')" = 0 ] || fail "retention: open pruned within the hour"
sqlite3 "$DB" "DELETE FROM pic_meta WHERE key = 'last_prune_ms'"
pic dump > /dev/null
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_image WHERE data IS NULL')" = 2 ] || fail "retention: open did not prune"
"$PIC" settings --unset imageRetentionDays > /dev/null
printf 'PASS: retention: old image bytes are pruned (pic prune, and at open), shown as [image removed]\n'

# Once compaction has summarized the entry away on every conversation that
# reaches it, its image is no longer sent: its bytes go, whatever its age.
serve "sse:$S/text.sse"
pic --model va/see ask --image "$T/dot.png" 'compact me' > /dev/null 2>> "$T/err" || fail "compacted: $(cat "$T/err")"
pic --model va/see ask -c --image "$T/noise.png" 'and me' > /dev/null 2>> "$T/err" || fail "compacted: $(cat "$T/err")"
for k in 1 2 3; do
    pic --model va/see ask -c "$(yes "B$k$k$k" | head -c 50000 | tr -d '\n')" > /dev/null 2>> "$T/err" || fail "compacted: $(cat "$T/err")"
done
pic prune > /dev/null
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_image WHERE data IS NULL')" = 0 ] || fail "compacted: pruned before compaction"
pic compact > /dev/null
pic --model va/see ask -c 'after' > /dev/null 2>> "$T/err" || fail "compacted: after: $(cat "$T/err")"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_entry WHERE kind = 'compaction'")" = 1 ] || fail "compacted: no compaction"
[ "$(pic prune)" = 'pruned 2 images, 3140 bytes' ] || fail "compacted: prune: $(sqlite3 "$DB" 'SELECT first_kept_seq FROM pic_entry WHERE kind = "compaction"')"
pic check > /dev/null || fail "compacted: integrity"
# Nothing is left to prune.
[ "$(pic prune)" = 'pruned 0 images, 0 bytes' ] || fail "compacted: prune again"
printf 'PASS: retention: images compacted away on every conversation are pruned\n'

[ "$FAULTS" = yes ] || exit 0
# A crash while the image is written leaves nothing of the request; a crash
# after a read's result keeps the result and its image together.
serve "sse:$S/text.sse"
rc=0
env PIC_CRASH_AT=after-image:1 "$PIC" --db "$DB" --workspace "$WS" --model va/see ask --image "$T/dot.png" 'crash' > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "crash: expected 77, got $rc"
pic check > /dev/null || fail "crash: integrity after the image write"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_submission') $(sqlite3 "$DB" 'SELECT count(*) FROM pic_image')" = "0 0" ] ||
    fail "crash: a partial request survived"
for point in after-image:1 after-result:1; do
    serve "sse:$I/read_png.sse" "sse:$S/text.sse"
    rc=0
    env PIC_CRASH_AT=$point "$PIC" --db "$DB" --workspace "$WS" --model va/see ask 'look again' > /dev/null 2>&1 || rc=$?
    [ "$rc" = 77 ] || fail "crash at $point: expected 77, got $rc"
    pic check > /dev/null || fail "crash at $point: integrity"
    got="$(sqlite3 "$DB" "SELECT count(*) FROM pic_entry WHERE kind = 'tool_result'") $(sqlite3 "$DB" "SELECT count(*) FROM pic_attachment")"
    case $point in
    after-image:1) [ "$got" = "0 0" ] || fail "crash at $point: results and images: $got" ;;
    after-result:1) [ "$got" = "1 1" ] || fail "crash at $point: results and images: $got" ;;
    esac
    # The next pic finishes the request: a lost read runs again.
    pic --model va/see run > /dev/null 2>> "$T/err" || fail "crash at $point: recovery: $(cat "$T/err")"
    pic check > /dev/null || fail "crash at $point: integrity after recovery"
    got="$(sqlite3 "$DB" "SELECT count(*) FROM pic_entry WHERE kind = 'tool_result'") $(sqlite3 "$DB" "SELECT count(*) FROM pic_attachment") $(sqlite3 "$DB" "SELECT status FROM pic_submission")"
    [ "$got" = "1 1 answered" ] || fail "crash at $point: after recovery: $got"
    has "$LOG/2.req" "$ANT_IMG" "crash at $point: the image did not reach the model"
done
# A crash inside a prune leaves every image's bytes.
"$PIC" settings imageRetentionDays 1 > /dev/null
sqlite3 "$DB" "UPDATE pic_entry SET created_ms = created_ms - 2 * 86400000"
rc=0
env PIC_CRASH_AT=in-prune:1 "$PIC" --db "$DB" --workspace "$WS" prune > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "crash in prune: expected 77, got $rc"
"$PIC" settings imageRetentionDays 0 > /dev/null
pic check > /dev/null || fail "crash in prune: integrity"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_image WHERE data IS NULL')" = 0 ] || fail "crash in prune: bytes lost"
"$PIC" settings --unset imageRetentionDays > /dev/null
printf 'PASS: crashes around the image write leave the request and its images whole\n'
