Files
project-work/triton-sota-toolkit-bb5effd/scripts/trial.sh
2026-10-19 14:52:32 -04:00

1685 lines
76 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
# Run difficulty trials: the profile's roster as Terminus-2 lanes, then analyze.
#
# Defaults come from the toolkit profile (profiles/<profile>/profile.env, loaded
# by scripts/lib/profile.sh; TOOLKIT_PROFILE selects the profile):
# lanes: TRIAL_ROSTER, one agent=model:quota entry per lane, launched in
# order (the same agent may appear in several lanes with different
# models); one `harbor run -k <quota>` per lane, -n capped at the quota
# harness: terminus-2 is the only trial harness. The model is called from
# this machine (LiteLLM; the provider prefix gemini/, anthropic/ or
# openai/ on the model string decides the lane's credentials) and the
# task container stays under the task's declared policy. An agent
# installed inside the container (claude-code, codex) cannot start
# there offline and is refused, in the roster or in --agents, before
# any harbor run. Every run carries
# --agent-kwarg record_terminal_session=false (the recording's
# asciinema install cannot run in the offline container; the pane log
# and the trajectory remain), the turn cap and the model answer
# timeout below
# turn cap: TRIAL_MAX_TURNS (CHEAT_TRIAL_MAX_TURNS for a cheat run), passed
# as --agent-kwarg max_turns with suppress_max_turns_warning=true.
# Terminus-2's own default is one million turns, so a trial whose
# model keeps answering with nothing parseable would otherwise run
# to the agent timeout; a trial that reaches the cap stops, runs the
# verifier and counts like any other trial
# model answer timeout: TRIAL_LLM_TIMEOUT_SEC (regular and cheat runs alike),
# passed as --agent-kwarg llm_call_kwargs={"timeout":<N>}; Terminus-2
# forwards llm_call_kwargs to every model call. The library default
# of 600 seconds is shorter than a long answer on a hard task takes
# to start arriving: the trial gave up, Harbor retried the call,
# every attempt timed out the same way, and the slot ended without a
# reward, while the answer was still produced and billed
# credentials: per lane (scripts/lib/trial-lanes.sh).
# TRIAL_ROSTER_FILTER_BY_CREDENTIALS=1 drops a roster lane whose
# variables are missing; 0 makes that an error before any harbor
# run. A lane named with --agents is mandatory either way: a lane
# the worker typed is never silently dropped
# top-ups: each lane is topped up to its own quota, the largest deficit
# first; TRIAL_EXACT=1 makes exactly the quotas count (surplus is
# recorded, never counted), 0 at least the quotas
# cheat trials: one lane, CHEAT_TRIAL_AGENT=CHEAT_TRIAL_MODEL:CHEAT_TRIAL_COUNT
# (scripts/cheat-trial.sh delegates here with the hostile prompt)
# cheat fallback: CHEAT_TRIAL_FALLBACK_MODELS, an ordered list of
# provider/model names (empty disables it). With it set, every cheat
# trial is classified from its trajectory after each harbor batch
# (scripts/lib/trial_attempt.py); a trial in which the model produced
# no usable response is recorded as a toolkit reject beside the trial
# (scripts/lib/trial-rejects.sh) and does not count toward the cheat
# quota; the shortfall is topped up on the first fallback model, then
# the next when a whole batch produced no usable response again, the
# last one repeating until the quota is met or the dry-batch abort
# fires. Counted trials on the cheat model and on the fallback models
# fill the one cheat quota together. A trial the verifier passed
# (reward 1) is never rejected, whatever the detector says: it
# counts, and one line says so
# concurrency: TRIAL_CONCURRENCY (parallel trials per harbor run); a lane
# never asks for more than its quota
# stopping: INT, TERM and HUP are trapped before the first harbor run. The
# signal is forwarded to the harbor run in progress and the script
# waits for it; then nothing is topped up or analyzed:
# trial-provenance.env is written for the trials that exist, a
# "Stopped." block names the --resume latest command, and the exit
# code is the signal's (130 for INT, 143 for TERM, 129 for HUP, the
# closed terminal). A harbor run that a signal ended on its own (its
# exit code 128 or more; the script received nothing) is treated the
# same way, with harbor's code
#
# Usage: scripts/trial.sh <task-path> [--trials N] [--agents list] [--concurrency N]
# [--agent-setup-timeout-multiplier N] [--agent-setup-retries N]
# scripts/trial.sh <task-path> --resume latest|<job-dir> [--analyze-only]
# Example: scripts/trial.sh tasks/compile-postgres-with-sanitizers
#
# --agents takes whitespace-separated tokens: `terminus-2` runs the agent's
# roster lanes, `terminus-2=<provider>/<model>` runs one lane with that model
# (the quota is the agent's roster quota, else the first lane's). --trials N
# sets every lane's quota to N. Both are local-iteration overrides: in a
# profile with TRIAL_EXACT=1 a run whose lanes differ from the roster (agent,
# model or quota; order does not matter) is non-standard and may not pass
# scripts/submit.sh unless its lanes reproduce the roster exactly; lanes
# identical to the roster are a standard run, however they were typed.
#
# --concurrency forwards to harbor's -n (parallel trials within a single
# harbor invocation), capped at the lane's quota. Lower it (--concurrency 1)
# when Docker or the model endpoint struggles under parallel trials.
#
# Repeated AgentSetupTimeoutError before any task engagement is setup noise,
# not task difficulty. Prefer lowering concurrency first; if setup still times
# out at Harbor's default 360s ceiling, raise only the setup ceiling with
# --agent-setup-timeout-multiplier 2 or 3. HARBOR_AGENT_SETUP_TIMEOUT_MULTIPLIER
# provides the same override via env.
#
# After the initial runs, the script tops each lane up until it has its quota
# of trials that produced a real verifier/reward.txt (or the TRIAL_MAX_TOTAL
# cap fires); MIN_VALID is the sum of the lane quotas. Runs with both
# exception.txt and reward.txt count as valid: the verifier reached a reward
# decision, even if the agent later hit a timeout or orchestration exception.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
TOOLKIT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$SCRIPT_DIR/lib/profile.sh"
source "$SCRIPT_DIR/lib/toolkit-env.sh"
source "$SCRIPT_DIR/lib/harbor-jobs.sh"
source "$SCRIPT_DIR/lib/trial-rejects.sh"
source "$SCRIPT_DIR/lib/trial-prompts.sh"
source "$SCRIPT_DIR/lib/toolkit-version.sh"
source "$SCRIPT_DIR/lib/trial-lanes.sh"
# Harbor must run with CWD = the host-visible workspace path so its nested
# container mounts resolve against the host Docker daemon.
HARBOR_CWD="${HOST_WORKSPACE:-$TOOLKIT_ROOT}"
ANALYSIS_JOB_PROMPT="$PROFILE_RUBRICS_DIR/trial-analysis-job.txt"
TRIAL_KIND="$(resolve_trial_kind "${CHEAT_TRIAL_DELEGATED:-}" "${TRIAL_KIND:-}")"
# TRIAL_ANALYSIS_MODEL, TRIAL_ANALYSIS_EFFORT, TRIAL_SUMMARY_MODEL and
# TRIAL_SUMMARY_EFFORT are set by profile.sh: profile.env values, unless the
# same variable is already set in the environment (worker override).
# TRIAL_EXACT=1: scripts/check-trial-signal.sh counts exactly the lane quotas
# (surplus is recorded, never counted), so a run whose lanes differ from the
# roster is non-standard and may not pass submit unless its lanes reproduce
# the roster exactly. 0: at least the quotas, every in-lane substantive trial
# counts. lanes_tally takes it as its third argument.
EXACT_QUOTAS="${TRIAL_EXACT:-0}"
if [ $# -lt 1 ]; then
echo "Usage: $0 <task-path> [--trials N] [--agents list] [--concurrency N] [--agent-setup-timeout-multiplier N] [--agent-setup-retries N] [--resume latest|<job-dir>] [--analyze-only]" >&2
exit 1
fi
TASK_PATH="$1"
shift
# Lanes, as parallel arrays (bash 3.2): LANE_AGENTS[i]=agent, LANE_MODELS[i]
# the roster model, LANE_QUOTAS[i] the quota, from TRIAL_ROSTER in launch
# order. --agents replaces the list; --trials N overrides every quota.
LANE_AGENTS=()
LANE_MODELS=()
LANE_QUOTAS=()
lane_add() {
LANE_AGENTS[${#LANE_AGENTS[@]}]="$1"
LANE_MODELS[${#LANE_MODELS[@]}]="$2"
LANE_QUOTAS[${#LANE_QUOTAS[@]}]="$3"
}
ROSTER_AGENTS=""
ROSTER_QUOTA_SUM=0
for roster_entry in $TRIAL_ROSTER; do
case "$roster_entry" in
*=*:*) ;;
*)
echo "ERROR: TRIAL_ROSTER entry '$roster_entry' in $PROFILE_ENV_FILE is not agent=model:trials." >&2
exit 1
;;
esac
if ! [[ "${roster_entry##*:}" =~ ^[0-9]+$ ]]; then
echo "ERROR: TRIAL_ROSTER entry '$roster_entry' in $PROFILE_ENV_FILE has a non-numeric trial count." >&2
exit 1
fi
lane_add "$(lane_entry_agent "$roster_entry")" "$(lane_entry_model "$roster_entry")" "$(lane_entry_quota "$roster_entry")"
ROSTER_QUOTA_SUM=$((ROSTER_QUOTA_SUM + $(lane_entry_quota "$roster_entry")))
case " $ROSTER_AGENTS " in
*" ${roster_entry%%=*} "*) ;;
*) ROSTER_AGENTS="${ROSTER_AGENTS:+$ROSTER_AGENTS }${roster_entry%%=*}" ;;
esac
done
if [ -z "$ROSTER_AGENTS" ]; then
echo "ERROR: TRIAL_ROSTER in $PROFILE_ENV_FILE is empty." >&2
exit 1
fi
# A lane is identified by its agent and model: the same pair twice is a
# profile error (the trials could not be told apart).
i=0
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
j=$((i + 1))
while [ "$j" -lt "${#LANE_AGENTS[@]}" ]; do
if [ "${LANE_AGENTS[$i]}=${LANE_MODELS[$i]}" = "${LANE_AGENTS[$j]}=${LANE_MODELS[$j]}" ]; then
echo "ERROR: TRIAL_ROSTER in $PROFILE_ENV_FILE names the lane ${LANE_AGENTS[$i]}=${LANE_MODELS[$i]} twice." >&2
exit 1
fi
j=$((j + 1))
done
i=$((i + 1))
done
# Cheat trials run the profile's cheat lane, CHEAT_TRIAL_AGENT=CHEAT_TRIAL_MODEL
# :CHEAT_TRIAL_COUNT, through the same lane code: the hostile prompt is
# cheat-trial.sh's, the credentials are the lane's. REFERENCE_ROSTER is what
# this job is measured against: the roster, or the cheat lane; provenance and
# the override warning name it.
REFERENCE_ROSTER="$TRIAL_ROSTER"
LANE_SOURCE="TRIAL_ROSTER in $PROFILE_ENV_FILE"
if [ "$TRIAL_KIND" = "cheat" ]; then
if [ -z "${CHEAT_TRIAL_AGENT:-}" ] || [ -z "${CHEAT_TRIAL_MODEL:-}" ]; then
echo "ERROR: $PROFILE_ENV_FILE sets no cheat lane (CHEAT_TRIAL_AGENT and CHEAT_TRIAL_MODEL); cheat trials run as that one lane." >&2
exit 1
fi
# The lane's quota is CHEAT_TRIAL_COUNT, the number of substantive cheat
# trials; TRIAL_MIN_VALID sizes the regular roster only.
case "${CHEAT_TRIAL_COUNT:-}" in
''|*[!0-9]*|0)
echo "ERROR: $PROFILE_ENV_FILE sets no CHEAT_TRIAL_COUNT (the number of substantive cheat trials, a positive integer); cheat trials are sized by it." >&2
exit 1
;;
esac
LANE_AGENTS=()
LANE_MODELS=()
LANE_QUOTAS=()
lane_add "$CHEAT_TRIAL_AGENT" "$CHEAT_TRIAL_MODEL" "$CHEAT_TRIAL_COUNT"
ROSTER_AGENTS="$CHEAT_TRIAL_AGENT"
ROSTER_QUOTA_SUM="$CHEAT_TRIAL_COUNT"
REFERENCE_ROSTER="$CHEAT_TRIAL_AGENT=$CHEAT_TRIAL_MODEL:$CHEAT_TRIAL_COUNT"
LANE_SOURCE="the cheat lane (CHEAT_TRIAL_AGENT, CHEAT_TRIAL_MODEL) in $PROFILE_ENV_FILE"
fi
# The fallback models for a cheat trial in which the model produced no usable
# response: CHEAT_TRIAL_FALLBACK_MODELS, an ordered space-separated list of
# provider/model names; empty disables the fallback. Each entry is checked
# like CHEAT_TRIAL_MODEL, before any harbor run: the provider/model shape, a
# provider the lane credentials know, not the cheat model itself and not
# listed twice (the tally could not tell the lanes apart). Regular runs
# never read the key.
CHEAT_FALLBACK_MODELS=()
CHEAT_FALLBACK_ENABLED=0
if [ "$TRIAL_KIND" = "cheat" ]; then
for fallback_model in ${CHEAT_TRIAL_FALLBACK_MODELS:-}; do
case "$fallback_model" in
*/*) ;;
*)
echo "ERROR: CHEAT_TRIAL_FALLBACK_MODELS entry '$fallback_model' in $PROFILE_ENV_FILE is not provider/model; the prefix (gemini/, anthropic/, openai/) decides the lane's credentials." >&2
exit 1
;;
esac
if [ -z "$(lane_credential_vars "$CHEAT_TRIAL_AGENT" "$fallback_model")" ]; then
echo "ERROR: CHEAT_TRIAL_FALLBACK_MODELS entry '$fallback_model' in $PROFILE_ENV_FILE names a provider this toolkit has no credentials for (known: gemini/, anthropic/, openai/)." >&2
exit 1
fi
if [ "$fallback_model" = "$CHEAT_TRIAL_MODEL" ]; then
echo "ERROR: CHEAT_TRIAL_FALLBACK_MODELS in $PROFILE_ENV_FILE lists the cheat model itself ($fallback_model); a fallback must be another model." >&2
exit 1
fi
for seen_model in ${CHEAT_FALLBACK_MODELS[@]+"${CHEAT_FALLBACK_MODELS[@]}"}; do
if [ "$seen_model" = "$fallback_model" ]; then
echo "ERROR: CHEAT_TRIAL_FALLBACK_MODELS in $PROFILE_ENV_FILE lists $fallback_model twice." >&2
exit 1
fi
done
CHEAT_FALLBACK_MODELS[${#CHEAT_FALLBACK_MODELS[@]}]="$fallback_model"
done
if [ "${#CHEAT_FALLBACK_MODELS[@]}" -gt 0 ]; then
CHEAT_FALLBACK_ENABLED=1
fi
fi
# The Terminus-2 turn cap for this run: CHEAT_TRIAL_MAX_TURNS for a cheat run,
# TRIAL_MAX_TURNS otherwise, both positive integers in profile.env. Terminus-2's
# own default is one million turns, so a trial whose model keeps answering with
# nothing parseable (an empty or cut-off response, retried every turn) would
# otherwise run to the agent timeout; a trial that reaches the cap stops, runs
# the verifier and counts like any other trial. select_agent_kwargs passes it.
if [ "$TRIAL_KIND" = "cheat" ]; then
MAX_TURNS_KEY="CHEAT_TRIAL_MAX_TURNS"
MAX_TURNS="${CHEAT_TRIAL_MAX_TURNS:-}"
else
MAX_TURNS_KEY="TRIAL_MAX_TURNS"
MAX_TURNS="${TRIAL_MAX_TURNS:-}"
fi
case "$MAX_TURNS" in
''|*[!0-9]*|0)
echo "ERROR: $PROFILE_ENV_FILE sets no $MAX_TURNS_KEY (the Terminus-2 turn cap per trial, a positive integer); every Terminus-2 lane is capped by it." >&2
exit 1
;;
esac
# How long a trial waits for one model answer: TRIAL_LLM_TIMEOUT_SEC, a positive
# integer of seconds in profile.env, the same for a regular and a cheat run,
# passed to every Terminus-2 lane as the timeout of each model call. The
# library default of 600 seconds is shorter than a long answer on a hard task
# takes to start arriving: the trial gave up, Harbor retried the call, every
# attempt timed out the same way, and the slot ended without a reward, while
# the answer was still produced and billed. select_agent_kwargs passes it.
LLM_TIMEOUT="${TRIAL_LLM_TIMEOUT_SEC:-}"
case "$LLM_TIMEOUT" in
''|*[!0-9]*|0)
echo "ERROR: $PROFILE_ENV_FILE sets no TRIAL_LLM_TIMEOUT_SEC (how long a trial waits for one model answer, a positive integer of seconds); every Terminus-2 lane waits that long per model call." >&2
exit 1
;;
esac
# Every lane runs on terminus-2, the only trial harness: the model is called
# from this machine and the task container stays under the task's policy. An
# agent installed inside the container (claude-code, codex) cannot start there
# offline, and a Terminus-2 model without a provider prefix this toolkit knows
# has no credentials to check. Both are refused before any harbor run.
refuse_unsupported_lanes() {
# refuse_unsupported_lanes <source>: <source> says where the lanes came from
local source="$1" i=0 agent model
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
agent="${LANE_AGENTS[$i]}"
model="${LANE_MODELS[$i]}"
if ! lane_agent_supported "$agent"; then
echo "ERROR: $source names $agent${model:+ ($agent=$model)}; trials run on terminus-2 under the task's offline policy, and $agent would install itself in the task container, which has no network." >&2
echo " terminus-2 is the only trial harness: run the roster, or one lane with --agents terminus-2=<provider>/<model>." >&2
exit 1
fi
if [ -z "$(lane_credential_vars "$agent" "$model")" ]; then
echo "ERROR: $source names $agent=$model; the model needs a provider prefix this toolkit knows (gemini/, anthropic/, openai/), which decides the lane's credentials." >&2
exit 1
fi
i=$((i + 1))
done
}
refuse_unsupported_lanes "$LANE_SOURCE"
# The roster as read, for --agents lookups after the lane list is replaced.
ROSTER_LANE_AGENTS=("${LANE_AGENTS[@]}")
ROSTER_LANE_MODELS=("${LANE_MODELS[@]}")
ROSTER_LANE_QUOTAS=("${LANE_QUOTAS[@]}")
# TRIALS is the figure the banner and provenance report: --trials N when given,
# otherwise the roster's first quota.
TRIALS=""
TRIALS_EXPLICIT=0
AGENTS_ARG=""
AGENTS_EXPLICIT=0
# Harbor concurrency: TRIAL_CONCURRENCY from the profile, capped at a lane's
# attempts (a lane of two trials asks for two parallel trials). A low cap
# spreads the load on Docker and the model endpoint; the top-up loop below
# fills any gaps. Workers can override with --concurrency N.
CONCURRENCY="$TRIAL_CONCURRENCY"
AGENT_SETUP_TIMEOUT_MULTIPLIER="${HARBOR_AGENT_SETUP_TIMEOUT_MULTIPLIER:-}"
AGENT_SETUP_TIMEOUT_MULTIPLIER_EXPLICIT=0
AGENT_SETUP_RETRIES="${HARBOR_AGENT_SETUP_RETRIES:-0}"
AGENT_SETUP_RETRIES_EXPLICIT=0
RESUME_JOB_DIR=""
ANALYZE_ONLY=0
# Auto-retry: after the initial runs, each lane short of its quota of valid
# trials (a real verifier/reward.txt; setup failures and scheduler stalls don't
# count) is topped up with a batch of its deficit until every lane is at its
# quota or the hard cap fires. MIN_VALID is the sum of the lane quotas (below).
# The cap exists to bound cost on tasks with truly broken environments.
MIN_VALID=0
MAX_TOTAL_TRIALS="$TRIAL_MAX_TOTAL"
MAX_CONSECUTIVE_DRY_TOPUPS="$TRIAL_MAX_CONSECUTIVE_DRY_TOPUPS" # abort if N consecutive top-up batches yielded no new valid trial
# Models come from the roster: Terminus-2 model strings carry LiteLLM's
# provider prefix (gemini/, anthropic/, openai/), which LiteLLM consumes before
# the request reaches the endpoint and which decides the lane's credentials.
lane_model() {
# lane_model <i>: the model lane i runs
printf '%s\n' "${LANE_MODELS[$1]}"
}
lane_quota() {
# lane_quota <i>: --trials N when given, else the lane's roster quota
if [ "$TRIALS_EXPLICIT" -eq 1 ]; then
echo "$TRIALS"
else
echo "${LANE_QUOTAS[$1]}"
fi
}
roster_quota_for_agent() {
# roster_quota_for_agent <agent>: the agent's first roster quota, else TRIALS
local i=0
while [ "$i" -lt "${#ROSTER_LANE_AGENTS[@]}" ]; do
if [ "${ROSTER_LANE_AGENTS[$i]}" = "$1" ]; then
echo "${ROSTER_LANE_QUOTAS[$i]}"
return 0
fi
i=$((i + 1))
done
echo "$TRIALS"
}
nonempty_or_none() {
if [ -n "${1:-}" ]; then
echo "$1"
else
echo "none"
fi
}
cheat_fallback_models_csv() {
# the fallback list, comma-separated, or none
local out="" model
for model in ${CHEAT_FALLBACK_MODELS[@]+"${CHEAT_FALLBACK_MODELS[@]}"}; do
out="${out:+$out,}$model"
done
nonempty_or_none "$out"
}
agents_csv() {
local out="" agent
for agent in $AGENTS; do
out="${out:+$out,}$agent"
done
nonempty_or_none "$out"
}
agent_models_csv() {
# one agent=model per lane, in launch order
local out="" i=0 model
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
model="$(lane_model "$i")"
out="${out:+$out,}${LANE_AGENTS[$i]}=${model:-unknown}"
i=$((i + 1))
done
nonempty_or_none "$out"
}
lanes_csv() {
# one agent=model:quota per lane, comma-separated, for the banner
local out="" i=0
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
out="${out:+$out, }${LANE_AGENTS[$i]}=$(lane_model "$i"):$(lane_quota "$i")"
i=$((i + 1))
done
printf '%s\n' "$out"
}
is_positive_number() {
[[ "$1" =~ ^[0-9]+([.][0-9]+)?$ ]] && awk -v v="$1" 'BEGIN { exit !(v + 0 > 0) }'
}
is_nonnegative_integer() {
[[ "$1" =~ ^[0-9]+$ ]]
}
while [ $# -gt 0 ]; do
case "$1" in
--trials)
TRIALS="$2"
TRIALS_EXPLICIT=1
shift 2
;;
--agents)
AGENTS_ARG="$2"
AGENTS_EXPLICIT=1
shift 2
;;
--concurrency)
CONCURRENCY="$2"
shift 2
;;
--agent-setup-timeout-multiplier)
AGENT_SETUP_TIMEOUT_MULTIPLIER="$2"
AGENT_SETUP_TIMEOUT_MULTIPLIER_EXPLICIT=1
shift 2
;;
--agent-setup-retries)
AGENT_SETUP_RETRIES="$2"
AGENT_SETUP_RETRIES_EXPLICIT=1
shift 2
;;
--resume)
RESUME_JOB_DIR="$2"
shift 2
;;
--analyze-only)
ANALYZE_ONLY=1
shift
;;
*)
echo "Unknown argument: $1" >&2
exit 1
;;
esac
done
if [ -z "$TRIALS" ]; then
TRIALS="${ROSTER_LANE_QUOTAS[0]}"
fi
# --agents replaces the lane list: `agent` takes that agent's roster lanes,
# `agent=model` one lane with that model. A token naming an unsupported agent
# is refused below with the same message as a roster lane; a supported agent
# outside the roster with no model is an error (which model would run?).
if [ "$AGENTS_EXPLICIT" -eq 1 ]; then
LANE_AGENTS=()
LANE_MODELS=()
LANE_QUOTAS=()
for agent_token in $AGENTS_ARG; do
case "$agent_token" in
*=*)
lane_add "${agent_token%%=*}" "${agent_token#*=}" "$(roster_quota_for_agent "${agent_token%%=*}")"
;;
*)
if ! lane_agent_supported "$agent_token"; then
lane_add "$agent_token" "" "$TRIALS"
continue
fi
found=0
i=0
while [ "$i" -lt "${#ROSTER_LANE_AGENTS[@]}" ]; do
if [ "${ROSTER_LANE_AGENTS[$i]}" = "$agent_token" ]; then
lane_add "$agent_token" "${ROSTER_LANE_MODELS[$i]}" "${ROSTER_LANE_QUOTAS[$i]}"
found=1
fi
i=$((i + 1))
done
if [ "$found" -eq 0 ]; then
echo "ERROR: --agents names $agent_token, which is not in this profile's roster ($REFERENCE_ROSTER)." >&2
echo " Give it a model: --agents $agent_token=<provider>/<model>." >&2
exit 1
fi
;;
esac
done
refuse_unsupported_lanes "--agents"
fi
if [ -f "$TOOLKIT_ROOT/.env" ]; then
set -a
source "$TOOLKIT_ROOT/.env"
set +a
restore_profile_policy_values
fi
# Harbor's Terminus-2 reads the Gemini endpoint from these two variables
# (LiteLLM builds the request URL from GEMINI_API_BASE); make sure a value set
# in the shell rather than in .env reaches the harbor process.
for gemini_var in GEMINI_API_KEY GEMINI_API_BASE; do
if [ -n "${!gemini_var:-}" ]; then
export "${gemini_var?}"
fi
done
if [ "$AGENT_SETUP_TIMEOUT_MULTIPLIER_EXPLICIT" -eq 0 ]; then
AGENT_SETUP_TIMEOUT_MULTIPLIER="${HARBOR_AGENT_SETUP_TIMEOUT_MULTIPLIER:-$AGENT_SETUP_TIMEOUT_MULTIPLIER}"
fi
if [ "$AGENT_SETUP_RETRIES_EXPLICIT" -eq 0 ]; then
AGENT_SETUP_RETRIES="${HARBOR_AGENT_SETUP_RETRIES:-$AGENT_SETUP_RETRIES}"
fi
if [ -n "$AGENT_SETUP_TIMEOUT_MULTIPLIER" ] && ! is_positive_number "$AGENT_SETUP_TIMEOUT_MULTIPLIER"; then
echo "ERROR: --agent-setup-timeout-multiplier must be a positive number, got: $AGENT_SETUP_TIMEOUT_MULTIPLIER" >&2
exit 1
fi
if ! is_nonnegative_integer "$AGENT_SETUP_RETRIES"; then
echo "ERROR: --agent-setup-retries must be a non-negative integer, got: $AGENT_SETUP_RETRIES" >&2
exit 1
fi
if [ ! -d "$TASK_PATH" ]; then
echo "ERROR: task directory not found: $TASK_PATH" >&2
exit 1
fi
if [ "$ANALYZE_ONLY" -eq 0 ]; then
require_frontier_harbor
fi
require_toolkit_command claude "trial.sh uses Claude Code to analyze trajectories."
TASK_ABS="$(cd "$TASK_PATH" && pwd)"
TASK_NAME=$(basename "$TASK_ABS")
# Paths recorded in artifacts that submit.sh bundles (trial-provenance.env and
# the analysis/summary headers) must not expose the worker's host filesystem.
# Strip the toolkit root (or the Harbor workspace this runs from); fall back to
# the basename for a path outside both. Relative paths pass through unchanged.
toolkit_relative_path() {
local path="$1" root
for root in "$TOOLKIT_ROOT" "$HARBOR_CWD"; do
case "$path" in
"$root"/*)
printf '%s\n' "${path#"$root"/}"
return 0
;;
esac
done
case "$path" in
/*) basename "$path" ;;
*) printf '%s\n' "$path" ;;
esac
}
TASK_SOURCE_REL="$(toolkit_relative_path "$TASK_ABS")"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
DIR_PREFIX="${JOB_DIR_PREFIX:-trial}"
if ! bash "$PROFILE_CHECKS_DIR/check-task-identity.sh" "$TASK_PATH"; then
echo "ERROR: task identity preflight failed; fix the task slug/task.toml before trialing." >&2
exit 1
fi
if [ "$ANALYZE_ONLY" -eq 0 ] && ! bash "$PROFILE_CHECKS_DIR/check-internet-policy.sh" "$TASK_PATH"; then
echo "ERROR: internet policy preflight failed; remove legacy allow_internet and declare network_mode before trialing." >&2
exit 1
fi
if [ "$ANALYZE_ONLY" -eq 1 ] && [ -z "$RESUME_JOB_DIR" ]; then
RESUME_JOB_DIR="latest"
fi
# Claude Code runs the trajectory analysis and the job summary below (the
# trials themselves run on terminus-2). Default its output ceiling to the
# profile's (CLAUDE_CODE_MAX_OUTPUT_TOKENS_DEFAULT), preserving an explicit
# worker/admin override; preflight checks the same value.
export CLAUDE_CODE_MAX_OUTPUT_TOKENS="${CLAUDE_CODE_MAX_OUTPUT_TOKENS:-$CLAUDE_CODE_MAX_OUTPUT_TOKENS_DEFAULT}"
# Switch to the host-visible path so Harbor's nested container mounts resolve.
cd "$HARBOR_CWD"
# Expanded below with the ${arr[@]+"${arr[@]}"} form: under set -u, bash 3.2
# treats an empty array's "${arr[@]}" as unbound (a run with no setup
# multiplier and no retries, the default, failed there before this form).
HARBOR_SETUP_ARGS=()
if [ -n "$AGENT_SETUP_TIMEOUT_MULTIPLIER" ]; then
HARBOR_SETUP_ARGS+=(--agent-setup-timeout-multiplier "$AGENT_SETUP_TIMEOUT_MULTIPLIER")
fi
if [ "$AGENT_SETUP_RETRIES" -gt 0 ]; then
# Keep retries narrow: setup timeouts happen before task engagement and are
# infra noise. Do not retry verifier/agent execution failures here.
HARBOR_SETUP_ARGS+=(--max-retries "$AGENT_SETUP_RETRIES" --retry-include AgentSetupTimeoutError)
fi
# No harbor run carries an --allow-*-host flag: the task container runs under
# the task's declared network policy, the model is called from this machine,
# and nothing is installed in the container.
# Terminus-2 records the terminal session with asciinema unless told not to,
# and its setup installs asciinema inside the task container (apt-get, then
# pip) before the agent's turn; the container is offline under the task's
# policy, so the install fails or hangs before any task work. Every Terminus-2
# run (initial, top-up, cheat) turns the recording off; the tmux pane log
# (agent/terminus_2.pane) and the trajectory remain. Every Terminus-2 run also
# carries the turn cap, max_turns=$MAX_TURNS (TRIAL_MAX_TURNS, or
# CHEAT_TRIAL_MAX_TURNS for a cheat run), with Terminus-2's "artificially
# limited" warning suppressed: its own default is one million turns, and a
# model that keeps answering with nothing parseable is asked to retry every
# turn, so an uncapped trial of that kind runs to the agent timeout; a trial
# that reaches the cap stops, runs the verifier and counts. Every Terminus-2
# run also carries the model answer timeout, llm_call_kwargs={"timeout":N}
# with N=$LLM_TIMEOUT (TRIAL_LLM_TIMEOUT_SEC, seconds, regular and cheat runs
# alike): Terminus-2 forwards llm_call_kwargs to every model call, and the
# library default of 600 seconds is shorter than a long answer on a hard task
# takes to start arriving, so a trial gave up on answers that were still being
# produced and billed, Harbor retried the call, every attempt timed out the
# same way, and the slot ended without a reward. Harbor JSON-parses the kwarg
# values, so the cap arrives as a number, true as a boolean and the timeout as
# a dict with the timeout and any native thinking settings (compact JSON).
# No other
# agent takes these kwargs.
RUN_REASONING_EFFORT="${TRIAL_REASONING_EFFORT:-}"
if [ "$TRIAL_KIND" = "cheat" ]; then
RUN_REASONING_EFFORT="${CHEAT_TRIAL_REASONING_EFFORT:-}"
fi
RUN_AGENT_KWARGS=()
select_agent_kwargs() {
# select_agent_kwargs <agent> <model>
local call_kwargs="{\"timeout\":$LLM_TIMEOUT}"
local effort="$RUN_REASONING_EFFORT"
case "$1" in
terminus-2)
# Native thinking fields avoid legacy LiteLLM model-name mappings
# that turn new Claude/Gemini effort into obsolete token budgets.
if [ -n "$effort" ]; then
case "${2:-}" in
anthropic/*)
call_kwargs="{\"timeout\":$LLM_TIMEOUT,\"thinking\":{\"type\":\"adaptive\"},\"output_config\":{\"effort\":\"$effort\"}}"
;;
gemini/*)
call_kwargs="{\"timeout\":$LLM_TIMEOUT,\"extra_body\":{\"generationConfig\":{\"thinkingConfig\":{\"thinkingLevel\":\"$effort\",\"includeThoughts\":true}}}}"
;;
esac
fi
RUN_AGENT_KWARGS=(
--agent-kwarg record_terminal_session=false
--agent-kwarg "max_turns=$MAX_TURNS"
--agent-kwarg suppress_max_turns_warning=true
--agent-kwarg "llm_call_kwargs=$call_kwargs"
)
case "${2:-}" in
openai/*)
if [ -n "$effort" ]; then
RUN_AGENT_KWARGS+=(
--agent-kwarg use_responses_api=true
--agent-kwarg "reasoning_effort=$effort"
--agent-kwarg temperature=null
)
fi
;;
esac
;;
*) RUN_AGENT_KWARGS=() ;;
esac
}
run_concurrency() {
# run_concurrency <attempts>: harbor -n for a run of that many attempts:
# CONCURRENCY, capped at the attempts (a lane of two trials asks for two
# parallel trials, not three).
local n="$CONCURRENCY"
if is_nonnegative_integer "$n" && is_nonnegative_integer "$1" && [ "$1" -lt "$n" ]; then
n="$1"
fi
printf '%s\n' "$n"
}
# Credentials per lane (scripts/lib/trial-lanes.sh, by the model's provider
# prefix), before any harbor run. Roster lanes: TRIAL_ROSTER_FILTER_BY_CREDENTIALS=1
# keeps only the lanes whose variables are set; 0 makes every lane mandatory
# and a missing variable an error naming the lane and the variables. A lane
# named with --agents is mandatory whatever the filter says: a lane the worker
# typed is never silently dropped, so a missing variable is the same error.
# Analyze-only mode does not need agent credentials.
if [ "$ANALYZE_ONLY" -eq 0 ]; then
if [ "$AGENTS_EXPLICIT" -eq 0 ] && [ "$TRIAL_ROSTER_FILTER_BY_CREDENTIALS" = "1" ]; then
KEPT_AGENTS=()
KEPT_MODELS=()
KEPT_QUOTAS=()
i=0
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
if [ -n "$(lane_credential_vars "${LANE_AGENTS[$i]}" "${LANE_MODELS[$i]}")" ] \
&& [ -z "$(lane_missing_credentials "${LANE_AGENTS[$i]}" "${LANE_MODELS[$i]}")" ]; then
KEPT_AGENTS[${#KEPT_AGENTS[@]}]="${LANE_AGENTS[$i]}"
KEPT_MODELS[${#KEPT_MODELS[@]}]="${LANE_MODELS[$i]}"
KEPT_QUOTAS[${#KEPT_QUOTAS[@]}]="${LANE_QUOTAS[$i]}"
fi
i=$((i + 1))
done
LANE_AGENTS=(${KEPT_AGENTS[@]+"${KEPT_AGENTS[@]}"})
LANE_MODELS=(${KEPT_MODELS[@]+"${KEPT_MODELS[@]}"})
LANE_QUOTAS=(${KEPT_QUOTAS[@]+"${KEPT_QUOTAS[@]}"})
else
MISSING_LANE=0
i=0
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
missing_vars="$(lane_missing_credentials "${LANE_AGENTS[$i]}" "${LANE_MODELS[$i]}")"
if [ -n "$missing_vars" ]; then
echo "ERROR: lane ${LANE_AGENTS[$i]}=${LANE_MODELS[$i]} needs $(lane_credential_vars "${LANE_AGENTS[$i]}" "${LANE_MODELS[$i]}" | sed 's/ /, /g') in .env; missing: $(printf '%s' "$missing_vars" | sed 's/ /, /g')" >&2
MISSING_LANE=1
fi
i=$((i + 1))
done
if [ "$MISSING_LANE" -eq 1 ]; then
if [ "$AGENTS_EXPLICIT" -eq 1 ]; then
echo " A lane named with --agents is never dropped: set the variables in .env (see .env.example) and rerun. No harbor run was started." >&2
else
echo " Every lane is mandatory in this profile (TRIAL_ROSTER_FILTER_BY_CREDENTIALS=0): set the variables in .env (see .env.example) and rerun. No harbor run was started." >&2
fi
exit 1
fi
fi
if [ "${#LANE_AGENTS[@]}" -eq 0 ]; then
echo "ERROR: no lane has its credentials in .env (TRIAL_ROSTER_FILTER_BY_CREDENTIALS=1 dropped every lane)." >&2
echo " Set the variables named in .env.example and rerun." >&2
exit 1
fi
# A fallback model's credentials are as mandatory as the cheat lane's: the
# fallback runs mid-job, after the cheat model's batch, and a missing
# variable found only then would waste that batch.
if [ "$CHEAT_FALLBACK_ENABLED" -eq 1 ]; then
MISSING_FALLBACK=0
for fallback_model in "${CHEAT_FALLBACK_MODELS[@]}"; do
missing_vars="$(lane_missing_credentials "$CHEAT_TRIAL_AGENT" "$fallback_model")"
if [ -n "$missing_vars" ]; then
echo "ERROR: cheat fallback model $CHEAT_TRIAL_AGENT=$fallback_model (CHEAT_TRIAL_FALLBACK_MODELS) needs $(lane_credential_vars "$CHEAT_TRIAL_AGENT" "$fallback_model" | sed 's/ /, /g') in .env; missing: $(printf '%s' "$missing_vars" | sed 's/ /, /g')" >&2
MISSING_FALLBACK=1
fi
done
if [ "$MISSING_FALLBACK" -eq 1 ]; then
echo " Set the variables in .env (see .env.example) and rerun. No harbor run was started." >&2
exit 1
fi
fi
fi
# The agents in the run, once each, in lane order (the banner and provenance).
AGENTS=""
i=0
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
case " $AGENTS " in
*" ${LANE_AGENTS[$i]} "*) ;;
*) AGENTS="${AGENTS:+$AGENTS }${LANE_AGENTS[$i]}" ;;
esac
i=$((i + 1))
done
# The target is every lane at its quota: MIN_VALID is their sum. A default
# regular run's profile must agree with itself (TRIAL_MIN_VALID equals the
# roster's sum; the test asserts it too). The cheat lane is sized by
# CHEAT_TRIAL_COUNT alone, so the check applies to regular runs only.
NONSTANDARD=0
if [ "$TRIAL_KIND" != "cheat" ] && [ "$AGENTS_EXPLICIT" -eq 0 ] && [ "$TRIALS_EXPLICIT" -eq 0 ] && [ "$ROSTER_QUOTA_SUM" -ne "$TRIAL_MIN_VALID" ]; then
echo "ERROR: TRIAL_MIN_VALID=$TRIAL_MIN_VALID in $PROFILE_ENV_FILE differs from the sum of the roster's lane quotas ($ROSTER_QUOTA_SUM); the profile is inconsistent." >&2
exit 1
fi
i=0
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
MIN_VALID=$((MIN_VALID + $(lane_quota "$i")))
i=$((i + 1))
done
# A run is standard when its final lanes are the reference roster's (agent,
# model and quota; order does not matter), however they were typed: --agents
# terminus-2 expands to the roster and is standard, a single lane or another
# quota is not. Under TRIAL_EXACT=1 that difference is what submit measures.
lanes_signature() {
# lanes_signature <agent=model:quota>...: the entries, sorted, one per line
printf '%s\n' "$@" | sort
}
FINAL_LANE_ENTRIES=()
i=0
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
FINAL_LANE_ENTRIES[${#FINAL_LANE_ENTRIES[@]}]="${LANE_AGENTS[$i]}=${LANE_MODELS[$i]}:$(lane_quota "$i")"
i=$((i + 1))
done
read -r -a REFERENCE_LANE_ENTRIES <<< "$REFERENCE_ROSTER"
if [ "$EXACT_QUOTAS" = "1" ] \
&& [ "$(lanes_signature ${FINAL_LANE_ENTRIES[@]+"${FINAL_LANE_ENTRIES[@]}"})" != "$(lanes_signature "${REFERENCE_LANE_ENTRIES[@]}")" ]; then
NONSTANDARD=1
fi
RESUMING=0
if [ -n "$RESUME_JOB_DIR" ]; then
RESUMING=1
if [ "$RESUME_JOB_DIR" = "latest" ]; then
# Relative to HARBOR_CWD (the cd above), like a fresh JOB_DIR.
JOB_DIR="$(latest_job_dir harbor-jobs "$DIR_PREFIX" "$TASK_NAME")"
if [ -z "$JOB_DIR" ]; then
echo "ERROR: no harbor-jobs/${DIR_PREFIX}-${TASK_NAME}-*/ directory found to resume." >&2
exit 1
fi
else
JOB_DIR="$RESUME_JOB_DIR"
fi
if [ ! -d "$JOB_DIR" ]; then
echo "ERROR: resume job directory not found: $JOB_DIR" >&2
exit 1
fi
else
# JOB_DIR_PREFIX defaults to "trial". cheat-trial.sh sets it to "cheat-trial"
# when delegating, so cheat output lands in a separate harbor-jobs entry and
# submit.sh can bundle both regular and cheat artifacts side by side without
# the later run silently overwriting the earlier one.
JOB_DIR="harbor-jobs/${DIR_PREFIX}-$TASK_NAME-$TIMESTAMP"
fi
mkdir -p "$JOB_DIR"
PROVENANCE_FILE="$JOB_DIR/trial-provenance.env"
JOB_DIR_REL="$(toolkit_relative_path "$JOB_DIR")"
REASONING_EFFORT_PROVENANCE="$RUN_REASONING_EFFORT"
if [ -n "$REASONING_EFFORT_PROVENANCE" ] && [ "$RESUMING" -eq 1 ]; then
previous_effort="$(toolkit_manifest_value reasoning_effort "$PROVENANCE_FILE" 2>/dev/null || true)"
if [ -z "$previous_effort" ]; then
previous_effort="$(toolkit_manifest_value openai_responses_effort "$PROVENANCE_FILE" 2>/dev/null || true)"
fi
if [ "$ANALYZE_ONLY" -eq 0 ]; then
if [ -n "$previous_effort" ] && [ "$previous_effort" != "unknown" ] && [ "$previous_effort" != "$REASONING_EFFORT_PROVENANCE" ]; then
echo "ERROR: this job records reasoning effort '$previous_effort', but the profile now requires '$REASONING_EFFORT_PROVENANCE'. Start a fresh $TRIAL_KIND job; do not mix trial settings." >&2
exit 1
fi
if [ -z "$previous_effort" ] || [ "$previous_effort" = "unknown" ]; then
echo "WARNING: this job has no confirmed reasoning-effort provenance. New attempts use $REASONING_EFFORT_PROVENANCE, but the combined job's effort remains unknown. Start a fresh job under the updated settings." >&2
REASONING_EFFORT_PROVENANCE=unknown
fi
fi
fi
provenance_existing_or_current() {
local key="$1"
local current="$2"
local existing
if [ "$ANALYZE_ONLY" -eq 1 ] && [ -f "$PROVENANCE_FILE" ]; then
existing="$(toolkit_manifest_value "$key" "$PROVENANCE_FILE" 2>/dev/null || true)"
if [ -n "$existing" ]; then
echo "$existing"
return
fi
fi
echo "$current"
}
provenance_value() {
local key="$1"
local value
value="$(toolkit_manifest_value "$key" "$PROVENANCE_FILE" 2>/dev/null || true)"
if [ -n "$value" ]; then
echo "$value"
else
echo "unknown"
fi
}
# The three trial counters in trial-provenance.env. Their values need not
# agree, and QC reads them by name, so neither the names nor what they count
# changes here:
# trials_run_total the trial launches requested in this job: the lane
# quotas at the initial launch plus every top-up
# requested (TOPUP_N per top-up batch); on --resume, the
# trial directories present at resume time plus the
# top-ups requested after it. A stopped run writes the
# directories on disk (stop_run); --analyze-only carries
# the value over from the job's existing file, or writes
# none when the job has none.
# trial_count the trial directories (*/<task>__*/) present when the
# file is written, whatever they hold.
# valid_trials the counted trials: a verifier reward present, no
# .user-reject.md excluding the slot, a result.json naming
# a lane of the run, and within the lane's quota when
# exactly the quotas count (TRIAL_EXACT=1; the surplus is
# not counted). It is the sum of lane_counts=.
# trials_run_total can exceed trial_count when a requested launch produced no
# directory (harbor stopped before writing the trial), and trial_count can
# exceed trials_run_total when harbor wrote more directories than were asked
# for (a retry): trial_count is the denominator for "trials that ran", and
# valid_trials never exceeds it. tests/test-trial-lanes.sh and
# tests/test-cheat-fallback.sh assert the ordering and, where the mock harbor
# wrote every requested trial, that the first two are equal.
write_trial_provenance_file() {
local invocation_mode="$1"
local trial_count="$2"
local valid_count="$3"
local tmp
local current_agents current_agent_models
current_agents="$(agents_csv)"
current_agent_models="$(agent_models_csv)"
tmp="$(mktemp)"
{
echo "schema_version=1"
echo "generated_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "invocation_mode=$invocation_mode"
echo "task_name=$TASK_NAME"
echo "trial_kind=$TRIAL_KIND"
if [ -n "$RUN_REASONING_EFFORT" ]; then
if [ "$ANALYZE_ONLY" -eq 1 ]; then
echo "reasoning_effort=$(provenance_value reasoning_effort)"
else
echo "reasoning_effort=$REASONING_EFFORT_PROVENANCE"
fi
fi
echo "harbor_job_name=$(basename "$JOB_DIR")"
echo "job_dir=$JOB_DIR_REL"
echo "task_source=$TASK_SOURCE_REL"
echo "agents=$(provenance_existing_or_current agents "$current_agents")"
echo "agent_models=$(provenance_existing_or_current agent_models "$current_agent_models")"
echo "trials_requested=$(provenance_existing_or_current trials_requested "$TRIALS")"
echo "min_valid=$(provenance_existing_or_current min_valid "$MIN_VALID")"
echo "max_total_trials=$(provenance_existing_or_current max_total_trials "$MAX_TOTAL_TRIALS")"
echo "max_consecutive_dry_topups=$(provenance_existing_or_current max_consecutive_dry_topups "$MAX_CONSECUTIVE_DRY_TOPUPS")"
echo "trials_run_total=$(provenance_existing_or_current trials_run_total "$(nonempty_or_none "${TRIALS_RUN_TOTAL:-}")")"
echo "trial_count=$trial_count"
echo "valid_trials=$valid_count"
echo "concurrency=$(provenance_existing_or_current concurrency "$(nonempty_or_none "$CONCURRENCY")")"
echo "agent_setup_timeout_multiplier=$(provenance_existing_or_current agent_setup_timeout_multiplier "$(nonempty_or_none "$AGENT_SETUP_TIMEOUT_MULTIPLIER")")"
echo "agent_setup_retries=$(provenance_existing_or_current agent_setup_retries "$(nonempty_or_none "$AGENT_SETUP_RETRIES")")"
echo "claude_code_max_output_tokens=$(provenance_existing_or_current claude_code_max_output_tokens "$(nonempty_or_none "${CLAUDE_CODE_MAX_OUTPUT_TOKENS:-}")")"
echo "turn_cap=$(provenance_existing_or_current turn_cap "$MAX_TURNS")"
echo "llm_timeout=$(provenance_existing_or_current llm_timeout "$LLM_TIMEOUT")"
echo "analysis_model=$TRIAL_ANALYSIS_MODEL"
echo "analysis_effort=$TRIAL_ANALYSIS_EFFORT"
echo "summary_model=$TRIAL_SUMMARY_MODEL"
echo "summary_effort=$TRIAL_SUMMARY_EFFORT"
echo "toolkit_commit=$(toolkit_resolved_value commit)"
echo "toolkit_commit_short=$(toolkit_resolved_value commit_short)"
echo "toolkit_version_source=$(toolkit_resolved_value version_source)"
echo "toolkit_name=$(toolkit_resolved_value toolkit_name)"
echo "toolkit_packed_at=$(toolkit_resolved_value packed_at)"
echo "toolkit_git_tracked_dirty=$(toolkit_resolved_value git_tracked_dirty)"
echo "toolkit_git_untracked_present=$(toolkit_resolved_value git_untracked_present)"
echo "toolkit_pack_force=$(toolkit_resolved_value pack_force)"
# The lane record QC reads to verify the mix: the profile's roster and
# version, the lanes this job ran with their quotas, the counted
# substantive trials and passes per lane, and the surplus trials
# (beyond a quota, kept on disk, never counted).
echo "roster=$(provenance_existing_or_current roster "$REFERENCE_ROSTER")"
echo "roster_version=$(provenance_existing_or_current roster_version "$PROFILE_VERSION")"
echo "lane_quotas=$(provenance_existing_or_current lane_quotas "$(lanes_tally_csv quotas)")"
echo "lane_counts=$(lanes_tally_csv counted)"
echo "lane_pass_counts=$(lanes_tally_csv passes)"
echo "surplus=$(nonempty_or_none "$TALLY_SURPLUS")"
if [ "$TRIAL_KIND" = "cheat" ]; then
# The cheat fallback: the models the profile named, and the trials
# in which the model produced no usable response (toolkit rejects,
# not counted toward the cheat quota).
echo "cheat_fallback_models=$(provenance_existing_or_current cheat_fallback_models "$(cheat_fallback_models_csv)")"
echo "no_attempt=$(nonempty_or_none "$NO_ATTEMPT_TRIALS")"
fi
} > "$tmp"
mv "$tmp" "$PROVENANCE_FILE"
}
# Trial directories Harbor has produced under $JOB_DIR so far: the same
# */${TASK_NAME}__*/ children lanes_tally walks, without the reward/reject
# filter.
count_trial_dirs() {
local count=0 child
for child in "$JOB_DIR"/*/"${TASK_NAME}__"*/; do
[ -d "${child%/}" ] || continue
count=$((count + 1))
done
echo "$count"
}
HARBOR_RUN_INDEX=0
# The invocation this job records in provenance: how the script was called,
# whether the job runs to its end or is stopped on the way.
INVOCATION_MODE="initial"
if [ "$ANALYZE_ONLY" -eq 1 ]; then
INVOCATION_MODE="analyze-only"
elif [ "$RESUMING" -eq 1 ]; then
INVOCATION_MODE="resume"
fi
# Stopping on a signal. A wrapper or a watchdog signals one process: this
# script alone, which without a handler would only notice once the batch had
# run its course, or harbor alone, whose death by a signal looked like a
# batch with failed trials and was followed by a top-up. And harbor leads its
# own process group (run_harbor_batch), so the hangup a closing terminal
# sends this script and tee would not reach it on its own. So INT, TERM and
# HUP are trapped (below, before the first harbor run): the handler forwards
# the signal to the harbor run in progress (its process group) and waits for
# it, and run_harbor_batch then stops the run (stop_run). A signal between
# batches is kept and honoured at the next batch or before the analysis
# (STOP_AT_NEXT_BATCH is 1 while that is the right response); before the
# lanes could start, or once the analysis has started, the script exits with
# the signal's code.
HARBOR_PID="" # the harbor child of the batch in progress, else empty
HARBOR_STOP="" # INT, TERM or HUP once a trapped signal asked the run to stop
STOP_AT_NEXT_BATCH=0
HARBOR_PIPE_DIR="$(mktemp -d)"
trap 'rm -rf "$HARBOR_PIPE_DIR"' EXIT
signal_exit_code() {
# signal_exit_code <INT|TERM|HUP>: the exit code of a process ended by it
case "$1" in
INT) echo 130 ;;
TERM) echo 143 ;;
HUP) echo 129 ;;
*) echo 1 ;;
esac
}
forward_signal() {
# forward_signal <INT|TERM|HUP>: to the harbor run in progress, its whole
# process group (harbor leads it; its children get the signal as they
# did from the terminal), else the process alone.
kill "-$1" -- "-$HARBOR_PID" 2>/dev/null || kill "-$1" "$HARBOR_PID" 2>/dev/null || true
}
on_stop_signal() {
# on_stop_signal <INT|TERM|HUP>: the trap.
HARBOR_STOP="$1"
if [ -n "$HARBOR_PID" ]; then
forward_signal "$1"
wait "$HARBOR_PID" 2>/dev/null || true
return 0
fi
if [ "$STOP_AT_NEXT_BATCH" -ne 1 ]; then
exit "$(signal_exit_code "$1")"
fi
}
stop_run() {
# stop_run <harbor-rc>: the run was stopped, by a signal this script
# received (HARBOR_STOP names it) or by one that ended harbor alone (its
# exit code, 128 or more). No top-up and no analysis: provenance for the
# trials that exist (trials_run_total is what is on disk) first, then the
# block that says how to go on, then the signal's exit code (harbor's
# when it alone was signalled). The block never decides the exit path:
# after a terminal hangup its writes fail, and under set -e a failing
# echo would exit 1 instead of the signal's code.
local rc="$1" code trial_count resume_script="scripts/trial.sh"
lane_tally_now
trial_count=$(find "$JOB_DIR" -maxdepth 2 -type d -name "${TASK_NAME}__*" 2>/dev/null | wc -l | tr -d ' ')
TRIALS_RUN_TOTAL="$trial_count"
write_trial_provenance_file "$INVOCATION_MODE" "$trial_count" "$VALID"
if [ "${CHEAT_TRIAL_DELEGATED:-}" = "1" ]; then
resume_script="scripts/cheat-trial.sh"
fi
echo "" >&2 || true
echo "Stopped. Trials already written are kept." >&2 || true
echo "Resume with: $resume_script $TASK_PATH --resume latest" >&2 || true
if [ -n "$HARBOR_STOP" ]; then
code="$(signal_exit_code "$HARBOR_STOP")"
else
code="$rc"
fi
exit "$code"
}
# run_harbor_batch <note> <harbor run args...>
#
# Harbor exits non-zero whenever any trial scored below 1.0, which is the
# expected outcome for a hard task, so a non-zero exit by itself only earns
# the one-line <note>. A non-zero exit that produced no new trial directory
# means nothing ran (image build failure, Docker down, bad credentials): stop
# with Harbor's exit code instead of burning the top-up budget and reporting
# success. Output streams to the terminal and to a log under $JOB_DIR so the
# failure tail is available afterwards. A run stopped by a signal (see
# on_stop_signal) or ended by one on its own is neither: stop_run.
#
# Harbor runs in the background, its output through tee to the terminal and
# the log as before, so that its PID is known to the signal handler and its
# exit code comes from wait; a named pipe joins the two (in a pipeline the
# known PID would be tee's). Waiting for tee afterwards keeps the log
# complete and the output in order before anything else is printed.
#
# The start runs under job control (set -m for that one command). Without it
# bash starts a background job with SIGINT ignored, which the job cannot
# undo, so neither Ctrl-C nor the forwarded signal would reach harbor; with
# it harbor leads its own process group with default signal dispositions.
# The terminal's Ctrl-C then reaches this script, whose handler forwards it
# to that group once, the way the terminal used to reach harbor and its
# children directly; so does the hangup of a closing terminal, which that
# group would otherwise never see. Harbor's stdin is /dev/null, as it is for a background
# job without job control (every run passes --yes); tee stays in this
# script's group and drains the pipe whatever happens to harbor.
run_harbor_batch() {
local note="$1"
shift
local before after rc log pipe tee_pid
[ -z "$HARBOR_STOP" ] || stop_run 0
HARBOR_RUN_INDEX=$((HARBOR_RUN_INDEX + 1))
log="$JOB_DIR/harbor-run-$TIMESTAMP-$HARBOR_RUN_INDEX.log"
before="$(count_trial_dirs)"
pipe="$HARBOR_PIPE_DIR/harbor-run-$HARBOR_RUN_INDEX"
mkfifo "$pipe"
set +e
tee "$log" < "$pipe" &
tee_pid=$!
set -m
harbor run "$@" < /dev/null > "$pipe" 2>&1 &
HARBOR_PID=$!
set +m
# A signal that arrived while the child was being started is forwarded
# now; the handler saw no PID to send it to.
if [ -n "$HARBOR_STOP" ]; then
forward_signal "$HARBOR_STOP"
fi
wait "$HARBOR_PID"
rc=$?
if [ -n "$HARBOR_STOP" ]; then
# The handler forwarded the signal and waited for the child; a repeat
# signal can have cut that wait short, so wait once more.
wait "$HARBOR_PID" 2>/dev/null
fi
HARBOR_PID=""
wait "$tee_pid"
set -e
rm -f "$pipe"
if [ -n "$HARBOR_STOP" ] || [ "$rc" -ge 128 ]; then
stop_run "$rc"
fi
after="$(count_trial_dirs)"
if [ "$rc" -ne 0 ]; then
if [ "$after" -le "$before" ]; then
echo "" >&2
echo "ERROR: harbor run produced no trials (exit $rc)." >&2
echo " No new */${TASK_NAME}__*/ directory appeared under $JOB_DIR, so this is a" >&2
echo " Harbor/Docker/setup failure, not task difficulty. Last 40 lines of Harbor" >&2
echo " output (full log: $log):" >&2
tail -n 40 "$log" | sed 's/^/ /' >&2
echo " Trials already written are kept; fix the cause and rerun with --resume latest (or --analyze-only to analyze what exists)." >&2
exit "$rc"
fi
echo " $note"
fi
}
# run_lane_batch <note> <agent> <model> <attempts>: one harbor run for a lane,
# with that lane's -n and agent kwargs.
run_lane_batch() {
local note="$1" agent="$2" model="$3" attempts="$4" n
n="$(run_concurrency "$attempts")"
select_agent_kwargs "$agent" "$model"
run_harbor_batch "$note" \
-p "$TASK_PATH" \
-a "$agent" \
-m "$model" \
-o "$JOB_DIR" \
-k "$attempts" \
${n:+-n "$n"} \
${RUN_AGENT_KWARGS[@]+"${RUN_AGENT_KWARGS[@]}"} \
${HARBOR_SETUP_ARGS[@]+"${HARBOR_SETUP_ARGS[@]}"} \
--yes \
--no-delete
}
echo "=========================================="
echo "$(trial_banner_title "$TRIAL_KIND"): $TASK_NAME"
if [ "$ANALYZE_ONLY" -eq 1 ]; then
echo "Mode: analyze existing job only"
elif [ "$RESUMING" -eq 1 ]; then
echo "Mode: resume existing job"
fi
if [ "$ANALYZE_ONLY" -eq 0 ]; then
echo "Agents: $AGENTS"
echo "Lanes (agent=model:quota, launched in order): $(lanes_csv)"
echo "Turn cap per Terminus-2 trial: $MAX_TURNS (a trial that reaches it stops, runs the verifier and counts)."
echo "Model answer timeout per call: $LLM_TIMEOUT s."
if [ -n "$RUN_REASONING_EFFORT" ]; then
echo "$TRIAL_KIND trial reasoning effort: $RUN_REASONING_EFFORT (explicit provider settings)."
fi
if [ "$TRIAL_KIND" = "cheat" ]; then
echo "Fallback models when a cheat trial produced no usable response (CHEAT_TRIAL_FALLBACK_MODELS, tried in turn): $(cheat_fallback_models_csv)"
fi
if [ "$EXACT_QUOTAS" = "1" ]; then
echo "Top-ups preserve the mix, lane by lane; exactly the quotas count (TRIAL_EXACT=1), surplus is recorded and never counted."
else
echo "Top-ups preserve the mix, lane by lane; at least the quotas count (TRIAL_EXACT=0), every in-lane substantive trial counts."
fi
if [ -n "$AGENT_SETUP_TIMEOUT_MULTIPLIER" ]; then
echo "Agent setup timeout multiplier: $AGENT_SETUP_TIMEOUT_MULTIPLIER"
fi
if [ "$AGENT_SETUP_RETRIES" -gt 0 ]; then
echo "Agent setup timeout retries: $AGENT_SETUP_RETRIES (AgentSetupTimeoutError only)"
fi
echo "Network: the task container runs under the task's declared policy; the model is called from this machine, nothing is installed in the container."
if [ "$NONSTANDARD" -eq 1 ]; then
if [ "$AGENTS_EXPLICIT" -eq 1 ] || [ "$TRIALS_EXPLICIT" -eq 1 ]; then
echo "WARNING: --agents/--trials override the profile's roster ($REFERENCE_ROSTER): this run is non-standard and may not pass scripts/submit.sh unless its lanes reproduce the roster exactly (the trial-signal check requires exactly the roster's lane quotas). Use it for local iteration only." >&2
else
# No override was typed, so the lanes differ because the profile
# dropped a roster lane whose credentials are missing.
echo "WARNING: this run's lanes differ from the profile's roster ($REFERENCE_ROSTER) because a lane was dropped for missing credentials (TRIAL_ROSTER_FILTER_BY_CREDENTIALS=1): this run is non-standard and may not pass scripts/submit.sh unless its lanes reproduce the roster exactly (the trial-signal check requires exactly the roster's lane quotas). Use it for local iteration only." >&2
fi
fi
fi
echo "Job dir: $JOB_DIR"
echo "=========================================="
# The initial launch: one batch per lane, in launch order. Called below, once
# the lane tally is set up, so that a stop during a batch can record what
# exists (stop_run tallies the trials and writes provenance).
launch_initial_batches() {
i=0
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
agent="${LANE_AGENTS[$i]}"
model="$(lane_model "$i")"
agent_trials="$(lane_quota "$i")"
i=$((i + 1))
echo ""
echo ">>> $agent × $agent_trials parallel trials (model: $model)"
run_lane_batch "(one or more trials did not achieve reward 1.0 — expected for hard tasks)" "$agent" "$model" "$agent_trials"
done
}
# --- Top-up loop: every lane at its quota of *valid* trials in $JOB_DIR ------
# Valid = trial subdir has verifier/reward.txt and no excluding
# .user-reject.md artifact. Setup failures, scheduler stalls, and
# worker-rejected infra/tooling artifacts do not count.
#
# Each lane is topped up to its own quota: the trials are attributed to lanes
# from their result.json (agent_info, see scripts/lib/trial-lanes.sh), the
# lane with the largest deficit is topped up first with one batch of that
# deficit, and a dry batch counts against that lane alone. Each batch calls
# harbor with -k <deficit> so it produces a parallel sub-trial layer under the
# same JOB_DIR — the trial-analysis pass picks them up automatically via the
# */${TASK_NAME}__* glob.
VALID=0
# The lanes as run (--trials applied) are what the tally attributes trials to
# and what provenance records. On a cheat run with fallback models, each
# fallback model is one more tally lane drawing on the cheat lane's quota
# (TALLY_POOL, scripts/lib/trial-lanes.sh): counted trials on the cheat model
# and on the fallback models fill the one cheat quota, the cheat model's first
# by directory order; lane_quotas names the cheat lane alone, lane_counts every
# model. The fallback lanes are not in LANE_*: the run's lanes, MIN_VALID and
# the standard-run check are unchanged.
lane_tally_now() {
classify_cheat_trials
lanes_tally "$JOB_DIR" "$TASK_NAME" "$EXACT_QUOTAS"
local i=0
VALID=0
while [ "$i" -lt "${#TALLY_AGENTS[@]}" ]; do
VALID=$((VALID + ${TALLY_COUNTED[$i]}))
i=$((i + 1))
done
}
# Cheat runs with fallback models: every cheat trial is classified from its
# trajectory by scripts/lib/trial_attempt.py after every harbor batch and on
# --resume and --analyze-only tallies. A trial in which the model produced no
# usable response gets a toolkit reject beside it (scripts/lib/trial-rejects.sh:
# reject_kind toolkit, reason no_attempt), drops out of the tally like a
# user-rejected trial and is listed in provenance (no_attempt=). A trial that
# already carries a reject file (a worker's, or one written on an earlier
# pass) is not classified again; a trajectory the detector cannot read (exit
# 2) is not classified and counts as it would have without the fallback. A
# trial the verifier passed (verifier/reward.txt reads 1 or more, the way
# lanes_tally counts a pass) is never rejected whatever the detector says: the
# model did real work before it stalled, so the trial counts, and one line
# says why no reject was written (on a --resume or --analyze-only pass the
# trial is classified again, having no reject file, and the line repeats).
# CLASSIFIED_NEW and NO_ATTEMPT_NEW describe the trials first seen on this
# pass, which after a top-up are that batch's trials: the top-up loop moves
# to the next fallback model when a whole batch produced no usable response.
NO_ATTEMPT_TRIALS=""
CLASSIFIED_SEEN=" "
CLASSIFIED_NEW=0
NO_ATTEMPT_NEW=0
CLASSIFIER_WARNED=0
classify_cheat_trials() {
local child clean name out no_attempt rc reward
CLASSIFIED_NEW=0
NO_ATTEMPT_NEW=0
NO_ATTEMPT_TRIALS=""
[ "$CHEAT_FALLBACK_ENABLED" -eq 1 ] || return 0
for child in "$JOB_DIR"/*/"${TASK_NAME}__"*/; do
clean="${child%/}"
[ -d "$clean" ] || continue
name="$(basename "$clean")"
if [ -f "$(trial_reject_file "$clean")" ]; then
if [ "$(trial_reject_kind "$clean")" = "toolkit" ] && [ "$(trial_reject_field "$clean" reason)" = "no_attempt" ]; then
NO_ATTEMPT_TRIALS="${NO_ATTEMPT_TRIALS:+$NO_ATTEMPT_TRIALS,}$name"
fi
continue
fi
case "$CLASSIFIED_SEEN" in
*" $name "*) continue ;;
esac
[ -f "$clean/agent/trajectory.json" ] || continue
if ! command -v python3 >/dev/null 2>&1; then
if [ "$CLASSIFIER_WARNED" -eq 0 ]; then
echo "WARNING: python3 is not on PATH; cheat trials are not classified and the fallback models are never used." >&2
CLASSIFIER_WARNED=1
fi
return 0
fi
set +e
out="$(python3 "$SCRIPT_DIR/lib/trial_attempt.py" "$clean" 2>/dev/null)"
rc=$?
set -e
[ "$rc" -eq 0 ] || continue
CLASSIFIED_SEEN="$CLASSIFIED_SEEN$name "
CLASSIFIED_NEW=$((CLASSIFIED_NEW + 1))
no_attempt="$(printf '%s\n' "$out" | sed -n 's/^no_attempt=//p')"
[ "$no_attempt" = "1" ] || continue
# The reward guard: a passed trial counts, whatever its turns look like.
reward=""
[ -f "$clean/verifier/reward.txt" ] && reward="$(tr -d '[:space:]' < "$clean/verifier/reward.txt")"
if [ -n "$reward" ] && awk -v r="$reward" 'BEGIN { exit (r + 0 >= 1.0) ? 0 : 1 }'; then
echo ">>> $name: the detector saw no usable attempt ($(printf '%s' "$out" | tr '\n' ' ' | sed 's/ $//')), but the verifier passed (reward $reward), so the trial counts and no toolkit reject is written." || true
continue
fi
trial_reject_write_toolkit "$clean" "$TASK_NAME" "$TRIAL_KIND" "$JOB_DIR_REL" no_attempt \
"$(printf '%s' "$out" | tr '\n' ' ')" \
"Counts from scripts/lib/trial_attempt.py over agent/trajectory.json."
NO_ATTEMPT_NEW=$((NO_ATTEMPT_NEW + 1))
NO_ATTEMPT_TRIALS="${NO_ATTEMPT_TRIALS:+$NO_ATTEMPT_TRIALS,}$name"
# Non-fatal: this also runs on the stopped path, after a terminal
# hangup, where the write fails and must not change the exit code.
echo ">>> $name: the model produced no usable response ($(printf '%s' "$out" | tr '\n' ' ' | sed 's/ $//')); recorded as a toolkit reject, not counted toward the cheat quota." || true
done
}
lane_status_line() {
local i=0 lanes="" notes="" head
while [ "$i" -lt "${#TALLY_AGENTS[@]}" ]; do
head="$(lanes_pool_head "$i")"
if [ "$head" != "$i" ]; then
lanes="${lanes:+$lanes, }${TALLY_AGENTS[$i]}=${TALLY_MODELS[$i]} ${TALLY_COUNTED[$i]} (fallback, counted toward the cheat quota)"
elif [ "$(lanes_pool_members "$i")" != "$i" ]; then
lanes="${lanes:+$lanes, }${TALLY_AGENTS[$i]}=${TALLY_MODELS[$i]} ${TALLY_COUNTED[$i]}/${TALLY_QUOTAS[$i]} (with its fallback models $(lanes_pool_counted "$i")/${TALLY_QUOTAS[$i]})"
else
lanes="${lanes:+$lanes, }${TALLY_AGENTS[$i]}=${TALLY_MODELS[$i]} ${TALLY_COUNTED[$i]}/${TALLY_QUOTAS[$i]}"
fi
i=$((i + 1))
done
if [ -n "$NO_ATTEMPT_TRIALS" ]; then
notes="$notes; not counted, the model produced no usable response: $NO_ATTEMPT_TRIALS"
fi
if [ -n "$TALLY_SURPLUS" ]; then
notes="$notes; surplus beyond a lane's quota, recorded and not counted: $TALLY_SURPLUS"
fi
if [ "$TALLY_UNATTRIBUTED" -gt 0 ]; then
notes="$notes; $TALLY_UNATTRIBUTED substantive trial(s) with no readable agent_info in result.json are not counted"
fi
if [ "$TALLY_OFFLANE" -gt 0 ]; then
notes="$notes; $TALLY_OFFLANE substantive trial(s) outside the lanes are not counted: $TALLY_OFFLANE_IDS"
fi
echo ">>> Valid trials so far: $VALID / $MIN_VALID (lanes: $lanes$notes)"
}
TALLY_AGENTS=()
TALLY_MODELS=()
TALLY_QUOTAS=()
# TALLY_POOL is read by scripts/lib/trial-lanes.sh (lanes_pool_head), not here.
# shellcheck disable=SC2034
TALLY_POOL=()
i=0
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
TALLY_AGENTS[$i]="${LANE_AGENTS[$i]}"
TALLY_MODELS[$i]="$(lane_model "$i")"
TALLY_QUOTAS[$i]="$(lane_quota "$i")"
TALLY_POOL[$i]="$i"
i=$((i + 1))
done
# The fallback lanes, in list order, each drawing on the first lane's quota
# (the cheat lane; with --agents naming another model, that lane). A fallback
# model already among the lanes is that lane, not a new one.
# FALLBACK_LANE_INDEX[k] is the tally index of the k-th fallback model.
FALLBACK_LANE_INDEX=()
if [ "$CHEAT_FALLBACK_ENABLED" -eq 1 ]; then
for fallback_model in "${CHEAT_FALLBACK_MODELS[@]}"; do
existing=-1
i=0
while [ "$i" -lt "${#TALLY_AGENTS[@]}" ]; do
if [ "${TALLY_AGENTS[$i]}=${TALLY_MODELS[$i]}" = "$CHEAT_TRIAL_AGENT=$fallback_model" ]; then
existing=$i
break
fi
i=$((i + 1))
done
if [ "$existing" -ge 0 ]; then
FALLBACK_LANE_INDEX[${#FALLBACK_LANE_INDEX[@]}]="$existing"
continue
fi
i="${#TALLY_AGENTS[@]}"
TALLY_AGENTS[$i]="$CHEAT_TRIAL_AGENT"
TALLY_MODELS[$i]="$fallback_model"
TALLY_QUOTAS[$i]=0
# shellcheck disable=SC2034
TALLY_POOL[$i]=0
FALLBACK_LANE_INDEX[${#FALLBACK_LANE_INDEX[@]}]="$i"
done
fi
# From here until the analysis, a signal stops the run for what exists: the
# traps forward it to the batch in progress, or keep it for the next batch.
trap 'on_stop_signal INT' INT
trap 'on_stop_signal TERM' TERM
trap 'on_stop_signal HUP' HUP
STOP_AT_NEXT_BATCH=1
if [ "$ANALYZE_ONLY" -eq 0 ] && [ "$RESUMING" -eq 0 ]; then
launch_initial_batches
elif [ "$ANALYZE_ONLY" -eq 0 ]; then
echo ""
echo ">>> Resuming $JOB_DIR; skipping initial launch and topping up from existing trials."
fi
lane_tally_now
if [ "$ANALYZE_ONLY" -eq 0 ]; then
if [ "$RESUMING" -eq 1 ]; then
TRIALS_RUN_TOTAL=$(find "$JOB_DIR" -maxdepth 2 -type d -name "${TASK_NAME}__*" 2>/dev/null | wc -l | tr -d ' ')
else
TRIALS_RUN_TOTAL=0
i=0
while [ "$i" -lt "${#LANE_AGENTS[@]}" ]; do
TRIALS_RUN_TOTAL=$((TRIALS_RUN_TOTAL + $(lane_quota "$i")))
i=$((i + 1))
done
fi
# Consecutive dry batches, and whether the lane has been given up, per
# lane with a quota of its own (a pool is topped up as one lane).
LANE_DRY=()
LANE_GAVE_UP=()
i=0
while [ "$i" -lt "${#TALLY_AGENTS[@]}" ]; do
LANE_DRY[$i]=0
LANE_GAVE_UP[$i]=0
i=$((i + 1))
done
# The cheat fallback chain: once a cheat trial in this job has produced no
# usable response, the cheat quota's top-ups run on the fallback models,
# the first one first; a top-up batch in which every classified trial
# again produced no usable response moves to the next model, and the last
# model repeats until the quota is met or the dry-batch abort fires. Until
# then (a shortfall from missing rewards alone) top-ups run on the cheat
# model as before.
FALLBACK_POS=0
topup_lane_for() {
# topup_lane_for <head>: the tally index whose model the next top-up
# batch of that pool runs
if [ "$CHEAT_FALLBACK_ENABLED" -eq 1 ] && [ "$1" = "0" ] && [ -n "$NO_ATTEMPT_TRIALS" ]; then
printf '%s\n' "${FALLBACK_LANE_INDEX[$FALLBACK_POS]}"
else
printf '%s\n' "$1"
fi
}
echo ""
lane_status_line
while [ "$TRIALS_RUN_TOTAL" -lt "$MAX_TOTAL_TRIALS" ]; do
# The lane with the largest deficit (the earlier lane on a tie), among
# the lanes with a quota of their own still being topped up; a pool's
# deficit is its quota less the counted trials across its lanes.
PICK=-1
DEFICIT=0
i=0
while [ "$i" -lt "${#TALLY_AGENTS[@]}" ]; do
if [ "$(lanes_pool_head "$i")" = "$i" ]; then
lane_deficit=$((${TALLY_QUOTAS[$i]} - $(lanes_pool_counted "$i")))
if [ "${LANE_GAVE_UP[$i]}" -eq 0 ] && [ "$lane_deficit" -gt "$DEFICIT" ]; then
PICK=$i
DEFICIT=$lane_deficit
fi
fi
i=$((i + 1))
done
[ "$PICK" -ge 0 ] || break
RUN_LANE="$(topup_lane_for "$PICK")"
TOPUP_LANE="${TALLY_AGENTS[$RUN_LANE]}=${TALLY_MODELS[$RUN_LANE]}"
ROOM=$((MAX_TOTAL_TRIALS - TRIALS_RUN_TOTAL))
TOPUP_N=$DEFICIT
[ "$TOPUP_N" -gt "$ROOM" ] && TOPUP_N=$ROOM
echo ""
if [ "$RUN_LANE" != "$PICK" ]; then
echo ">>> Top-up: the cheat quota (${TALLY_AGENTS[$PICK]}=${TALLY_MODELS[$PICK]}) needs $DEFICIT more valid trial(s); requesting $TOPUP_N on the fallback model ${TALLY_MODELS[$RUN_LANE]} (running total: $TRIALS_RUN_TOTAL/$MAX_TOTAL_TRIALS attempts)"
else
echo ">>> Top-up: lane $TOPUP_LANE needs $DEFICIT more valid trial(s); requesting $TOPUP_N (running total: $TRIALS_RUN_TOTAL/$MAX_TOTAL_TRIALS attempts)"
fi
run_lane_batch "(top-up: one or more trials did not achieve reward 1.0 — expected)" "${TALLY_AGENTS[$RUN_LANE]}" "${TALLY_MODELS[$RUN_LANE]}" "$TOPUP_N"
TRIALS_RUN_TOTAL=$((TRIALS_RUN_TOTAL + TOPUP_N))
PREV_COUNTED="$(lanes_pool_counted "$PICK")"
lane_tally_now
lane_status_line
if [ "$RUN_LANE" != "$PICK" ] && [ "$CLASSIFIED_NEW" -gt 0 ] && [ "$NO_ATTEMPT_NEW" -eq "$CLASSIFIED_NEW" ] \
&& [ "$FALLBACK_POS" -lt $((${#FALLBACK_LANE_INDEX[@]} - 1)) ]; then
FALLBACK_POS=$((FALLBACK_POS + 1))
echo ">>> Every trial of that batch produced no usable response; the next fallback model is ${TALLY_MODELS[${FALLBACK_LANE_INDEX[$FALLBACK_POS]}]}."
fi
if [ "$(lanes_pool_counted "$PICK")" -le "$PREV_COUNTED" ]; then
LANE_DRY[$PICK]=$((${LANE_DRY[$PICK]} + 1))
else
LANE_DRY[$PICK]=0
fi
if [ "${LANE_DRY[$PICK]}" -ge "$MAX_CONSECUTIVE_DRY_TOPUPS" ]; then
echo "" >&2
echo "ERROR: ${LANE_DRY[$PICK]} consecutive top-up batches for lane $TOPUP_LANE produced no new valid trials." >&2
echo " This usually means a setup-side problem for that lane (credentials or endpoint, network," >&2
echo " Docker image build failure). Investigate harbor-jobs/ before retrying; the other lanes continue." >&2
LANE_GAVE_UP[$PICK]=1
fi
done
if [ "$VALID" -lt "$MIN_VALID" ]; then
echo "" >&2
echo "WARNING: ended with $VALID/$MIN_VALID valid trials." >&2
i=0
while [ "$i" -lt "${#TALLY_AGENTS[@]}" ]; do
if [ "$(lanes_pool_head "$i")" = "$i" ] && [ "$(lanes_pool_counted "$i")" -lt "${TALLY_QUOTAS[$i]}" ]; then
echo " lane ${TALLY_AGENTS[$i]}=${TALLY_MODELS[$i]}: $(lanes_pool_counted "$i")/${TALLY_QUOTAS[$i]}" >&2
fi
i=$((i + 1))
done
echo " scripts/submit.sh will block until every lane of the latest regular and cheat jobs reaches its quota; rerun with --resume latest to top up." >&2
fi
else
echo ""
echo ">>> Analyze-only: found $VALID / $MIN_VALID valid trials in $JOB_DIR"
lane_status_line
fi
[ -z "$HARBOR_STOP" ] || stop_run 0
STOP_AT_NEXT_BATCH=0
# Aggregate all trial subdirs across all timestamp subdirs (initial run +
# any top-up runs) so the analysis sees every trial.
TRIAL_COUNT=$(find "$JOB_DIR" -maxdepth 2 -type d -name "${TASK_NAME}__*" 2>/dev/null | wc -l | tr -d ' ')
if [ "$TRIAL_COUNT" -eq 0 ]; then
echo "" >&2
echo "ERROR: no trial data found under $JOB_DIR — nothing to analyze." >&2
echo " Expected */${TASK_NAME}__*/ trial directories from harbor run. Check the" >&2
echo " harbor-run-*.log files in the job dir, or rerun once trials exist." >&2
exit 3
fi
write_trial_provenance_file "$INVOCATION_MODE" "$TRIAL_COUNT" "$VALID"
HEADER_AGENT_MODELS="$(provenance_value agent_models)"
HEADER_MAX_OUTPUT_TOKENS="$(provenance_value claude_code_max_output_tokens)"
HEADER_HARBOR_JOB_NAME="$(provenance_value harbor_job_name)"
echo ""
echo "=========================================="
echo "ANALYZING TRAJECTORIES ($TRIAL_COUNT trials)"
echo "=========================================="
# Analysis: rubric as system prompt, Read/Glob/Grep to examine trajectories
# and task files, output streamed to stdout and a markdown file.
ANALYSIS_RUBRIC_PATH="$PROFILE_RUBRICS_DIR/trial-analysis.toml"
ANALYSIS_FILE="$JOB_DIR/trial-analysis.md"
ANALYSIS_RUBRIC_CONTENT="$(cat "$ANALYSIS_RUBRIC_PATH")"
# The criteria (count and per-trial output lines) come from the profile's
# rubric file, so a profile with a different set needs no change here.
ANALYSIS_CRITERIA_COUNT="$(trial_analysis_criteria_count "$ANALYSIS_RUBRIC_PATH")"
ANALYSIS_CRITERIA_LINES="$(render_trial_criteria_lines "$ANALYSIS_RUBRIC_PATH")"
ANALYSIS_USER_PROMPT="You are analyzing agent trial trajectories against the ${ANALYSIS_CRITERIA_COUNT}-criterion analysis rubric in your system prompt. Your CWD is the Harbor job directory. Trial subdirectories are nested one level under timestamped parent dirs — find them all with glob \`*/${TASK_NAME}__*/\`. The original task source lives at: $TASK_ABS (available via --add-dir).
For EACH trial subdirectory found, read:
1. \`<trial>/agent/trajectory.json\` — the agent's action log
2. \`<trial>/verifier/reward.txt\` — the trial's final reward
3. \`<trial>/trial.log\` — trial orchestration log
4. \`<trial>/exception.txt\` if it exists — any infrastructure/agent errors
5. \`<trial>/.user-reject.md\` if it exists — an audit note for a non-substantive slot: worker-authored for an infra/tooling artifact, or written by the toolkit (reject_kind: toolkit, reason: no_attempt) for a cheat trial in which the model produced no usable response
6. Files under $TASK_ABS/ — task definition for context (instruction.md, task.toml, tests/)
Classify agent/tooling artifacts separately from task defects. If a trial is dominated by ExitPlanMode/planning-mode confusion, an unavailable agent tool, a model API/tool-wrapper failure, a worker-authored .user-reject.md artifact, or a Harbor orchestration exception before the agent meaningfully engaged the task, mark the task-facing criteria as N/A where appropriate and say it is an agent/tooling artifact in the evidence. Do not convert those artifacts into failures on the task-facing criteria. User-rejected trials should remain visible in the analysis but must not count as substantive or drive pass-rate conclusions.
For each trial subdirectory, output a markdown section in this exact format:
## <trial-id> — reward: <X.X or missing>
${ANALYSIS_CRITERIA_LINES}
Do not suggest fixes in the per-trial sections.
$(trial_analysis_context "$TRIAL_KIND")
Then end with a single summary line:
**JOB SUMMARY:** N trials, M achieved reward ≥1.0, K exceptions."
write_trial_analysis_header \
"$TASK_NAME" \
"$(date '+%Y-%m-%d %H:%M:%S %Z')" \
"$JOB_DIR_REL" \
"$TASK_SOURCE_REL" \
"$TRIAL_COUNT" \
"$TRIAL_KIND" \
"$HEADER_AGENT_MODELS" \
"$TRIAL_ANALYSIS_MODEL" \
"$TRIAL_ANALYSIS_EFFORT" \
"$HEADER_MAX_OUTPUT_TOKENS" \
"$JOB_DIR_REL/trial-provenance.env" \
"$HEADER_HARBOR_JOB_NAME" \
"$ANALYSIS_CRITERIA_COUNT" > "$ANALYSIS_FILE"
(cd "$JOB_DIR" && claude --print \
--model "$TRIAL_ANALYSIS_MODEL" \
--effort "$TRIAL_ANALYSIS_EFFORT" \
--allowed-tools "Read,Glob,Grep" \
--add-dir "$TASK_ABS" \
--append-system-prompt "$ANALYSIS_RUBRIC_CONTENT" \
"$ANALYSIS_USER_PROMPT") | tee -a "$ANALYSIS_FILE"
# --- Job-level summary (aggregates across per-trial analyses) ---
echo ""
echo "=========================================="
echo "JOB SUMMARY"
echo "=========================================="
JOB_PROMPT_PATH="$ANALYSIS_JOB_PROMPT"
SUMMARY_FILE="$JOB_DIR/job-summary.md"
JOB_PROMPT_TEMPLATE="$(cat "$JOB_PROMPT_PATH")"
TRIAL_RESULTS="$(cat "$ANALYSIS_FILE")"
JOB_PROMPT_WITH_RESULTS="$(render_job_prompt "$JOB_PROMPT_TEMPLATE" "$TRIAL_RESULTS")"
JOB_USER_PROMPT="$(build_job_user_prompt "$TRIAL_KIND" "$JOB_PROMPT_WITH_RESULTS")"
write_job_summary_header \
"$TASK_NAME" \
"$(date '+%Y-%m-%d %H:%M:%S %Z')" \
"$JOB_DIR_REL" \
"$TRIAL_KIND" \
"$HEADER_AGENT_MODELS" \
"$TRIAL_ANALYSIS_MODEL" \
"$TRIAL_ANALYSIS_EFFORT" \
"$TRIAL_SUMMARY_MODEL" \
"$TRIAL_SUMMARY_EFFORT" \
"$HEADER_MAX_OUTPUT_TOKENS" \
"$JOB_DIR_REL/trial-provenance.env" \
"$HEADER_HARBOR_JOB_NAME" > "$SUMMARY_FILE"
claude --print --model "$TRIAL_SUMMARY_MODEL" --effort "$TRIAL_SUMMARY_EFFORT" "$JOB_USER_PROMPT" | tee -a "$SUMMARY_FILE"
echo ""
echo "=========================================="
echo "Trial results in: $JOB_DIR"
echo "Analysis saved to: $ANALYSIS_FILE"
echo "Job summary: $SUMMARY_FILE"
echo "=========================================="
if [ "${CHEAT_TRIAL_DELEGATED:-}" != "1" ]; then
echo ""
echo "Next: scripts/cheat-trial.sh $TASK_PATH (or scripts/submit.sh when trials look right)"
fi