#!/bin/sh
# Monitors (docs/design/wakes.md): a monitor's command runs detached, writing to its spool; each
# look reads past the journaled offset and fires its new whole lines, the offset advancing in the
# fire's transaction, so no line is sent twice; lines that came together go in one fire, at most
# 8 KB of the newest with a count of the rest; a command that exits ends the monitor with one last
# fire (--done: only that one, with its status); stop ends the command; --restart starts again a
# command that died with no status; the command holds no lease of its starter's. A crash after the
# command started and before its process was recorded adopts it; a crash on either side of a fire's
# commit sends its lines once. Usage: test/pic/monitor.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-monitor.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-monitor-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")"
alive() { kill -0 "$1" 2> /dev/null; }
mpid() { q "SELECT pid FROM pic_wake WHERE id = $1"; }
waitgone() { # PID: wait up to 30s for it to exit
    i=0
    while alive "$1"; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for process $1 to end"
        sleep 0.05
    done
}
fired_once() { # TEXT: the provider saw TEXT in exactly one request
    [ "$(grep -lF -- "$1" "$LOG"/*.req 2> /dev/null | wc -l | tr -d ' ')" = 1 ] ||
        fail "the provider saw [$1] in $(grep -lF -- "$1" "$LOG"/*.req 2> /dev/null | wc -l) requests"
}

# A monitor on a growing file: its command runs detached; new lines fire, together, once; the
# offset is the spool's end; a line still being written waits; stop ends the command.
serve "sse:$S/text.sse"
pic ask 'hello' > /dev/null 2> "$T/err" || fail "setup: $(cat "$T/err")"
SID=$(q "SELECT id FROM pic_session")
: > "$WS/app.log"
out=$(pic monitor --session "$SID" "tail -n 0 -f '$WS/app.log' | grep --line-buffered ERROR") || fail "create: $out"
case "$out" in "monitor M1 in conversation $SID: each new line"*) ;; *) fail "create: printed $out" ;; esac
P1=$(mpid 1)
[ -n "$P1" ] && alive "$P1" || fail "create: no command running ($(q 'SELECT pid, spool FROM pic_wake'))"
SPOOL=$(q "SELECT spool FROM pic_wake WHERE id = 1")
case "$SPOOL" in */"$(basename "$DB")".pic-monitors/1.log) ;; *) fail "spool: $SPOOL" ;; esac
[ "$(pic loop fire)" = "0 fired" ] || fail "nothing new fired"
printf 'ok line\nERROR one\nERROR two\n' >> "$WS/app.log"
i=0; until [ "$(wc -l < "$SPOOL" | tr -d ' ')" = 2 ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "spool: $(cat "$SPOOL")"; sleep 0.05; done
[ "$(pic loop fire)" = "1 fired" ] || fail "lines: not fired"
until_sql "SELECT status FROM pic_submission WHERE request_key = 'inbox:wake:1:1'" answered
idle
grep -qF 'ERROR one\nERROR two\n\n[Monitor M1 (`tail -n 0 -f' "$LOG/2.req" || fail "lines: request $(cat "$LOG/2.req")"
[ "$(q "SELECT read_offset = $(wc -c < "$SPOOL" | tr -d ' ') FROM pic_wake")" = 1 ] || fail "lines: offset"
[ "$(pic loop fire)" = "0 fired" ] || fail "lines: fired twice"
printf 'ERROR thr' >> "$SPOOL" # a line still being written (straight into the spool)
[ "$(pic loop fire)" = "0 fired" ] || fail "partial: fired a half line"
printf 'ee\n' >> "$SPOOL"
[ "$(pic loop fire)" = "1 fired" ] || fail "partial: not fired once whole"
until_sql "SELECT status FROM pic_submission WHERE request_key = 'inbox:wake:1:2'" answered
idle
fired_once 'ERROR three'
pic loop | grep -qE '^M1 +every line +watching' || fail "list: $(pic loop)"
pic loop stop M1 > /dev/null || fail "stop"
waitgone "$P1"
pic check > /dev/null || fail "lines: integrity"
printf 'PASS: a monitor fires its new whole lines once, together; stop ends its command\n'

# More than 8 KB at once: the newest 8 KB from a line's start, with a count of the lines left out
# and the spool named.
serve "sse:$S/text.sse"
pic ask 'hello' > /dev/null 2> "$T/err" || fail "big: setup"
SID=$(q "SELECT id FROM pic_session")
pic monitor --session "$SID" 'while [ ! -e go ]; do sleep 0.05; done; i=0; while [ $i -lt 2000 ]; do echo "line $i of the flood"; i=$((i + 1)); done; exec sleep 600' > /dev/null || fail "big: create"
touch "$WS/go"
SPOOL=$(q "SELECT spool FROM pic_wake")
i=0; until [ "$(wc -l < "$SPOOL" | tr -d ' ')" = 2000 ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "big: spool"; sleep 0.05; done
[ "$(pic loop fire)" = "1 fired" ] || fail "big: not fired"
until_sql "SELECT status FROM pic_submission WHERE request_key = 'inbox:wake:1:1'" answered
idle
grep -qF 'line 1999 of the flood' "$LOG/2.req" || fail "big: the newest line is missing"
grep -qF 'line 10 of the flood' "$LOG/2.req" && fail "big: an old line was sent"
grep -qE '[0-9]+ earlier lines were left out; all of it is in [^ ]*pic-monitors/1.log' "$LOG/2.req" || fail "big: no count"
pic loop stop M1 > /dev/null
pic check > /dev/null || fail "big: integrity"
printf 'PASS: a flood sends its newest 8 KB and says how much was left out\n'

# A command that exits: one last fire with what it wrote and its status, and the monitor ends.
# --done: nothing until then.
serve "sse:$S/text.sse"
pic ask 'hello' > /dev/null 2> "$T/err" || fail "done: setup"
SID=$(q "SELECT id FROM pic_session")
pic monitor --session "$SID" --done 'echo compiling; while [ ! -e built ]; do sleep 0.05; done; echo built with 2 warnings; exit 3' > /dev/null || fail "done: create"
SPOOL=$(q "SELECT spool FROM pic_wake")
i=0; until grep -q compiling "$SPOOL" 2> /dev/null; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "done: spool"; sleep 0.05; done
[ "$(pic loop fire)" = "0 fired" ] || fail "done: fired before the command ended"
touch "$WS/built"
waitgone "$(mpid 1)"
[ "$(pic loop fire)" = "1 fired" ] || fail "done: not fired at the end"
until_sql "SELECT status FROM pic_submission WHERE request_key = 'inbox:wake:1:1'" answered
idle
grep -qF 'compiling\nbuilt with 2 warnings\n\n[Monitor M1 (`echo compiling;' "$LOG/2.req" || fail "done: request $(cat "$LOG/2.req")"
grep -qF 'its command has ended, sent by a monitor the user set up, not typed just now. Its command exited with status 3; the monitor has ended.]' "$LOG/2.req" ||
    fail "done: status: $(cat "$LOG/2.req")"
[ "$(q "SELECT state, why, exit_code FROM pic_wake")" = "ended|its command exited with status 3|3" ] || fail "done: row $(q 'SELECT state, why, exit_code FROM pic_wake')"
[ "$(pic loop fire)" = "0 fired" ] || fail "done: fired after it ended"
pic check > /dev/null || fail "done: integrity"
printf 'PASS: a command that exits ends its monitor with one last fire and its status; --done waits for it\n'

# A command killed (no status, as when the computer goes down): the monitor ends, saying so; with
# --restart it is started again instead. The ledger counts the starts.
serve "sse:$S/text.sse"
pic ask 'hello' > /dev/null 2> "$T/err" || fail "gone: setup"
SID=$(q "SELECT id FROM pic_session")
pic monitor --session "$SID" "echo start >> '$T/ledger'; exec sleep 600" > /dev/null || fail "gone: create"
pic monitor --session "$SID" --restart "echo again >> '$T/ledger2'; exec sleep 600" > /dev/null || fail "restart: create"
i=0; until [ -s "$T/ledger" ] && [ -s "$T/ledger2" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "gone: not started"; sleep 0.05; done
P1=$(mpid 1)
P2=$(mpid 2)
kill -9 -- "-$P1" "-$P2"
waitgone "$P1"
waitgone "$P2"
pic loop fire > /dev/null || fail "gone: fire"
until_sql "SELECT state || ' ' || why FROM pic_wake WHERE id = 1" "ended its command is no longer running"
[ "$(q "SELECT state FROM pic_wake WHERE id = 2")" = active ] || fail "restart: ended"
P2B=$(mpid 2)
[ "$P2B" != "$P2" ] && alive "$P2B" || fail "restart: not started again ($P2 $P2B)"
[ "$(wc -l < "$T/ledger2" | tr -d ' ')" = 2 ] || fail "restart: ledger $(cat "$T/ledger2")"
[ "$(wc -l < "$T/ledger" | tr -d ' ')" = 1 ] || fail "gone: started again without --restart"
until_sql "SELECT count(*) FROM pic_submission WHERE request_key = 'inbox:wake:1:1' AND status = 'answered'" 1
idle
grep -qF 'Its command is no longer running; the monitor has ended.' "$LOG/2.req" || fail "gone: the last fire"
pic loop stop M2 > /dev/null
waitgone "$P2B"
pic check > /dev/null || fail "gone: integrity"
printf 'PASS: a monitor whose command is gone ends, saying so; --restart starts it again\n'

# The command holds no lease: a monitor made from a process that holds the conversation's lease (a
# request running in pic --mode rpc, which answers create_wake while it runs) leaves the lease free
# once that request ends, though the command runs on.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse"
rm -f "$WS/started" "$WS/release"
mkfifo "$T/rpc.in"
"$PIC" --db "$DB" --workspace "$WS" --model fake/m --mode rpc < "$T/rpc.in" > "$T/rpc.out" 2> "$T/rpc.err" &
pid=$!
exec 5> "$T/rpc.in"
printf '{"type":"prompt","message":"hold on"}\n' >&5
exists "$WS/started"
SID=$(q "SELECT id FROM pic_session")
printf '{"type":"create_wake","kind":"monitor","command":"exec sleep 600","session":"%s","id":"cw"}\n' "$SID" >&5
i=0; until grep -qF '"command":"create_wake","success":true' "$T/rpc.out"; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "lease: $(cat "$T/rpc.out")"; sleep 0.05; done
PL=$(mpid 1)
touch "$WS/release"
until_sql "SELECT count(*) FROM pic_submission WHERE status = 'answered'" 1
exec 5>&-
wait "$pid" || :
pid=
alive "$PL" || fail "lease: the command ended with its starter"
pic ask --session "$SID" 'after' > /dev/null 2> "$T/err" || fail "lease: the conversation is still locked: $(cat "$T/err")"
pic loop stop M1 > /dev/null
waitgone "$PL"
printf 'PASS: a monitor'"'"'s command holds no lease of the process that started it\n'

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

# A crash after the command started and before its process was recorded: the next look adopts it
# (the command ran once); a crash on either side of a fire's commit sends its lines once.
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse"
pic ask 'hello' > /dev/null 2> "$T/err" || fail "adopt: setup"
SID=$(q "SELECT id FROM pic_session")
: > "$WS/feed"
rc=0
env PIC_CRASH_AT=monitor_started:1 "$PIC" --db "$DB" --workspace "$WS" monitor --session "$SID" "echo ran >> '$T/ledger3'; exec tail -n 0 -f '$WS/feed'" > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "adopt: exit $rc"
[ "$(q "SELECT pid IS NULL, state FROM pic_wake")" = "1|active" ] || fail "adopt: left $(q 'SELECT pid, state FROM pic_wake')"
pic check > /dev/null || fail "adopt: integrity after the crash"
i=0; until [ -s "$T/ledger3" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "adopt: never ran"; sleep 0.05; done
pic loop fire > /dev/null || fail "adopt: look"
PA=$(mpid 1)
[ -n "$PA" ] && alive "$PA" || fail "adopt: not adopted ($(q 'SELECT pid FROM pic_wake'))"
[ "$(wc -l < "$T/ledger3" | tr -d ' ')" = 1 ] || fail "adopt: the command ran again"
printf 'ok\n' >> "$WS/feed"
SPOOL=$(q "SELECT spool FROM pic_wake")
i=0; until [ -s "$SPOOL" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "adopt: spool"; sleep 0.05; done
for at in 1 2; do
    printf 'crash line %s\n' "$at" >> "$WS/feed"
    i=0; until grep -qF "crash line $at" "$SPOOL"; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "crash $at: spool"; sleep 0.05; done
    rc=0
    env PIC_CRASH_AT="wake_fire:$at" "$PIC" --db "$DB" --workspace "$WS" loop fire > /dev/null 2>&1 || rc=$?
    [ "$rc" = 77 ] || fail "crash $at: exit $rc"
    pic check > /dev/null || fail "crash $at: integrity after the crash"
    pic loop fire > /dev/null || fail "crash $at: again"
    until_sql "SELECT count(*) FROM pic_inbox WHERE state = 'pending'" 0
    idle
    fired_once "crash line $at"
done
pic loop stop M1 > /dev/null
waitgone "$PA"
pic check > /dev/null || fail "crash: integrity"
printf 'PASS: a monitor started and not recorded is adopted; a crash at a fire'"'"'s commit sends its lines once\n'
printf 'PASS: monitor\n'
