#!/usr/bin/env bash
# Runs headless verification journeys and the map-load suite.
#
#   tools/verification/run-verification                 build, then run the acceptance journeys
#   tools/verification/run-verification placement      run journeys whose names contain "placement"
#   tools/verification/run-verification --maps         load every catalogue map
#   tools/verification/run-verification --perf NAME    record one journey with perf
#   tools/verification/run-verification --tracy NAME   capture one journey with Tracy
#
# Journeys check behaviour, so they use the incremental dev build, which rebuilds in
# seconds after an edit. --profiling uses the optimised profiling build instead. --perf,
# --tracy and the timing journeys marked `# run-alone` need it, so dev runs skip those.
#
# The selected journeys run back to back in one game, which moves between their `start`
# places through its own UI. A navigation failure stops that batch; unreached journeys
# are reported as NOT RUN rather than retried through another game startup.
# Populated save/load follows reversible Freeform work in the same map.
# `# diagnostic` journeys run only when explicitly selected by name.
#
# Options: --no-build, --profiling, --jobs N (map loads at once, default 1), --windowed,
# --budget SECONDS (wall time for the whole game, default 300; unreached journeys are NOT RUN).
# A journey also fails, and the batch moves on, when its frame rate stays below 10 per second.
# --capture-ready waits for UI layout, assets and rendering instead of a 30-frame minimum.
# --capture-full retains that minimum (default); both modes render every simulation tick.
# With --no-build, $OPENZT2_VERIFICATION_BINARY names a prebuilt game binary instead.
# An explicit binary and OPENZT2_Z2F_PATH use the supplied runtime without direnv.
# Results go to $OPENZT2_VERIFICATION_OUTPUT (default /tmp/openzt2-verification)/<timestamp>/,
# with a `latest` link beside it. Each run writes summary.txt (results and the captures
# to review) and status (the exit code), so it can run unattended and be reviewed later.
#
# Each game instance needs several GB of memory, so a game starts only when
# $OPENZT2_VERIFICATION_MINIMUM_FREE_MEMORY_GIB (default 6) is available, and builds
# refuse to start below 15% free disk. Only the five newest result folders are kept.
set -uo pipefail

# Internal group leader: completion does not release the group identity until
# its parent has finished cleanup. Payloads explicitly restore signal defaults;
# the leader ignores signals so TERM grace cannot release its group identity.
if [[ ${1:-} == --owned-command-anchor ]]; then
    shift
    event_fd=$1 control_fd=$2 trace_file=$3 command_directory=$4
    shift 4
    trap '' INT TERM HUP
    printf 'ready %s\n' "$BASHPID" >&"$event_fd"
    read -r -u "$control_fd" start && [[ $start == start ]] || exit 125
    if [[ -n $trace_file ]]; then
        (
            exec {event_fd}>&-
            exec {control_fd}>&-
            cd "$command_directory" || exit 125
            exec env --default-signal=INT,TERM,HUP \
                nix shell nixpkgs#tracy -c tracy-capture -f -o "$trace_file") \
            >"${trace_file%/*}/tracy-capture.log" 2>&1 &
    fi
    (
        exec {event_fd}>&-
        exec {control_fd}>&-
        cd "$command_directory" || exit 125
        exec env --default-signal=INT,TERM,HUP "$@") &
    command_pid=$!
    wait "$command_pid"
    printf 'finished %s\n' "$?" >&"$event_fd"
    read -r -u "$control_fd" release
    wait || true
    exit 0
fi

# Run as a process-group leader for the runner's command supervisors.
# The group comes from /proc: a dev shell's `ps` can fail to start on hosts with
# an older glibc. The group is the third field after the command's closing parenthesis.
process_stat=$(</proc/$$/stat) || { echo "cannot read /proc/$$/stat"; exit 1; }
read -r _ _ process_group _ <<<"${process_stat##*) }"
if [[ ! $process_group =~ ^[0-9]+$ ]]; then
    echo "cannot read this run's process group from /proc/$$/stat"
    exit 1
fi
if [[ $process_group != "$$" ]]; then
    [[ ${OPENZT2_VERIFICATION_SETSID:-} == 1 ]] && { echo "setsid did not make this run a process-group leader"; exit 1; }
    OPENZT2_VERIFICATION_SETSID=1 exec setsid "$0" "$@"
fi
cleanup_scope=$(mktemp -d "${TMPDIR:-/tmp}/openzt2-run-cleanup.XXXXXX") || exit 1
runner_script=$(realpath "${BASH_SOURCE[0]}")

# Finite snapshots at teardown boundaries, not a liveness polling loop. The
# live leader reserves the group ID while signals are sent. Never signal PIDs
# read from /proc: those individual PIDs could already have been reused.
snapshot_verification_group() {
    local group=$1 exclude=$2 stat_file stat_data state parent pgid session
    group_members=()
    for stat_file in /proc/[0-9]*/stat; do
        [[ $stat_file == /proc/$exclude/stat ]] && continue
        { stat_data=$(<"$stat_file"); } 2>/dev/null || continue
        read -r state parent pgid session _ <<<"${stat_data##*) }"
        if [[ $pgid == "$group" && $session == "$group" && $state != Z ]]; then
            local member=${stat_file#/proc/}
            group_members+=("${member%/stat}")
        fi
    done
}

stop_every_game_in_this_run() {
    local original_status=$? cleanup_status=0 cleanup_log
    trap - EXIT
    trap '' INT TERM HUP
    if [[ -n ${output_root:-} ]]; then
        printf '%s\n' "$original_status" >"$output_root/original.status"
    fi
    cleanup_log="${output_root:-$cleanup_scope}/cleanup.log"
    snapshot_verification_group "$$" "$$"
    if ((${#group_members[@]})) && ((original_status != 130 && original_status != 143)); then
        # Give the summary writer time to drain its closed pipe on normal exit.
        sleep 1 &
        wait $!
        snapshot_verification_group "$$" "$$"
    fi
    if ((${#group_members[@]})); then
        # Command supervisors receive TERM too and finish their private groups'
        # bounded cleanup. Keep this leader alive until that grace has expired.
        kill -TERM -- -$$ 2>/dev/null || true
        sleep 8 &
        wait $!
        snapshot_verification_group "$$" "$$"
        if ((${#group_members[@]})); then
            printf 'remaining runner group members: %s\n' "${group_members[*]}" >>"$cleanup_log"
            printf 'incomplete runner cleanup: remaining group members %s\n' \
                "${group_members[*]}" >&2
            cleanup_status=1
        else
            wait || true
        fi
    fi
    local pending
    for pending in "$cleanup_scope"/command.*/pending; do
        if [[ -f $pending ]]; then
            printf 'unclosed command ownership: %s\n' "${pending%/pending}" >>"$cleanup_log"
            cleanup_status=1
        fi
    done
    [[ -f $cleanup_scope/incomplete ]] && cleanup_status=1
    if ((cleanup_status != 0)); then
        printf 'incomplete cleanup; ownership evidence: %s\n' "$cleanup_scope" >>"$cleanup_log"
        printf 'incomplete cleanup; ownership evidence retained in %s\n' "$cleanup_scope" >&2
    fi
    if [[ -n ${output_root:-} ]]; then
        printf '%s\n' "$cleanup_status" >"$output_root/cleanup.status"
        if ((cleanup_status != 0 && original_status == 0)); then original_status=1; fi
        printf '%s\n' "$original_status" >"$output_root/status"
    elif ((cleanup_status != 0 && original_status == 0)); then
        original_status=1
    fi
    if ((cleanup_status == 0)); then rm -rf -- "$cleanup_scope"; fi
    exit "$original_status"
}
trap stop_every_game_in_this_run EXIT
trap 'exit 130' INT
trap 'exit 143' TERM HUP

# Each invocation of this function owns one private, anchored process group.
# Its EXIT trap runs before the caller can launch another game.
run_owned_verification_command() (
    trap - EXIT
    trap 'exit 130' INT
    trap 'exit 143' TERM HUP
    local directory=$1 trace_file=$2 deadline=$3
    shift 3
    [[ ! -f $cleanup_scope/incomplete ]] || return 125
    [[ -n $directory ]] || directory="$cleanup_scope/build"
    mkdir -p "$directory" || return 125
    rm -f -- "$directory/cleanup.status" "$directory/command.status"
    local control_directory event_fd control_fd anchor_pid="" anchored=false
    control_directory=$(mktemp -d "$cleanup_scope/command.XXXXXX") || return 125
    : >"$control_directory/pending"
    mkfifo "$control_directory/events" "$control_directory/control" || return 125
    exec {event_fd}<>"$control_directory/events"
    exec {control_fd}<>"$control_directory/control"

    finish_owned_verification_command() {
        local original_status=$? cleanup_status=0 timer_pid completed stat_data state
        trap - EXIT
        trap '' INT TERM HUP
        printf '%s\n' "$original_status" >"$directory/command.status"
        if $anchored; then
            # Tracy normally finishes when the game disconnects. Allow its final
            # write before applying the same bounded cleanup to the whole group.
            if [[ -n $trace_file ]]; then
                sleep 2 &
                wait $!
            fi
            snapshot_verification_group "$anchor_pid" "$anchor_pid"
            if ((${#group_members[@]})); then
                printf 'TERM group=%s members=%s\n' "$anchor_pid" "${group_members[*]}" \
                    >>"$directory/cleanup.log"
                kill -TERM -- -"$anchor_pid" 2>/dev/null || true
                sleep 3 &
                wait $!
                snapshot_verification_group "$anchor_pid" "$anchor_pid"
            fi
            if ((${#group_members[@]})); then
                # The anchor has not been released: this group cannot be reused
                # by an unrelated command during TERM grace or this escalation.
                printf 'KILL group=%s members=%s\n' "$anchor_pid" "${group_members[*]}" \
                    >>"$directory/cleanup.log"
                kill -KILL -- -"$anchor_pid" 2>/dev/null || true
            else
                printf 'release\n' >&"$control_fd"
            fi
        else
            # No payload can start without the validated START handshake.
            printf 'cancel\n' >&"$control_fd"
            printf 'group ownership handshake failed; command canceled; no group signal sent\n' \
                >>"$directory/cleanup.log"
            cleanup_status=1
        fi
        if [[ -n $anchor_pid ]]; then
            # Reap our leader by completion, with a timer bounding even a stuck
            # kernel task. The timer sends no signals and cannot target a reused PID.
            sleep 2 &
            timer_pid=$!
            completed=""
            wait -n -p completed "$anchor_pid" "$timer_pid" || true
            if [[ ${completed:-} != "$anchor_pid" ]]; then
                # wait -n can omit a child that completed before the call. Reap
                # it only when its kernel task has exited; never block on a live one.
                if stat_data=$(</proc/$anchor_pid/stat) 2>/dev/null; then
                    read -r state _ <<<"${stat_data##*) }"
                    if [[ $state == Z ]]; then
                        wait "$anchor_pid" || true
                    else
                        cleanup_status=1
                    fi
                else
                    wait "$anchor_pid" || true
                fi
            fi
            wait "$timer_pid" || true
        fi
        if $anchored; then
            snapshot_verification_group "$anchor_pid" "$anchor_pid"
            ((${#group_members[@]} == 0)) || cleanup_status=1
            printf 'cleanup=%s group=%s remaining=%s\n' "$cleanup_status" "$anchor_pid" \
                "${group_members[*]}" >>"$directory/cleanup.log"
        fi
        printf '%s\n' "$cleanup_status" >"$directory/cleanup.status"
        if ((cleanup_status != 0)); then
            : >"$cleanup_scope/incomplete"
            printf 'incomplete command cleanup: %s; refusing further commands\n' "$directory" >&2
            ((original_status == 0)) && original_status=125
        else
            rm -f -- "$control_directory/pending"
        fi
        exit "$original_status"
    }
    trap finish_owned_verification_command EXIT
    trap 'exit 130' INT
    trap 'exit 143' TERM HUP
    set +m
    setsid "$runner_script" --owned-command-anchor "$event_fd" "$control_fd" \
        "$trace_file" "$repository" "$@" &
    anchor_pid=$!
    printf '%s\n' "$anchor_pid" >"$control_directory/leader"
    local kind value stat_data state parent pgid session
    read -r -t 5 -u "$event_fd" kind value || exit 125
    [[ $kind == ready && $value == "$anchor_pid" ]] || exit 125
    stat_data=$(</proc/$anchor_pid/stat) || exit 125
    read -r state parent pgid session _ <<<"${stat_data##*) }"
    [[ $pgid == "$anchor_pid" && $session == "$anchor_pid" ]] || exit 125
    anchored=true
    printf 'start\n' >&"$control_fd"
    if ((deadline > 0)); then
        read -r -t "$((deadline + 5))" -u "$event_fd" kind value || exit 124
    else
        read -r -u "$event_fd" kind value || exit 125
    fi
    [[ $kind == finished && $value =~ ^[0-9]+$ && $value -le 255 ]] || exit 125
    exit "$value"
)

repository=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
journey_directory="$repository/tools/verification/journeys"
build=true
jobs=1
maps=false
windowed=false
profiler=none
profile=dev
capture_mode=full
budget=300
filters=()

while (($#)); do
    case "$1" in
        --no-build) build=false ;;
        --jobs) jobs=$2; shift ;;
        --budget) budget=$2; shift ;;
        --maps) maps=true ;;
        --windowed) windowed=true ;;
        --profiling) profile=profiling ;;
        --capture-ready) capture_mode=ready ;;
        --capture-full) capture_mode=full ;;
        --perf) profiler=perf; profile=profiling ;;
        --tracy) profiler=tracy; profile=profiling ;;
        -h|--help) sed -n '2,/^set /p' "$0" | sed -n 's/^# \{0,1\}//p'; exit 0 ;;
        *) filters+=("$1") ;;
    esac
    shift
done

# Deployment hosts supply their binary, content and runtime libraries. Development
# runs activate direnv once; games load Vulkan and audio from that environment.
if ! $build && [[ -n ${OPENZT2_VERIFICATION_BINARY:-} && -n ${OPENZT2_Z2F_PATH:-} ]]; then
    executable=$OPENZT2_VERIFICATION_BINARY
else
    development_environment=$(cd "$repository" && direnv export bash) || exit 1
    eval "$development_environment" || exit 1
    if [[ -z ${CARGO_TARGET_DIR:-} || -z ${OPENZT2_Z2F_PATH:-} ]]; then
        echo "the development environment did not load; run direnv allow in $repository"
        exit 1
    fi
    if [[ $profile == dev ]]; then executable="$CARGO_TARGET_DIR/debug/openzt2"; else executable="$CARGO_TARGET_DIR/profiling/openzt2"; fi
    executable=${OPENZT2_VERIFICATION_BINARY:-$executable}
fi
if $build; then
    target_directory=$CARGO_TARGET_DIR
    mkdir -p "$target_directory"
    free_disk_percent=$(df --output=pcent "$target_directory" | tail -1 | tr -dc '0-9')
    if ((100 - free_disk_percent < 15)); then
        echo "refusing to build: $target_directory has less than 15% free disk"
        exit 1
    fi
    features=()
    [[ $profiler == tracy ]] && features=(--features trace-tracy-gpu)
    # Keep build children under the same bounded cleanup as game children.
    if [[ $profile == dev ]]; then
        run_owned_verification_command "" "" 0 \
            cargo build -p openzt2_game "${features[@]}" &
    else
        run_owned_verification_command "" "" 0 \
            cargo build --profile profiling -p openzt2_game "${features[@]}" &
    fi
    wait $!
    build_status=$?
    ((build_status == 0)) || exit "$build_status"
fi
[[ -x $executable ]] || { echo "verification binary is not executable: $executable"; exit 1; }

output_parent="${OPENZT2_VERIFICATION_OUTPUT:-/tmp/openzt2-verification}"
output_root="$output_parent/$(date +%Y%m%d-%H%M%S)"
mkdir -p "$output_root"
ln -sfn "$output_root" "$output_parent/latest"
find "$output_parent" -mindepth 1 -maxdepth 1 -type d -name '[0-9]*-[0-9]*' \
    | sort | head -n -5 | xargs -r rm -rf
# Headless games open no audio device. ALSA's null device accepts samples without
# pacing, so the mixer would spin a whole core; an absent device stops playback.
printf 'pcm.!default { type hw card 99 }\nctl.!default { type hw card 99 }\n' >"$output_root/asound-none.conf"
export ALSA_CONFIG_PATH="$output_root/asound-none.conf"
export NO_COLOR=1
export RUST_LOG="${RUST_LOG:-warn,openzt2_verification=info,openzt2_map_load_suite=info}"
minimum_free_memory_gib="${OPENZT2_VERIFICATION_MINIMUM_FREE_MEMORY_GIB:-6}"

# Waits up to ten minutes for enough free memory to start another game.
wait_for_free_memory() {
    local required_kib=$((minimum_free_memory_gib * 1024 * 1024))
    local attempt
    for attempt in $(seq 120); do
        (($(awk '/^MemAvailable:/ {print $2}' /proc/meminfo) >= required_kib)) && return 0
        sleep 5
    done
    echo "not enough free memory: ${minimum_free_memory_gib} GiB not available after ten minutes"
    return 1
}

journey_name() { basename "$1" .journey; }

# Reversible Freeform work shares one map, followed by populated save/load and
# habitat work. The next distinct map is Small Alpine, then budgeted Challenge,
# then the tutorial. A filtered subset keeps the same relative order.
journey_order_key() {
    local journey=$1 start rank name
    name=$(journey_name "$journey")
    start=$(sed -E 's/#.*//' "$journey" | awk '$1 == "start" { $1 = ""; sub(/^ /, ""); print; exit }')
    case "$start" in
        boot) rank=0 ;;
        main-menu) rank=1 ;;
        *freeform-map) rank=3 ;;
        *challenge-map) rank=6 ;;
        *) rank=9 ;;
    esac
    case "$name" in
        save-dialog-cancel) rank=2 ;;
        populated-zoo) rank=4 ;;
        first-person-map-bounds) rank=5 ;;
        catalogue-research) rank=7 ;;
        campaign-scenario-list) rank=8 ;;
    esac
    printf '%02d %s\n' "$rank" "$name"
}

# Writes each journey result. Forbidden loader errors invalidate the entire game log,
# including navigation, even when the boot journey was not selected.
# Each journey's section runs from the end of the previous journey to the end of its own.
record_journey_result() {
    local journey=$1 game_log=$2 section=$3 exit_note=$4
    local name output
    name=$(journey_name "$journey")
    output="$output_root/$name"
    cp "$section" "$output/game.log"
    local failed=false
    if [[ ! -f $output/report.json ]] || ! grep -q '"passed": true' "$output/report.json"; then
        failed=true
    fi
    local log_failures=""
    while IFS= read -r pattern; do
        if grep -a -q -F -- "$pattern" "$game_log"; then
            log_failures+="        log contains: $pattern"$'\n'
            failed=true
        fi
    done < <(sed -n -E 's/^expect-log-absent[[:space:]]+"(.*)"[[:space:]]*(#.*)?$/\1/p' "$journey_directory"/*.journey | sort -u)
    {
        if ! $failed; then
            printf 'PASS  %s\n' "$name"
        else
            printf 'FAIL  %s%s\n' "$name" "${exit_note:+ ($exit_note)}"
            grep -a 'verification failure' "$output/game.log" \
                | sed -E 's/.*verification failure location=([^ ]+) detail=(.*)$/        \1: \2/' \
                | head -20
            grep -a -m3 'panicked' "$output/game.log" | grep -v 'main.rs' | sed 's/^/        /'
            printf '%s' "$log_failures"
        fi
    } >"$output/summary"
    $failed && return 1
    return 0
}

# Runs one batch in one game. A broken route blocks the remaining journeys.
run_journeys_in_one_game() {
    local game_index=$1
    shift
    local journeys=("$@") journey
    local game_directory="$output_root/games/$game_index"
    mkdir -p "$game_directory/tmp"
    local command=("$executable") failed=0
    for journey in "${journeys[@]}"; do
        command+=(--verify-journey "$journey")
    done
    command+=(--verification-output "$output_root")
    command+=(--verification-capture-mode "$capture_mode")
    command+=(--verification-budget-seconds "$budget")
    [[ $windowed == true ]] && command+=(--verification-windowed)
    if ! wait_for_free_memory; then
        for journey in "${journeys[@]}"; do
            local name
            name=$(journey_name "$journey")
            mkdir -p "$output_root/$name"
            printf 'FAIL  %s (not started)\n' "$name" >"$output_root/$name/summary"
        done
        return 1
    fi
    local trace_file=""
    case "$profiler" in
        perf) command=(perf record -g -F 499 -o "$game_directory/perf.data" -- "${command[@]}") ;;
        tracy) trace_file="$game_directory/trace.tracy" ;;
    esac
    local game_log="$game_directory/game.log" game_started=$SECONDS
    # The game stops itself at its budget; this deadline only catches a hung game.
    local deadline=$((budget + 120))
    run_owned_verification_command "$game_directory" "$trace_file" "$deadline" \
        env TMPDIR="$game_directory/tmp" timeout --foreground "$deadline" \
        "${command[@]}" >"$game_log" 2>&1
    local status=$?
    if [[ ! -f $game_directory/cleanup.status ]] || [[ $(<"$game_directory/cleanup.status") != 0 ]]; then
        : >"$cleanup_scope/incomplete"
    fi
    if ((status != 0)); then
        failed=1
        printf 'FAIL  game %s exited %s; see %s\n' "$game_index" "$status" "$game_log"
    fi
    printf 'game %s: %s journeys, exit %s, %sm %ss\n' "$game_index" "${#journeys[@]}" "$status" \
        $(((SECONDS - game_started) / 60)) $(((SECONDS - game_started) % 60)) >>"$output_root/games/list"
    # Name navigation evidence after its game, so a later game cannot replace it.
    local evidence
    for evidence in "$output_root"/*/navigation-failure.png; do
        [[ -f $evidence ]] && mv "$evidence" "${evidence%.png}-game$game_index.png"
    done
    # Split the log at each finished journey.
    local sections="$game_directory/sections"
    mkdir -p "$sections"
    awk -v directory="$sections" '
        { print > (directory "/current") }
        /verification journey finished journey=/ {
            match($0, /journey=[^ ]+/)
            close(directory "/current")
            system("mv \"" directory "/current\" \"" directory "/" substr($0, RSTART + 8, RLENGTH - 8) "\"")
        }' "$game_log"
    touch "$sections/current"
    local index
    for index in "${!journeys[@]}"; do
        journey=${journeys[index]}
        local name
        name=$(journey_name "$journey")
        if [[ -f $sections/$name ]]; then
            record_journey_result "$journey" "$game_log" "$sections/$name" "" \
                || failed=1
            continue
        fi
        if grep -a -q 'second budget after' "$game_log"; then
            local unreached
            for unreached in "${journeys[@]:index}"; do
                local unreached_name
                unreached_name=$(journey_name "$unreached")
                mkdir -p "$output_root/$unreached_name"
                printf 'NOT RUN  %s (the %s-second budget ran out)\n' "$unreached_name" "$budget" \
                    >"$output_root/$unreached_name/summary"
            done
            failed=1
            break
        fi
        # Do not repeat a broken shared route once per remaining journey.
        record_journey_result "$journey" "$game_log" "$sections/current" \
            "interrupted, exit $status" || failed=1
        grep -a 'verification navigation failure' "$game_log" | tail -1 \
            | sed -E 's/.*detail=(.*)$/        \1/' >>"$output_root/$name/summary"
        local blocked
        for blocked in "${journeys[@]:index+1}"; do
            local blocked_name
            blocked_name=$(journey_name "$blocked")
            mkdir -p "$output_root/$blocked_name"
            printf 'NOT RUN  %s (batch stopped at %s; see games/%s/game.log)\n' \
                "$blocked_name" "$name" "$game_index" >"$output_root/$blocked_name/summary"
        done
        failed=1
        break
    done
    return "$failed"
}

run_one_map_load() {
    local index=$1 output=$2
    local log="$output/maps/$index.log"
    wait_for_free_memory || { printf 'FAIL  map %3s  (not started)\n' "$index"; return 1; }
    run_owned_verification_command "$output/maps/$index" "" 300 \
        timeout --foreground 300 "$executable" --verify-map-load "$index" >"$log" 2>&1
    local status=$?
    if [[ ! -f $output/maps/$index/cleanup.status ]] || [[ $(<"$output/maps/$index/cleanup.status") != 0 ]]; then
        : >"$cleanup_scope/incomplete"
    fi
    local detail
    if ((status == 0)) && grep -a 'map_load_result=completed' "$log" \
        | grep -q 'successful=true'; then
        detail=$(grep -a -m1 -o 'load_seconds=[0-9.]*' "$log" | sed 's/load_seconds=/loaded in /; s/$/ s/')
        printf 'PASS  map %3s  %s\n' "$index" "$detail"
    else
        ((status == 0)) && status=1
        detail=$(grep -a -o 'reason: [A-Za-z]*\|unresolved_joint_attachments=[1-9][0-9]*\|Caught rendering error\|map_load_result=timeout' "$log" | head -1)
        printf 'FAIL  map %3s  exit %s  %s\n' "$index" "$status" "${detail:-see $log}"
        grep -a 'Failed to load asset' "$log" | sed -E "s/.*Failed to load asset '([^']*)'.*: ([^:]*)$/        \1: \2/" | sort -u | head -5
    fi
    return "$status"
}
export -f wait_for_free_memory run_one_map_load run_owned_verification_command snapshot_verification_group
export executable repository minimum_free_memory_gib cleanup_scope runner_script

# Each selected batch owns one game; isolated diagnostics receive their own batch.
run_journeys() {
    mkdir -p "$output_root/games"
    local game_index=1
    if [[ -f $output_root/games/list ]]; then
        game_index=$(( $(wc -l <"$output_root/games/list") + 1 ))
    fi
    run_journeys_in_one_game "$game_index" "$@"
}

run_selected_verification() {
    local failed=0 started=$SECONDS
    if $maps; then
        mkdir -p "$output_root/maps"
        run_one_map_load 0 "$output_root" || failed=1
        [[ ! -f $cleanup_scope/incomplete ]] || return 1
        local map_count
        map_count=$(grep -a -m1 -o 'map_count=[0-9]*' "$output_root/maps/0.log" | cut -d= -f2)
        if [[ -z $map_count ]]; then
            echo "could not read the map count from $output_root/maps/0.log"
            return 1
        fi
        seq 1 $((map_count - 1)) \
            | xargs -P "$jobs" -I{} bash -c 'run_one_map_load "$1" "$2"' _ {} "$output_root" \
            || failed=1
    else
        local journeys=() journey name filter
        for journey in "$journey_directory"/*.journey; do
            name=$(journey_name "$journey")
            if ((${#filters[@]} == 0)); then
                grep -q '^# diagnostic:' "$journey" && continue
                journeys+=("$journey")
            else
                for filter in "${filters[@]}"; do
                    [[ $name == *"$filter"* ]] && journeys+=("$journey") && break
                done
            fi
        done
        if ((${#journeys[@]} == 0)); then
            echo "no journeys matched: ${filters[*]}"
            return 1
        fi
        # Journeys marked `# run-alone` measure timing, so each gets its own game afterwards.
        local together=() alone=()
        for journey in "${journeys[@]}"; do
            if ! grep -q '^# run-alone' "$journey"; then
                together+=("$journey")
            elif [[ $profile == profiling ]]; then
                alone+=("$journey")
            else
                printf 'SKIP  %s (timing journey; needs --profiling)\n' "$(journey_name "$journey")"
            fi
        done
        if ((${#together[@]})); then
            mapfile -t together < <(
                for journey in "${together[@]}"; do
                    printf '%s %s\n' "$(journey_order_key "$journey")" "$journey"
                done | sort | cut -d' ' -f3-
            )
            run_journeys "${together[@]}" || failed=1
        fi
        for journey in "${alone[@]}"; do
            [[ ! -f $cleanup_scope/incomplete ]] || { failed=1; break; }
            run_journeys "$journey" || failed=1
        done
        local results=0
        for journey in "${journeys[@]}"; do
            name=$(journey_name "$journey")
            if [[ -f $output_root/$name/summary ]]; then
                cat "$output_root/$name/summary"
                results=$((results + 1))
            fi
        done
        if ((results == 0)); then
            echo "FAIL: no journey produced a result"
            failed=1
        fi
        echo
        cat "$output_root/games/list" 2>/dev/null
        local reloads
        reloads=$(cat "$output_root"/games/*/game.log | grep -a -c 'in-map reset fell back')
        printf 'map reloads after an in-map reset: %s\n' "$reloads"
        echo
        echo "captures to review:"
        find "$output_root" -name '*.png' | sort | sed 's/^/    /'
    fi
    printf 'elapsed: %sm %ss\n' $(((SECONDS - started) / 60)) $(((SECONDS - started) % 60))
    return "$failed"
}

# Run in the background and wait, so a signal reaches the trap straight away.
(trap - EXIT
    trap 'exit 130' INT
    trap 'exit 143' TERM HUP
    run_selected_verification) > >(tee "$output_root/summary.txt") 2>&1 &
wait $!
status=$?
echo "$status" >"$output_root/status"
echo "results: $output_root (exit $status)"
exit "$status"
