Skip to content
pi-c Artifact [170a02f81d]
Login

Artifact [170a02f81d]

Artifact 170a02f81d4218c9ca4480358ef66edafa59b234a5754d1261ebc6da9d9948af:


#!/bin/sh
# pic import (Pi v3 session JSONL): full-fidelity import of user messages and
# images, assistant neutral content (text, thinking with signature/redacted,
# toolCall) with origin and stopReason, paired toolResult entries (text +
# images), bashExecution, compaction, branch_summary, custom_message,
# session_info, usage calibration (without inflating pic usage), multi-branch
# trees (/tree and /fork), Pi v1 compatibility, and malformed-input resilience.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-import-pi.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 || :; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export ANTHROPIC_API_KEY=k OPENROUTER_API_KEY=k OPENAI_API_KEY=k GEMINI_API_KEY=k PIC_PI_EXPORT=0 PIC_MODEL_CATALOG=offline
"$PIC" settings cacheRetention none > /dev/null

WS="$T/ws"
mkdir "$WS"
DB="$T/j.sqlite"
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
q() { sqlite3 "$DB" "$1"; }

# 1x1 transparent PNG, base64.
PNG_B64='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='

import_pi() {
    pic import "$1" > "$T/out" 2> "$T/err" || fail "import $1: $(cat "$T/err")"
    [ ! -s "$T/err" ] || fail "import $1: wrote to stderr: $(cat "$T/err")"
    pic check > /dev/null || fail "import $1: pic check failed"
    head -1 "$T/out"
}

# ---- 1. Full Pi v3 import + round-trip export -------------------------------
cat > "$T/full.jsonl" <<EOF
{"type":"session","version":3,"id":"orig-sess","timestamp":"2026-11-01T10:00:00.000Z","cwd":"$WS"}
{"type":"model_change","id":"mc1","parentId":null,"timestamp":"2026-11-01T10:00:00.100Z","provider":"anthropic","modelId":"claude-sonnet-5-5"}
{"type":"thinking_level_change","id":"tl1","parentId":"mc1","timestamp":"2026-11-01T10:00:00.200Z","thinkingLevel":"medium"}
{"type":"message","id":"u1","parentId":"tl1","timestamp":"2026-11-01T10:00:01.000Z","message":{"role":"user","content":[{"type":"text","text":"inspect and write"},{"type":"image","data":"$PNG_B64","mimeType":"image/png"}],"timestamp":1762000001000}}
{"type":"message","id":"a1","parentId":"u1","timestamp":"2026-11-01T10:00:02.000Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"plan first","thinkingSignature":"sig-anth-1"},{"type":"thinking","thinking":"","thinkingSignature":"redacted-blob-1","redacted":true},{"type":"text","text":"Running tools."},{"type":"toolCall","id":"toolu_1","name":"write","arguments":{"path":"never-created.txt","content":"hi"}},{"type":"toolCall","id":"toolu_2","name":"read","arguments":{"path":"photo.png"}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","usage":{"input":100,"output":40,"cacheRead":20,"cacheWrite":10,"totalTokens":170,"cost":{"input":0.01,"output":0.02,"cacheRead":0.001,"cacheWrite":0.002,"total":0.033}},"stopReason":"toolUse","timestamp":1762000002000}}
{"type":"message","id":"tr1","parentId":"a1","timestamp":"2026-11-01T10:00:03.000Z","message":{"role":"toolResult","toolCallId":"toolu_1","toolName":"write","content":[{"type":"text","text":"disk full"}],"isError":true,"timestamp":1762000003000}}
{"type":"message","id":"tr2","parentId":"tr1","timestamp":"2026-11-01T10:00:04.000Z","message":{"role":"toolResult","toolCallId":"toolu_2","toolName":"read","content":[{"type":"text","text":"Read image file [image/png]"},{"type":"image","data":"$PNG_B64","mimeType":"image/png"}],"isError":false,"timestamp":1762000004000}}
{"type":"message","id":"a2","parentId":"tr2","timestamp":"2026-11-01T10:00:05.000Z","message":{"role":"assistant","content":[{"type":"text","text":"Saw the image."}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","usage":{"input":200,"output":15,"cacheRead":50,"cacheWrite":0,"totalTokens":265,"cost":{"total":0.05}},"stopReason":"stop","timestamp":1762000005000}}
{"type":"custom_message","id":"cm1","parentId":"a2","timestamp":"2026-11-01T10:00:06.000Z","customType":"pic.instructions","content":"Use C11.","display":false}
{"type":"message","id":"b1","parentId":"cm1","timestamp":"2026-11-01T10:00:06.500Z","message":{"role":"bashExecution","command":"echo hi","output":"hi","exitCode":0,"cancelled":false,"truncated":false,"excludeFromContext":false,"timestamp":1762000006500}}
{"type":"compaction","id":"cp1","parentId":"b1","timestamp":"2026-11-01T10:00:07.000Z","summary":"Compacted earlier work.","firstKeptEntryId":"b1","tokensBefore":42000,"details":{"readFiles":["photo.png"],"modifiedFiles":["never-created.txt"]}}
{"type":"message","id":"u2","parentId":"cp1","timestamp":"2026-11-01T10:00:08.000Z","message":{"role":"user","content":"after compaction","timestamp":1762000008000}}
{"type":"message","id":"a3","parentId":"u2","timestamp":"2026-11-01T10:00:09.000Z","message":{"role":"assistant","content":[{"type":"text","text":"Continuing after compaction."}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","usage":{"input":300,"output":25,"cacheRead":0,"cacheWrite":0,"totalTokens":325},"stopReason":"stop","timestamp":1762000009000}}
{"type":"session_info","id":"si1","parentId":"a3","timestamp":"2026-11-01T10:00:10.000Z","name":"roundtrip-name"}
EOF

sid=$(import_pi "$T/full.jsonl")
[ ! -e "$WS/never-created.txt" ] || fail "roundtrip: imported tool call ran"
[ "$(q "SELECT name FROM pic_session WHERE id = '$sid'")" = "roundtrip-name" ] || fail "roundtrip: session name"

# Check assistant content, thinking, signature, redacted, origin, stopReason.
a1_row=$(q "SELECT e.provider || '|' || e.api || '|' || e.model || '|' || g.stop_reason || '|' ||
  json_extract(e.body, '\$[0].type') || '|' || json_extract(e.body, '\$[0].thinking') || '|' ||
  json_extract(e.body, '\$[0].signature') || '|' || json_extract(e.body, '\$[1].redacted') || '|' ||
  json_extract(e.body, '\$[1].signature') || '|' || json_extract(e.body, '\$[3].type') || '|' ||
  json_extract(e.body, '\$[3].id')
  FROM pic_entry e JOIN pic_generation g ON g.entry_seq = e.seq
  WHERE e.kind = 'assistant' ORDER BY e.seq LIMIT 1")
[ "$a1_row" = 'anthropic|anthropic-messages|claude-sonnet-5-5|toolUse|thinking|plan first|sig-anth-1|1|redacted-blob-1|toolCall|toolu_1' ] ||
    fail "roundtrip: assistant row: $a1_row"

# Check tool effects & tool_result attachments (text + image + isError).
effs=$(q "SELECT group_concat(call_id || ':' || tool || ':' || is_error || ':' || state, ',') FROM pic_effect ORDER BY ordinal")
[ "$effs" = 'toolu_1:write:1:done,toolu_2:read:0:done' ] || fail "roundtrip: effects: $effs"
tr_imgs=$(q "SELECT count(*) FROM pic_attachment a JOIN pic_entry e ON e.seq = a.entry_seq WHERE e.kind = 'tool_result'")
[ "$tr_imgs" = 1 ] || fail "roundtrip: tool_result image attachment count: $tr_imgs"
usr_imgs=$(q "SELECT count(*) FROM pic_attachment a JOIN pic_entry e ON e.seq = a.entry_seq WHERE e.kind = 'user'")
[ "$usr_imgs" = 1 ] || fail "roundtrip: user image attachment count: $usr_imgs"
[ "$(q "SELECT count(*) FROM pic_image")" = 1 ] || fail "roundtrip: images not deduplicated"

# Check compaction mapping: first_kept_seq points to the imported bashExecution entry.
bash_seq=$(q "SELECT entry_seq FROM pic_bash")
cp_row=$(q "SELECT first_kept_seq || '|' || tokens_before || '|' || body || '|' ||
  json_extract(native, '\$.readFiles[0]') || '|' || json_extract(native, '\$.modifiedFiles[0]')
  FROM pic_entry WHERE kind = 'compaction'")
[ "$cp_row" = "$bash_seq|42000|Compacted earlier work.|photo.png|never-created.txt" ] || fail "roundtrip: compaction: $cp_row"

# Check custom_message (pic.instructions).
[ "$(q "SELECT body FROM pic_entry WHERE kind = 'instructions'")" = "Use C11." ] || fail "roundtrip: instructions"

# Export back to Pi JSONL, re-import into a fresh DB, and compare key structures.
pic export --pi - > "$T/reexport.jsonl" || fail "roundtrip: export --pi"
grep -qF '"type":"toolCall","id":"toolu_1","name":"write"' "$T/reexport.jsonl" || fail "reexport: missing toolCall"
grep -qF '"role":"toolResult","toolCallId":"toolu_2","toolName":"read","content":[{"type":"text","text":"Read image file [image/png]"},{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]' "$T/reexport.jsonl" ||
    fail "reexport: missing toolResult image"
grep -qF '"type":"thinking","thinking":"plan first","signature":"sig-anth-1"' "$T/reexport.jsonl" || fail "reexport: missing thinking"
grep -qF '"redacted":true' "$T/reexport.jsonl" || fail "reexport: missing redacted"
grep -qF '"type":"compaction"' "$T/reexport.jsonl" || fail "reexport: missing compaction"
grep -qF '"tokensBefore":42000' "$T/reexport.jsonl" || fail "reexport: missing tokensBefore"
grep -qF '"customType":"pic.instructions","content":"Use C11."' "$T/reexport.jsonl" || fail "reexport: missing instructions"
grep -qF '"role":"bashExecution","command":"echo hi"' "$T/reexport.jsonl" || fail "reexport: missing bashExecution"
grep -qF '"type":"session_info"' "$T/reexport.jsonl" && grep -qF '"name":"roundtrip-name"' "$T/reexport.jsonl" || fail "reexport: missing name"

DB2="$T/j2.sqlite"
sid2=$("$PIC" --db "$DB2" --workspace "$WS" import "$T/reexport.jsonl") || fail "re-import failed"
"$PIC" --db "$DB2" --workspace "$WS" check > /dev/null || fail "re-import check failed"
[ "$(sqlite3 "$DB2" "SELECT count(*) FROM pic_effect")" = 2 ] || fail "re-import: effect count"
[ "$(sqlite3 "$DB2" "SELECT count(*) FROM pic_entry WHERE kind = 'compaction'")" = 1 ] || fail "re-import: compaction count"
[ "$(sqlite3 "$DB2" "SELECT name FROM pic_session WHERE id = '$sid2'")" = "roundtrip-name" ] || fail "re-import: name"
printf 'PASS: full Pi v3 import and export round-trip preserves tools, images, thinking, compaction, instructions, bash and name\n'

# ---- 2. Multi-branch tree import, branch_summary, /tree and /fork -----------
DB="$T/tree.sqlite"
cat > "$T/branches.jsonl" <<EOF
{"type":"session","version":3,"id":"tree-sess","timestamp":"2026-11-01T10:00:00.000Z","cwd":"$WS"}
{"type":"message","id":"m1","parentId":null,"timestamp":"2026-11-01T10:00:01.000Z","message":{"role":"user","content":"root prompt"}}
{"type":"message","id":"m2","parentId":"m1","timestamp":"2026-11-01T10:00:02.000Z","message":{"role":"assistant","content":[{"type":"text","text":"root reply"}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","stopReason":"stop"}}
{"type":"message","id":"m3","parentId":"m2","timestamp":"2026-11-01T10:00:03.000Z","message":{"role":"user","content":"branch A prompt"}}
{"type":"message","id":"m4","parentId":"m3","timestamp":"2026-11-01T10:00:04.000Z","message":{"role":"assistant","content":[{"type":"text","text":"branch A reply"}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","stopReason":"stop"}}
{"type":"model_change","id":"mc2","parentId":"m2","timestamp":"2026-11-01T10:00:04.500Z","provider":"anthropic","modelId":"claude-sonnet-5-5"}
{"type":"branch_summary","id":"bs1","parentId":"mc2","timestamp":"2026-11-01T10:00:05.000Z","fromId":"m4","summary":"Explored branch A.","details":{"readFiles":["a.c"],"modifiedFiles":[]},"usage":{"input":50,"output":20,"cacheRead":0,"cacheWrite":0,"totalTokens":70},"fromHook":false}
{"type":"message","id":"m5","parentId":"bs1","timestamp":"2026-11-01T10:00:06.000Z","message":{"role":"user","content":"branch B prompt"}}
{"type":"message","id":"m6","parentId":"m5","timestamp":"2026-11-01T10:00:07.000Z","message":{"role":"assistant","content":[{"type":"text","text":"branch B reply"}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","stopReason":"stop"}}
{"type":"session_info","id":"si2","parentId":"m6","timestamp":"2026-11-01T10:00:08.000Z","name":"branched-tree"}
EOF

main_id=$(import_pi "$T/branches.jsonl")
pic tree --json "$main_id" > "$T/tree.json" || fail "tree: pic tree --json"
[ "$(wc -l < "$T/tree.json" | tr -d ' ')" = 3 ] || fail "tree: expected 3 turns: $(cat "$T/tree.json")"
grep -q '"text":"root prompt"' "$T/tree.json" || fail "tree: missing root"
grep -q '"indent":1,"active":false,"text":"branch A prompt"' "$T/tree.json" || fail "tree: branch A: $(cat "$T/tree.json")"
grep -q '"indent":1,"active":true,"text":"branch B prompt"' "$T/tree.json" || fail "tree: branch B: $(cat "$T/tree.json")"

branch_a=$(sqlite3 :memory: "SELECT json_extract(value, '\$.sessions') FROM json_each('[' || replace(trim(readfile('$T/tree.json'), char(10)), char(10), ',') || ']') WHERE json_extract(value, '\$.text') = 'branch A prompt'")
[ -n "$branch_a" ] && [ "$branch_a" != "$main_id" ] || fail "tree: branch A session head missing: $branch_a"
pic log "$main_id" | grep -q 'branch B reply' || fail "tree: main log missing branch B"
pic log "$main_id" | grep -q 'Explored branch A.' || fail "tree: main log missing branch_summary"
pic log "$main_id" | grep -q 'branch A reply' && fail "tree: main log leaked branch A"
pic log "$branch_a" | grep -q 'branch A reply' || fail "tree: branch A log missing branch A"
pic log "$branch_a" | grep -q 'branch B reply' && fail "tree: branch A log leaked branch B"

# Forking from the root turn of main_id AND from branch_a both work.
root_end=$(head -1 "$T/tree.json" | sed 's/.*"end":\([0-9]*\).*/\1/')
f1=$(pic fork "$main_id" --at "$root_end") || fail "tree: fork main at root"
f2=$(pic fork "$branch_a") || fail "tree: fork branch A"
[ -n "$f1" ] && [ -n "$f2" ] || fail "tree: empty fork ids"
pic check > /dev/null || fail "tree: check after forks"
printf 'PASS: multi-branch Pi tree preserves parentId branches, branch_summary, and /tree + /fork navigation\n'

# ---- 3. Continue imported session on Messages, Chat, Responses, Gemini ------
DB="$T/api.sqlite"
cat > "$T/api.jsonl" <<EOF
{"type":"session","version":3,"id":"api-sess","timestamp":"2026-11-01T10:00:00.000Z","cwd":"$WS"}
{"type":"message","id":"u1","parentId":null,"timestamp":"2026-11-01T10:00:01.000Z","message":{"role":"user","content":"run two tools"}}
{"type":"message","id":"a1","parentId":"u1","timestamp":"2026-11-01T10:00:02.000Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"secret-thought","thinkingSignature":"sig-anth-xyz"},{"type":"thinking","thinking":"","thinkingSignature":"red-xyz","redacted":true},{"type":"text","text":"Calling tools."},{"type":"toolCall","id":"call_a|item_1","name":"write","arguments":{"path":"api-no-run.txt","content":"x"}},{"type":"toolCall","id":"call_b|item_2","name":"read","arguments":{"path":"f.txt"}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","stopReason":"toolUse"}}
{"type":"message","id":"r1","parentId":"a1","timestamp":"2026-11-01T10:00:03.000Z","message":{"role":"toolResult","toolCallId":"call_a|item_1","toolName":"write","content":[{"type":"text","text":"wrote"}],"isError":false}}
{"type":"message","id":"r2","parentId":"r1","timestamp":"2026-11-01T10:00:04.000Z","message":{"role":"toolResult","toolCallId":"call_b|item_2","toolName":"read","content":[{"type":"text","text":"contents"},{"type":"image","data":"$PNG_B64","mimeType":"image/png"}],"isError":false}}
{"type":"message","id":"a2","parentId":"r2","timestamp":"2026-11-01T10:00:05.000Z","message":{"role":"assistant","content":[{"type":"text","text":"Done."}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","stopReason":"stop"}}
EOF

id_anth_same=$(import_pi "$T/api.jsonl")
id_anth_cross=$(import_pi "$T/api.jsonl")
id_chat=$(import_pi "$T/api.jsonl")
id_resp=$(import_pi "$T/api.jsonl")
id_gem=$(import_pi "$T/api.jsonl")

mkdir "$T/log"
"$SERVER" "$T/port" "$T/log" 120 \
    "sse:$S/text.sse" \
    "sse:$S/text.sse" \
    "sse:$here/chat-streams/text.sse" \
    "sse:$here/responses-streams/reasoning_text.sse" \
    "sse:$here/gemini-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
base="http://127.0.0.1:$(cat "$T/port")"
body() { sed '1,/^\r*$/d' "$T/log/$1.req" > "$T/body$1.json"; printf '%s' "$T/body$1.json"; }

# 3a. Anthropic same-model: replays thinking + signature + redacted_thinking + tool_use/tool_result!
pic submit n1 'go on' --session "$id_anth_same" > /dev/null
pic run --model anthropic/claude-sonnet-5-5 --api-url "$base/v1/messages" 2> "$T/err" || fail "anth same: $(cat "$T/err")"
b=$(body 1)
grep -qF '"type":"thinking","thinking":"secret-thought","signature":"sig-anth-xyz"' "$b" || fail "anth same: thinking not replayed: $(cat "$b")"
grep -qF '"type":"redacted_thinking","data":"red-xyz"' "$b" || fail "anth same: redacted_thinking not replayed"
pairs=$(sqlite3 :memory: "WITH m AS (SELECT key k, value v FROM json_each(readfile('$b'), '\$.messages')),
  c AS (SELECT m.k, CASE WHEN x.type = 'object' THEN json_extract(x.value, '\$.type') END t,
          CASE WHEN x.type = 'object' THEN coalesce(json_extract(x.value, '\$.id'), json_extract(x.value, '\$.tool_use_id')) END id
        FROM m, json_each(m.v, '\$.content') x)
  SELECT (SELECT count(*) FROM c WHERE t = 'tool_use') || ' ' ||
    (SELECT count(*) FROM c u WHERE t = 'tool_use' AND NOT EXISTS (SELECT 1 FROM c r WHERE r.t = 'tool_result' AND r.k = u.k + 1 AND r.id = u.id)) || ' ' ||
    (SELECT count(*) FROM c r WHERE t = 'tool_result' AND NOT EXISTS (SELECT 1 FROM c u WHERE u.t = 'tool_use' AND u.k = r.k - 1 AND u.id = r.id))")
[ "$pairs" = '2 0 0' ] || fail "anth same: pairs: $pairs"

# 3b. Anthropic cross-model: drops thinking, normalizes pipe in call ids identically!
pic submit n2 'go on' --session "$id_anth_cross" > /dev/null
pic run --model anthropic/other-model --api-url "$base/v1/messages" 2> "$T/err" || fail "anth cross: $(cat "$T/err")"
b=$(body 2)
grep -q 'secret-thought\|sig-anth-xyz\|red-xyz' "$b" && fail "anth cross: leaked thinking to other model"
pairs=$(sqlite3 :memory: "WITH m AS (SELECT key k, value v FROM json_each(readfile('$b'), '\$.messages')),
  c AS (SELECT m.k, CASE WHEN x.type = 'object' THEN json_extract(x.value, '\$.type') END t,
          CASE WHEN x.type = 'object' THEN coalesce(json_extract(x.value, '\$.id'), json_extract(x.value, '\$.tool_use_id')) END id
        FROM m, json_each(m.v, '\$.content') x)
  SELECT (SELECT count(*) FROM c WHERE t = 'tool_use') || ' ' ||
    (SELECT count(*) FROM c u WHERE t = 'tool_use' AND NOT EXISTS (SELECT 1 FROM c r WHERE r.t = 'tool_result' AND r.k = u.k + 1 AND r.id = u.id)) || ' ' ||
    (SELECT count(*) FROM c r WHERE t = 'tool_result' AND NOT EXISTS (SELECT 1 FROM c u WHERE u.t = 'tool_use' AND u.k = r.k - 1 AND u.id = r.id))")
[ "$pairs" = '2 0 0' ] || fail "anth cross: pairs: $pairs"

# 3c. Chat Completions
pic submit n3 'go on' --session "$id_chat" > /dev/null
pic run --model openrouter/test/model --api-url "$base/v1/chat/completions" 2> "$T/err" || fail "chat: $(cat "$T/err")"
b=$(body 3)
grep -q 'secret-thought\|sig-anth-xyz' "$b" && fail "chat: leaked thinking"
pairs=$(sqlite3 :memory: "WITH m AS (SELECT key k, value v FROM json_each(readfile('$b'), '\$.messages')),
  u AS (SELECT m.k, json_extract(x.value, '\$.id') id FROM m, json_each(m.v, '\$.tool_calls') x),
  r AS (SELECT k, json_extract(v, '\$.tool_call_id') id FROM m WHERE json_extract(v, '\$.role') = 'tool')
  SELECT (SELECT count(*) FROM u) || ' ' ||
    (SELECT count(*) FROM u WHERE NOT EXISTS (SELECT 1 FROM r WHERE r.id = u.id AND r.k > u.k)) || ' ' ||
    (SELECT count(*) FROM r WHERE NOT EXISTS (SELECT 1 FROM u WHERE u.id = r.id AND u.k < r.k))")
[ "$pairs" = '2 0 0' ] || fail "chat: pairs: $pairs"

# 3d. Responses
pic submit n4 'go on' --session "$id_resp" > /dev/null
pic run --model openai/test-model --api-url "$base/v1/responses" 2> "$T/err" || fail "responses: $(cat "$T/err")"
b=$(body 4)
grep -q 'secret-thought\|sig-anth-xyz' "$b" && fail "responses: leaked thinking"
pairs=$(sqlite3 :memory: "WITH i AS (SELECT json_extract(value, '\$.type') t, json_extract(value, '\$.call_id') id FROM json_each(readfile('$b'), '\$.input'))
  SELECT (SELECT count(*) FROM i WHERE t = 'function_call') || ' ' ||
    (SELECT count(*) FROM i a WHERE t = 'function_call' AND NOT EXISTS (SELECT 1 FROM i o WHERE o.t = 'function_call_output' AND o.id = a.id)) || ' ' ||
    (SELECT count(*) FROM i o WHERE t = 'function_call_output' AND NOT EXISTS (SELECT 1 FROM i a WHERE a.t = 'function_call' AND a.id = o.id))")
[ "$pairs" = '2 0 0' ] || fail "responses: pairs: $pairs"

# 3e. Gemini (gemini-3-flash-preview carries tool call ids in functionCall & functionResponse)
pic submit n5 'go on' --session "$id_gem" > /dev/null
pic run --model google/gemini-3-flash-preview --api-url "$base/v1beta" 2> "$T/err" || fail "gemini: $(cat "$T/err")"
b=$(body 5)
grep -q 'secret-thought\|sig-anth-xyz' "$b" && fail "gemini: leaked thinking"
pairs=$(sqlite3 :memory: "WITH c AS (SELECT key k, value v FROM json_each(readfile('$b'), '\$.contents')),
  fc AS (SELECT c.k, json_extract(p.value, '\$.functionCall.id') id FROM c, json_each(c.v, '\$.parts') p WHERE json_type(p.value, '\$.functionCall') = 'object'),
  fr AS (SELECT c.k, json_extract(p.value, '\$.functionResponse.id') id FROM c, json_each(c.v, '\$.parts') p WHERE json_type(p.value, '\$.functionResponse') = 'object')
  SELECT (SELECT count(*) FROM fc) || ' ' ||
    (SELECT count(*) FROM fc WHERE NOT EXISTS (SELECT 1 FROM fr WHERE fr.id = fc.id AND fr.k = fc.k + 1)) || ' ' ||
    (SELECT count(*) FROM fr WHERE NOT EXISTS (SELECT 1 FROM fc WHERE fc.id = fr.id AND fc.k = fr.k - 1))")
[ "$pairs" = '2 0 0' ] || fail "gemini: pairs: $pairs ($(cat "$b"))"
[ ! -e "$WS/api-no-run.txt" ] || fail "api: an imported tool call ran"
pic check > /dev/null || fail "api: check after continuations"
printf 'PASS: imported Pi session continues cleanly on Messages (same+cross), Chat, Responses, and Gemini\n'

kill "$spid" 2>/dev/null || :
spid=

# ---- 4. Usage import & lapse trim calibration (without inflating pic usage) -
DB="$T/usage.sqlite"
cat > "$T/u.jsonl" <<EOF
{"type":"session","version":3,"id":"u-sess","timestamp":"2026-11-01T10:00:00.000Z","cwd":"$WS"}
{"type":"message","id":"u1","parentId":null,"message":{"role":"user","content":"one"}}
{"type":"message","id":"a1","parentId":"u1","message":{"role":"assistant","content":[{"type":"text","text":"ok-1"}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","usage":{"input":10,"cacheRead":100,"cacheWrite":20,"output":9,"cost":{"total":1.50}},"stopReason":"stop"}}
{"type":"message","id":"u2","parentId":"a1","message":{"role":"user","content":"two"}}
{"type":"message","id":"a2","parentId":"u2","message":{"role":"assistant","content":[{"type":"text","text":"ok-2"}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","usage":{"output":5},"stopReason":"stop"}}
{"type":"message","id":"u3","parentId":"a2","message":{"role":"user","content":"three"}}
{"type":"message","id":"a3","parentId":"u3","message":{"role":"assistant","content":[{"type":"text","text":"ok-3"}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","stopReason":"stop"}}
{"type":"message","id":"u4","parentId":"a3","message":{"role":"user","content":"four"}}
{"type":"message","id":"a4","parentId":"u4","message":{"role":"assistant","content":[{"type":"text","text":"ok-4"}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5","usage":{"input":"bad","output":-1},"stopReason":"stop"}}
EOF
before=$("$PIC" --db "$DB" usage --by-trial --json)
iu=$(import_pi "$T/u.jsonl")
got=$(q "SELECT coalesce(g.usage, '-') FROM pic_generation g JOIN pic_submission u ON u.id = g.submission_id WHERE u.session_id = '$iu' AND g.purpose = 'reply' ORDER BY g.id" | tr '\n' ' ')
want='{"input_tokens":10,"cache_read_input_tokens":100,"cache_creation_input_tokens":20,"output_tokens":9,"model":"claude-sonnet-5-5","imported":true} '
want="$want"'{"output_tokens":5,"model":"claude-sonnet-5-5","imported":true} - - '
[ "$got" = "$want" ] || fail "usage: $got"
[ "$("$PIC" --db "$DB" usage --by-trial --json)" = "$before" ] || fail "usage: import inflated pic usage"
q "SELECT 1 FROM pic_generation WHERE json_extract(usage, '\$.pic_cost') IS NOT NULL AND json_extract(usage, '\$.imported')" | grep -q . &&
    fail "usage: imported reply carries pic_cost"

# Calibration on resume after lapse (mirrors import_claude.sh).
msg() { printf '%08000d' 0 | tr 0 "$1"; }
cal_pi() {
    printf '{"type":"session","version":3,"id":"cal-%s","timestamp":"2026-11-01T10:00:00.000Z","cwd":"%s"}\n' "$1" "$WS"
    parent=null
    n=0
    for l in A B C D E F G H I J K L; do
        n=$((n + 1))
        printf '{"type":"message","id":"u%d","parentId":%s,"message":{"role":"user","content":"%s"}}\n' "$n" "$parent" "$(msg "$l")"
        u=
        [ "$n" != 12 ] || [ "$1" != yes ] || u=',"usage":{"input":100,"cacheRead":30000,"cacheWrite":5900,"output":3,"totalTokens":36003}'
        printf '{"type":"message","id":"a%d","parentId":"u%d","message":{"role":"assistant","content":[{"type":"text","text":"ok-%d"}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-5-5"%s,"stopReason":"stop"}}\n' "$n" "$n" "$n" "$u"
        parent="\"a$n\""
    done
}
cal_pi yes > "$T/cal-yes.jsonl"
cal_pi no > "$T/cal-no.jsonl"
"$PIC" settings cacheRetention short > /dev/null
rm -rf "$T/log" "$T/port"
mkdir "$T/log"
"$SERVER" "$T/port" "$T/log" 120 "sse:$S/text.sse" "sse:$S/text.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "cal: server"; sleep 0.05; done
URL="http://127.0.0.1:$(cat "$T/port")/v1/messages"
for v in no yes; do
    idv=$(import_pi "$T/cal-$v.jsonl")
    q "UPDATE pic_entry SET created_ms = created_ms - 400000"
    pic submit "cal-$v" 'go on' --session "$idv" > /dev/null
    PIC_LAPSE_HOLDOUT=0 pic --lapse-floor 0 run --model anthropic/m --api-url "$URL" 2> "$T/err" || fail "cal $v: $(cat "$T/err")"
    cal=$(q "SELECT json_extract(context, '\$.calibration') FROM pic_hook_run WHERE event = 'PreRequest' AND reason = 'lapse' AND session_id = '$idv' ORDER BY id DESC LIMIT 1")
    kept=$(q "SELECT e.kind || ':' || substr(e.body, 1, 1) FROM pic_entry e WHERE e.seq = (SELECT first_kept_seq FROM pic_entry c JOIN pic_submission u ON u.id = c.submission_id WHERE c.kind = 'compaction' AND u.session_id = '$idv')")
    if [ "$v" = no ]; then
        [ "$cal" = 1 ] || [ "$cal" = 1.0 ] || fail "cal no: $cal"
        [ "$kept" = user:C ] || fail "cal no: kept $kept"
    else
        [ "$(q "SELECT $cal BETWEEN 1.45 AND 1.55")" = 1 ] || fail "cal yes: $cal"
        [ "$kept" = user:F ] || fail "cal yes: kept $kept"
    fi
done
pic check > /dev/null || fail "cal: check"
printf 'PASS: imported Pi usage calibrates lapse compaction without inflating pic usage\n'

kill "$spid" 2>/dev/null || :
spid=

# ---- 5. Pi v1 compatibility + malformed/unknown entry resilience ------------
DB="$T/edge.sqlite"
cat > "$T/v1.jsonl" <<EOF
{"type":"session","id":"v1-sess","timestamp":"2025-10-01T00:00:00.000Z","cwd":"$WS"}
{"type":"message","timestamp":"2025-10-01T00:00:01.000Z","message":{"role":"user","content":"old v1 question"}}
{"type":"message","timestamp":"2025-10-01T00:00:02.000Z","message":{"role":"assistant","content":"old v1 answer"}}
{"type":"message","timestamp":"2025-10-01T00:00:03.000Z","message":{"role":"user","content":"kept v1 question"}}
{"type":"compaction","timestamp":"2025-10-01T00:00:04.000Z","summary":"v1 summary","firstKeptEntryIndex":3,"tokensBefore":12345}
EOF
v1_id=$(import_pi "$T/v1.jsonl")
v1_kept=$(q "SELECT e.body FROM pic_entry e WHERE e.seq = (SELECT first_kept_seq FROM pic_entry WHERE kind = 'compaction')")
[ "$v1_kept" = "kept v1 question" ] || fail "v1: firstKeptEntryIndex not mapped: $v1_kept"
printf 'PASS: Pi v1 sessions (no id/parentId, firstKeptEntryIndex) import cleanly\n'

# Malformed JSON, unknown entry types mid-chain, out-of-order and missing tool
# results, huge tokensBefore (no float-cast-overflow), bad image base64.
cat > "$T/messy.jsonl" <<'EOF'
not valid json at all
12345
["array","not","object"]
{"type":"session","version":3,"id":"messy","timestamp":"2026-11-01T10:00:00.000Z","cwd":"/tmp"}
{"type":"message","id":"u1","parentId":null,"message":{"role":"user","content":[{"type":"text","text":"first"},{"type":"image","data":"!!!not-base64!!!","mimeType":"image/png"}]}}
{"type":"future_unknown_entry","id":"unk1","parentId":"u1","payload":{"anything":true}}
{"type":"message","id":"a1","parentId":"unk1","message":{"role":"assistant","content":[{"type":"toolCall","id":"c1","name":"read","arguments":{"path":"a"}},{"type":"toolCall","id":"c2","name":"read","arguments":{"path":"b"}}],"stopReason":"toolUse"}}
{"type":"message","id":"tr2","parentId":"a1","message":{"role":"toolResult","toolCallId":"c2","toolName":"read","content":"res-b","isError":false}}
{"type":"message","id":"tr_orphan","parentId":"tr2","message":{"role":"toolResult","toolCallId":"no-such-call","toolName":"read","content":"orphan","isError":false}}
{"type":"compaction","id":"cp1","parentId":"tr_orphan","summary":"huge","firstKeptEntryId":"missing-id","tokensBefore":1e30}
{"type":"message","id":"u2","parentId":"cp1","message":{"role":"user","content":"still linked"}}
{"type":"message","id":"a2","parentId":"u2","message":{"role":"assistant","content":[{"type":"text","text":"survived"}],"stopReason":"stop"}}
{"type":"truncated_line
EOF
messy_id=$(import_pi "$T/messy.jsonl")
# c1 had no result -> synthesized as error; c2 matched -> ok; both in ordinal order!
messy_effs=$(q "SELECT group_concat(call_id || ':' || is_error, ',') FROM pic_effect e JOIN pic_entry x ON x.seq = e.entry_seq JOIN pic_submission u ON u.id = x.submission_id WHERE u.session_id = '$messy_id' ORDER BY e.ordinal")
[ "$messy_effs" = 'c1:1,c2:0' ] || fail "messy: effects: $messy_effs"
# u2 still links through unk1, tr2, tr_orphan, cp1 back to u1!
pic log "$messy_id" | grep -q 'still linked' || fail "messy: chain broken"
pic log "$messy_id" | grep -q 'first' || fail "messy: lost root through unknown entry"
# Empty/metadata-only file fails cleanly without corrupting the journal.
printf '{"type":"session","version":3,"id":"empty"}\n{"type":"model_change","id":"m1","parentId":null}\n' > "$T/empty.jsonl"
pic import "$T/empty.jsonl" > /dev/null 2> "$T/err" && fail "empty: should have failed"
grep -q 'no user messages' "$T/err" || fail "empty: error: $(cat "$T/err")"
pic check > /dev/null || fail "messy: check after failed import"
printf 'PASS: malformed JSON, unknown entry types, out-of-order/missing tool results and empty files are handled safely\n'