Skip to content

martin1847/evolab / skills/cto-orchestration

cto-orchestration

Unverified

以 CTO/orchestrator 模式管理多 agent 软件交付。用户要求“你做 CTO/编排者”“派 omp/codex 去做”“goal 模式派发”、管理多会话开发或接入这套工作流时使用;“复盘/收口/retro/retrospective”“工作盘点/盘点候选/stocktake”也必须触发,盘点只提案不动工。新项目先用 repo-governance-bootstrap 建治理骨架。不用于单 agent 小任务、无需评审循环的局部改动或纯文档初始化。

FileKindSize
README.mdmarkdown5.3 KB
SKILL.mdskill md15.8 KB
references/agentctl/README.mdmarkdown26.8 KB
references/agentctl/agentctlexecutablescript57.6 KB
references/agentctl/codegraph-hooks.shexecutablescript2.5 KB
references/agentctl/cto-guard-agent.pyexecutablescript26.6 KB
references/agentctl/cto-guard-bash.pyexecutablescript150.5 KB
references/agentctl/cto-guard-edit.pyexecutablescript16.7 KB
references/agentctl/cto-guard-stop.pyexecutablescript7.6 KB
references/agentctl/duplexctl.pyexecutablescript239.5 KB
references/agentctl/guard-hooks.jsonconfig1.5 KB
references/agentctl/identity.pyexecutablescript113.5 KB
references/agentctl/post-checkout-codegraph.shscript18 B
references/agentctl/seat-census.pyscript10.8 KB
references/agentctl/watchctl.pyexecutablescript143.2 KB
references/agents-md-orchestration-section.mdmarkdown5.3 KB
references/decision-queue.mdmarkdown5.7 KB
references/dispatch-baseline.mdmarkdown3.7 KB
references/doc-lifecycle.pyexecutablescript9.2 KB
references/frontend-verify.mdmarkdown7.9 KB
references/goal-clauses.mdmarkdown8.0 KB
references/goal-preflight.pyexecutablescript40.9 KB
references/goal-template.mdmarkdown10.8 KB
references/implementation-discipline.mdmarkdown8.0 KB
references/measurement-protocol.mdmarkdown4.2 KB
references/onboarding-checklist.mdmarkdown3.2 KB
references/queue-freshness.pyexecutablescript3.8 KB
references/queue-hooks.jsonconfig617 B
references/retro-check.shexecutablescript28.2 KB
references/retro-hooks.jsonconfig2.2 KB
references/retro-reminder.shexecutablescript5.8 KB
references/retrospective.mdmarkdown7.7 KB
references/review-brief-preamble.mdmarkdown3.4 KB
references/review-dispatch.mdmarkdown14.4 KB
references/session-economics.pyexecutablescript18.2 KB
references/shock-in-the-loop.mdmarkdown3.8 KB
references/stocktake.mdmarkdown2.3 KB

references/agentctl/agentctl

View on GitHub
#!/usr/bin/env bash
# agentctl — unified control surface for headless worker agents (duplex-lane era).
#
#   agentctl start  <omp|codex|claude> <session> <cwd> --goal F [--deliverable G]
#                   [--no-preflight] [--review] [--expect MINUTES] [engine args...]
#   agentctl steer  <session> (-m TEXT | -f FILE) [--interrupt] [-d|--deliverable G]
#   agentctl status <session>            # one-shot typed state (exit = verdict)
#   agentctl watch  <session> [--inline] [--expect MINUTES]  # follow until an ACTION verdict
#   agentctl stop   <session>            # end + clean control state (events kept for post-mortem)
#   agentctl capabilities [--json]       # runtime-generated provider capability contract
#   agentctl states [--json]             # runtime-generated typed state vocabulary
#   agentctl inventory --dry-run         # read-only candidate overview (never kills anything)
#   agentctl phases [--since W] [--repo D] [--json]   # phase-ledger readings (no verdict)
#
# ONE lane, three engines (unified 2026-07-19): each runs its native duplex stdio protocol
# long-lived in a tmux supervisor pane; steering is a protocol frame on the session fifo
# (duplexctl = single flock-serialized writer) and capability gaps REFUSE instead of forking
# lanes. tmux SUPERVISES only. NOT a transaction system: concurrent same-name starts are an
# orchestrator bug, sequential ones are refused mechanically. The typed exit vocabulary is
# NOT copied here: `agentctl states` prints it (and `--json` publishes it), generated from
# duplexctl's TYPED_STATES. Untyped: 1 usage/SESSION-GONE, 3 send-unconfirmed.
# `agentctl watch-daemon <session>` is INTERNAL: the sensing loop tmux runs for supervised watch.
#
# THIS SCRIPT IS A THIN ENTRY, AND THAT IS A CONTRACT: usage + argument parsing, tmux and
# process-group glue, the goal-file existence check, and `$CTL` dispatch with the exit code
# forwarded untouched. Every JUDGEMENT is in python — nothing here parses a JSON record, a
# lease, a terminal record, the events stream or the rc file, does timestamp arithmetic, or
# branches on what a classify verdict SAYS (guard: agentctl-structure.test.sh §S4/§S5).
set -uo pipefail
# $0 may be a PATH symlink: follow the chain before dirname, else CTL resolves beside the link
SELF="$0"
while [ -L "$SELF" ]; do
  link="$(readlink "$SELF")"
  case "$link" in /*) SELF="$link" ;; *) SELF="$(dirname "$SELF")/$link" ;; esac
done
HERE="$(cd "$(dirname "$SELF")" && pwd)"
SELFABS="$HERE/$(basename "$SELF")"   # the supervisor pane relaunches this exact script
DIR="${AGENT_WATCH_DIR:-/tmp/agent-watch-run}"
CTL="$HERE/duplexctl.py"
PY="${AGENTCTL_PYTHON:-python3}"
ARMED_ID=""   # arm-time snapshot of the active identity; captured by watch before it senses
# omp journal filter — the ONE definition of what the pane REFUSES to journal. The two lines
# are self-contained on purpose: test/agentctl-journal-filter.test.sh `eval`s them straight out
# of this file, so the regex exists exactly once in the repo and cannot drift from its test.
JOURNAL_FILTER_RE='^\{"type":"message_update","assistantMessageEvent":\{"type":"(text|thinking|toolcall)_delta",'
JOURNAL_FILTER_CMD="LC_ALL=C grep -a --line-buffered -v -E"
q() { printf %q "$1"; }
ctl() { "$PY" "$CTL" --run-dir "$DIR" "$@"; }
meta_get() { sed -n "s/^$2=//p" "$DIR/$1.duplex.meta" 2>/dev/null | head -1; }
goal_tier_deep() { # $1 goal file — rc 0 only when its `Tier:` line says deep. THE READING IS
  # goal-preflight.py's own `TIER_LINE` / `DEEP_WORDS`, loaded by path instead of re-spelled:
  # a second regex for one declaration drifts on the first edit, and that gate is what goal
  # authors already write against. Every unanswerable case (no python3, unreadable goal, no
  # `Tier:` line, an unknown value) is NOT deep — the caller then keeps the base variable.
  "$PY" - "$HERE/../goal-preflight.py" "$1" >/dev/null 2>&1 <<'TIERPY'
import importlib.util, sys
spec = importlib.util.spec_from_file_location("goal_preflight", sys.argv[1])
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
with open(sys.argv[2], encoding="utf-8", errors="replace") as fh:
    hit = mod.TIER_LINE.search(fh.read())
value = hit.group(1).strip(mod._TRAILING + "`*").lower() if hit else ""
sys.exit(0 if value in mod.DEEP_WORDS else 1)
TIERPY
}
usage() {
  echo "usage: agentctl start <omp|codex|claude> <session> <cwd> --goal F [--deliverable G] [--no-preflight] [--review] [--expect MINUTES] [engine args...]   # session = <proj>-<task>-<engine>, e.g. shop-cart-omp (prefix = who owns it in tmux ls)" >&2
  echo "       agentctl steer <session> (-m TEXT | -f FILE) [--interrupt] [-d G]  # default = deliver ASAP" >&2
  echo "       agentctl status <session> | watch <session> [--inline] [--expect MINUTES] | stop <session> | capabilities [--json] | states [--json]" >&2
  echo "       agentctl phases [--since <N>m|<N>h|<N>d|RFC3339] [--repo <abs>] [--json]   # read-only ledger readings" >&2
  echo "       agentctl closeout <absolute-worktree> --archive <new-absolute-directory> --keep <relative-file> [...] --source-head OID --acceptance FILE --integrated-as OID --base-ref <local-branch>   # see closeout --help for caller preconditions" >&2
  printf '%s\n' "       agentctl inventory --dry-run   # read-only; no other spelling exists" "       default model without --model: AGENTCTL_MODEL_<E>_REVIEW (--review only) > AGENTCTL_MODEL_<E>_DEEP (non-review deep-Tier goal only) > AGENTCTL_MODEL_<E> > engine default; E = OMP|CODEX|CLAUDE" >&2
  exit 1
}

# duplex sessions have .duplex.meta (the only lane since 2026-07-19 unification).
lane_of() { # $1 session
  if [ -f "$DIR/$1.duplex.meta" ]; then echo duplex; else echo none; fi
}

# tmux kill-session only signals the pane leader: children that outlive it are adopted by PID 1
# and leak (field 2026-07-28: 43 sessions left 8 workers + 16 grandchildren). The pane is its
# own session+group leader and POSIX reserves the pgid while ANY member lives, so the group is
# the ownership boundary: TERM, grace, KILL, verify — one pgid we own, never a global kill.
reap_tree() { # $1 pane_pid (== pgid)  $2 expected leader lstart ("" = pid read live, skip check)
  local pg="$1" want="$2" have i tries
  case "$pg" in ''|*[!0-9]*) return 0;; esac
  # lower bounds are load-bearing: Linux `pgrep -g 0` is OUR group, and reaping it is suicide
  [ "$pg" -gt 1 ] || return 0
  [ "$pg" = "$(ps -o pgid= -p $$ 2>/dev/null | tr -d ' ')" ] && return 0
  pgrep -g "$pg" >/dev/null 2>&1 || return 0
  if [ -n "$want" ]; then
    # stale meta: the pgid is a stranger's only if the LEADER pid was recycled after our whole
    # tree died, so its start time is the fingerprint (dead leader + live members = still ours)
    have="$(ps -p "$pg" -o lstart= 2>/dev/null | sed 's/ *$//')"
    if [ -n "$have" ] && [ "$have" != "$want" ]; then
      echo "WARN: pgid $pg leader started '$have' ≠ recorded '$want' (pid recycled) — not ours, not reaping" >&2
      return 0
    fi
  fi
  kill -TERM -- "-$pg" 2>/dev/null
  # non-numeric falls back to the 5s default; an explicit 0 means NO grace — caller's call.
  case "${AGENTCTL_REAP_GRACE:-}" in ''|*[!0-9]*) tries=25;; *) tries=$(( AGENTCTL_REAP_GRACE * 5 ));; esac
  i=0
  while [ "$i" -lt "$tries" ]; do
    pgrep -g "$pg" >/dev/null 2>&1 || { echo "reaped process group $pg (TERM)"; return 0; }
    sleep 0.2; i=$((i+1))
  done
  kill -KILL -- "-$pg" 2>/dev/null; sleep 0.2
  if pgrep -g "$pg" >/dev/null 2>&1; then
    echo "WARN: survivors in process group $pg after KILL: $(pgrep -g "$pg" 2>/dev/null | tr '\n' ' ')" >&2
    return 1
  fi
  echo "reaped process group $pg (KILL)"
}

# Escaped children are OUTSIDE the pane's group by construction (setsid / double fork), so the
# group-scoped reap above cannot see them and they outlive the stop (field 2026-08: one stop
# left 32 MCP children, ~700MB, oldest 6 days). These two calls bracket the reap and REPORT
# that gap on stderr — shared verbatim by both stop branches. They add NO signal of any kind:
# the snapshot is evidence, never a kill list, a recycled pid is not a survivor, and a probe
# that cannot answer prints [unknown] rather than letting silence read as clean. Judgement is
# duplexctl's (thin-entry contract); the shell only brackets the reap with it.
SURV_SNAP=""
survivor_probe() { # $1 session  $2 pane pgid ("" = no pane to probe: no snapshot, no advisory)
  SURV_SNAP=""
  [ -n "${2:-}" ] || return 0
  mkdir -p "$DIR" 2>/dev/null
  SURV_SNAP="$DIR/.$1.stop-probe.json"
  rm -f "$SURV_SNAP"
  ctl stop-probe "$1" --pane-pid "$2" --snapshot "$SURV_SNAP" >/dev/null 2>&1 || true
  return 0
}
survivor_advise() { # $1 session — stderr advisory only; never signals, never touches stop's rc
  [ -n "$SURV_SNAP" ] || return 0
  ctl stop-survivors "$1" --snapshot "$SURV_SNAP" || true
  rm -f "$SURV_SNAP"; SURV_SNAP=""
  return 0
}

# The advisory above stops at REPORTING because a group-scoped reap has no pgid that would
# reach an escapee and no right to signal one by name. The pane's exported labels give it a
# third option: AGENTCTL_SESSION says which seat made the process and AGENTCTL_CWD which
# directory it serves, both inherited by every exec'd descendant — so an escapee carries its
# own provenance and can be reaped ONE PID AT A TIME, on evidence it supplies itself.
# Division of labour: `lineage-plan` decides WHO is reapable (environment membership read from
# a NUL-delimited source, never a substring of a ps line; a cwd no other live session works
# in; every gap fail-closed) and prints `<pid> <start-time>`; the signalling is here, because
# the python lane sends no signals.
# The plan is a SAMPLE, so the identity is re-read immediately before TERM and again before
# KILL — same discipline reap_tree applies to its pgid leader, per pid.
pid_live() { # $1 pid — 0 while it is a LIVE process; a zombie is a corpse, not a survivor
  local st
  st="$(ps -o state= -p "$1" 2>/dev/null | tr -d ' ')"
  [ -n "$st" ] || return 1
  case "$st" in Z*) return 1;; esac
  return 0
}
lineage_verify() { # $1 pid  $2 recorded start time — 0 only if the pid is STILL that process
  local have
  # `tr -s ' '` is load-bearing, not tidying: ps pads a single-digit day ("Sep  4") and the
  # plan's start time came through a python field split that already collapsed it, so an
  # un-normalized compare calls EVERY process reaped on days 1-9 a recycled stranger.
  have="$(ps -p "$1" -o lstart= 2>/dev/null | tr -s ' ' | sed 's/ *$//')"
  [ -n "$have" ] && [ "$have" = "$2" ]
}
LINEAGE_SEEN=0   # what the last lineage_reap RECOGNIZED — sampled or refused; the no-lane stop
                 # reads it to tell a post-mortem from a name that never existed
STOP_RESIDUE_NONE=20   # watchctl's private code of the same name: consumed below, never an exit
lineage_reap() { # $1 session — prints one count line; rc 1 only if a pid survived its KILL
  local plan prc row pid want i tries seen=0 reaped=0 killed="" left="" refused=0
  plan="$(ctl lineage-plan "$1")"; prc=$?
  # rc 3 is the planner's typed "recognized something, signallable nothing": the plan is empty
  # on PURPOSE, so this stop did attribute processes to the name and only declined to signal.
  [ "$prc" = 3 ] && { prc=0; refused=1; }
  # A planner that DIED must not read as an empty plan: the count line would then report an
  # unenumerated escapee as `reaped 0`, i.e. as a clean box — and a stop that enumerated
  # nothing has no standing to call the name unknown either.
  if [ "$prc" != 0 ]; then
    echo "ADVISORY: stop $1: [unknown] lineage plan failed (rc=$prc) — no process was enumerated and NOTHING was signalled" >&2
    plan=""; refused=1
  fi
  case "${AGENTCTL_REAP_GRACE:-}" in ''|*[!0-9]*) tries=25;; *) tries=$(( AGENTCTL_REAP_GRACE * 5 ));; esac
  while IFS= read -r row; do
    pid="${row%% *}"; want="${row#* }"
    case "$pid" in ''|*[!0-9]*) continue;; esac
    [ "$want" != "$row" ] || continue          # no start-time half = not a plan line
    seen=$((seen+1))
    if ! lineage_verify "$pid" "$want"; then
      echo "ADVISORY: stop $1: [skipped pid=$pid identity changed] — gone or recycled since the plan was sampled; nothing signalled" >&2
      continue
    fi
    kill -TERM "$pid" 2>/dev/null
    i=0
    while [ "$i" -lt "$tries" ]; do
      pid_live "$pid" || break
      sleep 0.2; i=$((i+1))
    done
    if pid_live "$pid"; then
      if ! lineage_verify "$pid" "$want"; then
        echo "ADVISORY: stop $1: [skipped pid=$pid identity changed] — not KILLed" >&2
        continue
      fi
      kill -KILL "$pid" 2>/dev/null; sleep 0.2
      killed="$killed $pid"
    fi
    if pid_live "$pid"; then left="$left $pid"; else reaped=$((reaped+1)); fi
  done <<EOF
$plan
EOF
  LINEAGE_SEEN=$((seen + refused))
  echo "reaped $reaped lineage process(es)${killed:+ (KILL:$killed)}"
  [ -z "$left" ] || { echo "WARN: labelled process(es) survived KILL:$left" >&2; return 1; }
  return 0
}

# The BLOCKED.md footer IS the ask-user protocol: headless engines cannot prompt, so "on doubt,
# write BLOCKED.md and stop" maps to exit 4. Byte-for-byte the runtime understanding gate.
# The old wording ("do not wait for approval or interaction" + "if GENUINELY blocked") read as a
# licence to self-approve past a contract STOP gate — two workers did exactly that, same day,
# different goals. A contract gate is not interaction, and holding one is not a
# fallback path: it is the delivery action. Both halves are load-bearing, do not compress.
# The "unless" clause consumes the kernel's branch predicate (orchestrator-core §3): whether to
# wait is decided by what the contract PROMISED, never by who happens to be watching. Silence in
# the contract means start — the failure cost of a bounded false start beats deadlocking every
# lane that never promised a handshake.
# Every byte here is paid once per session and competes with the goal for attention (the
# mechanical footer meter retired with test/context-budget.test.sh). Two things were cut when
# the write-the-file and stamp-the-file sentences merged: the duplicated "when you write that
# file" lead-in, and the note that an unstamped blocker still works. The latter is true — the
# runtime keeps accepting one, and test/agentctl-identity.test.sh N2 holds that behaviour — but
# telling the worker its stamp is optional buys nothing it can act on and weakens the instruction
# that follows. Reader-facing rationale belongs here in the source, not in the injected frame.
append_footer() { # $1 out-file  $2 cwd  $3 identity stamp file  $4 deliverable glob ("" = none)
  # The deliverable sentence is injected ONLY when one was declared (review 2026-08-17 B1:
  # an unconditional sentence told no-deliverable sessions to write a file that does not
  # exist — the runtime contract must never lie to a legal path). GENERIC wording, no glob
  # (review R2): the footer is a one-shot frame while `steer -d` can move the deliverable
  # later — naming the start-time glob would order the worker to write a file the watcher
  # no longer checks. Known boundary: a session started WITHOUT a deliverable that gains
  # one via `steer -d` never gets this sentence — the steer text itself must name the
  # artifact (goal-template's 交付物 line does; runtime does not re-inject footers).
  local line2='This session is non-interactive. Work from this message and stop when done; further instructions may arrive as new messages.'
  [ -n "${4:-}" ] && line2='This session is non-interactive. Work from this message and stop when done; results go IN the declared deliverable file — chat output is not delivery. Further instructions may arrive as new messages.'
  printf '\n\n---\nHEADLESS PROTOCOL\n%s\n%s\n%s\n' \
    'Briefly restate the files/contracts, scope, and main risk. Unless the goal contract promises to review that restatement before work begins, start work immediately — do not idle waiting for approval to begin.' \
    "$line2" \
    "If completing the goal needs an external decision or prerequisite beyond your scope or authority, or when the goal contract tells you to stop and wait for the orchestrator (a promised pre-work review is such a gate — there you write the restatement itself), write it to $2/BLOCKED.md with the exact contents of $3 as its LAST line, then stop. Do not self-approve past a contract gate." >> "$1"
}

# THE provider list — generated by duplexctl from the one capability table. agentctl holds no
# provider knowledge of its own: allowlist, bin env, default binary, pinned argv, argv
# forwarding (= omp/claude's resume surface) and the resume flag all arrive as one row. A
# second, hand-maintained list here IS the drift the one-table rule exists to kill.
provider_row() { # $1 engine — stdout: the spec row, rc 1 = no such provider
  "$PY" "$CTL" providers --shell | awk -F'|' -v e="$1" '$1 == e { print; found = 1 }
                                                        END { exit found ? 0 : 1 }'
}
provider_names() { "$PY" "$CTL" providers | tr '\n' '|' | sed 's/|$//'; }

# Parameter-surface VALUE judgement (meta-line safety + the review seat's deliverable fence) is
# duplexctl's: `ctl check-params` owns both rules and prints its own refusal, because both are
# properties this shell does not own — the meta file format and the deliverable fence. Called
# before the start owns a fifo / meta / tmux session, so a refusal leaves nothing behind.

# A seat that watches / steers / stops ITSELF is a deadlock, and the typed face cannot see it:
# the seat's own turn can never end while that turn is blocked waiting for the seat's own
# deliverable, so `status` reads RUNNING with live tool frames for as long as the wait lasts
# (2026-09-02: a review seat burned 2h03m in `agentctl watch <itself>`). The pane exports
# AGENTCTL_SESSION, which makes the seat the one process that can recognize the request as
# self-directed. This is a PARAMETER-SURFACE refusal — rc 1, the same shape as an unknown
# session, decided before any verdict machinery runs, so it prints no `EXIT=` line, publishes
# nothing and is not a state-machine verdict.
# ACCEPTED BOUNDARY, not an adversary model: a seat that unsets the variable gets through. The
# refusal exists to stop the seat that does this BY MISTAKE, which is every observed case.
refuse_self() { # $1 verb  $2 target session
  [ -n "${AGENTCTL_SESSION:-}" ] || return 0
  [ "$2" = "$AGENTCTL_SESSION" ] || return 0
  echo "ERR: refusing 'agentctl $1 $2' — that is THIS seat's own session, and a seat that waits on itself deadlocks: your turn cannot end while it is blocked on your own deliverable (field 2026-09-02: one review seat spent 2h03m here, typed state RUNNING and tool frames live the whole time)" >&2
  echo "Instead: to stop and wait for a ruling, write <cwd>/BLOCKED.md and END your turn (that is exit 4 to the orchestrator); to report progress, write it INTO the declared deliverable. Neither needs you to observe yourself." >&2
  echo "Read: cto-orchestration/references/agentctl/README.md §Launch" >&2
  exit 1
}

cmd_start() {
  ENG="${1:?usage}" ; S="${2:?session}" ; CWD="${3:?cwd}"; shift 3
  refuse_self start "$S"
  PROW="$(provider_row "$ENG")" || { echo "ERR: unknown engine '$ENG' ($(provider_names)) — see agentctl capabilities" >&2; exit 1; }
  P_BIN_ENV="${PROW#*|}"; P_BIN_ENV="${P_BIN_ENV%%|*}"
  P_REST="${PROW#*|*|}"; P_BIN="${P_REST%%|*}"
  P_REST="${P_REST#*|}"; P_ARGV="${P_REST%%|*}"
  P_REST="${P_REST#*|}"; P_EXTRA_OK="${P_REST%%|*}"
  P_REST="${P_REST#*|}"; P_RESUME_FLAG="${P_REST%%|*}"
  # `${var#*|}` returns the string UNCHANGED when there is no delimiter left, so an older
  # SIX-field row handed the resume flag over AS the review tier: `--review` was then accepted
  # and the banner claimed a sandbox the producer never promised — a permission fail-open on the
  # exact compatibility path (review R1 B3). Field 7 exists only if a delimiter remains.
  # Empty = this provider declares no OS sandbox tier, which is what makes `--review` a typed
  # refusal below rather than a flag that quietly does nothing.
  case "$P_REST" in *"|"*) P_REVIEW_SANDBOX="${P_REST#*|}";; *) P_REVIEW_SANDBOX="";; esac
  case "$P_BIN_ENV" in ''|*[!A-Z0-9_]*) echo "ERR: provider spec for '$ENG' is malformed (bin env '$P_BIN_ENV')" >&2; exit 1;; esac
  GOAL=""; DELIV=""; PREFLIGHT=1; EXTRA=(); WORKFLOW=""; MAX_ROUNDS=""; MODEL=""; RESUME_THREAD=""; MODEL_TOKENS=0; REVIEW=""; EXPECT=""
  while [ "$#" -gt 0 ]; do case "$1" in
    --goal) GOAL="${2:?--goal needs a file}"; shift 2;;
    --deliverable) DELIV="${2:?--deliverable needs a glob}"; shift 2;;
    --no-preflight) PREFLIGHT=0; shift;;
    # pre-1.6.0 opt-in spelling; the gate is the default now — accepted as a no-op for one version
    --require-preflight) shift;;
    --workflow) WORKFLOW="${2:?--workflow needs a value}"; shift 2;;
    --max-rounds) MAX_ROUNDS="${2:?--max-rounds needs N}"; shift 2;;
    --resume-thread) RESUME_THREAD="${2:?--resume-thread needs an id}"; shift 2;;
    --review) REVIEW=1; shift;;
    # the round's wait budget in minutes: the VALUE is judged by check-params below, exactly
    # like every other value that reaches meta — this shell never decides what a number means
    --expect) EXPECT="${2:?--expect needs minutes}"; shift 2;;
    --model) MODEL="${2:?--model needs an id}"; EXTRA[${#EXTRA[@]}]="$1"; EXTRA[${#EXTRA[@]}]="$2"; MODEL_TOKENS=$((MODEL_TOKENS+2)); shift 2;;
    # an empty value is not a model: without this the flag zeroes MODEL, meta gets no model=
    # line, the pinned-argv rule drops the token, and the operator is told nothing at all
    --model=) echo "ERR: --model= needs an id — pass --model <id>, or omit the flag to take the engine default" >&2; exit 1;;
    --model=*) MODEL="${1#*=}"; EXTRA[${#EXTRA[@]}]="$1"; MODEL_TOKENS=$((MODEL_TOKENS+1)); shift;;
    *) EXTRA[${#EXTRA[@]}]="$1"; shift;;
  esac; done
  if [ -n "$WORKFLOW" ] || [ -n "$MAX_ROUNDS" ]; then
    [ "$WORKFLOW" = "review-loop" ] && [ -n "$MAX_ROUNDS" ] || { echo "ERR: --workflow review-loop and --max-rounds N must be provided together" >&2; exit 1; }
    case "$MAX_ROUNDS" in ''|*[!0-9]*) echo "ERR: --max-rounds must be a positive integer" >&2; exit 1;; esac
    [ "$MAX_ROUNDS" -gt 0 ] || { echo "ERR: --max-rounds must be a positive integer" >&2; exit 1; }
  fi
  [ -n "$GOAL" ] && [ -e "$GOAL" ] || { echo "ERR: --goal <file> required and must exist" >&2; exit 1; }
  # -s: an EXISTING empty goal (/dev/null included) is a contract with no content — the seat
  # correctly refuses to work and a whole round burns on BLOCKED-cleanup-recontract (field n=3)
  [ -s "$GOAL" ] || { echo "ERR: --goal file is empty ($GOAL) — an empty contract dispatches a seat with nothing to do; write the goal first" >&2; exit 1; }
  # THE DEFAULT MODEL NOBODY TYPED. With no --model a dispatched seat takes the ENGINE's own
  # default, which on an orchestrator's box is the orchestrator's own (expensive) model —
  # every cheap seat then costs top-tier tokens unless the operator retypes --model on every
  # start. `AGENTCTL_MODEL_<ENGINE>` (…_OMP / _CODEX / _CLAUDE, from the provider name upper-
  # cased) is exactly that retyping, done once in a shell profile: it stands in for the flag
  # and then takes the flag's WHOLE route — MODEL, EXTRA, MODEL_TOKENS — so argv-forwarding
  # and protocol-pinned engines each keep their single path and every downstream judgement
  # (check-params' meta-line safety, the pinned-argv token count) still weighs the value.
  # A TYPED --model always wins; an empty variable is not a setting.
  MODEL_SRC=""; MODEL_ENV_IGNORED=""
  MODEL_ENV="AGENTCTL_MODEL_$(printf %s "$ENG" | tr '[:lower:]' '[:upper:]')"
  eval "MODEL_ENV_VAL=\"\${$MODEL_ENV:-}\""
  # THE REVIEW SEAT IS NOT THE EXECUTION SEAT. Reading a diff and arguing about it is a
  # different job from writing the code, so an operator who wants a different model THERE has
  # had to retype --model on every `start --review`: both seats share one variable.
  # `AGENTCTL_MODEL_<ENGINE>_REVIEW` is that retyping done once. It is consulted ONLY when
  # --review marked this start, and when it holds a value it simply BECOMES the variable this
  # block is about — name, value and source alike. Nothing below branches on which of the two
  # spellings won: the flag's whole route, check-params' meta-line gate, the `(from …)`
  # annotation and the resume NOTE all read MODEL_ENV / MODEL_ENV_VAL, so the review default
  # inherits every judgement the base variable already faces and no gate is duplicated (two
  # copies of one rule are two rules that drift). Empty is not a setting here either: an
  # exported-but-blank _REVIEW falls through to the base variable instead of erasing it, and a
  # non-review start never reads _REVIEW at all.
  if [ -n "$REVIEW" ]; then
    eval "MODEL_ENV_REVIEW_VAL=\"\${${MODEL_ENV}_REVIEW:-}\""
    if [ -n "$MODEL_ENV_REVIEW_VAL" ]; then
      MODEL_ENV="${MODEL_ENV}_REVIEW"; MODEL_ENV_VAL="$MODEL_ENV_REVIEW_VAL"
    fi
  fi
  # THE GOAL'S TIER IS A MODEL DECISION TOO (owner ruling 2026-09-30). A deep goal is the one
  # that adds a 判断面; a light one has a reference implementation to follow. The operator has
  # been retyping --model on exactly the deep dispatches, so `AGENTCTL_MODEL_<ENGINE>_DEEP` is
  # that retyping done once, and like _REVIEW it simply BECOMES the variable this block is
  # about — name, value and source together, so no gate below is duplicated.
  # READ ONLY WHEN: no --model was typed (a typed flag is a request about THIS start), this is
  # not a --review (that seat has its own spelling above, and two tiers on one dispatch would
  # need a precedence nobody asked for), and not a --resume-thread (the thread keeps its
  # creation-time model, so swapping the NAME here would only change which variable the
  # ignore-NOTE blames). Cheap test first: with _DEEP unset nothing reads the goal at all.
  if [ -z "$REVIEW" ] && [ -z "$MODEL" ] && [ -z "$RESUME_THREAD" ]; then
    eval "MODEL_ENV_DEEP_VAL=\"\${${MODEL_ENV}_DEEP:-}\""
    if [ -n "$MODEL_ENV_DEEP_VAL" ] && goal_tier_deep "$GOAL"; then
      MODEL_ENV="${MODEL_ENV}_DEEP"; MODEL_ENV_VAL="$MODEL_ENV_DEEP_VAL"
    fi
  fi
  if [ -n "$MODEL_ENV_VAL" ] && [ -z "$MODEL" ]; then
    if [ -n "$RESUME_THREAD" ]; then
      # NOT the refusal below: that one answers a model the operator TYPED against a resume.
      # A profile-wide default is not a request about THIS start, and turning every resume on
      # such a box into rc1 would be the variable breaking a working command. The thread keeps
      # the model it was created with either way, so the only honest move is to say so — and
      # the saying is DEFERRED to the end of a start that really happened: a NOTE printed here
      # would announce a preserved thread model ahead of the resume-capability refusal below
      # (an engine that cannot resume at all), and ahead of the one gate that judges this
      # value's line shape. Only the flag is skipped; the value still faces check-params.
      MODEL_ENV_IGNORED=1
    else
      MODEL="$MODEL_ENV_VAL"; MODEL_SRC="$MODEL_ENV"
      EXTRA[${#EXTRA[@]}]="--model"; EXTRA[${#EXTRA[@]}]="$MODEL"
      MODEL_TOKENS=$((MODEL_TOKENS+2))
    fi
  fi
  # the review-tier refusals below stay HERE: they read the generated provider spec, which is
  # this shell's own input, and they decide nothing about a value's content
  if [ -n "$RESUME_THREAD" ] && [ "$P_RESUME_FLAG" != "--resume-thread" ]; then
    echo "ERR: --resume-thread only drives a provider whose resume capability declares it; '$ENG' does not — run 'agentctl capabilities' and read the resume note for $ENG" >&2; exit 1
  fi
  # --model with --resume-thread is not a supported pair, and a silent winner is the worst
  # possible answer: the resume handshake sends the threadId alone (a thread keeps the model
  # it was created with), so the requested model would be written to meta and then consumed
  # by nobody. Refused HERE — at the parameter surface, before this start owns a fifo, a meta
  # file, a tmux session or a handshake.
  if [ -n "$RESUME_THREAD" ] && [ -n "$MODEL" ]; then
    echo "ERR: --model cannot be combined with --resume-thread — a resumed thread keeps the model it was started with, so '$MODEL' would be dropped in silence: drop --model to resume thread '$RESUME_THREAD' on its own model, or drop --resume-thread to start a NEW thread on '$MODEL'" >&2
    exit 1
  fi
  # `--review` marks the review seat and selects its sandbox tier from the provider spec.
  # Two refusals, both HERE at the parameter surface — before this start owns a fifo, a meta
  # file, a tmux session or a handshake:
  #  * a provider that declares no tier — the lane must not accept a permission request it
  #    cannot deliver (an unhandled flag forwarded to an extra_argv engine is not a refusal).
  #  * with --resume-thread — thread/resume sends the threadId ALONE, so a resumed thread
  #    keeps its creation-time tier: `--review` here would stamp review=1 into meta and
  #    print a review banner for a thread whose start never selected the review tier —
  #    the lane's own record would misdescribe the thread. Holds even with tiers unified.
  if [ -n "$REVIEW" ] && [ -z "$P_REVIEW_SANDBOX" ]; then
    echo "ERR: --review needs a provider with an OS sandbox tier; '$ENG' declares none — the lane pins no sandbox for it at all, so there is nothing to select. Run 'agentctl capabilities' and read the permissionEnforcement row for $ENG; the review seat is codex" >&2
    exit 1
  fi
  if [ -n "$REVIEW" ] && [ -n "$RESUME_THREAD" ]; then
    echo "ERR: --review cannot be combined with --resume-thread — thread/resume carries only the threadId, so a resumed thread keeps its creation-time tier: stamping review=1 on it would make the lane's meta and banner claim a review dispatch the handshake never made. Drop --resume-thread to start a NEW review thread, or drop --review to continue thread '$RESUME_THREAD' as-is" >&2
    exit 1
  fi
  if [ "$PREFLIGHT" = 1 ]; then
    # the seat's cwd travels WITH the goal: the gate runs each PREMISE probe verbatim, and a
    # probe written against the seat's tree (`test -f x`, `grep -n y src/`) answers a different
    # question anywhere else. Not yet normalized/existence-checked here (that is the next two
    # lines, whose refusals stay in their current order) — an unusable cwd makes a probe
    # unrunnable, which this gate WARNs about and never blocks on.
    # …and so does the deliverable glob: the gate's write-set reading needs what THIS dispatch
    # declared it would produce, which is the only write-set source the goal text cannot state.
    GOAL_PREFLIGHT_CWD="$CWD" GOAL_PREFLIGHT_DELIVERABLE="$DELIV" "$HERE/../goal-preflight.py" "$GOAL" || {
      echo "HINT: mechanical / forensic / pure-research goals opt out explicitly — re-run with --no-preflight" >&2
      exit 1; }
  fi
  [ -d "$CWD" ] || { echo "ERR: cwd not found: $CWD" >&2; exit 1; }
  CWD="$(cd "$CWD" && pwd -P)"
  # every value that will reach meta, plus the review seat's deliverable fence, judged in ONE
  # duplexctl call against the NORMALIZED cwd — comparing against the caller's spelling would
  # let a symlinked or dot-laden cwd argument decide where the fence boundary is
  # An IGNORED default is judged here too, through the flag's own slot: it reaches no meta,
  # but it is about to be named on stderr, and a CR/LF value that no gate ever weighed is a
  # forged second line on any host that reads this output by line — plus it would sail on to
  # the operator's next, non-resume start. Same gate, same wording, same rc as a typed
  # --model, resume or not. (MODEL is empty whenever MODEL_ENV_IGNORED is set.)
  MODEL_CHECK="$MODEL"; [ -n "$MODEL_ENV_IGNORED" ] && MODEL_CHECK="$MODEL_ENV_VAL"
  ctl check-params --gate start --cwd "$CWD" ${REVIEW:+--review} \
     --deliverable "$DELIV" --model "$MODEL_CHECK" --resume-thread "$RESUME_THREAD" \
     --workflow "$WORKFLOW" --expect "$EXPECT" || exit 1
  mkdir -p "$DIR"

  # collisions: refuse ANY prior lane state or live tmux session BEFORE branching to an engine
  [ "$(lane_of "$S")" = none ] || { echo "ERR: session '$S' already exists ($(lane_of "$S") lane) — agentctl stop $S or pick a new name" >&2; exit 1; }
  tmux has-session -t "=$S" 2>/dev/null && { echo "ERR: tmux session '$S' already exists" >&2; exit 1; }

  FIFO="$DIR/$S.duplex.in"; EV="$DIR/$S.duplex.events.jsonl"
  ERR="$DIR/$S.duplex.stderr.log"; RC="$DIR/$S.duplex.rc"
  # mkfifo IS the atomic claim (EEXIST = concurrent start or crash residue); no rm -f first —
  # that TOCTOU orphaned a just-started engine. stop unlinks the fifo.
  if ! mkfifo "$FIFO" 2>/dev/null; then
    echo "ERR: session '$S' fifo already exists ($FIFO) — concurrent start, or crash residue: agentctl stop $S first" >&2; exit 1
  fi
  # record + publish debris share one lifecycle (else the NEXT attempt reads PUBLISH_INTERRUPTED
  # forever); the temp glob is session-scoped, so it cannot reach a sibling
  rm -f "$RC" "$DIR/$S.terminal.json" "$DIR"/".$S.terminal.json-"*.tmp \
        "$DIR/$S.terminal.consumed.json"; : > "$EV"; : > "$ERR"
  # nor the PREVIOUS life's sensing loop: an orphan supervisor would classify under a dead lease
  retire_supervisor "$S"
  # nor its predecessor's authority: an identity that cannot be dropped REFUSES the start
  if ! CLEAR_OUT="$(ctl identity clear "$S" 2>&1)"; then
    echo "ERR: cannot clear the previous identity for '$S' — $CLEAR_OUT" >&2
    echo "HINT: another process may hold the identity lock, or $DIR/$S.identity.lock is unreadable" >&2
    rm -f "$FIFO"; exit 1
  fi

  EXTRA_Q=""  # zero args to `printf ' %q'` would still format once → a literal '' engine arg
  [ "${#EXTRA[@]}" -gt 0 ] && EXTRA_Q="$(printf ' %q' "${EXTRA[@]}")"
  eval "BIN=\"\${$P_BIN_ENV:-}\""
  [ -n "$BIN" ] || BIN="$P_BIN"
  # extra_argv=0: engine config rides the protocol (--model into meta), any other argv REFUSED
  if [ "$P_EXTRA_OK" != 1 ] && [ "${#EXTRA[@]}" -ne "$MODEL_TOKENS" ]; then
    echo "ERR: $ENG duplex takes engine config via protocol (--model/--resume-thread/--review only) — unrecognized argv: ${EXTRA[*]}" >&2
    rm -f "$FIFO" "$DIR/$S.duplex.meta"; exit 1
  fi
  # extra_argv=0: argv stays PINNED — model rides the protocol only (meta model= is consumed
  # by the engine handshake, e.g. codex thread/start params). Appending --model to argv killed
  # the launch outright: codex app-server rejects any CLI arg (field 2026-08-10, clap usage
  # error before the engine ever spoke).
  [ "$P_EXTRA_OK" = 1 ] || EXTRA_Q=""
  ECMD="$(q "$BIN")${P_ARGV:+ $P_ARGV}$EXTRA_Q"
  { printf 'engine=%s\ncwd=%s\n' "$ENG" "$CWD"
    [ -n "$DELIV" ] && printf 'deliverable=%s\n' "$DELIV"
    [ -n "$MODEL" ] && printf 'model=%s\n' "$MODEL"
    [ -n "$RESUME_THREAD" ] && printf 'resume_thread=%s\n' "$RESUME_THREAD"
    [ -n "$REVIEW" ] && printf 'review=1\n'
    [ -n "$EXPECT" ] && printf 'expect_min=%s\n' "$EXPECT"
    [ -n "$WORKFLOW" ] && printf 'workflow=%s\nmax_rounds=%s\n' "$WORKFLOW" "$MAX_ROUNDS"; } > "$DIR/$S.duplex.meta"

  # exec 3<> holds the fifo read-write so stdin NEVER sees EOF; rc goes out tmp+rename.
  # AGENTCTL_SESSION is exported here — the ONE pane assembly point all three engines share —
  # because a seat cannot otherwise know its own session name: the goal frame never carries it
  # and the engine has no lane state of its own. It is the whole input to refuse_self.
  # AGENTCTL_CWD rides beside it as the OWNERSHIP half of the same label: every exec'd
  # descendant inherits both, so a child that setsid()s out of the pane's group still carries
  # which seat made it AND which directory it serves. Both are LABELS, not switches — nothing
  # branches on their presence, and a process without them is simply unattributable.
  # The engine's stdout goes through JOURNAL_FILTER before the journal. WHY each part:
  # · WHOLE LINE, not a rewrite: omp re-embeds the whole message-so-far as `partial` in every
  #   delta frame, so one message costs O(L²) bytes (field 2026-09-30: 3.5GB in 35min, classify
  #   past its 30s budget, a live seat published as ENGINE-SILENT). No reader here reads a
  #   delta frame or a `partial` — the matching `*_end` frame carries the full text — so the
  #   three delta subtypes are pure ballast and every surviving line stays BYTE-identical.
  # · PREFIX-ANCHORED, no `.*`: omp's key order puts the subtype in the first ~70 bytes, so the
  #   match is decided there; an unanchored pattern would also drop any KEPT frame that merely
  #   quotes that text inside its payload (a tool result echoing a stream, say), and a `.*`
  #   would walk megabyte lines for nothing.
  # · LC_ALL=C -a --line-buffered: bytes not characters (a stray invalid UTF-8 byte must not
  #   turn the stream "binary" and silence grep), and a line reaches the journal the moment the
  #   engine emits it — the stall probe reads this file's mtime, block buffering would freeze it.
  # · rc INSIDE the group: `$RC` must land when the ENGINE exits, not when the pipe closes (a
  #   lingering grandchild can hold the write end open long after). PIPESTATUS is out of the
  #   question anyway — the pane runs under tmux's default-shell, which is not always bash.
  PANE="export AGENTCTL_SESSION=$(q "$S") AGENTCTL_CWD=$(q "$CWD"); exec 3<>$(q "$FIFO"); { $ECMD <&3 2>> $(q "$ERR"); e=\$?; echo \$e > $(q "$RC").tmp && mv $(q "$RC").tmp $(q "$RC"); } | $JOURNAL_FILTER_CMD $(q "$JOURNAL_FILTER_RE") >> $(q "$EV") 2>> $(q "$ERR")"
  if ! tmux new-session -d -s "$S" -c "$CWD" "$PANE"; then
    rm -f "$FIFO" "$DIR/$S.duplex.meta"
    echo "ERR: tmux new-session failed for '$S' (nothing started)" >&2; exit 1
  fi

  # pane pgid for reap-at-stop: pid alone is recyclable, so pair it with the leader's start time
  PANE_PID="$(tmux display-message -p -t "=$S:" '#{pane_pid}' 2>/dev/null)"
  PANE_LSTART="$(ps -p "${PANE_PID:-0}" -o lstart= 2>/dev/null | sed 's/ *$//')"
  [ -n "$PANE_PID" ] && [ -n "$PANE_LSTART" ] \
    && printf 'pane_pid=%s\npane_lstart=%s\n' "$PANE_PID" "$PANE_LSTART" >> "$DIR/$S.duplex.meta"
  # pin remain-on-exit off: inherited "on" outlives a DEAD pane and stop's live #{pane_pid}
  # read would hand reap an exited, recyclable pid (review S1)
  tmux set-option -w -t "=$S:" remain-on-exit off 2>/dev/null || true

  if ! ctl wait-ready "$S" --wait 20; then
    echo "ERR: engine handshake failed — cleaning up. stderr tail:" >&2
    tail -c 800 "$ERR" >&2 2>/dev/null || true
    tmux kill-session -t "=$S" 2>/dev/null; reap_tree "$PANE_PID" ""
    rm -f "$FIFO" "$DIR/$S.duplex.meta"
    exit 1
  fi

  PROMPT="$DIR/$S.duplex.prompt"
  cat "$GOAL" > "$PROMPT"; append_footer "$PROMPT" "$CWD" "$DIR/$S.identity.d/blocked-stamp.txt" "$DELIV"
  ctl send "$S" --verb prompt --file "$PROMPT" || {
    echo "ERR: goal delivery failed — engine up but prompt not accepted; inspect then agentctl stop $S" >&2; exit 2; }
  echo "started $ENG → duplex session '$S' (cwd $CWD; tmux supervises, protocol steers)"
  echo "events : $EV (raw stays on disk; status/watch print bounded summaries only)"
  # What was REQUESTED, and by which route — never what took effect. The request reaches the
  # engine two different ways (argv for the forwarding providers, meta + protocol for the
  # pinned ones), and nothing here reads back the model the engine actually settled on.
  REQ="${MODEL:+model=$MODEL}"
  # WHOSE request it was: a model nobody typed reads as a mystery on the operator's screen
  # (and on codex it is invisible in argv), so the variable that supplied it is named here.
  [ -n "$MODEL_SRC" ] && REQ="$REQ (from $MODEL_SRC)"
  [ -n "$REVIEW" ] && REQ="${REQ:+$REQ; }review sandbox=$P_REVIEW_SANDBOX"
  if [ "$P_EXTRA_OK" = 1 ] && [ "${#EXTRA[@]}" -gt 0 ]; then REQ="${REQ:+$REQ; }argv ${EXTRA[*]}"; fi
  # the default nobody's start could use: named, never quoted — the variable NAME is a closed
  # set of three, so this line cannot be anything but one line, whatever the value held
  [ -n "$MODEL_ENV_IGNORED" ] && echo "NOTE: $MODEL_ENV is set but --resume-thread keeps the resumed thread on its creation-time model — ignored for this start" >&2
  echo "engine : $ENG — requested: ${REQ:-nothing (engine defaults apply)}; the model/backend actually in effect is the engine's own and is not read back here"
  echo "next   : agentctl watch $S   (blocking, run_in_background)  |  agentctl status $S  (one-shot)"
}

cmd_steer() {
  S="${1:?usage: agentctl steer <session> (-m TEXT | -f FILE) [--interrupt] [-d G]}"; shift
  refuse_self steer "$S"
  MODE=""; ARG=""; VERB="steer"; NEWDELIV=""
  while [ "$#" -gt 0 ]; do case "$1" in
    -m|-f) MODE="$1"; ARG="${2:?$1 needs a value}"; shift 2;;
    # ONE steering verb (default) + ONE escalation. `--replace` is kept as a SILENT alias of
    # the renamed escalation so live runbooks keep working; `--now` is GONE, because a
    # plain steer already delivers as soon as the engine allows (the flag existed to opt IN
    # to that, and forgetting it is what queued rulings behind 35-60min turns in the field).
    --interrupt|--replace) VERB="interrupt"; shift;;
    --now) echo "ERR: --now was removed: a plain 'agentctl steer' now delivers as soon as the engine allows (mid-turn where the engine has that route, next turn when idle). Drop the flag; use --interrupt to abandon the running turn." >&2; exit 1;;
    -d|--deliverable) NEWDELIV="${2:?-d needs a glob}"; shift 2;;
    *) echo "ERR: unknown steer option '$1'" >&2; usage;;
  esac; done
  [ -n "$MODE" ] || usage
  case "$(lane_of "$S")" in
    duplex)
      REVIEW_META="$(meta_get "$S" review)"
      [ "$MODE" = -f ] && { [ -e "$ARG" ] || { echo "ERR: file not found: $ARG" >&2; exit 1; }; }
      # `steer -d` moves the freshness target into the SAME line-oriented meta and past the SAME
      # fence, so it clears the same gate `start` did — otherwise a session that opened
      # compliant is walked outside its fence by one steer. Only when `-d` is present:
      # a plain steer writes no new value, so there is nothing to judge.
      if [ -n "$NEWDELIV" ]; then
        ctl check-params --gate "steer -d" --cwd "$(meta_get "$S" cwd)" \
           ${REVIEW_META:+--review} --deliverable "$NEWDELIV" || exit 1
      fi
      # The terminal record is NOT cleared here: a REFUSED steer opens no round and the
      # conclusion it would destroy is still every attached waiter's answer (R2 F-02) — duplexctl
      # unlinks it inside commit_round_state, at the instant the round counter moves.
      # `--interrupt` mints a NEW attempt, so the supervisor is about to go stale: retire it here.
      [ "$VERB" = interrupt ] && retire_supervisor "$S" "agentctl steer --interrupt is opening a new attempt"
      # -d rides duplexctl: applied atomically, only after delivery
      if [ "$MODE" = -f ]; then exec "$PY" "$CTL" --run-dir "$DIR" send "$S" --verb "$VERB" --file "$ARG" ${NEWDELIV:+--deliverable "$NEWDELIV"}
      else exec "$PY" "$CTL" --run-dir "$DIR" send "$S" --verb "$VERB" --text "$ARG" ${NEWDELIV:+--deliverable "$NEWDELIV"}; fi ;;
    none) echo "ERR: unknown session '$S' (no duplex state)" >&2; exit 1 ;;
  esac
}

cmd_status() {
  S="${1:?usage: agentctl status <session>}"
  refuse_self status "$S"
  case "$(lane_of "$S")" in
    duplex) exec "$PY" "$CTL" --run-dir "$DIR" status "$S" ;;
    none)   echo "ERR: unknown session '$S'" >&2; exit 1 ;;
  esac
}

# every watch exit prints twice: `=== … ===` for humans, `EXIT=<n>` for a wrapper that swallows
# the exit code and can still parse the verdict off the last line.
watch_exit() { # $1 rc
  echo "EXIT=$1"; exit "$1"
}

# The waiter verbs' two internal continuation codes. Opaque numbers, exactly like the 13 below:
# python decides whether a round's outcome ends the waiter, the shell only re-arms when told to
# and counts how often it has (the CEILING is the verb's, from AGENT_WATCH_FOLLOW_MAX).
FOLLOW_ROTATED=16   # a steer opened the next round: re-arm on it, and it costs no budget
FOLLOW_REARM=17     # a reported non-action verdict: re-arm, one unit of the bounded budget

# ── supervised watch ──────────────────────────────────────────────────────────────────
# The host reaps orchestrator-side background tasks (field 2026-08-08: ≥6 kills in 40min), so
# the sensing loop lives in tmux — the one place here the reaper does not reach — and
# `agentctl watch` is a DUMB WAITER over the fenced record: killing it costs a re-run, never a
# conclusion (`--inline` keeps the pre-supervised loop). What is left HERE is the tmux half:
# claiming the singleton session name (server-side, atomic) and killing a pane plus its group.
supervisor_of() { printf '%s-watchd\n' "$1"; }   # its OWN tmux session, never a worker window

# Every knob is spelled into the pane command: the loop cannot silently run with other bounds.
supervisor_env() {
  local out="AGENT_WATCH_DIR=$(q "$DIR") " k v
  for k in PATH AGENTCTL_PYTHON AGENT_WATCH_POLL_SECS AGENT_WATCH_MAX_POLLS \
           AGENT_WATCH_SILENT_POLLS AGENT_WATCH_STATUS_TIMEOUT AGENT_WATCH_STALL_MINS \
           AGENT_WATCH_PROGRESS_MINS \
           AGENTCTL_REAP_GRACE AGENTCTL_PUBLISH_BARRIER TMPDIR; do
    eval "v=\${$k:-}"
    [ -n "$v" ] && out="$out$k=$(q "$v") "
  done
  printf '%s' "$out"
}

# Retirement is identity lifecycle, not housekeeping: a supervisor that outlived its attempt
# would sense a round it cannot speak for. Pane here; last words then lease in the verb.
retire_supervisor() { # $1 session  [$2 why — left as the supervisor's last words for a waiter]
  local sup pane
  sup="$(supervisor_of "$1")"
  if tmux has-session -t "=$sup" 2>/dev/null; then
    pane="$(tmux display-message -p -t "=$sup:" '#{pane_pid}' 2>/dev/null)"
    tmux kill-session -t "=$sup" 2>/dev/null
    reap_tree "$pane" "" >/dev/null 2>&1
  fi
  if [ -n "${2:-}" ]; then ctl supervisor-retire "$1" --why "$2"
  else ctl supervisor-retire "$1"; fi
  return 0
}

# rc 0 = sensing under THIS identity; 1 = structurally impossible (degrade to --inline, loudly);
# 2 = undecidable, NOT a licence to sense inline. STDOUT is the diagnosis.
ensure_supervisor() { # $1 session
  local sup cmd cwd rc mine
  sup="$(supervisor_of "$1")"
  ctl watch-arm-check "$1" --armed-seq "$ARMED_SEQ"; rc=$?
  case "$rc" in
    0|1|2) return "$rc" ;;
    4) retire_supervisor "$1" ;;
  esac
  cwd="$(meta_get "$1" cwd)"; [ -d "$cwd" ] || cwd="$DIR"
  cmd="$(supervisor_env)exec bash $(q "$SELFABS") watch-daemon $(q "$1") >> $(q "$DIR/$1.watch.super.log") 2>&1"
  # tmux session-name uniqueness IS the singleton claim: WHO WON THE NAME is the only honest
  # answer to "whose supervisor is this?" — a later has-session poll cannot tell.
  mine=1
  if ! tmux new-session -d -s "$sup" -c "$cwd" "$cmd" 2>/dev/null; then
    # Losing the race is not an error — but the winner is NOT ours, so it must prove it leases.
    mine=0
    tmux has-session -t "=$sup" 2>/dev/null || {
      echo "tmux refused to create session '$sup' and no session by that name exists"; return 1; }
  fi
  ctl watch-arm-wait "$1" --mine "$mine"; rc=$?
  # 4 = our own pane never leased: retire it (a leaseless pane reads as a rogue), then degrade
  [ "$rc" = 4 ] && { retire_supervisor "$1"; return 1; }
  return "$rc"
}

# External kills are non-deterministic and the sender is invisible from inside the sandbox:
# leave an attributable tombstone, clean the pid file. The child goes FIRST — a survivor could
# still deliver a conclusion for a waiter that is gone.
on_sig() { # $1 signal-name  $2 exit-code
  [ -n "${CHILD:-}" ] && kill "$CHILD" 2>/dev/null
  ctl watch-tombstone "$S" --signal "$1" --ppid "$PPID" --uptime "$SECONDS"
  rm -f "$WPID"; exit "$2"
}

# `wait` on a backgrounded child: a foreground command defers a trapped TERM until it finishes
# (probed: 14s) and the tombstone would lose its TERM→KILL grace window.
# The interpreter is spawned DIRECTLY, never through `ctl`: backgrounding a shell FUNCTION forks
# a wrapper subshell, so `$!` named the wrapper and on_sig's kill missed the READER — which then
# survived, re-parented to init, and DELIVERED this round's conclusion (rotating terminal.json to
# .consumed.json) for a waiter already dead, so the next `agentctl watch` rightly refused the
# spent record and re-derived the class under a SECOND supervisor (Linux CI: M09 swSILENT got[2]).
run_child() { # $@ — duplexctl subcommand + args; rc = the child process's
  "$PY" "$CTL" --run-dir "$DIR" "$@" & CHILD=$!
  wait "$CHILD"
}
sense_inline() { # $1 session — the in-process fallback loop (no supervisor, not kill-resilient)
  run_child sense-loop "$1" --mode inline --armed "$ARMED_ID"
}

cmd_watch() {
  S=""; MODE=supervised; EXPECT=""
  while [ "$#" -gt 0 ]; do case "$1" in
    --inline) MODE=inline; shift;;
    --expect) EXPECT="${2:?--expect needs minutes}"; shift 2;;
    -*) echo "ERR: unknown watch option '$1'" >&2; usage;;
    *) [ -n "$S" ] && { echo "ERR: watch takes exactly one session" >&2; usage; }; S="$1"; shift;;
  esac; done
  [ -n "$S" ] || usage
  # AFTER the target is parsed and BEFORE anything else: a watch with no parsable session is a
  # usage error (above), never a self-request — nothing may be judged self on an empty target
  refuse_self watch "$S"
  [ "$(lane_of "$S")" = duplex ] || { echo "ERR: unknown session '$S'" >&2; exit 1; }
  # OVERRIDES the session's budget for every round from here on, before this waiter arms: the
  # value is judged and written by duplexctl (the single meta writer), a refusal ends the watch
  # rather than silently waiting under the old number.
  [ -n "$EXPECT" ] && { ctl set-expect "$S" --minutes "$EXPECT" || exit 1; }
  WPID="$DIR/$S.duplex.watch.pid"
  trap 'rm -f "$WPID"' EXIT
  trap 'on_sig TERM 143' TERM; trap 'on_sig INT 130' INT
  # Poll cadence, the poll budget, the ENGINE-SILENT bound and the follow ceiling are AGENT_WATCH_*
  # env knobs read by the loop verbs themselves — the shell forwards the environment, not a copy
  # of the defaults.
  # FOLLOW: one arm per EPISODE, and a session has as many episodes as it has rounds. The two
  # arm-time snapshots every later decision is fenced by are therefore re-captured per episode,
  # never carried across one: the identity this watcher may publish under, and the delivery
  # watermark for the episode it is entering. Opaque here — the shell forwards them, it never
  # compares them.
  FOLLOWED=0
  while : ; do
    ARMED_ID="$(ctl identity token "$S" 2>/dev/null)"
    ARMED_SEQ="$(ctl identity watermark "$S" 2>/dev/null)"
    [ -n "${ARMED_SEQ:-}" ] || ARMED_SEQ=0
    ctl watch-arm "$S" --pid $$ --mode "$MODE"
    [ "$MODE" = inline ] && { sense_inline "$S"; exit $?; }
    # arm-time read: a conclusion on disk IS this episode's answer. 13 = keep going; a follow
    # code = it was reported and this waiter goes round again; anything else is the verdict,
    # already printed, and is forwarded untouched.
    run_child watch-arm-read "$S" --armed-seq "$ARMED_SEQ" --followed "$FOLLOWED"; rc=$?
    case "$rc" in
      13) ;;
      "$FOLLOW_REARM") FOLLOWED=$((FOLLOWED + 1)); continue ;;
      *) exit "$rc" ;;
    esac
    sup_why="$(ensure_supervisor "$S")"; sup_rc=$?
    if [ "$sup_rc" = 2 ]; then
      # undecidable, NOT a licence to sense inline: the four-state machine's ④.
      echo "=== [$S] SUPERVISOR-LOST: reason=unknown $sup_why ==="
      watch_exit 12
    fi
    if [ "$sup_rc" != 0 ]; then
      echo "NOTE: the tmux watch supervisor for '$S' is structurally impossible here — $sup_why. Falling back to the in-process --inline sensing loop: this watch is NOT kill-resilient (an external TERM loses this round's conclusion) and persists no non-DONE class." >&2
      sense_inline "$S"; exit $?
    fi
    echo "[$S] supervised: sensing runs in tmux session $(supervisor_of "$S") (log $DIR/$S.watch.super.log); this waiter only reads the fenced terminal record"
    run_child watch-wait "$S" --armed-seq "$ARMED_SEQ" --followed "$FOLLOWED"; rc=$?
    case "$rc" in
      "$FOLLOW_ROTATED") ;;
      "$FOLLOW_REARM") FOLLOWED=$((FOLLOWED + 1)) ;;
      *) exit "$rc" ;;
    esac
  done
}

cmd_watch_daemon() { # INTERNAL — the sensing loop, launched by ensure_supervisor inside tmux
  S="${1:?usage: agentctl watch-daemon <session>}"
  [ "$(lane_of "$S")" = duplex ] || { echo "ERR: unknown session '$S'" >&2; exit 1; }
  ARMED_ID="$(ctl identity token "$S" 2>/dev/null)"
  # exec: the loop IS the pane process, so kill-session reaches it and its own handlers (which
  # leave the last words) are the prompt ones
  exec "$PY" "$CTL" --run-dir "$DIR" sense-loop "$S" --mode daemon --armed "$ARMED_ID"
}

cmd_stop() {
  S="${1:?usage: agentctl stop <session>}"
  refuse_self stop "$S"
  # WHO this stop is ending, captured NOW — before the supervisor is retired, before cleanup
  # clears the identity record, and therefore before the name is free for a same-name start to
  # claim. Opaque here: the shell never parses it, it only carries it to the verb that records
  # the ledger's stop row. Resolving the identity AFTER cleanup used to mean looking up "the
  # newest ledger row for this name", and a restart that got its `start` row in first stole the
  # old stop and closed a seat that had just begun (review R1 B3).
  STOP_ID="$(ctl identity token "$S" 2>/dev/null)"
  case "$(lane_of "$S")" in
    duplex)
      # Read the reap identity BEFORE the kill: the live pane pid is only trustworthy while the
      # pane is ALIVE (review S1); a dead pane falls back to the meta pid+lstart fingerprint. The
      # supervisor goes down FIRST — it must not publish for a session being torn down.
      retire_supervisor "$S"
      live="$(tmux display-message -p -t "=$S:" '#{pane_dead} #{pane_pid}' 2>/dev/null)"
      live_pg=""; case "$live" in "0 "*) live_pg="${live#0 }";; esac
      meta_pg="$(meta_get "$S" pane_pid)"; meta_ls="$(meta_get "$S" pane_lstart)"
      # snapshot BEFORE the kill: after it, the pane is gone and its escapees unattributable
      survivor_probe "$S" "${live_pg:-$meta_pg}"
      tmux kill-session -t "=$S" 2>/dev/null && echo "killed tmux session $S" || echo "no tmux session $S"
      # Cleanup precedes the reap: the marker guard prices in a µs kill→cleanup gap, a grace-long
      # reap would stretch it to seconds (S3). The sentinel brackets the reap from INSIDE these two
      # verbs — no timestamp in this shell, only an opaque token fencing part 2 to part 1's sample.
      STOP_TOK="$$-$RANDOM"; ctl stop-cleanup "$S" --token "$STOP_TOK"; ID_RC=$?
      if [ -n "$live_pg" ]; then reap_tree "$live_pg" ""
      else reap_tree "$meta_pg" "$meta_ls"; fi
      REAP_RC=$?
      survivor_advise "$S"
      # The label phase runs AFTER the group reap, in BOTH branches and unconditionally: a
      # session with no pane and no meta left is exactly the post-mortem `agentctl stop <s>`
      # an `inventory` lineage-orphan row sends an operator to, and it is the only exit.
      lineage_reap "$S"; LIN_RC=$?
      # The sentinel keeps the GROUP rc: it decides whether the SEAT ended, and a stray
      # labelled tool outliving its KILL does not un-end a seat whose pane group is gone.
      # stop's own exit is the max, so the failure is never silent either.
      ctl stop-sentinel "$S" --token "$STOP_TOK" --reap-rc "$REAP_RC" --identity "$STOP_ID"
      # a refused identity clear fails stop's contract: the name is not free to reuse
      [ "$ID_RC" = 0 ] || exit 1
      [ "$LIN_RC" -gt "$REAP_RC" ] && REAP_RC="$LIN_RC"
      exit "$REAP_RC" ;;
    none)
      # no lane meta: clean bare tmux AND orphan duplex claims — the recovery path start advertises
      cleaned=0; reap_rc=0
      retire_supervisor "$S"
      if tmux has-session -t "=$S" 2>/dev/null; then
        live="$(tmux display-message -p -t "=$S:" '#{pane_dead} #{pane_pid}' 2>/dev/null)"
        live_pg=""; case "$live" in "0 "*) live_pg="${live#0 }";; esac
        survivor_probe "$S" "$live_pg"
        tmux kill-session -t "=$S" 2>/dev/null; reap_tree "$live_pg" "" || reap_rc=1
        survivor_advise "$S"
        echo "killed bare tmux session $S"; cleaned=1
      fi
      lineage_reap "$S"; lin_rc=$?
      ctl stop-residue "$S" --killed "$cleaned" --reap-rc "$reap_rc" --identity "$STOP_ID"; res_rc=$?
      # STOP_RESIDUE_NONE = the residue verb found nothing of its own: an unknown name, or the
      # post-mortem exit an `inventory` lineage-orphan row sends an operator to? Only a DECIDED
      # empty answer reads as a name that never existed — a REFUSED candidate (planner rc 3) counts.
      if [ "$res_rc" = "$STOP_RESIDUE_NONE" ]; then
        res_rc=0
        [ "$LINEAGE_SEEN" != 0 ] || { echo "ERR: unknown session '$S' (no lane state, no tmux session, no residue)" >&2; res_rc=1; }
      fi
      [ "$lin_rc" -gt "$res_rc" ] && res_rc="$lin_rc"
      exit "$res_rc" ;;
  esac
}

case "${1:-}" in
  start)  shift; cmd_start "$@" ;;
  watch-daemon) shift; cmd_watch_daemon "$@" ;;
  steer)  shift; cmd_steer "$@" ;;
  status) shift; cmd_status "$@" ;;
  watch)  shift; cmd_watch "$@" ;;
  capabilities) shift; case "${1:-}" in
            "") "$PY" "$CTL" capabilities ;;
            --json) "$PY" "$CTL" capabilities --json ;;
            *) echo "ERR: unknown capabilities option '$1' (only --json)" >&2; exit 1 ;;
          esac ;;
  # exactly two spellings; anything else (including an extra word after --json) is refused
  states) shift; case "$#:${1:-}" in
            "0:")       "$PY" "$CTL" states ;;
            "1:--json") "$PY" "$CTL" states --json ;;
            *) echo "ERR: states is read-only and is spelled 'agentctl states' or 'agentctl states --json' — got: $*" >&2; exit 1 ;;
          esac ;;
  # read-only by construction: the argument contract is refused HERE, before any probe runs
  inventory) shift; case "${1:-}" in
            --dry-run) [ "$#" -eq 1 ] || { echo "ERR: inventory takes nothing beyond --dry-run (got: ${*:2})" >&2; exit 1; }
                       exec "$PY" "$CTL" --run-dir "$DIR" inventory --dry-run ;;
            *) echo "ERR: inventory is read-only and is spelled 'agentctl inventory --dry-run'${1:+ — got '$1'}; there is no --apply" >&2; exit 1 ;;
          esac ;;
  # phase-ledger readings. Argument JUDGEMENT is duplexctl's (`--since` grammar, `--repo`
  # containment): this shell forwards argv untouched and the strict parser refuses the rest.
  phases) shift; exec "$PY" "$CTL" --run-dir "$DIR" phases "$@" ;;
  closeout) shift; exec "$PY" "$CTL" --run-dir "$DIR" closeout "$@" ;;
  stop)   shift; cmd_stop "$@" ;;
  ""|-h|--help) usage ;;
  *) echo "ERR: unknown subcommand '${1}'" >&2; usage ;;
esac
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall