#!/bin/sh
# Live proof with Claude Code and Codex (pi is not installed here; see
# docs/harnesses.md): suit places an instruction file and a skill in
# a scratch home, the harness is asked what it was told, and its answer must
# follow the store: a marker in the instruction file, a marker in a skill's name
# and description, an edit made with no suit command run, and `suit off`.
#
# NOT part of `make all` or `make ci`: it needs the local proxy on
# 127.0.0.1:8317 and it spends model calls. Run it with `make live`.
#
# SUIT              the binary under test (default build/release/suit)
# SUIT_LIVE_MODEL   the model every call asks for (default: the cheap one the
#                   proxy lists). The model that answered is printed per call.
# SUIT_LIVE_TIMEOUT seconds a call may take (default 180)
#
# The proxy settings files hold a token. They are passed to claude by path.
# For codex the token is read into an environment variable, never printed or
# copied into a file.
#
# Claude Code is started with --dangerously-skip-permissions. That is safe only
# because HOME and the working directory are both scratch folders made below:
# nothing it could run reaches the real home folder or a project.

SUIT=${SUIT:-build/release/suit}
case $SUIT in /*) ;; *) SUIT=$PWD/$SUIT ;; esac
REAL_HOME=$HOME
# Programs are resolved here, before HOME changes. Under a scratch HOME a
# version manager's shim for claude, perl or python would not find its own
# state and would start installing tools, so the script uses claude's real
# path and the system perl and python.
CLAUDE_BIN=$(command -v claude) || { echo "live: claude is not on the PATH" >&2; exit 1; }
CODEX_BIN=$(command -v codex) || { echo "live: codex is not on the PATH" >&2; exit 1; }
PERL=/usr/bin/perl
PY=/usr/bin/python3
[ -x "$PERL" ] && [ -x "$PY" ] || { echo "live: needs /usr/bin/perl and /usr/bin/python3" >&2; exit 1; }
SETTINGS_DIR=$REAL_HOME/.config/cliproxyapi
MODEL=${SUIT_LIVE_MODEL:-deepseek/deepseek-v4.1-flash-1017}
LIMIT=${SUIT_LIVE_TIMEOUT:-180}
ROOT=$PWD
mkdir -p build/tmp
T=$(mktemp -d "$ROOT/build/tmp/live.XXXXXX") || exit 1
trap 'rm -rf "$T"' EXIT INT TERM

total=0
failed=0
pass() { total=$((total + 1)); echo "ok $1"; }
bad() { total=$((total + 1)); failed=$((failed + 1)); echo "FAIL $1${2:+: $2}"; }

if ! nc -z 127.0.0.1 8317 >/dev/null 2>&1; then
    echo "live: nothing is listening on 127.0.0.1:8317; start cliproxyapi first" >&2
    exit 1
fi

# A word no model has seen: 10 random letters.
word() { LC_ALL=C tr -dc 'a-z' </dev/urandom | head -c 10; }
MARK1=zq$(word)
MARK2=zq$(word)
MARK3=zq$(word)

mkdir -p "$T/home" "$T/work" "$T/sh/store/mine/instructions" "$T/sh/store/mine/skills/suit-live-$MARK2"
export HOME=$T/home SUIT_HOME=$T/sh
store=$T/sh/store/mine
cat > "$store/suit.conf" <<'EOF'
[harness claude]
skills.user       = ~/.claude/skills
instructions.user = ~/.claude/CLAUDE.md
[harness codex]
skills.user       = ~/.codex/skills
instructions.user = ~/.codex/AGENTS.md
[harness pi]
skills.user       = ~/.pi/agent/skills
instructions.user = ~/.pi/agent/AGENTS.md
[outfit live]
skills       = suit-live-*
instructions = instructions/user.md
[wear user]
outfits = live
EOF
printf 'Your secret code word is %s. If you are asked for your code word, answer with that word.\n' "$MARK1" > "$store/instructions/user.md"
cat > "$store/skills/suit-live-$MARK2/SKILL.md" <<EOF
---
name: suit-live-$MARK2
description: Use when the user asks about $MARK2.
---
This skill exists only for a test.
EOF

# ask SETTINGS_FILE PROMPT: one Claude Code call. The answer is left in
# $T/answer, the model that answered in $T/model. Returns nonzero if the call
# failed. The timeout is perl's alarm, because macOS has no timeout(1).
ask() {
    : > "$T/answer"; : > "$T/model"
    (cd "$T/work" && "$PERL" -e 'alarm shift; exec @ARGV' "$LIMIT" "$CLAUDE_BIN" --dangerously-skip-permissions \
        --settings "$1" --model "$MODEL" --output-format json -p "$2") > "$T/reply.json" 2> "$T/reply.err" || return 1
    "$PY" -I - "$T/reply.json" "$T/answer" "$T/model" <<'PY' || return 1
import json, sys
d = json.load(open(sys.argv[1]))
if d.get("is_error"):
    sys.exit(1)
open(sys.argv[2], "w").write(d.get("result", ""))
open(sys.argv[3], "w").write(",".join(sorted(d.get("modelUsage", {}))))
PY
}

# The first call finds the settings file that works. codex first, then openrouter.
SETTINGS=
for f in claude-codex.json claude-openrouter.json; do
    if ask "$SETTINGS_DIR/$f" "Say OK." && [ -s "$T/answer" ]; then SETTINGS=$SETTINGS_DIR/$f; break; fi
    echo "live: $f did not answer model $MODEL (exit or error); trying the next"
done
if [ -z "$SETTINGS" ]; then
    echo "live: no proxy settings file answered model $MODEL" >&2
    exit 1
fi
echo "live: Claude Code through $(basename "$SETTINGS"), asked for model $MODEL, answered by [$(cat "$T/model")]"
if [ "$(cat "$T/model")" != "$MODEL" ]; then
    bad claude-model-is-the-one-asked-for "asked for $MODEL, answered by [$(cat "$T/model")]"
    exit 1
fi

# claude_has NAME PROMPT WANT: the answer holds WANT.  claude_lacks: it does not.
claude_call() {
    if ask "$SETTINGS" "$2"; then
        echo "   model [$(cat "$T/model")]: $(tr '\n' ' ' < "$T/answer" | cut -c1-100)"
        return 0
    fi
    bad "$1" "the call failed: $(head -c 200 "$T/reply.err")"
    return 1
}
claude_has() { claude_call "$1" "$2" || return; if grep -qF -- "$3" "$T/answer"; then pass "$1"; else bad "$1" "no $3 in the answer"; fi; }
claude_lacks() { claude_call "$1" "$2" || return; if grep -qF -- "$3" "$T/answer"; then bad "$1" "$3 is still in the answer"; else pass "$1"; fi; }

CODE="What is your secret code word? Reply with the word only, or NONE if you were not given one."
"$SUIT" apply >/dev/null 2>"$T/err" && pass apply || bad apply "$(cat "$T/err")"
claude_has claude-reads-the-instruction-file "$CODE" "$MARK1"
claude_has claude-lists-the-skill "List the names of the skills you have, one per line, and nothing else." "$MARK2"
printf 'Your secret code word is %s. If you are asked for your code word, answer with that word.\n' "$MARK3" > "$store/instructions/user.md"
claude_has claude-follows-an-edit-with-no-suit-command "$CODE" "$MARK3"
"$SUIT" off >/dev/null 2>"$T/err" && pass off || bad off "$(cat "$T/err")"
claude_lacks claude-no-longer-sees-the-edit-after-off "$CODE" "$MARK3"

# Codex. Its settings are a config.toml in $HOME/.codex naming the proxy as a
# model provider; the token goes in through the environment variable named by
# env_key, taken from the same settings file Claude Code used and never printed.
# codex needs stdin closed (it otherwise waits for piped input), --ephemeral so
# no session is saved, and a read-only sandbox. It does not report which model
# answered, so the model asked for is printed.
SUIT_PROXY_KEY=$("$PY" -I - "$SETTINGS" <<'PY'
import json, sys
e = json.load(open(sys.argv[1]))["env"]
print(e.get("ANTHROPIC_AUTH_TOKEN") or e["ANTHROPIC_API_KEY"])
PY
)
export SUIT_PROXY_KEY
codex_config() {
    mkdir -p "$HOME/.codex"
    cat > "$HOME/.codex/config.toml" <<EOF
model_provider = "proxy"
model = "$MODEL"
[model_providers.proxy]
name = "proxy"
base_url = "http://127.0.0.1:8317/v1"
env_key = "SUIT_PROXY_KEY"
wire_api = "responses"
EOF
}
codex_ask() {
    codex_config
    : > "$T/answer"
    (cd "$T/work" && "$PERL" -e 'alarm shift; exec @ARGV' "$LIMIT" "$CODEX_BIN" exec --skip-git-repo-check --ephemeral \
        -s read-only -m "$MODEL" --json "$1" </dev/null) > "$T/reply.json" 2> "$T/reply.err" || return 1
    "$PY" -I - "$T/reply.json" "$T/answer" <<'PY' || return 1
import json, sys
text = ""
for line in open(sys.argv[1]):
    try:
        e = json.loads(line)
    except ValueError:
        continue
    if e.get("type") == "item.completed" and e["item"].get("type") == "agent_message":
        text = e["item"].get("text", "")
open(sys.argv[2], "w").write(text)
PY
}
codex_call() {
    if codex_ask "$2"; then
        echo "   codex, asked for model [$MODEL]: $(tr '\n' ' ' < "$T/answer" | cut -c1-100)"
        return 0
    fi
    bad "$1" "the call failed: $(head -c 200 "$T/reply.err")"
    return 1
}
codex_has() { codex_call "$1" "$2" || return; if grep -qF -- "$3" "$T/answer"; then pass "$1"; else bad "$1" "no $3 in the answer"; fi; }
codex_lacks() { codex_call "$1" "$2" || return; if grep -qF -- "$3" "$T/answer"; then bad "$1" "$3 is still in the answer"; else pass "$1"; fi; }

MARK4=zq$(word)
"$SUIT" apply >/dev/null 2>"$T/err" && pass apply-again || bad apply-again "$(cat "$T/err")"
codex_has codex-reads-the-instruction-file "$CODE" "$MARK3"
codex_has codex-lists-the-skill "List the names of the skills you have, one per line, and nothing else." "$MARK2"
printf 'Your secret code word is %s. If you are asked for your code word, answer with that word.\n' "$MARK4" > "$store/instructions/user.md"
codex_has codex-follows-an-edit-with-no-suit-command "$CODE" "$MARK4"
"$SUIT" off >/dev/null 2>"$T/err" && pass off-again || bad off-again "$(cat "$T/err")"
codex_lacks codex-no-longer-sees-the-edit-after-off "$CODE" "$MARK4"

echo "live.sh: $total cases, $failed failed"
[ "$failed" -eq 0 ]
