#!/bin/sh
# pic import --claude: a Claude Code transcript as a new conversation, its
# main thread only (sidechains, meta, synthetic and abandoned branches left
# out), from its latest compact summary, cut before --until; tool calls
# journaled as pic's tools, already done, and the rest rendered as text; the
# result passes pic check and continues at each API with every tool call
# paired with its result. The fixtures are synthetic.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
here=$(cd "$(dirname "$0")" && pwd)
F=$here/claude-transcripts
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-import-claude.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 PIC_PI_EXPORT=0 PIC_MODEL_CATALOG=offline
"$PIC" settings cacheRetention none > /dev/null
WS="$T/ws"
mkdir "$WS"
sed "s|@WS@|$WS|g" "$F/basic.jsonl" > "$T/basic.jsonl"
sed "s|@WS@|$WS|g" "$F/compact.jsonl" > "$T/compact.jsonl"
DB="$T/j.sqlite"
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
q() { sqlite3 "$DB" "$1"; }
# import FILE [ARGS]: the new id; stdout kept in $T/out
import() {
f=$1
shift
pic import --claude "$f" "$@" > "$T/out" 2> "$T/err" || fail "import $*: $(cat "$T/err")"
[ ! -s "$T/err" ] || fail "import $*: wrote to stderr"
pic check > /dev/null || fail "import $*: pic check"
head -1 "$T/out"
}
# The whole transcript.
id=$(import "$T/basic.jsonl")
[ "$(q "SELECT count(*) FROM pic_session WHERE id = '$id'")" = 1 ] || fail "no session $id"
for secret in THINK-SECRET META-SECRET SIDECHAIN-SECRET ABANDONED-SECRET SYNTHETIC-SECRET ATTACH-SECRET SYSTEM-SECRET; do
if sqlite3 "$DB" .dump | grep -q "$secret"; then fail "imported $secret"; fi
done
printf 'PASS: sidechains, thinking, meta, synthetic, attachment, system and abandoned-branch records are left out\n'
# Output: ids and counts only.
grep -q question "$T/out" && fail "output carries transcript text"
grep -q '^requests 5, tool calls 8 structured, 2 as text$' "$T/out" || fail "counts: $(cat "$T/out")"
grep -q '^context [0-9][0-9]* tokens (pic estimate: chars/4 of the messages)$' "$T/out" || fail "tokens: $(cat "$T/out")"
grep -q '^transcript usage 6 tokens (input + cache read + cache write of the last reply)$' "$T/out" || fail "usage: $(cat "$T/out")"
printf 'PASS: import prints the id, counts, the estimate and the transcript usage\n'
# Each tool mapping, with its result and error flag.
want() { # TOOL INPUT RESULT IS_ERROR
got=$(q "SELECT f.input || '|' || f.result || '|' || f.is_error || '|' || f.state FROM pic_effect f JOIN pic_entry e ON e.seq = f.entry_seq
JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = '$id' AND f.tool = '$1' AND f.call_id = '$5'")
[ "$got" = "$2|$3|$4|done" ] || fail "$1 ($5): $got"
}
want bash '{"command":"touch bash-ran","timeout":5}' 'bash out' 0 toolu_bash
want read '{"path":"/x/a.c","offset":2,"limit":3}' 'line two' 0 toolu_read
want edit '{"path":"/x/a.c","edits":[{"oldText":"a","newText":"b"}]}' edited 0 toolu_edit
want edit '{"path":"/x/b.c","edits":[{"oldText":"c","newText":"d"},{"oldText":"e","newText":"f"}]}' 'no match' 1 toolu_multi
want write '{"path":"written.txt","content":"hello"}' wrote 0 toolu_write
want grep '{"pattern":"foo","path":"src","glob":"*.c","ignoreCase":true,"context":2,"limit":10}' 'grep out' 0 toolu_grep
want find '{"pattern":"**/*.h","path":"src"}' 'glob out' 0 toolu_glob
printf 'PASS: Bash, Read, Edit, MultiEdit, Write, Grep and Glob become bash, read, edit, write, grep and find\n'
# LS becomes ls; the Agent call beside it is text in the turn, its result
# (an image omitted) text after the ls result.
want ls '{"path":"src"}' "$(printf 'ls out\n\n[result: agent said\n[image omitted]]')" 0 toolu_ls
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' AND effect_id = (SELECT id FROM pic_effect WHERE call_id = 'toolu_ls')" |
grep -q '^\[result: agent said$' || fail "agent result not after the ls result"
[ "$(q "SELECT json_extract(body, '\$[3].text') FROM pic_entry WHERE seq = (SELECT entry_seq FROM pic_effect WHERE call_id = 'toolu_ls')")" = \
'[tool Agent: {"description":"look","prompt":"go look"}]' ] || fail "agent call: $(q "SELECT body FROM pic_entry WHERE seq = (SELECT entry_seq FROM pic_effect WHERE call_id = 'toolu_ls')")"
printf 'PASS: LS becomes ls; an unknown tool and its result are text, an image a placeholder\n'
# A turn of only an unknown tool: the call ends that request as text, its
# result opens the next; the user's image is a placeholder.
users=$(q "SELECT group_concat(replace(e.body, char(10), '/'), ' | ') FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id
WHERE u.session_id = '$id' AND e.kind = 'user'")
[ "$users" = 'first question | second question/[image omitted] | [result: search results] | third question | fourth question' ] ||
fail "user entries: $users"
answers=$(q "SELECT group_concat(json_extract(e.body, '\$[0].text'), ' | ') FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id
WHERE u.session_id = '$id' AND e.kind = 'answer'")
[ "$answers" = 'All done. | [tool WebSearch: {"query":"q"}] | Found it. | Third answer. | Fourth answer.' ] || fail "answers: $answers"
printf 'PASS: a turn of only an unknown tool is text in the answer and the next request\n'
# Nothing ran: the bash and write calls are history.
[ ! -e "$WS/bash-ran" ] && [ ! -e "$WS/written.txt" ] || fail "an imported tool call ran"
# The cut: everything before the record with that uuid.
id2=$(import "$T/basic.jsonl" --until u5)
[ "$(q "SELECT count(*) FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = '$id2' AND e.body LIKE '%fourth%'")" = 0 ] ||
fail "cut: the cut record was imported"
[ "$(q "SELECT json_extract(body, '\$[0].text') FROM pic_entry WHERE seq = (SELECT head_seq FROM pic_session WHERE id = '$id2')")" = 'Third answer.' ] ||
fail "cut: head"
grep -q '^transcript usage 240 tokens' "$T/out" || fail "cut: usage $(cat "$T/out")"
# A cut between tool calls and their results: the calls are text.
id3=$(import "$T/basic.jsonl" --until r3)
[ "$(q "SELECT count(*) FROM pic_effect f JOIN pic_entry e ON e.seq = f.entry_seq JOIN pic_submission u ON u.id = e.submission_id
WHERE u.session_id = '$id3'")" = 2 ] || fail "cut: unanswered calls journaled"
grep -q '^requests 1, tool calls 2 structured, 3 as text$' "$T/out" || fail "cut: counts $(cat "$T/out")"
pic import --claude "$T/basic.jsonl" --until nosuch > /dev/null 2> "$T/err" && fail "cut: an unknown uuid was accepted"
grep -q 'no record nosuch' "$T/err" || fail "cut: $(cat "$T/err")"
printf 'PASS: --until imports everything before that record\n'
# Compaction: from the latest compact summary before the cut.
idc=$(import "$T/compact.jsonl")
body=$(q "SELECT group_concat(body, ' ') FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = '$idc'")
case "$body" in *OLD-*|*SUMMARY-ONE*|*MIDDLE-ANSWER*) fail "compact: before the summary: $body" ;; esac
case "$body" in *SUMMARY-TWO*LATE-ANSWER*) ;; *) fail "compact: $body" ;; esac
idc2=$(import "$T/compact.jsonl" --until b2)
body=$(q "SELECT group_concat(body, ' ') FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = '$idc2'")
case "$body" in *OLD-*|*SUMMARY-TWO*) fail "compact cut: $body" ;; esac
case "$body" in *'SUMMARY-ONE of the work so far'*'after the first compaction'*MIDDLE-ANSWER*) ;; *) fail "compact cut: $body" ;; esac
printf 'PASS: a compacted transcript starts from its latest summary before the cut\n'
# Attachments: hook context, @-mentioned files, file-change notices and
# queued prompts are user text in record order, merged with the user text
# beside them and after a batch's results, never between a call and its
# result; other attachment kinds and an abandoned queued prompt are not.
sed "s|@WS@|$WS|g" "$F/attachments.jsonl" > "$T/attachments.jsonl"
ida=$(import "$T/attachments.jsonl")
for secret in HOOK-OUTPUT-SECRET SKILL-SECRET DEFERRED-SECRET REMINDER-SECRET ABANDONED-SECRET; do
if sqlite3 "$DB" .dump | grep -q "$secret"; then fail "attachments: imported $secret"; fi
done
grep -q '^requests 3, tool calls 1 structured, 0 as text$' "$T/out" || fail "attachments: counts $(cat "$T/out")"
inses="FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = '$ida'"
got=$(q "SELECT e.body $inses AND e.kind = 'user' ORDER BY e.seq LIMIT 1")
want=$(printf '<system-reminder>\nSessionStart hook additional context: CTX-START\nCTX-MORE\n</system-reminder>\n\nfirst question\n\n<file name="/w/notes.txt">\nFILE-BODY\n</file>\n\n<file name="/w/plain.txt">\nPLAIN-BODY\n</file>')
[ "$got" = "$want" ] || fail "attachments: first request: $got"
got=$(q "SELECT e.body $inses AND e.kind = 'tool_result'")
want=$(printf 'out1\n\n<system-reminder>\nPreToolUse hook additional context: PRE-CTX\n</system-reminder>\n\n<system-reminder>\nNote: /w/a.c was modified, either by the user or by a linter. Its changes:\n1\tEDIT-SNIP\n</system-reminder>\n\nQUEUED-PROMPT')
[ "$got" = "$want" ] || fail "attachments: after the result: $got"
got=$(q "SELECT group_concat(e.kind || ':' || replace(CASE WHEN e.kind IN ('user','tool_result') THEN substr(e.body, 1, 11)
ELSE (SELECT group_concat(coalesce(json_extract(value, '\$.text'), json_extract(value, '\$.name')), '+') FROM json_each(e.body)) END,
char(10), '/'), ' | ') $inses")
[ "$got" = 'user:<system-rem | assistant:Running it.+bash | tool_result:out1//<syst | answer:Done. | user:NEXT-PROMPT | answer:Next done. | user:last questi | answer:Last answer.' ] ||
fail "attachments: order: $got"
printf 'PASS: hook context, files, change notices and queued prompts are user text in place\n'
# The workspace: the transcript's cwd, or --workspace.
(cd "$T" && "$PIC" import --claude "$T/basic.jsonl" > "$T/out2") || fail "cwd: import"
"$PIC" --workspace "$WS" sessions | grep -q "^$(head -1 "$T/out2")" || fail "cwd: not in the transcript's workspace"
mkdir "$T/other"
(cd "$T" && "$PIC" import --claude "$T/basic.jsonl" --workspace "$T/other" > "$T/out3") || fail "--workspace: import"
"$PIC" --workspace "$T/other" sessions | grep -q "^$(head -1 "$T/out3")" || fail "--workspace: not there"
printf 'PASS: the workspace is the transcript cwd unless --workspace names one\n'
# Continued at each API: every tool_use has its result in the next message.
mkdir "$T/log"
"$SERVER" "$T/port" "$T/log" 120 "sse:$S/text.sse" "sse:$here/chat-streams/text.sse" "sse:$here/responses-streams/reasoning_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"; }
pic submit next1 'go on' --session "$id" > /dev/null
pic run --model anthropic/m --api-url "$base/v1/messages" 2> "$T/err" || fail "anthropic: $(cat "$T/err")"
b=$(body 1)
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" = '8 0 0' ] || fail "anthropic: tool_use/tool_result pairs: $pairs"
pic check > /dev/null || fail "anthropic: check after the reply"
[ ! -e "$WS/bash-ran" ] && [ ! -e "$WS/written.txt" ] || fail "anthropic: an imported tool call ran"
printf 'PASS: the imported conversation continues at the Messages API with its tool calls paired\n'
pic submit next2 'go on' --session "$id2" > /dev/null
pic run --model openrouter/test/model --api-url "$base/v1/chat/completions" 2> "$T/err" || fail "chat: $(cat "$T/err")"
b=$(body 2)
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" = '8 0 0' ] || fail "chat: tool_calls/tool pairs: $pairs"
printf 'PASS: and at the Chat Completions API\n'
pic submit next3 'go on' --session "$id3" > /dev/null
pic run --model openai/test-model --api-url "$base/v1/responses" 2> "$T/err" || fail "responses: $(cat "$T/err")"
b=$(body 3)
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: function_call pairs: $pairs"
pic check > /dev/null || fail "check after the replies"
printf 'PASS: and at the Responses API\n'
# --count: the first request pic would send on the conversation (its system
# prompt with the project instructions, its tools, the messages), counted
# by the Messages API's counter; the key is sent and never printed.
mkdir "$T/cws"
printf 'COUNT-RULE for this project\n' > "$T/cws/AGENTS.md"
ANTHROPIC_API_KEY=pic-count-secret-key "$PIC" --db "$DB" --model anthropic/m import --claude "$T/basic.jsonl" --workspace "$T/cws" \
--count --api-url "$base/v1/messages" > "$T/cout" 2> "$T/err" || fail "count: $(cat "$T/err")"
grep -q pic-count-secret-key "$T/cout" "$T/err" && fail "count: the key was printed"
creq=$(grep -l '^POST /v1/messages/count_tokens ' "$T/log/"*.req) || fail "count: no count_tokens request"
[ "$(printf '%s\n' "$creq" | wc -l | tr -d ' ')" = 1 ] || fail "count: more than one count_tokens request"
grep -qi '^x-api-key: pic-count-secret-key' "$creq" || fail "count: the key was not sent"
sed '1,/^\r*$/d' "$creq" > "$T/cbody.json"
got=$(sqlite3 :memory: "SELECT json_extract(b, '\$.model') || ' ' || (json_extract(b, '\$.system[0].text') LIKE '%COUNT-RULE for this project%') || ' ' ||
(SELECT group_concat(json_extract(value, '\$.name'), ',') FROM json_each(b, '\$.tools')) || ' ' || json_array_length(b, '\$.messages') || ' ' ||
(json_type(b, '\$.stream') IS NULL AND json_type(b, '\$.max_tokens') IS NULL) FROM (SELECT readfile('$T/cbody.json') b)")
case "$got" in 'm 1 read,bash,edit,write'*' 1'|'m 1 '*read*bash*edit*write*' 1') ;; *) fail "count: request body: $got" ;; esac
n=$(wc -c < "$T/cbody.json" | tr -d ' ')
grep -q "^counted $n tokens (anthropic count_tokens: system prompt, tools and messages)\$" "$T/cout" || fail "count: $(cat "$T/cout")"
grep -q '^context [0-9]* tokens (pic estimate' "$T/cout" && grep -q '^transcript usage 6 tokens' "$T/cout" || fail "count: the other figures: $(cat "$T/cout")"
"$PIC" --db "$DB" check > /dev/null || fail "count: pic check"
"$PIC" --db "$DB" --model openrouter/test/model import --claude "$T/basic.jsonl" --workspace "$T/cws" --count > "$T/cout" 2> "$T/err" ||
fail "count elsewhere: $(cat "$T/err")"
grep -q '^counted: openrouter has no token-counting endpoint; the estimate stands$' "$T/cout" || fail "count elsewhere: $(cat "$T/cout")"
printf 'PASS: --count counts pic'"'"'s own first request at the Messages API and says when a provider cannot\n'