Skip to content

hashgraph-online/awesome-codex-plugins / plugins/beastlabai/multi-llm-plugin/skills/multi-llm

multi-llm

Flagged

Orchestrate plan reviews, task generation, implementation and code reviews across several LLM CLIs in parallel, or ask every model one free-text question about a plan. Use when the user says: review my plan, multi-llm, run a code review, generate tasks from a plan, implement this plan, ask the models about my plan.

FileKindSize
SKILL.mdskill md4.0 KB
apply_code_fixes_orchestrator.pyscript56.6 KB
apply_commit_fixes_orchestrator.pyscript2.3 KB
apply_suggestions_orchestrator.pyscript4.5 KB
apply_task_suggestions_orchestrator.pyscript19.1 KB
ask_orchestrator.pyscript162.5 KB
assets/icons/Anthropic.svgother584 B
assets/icons/Codex.svgother1.3 KB
assets/icons/Copilot.svgother1.5 KB
assets/icons/Cursor.svgother793 B
assets/icons/GoogleGemini.svgother623 B
assets/icons/Goose.svgother3.2 KB
assets/icons/Kilocode.svgother531 B
assets/icons/MiniMax.pngbinary1.5 KB
assets/icons/Mistral.svgother717 B
assets/icons/MoonshotAI.svgother957 B
assets/icons/Nvidia.svgother2.4 KB
assets/icons/OhMyPi.svgother434 B
assets/icons/OpenAI.svgother1.7 KB
assets/icons/Opencode.svgother325 B
assets/icons/Pi.svgother440 B
assets/icons/Qwen.svgother1.7 KB
assets/icons/Zhipu.pngbinary442 B
assets/icons/xAI.svgother343 B
assets/omp/overlay.ymlconfig2.4 KB
check_workflow_prerequisites.pyscript74.5 KB
code_review_orchestrator.pyscript324.0 KB
display_decisions.pyscript9.8 KB
finalize_tracking.pyscript1.3 KB
full_workflow_orchestrator.pyscript58.8 KB
generate_tasks_orchestrator.pyscript44.2 KB
hosts/capabilities.yamlconfig49.9 KB
hosts/codex/plugin-skill.md.tmplother2.8 KB
hosts/codex/shim.md.tmplother7.3 KB
hosts/opencode/plugin-command.md.tmplother2.2 KB
hosts/opencode/shim.md.tmplother6.8 KB
hosts/render_capabilities.pyscript48.4 KB
hosts/snippets/poll-loop.mdmarkdown4.4 KB
hosts/snippets/uv-preflight.mdmarkdown2.2 KB
hosts/uv-missing.txtmarkdown1.5 KB
implement_orchestrator.pyscript156.0 KB
improve_code_orchestrator.pyscript1.6 KB
improve_commits_orchestrator.pyscript2.5 KB
improve_plan_orchestrator.pyscript1.6 KB
init_config.pyscript57.6 KB
instructions/apply-code-fixes.mdmarkdown52.0 KB
instructions/apply-commit-fixes.mdmarkdown10.3 KB
instructions/apply-suggestions.mdmarkdown48.2 KB
instructions/apply-task-suggestions.mdmarkdown53.9 KB
instructions/ask.mdmarkdown27.6 KB
instructions/full-workflow.mdmarkdown24.6 KB
instructions/generate-tasks.mdmarkdown18.1 KB
instructions/implement.mdmarkdown54.0 KB
instructions/improve-code.mdmarkdown25.0 KB
instructions/improve-commits.mdmarkdown24.8 KB
instructions/improve-plan.mdmarkdown26.2 KB
instructions/init-config.mdmarkdown6.6 KB
instructions/review-code.mdmarkdown43.5 KB
instructions/review-commits.mdmarkdown11.4 KB
instructions/review-plan.mdmarkdown38.4 KB
instructions/review-tasks.mdmarkdown37.8 KB
modes.pyscript58.8 KB
multi_llm.pyscript101.1 KB
prompts/ask.txtmarkdown948 B
prompts/code_review.txtmarkdown4.5 KB
prompts/commit_review.txtmarkdown6.2 KB
prompts/consolidate_suggestions.txtmarkdown3.1 KB
prompts/implementation_task.txtmarkdown1.4 KB
prompts/plan_review.txtmarkdown8.0 KB
prompts/task_review.txtmarkdown8.3 KB
providers.yamlconfig19.6 KB
pyproject.tomlmanifest6.8 KB
references/apply-write-executor.mdmarkdown3.0 KB
references/consolidation.mdmarkdown5.6 KB
references/host-capabilities.mdmarkdown13.5 KB
references/human-decision-batch.mdmarkdown17.2 KB
references/implement-prerequisites.mdmarkdown6.0 KB
references/implement-write-executor.mdmarkdown4.9 KB
references/interrupted-run-recovery.mdmarkdown3.1 KB
references/own-check.mdmarkdown4.3 KB
references/resume-detection.mdmarkdown8.5 KB
references/revalidation.mdmarkdown6.9 KB
references/review-code-apply-fixes.mdmarkdown4.3 KB
references/salvage-handling.mdmarkdown12.5 KB
references/summary-format.mdmarkdown10.0 KB
references/uv-check.mdmarkdown5.7 KB
references/wave-batching.mdmarkdown5.2 KB
review_commits_orchestrator.pyscript2.3 KB
review_plan_orchestrator.pyexecutablescript22.3 KB
review_tasks_orchestrator.pyscript10.7 KB
schemas/cascade_record.schema.jsonconfig6.6 KB
schemas/code_review_issues.schema.jsonconfig2.0 KB
schemas/consolidated.schema.jsonconfig6.8 KB
schemas/consolidation_batch.schema.jsonconfig3.7 KB
schemas/generated_tasks.schema.jsonconfig3.1 KB
schemas/host_capabilities.schema.jsonconfig38.3 KB
schemas/human_decision_verdicts.schema.jsonconfig2.6 KB
schemas/result_line.schema.jsonconfig10.1 KB
schemas/review_suggestions.schema.jsonconfig2.4 KB
schemas/state_file.schema.jsonconfig21.5 KB
schemas/status_file.schema.jsonconfig24.9 KB
schemas/status_json.schema.jsonconfig10.8 KB
schemas/subagent_tasks.schema.jsonconfig20.5 KB
schemas/task_decomposition.schema.jsonconfig1.2 KB
schemas/write_batch_result.schema.jsonconfig8.8 KB
templates/config/providers.override.yamlconfig17.2 KB
templates/consolidated_report_template.htmlother44.1 KB
templates/pr_report_template.htmlother181.2 KB
templates/report_template.htmlother67.5 KB
templates/shared/report_core.cssother4.1 KB
templates/shared/report_core.jsscript25.5 KB
update_plan_tasks.pyscript20.9 KB
utils/__init__.pyscript284 B
utils/advisory.pyscript4.8 KB
utils/apply_orchestrator_base.pyscript220.6 KB
utils/apply_output_helpers.pyscript10.9 KB
utils/apply_path_helpers.pyscript683 B
utils/apply_report.pyscript51.2 KB
utils/apply_selection_helpers.pyscript6.8 KB
utils/apply_suggestion_phase.pyscript11.7 KB
utils/atomic_io.pyscript12.9 KB
utils/attempt_classifier.pyscript31.4 KB
utils/backup.pyscript2.0 KB
utils/batch_done.pyscript79.2 KB
utils/batch_ledger.pyscript27.4 KB
utils/batch_prompt.pyscript29.3 KB
utils/batch_prompt_builder.pyscript12.2 KB
utils/batch_reply.pyscript32.9 KB
utils/cascade_archive.pyscript50.6 KB
utils/cascade_ledger.pyscript39.3 KB
utils/cascade_provenance.pyscript22.0 KB
utils/check_records.pyscript59.3 KB
utils/check_reply.pyscript9.5 KB
utils/check_tree.pyscript1.2 KB
utils/cli_common.pyscript91.2 KB
utils/cli_version_cache.pyscript14.0 KB
utils/clock.pyscript3.5 KB
utils/code_fix_batcher.pyscript30.6 KB
utils/codex_trust.pyscript12.9 KB
utils/commit_apply.pyscript73.3 KB
utils/commit_attribution.pyscript21.2 KB
utils/commit_brief.pyscript32.2 KB
utils/commit_front_door.pyscript81.6 KB
utils/commit_paths.pyscript18.0 KB
utils/commit_range.pyscript61.2 KB
utils/commit_report.pyscript19.9 KB
utils/commit_review.pyscript413 B
utils/commit_spelling.pyscript7.9 KB
utils/commit_write_guard.pyscript9.9 KB
utils/concurrency.pyscript11.6 KB
utils/consolidation.pyscript87.3 KB
utils/detach.pyscript186.8 KB
utils/dispatch_spawn.pyscript56.3 KB
utils/doctor.pyscript76.7 KB
utils/env_vars.pyscript20.5 KB
utils/failure_capture.pyscript10.1 KB
utils/file_discovery.pyscript11.0 KB
utils/filtering.pyscript19.9 KB
utils/git_diff.pyscript23.6 KB
utils/git_utils.pyscript86.6 KB
utils/held_folder.pyscript21.3 KB
utils/host_capabilities.pyscript48.0 KB
utils/host_install.pyscript77.6 KB
utils/host_paths.pyscript12.0 KB
utils/host_routes/__init__.pyscript5.7 KB
utils/host_routes/codex.pyscript18.3 KB
utils/host_routes/npm.pyscript12.2 KB
utils/host_shim.pyscript14.7 KB
utils/html_report_generator.pyscript118.9 KB
utils/human_decisions.pyscript38.3 KB
utils/human_task_plan.pyscript30.2 KB
utils/importance.pyscript6.2 KB
utils/improve_cascade.pyscript63.7 KB
utils/improve_cascade_next.pyscript22.2 KB
utils/improve_steps.pyscript32.4 KB
utils/improve_workflow.pyscript114.4 KB
utils/interactive.pyscript31.6 KB
utils/json_extractor.pyscript61.5 KB
utils/judge_vocab.pyscript5.3 KB
utils/known_checks.pyscript37.5 KB
utils/landlock_dispatch.pyscript103.8 KB
utils/landlock_exec.pyscript21.4 KB
utils/launch_limiter.pyscript13.5 KB
utils/llm_client.pyscript126.9 KB
utils/manual_tasks.pyscript14.9 KB
utils/metrics.pyscript68.1 KB
utils/next_phase.pyscript96.1 KB
utils/next_phase_words.pyscript6.4 KB
utils/output_handler.pyscript23.2 KB
utils/phase_walk.pyscript6.4 KB
utils/plan_updater.pyscript17.9 KB
utils/positionals.pyscript5.8 KB
utils/prior_changes.pyscript28.7 KB
utils/probe_state.pyscript17.9 KB
utils/process_capture.pyscript37.6 KB
utils/process_control.pyscript228.7 KB
utils/process_state.pyscript6.6 KB
utils/progress_tracker.pyscript92.2 KB
utils/prompt_channels.pyscript34.1 KB
utils/prompt_files.pyscript24.5 KB

multi_llm.py

View on GitHub
#!/usr/bin/env python3
"""multi_llm.py — the single entry point for every multi-llm mode.

    uv run --project <skill-dir> -- python <skill-dir>/multi_llm.py <mode> [args]

A host shim resolves *one* path, once, and routes nothing itself.

Grammar (one line, no shell preprocessing)::

    multi_llm.py <mode> [<positional>…] [--host <id>] [mode flags…]

* ``<mode>`` is a bare word and must be ``argv[1]``; unknown or missing is exit 3
  listing the valid modes. Users still type ``--review-plan``; the shim maps
  flag → mode word through the closed table in ``modes.py``, so this script never
  has to disambiguate a mode flag from an option.
* **Positionals are normalized into the flags the target already parses** — plan
  modes take ``<plan>`` → ``--plan-file``; ``ask`` takes ``<plan> <question>`` →
  ``--plan-file`` + ``--question`` (falling back to ``--question-file``, written
  *here* and never by the driving agent, when the question outgrows the argv
  budget); ``install-host`` takes ``<host>``; ``init`` takes none. An extra
  positional is exit 3, never silently dropped. The commit modes take an
  optional ``[<range>]`` instead, every leading bare word (``-N`` included)
  joined into one ``--revs`` value, or ``--plan-file`` for a commit brief's
  path; they refuse a typed ``--plan-file``, ``--base-ref`` or ``--head-ref``
  (``[COMMIT_FLAG_CONFLICT]``), which their front door synthesises.
* **Everything after the positionals is forwarded verbatim** to that mode's own
  argparse parser, which stays the single source of truth for its options.
  ``multi_llm.py <mode> --help`` prints that parser's help.
* **Dispatch is in-process**, never ``subprocess``: the target's
  ``main(argv) -> int`` is imported lazily and called, so one ``uv`` resolution
  covers the whole invocation, a plan path containing a space survives by
  construction (the hand-off is a Python list — ``shlex`` never runs on this
  path), stream setup happens once, and foreground Ctrl-C reaches the code that
  owns the phase dir with no forwarding layer.
* **Exit codes are uniform and never remapped**: 0 done, 1 unexpected error,
  2 nothing to do / phase already complete, 3 needs a human. Exit **3** is
  reserved across every mode for "unattended run cannot proceed" (missing
  tooling, unmet prerequisite, contradictory or empty decision flag), so a host
  can tell "needs a human" from "already done" (exit 2) without parsing prose.
  The only codes this script invents are the 3s it raises for an unknown mode, a
  bad positional, a rejected flag combination, an empty/unrecognized decision
  value (D6 row 15) and a missing ``uv`` (D6 row 1 / D6c layer 3) — plus the one
  code it *rewrites*: argparse's usage exit (2) out of a target's own parser
  becomes 3, because 2 already means "phase already complete" and a host must
  never read a typo'd flag as a finished phase.
* **Exactly one machine-readable last stdout line per invocation** —
  ``MULTI_LLM_RESULT: {"mode","phase","state","exit","artifacts":[…],"next":…}``
  — emitted even on a crash, so the contract holds for a host that cannot parse
  prose or is tailing a detached log. ``next`` is ``null`` whenever no follow-up
  is owed, which is the normal case. Optional keys join these only when set;
  one of them, ``user_next_step``, is the workflow's next phase as a command for
  the *user* to type — never a follow-up for the caller, which is ``next``.
"""

from __future__ import annotations

import hashlib
import importlib
import inspect
import os
import re
import shlex
import stat
import sys
import tempfile
import textwrap
import time
import traceback
from pathlib import Path
from typing import Callable, Dict, List, Optional, Sequence, Tuple

# Absolute, symlinks preserved — see utils/cli_common.py for why never realpath.
sys.path.insert(0, str(Path(os.path.abspath(__file__)).parent))

import modes as mode_table
from utils.cli_common import (
    CONTINUATION_VERBS,
    EXIT_ERROR,
    EXIT_NEEDS_HUMAN,
    EXIT_NOTHING_TO_DO,
    EXIT_OK,
    INTERNAL_FLAG_PREFIX,
    ResultContext,
    activate_result,
    clear_invocation,
    deactivate_result,
    dispatcher_command,
    flag_present,
    flag_value,
    invocation,
    invocation_plan_arg,
    record_error,
    record_invocation,
    render_instruction_text,
    skill_dir,
    record_ran_from_root,
)
from utils.stream_bootstrap import bootstrap_streams
from utils.unattended import (
    NeedsHuman,
    require_uv,
    validate_decision_flags,
)
# The positional grammar lives in utils/positionals.py, shared with the commit
# front door; this module reads it there. The private spellings below are
# read-only aliases for readers of the old names (tests/test_layer_moves.py).
from utils import positionals as _positionals
from utils.positionals import (  # noqa: F401 - re-exported for reading only
    COMMIT_BRIEF_SUFFIX as _COMMIT_BRIEF_SUFFIX,
    RANGE_COUNT_WORD as _RANGE_COUNT_WORD,
    inside as _inside,
    names_a_commit_brief as _names_a_commit_brief,
    relative_paths as _relative,
    revs_flags as _revs_flags,
    root_holding as _root_holding,
    split_positionals as _split_positionals,
    takes_revs as _takes_revs,
)

#: Above this many characters the ``ask`` question is handed over as a file
#: instead of an argv value. Well under the tightest real ceiling (Windows caps a
#: whole command line at 32767 chars; POSIX caps a single argument at 128 KiB),
#: because the same normalization feeds the detached-worker re-exec later.
MAX_ARGV_QUESTION_CHARS = 4096

#: The hidden re-entry flags this script reserves under the ``--internal-*``
#: prefix. Excluded from ``--help``, never rendered into a follow-up command or a
#: ``MULTI_LLM_RESULT.next`` value (see ``ResultContext.set_next``), and not part
#: of the compatibility surface. Targets own further ``--internal-*`` names of
#: their own (e.g. the retired ``--internal-revalidation``, which must still
#: reach its parser to warn), which is why the dispatcher forwards the prefix
#: rather than validating against this list.
INTERNAL_FLAGS: Tuple[str, ...] = tuple(
    INTERNAL_FLAG_PREFIX + name for name in ("reaggregate", "consolidate", "worker")
)


# ---------------------------------------------------------------------------
# The `util` namespace
# ---------------------------------------------------------------------------
# Utility scripts the instruction layer used to shell out to directly, routed the
# same in-process ``main(argv)`` way as the modes with flags forwarded verbatim to
# each script's existing parser. This is what makes "one substitution site per
# command" true rather than aspirational.
#
# `util` is NOT a user-facing surface: it is excluded from `argument-hint` and
# from `--help`'s mode list, documented only under `multi_llm.py util --help`,
# and — like `--internal-*` — never rendered into a MULTI_LLM_RESULT.next value.
UTIL_COMMANDS: Dict[str, Tuple[Optional[str], str, str]] = {
    "metrics": ("utils.metrics", "main", "Record/report per-subagent metrics in state.json."),
    "prior-changes": ("utils.prior_changes", "main", "Read, append to or clear the prior-batch change log."),
    "report": ("utils.html_report_generator", "main", "Regenerate an HTML review report with decisions overlaid."),
    "decisions": ("display_decisions", "main", "Print the decision summary from an orchestrator output file."),
    "update-tasks": ("update_plan_tasks", "main", "Write generated tasks into a plan's Tasks section."),
    "prereq": ("check_workflow_prerequisites", "main", "Check, skip or report a workflow phase's prerequisites."),
    "finalize-tracking": ("finalize_tracking", "main",
                          "Record the files implementation changed, and link the "
                          "summary from the plan."),
    "backup": ("utils.backup", "main", "Back up a file before it is modified."),
    "restore-batch": ("utils.restore_batch", "main",
                      "Restore a failed write batch from its pre-batch snapshot."),
    "runs": ("utils.run_sweep", "main", "List (or --sweep) this project's detached runs."),
    "report-check": ("utils.report_check", "main",
                     "Check a turn's final message copies the printed next "
                     "command (Claude Code Stop hook)."),
    "wakeup-check": ("utils.wakeup_check", "main",
                     "Refuse a scheduled wakeup or cron job while a phase "
                     "runs (Claude Code PreToolUse hook)."),
    "next-command": ("utils.next_phase", "main",
                     "Print a plan's next workflow command (read-only; "
                     "--after <mode>, --host <id>)."),
    "improve-steps": ("utils.improve_steps", "main",
                      "Plan an --improve-plan/--improve-code/--improve-commits "
                      "run: each step's decision and flags (read-only; the "
                      "native leg's planner)."),
    "improve-cascade": ("utils.improve_cascade_next", "main",
                        "Advance a native --cascade run: close out the stage "
                        "just run and print the next stage's steps (`next`; "
                        "the cascade's one writer on that leg)."),
    "commit-brief": ("utils.commit_front_door", "commit_brief_main",
                     "Resolve a commit range, print its commit block and write "
                     "or reuse its commit brief (a commit mode's preparation, "
                     "launching nothing)."),
    "check-tasks": ("utils.tasks_graph_check", "main",
                    "Report inconsistencies in a tasks.md's task graph (advisory)."),
    "check-reply": ("utils.check_reply", "main",
                    "Check the replies persisted for a task file's batches "
                    "parse and cover their groups."),
    "write-prompt": ("utils.write_prompt", "main",
                     "Write one write batch's prompt, prior-batch context "
                     "bound now and the result contract appended."),
    "batch-done": ("utils.batch_done", "main",
                   "Record one write batch's outcome in state.json (the "
                   "native leg's per-batch progress record)."),
    "resume-state": ("utils.resume_state", "main",
                     "Print a review phase's resume case and what to do "
                     "about it (read-only)."),
    "instructions": (None, "", "Print a mode's core instruction file with every path resolved."),
}

#: The ``util`` command that is a commit front door's steps 1 to 6 on their
#: own: the native leg's preparation entrypoint.
COMMIT_BRIEF_UTIL = "commit-brief"


#: Once served a frozen pre-refactor core; that core is gone (see
#: docs/development/hosts.md). Still read so a set variable is answered on stderr,
#: never with a stop: the current core is served either way.
LEGACY_INSTRUCTIONS_ENV = "MULTI_LLM_LEGACY_INSTRUCTIONS"


class DispatchError(Exception):
    """A dispatcher-owned failure that maps to a fixed exit code."""

    def __init__(self, message: str, exit_code: int = EXIT_NEEDS_HUMAN):
        super().__init__(message)
        self.exit_code = exit_code


# ---------------------------------------------------------------------------
# Help rendering (from modes.py — never a hand-maintained second list)
# ---------------------------------------------------------------------------

def render_help() -> str:
    lines = [
        "usage: multi_llm.py <mode> [<positional>...] [--host <id>] [mode flags...]",
        "",
        "Run a multi-llm workflow phase. The mode is a bare word and must come first;",
        "every flag after it is forwarded verbatim to that mode's own parser, so",
        "`multi_llm.py <mode> --help` prints the authoritative flag list.",
        "",
        "modes:",
    ]
    width = max(len(m.name) for m in mode_table.MODES)
    for mode in mode_table.MODES:
        positionals = " ".join(mode.positionals)
        head = f"  {mode.name.ljust(width)}  {positionals}".rstrip()
        lines.append(f"{head.ljust(width + 22)}{mode.summary}")
        if mode.unavailable:
            lines.append(f"  {''.ljust(width)}  ({mode.unavailable.format(mode=mode.name)})")
    lines += [
        "",
        "aliases:",
    ]
    for alias in sorted(mode_table.ALIASES):
        lines.append(f"  {alias} -> {mode_table.alias_expansion(alias)}")
    revs_modes = [m.name for m in mode_table.MODES if _positionals.takes_revs(m)]
    if revs_modes:
        lines.append("")
        lines += textwrap.wrap(
            f"The commit modes ({', '.join(revs_modes)}) take an optional "
            f"{mode_table.POS_REVS}, HEAD (the last commit) when omitted: git "
            "revision syntax (A..B, A...B, a commit), one phrase (last 2 "
            "commits, -2, this branch, since <rev>, last two days), a commit "
            "brief's path, or the pinned <base12>..<head12> a run printed. "
            "Its words are joined, so it needs no quotes; it goes right after "
            "the mode word, before any flag, and a run takes one range.",
            width=78,
        )
    lines += [
        "",
        "cross-cutting flags (accepted by every mode, and by each orchestrator",
        "directly): --host ID, --yes/-y/--non-interactive, --interactive/-i,",
        "--detach, --if-not-running, --max-detached N, --exec-subagents,",
        "--skip-prerequisites.",
        "",
        "Unattended is the default everywhere except Claude Code: --yes resolves",
        "every gate from config and flags and renders no question, --interactive",
        "is the opt-in to a rendered gate, and the two together are exit 3 (never",
        "a precedence rule). --yes never implies --skip-prerequisites.",
        "",
        "--detach self-daemonizes the long-running modes "
        f"({', '.join(mode_table.DETACH_MODES)}):",
        "it implies --yes, returns immediately with a log path plus a status",
        "command, and is stopped only by `status <plan> --abort`. Never wrap it in",
        "a host background primitive — pick one mechanism.",
        "",
        "exit codes: 0 done | 1 unexpected error | 2 nothing to do / phase already",
        "complete | 3 needs a human (an unattended run that cannot proceed:",
        "missing uv, unmet prerequisite, contradictory or empty decision flag, or",
        "a command line a parser refused).",
        "",
        "Every invocation ends with one machine-readable line:",
        '  MULTI_LLM_RESULT: {"mode","phase","state","exit","artifacts":[...],"next":...}',
        "Optional keys join these only when set. One is `user_next_step`: the",
        "workflow's next phase as a command for the user to type, never a",
        "follow-up for the caller (that is `next`).",
        "",
        "Utility scripts live under a separate namespace: `multi_llm.py util --help`.",
    ]
    return "\n".join(lines)


def render_util_help() -> str:
    lines = [
        "usage: multi_llm.py util <command> [flags...]",
        "",
        "Utility scripts, routed in-process with flags forwarded verbatim to each",
        "script's own parser. Not a user-facing surface: `util` never appears in the",
        "skill's argument-hint, in `multi_llm.py --help`'s mode list, or in a",
        "MULTI_LLM_RESULT.next value.",
        "",
        "commands:",
    ]
    width = max(len(name) for name in UTIL_COMMANDS)
    for name, (_module, _attr, summary) in UTIL_COMMANDS.items():
        lines.append(f"  {name.ljust(width)}  {summary}")
    lines += [
        "",
        "`util instructions <mode>` prints instructions/<mode>.md with every",
        "skill-dir placeholder replaced by the running skill dir, so the text a host",
        "agent reads contains no unexpanded token. With --to-file it writes that",
        "text to a file under <repository root>/.multi-llm/tmp/cores/ instead and",
        "prints one [CORE_FILE] <path> lines=<n> bytes=<n> line. With --page <i>",
        "[--page-size <bytes>] it prints page <i> of that text, between a",
        "[CORE_PAGE] header and a [CORE_PAGE_END] line, for a host whose shell",
        "output loses the middle of long text.",
        "",
        "`util resume-state <mode> <plan>` reads a review phase's folder (review-plan,",
        "review-tasks, review-code) and prints one [RESUME_STATE] line: the resume",
        "case, the action to take, the models, batches and flags it needs, and",
        "ownership=stale (or uncertain) when validation files on disk are (or may",
        "be) an earlier round's. Read-only; references/resume-detection.md lists",
        "the cases.",
        "",
        "`util next-command <plan> [--after <mode>] [--host <id>]` prints the",
        "workflow's next phase as the next-command block (or the workflow-complete",
        "line) and sets MULTI_LLM_RESULT.user_next_step: a command for the user to",
        "type, never a follow-up for the caller. It reads state.json as recorded.",
        "",
        "`util improve-steps <plan> --mode improve-plan|improve-code|improve-commits [flags...]`",
        "prints the steps a native --improve-plan, --improve-code or --improve-commits",
        "run takes, each step's run/skip decision and its exact flags, and the command",
        "that continues the run; exit 2 with [ALREADY_COMPLETE] when nothing is left",
        "to do. --json prints the same facts as one object. Read-only, like",
        "next-command. An --improve-commits run names the commit brief as its plan.",
        "A --cascade run prints no steps: [IMPROVE_CASCADE_NEXT] names the",
        "`util improve-cascade next` call to make instead.",
        "",
        "`util improve-cascade next <plan> --mode improve-plan|improve-code [flags...]",
        "[--cascade-id <id> --after-stage <k>]` is a --cascade run's planner and",
        "recorder on the native leg: it closes out the stage just run, then prints the",
        "next stage's steps as improve-steps prints them, [IMPROVE_CASCADE_CONTINUE]",
        "<the call to make once they are done> and [IMPROVE_RERUN]; exit 2 with the",
        "stage count and table ([CASCADE_COMPLETE]) once every stage is closed, exit 3",
        "when the stage a continue call follows is still open. It writes the cascade's",
        "record, archive and ledger.",
        "",
        "`util commit-brief [<range>] [--focus \"<text>\"] [--context-plan <path>]",
        "[flags...]` takes the tokens a commit mode was typed with, range words",
        "included: it resolves the range, prints the commit block, writes or reuses",
        "the commit brief and records the range, then prints [COMMIT_BRIEF] <path>",
        "and [COMMIT_REMAINING_FLAGS] <the tokens it did not consume>. It launches",
        "nothing: the native leg's preparation before `util improve-steps <brief>`.",
    ]
    return "\n".join(lines)


def _unknown_mode_message(word: str) -> str:
    return (
        f"ERROR: unknown mode '{word}'.\n"
        f"Valid modes: {', '.join(mode_table.mode_names())}\n"
        f"Aliases: "
        + ", ".join(f"{a}={t}" for a, t in sorted(mode_table.ALIASES.items()))
        + "\nRun `multi_llm.py --help` for the full grammar."
    )


# ---------------------------------------------------------------------------
# Grammar
# ---------------------------------------------------------------------------

def _normalize_positionals(
    mode: "mode_table.Mode",
    positionals: Sequence[str],
    cleanup: List[Path],
) -> List[str]:
    """Turn a mode's positionals into the flags its target already parses."""
    if _positionals.takes_revs(mode):
        # Ahead of the length check: `last 2 commits` is three words for the
        # range's one slot, and the extra-positional error never fires on a
        # commit mode (the range grammar is what refuses a bad range).
        return _positionals.revs_flags(positionals)
    if len(positionals) > len(mode.positionals):
        expected = " ".join(mode.positionals) or "(none)"
        raise DispatchError(
            f"ERROR: mode '{mode.name}' takes {len(mode.positionals)} positional "
            f"argument(s) {expected}, got {len(positionals)}: "
            f"{' '.join(positionals)}\n"
            "Flags must follow the positionals; an extra positional is never "
            "silently dropped."
        )

    normalized: List[str] = []
    for kind, value in zip(mode.positionals, positionals):
        if kind == mode_table.POS_PLAN:
            normalized += ["--plan-file", value]
        elif kind == mode_table.POS_QUESTION:
            normalized += _question_flags(value, cleanup)
        elif kind == mode_table.POS_HOST:
            # Forwarded verbatim as a positional: the install-host parser (and
            # with it the host-id vocabulary) is owned by the install design.
            normalized += [value]
        else:  # pragma: no cover - guarded by the table
            raise DispatchError(f"ERROR: unhandled positional kind {kind!r}")
    return normalized


#: The flags a commit front door synthesises for the phase it fronts, which a
#: user may never type there, each with the commit spelling that replaces it.
COMMIT_OWNED_FLAGS: Tuple[Tuple[str, str], ...] = (
    ("--plan-file",
     "there is no plan by default: the commit messages are the stated intent. "
     "Add a plan as read-only context with `--context-plan <path>`, or name a "
     "commit brief by its path as the range (`{door} <brief>`)."),
    ("--base-ref",
     "the range names its base: type it right after the mode word, before any "
     "flag, as `{door} C..HEAD` (the commits after C up to HEAD) or "
     "`{door} A..B`."),
    ("--head-ref",
     "the range names its end: type it right after the mode word, before any "
     "flag, as `{door} A..B` (the commits after A up to B)."),
)

#: The hidden flag a detached worker carries; its argv is the plugin's own.
_WORKER_FLAG = INTERNAL_FLAG_PREFIX + "worker"


def _reject_commit_owned_flags(door: str, tokens: Sequence[str]) -> None:
    """``[COMMIT_FLAG_CONFLICT] <flag>`` for a typed ``--plan-file``,
    ``--base-ref`` or ``--head-ref`` on a commit front door, exit 3.

    A front door synthesises all three for the phase it fronts, so a typed
    one would be overridden silently or win by argparse's last-one rule.
    Checked on the tokens as typed, before :func:`_normalize_positionals`
    turns a brief path into the door's own ``--plan-file``, so a root range's
    printed command (a commit mode and its brief path) passes, and before the
    front door's step 1, so nothing is written. An argparse abbreviation
    (``--plan``) is refused like the full spelling, as the parser would bind
    it. *door* is how the user names the command (``--review-commits``,
    ``util commit-brief``). A detached worker's argv is skipped by the
    caller: the plugin built it, and a root range's brief is already
    ``--plan-file`` there.
    """
    for token in tokens:
        if token == "--":
            return
        head = token.split("=", 1)[0]
        for flag, instead in COMMIT_OWNED_FLAGS:
            if not flag_present([head], flag):
                continue
            typed = "" if head == flag else f" (typed as {head})"
            marker = f"[COMMIT_FLAG_CONFLICT] {flag}{typed}"
            print(marker)
            reason = f"{door} takes no {flag}: {instead.format(door=door)}"
            record_error(f"{marker}: {reason}")
            raise DispatchError(f"ERROR: {reason}")


def _question_flags(question: str, cleanup: List[Path]) -> List[str]:
    """``--question`` for a short question, else a dispatcher-written file.

    ``ask_orchestrator.py`` already accepts ``--question-file``; writing it here
    keeps user-controlled free text off every command line, and keeps the
    decision out of the driving agent's hands.
    """
    if len(question) <= MAX_ARGV_QUESTION_CHARS:
        return ["--question", question]
    handle, path = tempfile.mkstemp(prefix="multi_llm_question_", suffix=".txt")
    with os.fdopen(handle, "w", encoding="utf-8") as stream:
        stream.write(question)
    cleanup.append(Path(path))
    return ["--question-file", path]


def _host_capabilities():
    """Import the capability reader lazily (one yaml parse, only when needed)."""
    # Imported here to keep multi_llm light.
    from utils import host_capabilities

    return host_capabilities


def resolve_host(argv: Sequence[str]) -> str:
    """The host id this invocation runs under: ``--host`` → env → ``claude-code``.

    An omitted flag resolves to the reference host, so a command that predates the
    capability data behaves exactly as it did. Never sniffed: a host is *declared*
    (by the shim that baked the flag in, or by the user), never guessed from the
    environment.
    """
    return _host_capabilities().resolve_host_id(argv)


def _validate_host(argv: Sequence[str]) -> None:
    """An unknown ``--host`` is exit 3 before anything is created (D5b)."""
    caps = _host_capabilities()
    caps.entry(caps.resolve_host_id(argv))


def _reject_incompatible_flags(mode: "mode_table.Mode", argv: Sequence[str]) -> None:
    """Reject contradictory combinations at parse time, never by precedence.

    Enforced here — before any phase dir is touched — because the alternative is
    each mode guessing which flag wins.
    """
    unattended = flag_present(argv, "--yes", "-y", "--non-interactive")
    if unattended and flag_present(argv, "--interactive", "-i"):
        raise DispatchError(
            "ERROR: --yes (or --non-interactive) and --interactive are "
            "contradictory: one forbids prompting, the other forces it. "
            "Pass exactly one."
        )
    if unattended and flag_value(argv, "--force-strategy") == "pause-and-ask":
        raise DispatchError(
            "ERROR: --force-strategy pause-and-ask requires a human at the "
            "per-task gate, which --yes forbids. Pass a non-interactive "
            "strategy (e.g. skip-dependents) or drop --yes."
        )
    _reject_capability_conflicts(mode, argv)


def _reject_capability_conflicts(mode: "mode_table.Mode", argv: Sequence[str]) -> None:
    """The foreground-only gates ``--detach`` is incompatible with.

    A detached worker has ``stdin`` at ``DEVNULL`` and no channel back to the
    host, so anything that would raise a question is a contradiction — and it is
    rejected **at parse time, in the foreground invoker, before the process
    daemonizes**, so the user sees it on their own terminal instead of finding it
    in a log by polling. ``--detach`` therefore implies ``--yes`` (every decision
    point auto-resolves from the documented defaults and the resolution is
    recorded in ``.status.json``), and any flag whose resolution needs a human is
    exit 3.

    ``--exec-subagents`` is rejected the same way, from the capability data rather
    than from a guess here — but in ``_require_executor_capability`` below, which
    runs *after* the implications so ``--detach``'s implied flag is gated exactly
    like a typed one.
    """
    if not flag_present(argv, "--detach"):
        return None
    if flag_present(argv, "--interactive", "-i"):
        raise DispatchError(
            "ERROR: --detach and --interactive are contradictory: a detached run "
            "has no terminal to prompt on (stdin is /dev/null and there is no "
            "channel back to the host), so --detach implies --yes. Pass exactly "
            "one."
        )
    if flag_value(argv, "--force-strategy") == "pause-and-ask":
        raise DispatchError(
            "ERROR: --force-strategy pause-and-ask requires a human at the "
            "per-task gate, which --detach forbids (it implies --yes). Pass a "
            "non-interactive strategy (e.g. skip-dependents) or drop --detach."
        )
    if not mode.supports_detach:
        # A flag that silently does nothing is worse than a refusal: the caller
        # would poll `status` forever for a run that was never detached.
        raise DispatchError(
            f"ERROR: --detach is not available for mode '{mode.name}'.\n"
            "       It covers the long-running fan-out modes today: "
            f"{', '.join(mode_table.DETACH_MODES)}.\n"
            "       Run this mode in the foreground (it emits task JSON and "
            "exits in seconds) or under your host's own background mechanism."
        )
    return None


def _apply_flag_implications(argv: List[str]) -> List[str]:
    """Write ``--detach``'s implications out explicitly rather than leaving them.

    The detached child's argv is rebuilt from the invoker's, so an implication
    that stayed implicit would have to be re-derived in a second place. Making it
    explicit here means the worker's recorded argv says exactly what it ran with.

    Two implications, both D4c's, and both about there being nobody on the other
    end: ``--yes`` because no one is there to *answer*, and ``--exec-subagents``
    because no one is there to *continue* — a detached worker without it would
    print ``[VALIDATION_PENDING]``/``[SALVAGE_NEEDED]`` and exit 0 with the phase
    unfinished, which a poller reads as ``run.state: done``, and the write phases
    would decline the scheduler outright.
    """
    if flag_present(argv, "--detach"):
        if not flag_present(argv, "--yes", "-y", "--non-interactive"):
            argv = list(argv) + ["--yes"]
        if not flag_present(argv, "--exec-subagents"):
            argv = list(argv) + ["--exec-subagents"]
    return argv


def _require_executor_capability(argv: Sequence[str]) -> None:
    """Gate ``--exec-subagents`` on the host's capability data (D3e/D5b).

    Called *after* ``_apply_flag_implications``, so the flag ``--detach`` implies
    is checked exactly like one the caller typed: a host whose entry declares no
    executor-capable runner (the ``agent-readonly``/``agent-write`` profiles)
    would otherwise accept the run, stop at a dispatch marker and wait for a
    subagent nobody starts.
    """
    if flag_present(argv, "--exec-subagents"):
        _host_capabilities().require_executor_runner(resolve_host(argv))


# ---------------------------------------------------------------------------
# Dispatch
# ---------------------------------------------------------------------------

def _load_target(module_path: str, attr: str) -> Callable[[Sequence[str]], int]:
    """Import a dispatch target lazily and return its ``main``.

    Import must be side-effect free: every target keeps argparse and all work
    inside ``main(argv)`` so two targets can safely run inside one interpreter
    (see tests/test_instruction_portability.py).
    """

    module = importlib.import_module(module_path)
    target = getattr(module, attr, None)
    if target is None:  # pragma: no cover - guarded by the table + tests
        raise DispatchError(
            f"ERROR: {module_path} has no '{attr}' entry point.",
            exit_code=EXIT_ERROR,
        )
    return target


def _call_target(target: Callable[[Sequence[str]], int], argv: Sequence[str]) -> int:
    """Call ``main(argv)``, awaiting it when the target is async.

    An async target runs under ``sweeping_live_clis_on_interrupt``, so a Ctrl-C
    stops its fan-out's CLIs from inside the cancellation, before ``asyncio.run``
    joins the worker threads waiting on them (decision 11.9).
    """
    # Imported here: multi_llm does not otherwise load asyncio.
    import asyncio

    if inspect.iscoroutinefunction(target):
        # Imported here to keep multi_llm light.
        from utils import process_control

        result = asyncio.run(
            process_control.sweeping_live_clis_on_interrupt(target(list(argv)))
        )
    else:
        result = target(list(argv))
    return EXIT_OK if result is None else int(result)


def _validate_skip_rung(mode_name: str) -> None:
    """Reject a bad ``MULTI_LLM_CODEX_SKIP_RUNG`` before any mode runs: any value but
``plugin-landlock`` is exit 3 naming the
    variable and the accepted value, never silently ignored. ``doctor`` is
    exempt — it is where a user looks when something is wrong, so it reports
    the bad value on its ``plugin-landlock`` row instead of dying on it."""
    if mode_name == "doctor":
        return
    # Imported here to keep multi_llm light.
    from utils.providers.base import skip_rung_requested

    try:
        skip_rung_requested()
    except ValueError as exc:
        raise DispatchError(f"ERROR: {exc}") from exc


def _run_mode(word: str, rest: Sequence[str], ctx: ResultContext) -> int:
    mode = mode_table.resolve(word)
    if mode is None:
        raise DispatchError(_unknown_mode_message(word))

    ctx.mode = mode.name
    ctx.phase = mode.phase

    if mode.unavailable:
        if flag_present(rest, "--help", "-h"):
            print(f"{mode.name}: {mode.summary}")
            print(f"  {mode.unavailable.format(mode=mode.name)}")
            return EXIT_OK
        raise DispatchError(
            f"ERROR: mode '{mode.name}' is {mode.unavailable.format(mode=mode.name)}."
        )

    assert mode.target_module is not None  # every available mode has a target
    cleanup: List[Path] = []
    try:
        positionals, flags = _positionals.split_positionals(rest, mode)
        if flag_present(flags, "--help", "-h"):
            # Forward to the target's own parser: it is the source of truth.
            return _call_target(
                _load_target(mode.target_module, mode.target_attr), list(flags)
            )
        # The host id first: every rejection below may consult its capability
        # entry, and an unknown id must fail as itself rather than as a confusing
        # consequence.
        _validate_host(flags)
        if _positionals.takes_revs(mode) and not flag_present(flags, _WORKER_FLAG):
            # On the tokens as typed, before the brief path becomes the
            # door's own `--plan-file` below.
            _reject_commit_owned_flags(f"--{mode.name}", flags)
        _reject_incompatible_flags(mode, flags)
        # D6 row 15 then row 1, both before anything is created: an empty or
        # unrecognized decision value and a missing `uv` are the two failures a
        # mode must never discover halfway through a phase dir.
        validate_decision_flags(flags)
        _validate_skip_rung(mode.name)
        if mode.requires_uv:
            # The two install modes opt out (modes.py): `install-host --check` is
            # layer 1 of the same uv bootstrap and reports a miss as one of its
            # five assertions, and `uninstall-host` must work on a machine whose
            # uv is already gone. Every other mode fails here, before anything is
            # created.
            require_uv()
        argv = (
            list(mode.injected_flags)
            + list(mode_table.alias_flags(word))
            + _normalize_positionals(mode, positionals, cleanup)
            + list(flags)
        )
        argv = _apply_flag_implications(argv)
        # After the implications: --detach's implied --exec-subagents faces the
        # same capability gate as an explicit one, so a host with no executor-
        # capable runner is exit 3 here rather than a marker nobody continues.
        _require_executor_capability(argv)
        # A plan spelled from the repository root, typed in a subdirectory of
        # it: the whole command runs from the root, before
        # anything reads a path or records the invocation.
        _run_from_repository_root(
            [flag_value(argv, option) for option in _MODE_INPUT_PATH_OPTIONS],
            [flag_value(argv, option) for option in _MODE_OUTPUT_PATH_OPTIONS],
        )
        # What a detached child re-executes: the mode word plus this normalized
        # argv, never a remembered sys.argv (see utils/detach.build_child_command).
        # A continuation also carries the plan spelling its hand-off recorded.
        record_invocation(
            mode.name, argv, plan_arg=_continued_plan_arg(mode, argv)
        )
        return _call_target(
            _load_target(mode.target_module, mode.target_attr), argv
        )
    finally:
        for path in cleanup:
            try:
                path.unlink()
            except OSError:  # pragma: no cover - best-effort cleanup
                pass


def _run_util(rest: Sequence[str], ctx: ResultContext) -> int:
    ctx.mode = mode_table.UTIL_NAMESPACE
    if not rest or rest[0] in ("--help", "-h"):
        print(render_util_help())
        return EXIT_OK
    name, args = rest[0], list(rest[1:])
    if name not in UTIL_COMMANDS:
        raise DispatchError(
            f"ERROR: unknown util command '{name}'.\n"
            f"Valid commands: {', '.join(UTIL_COMMANDS)}\n"
            "Run `multi_llm.py util --help` for details."
        )
    ctx.mode = f"{mode_table.UTIL_NAMESPACE} {name}"
    if name == "instructions":
        return _run_util_instructions(args, ctx)
    module_path, attr, _summary = UTIL_COMMANDS[name]
    assert module_path is not None
    if name == COMMIT_BRIEF_UTIL and not flag_present(args, "--help", "-h"):
        # The front doors' preparation half takes the same typed tokens, so
        # it refuses the same three flags.
        _reject_commit_owned_flags(
            f"{mode_table.UTIL_NAMESPACE} {COMMIT_BRIEF_UTIL}", args)
    if not flag_present(args, "--help", "-h"):
        _run_from_repository_root(
            _util_input_paths(name, args),
            [flag_value(args, option) for option in _UTIL_OUTPUT_PATH_OPTIONS],
        )
    return _call_target(_load_target(module_path, attr), args)


# ---------------------------------------------------------------------------
# A command run from a subdirectory of the repository
# ---------------------------------------------------------------------------
# Every path a workflow command names (the plan, its folder, state.json, a phase
# folder, tasks.md) is spelled from the repository root. When the relative ones
# name nothing from the cwd and each names something inside the root of the
# repository the cwd is in (a host that `cd`s into a phase folder and re-runs a
# command there), the command runs from that root, exactly as it would have there,
# and says so on one line.

#: A mode's options whose value is an existing file the command reads (a plan
#: positional is ``--plan-file`` by now, and so is a commit brief's path; a
#: commit mode's ``--context-plan`` is a plan read as context, the hidden
#: ``--commit-stage`` the staged header a detached worker applies, and
#: review-plan's and review-code's hidden ``--cascade-stage-file`` a cascade
#: stage's inputs manifest, which a cascade always names absolute; one typed
#: relative is read from the cwd the move settles on, like the plan).
_MODE_INPUT_PATH_OPTIONS: Tuple[str, ...] = (
    "--plan-file", "--question-file", "--tasks-file", "--files-from",
    "--context-plan", "--commit-stage", "--cascade-stage-file",
)

#: A mode's options whose value is a path the command creates, so it need not
#: exist yet: review-plan's output folder
#: and implement's task JSON. ``--files`` and ``--touched`` are
#: repository-relative wherever they are typed, and init's ``--dir`` is its
#: target as typed; none of them is read here.
_MODE_OUTPUT_PATH_OPTIONS: Tuple[str, ...] = ("--out-dir", "--output")

#: A ``util`` command's options whose value names something the workflow keeps
#: in the repository (``--output-file`` is the orchestrator output
#: ``util decisions`` reads, and ``--output-dir`` the plan folder
#: ``prior-changes`` reads and appends to; ``--files-from`` is the scope list
#: ``improve-steps`` and ``improve-cascade next`` read, as the mode route reads
#: review-code's;
#: ``--context-plan`` is the plan ``commit-brief`` reads as context).
_UTIL_INPUT_PATH_OPTIONS: Tuple[str, ...] = (
    "--plan-file", "--state-file", "--phase-dir", "--output-dir", "--tasks-file",
    "--output-file", "--project-root", "--files-from", "--context-plan",
)

#: A ``util`` command's options whose value is a path it creates:
#: ``write-prompt``'s prompt file.
_UTIL_OUTPUT_PATH_OPTIONS: Tuple[str, ...] = ("--output",)

#: The ``util`` commands whose first positional is such a path, with their
#: options that take a value (whose value is not that positional).
_UTIL_PATH_POSITIONAL: Dict[str, Tuple[str, ...]] = {
    "next-command": ("--after", "--blocked", "--host"),
    "improve-steps": ("--mode", "--host", "--models", "--files", "--files-from",
                      "--base-ref", "--head-ref", "--max-detached",
                      "--internal-run-id", "--scope-policy"),
    "improve-cascade": ("--mode", "--host", "--models", "--files", "--files-from",
                        "--base-ref", "--max-detached", "--internal-run-id",
                        "--scope-policy", "--cascade-id", "--after-stage"),
    "check-tasks": (),
    "backup": (),
    "resume-state": (),
}

#: The ``util`` commands whose path positional comes after this many other
#: positionals: ``resume-state <mode> <plan>`` and ``improve-cascade next
#: <plan>`` name the plan second.
_UTIL_PATH_POSITIONAL_INDEX: Dict[str, int] = {"resume-state": 1, "improve-cascade": 1}

#: Of those options, the ones that take one or more values (``nargs="+"``):
#: argparse hands such an option every token up to the next option, so none
#: of them is the positional (``util improve-steps --models m1 m2 --mode
#: improve-plan <plan>`` names the plan last, not ``m2``).
_UTIL_VARIADIC_OPTIONS: Dict[str, Tuple[str, ...]] = {
    "improve-steps": ("--models",),
    "improve-cascade": ("--models",),
}

#: The cwd :func:`_run_from_repository_root` moved away from, which ``main``
#: moves back to on its way out (an in-process caller keeps its own cwd).
_CWD_BEFORE_ROOT: List[str] = []


def _is_option_token(token: str) -> bool:
    return token.startswith("-") and token != "-"


def _first_positional(
    args: Sequence[str], value_options: Sequence[str],
    variadic_options: Sequence[str] = (), skip: int = 0,
) -> Optional[str]:
    """The first positional of *args* after *skip* others, or ``None``."""
    index = 0
    while index < len(args):
        token = args[index]
        if token == "--":
            rest = args[index + 1:]
            return rest[skip] if skip < len(rest) else None
        if _is_option_token(token):
            index += 1
            if "=" in token:
                continue
            if token in variadic_options:
                while index < len(args) and not _is_option_token(args[index]):
                    index += 1
            elif token in value_options:
                index += 1
            continue
        if skip:
            skip -= 1
            index += 1
            continue
        return token
    return None


def _util_input_paths(name: str, args: Sequence[str]) -> List[Optional[str]]:
    paths = [flag_value(args, option) for option in _UTIL_INPUT_PATH_OPTIONS]
    if name in _UTIL_PATH_POSITIONAL:
        paths.append(_first_positional(
            args, _UTIL_PATH_POSITIONAL[name], _UTIL_VARIADIC_OPTIONS.get(name, ()),
            skip=_UTIL_PATH_POSITIONAL_INDEX.get(name, 0),
        ))
    return paths


def _names_something_here(output: str) -> bool:
    """Whether an output path, or the first folder it names, exists from the
    cwd: then it is spelled from here (``out/new`` beside an ``out``, ``..``)."""
    first = os.path.normpath(output).split(os.sep, 1)[0]
    return os.path.lexists(output) or os.path.lexists(first)


def _run_from_repository_root(
    paths: Sequence[Optional[str]], outputs: Sequence[Optional[str]] = (),
) -> None:
    """Move to the repository root when the command's relative paths name
    nothing from here and each names something inside that root.

    The root is the one the write path pins (``git_utils.pin_repo_root``: the
    nearest ``.git`` entry above the cwd, which git must confirm; nothing is
    pinned while ``GIT_DIR`` and the like redirect git). Nothing moves when no
    path is relative, when any of them names something from the cwd (so a
    spelling that works here keeps working, and a mixed one is not guessed at),
    when the cwd is the root already, or when a path is missing from the root
    too or resolves outside it (a ``..`` or a link out of the repository).

    *outputs* are paths the command creates: one need not
    exist at the root, but it keeps the command here when it, or the first
    folder it names, exists from the cwd, and it must stay inside the root as
    spelled and resolved. Outputs alone never move a command: only a path it
    reads says it was spelled from the root.
    """
    relative = _positionals.relative_paths(paths)
    made = _positionals.relative_paths(outputs)
    if (
        not relative
        or any(os.path.lexists(path) for path in relative)
        or any(_names_something_here(path) for path in made)
    ):
        return
    try:
        cwd = os.getcwd()
        # Imported here to keep multi_llm light.
        from utils.git_utils import pin_repo_root

        root, problem = pin_repo_root(cwd)
    except Exception:  # noqa: BLE001 - a convenience: the command runs as typed
        return
    if root is None or problem or os.path.realpath(cwd) == root:
        return
    for path in relative + made:
        candidate = os.path.join(root, path)
        if not (
            (path in made or os.path.exists(candidate))
            and _positionals.inside(os.path.normpath(candidate), root)
            and _positionals.inside(os.path.realpath(candidate), root)
        ):
            return
    os.chdir(root)
    _CWD_BEFORE_ROOT.append(cwd)
    # On the result line too, so a tool server names the plan
    # the way this command reads it, never by a `.git` walk of its own.
    record_ran_from_root(root)
    print(
        f"multi-llm: running from the repository root {root}, where "
        f"{relative[0]} is (it is not under the current directory {cwd}).",
        file=sys.stderr,
    )


def _back_to_the_callers_cwd() -> None:
    if not _CWD_BEFORE_ROOT:
        return
    cwd = _CWD_BEFORE_ROOT[0]
    del _CWD_BEFORE_ROOT[:]
    try:
        os.chdir(cwd)
    except OSError:  # pragma: no cover - the folder went away meanwhile
        pass


def _run_util_instructions(args: Sequence[str], ctx: ResultContext) -> int:
    """Serve a mode's core instruction file with every placeholder resolved.

    The instruction markdown is static and no installer rewrites it, so a host
    that reads the file directly would have to apply the skill-dir binding by
    hand — an instruction-following step across a 5k-line corpus. Serving the
    rendered text from ``__file__`` removes that step and cannot go stale.
    """
    if not args or args[0] in ("--help", "-h"):
        served = [m.name for m in mode_table.MODES if m.instruction_file]
        print(
            "usage: multi_llm.py util instructions <mode> [--host <id>] "
            "[--to-file | --page <i> [--page-size <bytes>]]"
        )
        print(f"modes with a core instruction file: {', '.join(served)}")
        print(
            "  --host <id>         append this host's three resolved capability-verb "
            "sentences"
        )
        print(
            "  --to-file           write the core to a file under "
            f"<repository root>/{'/'.join(CORE_FILE_DIR)}/ and print "
            f"`{CORE_FILE_MARKER} <path> lines=<n> bytes=<n>` instead of the core"
        )
        print(
            "  --page <i>          print page <i> of the core, framed by a "
            f"`{CORE_PAGE_MARKER}` header and a `{CORE_PAGE_END_MARKER}` line"
        )
        print(
            "  --page-size <bytes> the most core bytes one page holds (default "
            f"{CORE_PAGE_SIZE_DEFAULT}, at least {CORE_PAGE_SIZE_MIN}); a longer "
            "line gets a page of its own"
        )
        return EXIT_OK
    positional, host_id, to_file, page, page_size = _split_instructions_host(args)
    if len(positional) > 1:
        raise DispatchError(
            "ERROR: `util instructions` takes exactly one mode word, got: "
            + " ".join(positional)
        )
    if not positional:
        raise DispatchError(
            "ERROR: `util instructions` needs a mode word before --host."
        )
    word = positional[0]
    mode = mode_table.resolve(word)
    if mode is None:
        raise DispatchError(_unknown_mode_message(word))
    relative = mode_table.instruction_path(mode.name)
    if relative is None:
        # Dispatcher-driven by design (`status`, `install-host`,
        # `uninstall-host`): there is no workflow to narrate, only flags. Every
        # shim names this command as its unconditional read step, so erroring
        # here would hand a host agent a failure before it had done anything —
        # observed on OpenCode, where the agent had to improvise past an exit 3.
        # Answer with the one useful thing instead and exit 0; a mode that
        # *declares* a core file which is missing is still a hard error below.
        answer = _dispatcher_only_answer(mode.name)
        if to_file:
            return _serve_core_file(mode.name, answer, answer, ctx)
        if page is not None:
            return _serve_core_page(mode.name, answer, page, page_size)
        sys.stdout.write(answer)
        return EXIT_OK
    path = skill_dir() / relative
    if os.environ.get(LEGACY_INSTRUCTIONS_ENV) == "1":
        # stderr, never stdout: stdout is the core, which a host may pipe into a prompt.
        print(
            f"[LEGACY_INSTRUCTIONS] {LEGACY_INSTRUCTIONS_ENV}=1 is ignored: the legacy "
            "instruction core was removed, so the current instructions are served.",
            file=sys.stderr,
        )
    if not path.exists():
        raise DispatchError(
            f"ERROR: core instruction file missing: {path}\n"
            "The plugin install looks corrupt or partial; reinstall the skill.",
            exit_code=EXIT_ERROR,
        )
    core = render_instruction_text(path.read_text(encoding="utf-8"), skill_dir())
    body = core if core.endswith("\n") else core + "\n"
    # The sentinel closes the *core*, before the optional verb appendix, because
    # `--host` has always appended to an unchanged core and a marker that moved
    # depending on the flag would be a second thing to reason about. Every shim
    # host runs the plain form, where this is the last line of content.
    body += f"{CORE_END_MARKER} {mode.name}\n"
    if host_id is not None:
        body += _verb_section(host_id)
    ctx.add_artifact(path)
    if page is not None:
        # The paged form replaces the head banner, never the body: its own
        # banner on page 1 states the paged completeness rule, because the
        # printed banner's test (one end line in what arrived) is the wrong
        # test for a page.
        return _serve_core_page(mode.name, body, page, page_size)
    served = _truncation_notice(mode.name, core) + body
    if to_file:
        return _serve_core_file(mode.name, body, served, ctx)
    sys.stdout.write(served)
    return EXIT_OK


def _dispatcher_only_answer(mode_name: str) -> str:
    """What ``util instructions`` serves for a mode with no core file."""
    lines = [
        f"Mode '{mode_name}' has no core instruction file: it is driven "
        "entirely by the dispatcher, so there are no workflow steps to "
        "follow. Its flags are the whole interface:",
        "",
        f"  {dispatcher_command(mode_name)} --help",
    ]
    if mode_name == "status":
        # 2026-10-04: a host reading `status`
        # only to report it showed "Exit code 2" as a tool error. The code
        # is the poll contract and never moves; the read step says so.
        lines += [
            "",
            "Read its output, not its exit code: exit code 2 is not a "
            "failure — it means no run is recorded (every phase a host ran "
            "in the foreground) or one is still running, the poll "
            "contract; 0 and 3 are a finished run's verdict, and only 1 is "
            "an error (the phase dir could not be read). To report it to "
            "the user on a host that shows any non-zero exit as an error, "
            "add --exit-zero: the call then exits 0 whenever the status was "
            "read, and the run's state is still in its text. Keep that flag "
            "off a poll whose loop reads the exit code.",
        ]
    # The end marker is unconditional across `util instructions`, so "search
    # for the end line" is a rule with no exception for a reader to hold. This
    # answer is a few hundred characters and can never be truncated; it
    # carries the marker anyway, because a check that is sometimes
    # inapplicable is a check an agent has to decide about.
    lines.append(f"{CORE_END_MARKER} {mode_name}")
    return "\n".join(lines) + "\n"


# ---------------------------------------------------------------------------
# `util instructions --to-file`: the core as a file the host reads
# ---------------------------------------------------------------------------
# A host whose tool results are capped (Claude Code persists a Bash result over
# ~30 000 characters behind a 2 KB stub; OpenCode cuts a tool result at 51 200
# bytes or 2 000 lines) reads a printed core as a fragment. The file form hands
# it a path and a line count instead, so "did I read all of it" is a count to
# reach, not a marker to hunt for. See docs/development/hosts.md.

#: The line ``--to-file`` prints, and the only line it prints on success.
CORE_FILE_MARKER = "[CORE_FILE]"

#: Where the file goes, under the repository root: a folder of its own inside
#: the self-ignoring workspace temp dir every run's scratch files use
#: (``utils/write_prompt.WORKSPACE_TMP``, implement's task JSON), inside the
#: workspace so the host's file tools and its shell name the same file on every
#: OS. Its own folder because the seven-day sweep deletes there: nothing but
#: this command writes ``cores/``, and the sweep reads no other folder.
CORE_FILE_DIR: Tuple[str, str, str] = (".multi-llm", "tmp", "cores")

#: ``core-<mode>-<sha12>.md``. The hash is of the bytes written, so two runs of
#: one mode under one plugin write the same bytes to the same name, and a
#: different plugin (or a changed core) writes a different file beside it:
#: concurrent runs never read each other's half-written or different core.
CORE_FILE_PREFIX = "core-"

#: The name format this command writes, and the only names its sweep removes:
#: ``core-`` + a mode word (lower-case words joined by ``-``) + ``-`` + twelve
#: hex digits + ``.md``.
CORE_FILE_NAME = re.compile(r"core-[a-z][a-z0-9]*(?:-[a-z0-9]+)*-[0-9a-f]{12}\.md")

#: A core file older than this is removed when another one is written.
CORE_FILE_MAX_AGE_S = 7 * 24 * 3600


def _core_file_root() -> str:
    """The repository root the core file goes under (the cwd outside one)."""
    cwd = os.getcwd()
    try:
        # Imported here to keep multi_llm light.
        from utils.git_utils import pin_repo_root

        root, problem = pin_repo_root(cwd)
    except Exception:  # noqa: BLE001 - no repository is the cwd's answer
        return cwd
    return root if root and not problem else cwd


def _write_core_file(mode_name: str, text: str) -> str:
    """Write *text* to ``<root>/.multi-llm/tmp/cores/core-<mode>-<sha12>.md``;
    its path.

    Written as a new file renamed into place, never through a link at the
    name or in the folder chain (``utils/prompt_files``), so a reader sees the
    previous complete file or the new one. Raises ``OSError``.
    """

    # Imported here to keep multi_llm light.
    from utils import prompt_files

    data = text.encode("utf-8")
    root = _core_file_root()
    try:
        os.mkdir(os.path.join(root, CORE_FILE_DIR[0]))
    except FileExistsError:
        pass  # a link there is refused by the walk below
    # `tmp` first, self-ignoring as the write phases leave it, then `cores`
    # inside it: each opened below the one before without following a link.
    tmp_pin = prompt_files.PhasePin(root=root, parts=CORE_FILE_DIR[:1])
    with prompt_files.PromptFolder.open(tmp_pin, folder=CORE_FILE_DIR[1]) as tmp:
        if ".gitignore" not in tmp.names():
            tmp.write(".gitignore", "*\n")
    pin = prompt_files.PhasePin(root=root, parts=CORE_FILE_DIR[:2])
    name = f"{CORE_FILE_PREFIX}{mode_name}-{hashlib.sha256(data).hexdigest()[:12]}.md"
    with prompt_files.PromptFolder.open(pin, folder=CORE_FILE_DIR[2]) as folder:
        names = folder.names()
        folder.write_bytes(name, data)
        _sweep_core_files(folder, names, keep=name)
        return os.path.join(folder.path, name)


def _sweep_core_files(folder, names: Sequence[str], *, keep: str) -> None:
    """Remove the core files in *folder* older than :data:`CORE_FILE_MAX_AGE_S`.

    Only a name of :data:`CORE_FILE_NAME`'s format, and only a regular file:
    each entry is inspected through the folder's own descriptor without
    following a link (``PromptFolder.lstat``), so a link, a folder or any other
    kind of entry stays, and so does every other name. Best effort: a file
    left behind costs nothing.
    """

    cutoff = time.time() - CORE_FILE_MAX_AGE_S
    for old in names:
        if old == keep or not CORE_FILE_NAME.fullmatch(old):
            continue
        try:
            info = folder.lstat(old)
            if stat.S_ISREG(info.st_mode) and info.st_mtime < cutoff:
                folder.remove(old)
        except OSError:
            pass


def _serve_core_file(mode_name: str, text: str, fallback: str, ctx: ResultContext) -> int:
    """Write *text* as the core file and print its ``[CORE_FILE]`` line.

    A folder that cannot be written (a read-only checkout, a link planted at
    ``.multi-llm``) costs the file, never the core: *fallback*, the printed
    form, goes to stdout instead, after one stderr line saying why.
    """
    try:
        path = _write_core_file(mode_name, text)
    except OSError as exc:
        print(
            f"multi-llm: could not write the core file ({exc}); "
            "printing the core instead.",
            file=sys.stderr,
        )
        sys.stdout.write(fallback)
        return EXIT_OK
    ctx.add_artifact(path)
    lines, size = text.count("\n"), len(text.encode("utf-8"))
    print(f"{CORE_FILE_MARKER} {path} lines={lines} bytes={size}")
    return EXIT_OK


#: Closes the served core. Its whole job is to be *checkable*: an agent does not
#: have to judge whether it received the whole document, it searches for a literal
#: string. Never printed anywhere else, so a match means the tail arrived.
CORE_END_MARKER = "MULTI_LLM_CORE_END:"

#: How :func:`_truncation_notice`'s head banner opens. A constant rather than
#: a literal inside the banner because a package route's server reads the
#: ``util instructions`` stdout through a pipe and *drops* the banner before it
#: attaches the runbook (its character count describes the unscrubbed core):
#: it finds the banner by this prefix, read off the generated surface, never
#: by a spelling of its own.
TRUNCATION_BANNER_OPENING = "=== READ THIS FIRST"


def _truncation_notice(mode_name: str, core: str) -> str:
    """The head banner that survives a host truncating this command's output.

    MEASURED, not hypothetical. Claude Code persists any Bash result over ~30 000
    characters to a file and replaces it with a ~2.2 KB stub: a pointer line plus
    the output's **first 2 KB** and nothing else. Seven of the eleven cores are
    over that cap. On 2026-09-22 an `apply-suggestions` row read that stub, did not
    follow the pointer, never saw the per-batch loop that lives in the second half,
    and finished the turn reporting four batches applied with zero edits made.

    Two facts decide the shape. The surviving region is the **head**, so a footer
    would be the first thing lost — a notice can only live here. And the host's own
    stub already names the byte count and the path, and was ignored; so this does
    not repeat the pointer, it gives the reader a *test* — one literal string, at a
    known place — that turns "did I get all of it?" from a judgement into a lookup.
    """
    return (
        f"{TRUNCATION_BANNER_OPENING} · multi-llm core instructions · "
        f"{mode_name} ===\n"
        f"The core below is {len(core):,} characters. Its last line is exactly:\n"
        "\n"
        f"    {CORE_END_MARKER} {mode_name}\n"
        "\n"
        "Search what you just received for that line. If it is not there, your host\n"
        "truncated this command's output and saved the whole of it to a file; the\n"
        "host's own wrapper around this text names that file's path. Stop there:\n"
        "read that file to the end before your next tool call and follow it, not\n"
        "this excerpt.\n"
        "\n"
        "A note from your host, anywhere in what you received, that it truncated\n"
        "or omitted part of this output means you do not have the whole core, even\n"
        "with that line there: a host that cuts the middle keeps the end line.\n"
        "\n"
        "Truncation keeps the head. The head is what the mode is and how it is\n"
        "invoked; the rest is the loop that does the work. So a cut\n"
        "core reads like a complete overview, and the usage line you can still see\n"
        "runs cleanly — it starts the orchestrator, which reports success, and you\n"
        "end the turn having applied nothing. Do not run any command from a core\n"
        "you have not seen all of.\n"
        "=== the core begins on the next line ===\n"
    )


# ---------------------------------------------------------------------------
# `util instructions --page`: the core in pieces a cutting shell passes whole
# ---------------------------------------------------------------------------
# Codex has no file-read tool, and its shell keeps the head and the tail of an
# output over its budget and drops the middle, so the printed core's end line
# survives a cut that lost workflow steps (docs/development/hosts.md, "Paged
# delivery"). Pages bounded under that budget arrive whole; each one says which
# page it is and closes with its own end line, and a page that was cut anyway
# is fetched again smaller.

#: Opens every page: ``[CORE_PAGE] mode=<m> page=<i>/<n> sha=<sha12> bytes=<n>``.
CORE_PAGE_MARKER = "[CORE_PAGE]"

#: Closes every page: ``[CORE_PAGE_END] mode=<m> page=<i>/<n> sha=<sha12>``.
CORE_PAGE_END_MARKER = "[CORE_PAGE_END]"

#: The two page lines, whole: ``str.format`` templates over ``mode``, ``page``,
#: ``pages``, ``sha`` and (the header) ``bytes``, the page's UTF-8 byte count
#: between its two lines. The one spelling of the format, which the Codex tool
#: route's pages carry too (``packaging/common/surface.py``, ``runbook.pages``).
CORE_PAGE_HEADER = (
    CORE_PAGE_MARKER + " mode={mode} page={page}/{pages} sha={sha} bytes={bytes}"
)
CORE_PAGE_END = CORE_PAGE_END_MARKER + " mode={mode} page={page}/{pages} sha={sha}"

#: Hex digits of the sha every page line carries.
CORE_PAGE_SHA_CHARS = 12

#: The most core bytes one page holds when ``--page-size`` is not given:
#: 4,000 tokens as codex counts them (4 bytes a token), 40% of the 10,000-token
#: budget its shell and code-mode ``exec`` results default to. The model can
#: lower that budget per call, and has (about 4,600 tokens in one measured
#: read), so the default leaves room below the documented figure rather than
#: filling it; a page cut anyway is fetched again at half the size.
CORE_PAGE_SIZE_DEFAULT = 16_000

#: The smallest ``--page-size`` served. The longest core line (about 2,500
#: bytes) already gets a page of its own at this size, so a smaller one only
#: multiplies the pages; and a typo (``8`` meant as 8 KB) is refused rather
#: than served as a page per line.
CORE_PAGE_SIZE_MIN = 2_000


def _core_pages(text: str, size: int, first: int) -> List[str]:
    """*text* cut into pages on line boundaries: the first of at most *first*
    UTF-8 bytes, every later one of at most *size*.

    Packed greedily from the start, so every page but the last is as full as
    whole lines allow. A line longer than its page's room gets a page of its
    own rather than being split. ``"".join`` of the result is *text*, byte for
    byte.
    """
    pages: List[str] = []
    current: List[str] = []
    filled = 0
    for line in re.findall(r"[^\n]*\n|[^\n]+$", text):
        length = len(line.encode("utf-8"))
        room = first if not pages else size
        if current and filled + length > room:
            pages.append("".join(current))
            current, filled = [], 0
        current.append(line)
        filled += length
    if current or not pages:
        pages.append("".join(current))
    return pages


def _core_sha(text: str) -> str:
    """The sha every page carries: sha256 of the whole paged text, 12 hex digits.

    The same digest ``--to-file`` names its file by, so a paged read and the
    file form of one render agree on it.
    """

    return hashlib.sha256(text.encode("utf-8")).hexdigest()[:CORE_PAGE_SHA_CHARS]


def _serve_core_page(mode_name: str, text: str, page: int, size: Optional[int]) -> int:
    """Print page *page* of *text*: header, page 1's banner, the page, end line.

    *text* is what ``--to-file`` writes (the core, its end line, the ``--host``
    section), so the pages' bodies joined are that text exactly. Between its
    header and its end line a page prints at most *size* bytes, page 1's banner
    included, unless one line alone is longer.
    """
    size = size or CORE_PAGE_SIZE_DEFAULT
    sha = _core_sha(text)
    # Page 1's room is the size less the longest banner it could carry (both
    # wordings, a four-digit count), so the cut never depends on the count the
    # cut produces.
    allowance = max(
        len(_paged_notice(mode_name, text, count, sha, size).encode("utf-8"))
        for count in (1, 9999)
    )
    pages = _core_pages(text, size, first=max(0, size - allowance))
    count = len(pages)
    if page > count:
        raise DispatchError(
            f"ERROR: `util instructions {mode_name} --page {page}`: at "
            f"--page-size {size} the core has {count} page"
            f"{'' if count == 1 else 's'}, so --page takes 1 to {count}."
        )
    body = pages[page - 1]
    where = {"mode": mode_name, "page": page, "pages": count, "sha": sha}
    out = CORE_PAGE_HEADER.format(bytes=len(body.encode("utf-8")), **where) + "\n"
    if page == 1:
        out += _paged_notice(mode_name, text, count, sha, size)
    out += body + CORE_PAGE_END.format(**where) + "\n"
    sys.stdout.write(out)
    return EXIT_OK


def _paged_notice(mode_name: str, text: str, count: int, sha: str, size: int) -> str:
    """Page 1's banner: the paged completeness rule, after the header line.

    It opens with :data:`TRUNCATION_BANNER_OPENING` and closes with the printed
    banner's closing line, so a reader that drops the printed banner drops this
    one the same way. It sits at the head, which a middle cut keeps.
    """

    smaller = max(CORE_PAGE_SIZE_MIN, size // 2)
    total = len(text.encode("utf-8"))
    if count == 1:
        whole = (
            f"The core is {total:,} bytes, all on this page: there is no other "
            "page to fetch. You hold the whole core only when this page arrived "
            "whole: it starts with its header line and ends with its end line, "
            f"both carrying page=1/1 and sha={sha}:"
        )
    else:
        whole = (
            f"The core is {total:,} bytes in {count} pages. Run the same command "
            f"for pages 2 to {count}, changing only the --page number. You hold "
            f"the whole core only when every page from 1 to {count} arrived "
            "whole: each starts with its header line and ends with its end "
            f"line, both carrying its page=<i>/{count} and the same sha={sha}:"
        )
    if smaller < size:
        again = (
            f"Fetch it again with --page-size {smaller}. A new size cuts the "
            "core afresh, so start again at page 1 with that size and keep it "
            "for every later page; never combine pages of two sizes."
        )
    else:
        again = (
            f"--page-size {size} is already the smallest this command serves, "
            "so your host cannot pass a page whole: stop and tell the user."
        )
    cut = (
        "A note from your host, anywhere in a page's output, that it truncated "
        "or omitted part of that output means the page is incomplete, even with "
        "both of its lines there: a host that cuts the middle keeps the head and "
        f"the end. {again}"
    )
    where = f"mode={mode_name} page=<i>/{count} sha={sha}"
    return (
        f"{TRUNCATION_BANNER_OPENING} · multi-llm core instructions · "
        f"{mode_name} · page 1 of {count} ===\n"
        f"{textwrap.fill(whole, 78)}\n"
        "\n"
        f"    {CORE_PAGE_MARKER} {where} bytes=<n>\n"
        f"    {CORE_PAGE_END_MARKER} {where}\n"
        "\n"
        "One of the pages ends the core with this line (a --host section may follow it):\n"
        "\n"
        f"    {CORE_END_MARKER} {mode_name}\n"
        "\n"
        f"{textwrap.fill(cut, 78)}\n"
        "\n"
        "Do not run any command from the core until you hold every page.\n"
        "=== the core begins on the next line ===\n"
    )


# The tool route's paging rule (docs/development/hosts.md, "Paged delivery on
# the Codex tool route"). The Codex MCP server pages the runbook it attaches to
# a tool result, with the two page lines above, and states this rule in the
# key that closes the result, right after the page: a middle cut keeps the tail.
# Templates the surface carries (``runbook.pages``): the server fills the
# ``{name}`` tokens by plain substitution and spells none of these words.

#: The option a page request carries in ``extra_flags``, and the size option.
TOOL_PAGE_OPTION = "--page"
TOOL_PAGE_SIZE_OPTION = "--page-size"

_TOOL_PAGE_LINES = (
    f"each opens with `{CORE_PAGE_MARKER} mode={{mode}} page=<i>/{{pages}} "
    "sha={sha} bytes=<n>` and closes with "
    f"`{CORE_PAGE_END_MARKER} mode={{mode}} page=<i>/{{pages}} sha={{sha}}`"
)

_TOOL_PAGE_CUT = (
    "A note from your host anywhere in a result that it truncated or omitted "
    "part of that result means its page is incomplete, even with both of its "
    "lines there: a host that cuts the middle keeps the head and the end."
)

#: ``runbook_pages.rule`` for a runbook of several pages.
TOOL_PAGES_RULE = (
    "`runbook` holds page {page} of the {mode} runbook, which is {pages} pages "
    "of at most {size} bytes. You hold the whole runbook only when every page "
    f"from 1 to {{pages}} arrived whole: {_TOOL_PAGE_LINES}, every one with the "
    "same sha, and one of them carries the line that closes the core, "
    f"`{CORE_END_MARKER} {{mode}}`. To fetch page <i>, call this tool again "
    f'with mode "{{mode}}" and extra_flags ["{TOOL_PAGE_OPTION}", "<i>", '
    f'"{TOOL_PAGE_SIZE_OPTION}", "{{size}}"] (`next_page` is that call for the '
    "next page): a call whose extra_flags carry "
    f"{TOOL_PAGE_OPTION} returns that page and nothing else, and never starts, "
    f"resumes or repeats a run. {_TOOL_PAGE_CUT} {{again}} Do not run any step "
    "of the runbook until you hold every page."
)

#: ``runbook_pages.rule`` for a runbook that fits on one page.
TOOL_PAGES_RULE_ONE = (
    "`runbook` holds the whole {mode} runbook, on one page of at most {size} "
    "bytes: there is no other page to fetch. You hold it only when it arrived "
    f"whole: it opens with `{CORE_PAGE_MARKER} mode={{mode}} page=1/1 "
    "sha={sha} bytes=<n>` and closes with "
    f"`{CORE_PAGE_END_MARKER} mode={{mode}} page=1/1 sha={{sha}}`. "
    f"{_TOOL_PAGE_CUT} {{again}} Do not run any step of the runbook until you "
    "hold all of it."
)

#: The rule's ``{again}`` while a smaller size is left.
TOOL_PAGES_AGAIN = (
    f"Fetch it again at {TOOL_PAGE_SIZE_OPTION} {{smaller}} (`smaller` is that "
    "call, for page 1): a new size cuts the runbook afresh, so start again at page 1 "
    "with that size and keep it for every later page; never combine pages of "
    "two sizes."
)

#: The rule's ``{again}`` at the smallest size.
TOOL_PAGES_FLOOR = (
    f"{TOOL_PAGE_SIZE_OPTION} {{size}} is already the smallest this tool "
    "serves, so your host cannot pass a page whole: stop and tell the user."
)

#: The ``message`` of a page request's result.
TOOL_PAGES_SERVED = (
    "This call fetched page {page} of {pages} of the {mode} runbook into "
    "`runbook`, and nothing else: it started, resumed and repeated no run. "
    "`runbook_pages` says when you hold the whole runbook."
)

#: ``runbook.references``: the line a Codex tool-route runbook opens with when it
#: names a reference. That route scrubs every dispatcher command line, and those
#: are the only lines of a served core that name the skill directory, so the
#: server states where ``references/`` is; ``{dir}`` is its own skill
#: directory's ``references`` folder (docs/development/hosts.md, "Paged delivery
#: on the Codex tool route").
TOOL_REFERENCES_LINE = (
    "Every `references/<file>.md` this runbook names, or a file it sends you to "
    "names, is the file of that name in `{dir}`: read it there when a step says to."
)

#: ``runbook.core_file``: how a package route that hands the core to the model in
#: a tool result hands it a file instead. OpenCode cuts a tool result at 51 200
#: bytes and several cores are over that once JSON-escaped, so the OpenCode
#: package asks ``util instructions <mode> --host <id>`` for this option's
#: ``[CORE_FILE]`` line and attaches that line and :data:`TOOL_CORE_FILE_READ`
#: (``{mode}``, ``{lines}``) in place of the core (docs/development/hosts.md,
#: "Host-neutral instruction core").
TOOL_CORE_FILE_OPTION = "--to-file"
TOOL_CORE_FILE_READ = (
    "The {mode} core instructions, this host's capability verbs included, are in "
    "the file the line above names. Read that file in full, through line {lines}, "
    "before your next command or call: a read that stops early names the offset "
    "to go on from. Do not run any step of it until you have read all of it."
)


#: Heading the ``--host`` verb block is served under. The core files name the
#: three capability verbs abstractly and it has always been the *shim's* section 4
#: that resolved them; a host with no prose left to carry that section — the
#: OpenCode npm plugin, whose command body is one line — needs the resolution to
#: arrive with the core instead. Same single owner either way:
#: ``caps.verb_block()``.
_VERB_HEADING = "## Capability verbs — how this host answers each one"


def _verb_section(host_id: str) -> str:
    """The three resolved verb sentences, as the section a shim used to carry."""
    # Imported here to keep multi_llm light.
    from utils import host_capabilities as caps

    return (
        f"\n{_VERB_HEADING}\n\n"
        "The core above names three capability verbs and never a tool. These are "
        "their one concrete resolution here, so nothing is left to decide "
        f"mid-run:\n\n{caps.verb_block(host_id)}\n"
    )


#: ``util instructions``'s options, as its refusal of any other one names them.
_INSTRUCTIONS_OPTIONS = (
    "`--host <id>`, `--to-file`, `--page <i>` and `--page-size <bytes>`"
)


def _option_value(args: Sequence[str], index: int, name: str, what: str) -> "tuple[str, int]":
    """The value of option *name* at ``args[index]`` (inline ``=`` or the next
    token) and the index of the last token it used. Raises on a missing value."""
    _head, separator, inline = args[index].partition("=")
    if not separator:
        index += 1
        inline = args[index] if index < len(args) else ""
    if not inline:
        raise DispatchError(f"ERROR: `util instructions {name}` needs {what}.")
    return inline, index


def _positive_count(value: str, name: str, least: int) -> int:
    """*value* as a whole number of at least *least*, or a refusal naming *name*."""
    if not re.fullmatch(r"[0-9]+", value) or int(value) < least:
        raise DispatchError(
            f"ERROR: `util instructions {name}` takes a whole number of at least "
            f"{least}, got {value!r}."
        )
    return int(value)


def _split_instructions_host(
    args: Sequence[str],
) -> "tuple[list[str], Optional[str], bool, Optional[int], Optional[int]]":
    """Split ``util instructions`` argv into positionals, a ``--host`` value,
    whether ``--to-file`` was given, the ``--page`` number and ``--page-size``.

    Hand-parsed rather than argparse'd because this command's whole contract is
    that its stdout **is** the core text: an argparse error would print a usage
    block a host may be piping straight into a prompt, and the surrounding
    dispatcher already owns the exit-3 wording for a bad argument.
    """
    positional: list = []
    host_id: Optional[str] = None
    to_file = False
    page: Optional[int] = None
    page_size: Optional[int] = None
    index = 0
    while index < len(args):
        token = args[index]
        head, separator, inline = token.partition("=")
        if token == "--to-file":
            to_file = True
        elif head == "--page":
            value, index = _option_value(args, index, "--page", "a page number")
            page = _positive_count(value, "--page", 1)
        elif head == "--page-size":
            value, index = _option_value(args, index, "--page-size", "a size in bytes")
            page_size = _positive_count(value, "--page-size", CORE_PAGE_SIZE_MIN)
        elif head == "--host":
            if separator:
                value = inline
            else:
                index += 1
                if index >= len(args):
                    raise DispatchError(
                        "ERROR: `util instructions --host` needs a host id."
                    )
                value = args[index]
            if not value:
                raise DispatchError(
                    "ERROR: `util instructions --host` needs a host id."
                )
            host_id = value
        elif token.startswith("-"):
            raise DispatchError(
                f"ERROR: `util instructions` does not take {token!r}. Its "
                f"options are {_INSTRUCTIONS_OPTIONS}."
            )
        else:
            positional.append(token)
        index += 1
    if page_size is not None and page is None:
        raise DispatchError(
            "ERROR: `util instructions --page-size` sizes the pages of a paged "
            "read; add `--page <i>`."
        )
    if page is not None and to_file:
        raise DispatchError(
            "ERROR: `util instructions` takes `--to-file` or `--page`, not both: "
            "the file form is for a host that reads files, pages for one that "
            "cannot."
        )
    return positional, host_id, to_file, page, page_size


def _dispatch(argv: Sequence[str], ctx: ResultContext) -> int:
    if not argv:
        raise DispatchError(
            "ERROR: no mode given. The mode is a bare word and must be the first "
            f"argument.\nValid modes: {', '.join(mode_table.mode_names())}\n"
            "Run `multi_llm.py --help` for the full grammar."
        )
    word = argv[0]
    if word in ("--help", "-h", "help"):
        print(render_help())
        return EXIT_OK
    if word == mode_table.UTIL_NAMESPACE:
        return _run_util(argv[1:], ctx)
    if word.startswith("-"):
        raise DispatchError(
            f"ERROR: '{word}' is not a mode. The mode is a bare word and must be "
            "the first argument (e.g. `multi_llm.py review-plan plans/x.md "
            f"{word}`).\n" + _unknown_mode_message(word)
        )
    return _run_mode(word, argv[1:], ctx)


def _exit_code_of(exc: SystemExit) -> int:
    """A target's ``sys.exit`` is its return value; never remap 0/1/2/3.

    The one exception is argparse's usage exit — see ``_is_argparse_usage_exit``,
    which the caller consults; that code was never the target's to spend.
    """
    code = exc.code
    if code is None:
        return EXIT_OK
    if isinstance(code, int):
        return code
    print(str(code), file=sys.stderr)
    return EXIT_ERROR


def _is_argparse_usage_exit(exc: SystemExit) -> bool:
    """True when this ``SystemExit`` came out of argparse's usage-error path.

    ``ArgumentParser.error`` exits **2**, which is the one code this skill has
    already spent: 2 means "nothing to do / phase already complete" (the
    orchestrators' phase-complete guards, which raise it with a plain
    ``sys.exit(2)``). Passing argparse's 2 through would put
    ``state: nothing-to-do`` on the MULTI_LLM_RESULT line for a typo'd flag or a
    missing ``--plan-file``, and a host reading only the machine contract would
    conclude the phase was done and skip it — the worst possible reading of a
    command that never ran.

    The two are distinguishable only by origin, so the traceback is the
    discriminator: argparse raises from its own module frames, a phase guard from
    the orchestrator's. Matching on frames rather than on the message keeps this
    independent of argparse's (localized, version-dependent) wording.
    """
    tb = exc.__traceback__
    while tb is not None:
        if tb.tb_frame.f_globals.get("__name__") == "argparse":
            return True
        tb = tb.tb_next
    return False


def _sweep_live_clis_on_interrupt() -> None:
    """Stop every Lane A CLI still registered when Ctrl-C reached the dispatcher.

    A fan-out's slots wait on their CLIs from worker threads, where
    ``KeyboardInterrupt`` is never raised, and an agent CLI's tool shells run in
    sessions of their own that a terminal SIGINT does not reach. The
    registry holds each live CLI with a refreshed snapshot of its descendants,
    so this reaps what those slots started before the process exits.

    The backstop, not the main path: an async target's fan-out is swept inside
    its own cancellation (``_call_target``), because by the time
    ``asyncio.run`` lets a ``KeyboardInterrupt`` reach this handler it has
    already joined every worker thread. What is left for here is a sync
    target's CLI. A no-op when nothing is registered, and it never raises: the
    interrupt's own exit and result line must still happen.
    """
    try:
        # Imported here to keep multi_llm light.
        from utils import process_control
    except Exception as exc:  # noqa: BLE001 - see above
        print(f"[INTERRUPT_SWEEP] failed: {exc}", file=sys.stderr)
        return
    process_control.sweep_live_clis("INTERRUPT_SWEEP")


def main(argv: Optional[Sequence[str]] = None) -> int:
    # Imported here to keep multi_llm light.
    from utils import process_control

    # The CLI's process, and the detached worker's: SIGCHLD at its default, so
    # every provider child stays this process's until it is reaped.
    process_control.restore_sigchld_default()
    argv = list(sys.argv[1:] if argv is None else argv)
    if _WORKER_FLAG in argv:
        # Imported here to keep multi_llm light.
        from utils.detach import prepare_worker_output

        prepare_worker_output()
        # A commit front door's stage, applied once the worker owns its dir:
        # the applier sits above `detach`, so it is handed in here.
        # Imported here to keep multi_llm light.
        from utils.commit_front_door import hand_worker_the_stage_applier

        hand_worker_the_stage_applier(argv)
    # Line buffering + UTF-8/replace stream encoding, once per invocation: there
    # is exactly one process per invocation, so this covers every mode and every
    # in-process continuation.
    bootstrap_streams()
    ctx = activate_result(ResultContext())
    crash: Optional[str] = None
    exit_code = EXIT_ERROR
    previous_sigterm = _install_foreground_sigterm()
    try:
        try:
            exit_code = _dispatch(argv, ctx)
        except DispatchError as exc:
            print(str(exc), file=sys.stderr)
            exit_code = exc.exit_code
        except NeedsHuman as exc:
            # Every unattended gate that cannot resolve lands here with the same
            # code, whether it was raised by the dispatcher's own pre-checks or
            # by the mode it dispatched to.
            print(exc.message, file=sys.stderr)
            ctx.state = "needs-human"
            exit_code = exc.exit_code
        except SystemExit as exc:
            exit_code = _exit_code_of(exc)
            if exit_code == EXIT_NOTHING_TO_DO and _is_argparse_usage_exit(exc):
                # A parser refused the command line: that is a broken invocation
                # a human has to retype, so it lands on exit 3 with every other
                # "cannot proceed" — never on 2, which the phase-complete guards
                # own. argparse has already named the offending token on stderr.
                print(
                    "ERROR: that command line did not parse (see the usage error "
                    "above). Fix the invocation and re-run.\nExit 3, not 2: exit 2 "
                    "is reserved for 'nothing to do / phase already complete', and "
                    "nothing about this phase ran.",
                    file=sys.stderr,
                )
                exit_code = EXIT_NEEDS_HUMAN
        except KeyboardInterrupt:
            print("\nInterrupted.", file=sys.stderr)
            _sweep_live_clis_on_interrupt()
            exit_code = EXIT_ERROR
        except Exception:
            # The machine-readable contract has to hold on a crash too, so the
            # traceback goes to stderr and the result line is still the last
            # stdout line before this returns 1.
            traceback.print_exc()
            crash = _crash_summary()
            exit_code = EXIT_ERROR
        try:
            _remember_plan_spelling(ctx)
        except Exception as exc:  # noqa: BLE001 - advisory, never the exit code
            print(
                f"multi-llm: could not save the plan path as you typed it ({exc}); "
                "the next command may name the plan by its absolute path.",
                file=sys.stderr,
            )
        try:
            _emit_user_next_step(ctx, exit_code)
        except Exception as exc:  # noqa: BLE001 - advisory, never the exit code
            # Imported here to keep multi_llm light.
            from utils.next_phase import lookup_failure_line

            print(lookup_failure_line(exc), file=sys.stderr)
        ctx.emit(exit_code)
        return exit_code
    finally:
        # Unavailable I12 (option B, 2026-09-30): every codex
        # child of this run has exited by now, so remove the
        # `[projects."<repo>"] trust_level = "trusted"` tables they added to the
        # user's codex config — and nothing else. A detached worker's `--abort`
        # and heartbeat-lost endings `os._exit` without reaching this line, so
        # `utils/detach.py` restores on those two paths itself.
        _restore_codex_trust()
        _uninstall_foreground_sigterm(previous_sigterm)
        # If this process is a detached worker, it is the only thing that can
        # ever observe its own exit status (after the double-spawn nothing is its
        # parent), so it records its own outcome before exiting. A no-op in every
        # other invocation.
        _close_detached_run(exit_code, crash or ctx.error, ctx.state)
        deactivate_result()
        clear_invocation()
        _back_to_the_callers_cwd()


def _write_phases() -> "frozenset":
    """The phases whose batch loop is the invoker's without ``--exec-subagents``.

    From the executor's own table (``subagent_tasks.PHASE_BY_WRITE_KIND``, the
    mode/``state.json`` spelling), never a hand-kept list.
    """
    # Imported here to keep multi_llm light.
    from utils.subagent_tasks import PHASE_BY_WRITE_KIND

    return frozenset(PHASE_BY_WRITE_KIND.values())


def _emit_user_next_step(ctx: ResultContext, exit_code: int) -> None:
    """Set ``user_next_step`` and print its block.

    Only for the recorded invocation of a workflow-phase mode or a
    review-then-apply composite (``improve-plan``, ``improve-code``) that exits
    0 or 2, or ``full`` on 0, with no ``next`` owed — and never for a write phase that
    handed its batch loop to the invoker (no ``--exec-subagents`` and not the
    closing ``--mark-completed`` call) or for the invoker of a ``--detach``
    launch, whose run's terminal poll answers instead.
    That last exclusion is the ``next`` test itself: ``detach.launch`` records
    the run's poll command as ``next`` on both of its success paths (a fresh
    launch and an ``--if-not-running`` re-attach) and fails every other way
    with exit 1 or 3. A ``--detach`` invocation that ended before the boundary
    — the completed-phase guard's exit 2, which the tool routes hit on every
    re-run because they always append ``--detach`` — launched nothing, so no
    poll will ever answer for it, and it goes through the builder like any
    foreground exit. The builder's gate decides the rest. ``plan_arg`` is the
    ``--plan-file`` value as received — or, for a continuation, the spelling its
    hand-off recorded (:func:`_continued_plan_arg`); a detached worker, whose
    argv holds it absolute, takes the run record's ``plan_arg`` (else its
    ``plan_file``). The block goes to stderr when the invocation asked for JSON
    output.

    A commit review's front doors record the phase they front (``review-code``,
    ``apply-code-fixes``) or ``improve-commits`` with its pinned range, so the gate below
    passes as for any phase, and the builder spells the answer back in the
    commit spelling: after ``review-commits``, ``--apply-commit-fixes
    <base12>..<head12>`` under a why naming both reports.
    """
    record = invocation()
    if not record or ctx.next:
        return
    mode = mode_table.resolve(str(record.get("mode") or ""))
    if mode is None:
        return
    if mode.runs_workflow:
        if exit_code != EXIT_OK:
            return
    elif not (
        (mode.is_workflow_phase or mode.is_composite)
        and exit_code in (EXIT_OK, EXIT_NOTHING_TO_DO)
    ):
        # A review-then-apply composite answers on 0 and on 2 too: its exit 2 is
        # `[ALREADY_COMPLETE]`, returned before its detach boundary, so a tool
        # route's `--detach` re-run of a finished composite carries the next
        # step like any foreground exit 2. The builder answers as the phase
        # it ends on, gate included.
        return
    argv = list(record.get("argv") or [])
    # No `--detach` test here: a launched or re-attached run already returned
    # above on its recorded `next`, and keying on the flag instead silenced a
    # completed phase's exit 2 that launched no run and so has no poll to
    # carry the answer.
    #
    # The native write leg's EMIT call is excluded (the batches are the
    # host's now, and the builder would answer `--resume` for the phase
    # being run); its closing `--mark-completed` call is not — that call
    # records the phase completed and is the one dispatcher invocation on
    # the native apply leg that can carry the answer (until 2026-10-05 the
    # exclusion swallowed it too, and only the report step's `util
    # next-command` ever answered). implement's closing step is `util
    # finalize-tracking --mark-completed`, a util, so that leg still reads
    # its answer from the report step's lookup.
    if (
        mode.phase in _write_phases()
        and not flag_present(argv, "--exec-subagents")
        and not flag_present(argv, "--mark-completed")
    ):
        return
    plan_arg, plan_path = _typed_plan(argv)
    if not plan_arg:
        return
    # Imported here to keep multi_llm light.
    from utils import next_phase

    as_json = flag_value(argv, "--output-format") == "json"
    next_phase.emit_answer(
        plan_arg,
        resolve_host(argv),
        mode.name,
        plan_path=plan_path,
        stream=sys.stderr if as_json else sys.stdout,
    )


def _typed_plan(argv: Sequence[str]) -> Tuple[Optional[str], Optional[str]]:
    """``(plan as the user typed it, absolute plan path)`` for this invocation.

    The typed spelling is :func:`utils.cli_common.invocation_plan_arg` (the
    ``--plan-file`` value as received, or a continuation's recovered one); a
    detached worker, whose argv holds the plan absolute, takes its run record's
    ``plan_arg`` (else its ``plan_file``) instead.

    ``improve-commits`` is recorded with its pinned range, not a plan
    (``--revs <base12>..<head12>``, "What step
    7 records"): the plan is the brief that spelling names
    (``commit_paths.brief_for_pinned``), and the typed spelling is the
    pinned range itself, which every command printed for it carries.
    """
    plan_file = flag_value(argv, "--plan-file")
    plan_arg = invocation_plan_arg() or plan_file
    plan_path = os.path.abspath(plan_file) if plan_file else None
    if plan_file is None:
        pinned = flag_value(argv, "--revs")
        brief = _brief_for_pinned(pinned) if pinned else None
        if brief is not None:
            plan_arg, plan_path = plan_arg or pinned, brief
    worker = flag_present(argv, "--internal-worker")
    detach = sys.modules.get("utils.detach") if worker else None
    handle = detach.active_run() if detach is not None else None
    if handle is not None:
        plan_path = handle.plan_file
        plan_arg = handle.plan_arg or handle.plan_file
    return plan_arg, plan_path


def _brief_for_pinned(text: str) -> Optional[str]:
    """The brief a commit review's pinned ``<base12>..<head12>`` names
    (``commit_paths.brief_for_pinned``: by name, no git call beyond the
    root), absolute, or ``None`` for any other text or outside a repository."""
    try:
        # Imported here to keep multi_llm light.
        from utils.commit_paths import brief_for_pinned

        brief = brief_for_pinned(str(text))
    except Exception:  # noqa: BLE001 - not a pinned range here
        return None
    return os.path.abspath(str(brief)) if brief is not None else None


def _continuation_target(command: str) -> Optional[Tuple["mode_table.Mode", str]]:
    """``(mode, plan)`` of a printed continuation command, else ``None``.

    A continuation is a dispatcher command (``… multi_llm.py <mode> <plan> …``,
    or ``--plan-file <plan>``) carrying one of
    :data:`utils.cli_common.CONTINUATION_VERBS`; its *mode* is a workflow phase.

    A continuation in the commit spelling (``review-commits <base12>..<head12>
    --reaggregate``, or the brief path on
    a root range) names the phase its front door fronts
    (``Mode.commit_view_of``) and the brief its range names.
    """

    try:
        tokens = shlex.split(command)
    except ValueError:
        return None
    if not CONTINUATION_VERBS.intersection(t.split("=", 1)[0] for t in tokens):
        return None
    script = next(
        (i for i, token in enumerate(tokens)
         if os.path.basename(token) == "multi_llm.py"),
        None,
    )
    if script is None or script + 1 >= len(tokens):
        return None
    mode = mode_table.resolve(tokens[script + 1])
    fronts = mode.commit_view_of if mode is not None else None
    if fronts:
        mode = mode_table.resolve(fronts)
    if mode is None or not mode.is_workflow_phase or not mode.phase:
        return None
    rest = tokens[script + 2:]
    plan = flag_value(rest, "--plan-file")
    if plan is None and rest and not rest[0].startswith("-"):
        plan = rest[0]
        if fronts and not os.path.isfile(plan):
            plan = _brief_for_pinned(plan) or ""
    if not plan:
        return None
    return mode, plan


def _continued_phase_dir(mode: "mode_table.Mode", plan: str) -> Path:
    # Imported here to keep multi_llm light.
    from utils.output_handler import phase_dir_path

    return phase_dir_path(Path(os.path.abspath(plan)), str(mode.phase))


def _remember_plan_spelling(ctx: ResultContext) -> None:
    """Record, for the continuation this run hands back, how its plan was typed.

    A native leg's ``next`` (``generate-tasks <plan> --reaggregate``, a review's
    ``--reaggregate``) names the plan absolutely, like every printed follow-up,
    and the host runs it verbatim — so the run that finishes the phase would
    otherwise print its next-phase command with the absolute path although the
    user typed a relative one (racing re-run 4, Claude Code phase 03). This
    writes the plan as this invocation received it into the continued phase's
    ``.status.json`` as ``plan_arg``, beside the ``plan_file`` the checkpoint
    already holds; :func:`_continued_plan_arg` reads it back. Only when the
    command names the same file and its phase dir exists; best-effort.
    """
    record = invocation()
    if not record or not ctx.next:
        return
    target = _continuation_target(str(ctx.next))
    if target is None:
        return
    mode, plan = target
    typed, _plan_path = _typed_plan(list(record.get("argv") or []))
    if not typed or os.path.realpath(typed) != os.path.realpath(plan):
        return
    phase_dir = _continued_phase_dir(mode, plan)
    if not phase_dir.is_dir():
        return
    # Imported here to keep multi_llm light.
    from utils import status_file

    status_file.update_status(str(phase_dir), {"plan_arg": str(typed)})


def _continued_plan_arg(
    mode: "mode_table.Mode", argv: Sequence[str]
) -> Optional[str]:
    """The typed plan a continuation's hand-off recorded, when it names this plan.

    For a workflow-phase invocation carrying a continuation verb: the
    ``plan_arg`` :func:`_remember_plan_spelling` wrote into the phase dir's
    ``.status.json`` — else, when the hand-off recorded none (or one that does
    not pass), the phase's detached run record's ``plan_arg``, the plan as its
    launcher typed it: a detached launch records no hand-off spelling, and its
    status read's "advance it with: … --reaggregate" names the plan absolutely. Either
    is printed only when
    ``next_phase.recorded_plan_spelling`` passes it — the folder is writable by
    every jailed batch, so a spelling that does not resolve strictly to this
    plan from this cwd, or that holds a character a shell would act on, is
    never printed. A passing spelling equal to the ``--plan-file`` received is
    ``None`` too, and the plan is printed as received.
    """
    if not mode.is_workflow_phase or not mode.phase:
        return None
    if not flag_present(argv, *sorted(CONTINUATION_VERBS)):
        return None
    plan = flag_value(argv, "--plan-file")
    if not plan:
        return None
    # Imported here to keep multi_llm light.
    from utils import next_phase, status_file

    status = status_file.read_status(str(_continued_phase_dir(mode, plan)))
    run = status.get("run")
    for recorded in (
        status.get("plan_arg"),
        run.get("plan_arg") if isinstance(run, dict) else None,
    ):
        spelling = next_phase.recorded_plan_spelling(recorded, plan)
        if spelling is not None:
            return None if spelling == plan else spelling
    return None


def _raise_on_sigterm(signum, frame):  # pragma: no cover - exercised in a subprocess
    """SIGTERM → ``SystemExit(128 + signum)``, so ``main``'s ``finally`` runs.

    Once: later SIGTERMs are ignored before raising. A group kill reaches this
    process twice — directly and as the copy ``uv run`` forwards to its child —
    and the second ``SystemExit`` would be raised inside that ``finally``,
    cutting short the config restore and the result line it exists to run.
    Nothing is printed here: a handler can land inside a buffered write.
    """
    # Imported here: multi_llm does not otherwise load signal.
    import signal

    try:
        signal.signal(signal.SIGTERM, signal.SIG_IGN)
    except (ValueError, OSError):
        pass
    raise SystemExit(128 + signum)


def _install_foreground_sigterm():
    """Make a foreground SIGTERM run ``main``'s ``finally`` (plan I12).

    A foreground run had no SIGTERM handler, so the default action killed the
    process with no cleanup — and the trust entries its codex children wrote
    stayed in the user's config. Installed only when nothing else owns the
    signal (the default disposition) and only on the main thread; the detached
    worker installs its own handler later, which takes precedence. Returns the
    previous handler for :func:`_uninstall_foreground_sigterm`, or ``None``
    when nothing was installed.
    """
    try:
        # Imported here: multi_llm does not otherwise load signal or threading.
        import signal
        import threading

        if threading.current_thread() is not threading.main_thread():
            return None
        if signal.getsignal(signal.SIGTERM) is not signal.SIG_DFL:
            return None
        signal.signal(signal.SIGTERM, _raise_on_sigterm)
        return signal.SIG_DFL
    except (ImportError, ValueError, OSError, AttributeError):  # pragma: no cover
        return None


def _uninstall_foreground_sigterm(previous) -> None:
    """Put back the disposition :func:`_install_foreground_sigterm` replaced,
    only if our handler is still the one installed."""
    if previous is None:
        return
    try:
        # Imported here: multi_llm does not otherwise load signal.
        import signal

        if signal.getsignal(signal.SIGTERM) is _raise_on_sigterm:
            signal.signal(signal.SIGTERM, previous)
    except (ValueError, OSError):  # pragma: no cover
        pass


def _restore_codex_trust() -> None:
    """Remove the codex trust entries this run's children added (plan I12).
    Never raises: close-out must never mask the run's result."""
    try:
        # Imported here to keep multi_llm light.
        from utils import codex_trust
    except Exception:  # noqa: BLE001 - see above
        return
    try:
        codex_trust.restore_all()
    except Exception:  # noqa: BLE001 - see above  # pragma: no cover
        traceback.print_exc()


def _crash_summary(limit: int = 2000) -> str:
    """Message + traceback tail, for ``run.error`` on a crashed detached run."""
    text = traceback.format_exc()
    return text[-limit:]


def _close_detached_run(
    exit_code: Optional[int],
    error: Optional[str],
    result_state: Optional[str] = None,
) -> None:
    """Write the terminal ``run`` record when this process owns a detached run.

    *result_state* is the result context's state; ``detach`` records it as
    ``run.result_state`` only when the exit code cannot express it
    (``partial``), so a ``status`` poll can restate it.
    """
    detach = sys.modules.get("utils.detach")
    if detach is None:
        return  # nothing detached ran; do not pay the import
    try:
        detach.finish_active_run(exit_code, error=error, result_state=result_state)
    except Exception:  # pragma: no cover - close-out must never mask the result
        traceback.print_exc()


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 321kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 321kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 321kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 321kUpdated Claude CodeCodexVerifiedInstall