#!/bin/sh
# Asks (docs/dev/asks.md): a question a conversation waits on a person for is a pic_ask row that any
# client answers once. A loop or goal the model asked for is one, and its answer is the wake's
# decision; a stopped one withdraws it. A run waiting on an ask sees the answer; a second answer is
# refused with the first; a crash on either side of the answer's commit answers once; a run killed
# while it waits leaves the question open, and the next owner finds the answer. pic --mode rpc
# answers with answer_ask or Pi's extension_ui_response. Usage: test/pic/ask.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-ask.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
    rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export ANTHROPIC_API_KEY=pic-ask-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))"
    [ -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> /dev/null)" = "$2" ]; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for [$1] = $2: $(q "$1")"
        sleep 0.05
    done
}
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'
}
ask_state() { q "SELECT state || '|' || coalesce(answer, '') || '|' || coalesce(answered_by, '') FROM pic_ask WHERE id = $1"; }

# A loop the model asks for is an ask: listed by pic answer with its loop, answered once; the
# answer is the loop's decision, and a second answer is refused with the first.
tool_sse wake '{"action":"loop","prompt":"look again","every":"5m"}' > "$T/loop.sse"
tool_sse wake '{"action":"goal","condition":"it is green"}' > "$T/goal.sse"
serve "sse:$T/loop.sse" "sse:$S/text.sse" "sse:$T/goal.sse" "sse:$S/text.sse" "sse:$T/loop.sse" "sse:$S/text.sse"
pic ask 'watch it' > /dev/null 2> "$T/err" || fail "wake: $(cat "$T/err")"
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
[ "$(q "SELECT ask_key, session_id = '$SID', kind, title, body, state FROM pic_ask")" = "wake:1|1|confirm|Start loop L1, every 5m?|look again|open" ] ||
    fail "wake: the ask: $(q 'SELECT * FROM pic_ask')"
pic answer > "$T/list" || fail "wake: list"
grep -qF "1  $SID  confirm  Start loop L1, every 5m?" "$T/list" || fail "wake: list: $(cat "$T/list")"
[ "$(pic answer --json | "$SQLITE3" :memory: "SELECT json_extract(readfile('/dev/stdin'), '\$[0].wake')")" = L1 ] || fail "wake: list --json: $(pic answer --json)"
if pic answer 1 '"maybe"' 2> "$T/err"; then fail "wake: a text answer to a confirm"; fi
grep -qF 'a confirm is answered true or false' "$T/err" || fail "wake: refused: $(cat "$T/err")"
[ "$(pic answer 1 true)" = "answered 1" ] || fail "wake: answer"
[ "$(ask_state 1)" = "answered|true|cli" ] || fail "wake: answered: $(ask_state 1)"
[ "$(q "SELECT state, json_extract(options, '\$.approval') FROM pic_wake WHERE id = 1")" = "active|approved" ] || fail "wake: not approved: $(q 'SELECT state, options FROM pic_wake')"
[ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key = 'approval:1'")" = 1 ] || fail "wake: the model's message"
[ "$(pic answer 1 true)" = "answered 1" ] || fail "wake: the same answer again"
if pic answer 1 false 2> "$T/err"; then fail "wake: a second answer"; fi
grep -qF '"state":"answered","value":true,"answeredBy":"cli"' "$T/err" || fail "wake: second: $(cat "$T/err")"
[ "$(q "SELECT state FROM pic_wake WHERE id = 1")" = active ] || fail "wake: the second answer changed it"
[ -z "$(pic answer)" ] || fail "wake: still listed: $(pic answer)"
pic loop stop L1 > /dev/null
# pic loop decline is an answer too, and closes the ask; a stopped loop withdraws its ask
pic ask --session "$SID" 'and a goal' > /dev/null 2> "$T/err" || fail "wake: goal: $(cat "$T/err")"
[ "$(q "SELECT title FROM pic_ask WHERE id = 2")" = "Start goal G2?" ] || fail "wake: goal's ask: $(q 'SELECT * FROM pic_ask')"
[ "$(pic loop decline G2)" = "declined G2" ] || fail "wake: decline"
[ "$(ask_state 2)" = "answered|false|cli" ] || fail "wake: declined: $(ask_state 2)"
pic ask --session "$SID" 'once more' > /dev/null 2> "$T/err" || fail "wake: third: $(cat "$T/err")"
pic loop stop L3 > /dev/null
[ "$(ask_state 3)" = "withdrawn||" ] || fail "wake: stopped: $(ask_state 3)"
if pic answer 3 true 2> "$T/err"; then fail "wake: answered a withdrawn ask"; fi
grep -qF '"state":"withdrawn"' "$T/err" || fail "wake: withdrawn: $(cat "$T/err")"
pic check > /dev/null || fail "wake: integrity"
printf 'PASS: a loop or goal the model asks for is an ask, answered once by any client; a stopped one is withdrawn\n'

# pic --mode rpc lists and answers: get_asks, answer_ask, and Pi's extension_ui_response.
serve "sse:$T/loop.sse" "sse:$S/text.sse" "sse:$T/loop.sse" "sse:$S/text.sse"
pic ask 'watch it' > /dev/null 2> "$T/err" || fail "rpc: $(cat "$T/err")"
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
pic ask --session "$SID" 'and again' > /dev/null 2> "$T/err" || fail "rpc: $(cat "$T/err")"
printf '{"id":"a","type":"get_asks"}\n{"id":"b","type":"answer_ask","ask":1,"value":true}\n{"type":"extension_ui_response","id":"2","confirmed":false}\n{"id":"d","type":"answer_ask","ask":2,"value":true}\n' |
    pic --mode rpc --session "$SID" > "$T/rpc.out" 2> "$T/err" || fail "rpc: $(cat "$T/err")"
grep -F '"command":"get_asks"' "$T/rpc.out" | grep -qF '"title":"Start loop L1, every 5m?"' || fail "rpc: get_asks: $(cat "$T/rpc.out")"
grep -F '"command":"answer_ask"' "$T/rpc.out" | head -1 | grep -qF '"state":"answered"' || fail "rpc: answer_ask: $(cat "$T/rpc.out")"
grep -F '"command":"extension_ui_response"' "$T/rpc.out" | grep -qF '"success":true' || fail "rpc: extension_ui_response: $(cat "$T/rpc.out")"
grep -F '"command":"answer_ask"' "$T/rpc.out" | tail -1 | grep -qF '"state":"already_answered"' || fail "rpc: second answer: $(cat "$T/rpc.out")"
[ "$(ask_state 1)|$(ask_state 2)" = "answered|true|user|answered|false|user" ] || fail "rpc: rows: $(ask_state 1) $(ask_state 2)"
printf 'PASS: pic --mode rpc lists asks and answers them, with answer_ask and extension_ui_response\n'

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

# A run waiting on an ask sees its answer: a select's option, refused when it is not one.
tool_sse ask_person '{"kind":"select","title":"Which branch?","options":["main","dev"]}' > "$T/select.sse"
serve "sse:$T/select.sse" "sse:$S/text.sse"
"$PIC" --db "$DB" --workspace "$WS" ask 'pick one' > "$T/out" 2> "$T/err" &
pid=$!
until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
[ "$(q "SELECT kind, title, json_extract(spec, '\$.options') FROM pic_ask")" = 'select|Which branch?|["main","dev"]' ] || fail "select: $(q 'SELECT * FROM pic_ask')"
if pic answer 1 other 2> "$T/err2"; then fail "select: not an option"; fi
grep -qF 'one of its options' "$T/err2" || fail "select: refused: $(cat "$T/err2")"
SID=$(q "SELECT session_id FROM pic_ask")
pic attach --session "$SID" --no-follow --format json > "$T/attach.out" 2> "$T/err2" || fail "select: attach: $(cat "$T/err2")"
grep -qF '{"type":"extension_ui_request","id":"1","method":"select","title":"Which branch?","options":["main","dev"],' "$T/attach.out" ||
    fail "select: attach shows: $(cat "$T/attach.out")"
printf '{"type":"extension_ui_response","id":"1","value":"dev"}\n' | pic attach -i --session "$SID" --format json > /dev/null 2> "$T/err2" ||
    fail "select: attach -i: $(cat "$T/err2")"
[ "$(ask_state 1)" = 'answered|"dev"|attach' ] || fail "select: answered from attach: $(ask_state 1) $(cat "$T/err2")"
wait "$pid" || fail "select: the run: $(cat "$T/err")"
pid=
[ "$(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")" = 'answered: "dev"' ] || fail "select: the run saw: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")"
pic check > /dev/null || fail "select: integrity"
printf 'PASS: a run waiting on an ask sees the answer given in pic attach, and an answer that is not one is refused\n'

# A crash on either side of the answer's commit: before, the ask is still open and the run still
# waits; after, it is answered once and the run sees it. A second answer is refused either way.
tool_sse ask_person '{"kind":"input","title":"Name it","placeholder":"a name"}' > "$T/input.sse"
for at in 1 2; do
    serve "sse:$T/input.sse" "sse:$S/text.sse"
    "$PIC" --db "$DB" --workspace "$WS" ask 'name it' > "$T/out" 2> "$T/err" &
    pid=$!
    until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
    rc=0
    env PIC_CRASH_AT="ask_answer:$at" "$PIC" --db "$DB" --workspace "$WS" answer 1 first > /dev/null 2>&1 || rc=$?
    [ "$rc" = 77 ] || fail "crash $at: exit $rc"
    if [ "$at" = 1 ]; then
        [ "$(ask_state 1)" = "open||" ] || fail "crash 1: $(ask_state 1)"
        kill -0 "$pid" 2> /dev/null || fail "crash 1: the run stopped waiting"
        [ "$(pic answer 1 second)" = "answered 1" ] || fail "crash 1: answer again"
        want='answered: "second"'
    else
        [ "$(ask_state 1)" = 'answered|"first"|cli' ] || fail "crash 2: $(ask_state 1)"
        want='answered: "first"'
        if pic answer 1 second 2> /dev/null; then fail "crash 2: a second answer"; fi
    fi
    wait "$pid" || fail "crash $at: the run: $(cat "$T/err")"
    pid=
    [ "$(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")" = "$want" ] || fail "crash $at: the run saw: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")"
    pic check > /dev/null || fail "crash $at: integrity"
done
printf 'PASS: a crash at the answer answers once, and the waiting run sees the one answer\n'

# A run killed while it waits leaves the question open; answered meanwhile, the next owner of the
# request finds the same ask answered and goes on with it.
tool_sse ask_person '{"kind":"confirm","title":"Go on?"}' > "$T/confirm.sse"
serve "sse:$T/confirm.sse" "sse:$S/text.sse"
"$PIC" --db "$DB" --workspace "$WS" ask 'go' > "$T/out" 2> "$T/err" &
pid=$!
until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
kill -9 "$pid"
wait "$pid" 2> /dev/null || true
pid=
[ "$(ask_state 1)" = "open||" ] || fail "kill: the ask closed: $(ask_state 1)"
pic answer > "$T/list"
grep -qF "1  $SID  confirm  Go on?" "$T/list" || fail "kill: not listed: $(cat "$T/list")"
[ "$(pic answer 1 true)" = "answered 1" ] || fail "kill: answer"
pic run --session "$SID" > /dev/null 2> "$T/err" || fail "kill: resume: $(cat "$T/err")"
[ "$(q "SELECT count(*) FROM pic_ask")" = 1 ] || fail "kill: asked twice: $(q 'SELECT * FROM pic_ask')"
[ "$(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")" = 'answered: true' ] || fail "kill: the run saw: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")"
[ "$(q "SELECT status FROM pic_submission ORDER BY id DESC LIMIT 1")" = answered ] || fail "kill: the request"
pic check > /dev/null || fail "kill: integrity"
printf 'PASS: a run killed while it waits leaves the question open, and the next owner finds the answer\n'
printf 'PASS: ask\n'
