Skip to content
pi-c Artifact [2f1e019a45]
Login

Artifact [2f1e019a45]

Artifact 2f1e019a45d649b89e3a3767b493cfcc72f46b2d5c29b9d567a1aaa8187f5725:


#!/bin/sh
# Steering and follow-ups over --commands (Pi's RPC command lines on stdin):
# a steer sent during a tool call reaches the model as a user message after
# the tool result, a follow-up runs after the answer, clear_queue returns and
# drops what was queued, abort cancels, an unknown command is an error and the
# run goes on. Every message is journaled as it arrives.
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-steer.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME/.pic/prompts"
# 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-steer-test-key PIC_PI_EXPORT=0
n=0
serve() { # SPEC...: a fresh server, journal and workspace
    [ -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"
    "$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
    # ask takes its endpoint from the model: a models.json provider at the fake server.
    printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"m"}]}}}' \
        "$(cat "$T/port$n")" > "$T/models$n.json"
    export PIC_MODELS_FILE="$T/models$n.json"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
await() { # FILE PATTERN: wait up to 30s for the fixed string PATTERN in FILE
    i=0
    until grep -qF -- "$2" "$1" 2>/dev/null; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for $2 in $1: $(cat "$1" 2>/dev/null)"
        sleep 0.05
    done
}
exists() { # FILE: wait up to 30s for it
    i=0
    until [ -e "$1" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for $1: $(cat "$T/err$n" 2>/dev/null)"
        sleep 0.05
    done
}
start() { # ARGS...: pic --json --commands ARGS, commands written to fd 3
    rm -f "$T/in"
    mkfifo "$T/in"
    "$PIC" --db "$DB" --workspace "$WS" --model fake/m --json --commands "$@" < "$T/in" > "$T/ev$n" 2> "$T/err$n" &
    pid=$!
    exec 3> "$T/in"
}
send() { printf '%s\n' "$1" >&3; }
finish() { # wait for pic; its status in rc
    rc=0
    wait "$pid" || rc=$?
    pid=
    exec 3>&-
}
# The position of the fixed string $2 in file $1 (0: absent).
at() { awk -v s="$2" '{ i = index($0, s); if (i) { print i; found = 1; exit } } END { if (!found) print 0 }' "$1"; }

# A steer and a follow-up sent while a command runs; one-at-a-time by default.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
start ask 'hold on'
exists "$WS/started"
send '{"id":"s1","type":"steer","message":"steer one"}'
await "$T/ev$n" '{"id":"s1","type":"response","command":"steer","success":true,"data":{"disposition":"queued"}}'
await "$T/ev$n" '{"type":"queue_update","steering":["steer one"],"followUp":[]}'
send '{"type":"steer","message":"steer two"}'
send '{"type":"follow_up","message":"then this"}'
send '{"type":"bogus"}'
send 'not json'
await "$T/ev$n" '{"type":"response","command":"bogus","success":false,"error":"Unknown command: bogus"}'
await "$T/ev$n" '{"type":"response","command":"follow_up","success":true,"data":{"disposition":"queued"}}'
await "$T/ev$n" '{"type":"queue_update","steering":["steer one","steer two"],"followUp":["then this"]}'
await "$T/ev$n" '{"type":"response","command":"parse","success":false,"error":"Failed to parse command: '
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "steer: exit $rc: $(cat "$T/err$n")"
# Request 2 carries the first steer as a user message after the tool result; not the second.
r2="$LOG/2.req"
[ -e "$r2" ] || fail "steer: no second request"
tr=$(at "$r2" '"tool_result"')
st=$(at "$r2" '{"role":"user","content":"steer one"}')
[ "$tr" -gt 0 ] && [ "$st" -gt "$tr" ] || fail "steer: steer one not after the tool result: $(cat "$r2")"
[ "$(at "$r2" 'steer two')" = 0 ] || fail "steer: one-at-a-time delivered both"
grep -qF '{"type":"message_start","message":{"role":"user","content":[{"type":"text","text":"steer one"}]}}' "$T/ev$n" ||
    fail "steer: no message_start for the steer"
grep -qF '{"type":"queue_update","steering":["steer two"],"followUp":["then this"]}' "$T/ev$n" ||
    fail "steer: no queue_update after delivery"
# The answer ended the request with steer two still queued: it ran next, then the follow-up.
r3="$LOG/3.req"
r4="$LOG/4.req"
[ -e "$r4" ] || fail "steer: steer two and the follow-up did not both run: $(ls "$LOG")"
[ "$(at "$r3" '{"role":"user","content":"steer two"}')" -gt 0 ] || fail "steer: request 3: $(cat "$r3")"
[ "$(at "$r3" 'then this')" = 0 ] || fail "steer: the follow-up ran before the steer"
[ "$(at "$r4" '{"role":"user","content":"then this"}')" -gt 0 ] || fail "steer: request 4: $(cat "$r4")"
[ "$(at "$r4" '{"role":"user","content":"steer one"}')" -gt 0 ] || fail "steer: request 4 lost the conversation"
[ ! -e "$LOG/5.req" ] || fail "steer: an extra request"
grep -qF '{"type":"queue_update","steering":[],"followUp":[]}' "$T/ev$n" || fail "steer: queues never emptied"
[ "$(grep -c '"type":"agent_end"' "$T/ev$n")" = 3 ] || fail "steer: agent_end count: $(grep agent_end "$T/ev$n")"
pic check > /dev/null || fail "steer: integrity"
out=$(pic dump)
[ "$(printf '%s\n' "$out" | grep -c '^submission .* answered ')" = 3 ] || fail "steer: submissions: $(printf '%s\n' "$out" | grep '^submission')"
[ "$(printf '%s\n' "$out" | grep -c '^queued .* delivered entry=')" = 3 ] || fail "steer: queued rows: $(printf '%s\n' "$out" | grep '^queued')"
[ "$(pic log | grep -c 'you: steer one')" = 1 ] || fail "steer: log: $(pic log)"
pic tree --json > "$T/tree" || fail "steer: tree"
[ "$(wc -l < "$T/tree" | tr -d ' ')" = 3 ] || fail "steer: tree rows: $(cat "$T/tree")"
for text in 'steer one' 'steer two' 'then this'; do
    [ "$(grep -cF '{"type":"message_start","message":{"role":"user","content":[{"type":"text","text":"'"$text"'"}]}}' "$T/ev$n")" = 1 ] ||
        fail "steer: message_start count for $text: $(grep -F "$text" "$T/ev$n")"
done
printf 'PASS: a steer reaches the model after the tool result, one at a time, then the follow-up\n'

# A branch forked from that conversation: steering inside a request is not a
# request of the tree, and a fork cannot start at it.
steer_seq=$(pic dump | sed -n 's/^entry \([0-9]*\) 1 user | steer one$/\1/p')
answer_seq=$(pic dump | sed -n 's/^entry \([0-9]*\) 1 answer .*/\1/p')
[ -n "$steer_seq" ] && [ -n "$answer_seq" ] || fail "fork: entries: $(pic dump | grep '^entry')"
conv=$(sed -n 's/.*"conversation":"\([^"]*\)".*/\1/p' "$T/ev$n" | head -1)
if pic fork "$conv" --at "$steer_seq" > /dev/null 2>&1; then fail "fork: at a steering entry"; fi
branch=$(pic fork "$conv" --at "$answer_seq")
pic submit kb 'on the branch' --session "$branch" > /dev/null
pic tree --json "$branch" > "$T/tree"
[ "$(wc -l < "$T/tree" | tr -d ' ')" = 4 ] || fail "fork: tree rows: $(cat "$T/tree")"
grep -q '"text":"on the branch"' "$T/tree" || fail "fork: branch row: $(cat "$T/tree")"
! grep -q '"text":"steer one"' "$T/tree" || fail "fork: a steer as a tree row"
pic check > /dev/null || fail "fork: integrity"
printf 'PASS: fork and tree after a steer inside a request\n'

# pic check holds steering to the journal's rules: a later user entry is a
# delivered message, and it comes after its turn's tool results.
cp "$DB" "$T/bad.sqlite"
sqlite3 "$T/bad.sqlite" "UPDATE pic_queued SET state = 'queued', entry_seq = NULL WHERE text = 'steer one'"
"$PIC" --db "$T/bad.sqlite" --workspace "$WS" check 2>&1 | grep -q 'user entry after the first that is not a delivered message' ||
    fail "check: an undelivered steer entry passed"
cp "$DB" "$T/bad.sqlite"
sqlite3 "$T/bad.sqlite" "UPDATE pic_entry SET body = 'other' WHERE body = 'steer one'"
"$PIC" --db "$T/bad.sqlite" --workspace "$WS" check 2>&1 | grep -q 'delivered message without its user entry' ||
    fail "check: a steer entry with other text passed"
printf 'PASS: pic check rejects steering entries the queue does not account for\n'

# set_steering_mode all: every queued steer at the next turn; templates expanded.
printf 'Check $1 carefully\n' > "$HOME/.pic/prompts/chk.md"
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
start ask 'hold on'
exists "$WS/started"
send '{"type":"set_steering_mode","mode":"all"}'
await "$T/ev$n" '{"type":"response","command":"set_steering_mode","success":true}'
send '{"type":"set_steering_mode","mode":"some"}'
await "$T/ev$n" '{"type":"response","command":"set_steering_mode","success":false,'
send '{"type":"steer","message":"first"}'
send '{"type":"steer","message":"/chk the tests"}'
await "$T/ev$n" '"steering":["first","Check the carefully"]'
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "all: exit $rc: $(cat "$T/err$n")"
r2="$LOG/2.req"
a=$(at "$r2" '{"role":"user","content":"first"}')
b=$(at "$r2" '{"role":"user","content":"Check the carefully"}')
[ "$a" -gt 0 ] && [ "$b" -gt "$a" ] || fail "all: both steers, in order: $(cat "$r2")"
[ ! -e "$LOG/3.req" ] || fail "all: an extra request"
pic check > /dev/null || fail "all: integrity"
printf 'PASS: set_steering_mode all delivers every queued steer; templates are expanded\n'

# clear_queue returns and drops what was queued; nothing more is sent.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
start ask 'hold on'
exists "$WS/started"
send '{"type":"steer","message":"never"}'
send '{"type":"follow_up","message":"nor this"}'
await "$T/ev$n" '"followUp":["nor this"]'
send '{"type":"clear_queue"}'
await "$T/ev$n" '{"type":"response","command":"clear_queue","success":true,"data":{"steering":["never"],"followUp":["nor this"]}}'
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "clear: exit $rc: $(cat "$T/err$n")"
[ "$(at "$LOG/2.req" 'never')" = 0 ] || fail "clear: a cleared steer was sent"
[ ! -e "$LOG/3.req" ] || fail "clear: a cleared follow-up ran"
pic check > /dev/null || fail "clear: integrity"
[ "$(pic dump | grep -c '^queued .* cleared |')" = 2 ] || fail "clear: $(pic dump | grep '^queued')"
printf 'PASS: clear_queue returns the queued text and nothing of it is sent\n'

# abort cancels the request (the command is stopped) and stops, as Pi's
# does; what was queued comes back in queue_returned and never runs. The
# response follows the journaled cancel.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
start ask 'hold on'
exists "$WS/started"
send '{"type":"steer","message":"back one"}'
send '{"type":"follow_up","message":"after abort"}'
await "$T/ev$n" '"followUp":["after abort"]'
send '{"id":"a1","type":"abort"}'
finish
[ "$rc" = 1 ] || fail "abort: exit $rc"
end=$(grep -n '"status":"failed","errorMessage":"cancelled"' "$T/ev$n" | cut -d: -f1)
ret=$(grep -nF '{"type":"queue_returned","steering":["back one"],"followUp":["after abort"]}' "$T/ev$n" | cut -d: -f1)
ack=$(grep -nF '{"id":"a1","type":"response","command":"abort","success":true}' "$T/ev$n" | cut -d: -f1)
[ -n "$end" ] && [ -n "$ret" ] && [ -n "$ack" ] || fail "abort: events: $(cat "$T/ev$n")"
[ "$ret" -lt "$end" ] && [ "$end" -lt "$ack" ] || fail "abort: order returned=$ret end=$end response=$ack"
[ ! -e "$LOG/2.req" ] || fail "abort: the model was asked again"
pic check > /dev/null || fail "abort: integrity"
[ "$(pic dump | grep -c '^queued .* returned |')" = 2 ] || fail "abort: $(pic dump | grep '^queued')"
printf 'PASS: abort cancels, stops, and returns the queue; its response follows the cancel\n'

# A Ctrl-C right after an abort command is still a first Ctrl-C: pic settles and exits.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
start ask 'hold on'
exists "$WS/started"
send '{"type":"abort"}'
kill -INT "$pid"
finish
[ "$rc" = 1 ] || fail "abort+ctrl-c: exit $rc (killed outright?)"
pic check > /dev/null || fail "abort+ctrl-c: integrity"
grep -qF '"status":"failed","errorMessage":"cancelled"' "$T/ev$n" || fail "abort+ctrl-c: not cancelled"
printf 'PASS: Ctrl-C after an abort command does not kill pic outright\n'

# A failed request returns its queue; a later ask in the conversation (no
# --commands) runs none of it.
serve "sse:$S/bash_hold.sse" "status:400:-" "sse:$S/text.sse"
start ask 'hold on'
exists "$WS/started"
send '{"type":"steer","message":"steer a"}'
send '{"type":"steer","message":"steer b"}'
send '{"type":"follow_up","message":"after fail"}'
await "$T/ev$n" '"followUp":["after fail"]'
touch "$WS/release"
finish
[ "$rc" = 1 ] || fail "failure: exit $rc"
grep -qF '{"type":"queue_returned","steering":["steer b"],"followUp":["after fail"]}' "$T/ev$n" ||
    fail "failure: no queue_returned: $(cat "$T/ev$n")"
pic check > /dev/null || fail "failure: integrity"
pic --model fake/m ask -c later > /dev/null 2> "$T/later.err" || fail "failure: later ask: $(cat "$T/later.err")"
[ "$(at "$LOG/3.req" 'later')" -gt 0 ] || fail "failure: later request: $(ls "$LOG")"
[ "$(at "$LOG/3.req" 'steer b')" = 0 ] && [ "$(at "$LOG/3.req" 'after fail')" = 0 ] ||
    fail "failure: returned messages were sent later"
[ "$(pic dump | grep -c '^queued .* returned |')" = 2 ] || fail "failure: $(pic dump | grep '^queued')"
printf 'PASS: a failed request returns its queue, and a later ask runs none of it\n'

# Commands steer the request ask was given, not a leftover in the journal.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse"
pic submit leftover-1 'other work' > /dev/null
start ask 'hold on'
exists "$WS/started"
send '{"type":"steer","message":"routed"}'
await "$T/ev$n" '"steering":["routed"]'
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "routing: exit $rc: $(cat "$T/err$n")"
pic dump | grep -q '^entry [0-9]* 2 user | routed$' || fail "routing: $(pic dump | grep -E '^(entry|submission)')"
# The leftover is another conversation's: ask leaves it to that conversation
# (pic tui -c offers it); a plain pic run finishes it.
pic dump | grep -q '^submission 1 leftover-1 admitted' || fail "routing: ask touched the leftover"
pic --model fake/m run > /dev/null 2>&1 || fail "routing: run"
pic dump | grep -q '^submission 1 leftover-1 answered' || fail "routing: the leftover did not run after"
pic check > /dev/null || fail "routing: integrity"
printf 'PASS: a steer goes to the request ask runs; older leftovers are left to pic run\n'

# A retried generation delivers nothing more: one steer per turn.
serve "sse:$S/bash_hold.sse" "cut:$S/text.sse:300" "sse:$S/text.sse"
start ask 'hold on'
exists "$WS/started"
send '{"type":"steer","message":"steer one"}'
send '{"type":"steer","message":"steer two"}'
await "$T/ev$n" '"steering":["steer one","steer two"]'
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "retry: exit $rc: $(cat "$T/err$n")"
grep -q '"type":"auto_retry_start"' "$T/ev$n" || fail "retry: no retry"
[ "$(grep -o 'steer one' "$LOG/3.req" | wc -l | tr -d ' ')" = 1 ] || fail "retry: request 3: $(cat "$LOG/3.req")"
[ "$(at "$LOG/3.req" 'steer two')" = 0 ] || fail "retry: the retry delivered the second steer"
[ "$(at "$LOG/4.req" '{"role":"user","content":"steer two"}')" -gt 0 ] || fail "retry: steer two never ran"
pic check > /dev/null || fail "retry: integrity"
printf 'PASS: a retried generation delivers no further steering\n'

# Across a compaction: the turn's steer goes before it, and the poll after it
# delivers nothing more that turn (Pi polls again only when the first found
# nothing). Scripted provider; the large outputs push past the window.
n=$((n + 1))
DB="$T/j$n.sqlite"
WS="$T/ws$n"
mkdir "$WS"
HOLD='i=0; while [ ! -e release ] && [ $i -lt 600 ]; do sleep 0.05; i=$((i + 1)); done'
printf 'tool exec touch started; %s\ntool bash head -c 40000 /dev/zero | tr "\\0" x\ntool bash head -c 40000 /dev/zero | tr "\\0" y\ntext done\n' \
    "$HOLD" > "$T/compact.script"
pic submit k1 'go' > /dev/null
rm -f "$T/in"
mkfifo "$T/in"
"$PIC" --db "$DB" --workspace "$WS" --context-window 30000 --json --commands run --script "$T/compact.script" \
    < "$T/in" > "$T/ev$n" 2> "$T/err$n" &
pid=$!
exec 3> "$T/in"
exists "$WS/started"
for i in 1 2 3 4; do send '{"type":"steer","message":"c'"$i"'"}'; done
await "$T/ev$n" '"steering":["c1","c2","c3","c4"]'
touch "$WS/release"
finish
[ "$rc" = 0 ] || fail "compaction: exit $rc: $(cat "$T/err$n")"
pic check > /dev/null || fail "compaction: integrity"
pic dump > "$T/dump$n"
c3=$(sed -n 's/^entry \([0-9]*\) 1 user | c3$/\1/p' "$T/dump$n")
cs=$(sed -n 's/^entry \([0-9]*\) 1 compaction .*/\1/p' "$T/dump$n" | head -1)
an=$(sed -n 's/^entry \([0-9]*\) 1 answer .*/\1/p' "$T/dump$n")
[ -n "$c3" ] && [ -n "$cs" ] && [ -n "$an" ] && [ "$c3" -lt "$cs" ] && [ "$cs" -lt "$an" ] ||
    fail "compaction: c3=$c3 compaction=$cs answer=$an: $(grep '^entry' "$T/dump$n" | cut -c1-60)"
[ "$(grep -c ' 1 user | c4$' "$T/dump$n")" = 0 ] || fail "compaction: c4 delivered after the compaction"
grep -q '^entry [0-9]* 2 user | c4$' "$T/dump$n" || fail "compaction: c4 not the next request"
printf 'PASS: steering across a compaction: before it, and no second delivery after it\n'

# Without --json there is no command channel.
if "$PIC" --db "$DB" --workspace "$WS" --commands ask x < /dev/null > /dev/null 2>&1; then fail "--commands without --json accepted"; fi
printf 'PASS: --commands needs --json\n'