#!/bin/sh
# The tool registry: a tool a component registers is offered, chosen by the tool flags, run
# through a request, and settled on recovery by the replay safety it registered with. The tool is
# the test seam PIC_TEST_TOOL=NAME:safe|unsafe:LEDGER (dev builds only), which appends its input
# to LEDGER, a file outside the workspace, so the ledger counts how often it ran. --no-faults
# (the release build, which has no seam) checks only that the seam is not there.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SQLITE3=${SQLITE3:-sqlite3}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-registry.XXXXXX")
export HOME="$T/home"
mkdir -p "$HOME/.pic"
"$PIC" settings loops.tool false > /dev/null # the wake tool: not one of these cases
mkdir -p "$HOME"
trap 'rm -rf -- "$T"' EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }

n=0
fresh() { # a new journal, workspace and ledger
    n=$((n + 1))
    DB="$T/$n.sqlite"
    WS="$T/ws$n"
    mkdir "$WS"
    : > "$T/ledger"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
# with_tool MODE ARGS...: pic with the test tool registered, replay-safe or not; crash_after MODE
# ARGS... the same, crashing once the tool has run, before its result commits. The variables go
# through env: sh keeps an assignment made before a function call.
with_tool() {
    mode=$1
    shift
    env PIC_TEST_TOOL="probe:$mode:$T/ledger" "$PIC" --db "$DB" --workspace "$WS" "$@"
}
crash_after() {
    mode=$1
    shift
    env PIC_CRASH_AT=after-exec:1 PIC_TEST_TOOL="probe:$mode:$T/ledger" "$PIC" --db "$DB" --workspace "$WS" "$@"
}
lines() { wc -l < "$T/ledger" | tr -d ' '; }
declared() { "$SQLITE3" "$DB" "SELECT group_concat(json_extract(value,'\$.name'),' ') FROM pic_session, json_each(tools)"; }

printf 'tool raw probe {"n":1}\ntext done\n' > "$T/one"

if [ "$FAULTS" = no ]; then
    fresh
    pic submit job 'probe once' > /dev/null
    with_tool unsafe run --script "$T/one" > /dev/null
    pic dump | grep -q 'Tool probe not found' || fail "release: the test seam registered a tool"
    [ "$(lines)" = 0 ] || fail "release: the test tool ran"
    printf 'PASS: release builds have no test tool\n'
    exit 0
fi

# A registered tool is on by default beside the built-in ones, and the flags choose it like any tool.
for c in "read bash edit write send_message web_fetch web_search probe|" "probe|--no-builtin-tools" "read|--tools read" \
    "read bash edit write send_message web_fetch web_search|--exclude-tools probe" "read bash edit write send_message web_fetch web_search|--tools -probe" \
    "|--no-tools" "read probe|--tools read,probe"; do
    want=${c%%|*} flags=${c#*|}
    fresh
    # shellcheck disable=SC2086
    pic $flags submit job 'probe once' > /dev/null
    # shellcheck disable=SC2086
    with_tool unsafe $flags run --script "$T/one" > /dev/null
    [ "$(declared)" = "$want" ] || fail "flags '$flags': declared '$(declared)', wanted '$want'"
done
printf 'PASS: the tool flags choose a registered tool\n'

# Driven through a request: the call runs once and its result reaches the conversation.
fresh
pic submit job 'probe once' > /dev/null
with_tool unsafe run --script "$T/one" > /dev/null
out=$(pic dump)
printf '%s\n' "$out" | grep -q '^effect 1 .* probe done safe=0 ' || fail "request: effect not done: $out"
printf '%s\n' "$out" | grep -q 'probe ran: {"n":1}' || fail "request: no result in the conversation"
printf '%s\n' "$out" | grep -q '^submission 1 job answered ' || fail "request: not answered"
[ "$(lines)" = 1 ] || fail "request: ledger has $(lines) lines"
printf 'PASS: a registered tool runs through a request\n'

# Two calls in one reply run at once, each once.
fresh
printf 'tool raw probe {"n":1}\traw probe {"n":2}\ntext done\n' > "$T/two"
pic submit job 'probe twice' > /dev/null
with_tool unsafe run --script "$T/two" > /dev/null
[ "$(pic dump | grep -c ' probe done safe=0 ')" = 2 ] || fail "parallel: $(pic dump | grep '^effect')"
[ "$(lines)" = 2 ] || fail "parallel: ledger has $(lines) lines"
printf 'PASS: registered tools run in parallel\n'

# A crash after a replay-unsafe tool's effect, before its result commits: the outcome is unknown
# and the tool is never run again.
fresh
pic submit job 'probe once' > /dev/null
if crash_after unsafe run --script "$T/one" 2> /dev/null; then
    fail "unsafe: did not crash"
fi
[ "$("$SQLITE3" "$DB" "SELECT state || ' ' || replay_safe FROM pic_effect")" = "started 0" ] ||
    fail "unsafe: effect not left started"
with_tool unsafe run --script "$T/one" > /dev/null
out=$(pic dump)
printf '%s\n' "$out" | grep -q '^effect 1 .* probe unknown safe=0 ' || fail "unsafe: not unknown: $out"
printf '%s\n' "$out" | grep -q 'outcome unknown (interrupted before its result was recorded); not re-run' ||
    fail "unsafe: the model was not told"
printf '%s\n' "$out" | grep -q '^submission 1 job answered ' || fail "unsafe: not answered"
[ "$(lines)" = 1 ] || fail "unsafe: ran $(lines) times"
pic check > /dev/null || fail "unsafe: integrity check"
printf 'PASS: a replay-unsafe registered tool is not run again after a crash\n'

# The same crash with a replay-safe tool: run again, and done.
fresh
pic submit job 'probe once' > /dev/null
if crash_after safe run --script "$T/one" 2> /dev/null; then
    fail "safe: did not crash"
fi
with_tool safe run --script "$T/one" > /dev/null
pic dump | grep -q '^effect 1 .* probe done safe=1 ' || fail "safe: not done: $(pic dump | grep '^effect')"
[ "$(lines)" = 2 ] || fail "safe: ran $(lines) times, expected 2"
printf 'PASS: a replay-safe registered tool runs again after a crash\n'

# Recovery reads the record, not the registry: the unsafe call settles as unknown even when the
# recovering pic has no such tool.
fresh
pic submit job 'probe once' > /dev/null
if crash_after unsafe run --script "$T/one" 2> /dev/null; then
    fail "unregistered: did not crash"
fi
pic run --script "$T/one" > /dev/null
pic dump | grep -q '^effect 1 .* probe unknown safe=0 ' || fail "unregistered: not unknown"
[ "$(lines)" = 1 ] || fail "unregistered: ran $(lines) times"
printf 'PASS: recovery settles a call by its record alone\n'
