Skip to content
pi-c Artifact [f989a3cfb6]
Login

Artifact [f989a3cfb6]

Artifact f989a3cfb651922001995e9dfdf4baeb1fcf65ea1c9a706c35c82bde297fb0b0:


#!/bin/sh
# Goals and the wake tool (docs/design/wakes.md): a goal runs in rounds, each a request; when one
# ends, its check runs once (journaled like a verdict) and the stop policy says done, continue or
# needs; core enforces the rounds and stalls. A check that passes ends it; rounds that make no
# progress stop at 3; --rounds caps them; without a check the model's goal_done ends it; a check
# cut off by a crash is never run again and counts as a stall. The model's wake tool starts a
# monitor freely and a loop or goal only once the user agreed. Usage: test/pic/goal.sh [--no-faults]
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
FAULTS=1
[ "${1:-}" = --no-faults ] && FAULTS=0
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-goal.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME/.pic"
"$PIC" settings cacheRetention none > /dev/null
"$PIC" settings defaultModel fake/m > /dev/null
spid=
pid=
cleanup() {
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    [ -n "$pid" ] && kill -9 "$pid" 2>/dev/null
    # every monitor's command still running, by the process group its row records, so a failed
    # case leaves none behind
    for j in "$T"/j*.sqlite; do
        [ -e "$j" ] || continue
        for g in $("${SQLITE3:-sqlite3}" "$j" "SELECT pid FROM pic_wake WHERE pid > 0" 2> /dev/null); do
            ps -o command= -p "$g" 2> /dev/null | grep -qF '.pid"; (eval' && kill -TERM -- "-$g" 2> /dev/null
        done
    done
    rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export ANTHROPIC_API_KEY=pic-goal-test-key PIC_PI_EXPORT=0
SQLITE3=${SQLITE3:-sqlite3}
n=0
serve() { # SPEC...: a fresh server, journal and workspace
    mkdir "$T/ws$((n + 1))"
    DB="$T/j$((n + 1)).sqlite"
    WS="$T/ws$((n + 1))"
    reserve "$@"
}
reserve() { # SPEC...: a fresh server for the same journal and workspace
    [ -n "$spid" ] && kill "$spid" 2>/dev/null
    n=$((n + 1))
    mkdir "$T/log$n"
    LOG="$T/log$n"
    "$SERVER" "$T/port$n" "$LOG" 90 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port$n" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "server did not start"
        sleep 0.05
    done
    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" "$@"; }
q() { "$SQLITE3" -cmd ".timeout 10000" "$DB" "$1"; }
until_sql() { # SQL VALUE: wait up to 30s for the query to print VALUE
    i=0
    until [ "$(q "$1")" = "$2" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for [$1] = $2: $(q "$1")"
        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"
        sleep 0.05
    done
}
reqs() { ls "$LOG" | grep -c '\.req$' || true; }
idle() { # wait until no pic works the conversation SID (the started run has exited)
    i=0
    while [ "$(q "SELECT count(*) FROM pic_submission WHERE session_id = '$SID' AND status = 'admitted'")" != 0 ] ||
        [ "$(q "SELECT count(*) FROM pic_inbox WHERE session_id = '$SID' AND state = 'pending'")" != 0 ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for $SID to go idle"
        sleep 0.05
    done
    sleep 0.3 # the run lets the lease go as it exits
}
T0=1800000000000
when() { # MINUTES COMMAND...: COMMAND with the wake clock at T0 plus MINUTES (dev builds read PIC_WAKE_NOW_MS)
    m=$1
    shift
    env PIC_WAKE_NOW_MS=$((T0 + m * 60000)) "$@"
}

# A loop in a conversation: created due now; pic loop fire fires it once and starts a pic run,
# which takes it up as a request keyed inbox:wake:1:1 with the loop's frame and prompt.
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse"
pic ask 'hello' > /dev/null 2> "$T/err" || fail "setup: $(cat "$T/err")"
tool_sse() { # NAME JSON: a reply that calls tool NAME with input JSON
    esc=$(printf '%s' "$2" | sed 's/\\/\\\\/g; s/"/\\"/g')
    printf 'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_01","type":"message","role":"assistant","model":"m","content":[],"stop_reason":null,"usage":{"input_tokens":25,"output_tokens":1}}}\n\n'
    printf 'event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_g","name":"%s","input":{}}}\n\n' "$1"
    printf 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"%s"}}\n\n' "$esc"
    printf 'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n'
    printf 'event: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":40}}\n\n'
    printf 'event: message_stop\ndata: {"type":"message_stop"}\n\n'
}
newconv() { # a conversation with one answered request: SID
    pic ask 'hello' > /dev/null 2> "$T/err" || fail "setup: $(cat "$T/err")"
    SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
}
gstate() { q "SELECT state || '|' || coalesce(why, '') || '|' || fires FROM pic_wake WHERE kind = 'goal'"; }
until_goal() { # STATE: wait for the goal to leave active as STATE
    i=0
    until [ "$(q "SELECT state FROM pic_wake WHERE kind = 'goal'")" = "$1" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for the goal to be $1: $(gstate)"
        sleep 0.05
    done
}

# A check that passes after the first round ends the goal: one round, one check.
serve "sse:$S/text.sse"
newconv
touch "$WS/ok"
out=$(pic goal --session "$SID" --check "echo ran >> '$T/ledger1'; test -e ok" the build is green) || fail "met: create: $out"
case "$out" in "goal G1 in conversation $SID: round 1 now; met when its check exits 0"*) ;; *) fail "met: printed $out" ;; esac
[ "$(pic loop fire)" = "1 fired" ] || fail "met: round 1 not fired"
until_goal ended
idle
[ "$(gstate)" = 'ended|met: `echo ran >> '"'$T/ledger1'"'; test -e ok` passed|1' ] || fail "met: $(gstate)"
[ "$(wc -l < "$T/ledger1" | tr -d ' ')" = 1 ] || fail "met: check ran $(wc -l < "$T/ledger1") times"
grep -qF 'the build is green\n\n[Goal G1, round 1 of 50: keep working until this is true' "$LOG/2.req" || fail "met: round 1: $(cat "$LOG/2.req")"
[ "$(q "SELECT count(*) FROM pic_hook_run WHERE event = 'GoalCheck' AND state = 'done' AND exit_code = 0")" = 1 ] || fail "met: check row"
[ "$(q "SELECT json_extract(context, '\$.goal') FROM pic_hook_run WHERE event = 'StopPolicy'")" = done ] || fail "met: answer"
pic check > /dev/null || fail "met: integrity"
printf 'PASS: a goal whose check passes ends after its round, the check run once\n'

# A check that keeps failing, with rounds that change nothing: three stalls, three rounds in one
# run, each round told what the check said; then the goal needs the person.
serve "sse:$S/text.sse"
newconv
pic goal --session "$SID" --check "echo ran >> '$T/ledger2'; echo 2 of 14 suites fail; exit 1" every suite passes > /dev/null || fail "stall: create"
pic loop fire > /dev/null
until_goal needs
idle
[ "$(gstate)" = "needs|3 rounds in a row made no progress|3" ] || fail "stall: $(gstate)"
[ "$(wc -l < "$T/ledger2" | tr -d ' ')" = 3 ] || fail "stall: check ran $(wc -l < "$T/ledger2") times"
[ "$(reqs)" = 4 ] || fail "stall: $(reqs) requests"
grep -qF '[Goal G1, round 2 of 50: keep working until this is true; the user set this goal, this was not typed just now. pic ran `' "$LOG/3.req" ||
    fail "stall: round 2: $(cat "$LOG/3.req")"
grep -qF 'after the last round: it exited 1.' "$LOG/3.req" && grep -qF 'Its output ended:\n2 of 14 suites fail' "$LOG/3.req" || fail "stall: the check's words: $(cat "$LOG/3.req")"
[ "$(q "SELECT count(*) FROM pic_submission WHERE request_key LIKE 'inbox:wake:1:%'")" = 3 ] || fail "stall: rounds were not requests of their own"
pic check > /dev/null || fail "stall: integrity"
printf 'PASS: rounds that make no progress stop at three, each told what the check said\n'

# Rounds that do something are not stalls; --rounds 2 caps them.
tool_sse bash '{"command":"echo more >> progress"}' > "$T/work.sse"
serve "sse:$T/work.sse" "sse:$S/text.sse" "sse:$T/work.sse" "sse:$S/text.sse" "sse:$T/work.sse" "sse:$S/text.sse"
pic ask 'hello' > /dev/null 2> "$T/err" || :
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
pic goal --session "$SID" --rounds 2 --check 'exit 1' cap me > /dev/null || fail "rounds: create"
pic loop fire > /dev/null
until_goal needs
idle
[ "$(gstate)" = "needs|reached 2 rounds; the goal is not met yet|2" ] || fail "rounds: $(gstate)"
[ "$(q "SELECT stalls FROM pic_wake WHERE kind = 'goal'")" = 0 ] || fail "rounds: a working round counted as a stall"
pic loop resume G1 > /dev/null || fail "rounds: resume"
[ "$(q "SELECT max_rounds, stalls, due_ms IS NOT NULL FROM pic_wake WHERE kind = 'goal'")" = "12|0|1" ] || fail "rounds: resume: $(q 'SELECT max_rounds, stalls, due_ms FROM pic_wake')"
pic loop stop G1 > /dev/null
printf 'PASS: rounds that work are not stalls; --rounds caps them; resuming gives ten more\n'

# No check: the model's goal_done ends it, said to be declared, not checked.
tool_sse wake '{"action":"goal_done","reason":"all green now"}' > "$T/done.sse"
serve "sse:$S/text.sse" "sse:$T/done.sse" "sse:$S/text.sse"
newconv
pic goal --session "$SID" the docs are rewritten > /dev/null || fail "declared: create"
pic loop fire > /dev/null
until_goal ended
idle
[ "$(gstate)" = "ended|declared done, not checked: all green now|1" ] || fail "declared: $(gstate)"
grep -qF 'When it is met, call the wake tool with action goal_done and say why' "$LOG/2.req" || fail "declared: round 1: $(cat "$LOG/2.req")"
printf 'PASS: without a check, the model'"'"'s goal_done ends the goal, declared, not checked\n'

# The wake tool: a loop is refused until the user agreed; a monitor needs no question.
tool_sse wake '{"action":"loop","prompt":"look again","every":"5m"}' > "$T/ask.sse"
tool_sse wake '{"action":"loop","prompt":"look again","every":"5m","user_agreed":true}' > "$T/agreed.sse"
tool_sse wake '{"action":"monitor","command":"exec sleep 600"}' > "$T/mon.sse"
serve "sse:$T/ask.sse" "sse:$S/text.sse" "sse:$T/agreed.sse" "sse:$S/text.sse" "sse:$T/mon.sse" "sse:$S/text.sse"
pic ask 'watch it' > /dev/null 2> "$T/err" || fail "tool: $(cat "$T/err")"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1" | grep -qF 'Not started: ask the user in this conversation first' ||
    fail "tool: not refused: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1")"
[ "$(q "SELECT count(*) FROM pic_wake")" = 0 ] || fail "tool: made one"
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
pic ask --session "$SID" 'yes, do' > /dev/null 2> "$T/err" || fail "tool: agreed: $(cat "$T/err")"
[ "$(q "SELECT kind, creator, every_ms FROM pic_wake WHERE id = 1")" = "loop|model|300000" ] || fail "tool: agreed: $(q 'SELECT kind, creator, every_ms FROM pic_wake')"
# the loop's first run (a follow-up in the same pic) asks for a monitor, which needs no question
[ "$(q "SELECT kind, creator FROM pic_wake WHERE id = 2")" = "monitor|model" ] || fail "tool: monitor: $(q 'SELECT kind, creator FROM pic_wake')"
pic loop stop L1 > /dev/null
pic loop stop M2 > /dev/null
pic check > /dev/null || fail "tool: integrity"
printf 'PASS: the wake tool starts a loop only once the user agreed, and a monitor without asking\n'

[ "$FAULTS" = 1 ] || { printf 'PASS: goal (release: the fault points are dev-only)\n'; exit 0; }

# A crash once the check is journaled as started: it is interrupted, never run again, counts as a stall; the next
# pic goes on with the next round.
serve "sse:$S/text.sse"
newconv
pic goal --session "$SID" --rounds 2 --check "echo ran >> '$T/ledger3'; exit 1" crash in the check > /dev/null || fail "crash: create"
env PIC_CRASH_AT=after-goal-check-started:1 "$PIC" --db "$DB" --workspace "$WS" loop fire > /dev/null 2>&1 || fail "crash: fire"
until_sql "SELECT count(*) FROM pic_hook_run WHERE event = 'GoalCheck'" 1 # the started run crashes as the check starts
i=0
until [ "$("$PIC" --db "$DB" --workspace "$WS" sessions 2> /dev/null | grep -c running)" = 0 ]; do
    i=$((i + 1)); [ "$i" -lt 600 ] || fail "crash: the run did not end"; sleep 0.05
done
sleep 0.3
[ ! -e "$T/ledger3" ] || fail "crash: the check ran before the crash point"
[ "$(q "SELECT status FROM pic_submission WHERE request_key = 'inbox:wake:1:1'")" = admitted ] || fail "crash: the round"
pic run --session "$SID" > /dev/null 2> "$T/err" || fail "crash: resume: $(cat "$T/err")"
until_goal needs
[ "$(q "SELECT state, error FROM pic_hook_run WHERE event = 'GoalCheck' ORDER BY id LIMIT 1")" = "interrupted|interrupted before its outcome was recorded; not run again" ] ||
    fail "crash: the first check: $(q "SELECT state, error FROM pic_hook_run WHERE event = 'GoalCheck'")"
[ "$(wc -l < "$T/ledger3" | tr -d ' ')" = 1 ] || fail "crash: check ran $(wc -l < "$T/ledger3") times (only for round 2)"
[ "$(q "SELECT json_extract(context, '\$.stall') FROM pic_hook_run WHERE event = 'StopPolicy' ORDER BY id LIMIT 1")" = 1 ] || fail "crash: not a stall"
grep -qF 'it was interrupted, so its result is unknown.' "$LOG/3.req" || fail "crash: round 2 was not told"
pic check > /dev/null || fail "crash: integrity"
printf 'PASS: a check cut off by a crash is never run again, counts as a stall, and the goal goes on\n'
printf 'PASS: goal\n'