#!/usr/bin/env bash
# Headless runner for Eval B — the ONLY valid execution mode for these
# scenarios (design.md Decision 1): a fresh `claude -p` process with cwd set
# to the sandbox, so the real SessionStart hook fires for the model under
# test. Never run these prompts via in-session Agent-tool subagents.
#
# Usage: run <scenario> <model> <workdir> [--reps N] [--results FILE]
#
#   scenario  W1|W2|W3|R1|R2|R3|R4|R4-nograph
#   model     haiku|sonnet|opus|...
#   workdir   sandboxes are created under here as <scenario>-<model>-rN
#   --reps    repeated executions of the same cell (default 1; the grid-run
#             stage decides the real default — design.md Decision 5)
#
# Each rep: fresh sandbox -> claude -p with ONLY the scenario's task prompt
# (no system-level hints) -> full stream-json transcript saved to
# <sandbox>/transcript.jsonl -> bin/check appends one TSV row to RESULTS.
set -euo pipefail

SCENARIO="${1:?usage: run <scenario> <model> <workdir> [--reps N] [--results FILE]}"
MODEL="${2:?model required (haiku|sonnet|...)}"
WORKDIR="${3:?workdir required}"
shift 3

REPS=1
RESULTS=""
while [ $# -gt 0 ]; do
  case "$1" in
    --reps)    REPS="${2:?--reps needs a number}"; shift 2 ;;
    --results) RESULTS="${2:?--results needs a path}"; shift 2 ;;
    *) echo "unknown option: $1" >&2; exit 2 ;;
  esac
done

EVAL_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SCENARIO_FILE="$EVAL_ROOT/scenarios/${SCENARIO%-nograph}.md"
[ -f "$SCENARIO_FILE" ] || { echo "unknown scenario: $SCENARIO" >&2; exit 2; }
mkdir -p "$WORKDIR"
RESULTS="${RESULTS:-$WORKDIR/results.tsv}"

TASK="$(awk '/^## Task/{found=1; next} found' "$SCENARIO_FILE")"

for rep in $(seq 1 "$REPS"); do
  SANDBOX="$WORKDIR/$SCENARIO-$MODEL-r$rep"
  "$EVAL_ROOT/bin/sandbox" "$SCENARIO" "$SANDBOX" >/dev/null

  # cwd = sandbox: the SessionStart hook resolves the project root from here.
  (cd "$SANDBOX" && claude -p \
      --model "$MODEL" \
      --output-format stream-json --verbose \
      --dangerously-skip-permissions \
      "$TASK" > transcript.jsonl) || echo "claude exited non-zero for $SANDBOX" >&2

  "$EVAL_ROOT/bin/check" "$SCENARIO" "$SANDBOX" --tsv "$MODEL" | tee -a "$RESULTS"
done
