#!/bin/sh
# SPDX-License-Identifier: Apache-2.0
#
# lights-out: gates, init, triage, post mortem, state reporting, and opt-in
# plane/workflow orchestration on any repository from the published image,
# with no clone of lights-out (docs/adr/0045, docs/adr/0105). The host needs
# a container engine (podman or docker) and git, nothing else.
#
# Read-only & gates (socket-free by default; --engine or LIGHTS_OUT_ENGINE_GATES=1 opts into engine socket for custom/compose toolchains):
#   lights-out init [--engine] [--apply [--branch <name>] [--commit] [--force]] [--workspace] [--baseline-mode full|incremental] [--baseline-max-files <n>] [HEAD=]  draft .lights-out/ for this repository (or apply directly with --apply)
#   lights-out genesis --brief <text> [--stack <stack>] [--port <n>] [--no-commit]  scaffold a greenfield repository (/repo:rw with stderr notice)
#   lights-out gates [--engine] [BASE= HEAD=]      judge the last commit, or a range; STAGED=1 judges what is staged;
#                                                  JUDGED="<sha> ..." names trees already judged, whose lines mutation skips (docs/adr/0074)
#   lights-out test-proof [--engine] [BASE= HEAD=]     only test and test-proof: the tests a change adds fail on its base
#   lights-out test-integrity [--engine] [BASE= HEAD=] only test-weakening and mutation: no test weakened, mutants killed
#   lights-out adr-check [--engine] [BASE= HEAD=]      judge ADR lifecycle compliance against policy (ADR 0115)
#   lights-out migration-safety [--engine] [BASE= HEAD=] judge database migration expand/contract safety (ADR 0123)
#   lights-out triage ALERT=<file>      an alert in, an incident out (PROFILE=l1 and a key on your alerts)
#   lights-out postmortem INCIDENT=<file>   an incident document in, a post mortem and tickets out
#   lights-out doctor                   engine, image, key: one line each, then GO or NO-GO
#   lights-out version                  wrapper version and images (or --version)
#   lights-out completion bash|zsh|fish print a shell completion script (no engine, docs/adr/0112)
#   lights-out map [MAP_FILE=]          build the project map of this repository
#
# State-only (socket-free, mounts $LIGHTS_OUT_OUT/crew -> /opt/lights-out/.crew):
#   lights-out next [MODE=junior|expert] [--json]       inspect repo, contract and state; print next E2E command
#   lights-out dora [WINDOW_DAYS=30]                    compute the four DORA measures from the logbook
#   lights-out spend                                    cost and time per ticket, role and day
#   lights-out cloud-setup CLOUD=<provider>             stage Terraform + OIDC starter into crew state
#   lights-out network [TICKET= ATTEMPT=]               one ticket's agent network in text
#   lights-out scoreboard                               per provider and harness: first-attempt merges, reworks, cost
#   lights-out auto-incident [RELEASE_RECORD=]          incident document from a rolled-back release record
#   lights-out incident NAME= FROM= TO= [LOGS=]         incident document from the release record (TICKET= needs the plane)
#   lights-out alert-webhook ALERT_FILE=<path>          normalize an alert JSON file in the repository
#   lights-out top [LOGBOOK_FILE= URL= ONCE=1 --json]   interactive terminal cockpit over the logbook (ADR 0114)
#   lights-out epics <create|status|unblock|workspace>  manage multi-ticket epic DAGs and monorepo workspaces (ADR 0119)
#   lights-out spec-split <check|split|compose> <file>  autonomous ## Network spec-split planner and validator (ADR 0120)
#   lights-out m24-check [evaluate|ingest-logbook ...]  deterministic M24 benchmark evaluator and logbook ingester (ADR 0120)
#   lights-out demo-loop [run] [--out DIR] [--budget S] closed deterministic L0 self-healing demo loop (ADR 0132)
#   lights-out jury <select-env|inspect> [flags]        cross-provider jury reviewer selection and inspection (ADR 0130)
#   lights-out map-brief-eval [flags]                   measure MAP_BRIEF=off vs MAP_BRIEF=on brief footprint (ADR 0054)
#   lights-out live-preflight [--strict] [flags]        non-destructive live L1/CodeHost/Cloud readiness audit
#   lights-out thresholds [JSON=1] [--no-git]           audit effective policy/role thresholds, provenance, and overrides (ADR 0135)
#   lights-out reviewer-eval [--mode replay|live] [flags] labeled-diff reviewer & gate catch-rate evaluation (ADR 0137)
#   lights-out portfolio [--repos <p1,p2>] [flags]      read-only multi-repo fleet portfolio overview (ADR 0138)
#
# Opt-in plane & workflow (mounts engine socket with stderr notice, host-mirrored $LIGHTS_OUT_OUT/platform):
#   lights-out start [--non-interactive ...]            guided setup wizard or preset plan
#   lights-out intake [TICKET=] TEXT=<text>             start an intake interview
#   lights-out answer TICKET=<id> ANSWER=<text>         answer an intake or ticket question
#   lights-out intake-confirm TICKET=<id> DECISIONS=... confirm, edit or drop proposed intake tickets
#   lights-out assign TICKET=<id>                       turn a ticket into a PR
#   lights-out up                                       start the L0 compose plane and publish stable image
#   lights-out down                                     stop the compose plane
#   lights-out smoke                                    run the workload's smoke path through the edge
#   lights-out release [CANARY_VERSION= CANARY_TAG=]    deploy canary and run SLO verification controller
#   lights-out promote [GO_FOR_LAUNCH=GO|NO-GO REASON=] go-for-launch brief and human promotion gate
#   lights-out try                                      draft the contract and judge the last commit, keep the draft
#   lights-out watch [ONCE=1] [POLL_S=<sec>] [RUNNER_WORKERS=<1..8>]  continuous tower orchestrator draining the event bus
#   lights-out request TICKET=<id> [REQUEST_BY=]        start a ticket at requested
#   lights-out resume TICKET=<id>                       request again the step a ticket failed
#   lights-out audit TICKET=<id>                        rebuild the chain deploy to spec from the state store
#   lights-out production-readiness                     GO only with a conformant delivery, metrics and a human gate
#   lights-out console                                  serve the console on CONSOLE_PUBLISH:CONSOLE_PORT (default 127.0.0.1:8098)
#   lights-out evidence VERSION=<v>                     build, sign and verify release evidence pack
#   lights-out provenance [VERSION= TICKET= PROVENANCE_DIR=] [--attach] [attach ...]  build, sign, verify and attach in-toto provenance attestation (ADR 0117, 0134)
#
# Grammar (docs/adr/0112): lights-out <domain> <verb> [--flag value | KEY=VALUE ...] with domains
#   repo ticket release ops config completion; --flag value is KEY=VALUE, flat commands still work.
#   --json / --jsonl print a structured envelope on non-gate commands. Exit codes: 0 GO, 1 NO-GO,
#   2 usage error, 3 waiting on a human or a lock, 4 budget stop.
#
# init, gates, test-proof and test-integrity run the gates image,
# ghcr.io/nicolaguglielmi/lights-out-gates; triage, postmortem, state-only,
# and plane/workflow commands run the full image, ghcr.io/nicolaguglielmi/lights-out
# (docs/adr/0057 §5, docs/adr/0105). LIGHTS_OUT_IMAGE overrides the image.
# The repository is mounted read-only; state goes to LIGHTS_OUT_OUT, default
# ~/.local/state/lights-out/<repository>. Keys are passed by name only.
set -eu

version=0.9.0
gates_image=${LIGHTS_OUT_IMAGE:-ghcr.io/nicolaguglielmi/lights-out-gates:$version}
full_image=${LIGHTS_OUT_IMAGE:-ghcr.io/nicolaguglielmi/lights-out:$version}
keys="GEMINI_API_KEY ANTHROPIC_API_KEY OPENAI_API_KEY ZAI_API_KEY"
plane_keys="GITHUB_TOKEN GITLAB_TOKEN METRICS_AUTH_HEADER"
all_cmds="init genesis gates test-proof test-integrity adr-check migration-safety triage postmortem doctor version next dora spend cloud-setup map network scoreboard auto-incident incident alert-webhook top epics spec-split m24-check demo-loop jury map-brief-eval live-preflight thresholds reviewer-eval portfolio start intake answer intake-confirm assign up down smoke release promote console evidence provenance try watch request resume audit production-readiness completion"
all_keys="BASE HEAD JUDGED STAGED ALERT INCIDENT PROFILE MODEL_PROVIDER MODEL TICKET TEXT ANSWER DECISIONS VERSION CANARY_VERSION CANARY_TAG GO_FOR_LAUNCH REASON MODE PRESET CLOUD DELIVERY CODE_HOST AGENT_HARNESS PROVIDER ADAPTERS_PATH WINDOW_DAYS SPEND_BUDGET_TICKET_USD SPEND_BUDGET_DAY_USD"
# Socket tiers (docs/adr/0112 §6); gate_cmds keep the one-line contract and take no --json/--jsonl.
state_cmds="next dora spend cloud-setup map network scoreboard auto-incident incident alert-webhook top epics spec-split m24-check demo-loop jury map-brief-eval live-preflight thresholds reviewer-eval portfolio"
plane_cmds="start intake answer intake-confirm assign up down smoke release promote console evidence provenance try watch request resume audit production-readiness"
gate_cmds="init try gates test-proof test-integrity adr-check migration-safety doctor map production-readiness version"
domains="repo ticket release ops config completion"
top_words="repo ticket release ops config completion init try gates test-proof test-integrity adr-check migration-safety doctor map corpus genesis map-brief-eval intake request answer intake-confirm assign resume network audit epics spec-split up down smoke promote evidence provenance production-readiness watch alert-webhook triage auto-incident incident postmortem dora spend top charts-conformance metrics-conformance orchestrator-conformance m24-check demo-loop reviewer-eval portfolio start next cloud-setup scoreboard agents tracker-conformance console-build jury live-preflight thresholds console version"
completion_extra_keys="REQUEST_BY REQUEST_VIA ATTEMPT ONCE POLL_S RUNNER_WORKERS WORKERS INTAKE_NETWORK_SPLIT NETWORK_AUTO_SPLIT ALERT_FILE RELEASE_RECORD NAME FROM TO LOGS MAP_FILE SLO_MODE CORPUS_FULL LOGBOOK_FILE LOGBOOK URL JSON VIEW WIDTH HEIGHT TICKET_FILE PROVENANCE_DIR PROVENANCE_ATTACH PROVENANCE_ATTACH_REQUIRED TRACKER CHARTS METRICS ORCHESTRATOR REVIEWER_ROLE THINKING PORTFOLIO_REPOS"

# die MESSAGE [STATUS]: one stderr line, exit 1; a usage or contract error exits 2 before any
# engine (docs/adr/0112 §3).
die() { printf 'lights-out: %s\n' "$1" >&2; exit "${2:-1}"; }
usage_die() { die "$*" 2; }
member() {
  case "$1" in ""|*[[:space:]]*) return 1 ;; esac
  case " $2 " in *" $1 "*) return 0 ;; esac
  return 1
}

verbs_of() {
  case "$1" in
    repo) echo "init try gates test-proof test-integrity adr-check migration-safety doctor map corpus genesis map-brief-eval" ;;
    ticket) echo "intake request answer intake-confirm assign resume network audit epics spec-split" ;;
    release) echo "up down smoke deploy promote evidence provenance production-readiness" ;;
    ops) echo "watch alert-webhook triage auto-incident incident postmortem dora spend top charts-conformance metrics-conformance orchestrator-conformance m24-check demo-loop reviewer-eval portfolio" ;;
    config) echo "start next cloud-setup scoreboard agents tracker-conformance console-build jury live-preflight thresholds" ;;
    completion) echo "bash zsh fish" ;;
  esac
}

# The keys beyond the 29 a command takes (docs/adr/0112 §2), a function, not case arms,
# so the allowlist equality with package/entrypoint.sh (docs/adr/0105) is untouched.
extra_keys_for() {
  case "$1" in
    migration-safety) echo "TICKET_FILE" ;;
    provenance) echo "PROVENANCE_DIR PROVENANCE_ATTACH PROVENANCE_ATTACH_REQUIRED" ;;
    intake|answer) echo "INTAKE_NETWORK_SPLIT" ;;
    assign) echo "NETWORK_AUTO_SPLIT" ;;
    resume) echo "INTAKE_NETWORK_SPLIT NETWORK_AUTO_SPLIT" ;;
    request) echo "REQUEST_BY REQUEST_VIA" ;;
    network) echo "ATTEMPT" ;;
    watch) echo "ONCE POLL_S RUNNER_WORKERS WORKERS" ;;
    alert-webhook) echo "ALERT_FILE" ;;
    auto-incident) echo "RELEASE_RECORD" ;;
    incident) echo "NAME FROM TO LOGS" ;;
    map) echo "MAP_FILE" ;;
    cloud-setup) echo "SLO_MODE" ;;
    top) echo "LOGBOOK_FILE LOGBOOK URL ONCE JSON POLL_S VIEW WIDTH HEIGHT" ;;
    thresholds) echo "JSON" ;;
    reviewer-eval) echo "JSON REVIEWER_ROLE THINKING" ;;
    portfolio) echo "PORTFOLIO_REPOS JSON" ;;
  esac
}

# Flags the command owns, which are not translated to KEY=VALUE (docs/adr/0112 §2).
native_flag() {
  case "$1:$2" in
    init:--branch|init:--baseline-mode|init:--baseline-max-files|start:--preset|start:--provider|start:--harness|start:--delivery|start:--profile|start:--ticket-budget-usd|start:--day-budget-usd|start:--mode|next:--mode) return 0 ;;
    genesis:--repo|genesis:--brief|genesis:--brief-file|genesis:--stack|genesis:--name|genesis:--port|genesis:--tickets-count|genesis:--today|genesis:--stacks) return 0 ;;
    epics:--id|epics:--title|epics:--tickets|epics:--tickets-dir|epics:--state-dir|epics:--repo|epics:--out|epics:--manifest|epics:--stacks|epics:--today|epics:--baseline-mode|epics:--changed) return 0 ;;
    spec-split:--in-place) return 0 ;;
    m24-check:--data|m24-check:--logbook|m24-check:--logbooks|m24-check:--min-providers|m24-check:--allow-incomplete|m24-check:--out|m24-check:--handoff|m24-check:--scope|m24-check:--repository|m24-check:--kind|m24-check:--phase|m24-check:--replace) return 0 ;;
    demo-loop:--out|demo-loop:--budget|demo-loop:--inject-break) return 0 ;;
    jury:--author-provider|jury:--author-harness|jury:--risk|jury:--role|jury:--run-json|jury:--review-run-json|jury:--doc|jury:--providers) return 0 ;;
    map-brief-eval:--repo|map-brief-eval:--rev|map-brief-eval:--map|map-brief-eval:--tickets|map-brief-eval:--exclude|map-brief-eval:--worker-brief|map-brief-eval:--write-map|map-brief-eval:--no-determinism-check) return 0 ;;
    live-preflight:--repo|live-preflight:--strict) return 0 ;;
    thresholds:--root|thresholds:--contract-dir|thresholds:--no-git) return 0 ;;
    provenance:--attach|provenance:--attach-required|provenance:--required|provenance:--statement|provenance:--bundle|provenance:--sha|provenance:--out-receipt|provenance:--key|provenance:--out-dir|provenance:--repo) return 0 ;;
    reviewer-eval:--fixtures|reviewer-eval:--repo|reviewer-eval:--mode|reviewer-eval:--role|reviewer-eval:--scope|reviewer-eval:--provider|reviewer-eval:--model|reviewer-eval:--thinking|reviewer-eval:--record-replay|reviewer-eval:--strict-replay-sha|reviewer-eval:--no-gitleaks|reviewer-eval:--only-cases|reviewer-eval:--compare-manifest|reviewer-eval:--compare-tickets|reviewer-eval:--tickets-dir|reviewer-eval:--patches-dir|reviewer-eval:--map|reviewer-eval:--save-compare-replay|reviewer-eval:--only-compare) return 0 ;;
    portfolio:--repos|portfolio:--repo) return 0 ;;
  esac
  return 1
}

flag_words() {
  fw="--json --jsonl --help --engine --non-interactive --mode --preset --provider --harness --delivery --profile --ticket-budget-usd --day-budget-usd --level --staged --once --apply --branch --commit --force --workspace --baseline-mode --baseline-max-files --check --repo --brief --brief-file --stack --name --port --tickets-count --no-commit --today --stacks --id --title --tickets --tickets-dir --state-dir --no-publish --out --manifest --changed --in-place --data --logbook --logbooks --min-providers --allow-incomplete --handoff --scope --repository --kind --phase --replace --budget --inject-break --author-provider --author-harness --risk --role --run-json --review-run-json --doc --providers --rev --map --exclude --worker-brief --write-map --no-determinism-check --strict --root --contract-dir --no-git --attach --attach-required --required --statement --bundle --sha --out-receipt --key --out-dir --fixtures --model --thinking --record-replay --strict-replay-sha --no-gitleaks --only-cases --compare-manifest --compare-tickets --patches-dir --save-compare-replay --only-compare --repos"
  for k in $all_keys $completion_extra_keys; do
    f="--$(printf '%s' "$k" | tr 'A-Z_' 'a-z-')"
    member "$f" "$fw" || fw="$fw $f"
  done
  printf '%s' "$fw"
}

# Byte-identical to `python3 core/cli.py completion <shell>` (ci/tests/test_cli_wrapper_parity.py).
# shellcheck disable=SC2016 # the scripts are literal shell text
emit_completion() {
  fw=$(flag_words)
  case "$1" in
    bash)
      printf '%s\n' '# lights-out bash completion: eval "$(lights-out completion bash)"' '_lights_out() {' '  local cur=${COMP_WORDS[COMP_CWORD]}' '  if [ "$COMP_CWORD" -eq 1 ]; then'
      printf '    COMPREPLY=($(compgen -W "%s" -- "$cur"))\n' "$top_words"
      printf '%s\n' '    return 0' '  fi' '  case "${COMP_WORDS[1]}:$COMP_CWORD" in'
      for d in $domains; do printf '    %s:2) COMPREPLY=($(compgen -W "%s" -- "$cur")) ;;\n' "$d" "$(verbs_of "$d")"; done
      printf '    *) COMPREPLY=($(compgen -W "%s" -- "$cur")) ;;\n' "$fw"
      printf '%s\n' '  esac' '}' 'complete -F _lights_out lights-out' ;;
    zsh)
      printf '%s\n' '#compdef lights-out' '# lights-out zsh completion: eval "$(lights-out completion zsh)"' '_lights_out() {' '  if (( CURRENT == 2 )); then'
      printf '    compadd -- %s\n' "$top_words"
      printf '%s\n' '    return 0' '  fi' '  case "${words[2]}:$CURRENT" in'
      for d in $domains; do printf '    %s:3) compadd -- %s ;;\n' "$d" "$(verbs_of "$d")"; done
      printf '    *) compadd -- %s ;;\n' "$fw"
      printf '%s\n' '  esac' '}' 'compdef _lights_out lights-out' ;;
    fish)
      printf '%s\n' '# lights-out fish completion: lights-out completion fish | source' 'complete -c lights-out -f'
      printf "complete -c lights-out -n '__fish_use_subcommand' -a '%s'\n" "$top_words"
      for d in $domains; do printf "complete -c lights-out -n '__fish_seen_subcommand_from %s' -a '%s'\n" "$d" "$(verbs_of "$d")"; done
      for f in $fw; do printf 'complete -c lights-out -l %s\n' "${f#--}"; done ;;
    *) usage_die "completion supports: bash zsh fish" ;;
  esac
}

usage() {
  sed -n 's/^#   //p' "$0" >&2
}

# --json / --jsonl may lead (lights-out --json ticket assign ...): they join the arguments below.
lead=""
while [ $# -gt 0 ]; do
  case "$1" in --json|--jsonl) lead="$lead $1"; shift ;; *) break ;; esac
done
cmd=${1:-help}
[ $# -gt 0 ] && shift
domain=""
case "$cmd" in
  repo|ticket|release|ops|config)
    case "${1:-}" in
      -h|--help|help) printf 'usage: lights-out %s <verb> [--flag value | KEY=VALUE ...]\nverbs: %s\n' "$cmd" "$(verbs_of "$cmd")"; exit 0 ;;
    esac
    # release is both a domain and the flat deploy command: a domain only when a verb follows.
    if [ "$cmd" != release ] || { [ $# -gt 0 ] && member "$1" "$(verbs_of release)"; }; then domain=$cmd; fi ;;
esac
if [ -n "$domain" ]; then
  verb=${1:-}
  case "$verb" in ""|-*) usage_die "$domain needs a verb: $(verbs_of "$domain")" ;; esac
  member "$verb" "$(verbs_of "$domain")" || usage_die "unknown $domain verb '$verb'; one of: $(verbs_of "$domain")"
  shift
  case "$domain:$verb" in
    release:deploy) cmd=release ;;
    repo:corpus|config:agents|config:tracker-conformance|ops:charts-conformance|ops:metrics-conformance|ops:orchestrator-conformance|config:console-build) usage_die "$domain $verb needs a clone of lights-out, not the image: run ./go $verb" ;;
    *) cmd=$verb ;;
  esac
fi
case "$cmd" in
  init|genesis|gates|test-proof|test-integrity|adr-check|migration-safety|triage|postmortem|doctor|version) ;;
  next|dora|spend|cloud-setup|map|network|scoreboard|auto-incident|incident|alert-webhook|top|epics|spec-split|m24-check|demo-loop|jury|map-brief-eval|live-preflight|thresholds|reviewer-eval|portfolio) ;;
  start|intake|answer|intake-confirm|assign|up|down|smoke|release|promote|console|evidence|provenance) ;;
  try|watch|request|resume|audit|production-readiness) ;;
  --version) cmd=version ;;
  help|-h|--help) usage; exit 0 ;;
  completion)
    [ -z "$lead" ] || usage_die "completion takes no --json or --jsonl"
    [ $# -eq 1 ] || usage_die "completion takes exactly one shell: bash zsh fish"
    emit_completion "$1"
    exit 0 ;;
  *) die "unknown command '$cmd'; one of: $all_cmds; or a domain: $domains" 2 ;;
esac

for f in $lead; do set -- "$@" "$f"; done

# POSIX flags to KEY=VALUE (docs/adr/0112 §2); the flags a command owns pass through untouched.
n=$#
i=0
while [ "$i" -lt "$n" ]; do
  a=$1
  shift
  i=$((i + 1))
  case "$a" in
    --json|--jsonl|--engine|--non-interactive|--apply|--commit|--force|--workspace|--no-commit|--no-publish|--in-place|--allow-incomplete|--replace|--write-map|--no-determinism-check|--strict|--no-git|--attach|--attach-required|--required|--record-replay|--strict-replay-sha|--no-gitleaks|--only-compare|--help|-h) set -- "$@" "$a" ;;
    --staged) set -- "$@" STAGED=1 ;;
    --once) set -- "$@" ONCE=1 ;;
    --*=*)
      name=${a%%=*}
      if native_flag "$cmd" "$name"; then
        set -- "$@" "$a"
      else
        name=${name#--}
        set -- "$@" "$(printf '%s' "$name" | tr 'a-z-' 'A-Z_')=${a#*=}"
      fi ;;
    --*)
      [ "$i" -lt "$n" ] || usage_die "'$a' requires a value"
      v=$1
      shift
      i=$((i + 1))
      if native_flag "$cmd" "$a"; then
        set -- "$@" "$a" "$v"
      else
        name=${a#--}
        set -- "$@" "$(printf '%s' "$name" | tr 'a-z-' 'A-Z_')=$v"
      fi ;;
    *) set -- "$@" "$a" ;;
  esac
done

validate_args() {
  json_opt=""
  while [ $# -gt 0 ]; do
    a=$1
    shift
    case "$a" in
      BASE=*|HEAD=*|JUDGED=*|STAGED=*|ALERT=*|INCIDENT=*|PROFILE=*|MODEL_PROVIDER=*|MODEL=*|TICKET=*|TEXT=*|ANSWER=*|DECISIONS=*|VERSION=*|CANARY_VERSION=*|CANARY_TAG=*|GO_FOR_LAUNCH=*|REASON=*|MODE=*|PRESET=*|CLOUD=*|DELIVERY=*|CODE_HOST=*|AGENT_HARNESS=*|PROVIDER=*|ADAPTERS_PATH=*|WINDOW_DAYS=*|SPEND_BUDGET_TICKET_USD=*|SPEND_BUDGET_DAY_USD=*) ;;
      --json)
        [ -z "$json_opt" ] || [ "$json_opt" = "$a" ] || usage_die "--json and --jsonl are mutually exclusive"
        json_opt=$a
        member "$cmd" "start next top" || ! member "$cmd" "$gate_cmds" \
          || usage_die "'$a' is not offered for $cmd: a gate keeps its one-line GO/NO-GO contract (docs/adr/0112 §5)" ;;
      --jsonl)
        [ -z "$json_opt" ] || [ "$json_opt" = "$a" ] || usage_die "--json and --jsonl are mutually exclusive"
        json_opt=$a
        ! member "$cmd" "start next top $gate_cmds" \
          || usage_die "'$a' is not offered for $cmd: a gate keeps its one-line GO/NO-GO contract, and start, next, and top keep their native --json" ;;
      --mode=*)
        case "$cmd" in start|next|reviewer-eval) ;; *) usage_die "'$a' is only valid with start, next, or reviewer-eval" ;; esac ;;
      --mode)
        case "$cmd" in start|next|reviewer-eval) ;; *) usage_die "'$a' is only valid with start, next, or reviewer-eval" ;; esac
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --provider=*)
        case "$cmd" in start|reviewer-eval) ;; *) usage_die "'$a' is only valid with start or reviewer-eval" ;; esac ;;
      --provider)
        case "$cmd" in start|reviewer-eval) ;; *) usage_die "'$a' is only valid with start or reviewer-eval" ;; esac
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --non-interactive|--preset=*|--harness=*|--delivery=*|--profile=*|--ticket-budget-usd=*|--day-budget-usd=*)
        [ "$cmd" = start ] || usage_die "'$a' is only valid with start" ;;
      --preset|--harness|--delivery|--profile|--ticket-budget-usd|--day-budget-usd)
        [ "$cmd" = start ] || usage_die "'$a' is only valid with start"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --apply|--commit|--force|--workspace|--branch=*|--baseline-max-files=*)
        [ "$cmd" = init ] || usage_die "'$a' is only valid with init" ;;
      --branch|--baseline-max-files)
        [ "$cmd" = init ] || usage_die "'$a' is only valid with init"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --baseline-mode=*)
        case "$cmd" in init|epics) ;; *) usage_die "'$a' is only valid with init or epics" ;; esac ;;
      --baseline-mode)
        case "$cmd" in init|epics) ;; *) usage_die "'$a' is only valid with init or epics" ;; esac
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --no-commit|--brief=*|--brief-file=*|--stack=*|--name=*|--port=*|--tickets-count=*)
        [ "$cmd" = genesis ] || usage_die "'$a' is only valid with genesis" ;;
      --brief|--brief-file|--stack|--name|--port|--tickets-count)
        [ "$cmd" = genesis ] || usage_die "'$a' is only valid with genesis"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --no-publish|--id=*|--title=*|--state-dir=*|--manifest=*|--changed=*)
        [ "$cmd" = epics ] || usage_die "'$a' is only valid with epics" ;;
      --id|--title|--state-dir|--manifest|--changed)
        [ "$cmd" = epics ] || usage_die "'$a' is only valid with epics"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --tickets-dir=*)
        case "$cmd" in epics|reviewer-eval) ;; *) usage_die "'$a' is only valid with epics or reviewer-eval" ;; esac ;;
      --tickets-dir)
        case "$cmd" in epics|reviewer-eval) ;; *) usage_die "'$a' is only valid with epics or reviewer-eval" ;; esac
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --tickets=*)
        case "$cmd" in epics|map-brief-eval) ;; *) usage_die "'$a' is only valid with epics or map-brief-eval" ;; esac ;;
      --tickets)
        case "$cmd" in epics|map-brief-eval) ;; *) usage_die "'$a' is only valid with epics or map-brief-eval" ;; esac
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --out=*)
        case "$cmd" in epics|m24-check|demo-loop) ;; *) usage_die "'$a' is only valid with epics, m24-check, or demo-loop" ;; esac ;;
      --out)
        case "$cmd" in epics|m24-check|demo-loop) ;; *) usage_die "'$a' is only valid with epics, m24-check, or demo-loop" ;; esac
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --in-place)
        [ "$cmd" = spec-split ] || usage_die "'$a' is only valid with spec-split" ;;
      --allow-incomplete|--replace|--data=*|--logbook=*|--logbooks=*|--min-providers=*|--handoff=*|--repository=*|--kind=*|--phase=*)
        [ "$cmd" = m24-check ] || usage_die "'$a' is only valid with m24-check" ;;
      --data|--logbook|--logbooks|--min-providers|--handoff|--repository|--kind|--phase)
        [ "$cmd" = m24-check ] || usage_die "'$a' is only valid with m24-check"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --scope=*)
        case "$cmd" in m24-check|reviewer-eval) ;; *) usage_die "'$a' is only valid with m24-check or reviewer-eval" ;; esac ;;
      --scope)
        case "$cmd" in m24-check|reviewer-eval) ;; *) usage_die "'$a' is only valid with m24-check or reviewer-eval" ;; esac
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --budget=*|--inject-break=*)
        [ "$cmd" = demo-loop ] || usage_die "'$a' is only valid with demo-loop" ;;
      --budget|--inject-break)
        [ "$cmd" = demo-loop ] || usage_die "'$a' is only valid with demo-loop"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --author-provider=*|--author-harness=*|--risk=*|--run-json=*|--review-run-json=*|--doc=*|--providers=*)
        [ "$cmd" = jury ] || usage_die "'$a' is only valid with jury" ;;
      --author-provider|--author-harness|--risk|--run-json|--review-run-json|--doc|--providers)
        [ "$cmd" = jury ] || usage_die "'$a' is only valid with jury"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --role=*)
        case "$cmd" in jury|reviewer-eval) ;; *) usage_die "'$a' is only valid with jury or reviewer-eval" ;; esac ;;
      --role)
        case "$cmd" in jury|reviewer-eval) ;; *) usage_die "'$a' is only valid with jury or reviewer-eval" ;; esac
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --write-map|--no-determinism-check|--rev=*|--exclude=*|--worker-brief=*)
        [ "$cmd" = map-brief-eval ] || usage_die "'$a' is only valid with map-brief-eval" ;;
      --rev|--exclude|--worker-brief)
        [ "$cmd" = map-brief-eval ] || usage_die "'$a' is only valid with map-brief-eval"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --map=*)
        case "$cmd" in map-brief-eval|reviewer-eval) ;; *) usage_die "'$a' is only valid with map-brief-eval or reviewer-eval" ;; esac ;;
      --map)
        case "$cmd" in map-brief-eval|reviewer-eval) ;; *) usage_die "'$a' is only valid with map-brief-eval or reviewer-eval" ;; esac
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --strict)
        [ "$cmd" = live-preflight ] || usage_die "'$a' is only valid with live-preflight" ;;
      --no-git|--root=*|--contract-dir=*)
        [ "$cmd" = thresholds ] || usage_die "'$a' is only valid with thresholds" ;;
      --root|--contract-dir)
        [ "$cmd" = thresholds ] || usage_die "'$a' is only valid with thresholds"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --attach|--attach-required|--required|--statement=*|--bundle=*|--sha=*|--out-receipt=*|--key=*|--out-dir=*)
        [ "$cmd" = provenance ] || usage_die "'$a' is only valid with provenance" ;;
      --statement|--bundle|--sha|--out-receipt|--key|--out-dir)
        [ "$cmd" = provenance ] || usage_die "'$a' is only valid with provenance"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --record-replay|--strict-replay-sha|--no-gitleaks|--only-compare|--fixtures=*|--model=*|--thinking=*|--only-cases=*|--compare-manifest=*|--compare-tickets=*|--patches-dir=*|--save-compare-replay=*)
        [ "$cmd" = reviewer-eval ] || usage_die "'$a' is only valid with reviewer-eval" ;;
      --fixtures|--model|--thinking|--only-cases|--compare-manifest|--compare-tickets|--patches-dir|--save-compare-replay)
        [ "$cmd" = reviewer-eval ] || usage_die "'$a' is only valid with reviewer-eval"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --repos=*)
        [ "$cmd" = portfolio ] || usage_die "'$a' is only valid with portfolio" ;;
      --repos)
        [ "$cmd" = portfolio ] || usage_die "'$a' is only valid with portfolio"
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --repo=*)
        case "$cmd" in genesis|epics|map-brief-eval|live-preflight|provenance|reviewer-eval|portfolio) ;; *) usage_die "'$a' is only valid with genesis, epics, map-brief-eval, live-preflight, provenance, reviewer-eval, or portfolio" ;; esac ;;
      --repo)
        case "$cmd" in genesis|epics|map-brief-eval|live-preflight|provenance|reviewer-eval|portfolio) ;; *) usage_die "'$a' is only valid with genesis, epics, map-brief-eval, live-preflight, provenance, reviewer-eval, or portfolio" ;; esac
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --today=*|--stacks=*)
        case "$cmd" in genesis|epics) ;; *) usage_die "'$a' is only valid with genesis or epics" ;; esac ;;
      --today|--stacks)
        case "$cmd" in genesis|epics) ;; *) usage_die "'$a' is only valid with genesis or epics" ;; esac
        [ $# -gt 0 ] || usage_die "'$a' requires a value"
        shift ;;
      --engine)
        case "$cmd" in
          adr-check|migration-safety) ;;
          init|gates|test-proof|test-integrity) ;; *) die "'$a' is only valid with init, gates, test-proof, test-integrity, adr-check, or migration-safety" 2 ;;
        esac ;;
      [A-Z]*=*)
        # Only the key is echoed: a value may be a secret that must never reach a terminal log.
        member "${a%%=*}" "$(extra_keys_for "$cmd")" \
          || usage_die "'${a%%=*}=' is not an argument lights-out takes; one of $all_keys $(extra_keys_for "$cmd")" ;;
      -*)
        usage_die "'${a%%=*}' is not an argument lights-out takes; one of $all_keys $(extra_keys_for "$cmd")" ;;
      *)
        case "$cmd" in
          genesis|epics|spec-split|m24-check|demo-loop|jury|provenance|portfolio) ;;
          *) usage_die "'${a%%=*}' is not an argument lights-out takes; one of $all_keys $(extra_keys_for "$cmd")" ;;
        esac ;;
    esac
  done
}
validate_args "$@"

if [ "$cmd" = alert-webhook ]; then
  has_file=0
  for a do
    case "$a" in "ALERT_FILE="*) has_file=1 ;; esac
  done
  [ "$has_file" = 1 ] || usage_die "alert-webhook from the image normalizes a file in the repository: ALERT_FILE=<path>; serving the webhook needs a published port: ./go alert-webhook"
fi

engine_gates=0
case "$cmd" in
  init|gates|test-proof|test-integrity|adr-check|migration-safety)
    [ "${LIGHTS_OUT_ENGINE_GATES:-0}" != 1 ] || engine_gates=1
    for a do
      [ "$a" != --engine ] || engine_gates=1
    done ;;
esac

case "$cmd" in
  doctor) image=$gates_image ;;
  init|gates|test-proof|test-integrity|adr-check|migration-safety)
    if [ "$engine_gates" = 1 ]; then image=$full_image; else image=$gates_image; fi ;;
  *) image=$full_image ;;
esac

if [ "$cmd" = version ]; then
  printf 'lights-out %s (gates image %s, full image %s)\n' "$version" "$gates_image" "$full_image"
  exit 0
fi

if [ -n "${CONTAINER_ENGINE:-}" ]; then
  engine=$CONTAINER_ENGINE
  command -v "$engine" >/dev/null 2>&1 || die "CONTAINER_ENGINE=$engine is not on PATH"
elif command -v podman >/dev/null 2>&1; then
  engine=podman
elif command -v docker >/dev/null 2>&1; then
  engine=docker
else
  die "no container engine found. Install podman (reference) or docker, or set CONTAINER_ENGINE."
fi
engine_kind=$(basename "$engine")

# The key the chosen provider needs, by name; L0 replays and needs none.
profile_explicit=0
[ -z "${PROFILE:-}" ] || profile_explicit=1
profile=${PROFILE:-l0}
model_provider=${MODEL_PROVIDER:-${PROVIDER:-gemini}}
adapters_path=${ADAPTERS_PATH:-}
for a do
  case "$a" in
    PROFILE=*) profile=${a#PROFILE=}; profile_explicit=1 ;;
    MODEL_PROVIDER=*) model_provider=${a#MODEL_PROVIDER=} ;;
    PROVIDER=*) [ -n "${MODEL_PROVIDER:-}" ] || model_provider=${a#PROVIDER=} ;;
    ADAPTERS_PATH=*) adapters_path=${a#ADAPTERS_PATH=} ;;
  esac
done
case "$model_provider" in
  anthropic) key=ANTHROPIC_API_KEY ;;
  openai) key=OPENAI_API_KEY ;;
  zai) key=ZAI_API_KEY ;;
  *) key=GEMINI_API_KEY ;;
esac

run_doctor() {
  bad=""
  item() { printf 'doctor: %-7s %s\n' "$1" "$2" >&2; }
  if "$engine" info >/dev/null 2>&1; then
    item engine "ok, $engine $("$engine" version --format '{{.Client.Version}}' 2>/dev/null || echo '?'), answers"
  else
    item engine "FAIL, $engine does not answer ('$engine info' fails): start it (podman machine start, or the docker daemon)"
    bad="$bad engine"
  fi
  if command -v git >/dev/null 2>&1; then
    item git "ok, $(git --version)"
  else
    item git "FAIL, git is not on PATH"; bad="$bad git"
  fi
  if [ -z "$bad" ] && got=$("$engine" image inspect --format '{{index .Config.Labels "org.opencontainers.image.version"}}' "$1" 2>/dev/null); then
    item image "ok, $1 is here (version ${got:-unlabelled})"
  elif [ -z "$bad" ] && "$engine" manifest inspect "$1" >/dev/null 2>&1; then
    item image "ok, $1 is in the registry, pulled on the first run"
  elif [ -z "$bad" ]; then
    item image "FAIL, $1 is neither here nor reachable: not published yet, private, or no login (docker login ghcr.io); from a clone, ./go package-gates builds localhost/lights-out-gates:dev for LIGHTS_OUT_IMAGE"
    bad="$bad image"
  fi
  if [ "$profile" = l0 ]; then
    item key "ok, none needed at L0 (recordings replay; on your own alerts and incidents: PROFILE=l1 and a key)"
  elif eval "[ -n \"\${$key:-}\" ]"; then
    item key "ok, $key is set for $model_provider at $profile"
  else
    item key "FAIL, $key is not set in this environment; $model_provider at $profile needs it"
    bad="$bad key"
  fi
  if [ -n "$bad" ]; then
    printf 'NO-GO: doctor —%s\n' "$bad"
    return 1
  fi
  printf 'GO: doctor\n'
  return 0
}

if [ "$cmd" = doctor ]; then
  if run_doctor "$image"; then exit 0; else exit 1; fi
fi

# init and gates judge a repository: run from its top level, whatever the
# subdirectory. State and plane commands also resolve to the repository root
# when inside a git repository.
if member "$cmd" "init gates test-proof test-integrity adr-check migration-safety"; then
  top=$(git rev-parse --show-toplevel 2>/dev/null) || die "lights-out $cmd runs inside a git repository"
  cd "$top"
elif member "$cmd" "$state_cmds $plane_cmds"; then
  if top=$(git rev-parse --show-toplevel 2>/dev/null); then
    cd "$top"
  fi
fi
here=$(pwd -P)
out=${LIGHTS_OUT_OUT:-${XDG_STATE_HOME:-$HOME/.local/state}/lights-out/$(basename "$here")}
mkdir -p "$out" || die "cannot create $out (LIGHTS_OUT_OUT)"
out=$(CDPATH='' cd -- "$out" && pwd -P)

tier="readonly"
if member "$cmd" "$state_cmds"; then
  tier="state"
elif member "$cmd" "$plane_cmds"; then
  tier="plane"
elif member "$cmd" "init gates test-proof test-integrity adr-check migration-safety"; then
  [ "$engine_gates" != 1 ] || tier="engine-gates"
fi
# incident reads the release record; only its TICKET= option needs the state store (the plane).
if [ "$cmd" = incident ]; then
  for a do
    case "$a" in "TICKET="*) tier="plane" ;; esac
  done
fi

# STAGED=1: the staged changes as this host's git sees them, handed to the
# image as a file. Read through the engine's mount, .git/index can be a
# stale copy right after `git add` (podman machine's file sharing,
# observed 2026-11-08), and the patch would be another change.
rm -f "$out/staged.patch"
for a do
  case "$a" in
    STAGED=0|STAGED=) ;;
    STAGED=*) git diff --cached --binary > "$out/staged.patch" || die "git diff --cached failed in $here" ;;
  esac
done

mount_adapters=""
if [ -n "$adapters_path" ]; then
  if [ "$tier" != readonly ]; then
    case "$adapters_path" in
      /*) ;;
      *) die "ADAPTERS_PATH=$adapters_path is not an absolute path" ;;
    esac
    [ -d "$adapters_path" ] || die "ADAPTERS_PATH=$adapters_path is not a directory"
    mount_adapters=$adapters_path
  elif [ -d "$adapters_path" ]; then
    case "$adapters_path" in /*) mount_adapters=$adapters_path ;; esac
  fi
fi

sock=""
sock_gid=""
if [ "$tier" = plane ] || [ "$tier" = engine-gates ]; then
  if [ "$engine_kind" = podman ]; then
    sock=$("$engine" info --format '{{.Host.RemoteSocket.Path}}' 2>/dev/null || true)
    sock=${sock#unix://}
    if [ "$("$engine" info --format '{{.Host.RemoteSocket.Exists}}' 2>/dev/null || true)" != true ] || [ -z "$sock" ]; then
      die "podman's API socket ${sock:-(none)} does not exist. Enable it: systemctl --user enable --now podman.socket"
    fi
  else
    sock=${DOCKER_HOST:-}
    sock=${sock#unix://}
    [ -n "$sock" ] || sock=/var/run/docker.sock
    if [ ! -S "$sock" ]; then
      die "$engine's socket $sock does not exist"
    fi
    sock_gid=$(stat -c %g "$sock" 2>/dev/null || stat -f %g "$sock" 2>/dev/null || true)
  fi
  notice_kind="plane"
  [ "$tier" != engine-gates ] || notice_kind="--engine"
  printf 'lights-out: mounting container engine socket (%s) for opt-in %s command %s\n' "$sock" "$notice_kind" "$cmd" >&2
fi

if [ "$cmd" = start ]; then
  doc_out=$(mktemp)
  doc_err=$(mktemp)
  doc_rc=0
  run_doctor "$image" >"$doc_out" 2>"$doc_err" || doc_rc=$?
  LIGHTS_OUT_DOCTOR_RC=$doc_rc
  LIGHTS_OUT_DOCTOR_OUT=$(cat "$doc_out")
  LIGHTS_OUT_DOCTOR_ERR=$(cat "$doc_err")
  rm -f "$doc_out" "$doc_err"
  export LIGHTS_OUT_DOCTOR_RC LIGHTS_OUT_DOCTOR_OUT LIGHTS_OUT_DOCTOR_ERR
fi

tty="-i"
[ -t 0 ] && [ -t 1 ] && tty="-it"

repo_rw=0
rw_reason=""
if [ "$cmd" = init ]; then
  for a do
    [ "$a" != --apply ] || { repo_rw=1; rw_reason="opt-in init --apply"; }
  done
elif [ "$cmd" = genesis ]; then
  repo_rw=1
  rw_reason="genesis scaffold"
fi

# SELinux: never :z, which would relabel your repository (docs/adr/0045 §2).
# Passed by name only: secret values never appear on a command line.
n=$#
set -- "$@" --rm --init "$tty" --security-opt label=disable
if [ "$engine_kind" = docker ]; then
  set -- "$@" --user "$(id -u):$(id -g)" -e HOME=/tmp
  if [ "$tier" = plane ] || [ "$tier" = engine-gates ]; then
    set -- "$@" --add-host host.containers.internal:host-gateway
  fi
fi

if [ "$tier" = readonly ]; then
  for k in $keys MODEL_PROVIDER MODEL; do
    if eval "[ -n \"\${$k:-}\" ]"; then set -- "$@" -e "$k"; fi
  done
  if [ "$repo_rw" = 1 ]; then
    printf 'lights-out: mounting %s read-write (/repo:rw) for %s\n' "$here" "$rw_reason" >&2
    set -- "$@" -v "$here:/repo:rw" -v "$out:/out" -e LIGHTS_OUT_HOST_OUT="$out" -e PROFILE="$profile"
  else
    set -- "$@" -v "$here:/repo:ro" -v "$out:/out" -e LIGHTS_OUT_HOST_OUT="$out" -e PROFILE="$profile"
  fi
elif [ "$tier" = state ]; then
  mkdir -p "$out/crew" || die "cannot create $out/crew"
  for k in $keys $plane_keys MODEL_PROVIDER MODEL AGENT_HARNESS DELIVERY CODE_HOST GITHUB_REPO METRICS_URL GOOGLE_CLOUD_PROJECT GCP_PROJECT GOOGLE_CLOUD_LOCATION RUNNER_WORKERS WORKERS INTAKE_NETWORK_SPLIT NETWORK_AUTO_SPLIT DEMO_LOOP_OUT DEMO_LOOP_BUDGET_SECONDS JURY_CROSS_PROVIDER JURY_PROVIDER JURY_MODEL JURY_HARNESS REVIEWER_ROLE THINKING PORTFOLIO_REPOS; do
    if eval "[ -n \"\${$k:-}\" ]"; then set -- "$@" -e "$k"; fi
  done
  if [ "$cmd" = top ]; then
    for k in NO_COLOR TERM; do
      if eval "[ -n \"\${$k:-}\" ]"; then set -- "$@" -e "$k"; fi
    done
  fi
  if [ -n "$mount_adapters" ]; then
    set -- "$@" -v "$mount_adapters:$mount_adapters:ro" -e ADAPTERS_PATH="$mount_adapters"
  fi
  set -- "$@" -v "$here:/repo:ro" -v "$out/crew:/opt/lights-out/.crew" -e LIGHTS_OUT_HOST_OUT="$out"
  [ "$profile_explicit" = 0 ] || set -- "$@" -e PROFILE="$profile"
else
  mkdir -p "$out/platform" "$out/crew" || die "cannot create $out/platform or $out/crew"
  env_keys="$keys MODEL_PROVIDER MODEL"
  [ "$tier" = engine-gates ] || env_keys="$env_keys $plane_keys AGENT_HARNESS DELIVERY CODE_HOST GITHUB_REPO GITLAB_URL GITLAB_PROJECT_PATH GITHUB_API_URL PROVENANCE_ATTACH PROVENANCE_ATTACH_REQUIRED METRICS_URL GOOGLE_CLOUD_PROJECT GOOGLE_CLOUD_LOCATION RUNNER_WORKERS WORKERS INTAKE_NETWORK_SPLIT NETWORK_AUTO_SPLIT"
  for k in $env_keys; do
    if eval "[ -n \"\${$k:-}\" ]"; then set -- "$@" -e "$k"; fi
  done
  if [ "$tier" != engine-gates ] && [ -n "$mount_adapters" ]; then
    set -- "$@" -v "$mount_adapters:$mount_adapters:ro" -e ADAPTERS_PATH="$mount_adapters"
  fi
  set -- "$@" -v "$sock:/var/run/docker.sock" -e DOCKER_HOST=unix:///var/run/docker.sock
  if [ "$engine_kind" = docker ] && [ -n "$sock_gid" ]; then
    set -- "$@" --group-add "$sock_gid"
  fi
  if [ "$tier" = engine-gates ]; then
    set -- "$@" -v "$out:/out" -e LIGHTS_OUT_ENGINE_GATES=1
  fi
  if [ "$cmd" = console ]; then
    publish=${CONSOLE_PUBLISH:-127.0.0.1}
    cport=${CONSOLE_PORT:-8098}
    set -- "$@" -p "$publish:$cport:8098" -e CONSOLE_PORT="$cport" -e CONSOLE_BIND=0.0.0.0 -e CONSOLE_PUBLISH="$publish"
  fi
  if [ "$cmd" = console ] || [ "$cmd" = production-readiness ]; then
    for cv in CONSOLE_AUTH CONSOLE_IDENTITY_HEADER CONSOLE_LAUNCHERS CONSOLE_SNAPSHOT CONSOLE_HOSTS CONSOLE_POLL_S \
              CONSOLE_VERIFY_JWT CONSOLE_JWT_HEADER CONSOLE_JWKS_URL CONSOLE_JWKS_FILE CONSOLE_JWKS_TTL_S \
              CONSOLE_JWKS_REFRESH_COOLDOWN_S CONSOLE_JWT_ISSUER CONSOLE_JWT_AUDIENCE CONSOLE_JWT_LEEWAY_S \
              CONSOLE_JWT_ALGS CONSOLE_JWT_SECRET CONSOLE_IDENTITY_CLAIM CONSOLE_RBAC CONSOLE_DEFAULT_ROLE \
              CONSOLE_VIEWERS CONSOLE_DEVELOPERS CONSOLE_OPERATORS CONSOLE_ROLE_CLAIM CONSOLE_ROLE_MAP \
              CONSOLE_AUDIT_LOG; do
      if eval "[ -n \"\${$cv:-}\" ]"; then set -- "$@" -e "$cv"; fi
    done
  fi
  if [ "$cmd" = start ]; then
    set -- "$@" -e LIGHTS_OUT_DOCTOR_RC -e LIGHTS_OUT_DOCTOR_OUT -e LIGHTS_OUT_DOCTOR_ERR
  fi
  repo_spec="$here:/repo:ro"
  if [ "$repo_rw" = 1 ]; then
    printf 'lights-out: mounting %s read-write (/repo:rw) for %s\n' "$here" "$rw_reason" >&2
    repo_spec="$here:/repo:rw"
  fi
  set -- "$@" \
    -v "$repo_spec" \
    -v "$out/platform:$out/platform" \
    -v "$out/crew:$out/crew" \
    -e LIGHTS_OUT_PLATFORM_DIR="$out/platform" \
    -e LIGHTS_OUT_CREW_DIR="$out/crew" \
    -e WORKBENCH_IMAGE="$image" \
    -e LIGHTS_OUT_HOST_OUT="$out"
  [ "$profile_explicit" = 0 ] || set -- "$@" -e PROFILE="$profile"
  # try names its draft after the repository's host path (docs/adr/0093 §5).
  [ "$cmd" != try ] || set -- "$@" -e TRY_SOURCE="$here"
fi

set -- "$@" "$image" "$cmd"
i=0
while [ "$i" -lt "$n" ]; do
  arg=$1
  shift
  set -- "$@" "$arg"
  i=$((i + 1))
done

rc=0
"$engine" run "$@" || rc=$?
if [ "$rc" = 125 ]; then
  die "$engine could not start $image (exit 125, see above): not published yet, private, or no login (docker login ghcr.io); from a clone, ./go package-gates (./go package for triage, postmortem, state, and plane commands) builds one for LIGHTS_OUT_IMAGE"
fi
if [ "$rc" != 0 ]; then
  case "$cmd" in
    gates|test-proof|test-integrity|adr-check|migration-safety)
      printf 'lights-out: the details of a NO-GO are above and in %s/gates/\n' "$out" >&2 ;;
  esac
fi
exit "$rc"
