#!/bin/sh
# Deferred MCP exposure and tool_search, against a fake MCP server (test/pic/fake_mcp.c) and a
# fake Messages API (test/pic/fake_server.c): a deferred server's tools stay out of the request
# until tool_search returns them, are declared by the next request and every later one on that
# branch (a new request, a resumed conversation, a fork), and what was revealed is journaled in
# the result's own transaction, so a crash settles it exactly once. --no-faults (the release
# build, which has no crash points) skips the crash cases.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
MCP=${MCP:-$(dirname "$PIC")/../fake_mcp}
SQLITE3=${SQLITE3:-sqlite3}
STREAMS=$(cd "$(dirname "$0")/streams" && pwd)
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-toolsearch.XXXXXX")
T=$(cd "$T" && pwd -P)
pids=
cleanup() { for p in $pids; do kill "$p" 2>/dev/null && wait "$p" 2>/dev/null || :; done; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
mkdir "$T/home" "$T/ws"
export HOME="$T/home" PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0 PIC_NO_KEY_CHECKS=1 ANTHROPIC_API_KEY=pic-test-key
mkdir -p "$HOME/.pic"
"$PIC" settings loops.tool false > /dev/null # the wake tool: not one of these cases
"$PIC" settings cacheRetention none > /dev/null

wait_port() { # FILE
    i=0
    while [ ! -s "$1" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "no server ($1)"; sleep 0.05; done
}
mkdir "$T/mcp"
"$MCP" "$T/mcp.port" "$T/mcp" 300 modern &
pids="$pids $!"
wait_port "$T/mcp.port"
MCPURL="http://127.0.0.1:$(cat "$T/mcp.port")/mcp"

# A reply that calls tool_search with the query $2 (Anthropic SSE).
search_stream() { # FILE QUERY
    cat > "$1" <<EOF
event: message_start
data: {"type":"message_start","message":{"id":"msg_01","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"usage":{"input_tokens":25,"output_tokens":1}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_01","name":"tool_search","input":{}}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"query\": \"$2\"}"}}

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":40}}

event: message_stop
data: {"type":"message_stop"}

EOF
}
search_stream "$T/s-echo.sse" "echo arguments"
search_stream "$T/s-note.sse" "write a note"
search_stream "$T/s-none.sse" "zzzz qqqq"

n=0
spid=
# case_ SPEC...: a fresh journal, workspace and fake provider.
case_() {
    n=$((n + 1))
    DB="$T/$n.sqlite"; WS="$T/ws$n"; LOG="$T/log$n"
    mkdir "$WS" "$LOG"
    [ -n "$spid" ] && kill "$spid" 2>/dev/null && wait "$spid" 2>/dev/null || true
    rm -f "$T/port"
    "$SERVER" "$T/port" "$LOG" 120 "$@" &
    spid=$!
    pids="$pids $spid"
    wait_port "$T/port"
    URL="http://127.0.0.1:$(cat "$T/port")/v1/messages"
}
FLAGS=
# shellcheck disable=SC2086
pic() { "$PIC" $FLAGS --db "$DB" --workspace "$WS" "$@"; }
run() { pic run --provider anthropic --model anthropic/test-model --api-url "$URL" 2> "$T/stderr"; }
# The tool names of request K, in the order they were declared.
names() { grep -o '"name":"[A-Za-z0-9_]*","description"' "$LOG/${1:-1}.req" | sed 's/"name":"\([A-Za-z0-9_]*\)".*/\1/' | tr '\n' ' ' | sed 's/ $//'; }
has() { names "$1" | tr ' ' '\n' | grep -qx "$2"; }
nreq() { ls "$LOG" | grep -c '\.req$'; }
add() { # EXPOSURE
    "$PIC" mcp remove srv > /dev/null 2>&1 || :
    "$PIC" mcp add srv --url "$MCPURL" ${1:+--exposure "$1"} > /dev/null 2> "$T/e" || fail "add srv: $(cat "$T/e")"
}

# ---- the tools stay out of the request until tool_search loads them ------------------------------
add deferred
case_ "sse:$T/s-echo.sse" "sse:$STREAMS/text.sse"
pic submit job 'use echo' > /dev/null
run > /dev/null || fail "run: $(cat "$T/stderr")"
has 1 tool_search || fail "request 1 does not declare tool_search: $(names 1)"
names 1 | grep -q 'mcp__' && fail "request 1 declares a deferred tool: $(names 1)"
has 2 mcp__srv__echo || fail "request 2 does not declare the loaded tool: $(names 2)"
has 2 tool_search || fail "request 2 lost tool_search: $(names 2)"
has 2 read || fail "request 2 lost read: $(names 2)"
printf 'PASS: a deferred tool is declared only once tool_search has loaded it\n'

# What the model was told, and what is frozen and journaled.
pic dump > "$T/d"
grep -q '^effect 1 .* tool_search done safe=1 ' "$T/d" || fail "tool_search effect: $(grep '^effect' "$T/d")"
grep -q 'mcp__srv__echo' "$T/d" || fail "the result does not name the tool: $(cat "$T/d")"
"$SQLITE3" "$DB" "SELECT group_concat(json_extract(value,'\$.name'),' ') FROM pic_session, json_each(tools)" > "$T/f"
grep -q 'mcp__' "$T/f" && fail "the frozen tools hold a deferred tool: $(cat "$T/f")"
grep -q tool_search "$T/f" || fail "the frozen tools lack tool_search: $(cat "$T/f")"
[ "$("$SQLITE3" "$DB" "SELECT group_concat(name) FROM pic_tool_reveal")" = mcp__srv__echo ] ||
    fail "journaled reveals: $("$SQLITE3" "$DB" "SELECT name FROM pic_tool_reveal")"
printf 'PASS: the reveal is journaled; the frozen tool set is unchanged\n'

# ---- a later request, a resumed conversation and a fork declare the same tools --------------------
sid=$(pic sessions | awk 'NR==1{print $1}')
k=$(nreq)
pic submit job2 'again' --session "$sid" > /dev/null
run > /dev/null || fail "second run: $(cat "$T/stderr")"
has $((k + 1)) mcp__srv__echo || fail "a later request lost the loaded tool: $(names $((k + 1)))"
f=$(pic fork "$sid" 2> /dev/null) || fail "fork"
k=$(nreq)
pic submit job3 'in the fork' --session "$f" > /dev/null || fail "submit in the fork"
run > /dev/null || fail "fork run: $(cat "$T/stderr")"
has $((k + 1)) mcp__srv__echo || fail "the fork lost the loaded tool: $(names $((k + 1)))"
printf 'PASS: later requests, a resumed conversation and a fork declare what was loaded\n'

# ---- the ranking picks the match ------------------------------------------------------------------------
case_ "sse:$T/s-note.sse" "sse:$STREAMS/text.sse"
pic submit job 'note' > /dev/null
run > /dev/null || fail "run note: $(cat "$T/stderr")"
has 2 mcp__srv__write_note || fail "write_note not loaded: $(names 2)"
has 2 mcp__srv__slow && fail "an unrelated tool was loaded: $(names 2)"
printf 'PASS: tool_search loads the tools that match its query, not the rest\n'

# ---- no match -----------------------------------------------------------------------------------------
case_ "sse:$T/s-none.sse" "sse:$STREAMS/text.sse"
pic submit job 'none' > /dev/null
run > /dev/null || fail "run none: $(cat "$T/stderr")"
pic dump | grep -q 'No matching tools found' || fail "no-match result: $(pic dump | grep '^effect')"
names 2 | grep -q 'mcp__' && fail "a no-match search loaded something: $(names 2)"
[ "$("$SQLITE3" "$DB" "SELECT count(*) FROM pic_tool_reveal")" = 0 ] || fail "a no-match search journaled a reveal"
printf 'PASS: a search with no match loads nothing\n'

# ---- exposure direct, and nothing deferred: no tool_search, as before ---------------------------------
add direct
case_ "sse:$STREAMS/text.sse"
pic submit job 'direct' > /dev/null
run > /dev/null || fail "run direct: $(cat "$T/stderr")"
has 1 mcp__srv__echo || fail "a direct tool is not declared: $(names 1)"
has 1 tool_search && fail "tool_search is declared with no deferred tool: $(names 1)"
add ""
case_ "sse:$STREAMS/text.sse"
pic submit job 'default' > /dev/null
run > /dev/null || fail "run default: $(cat "$T/stderr")"
has 1 mcp__srv__echo || fail "a default-exposure tool is not declared: $(names 1)"
printf 'PASS: direct and default exposure declare their tools, with no tool_search\n'

# ---- the tool flags: excluded and unlisted tools -------------------------------------------------------
add deferred
case_ "sse:$T/s-echo.sse" "sse:$STREAMS/text.sse"
pic submit job 'excl' > /dev/null
FLAGS="--exclude-tools mcp__srv__*"
run > /dev/null || fail "run excluded: $(cat "$T/stderr")"
FLAGS=
pic dump | grep -q 'No matching tools found' || fail "an excluded tool was found: $(pic dump | grep '^effect')"
case_ "sse:$T/s-echo.sse" "sse:$STREAMS/text.sse"
pic submit job 'plain' > /dev/null
FLAGS="--tools read,tool_search"
run > /dev/null || fail "run --tools: $(cat "$T/stderr")"
FLAGS=
[ "$(names 1)" = "read tool_search" ] || fail "--tools read,tool_search declared: $(names 1)"
has 2 mcp__srv__echo || fail "tool_search did not reach a tool no --tools entry names: $(names 2)"
case_ "sse:$STREAMS/text.sse"
pic submit job 'off' > /dev/null
FLAGS="--tools read"
run > /dev/null || fail "run --tools read: $(cat "$T/stderr")"
FLAGS=
[ "$(names 1)" = "read" ] || fail "--tools read declared: $(names 1)"
printf 'PASS: --exclude-tools hides deferred tools; --tools reaches them only through tool_search\n'

# ---- crashes: a started search runs again, once; a committed one is not run again ----------------------
if [ "$FAULTS" = yes ]; then
    add deferred
    case_ "sse:$T/s-note.sse" "sse:$STREAMS/text.sse"
    pic submit job 'crash' > /dev/null
    if env PIC_CRASH_AT=after-exec:1 "$PIC" --db "$DB" --workspace "$WS" run --provider anthropic --model anthropic/test-model \
        --api-url "$URL" > /dev/null 2>&1; then fail "did not crash after the search ran"; fi
    [ "$("$SQLITE3" "$DB" "SELECT state FROM pic_effect")" = started ] || fail "the search was not left started"
    [ "$("$SQLITE3" "$DB" "SELECT count(*) FROM pic_tool_reveal")" = 0 ] || fail "a reveal outlived its uncommitted result"
    run > /dev/null || fail "recovery run: $(cat "$T/stderr")"
    [ "$("$SQLITE3" "$DB" "SELECT state || ' ' || replay_safe FROM pic_effect")" = "done 1" ] ||
        fail "recovered effect: $(pic dump | grep '^effect')"
    [ "$("$SQLITE3" "$DB" "SELECT group_concat(name) FROM pic_tool_reveal")" = mcp__srv__write_note ] ||
        fail "reveals after recovery: $("$SQLITE3" "$DB" "SELECT name FROM pic_tool_reveal")"
    k=$(nreq)
    has "$k" mcp__srv__write_note || fail "the recovered request does not declare the loaded tool: $(names "$k")"

    case_ "sse:$T/s-note.sse" "sse:$STREAMS/text.sse"
    pic submit job 'crash2' > /dev/null
    if env PIC_CRASH_AT=after-result:1 "$PIC" --db "$DB" --workspace "$WS" run --provider anthropic --model anthropic/test-model \
        --api-url "$URL" > /dev/null 2>&1; then fail "did not crash after the result"; fi
    [ "$("$SQLITE3" "$DB" "SELECT count(*) FROM pic_tool_reveal")" = 1 ] || fail "the committed result lost its reveal"
    run > /dev/null || fail "recovery run 2: $(cat "$T/stderr")"
    [ "$("$SQLITE3" "$DB" "SELECT count(*) FROM pic_tool_reveal")" = 1 ] || fail "the reveal was journaled twice"
    k=$(nreq)
    has "$k" mcp__srv__write_note || fail "after-result: not declared: $(names "$k")"
    printf 'PASS: a crash before the result is settled by running the search again; one after it is not rerun\n'
fi
