#!/usr/bin/env bash
# 𝚅𝚒𝚋𝚎𝚌𝚛𝚊𝚏𝚝𝚎𝚍. command deck
set -euo pipefail
# shellcheck disable=SC2034  # marker the installer and staged-tools tests read from this file
readonly VIBECRAFTED_SERVICE_LIFECYCLE_LOCK_CONTRACT=1

_vc_source_launcher_ulimits() {
  local owner_root candidate
  owner_root="$(_script_owner_root)" || return $?
  candidate="$owner_root/vibecrafted-core/vibecrafted_core/runtime/scripts/lib/ulimits.sh"
  # A wheel's deck is directly under the installed package, without the
  # source carrier's vibecrafted-core directory. Select only this deck's own
  # sibling resource, never an inherited or unrelated runtime root.
  if [[ "${BASH_SOURCE[0]}" -ef "$owner_root/deck/vibecrafted" ]]; then
    candidate="$owner_root/runtime/scripts/lib/ulimits.sh"
  fi
  if [[ ! -f "$candidate" || ! -r "$candidate" || -L "$candidate" ]]; then
    printf 'vibecrafted: selected launcher limit helper missing: %s\n' "$candidate" >&2
    return 1
  fi
  source "$candidate" || return $?
  vc_raise_launcher_limits
}

_expand_home_path() {
  local raw="${1:-}"
  case "$raw" in
    [~]) printf '%s\n' "$HOME/" ;;
    [~]/*) printf '%s/%s\n' "$HOME/" "${raw:2}" ;;
    *) printf '%s\n' "$raw" ;;
  esac
}

crafted_home="$(_expand_home_path "${VIBECRAFTED_HOME:-$HOME/.vibecrafted}")"
if [[ -n "${VIBECRAFTED_RUNTIME_HOME:-}" ]]; then
  crafted_runtime_home="$(_expand_home_path "$VIBECRAFTED_RUNTIME_HOME")"
elif [[ -n "${XDG_DATA_HOME:-}" ]]; then
  crafted_runtime_home="$(_expand_home_path "$XDG_DATA_HOME/vibecrafted")"
else
  crafted_runtime_home="$HOME/.local/share/vibecrafted"
fi
crafted_skills="$crafted_home/skills"
crafted_tools="$(_expand_home_path "${VIBECRAFTED_TOOLS_HOME:-$crafted_runtime_home/tools}")/vibecrafted-current"

# The installer stages npm-provided agent CLIs under $crafted_home/tools/node/bin
# and reports them as installed — but that directory never reaches the user's
# PATH, so a fresh install answered `vibecrafted init claude` with exit 1 and
# zero output. Teach the deck where its own installer puts them. Appended, never
# prepended: an operator's own agent install keeps winning.
crafted_agent_bin="$crafted_home/tools/node/bin"
if [[ -d "$crafted_agent_bin" ]]; then
  case ":${PATH:-}:" in
    *":$crafted_agent_bin:"*) ;;
    *) export PATH="${PATH:+$PATH:}$crafted_agent_bin" ;;
  esac
fi

# Darwin caps an AF_UNIX sun_path at ~104 bytes, and the per-user $TMPDIR macOS
# hands out (/var/folders/../T/) already eats ~81 of them. vc-frame derives its
# session socket from that directory, so any session name longer than a couple
# of characters computed a negative budget and the session simply refused to
# start. Bind one short, private, per-uid socket directory here — the deck is the
# single door every vc-frame surface walks through, so this stays one canon
# instead of three. An explicit operator override always wins.
if [[ -z "${VC_FRAME_SOCKET_DIR:-}" ]]; then
  vc_frame_socket_dir="/tmp/vc-frame-$(id -u)"
  # /tmp is world-writable, so refuse a squatted symlink or a directory we do not
  # own rather than handing vc-frame a hostile socket home. Staying silent on
  # failure is deliberate: vc-frame then keeps its own default.
  if [[ ! -L "$vc_frame_socket_dir" ]] \
    && mkdir -p "$vc_frame_socket_dir" 2>/dev/null \
    && [[ -O "$vc_frame_socket_dir" && -d "$vc_frame_socket_dir" ]] \
    && chmod 700 "$vc_frame_socket_dir" 2>/dev/null; then
    export VC_FRAME_SOCKET_DIR="$vc_frame_socket_dir"
  fi
  unset vc_frame_socket_dir
fi

_bold='\033[1m'
_dim='\033[2m'
_copper='\033[38;5;173m'
_steel='\033[38;5;247m'
_green='\033[32m'
_yellow='\033[33m'
_cyan='\033[36m'
_red='\033[31m'
_reset='\033[0m'

_agents=(claude codex agy junie grok cursor kimi copilot omp)
_skills=(audit canary decorate delegate dou followup guard hydrate implement intents justdo marbles ownership partner polarize prune release research review scaffold trust workflow)

_script_repo_root() {
  local script_dir
  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  cd "$script_dir/.." && pwd
}

_script_owner_root() {
  local script_path="${BASH_SOURCE[0]}" script_dir link_target
  while [[ -L "$script_path" ]]; do
    script_dir="$(cd -P "$(dirname "$script_path")" && pwd -P)" || return $?
    link_target="$(readlink "$script_path")" || return $?
    if [[ "$link_target" == /* ]]; then
      script_path="$link_target"
    else
      script_path="$script_dir/$link_target"
    fi
  done
  script_dir="$(cd -P "$(dirname "$script_path")" && pwd -P)" || return $?
  # The tracked package deck and published bin deck share this physical owner.
  case "$script_dir" in
    */vibecrafted-core/vibecrafted_core/deck)
      cd -P "$script_dir/../../.." && pwd -P ;;
    *) cd -P "$script_dir/.." && pwd -P ;;
  esac
}

_vc_source_launcher_ulimits || exit $?
unset -f _vc_source_launcher_ulimits

_runtime_payload_root() {
  local candidate
  candidate="$(_script_owner_root)" || return 1
  if _is_installed_generation_root "$candidate"; then
    printf '%s\n' "$candidate"
    return 0
  fi
  # An exact checkout invocation selects source, even inside an older runtime.
  # Runtime roots describe inherited context; they are not a deck selector.
  _is_framework_source_root "$candidate" && return 1
  if [[ -x "$candidate/bin/vc-server" && -d "$candidate/server/site" ]]; then
    printf '%s\n' "$candidate"
    return 0
  fi
  return 1
}

_package_resource_root() {
  local script_root candidate
  script_root="$(_script_repo_root)"
  for candidate in \
    "$script_root" \
    "$script_root/vibecrafted-core/vibecrafted_core"; do
    [[ -d "$candidate/runtime" && -d "$candidate/skills" ]] || continue
    printf '%s\n' "$candidate"
    return 0
  done
  return 1
}

_prepend_repo_bin_path() {
  local repo_source bin_dir
  repo_source="$(_repo_source_root 2>/dev/null || _script_repo_root)"
  bin_dir="$repo_source/bin"
  [[ -d "$bin_dir" ]] || return 0
  case ":${PATH:-}:" in
    *":$bin_dir:"*) ;;
    *) export PATH="$bin_dir${PATH:+:$PATH}" ;;
  esac
}

_is_framework_source_root() {
  local candidate="${1:-}"
  [[ -n "$candidate" && -f "$candidate/VERSION" && -f "$candidate/scripts/vibecrafted" ]] || return 1
  [[ -d "$candidate/skills" || -d "$candidate/vibecrafted-core/vibecrafted_core/skills" ]] || return 1
  [[ -d "$candidate/runtime" || -d "$candidate/vibecrafted-core/vibecrafted_core/runtime" ]]
}

# A physically installed generation, told apart from a development checkout by
# the receipt the installer writes and a checkout never carries. The shell layer
# already draws this exact boundary (_vetcoders_vc_frame_developer_mode); the
# deck needs it one step earlier -- BEFORE it chooses which helper tree to load.
_is_installed_generation_root() {
  local candidate="${1:-}"
  [[ -n "$candidate" ]] || return 1
  [[ -f "$candidate/runtime-manifest.json" && ! -L "$candidate/runtime-manifest.json" ]] || return 1
  [[ ! -e "$candidate/.git" ]]
}

_repo_source_root() {
  local repo_root script_root
  repo_root="$(_repo_root)"
  if _is_framework_source_root "$repo_root"; then
    printf '%s\n' "$repo_root"
    return 0
  fi

  script_root="$(_script_repo_root)"
  if _is_framework_source_root "$script_root" && [[ "$script_root" != "$crafted_tools" ]]; then
    printf '%s\n' "$script_root"
    return 0
  fi

  return 1
}

_version() {
  local source_root repo_root vf
  repo_root="$(_script_owner_root)"
  source_root="$(_repo_source_root 2>/dev/null || true)"

  for vf in \
    "$repo_root/VERSION" \
    "${source_root:+$source_root/VERSION}" \
    "$crafted_home/VERSION" \
    "$crafted_tools/VERSION"; do
    [[ -f "$vf" ]] || continue
    cat "$vf"
    return 0
  done

  echo "?"
}

_repo_root() {
  git rev-parse --show-toplevel 2>/dev/null || pwd
}

_realpath_quiet() {
  local target="${1:-}"
  [[ -n "$target" ]] || return 1
  # Physical path resolution is product-internal: it runs on the interpreter
  # this generation owns, isolated from PYTHON* env, never on a PATH python3.
  "$(_vibecrafted_python)" -I - "$target" <<'PY'
import os
import sys

target = sys.argv[1]
if not target:
    raise SystemExit(1)
print(os.path.realpath(target))
PY
}

_has_agent() {
  local candidate="${1:-}"
  case "$candidate" in
    claude|codex|agy|junie|grok|cursor|kimi|copilot|omp) return 0 ;;
    gemini) return 1 ;;  # deprecated - see migration error below
    *) return 1 ;;
  esac
}

# Fleet agent key → installed CLI binary when they differ (mirrors
# spawn.AGENT_BINARY_NAMES: key stays the UX name, binary is cursor-agent).
_agent_cli_binary() {
  local cli="${1:-}"
  case "${1:-}" in
    cursor) cli="cursor-agent" ;;
  esac
  printf '%s' "$cli"
}

# A missing agent CLI is the stranger's first-use cliff: `init` used to answer
# a bare `return 1` — exit 1, zero bytes, nothing to act on. Name the gap and
# hand over the one command that closes it.
_require_agent_cli() {
  local agent="${1:-}"
  local binary
  binary="$(_agent_cli_binary "$agent")"
  command -v "$binary" >/dev/null 2>&1 && return 0
  local staged="$crafted_agent_bin/$binary"
  if [[ "$binary" == "$agent" ]]; then
    printf '%b✗%b %s CLI is not available.\n' "$_red" "$_reset" "$agent" >&2
  else
    printf '%b✗%b %s CLI (%s) is not available.\n' "$_red" "$_reset" "$agent" "$binary" >&2
  fi
  if [[ -e "$staged" ]]; then
    printf '  Found at %s but it is not executable from here.\n' "$staged" >&2
    printf '  Fix: chmod +x %s\n' "$staged" >&2
  else
    printf '  Install it, then re-run this command:\n' >&2
    case "$agent" in
      claude) printf '    npm install -g @anthropic-ai/claude-code\n' >&2 ;;
      codex) printf '    npm install -g @openai/codex\n' >&2 ;;
      junie) printf '    npm install -g @jetbrains/junie\n' >&2 ;;
      grok) printf '    npm install -g @xai-official/grok\n' >&2 ;;
      agy) printf '    install Google Antigravity CLI, then: agy install\n' >&2 ;;
      cursor) printf '    curl https://cursor.com/install -fsS | bash\n' >&2 ;;
      kimi) printf '    curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash\n' >&2 ;;
      copilot) printf '    npm install -g @github/copilot\n' >&2 ;;
      omp) printf '    curl -fsSL https://omp.sh/install | sh\n' >&2 ;;
    esac
    printf '  Or check the whole fleet: vibecrafted doctor\n' >&2
  fi
  return 1
}

_has_skill() {
  local candidate="${1:-}"
  local skill
  for skill in "${_skills[@]}"; do
    [[ "$candidate" == "$skill" ]] && return 0
  done
  return 1
}

_is_marbles_control_subcommand() {
  local candidate="${1:-}"
  case "$candidate" in
    pause|stop|resume|session|inspect|delete) return 0 ;;
    *) return 1 ;;
  esac
}

_helper_candidates() {
  local repo_source repo_helper package_root
  repo_source="$(_repo_source_root 2>/dev/null || true)"
  package_root="$(_package_resource_root 2>/dev/null || true)"
  repo_helper="$(_script_repo_root)/vibecrafted-core/vibecrafted_core/runtime/shell/vetcoders.sh"
  if [[ -n "$repo_source" ]]; then
    printf '%s\n' "$repo_source/runtime/shell/vetcoders.sh"
    printf '%s\n' "$repo_source/vibecrafted-core/vibecrafted_core/runtime/shell/vetcoders.sh"
  fi
  if [[ -n "$package_root" ]]; then
    printf '%s\n' "$package_root/runtime/shell/vetcoders.sh"
  fi
  # Prefer the staged control plane over the mutable shared skill store so a
  # freshly updated launcher cannot be shadowed by older installed helpers.
  printf '%s\n' \
    "$crafted_tools/vibecrafted-core/vibecrafted_core/runtime/shell/vetcoders.sh" \
    "$crafted_skills/runtime/shell/vetcoders.sh" \
    "$repo_helper"
}

_ensure_helpers_loaded() {
  local helper owner_kind="" owner_root="${1:-}"
  if [[ -z "$owner_root" ]]; then
    # An installed public entry owns its helper tree by where it PHYSICALLY is,
    # never by where it was run from. Without this, `vibecrafted resume` started
    # inside a framework checkout resolved _repo_source_root from cwd, sourced
    # that checkout's helpers, and the front-door lookup then asked the checkout
    # for bin/vibecrafted -- absent -- so the public resume died with "no
    # installed vibecrafted front door" while `start`, which passes the owner
    # explicitly, opened a terminal from the very same directory.
    #
    # The receipt lying beside the script is the authority, not the caller's
    # environment: VIBECRAFTED_ROOT and friends are inherited from whoever
    # invoked us and cannot be allowed to select a different generation.
    local physical_owner=""
    physical_owner="$(_script_owner_root 2>/dev/null || true)"
    if _is_installed_generation_root "$physical_owner"; then
      owner_root="$physical_owner"
      owner_kind="runtime"
    elif _is_framework_source_root "$physical_owner"; then
      owner_root="$physical_owner"
      owner_kind="source"
    fi
  elif _is_installed_generation_root "$owner_root"; then
    owner_kind="runtime"
  elif _is_framework_source_root "$owner_root"; then
    owner_kind="source"
  fi
  if [[ -n "$owner_root" ]]; then
    # A product entry runs on the physical deck owner, not the current checkout
    # or an inherited tools-current. Do not fall through on a partial install:
    # a selected generation missing its own helper is a broken install, and
    # borrowing another tree's helpers would hide that behind a working window.
    helper="$owner_root/vibecrafted-core/vibecrafted_core/runtime/shell/vetcoders.sh"
    if [[ ! -r "$helper" ]]; then
      printf 'vibecrafted: selected runtime shell missing: %s\n' "$helper" >&2
      printf 'Install explicitly: python3 <checkout>/scripts/vetcoders_install.py runtime-install --payload-root <Runtime-Pack>\n' >&2
      printf 'If historical rollback bytes are missing: python3 <checkout>/scripts/vetcoders_install.py runtime-install --payload-root <Runtime-Pack> --rescue --plan\n' >&2
      return 1
    fi
    export VIBECRAFTED_ROOT="$owner_root"
    export VIBECRAFTED_CORE_DIR="$owner_root/vibecrafted-core"
    if [[ "$owner_kind" == "runtime" ]]; then
      export VIBECRAFTED_RUNTIME_ROOT="$owner_root"
      export VIBECRAFTED_RUNTIME_BIN="$owner_root/bin"
      unset VIBECRAFTED_PREFER_REPO_SPAWN
    else
      # A checkout or source carrier owns code, not an immutable Runtime Pack.
      # Never let its mutable root enter the runtime-generation resolver, and
      # discard stale generation pointers inherited from the caller.
      unset VIBECRAFTED_RUNTIME_ROOT VIBECRAFTED_RUNTIME_BIN VIBECRAFTED_RUNTIME_HOME
      export VIBECRAFTED_PREFER_REPO_SPAWN=1
    fi
    source "$helper" || return $?
    return 0
  fi
  local repo_source=""
  repo_source="$(_repo_source_root 2>/dev/null || true)"
  if [[ -n "$repo_source" ]]; then
    export VIBECRAFTED_PREFER_REPO_SPAWN=1
    [[ -n "${VIBECRAFTED_ROOT:-}" ]] || export VIBECRAFTED_ROOT="$repo_source"
  else
    unset VIBECRAFTED_PREFER_REPO_SPAWN
  fi
  while IFS= read -r helper; do
    [[ -r "$helper" ]] || continue
    source "$helper" || return $?
    return 0
  done < <(_helper_candidates)
  printf '%b✗%b Could not find the 𝚅𝚒𝚋𝚎𝚌𝚛𝚊𝚏𝚝𝚎𝚍. helper layer.\n' "$_red" "$_reset" >&2
  printf '  Expected one of:\n' >&2
  _helper_candidates | sed 's/^/    - /' >&2
  return 1
}

_run_helper() {
  local helper="$1"
  shift
  local helper_type resolved helper_real self_real self_path
  helper_type="$(type -t "$helper" 2>/dev/null || true)"
  if [[ "$helper_type" == "function" || "$helper_type" == "builtin" || "$helper_type" == "keyword" || "$helper_type" == "alias" ]]; then
    "$helper" "$@"
    return 0
  fi

  resolved="$(type -P "$helper" 2>/dev/null || true)"
  if [[ -n "$resolved" ]]; then
    self_path="${BASH_SOURCE[0]:-$0}"
    helper_real="$(_realpath_quiet "$resolved" 2>/dev/null || true)"
    self_real="$(_realpath_quiet "$self_path" 2>/dev/null || true)"
    if [[ -n "$helper_real" && -n "$self_real" && "$helper_real" == "$self_real" ]]; then
      printf '%b✗%b Helper %s resolved back to vibecrafted itself.\n' "$_red" "$_reset" "$helper" >&2
      printf '  Add the missing function definition to vetcoders.sh instead of relying on PATH fallback.\n' >&2
      return 1
    fi
    "$resolved" "$@"
    return 0
  fi

  printf '%b✗%b Missing helper %s.\n' "$_red" "$_reset" "$helper" >&2
  if [[ ! -t 0 || ! -t 1 ]]; then
    printf '  Non-interactive shells should use the standalone bin/vc-* wrappers.\n' >&2
    printf '  Add this repo bin directory to PATH or run scripts/install-foundations.sh:\n' >&2
    local path_literal="\$PATH"
    printf '    export PATH="%s/bin:%s"\n' "$(_repo_source_root 2>/dev/null || _script_repo_root)" "$path_literal" >&2
  fi
  return 1
}

_installer_gui_script() {
  local repo_source candidate
  repo_source="$(_repo_source_root 2>/dev/null || true)"
  for candidate in \
    "${repo_source:+$repo_source/scripts/installer_gui.py}" \
    "$crafted_tools/scripts/installer_gui.py" \
    "$(_script_repo_root)/scripts/installer_gui.py"; do
    [[ -f "$candidate" ]] || continue
    printf '%s\n' "$candidate"
    return 0
  done
  return 1
}

_loop_script() {
  local repo_source package_root candidate
  repo_source="$(_repo_source_root 2>/dev/null || true)"
  package_root="$(_package_resource_root 2>/dev/null || true)"
  for candidate in \
    "${repo_source:+$repo_source/runtime/scripts/vibecrafted-loop.sh}" \
    "${repo_source:+$repo_source/vibecrafted-core/vibecrafted_core/runtime/scripts/vibecrafted-loop.sh}" \
    "${package_root:+$package_root/runtime/scripts/vibecrafted-loop.sh}" \
    "$crafted_tools/vibecrafted-core/vibecrafted_core/runtime/scripts/vibecrafted-loop.sh" \
    "$(_script_repo_root)/vibecrafted-core/vibecrafted_core/runtime/scripts/vibecrafted-loop.sh"; do
    [[ -n "$candidate" && -f "$candidate" ]] || continue
    printf '%s\n' "$candidate"
    return 0
  done
  return 1
}

_cron_script() {
  local repo_source package_root candidate
  repo_source="$(_repo_source_root 2>/dev/null || true)"
  package_root="$(_package_resource_root 2>/dev/null || true)"
  for candidate in \
    "${repo_source:+$repo_source/runtime/scripts/vibecrafted-cron.sh}" \
    "${repo_source:+$repo_source/vibecrafted-core/vibecrafted_core/runtime/scripts/vibecrafted-cron.sh}" \
    "${package_root:+$package_root/runtime/scripts/vibecrafted-cron.sh}" \
    "$crafted_tools/vibecrafted-core/vibecrafted_core/runtime/scripts/vibecrafted-cron.sh" \
    "$(_script_repo_root)/vibecrafted-core/vibecrafted_core/runtime/scripts/vibecrafted-cron.sh"; do
    [[ -n "$candidate" && -f "$candidate" ]] || continue
    printf '%s\n' "$candidate"
    return 0
  done
  return 1
}

# `scripts/vibecrafted_housekeeping.py` ships under the top-level `scripts/`
# tree (distribution_manifest.py carries it into every installed generation
# alongside vetcoders_install.py), so this mirrors _dispatcher_core_dir's
# installed-root-first resolution rather than _cron_script's
# runtime/scripts-bundled-in-package pattern.
_housekeeping_script_path() {
  local owner_root candidate repo_source
  owner_root="$(_script_owner_root 2>/dev/null || true)"
  if [[ -n "$owner_root" ]] \
    && { _is_installed_generation_root "$owner_root" || _is_framework_source_root "$owner_root"; }; then
    candidate="$owner_root/scripts/vibecrafted_housekeeping.py"
    if [[ -f "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
  fi
  repo_source="$(_repo_source_root 2>/dev/null || true)"
  for candidate in \
    "${repo_source:+$repo_source/scripts/vibecrafted_housekeeping.py}" \
    "$crafted_tools/scripts/vibecrafted_housekeeping.py" \
    "$(_script_repo_root)/scripts/vibecrafted_housekeeping.py"; do
    [[ -n "$candidate" && -f "$candidate" ]] || continue
    printf '%s\n' "$candidate"
    return 0
  done
  return 1
}

_core_module_dir() {
  _dispatcher_core_dir
}

_dispatcher_core_dir() {
  local repo_source candidate owner_root
  owner_root="$(_script_owner_root)" || return 1
  if _is_installed_generation_root "$owner_root" || _is_framework_source_root "$owner_root"; then
    candidate="$owner_root/vibecrafted-core"
    if [[ ! -f "$candidate/vibecrafted_core/dispatcher.py" ]]; then
      printf 'vibecrafted: selected launcher core missing: %s\n' "$candidate" >&2
      return 1
    fi
    printf '%s\n' "$candidate"
    return 0
  fi
  repo_source="$(_repo_source_root 2>/dev/null || true)"
  for candidate in \
    "${repo_source:+$repo_source/vibecrafted-core}" \
    "${repo_source:+$repo_source/vibecrafted-core/vibecrafted_core/..}" \
    "$crafted_tools/vibecrafted-core" \
    "$(_script_repo_root)/vibecrafted-core" \
    "$(_script_repo_root)/.."; do
    [[ -n "$candidate" && -f "$candidate/vibecrafted_core/dispatcher.py" ]] || continue
    printf '%s\n' "$candidate"
    return 0
  done
  return 1
}

# An installed deck may inherit VIBECRAFTED_PYTHON from a different product
# generation. Accept it only when it belongs to this deck's current generation;
# checkout decks keep the explicit development override.
_vibecrafted_python_owned_by_current() {
  local candidate="$1" candidate_real current_real deck_real
  local physical_owner candidate_owner
  physical_owner="$(_script_owner_root)" || return 1
  candidate_owner="$(cd -P "$(dirname "$candidate")/.." 2>/dev/null && pwd -P)" || return 1
  if _is_framework_source_root "$physical_owner" && _is_installed_generation_root "$candidate_owner"; then
    return 1
  fi
  [[ -d "$crafted_tools" ]] || return 0
  current_real="$(cd "$crafted_tools" 2>/dev/null && pwd -P)" || return 1
  deck_real="$(readlink -f "${BASH_SOURCE[0]}" 2>/dev/null)" || return 0
  deck_real="$(cd "$(dirname "$deck_real")" 2>/dev/null && pwd -P)" || return 0
  [[ "$deck_real" == "$current_real" || "$deck_real" == "$current_real/"* ]] || return 0
  candidate_real="$(cd "$(dirname "$candidate")" 2>/dev/null && pwd -P)/$(basename "$candidate")" || return 1
  [[ "$candidate_real" == "$current_real/"* ]]
}

# Resolve the interpreter this generation owns, with no host fallback. A
# Runtime Pack's own interpreter wins; a source generation falls through to an
# owned override or the uv-tool shim shebang on PATH. Returns 1 when nothing
# owned exists, so each caller decides whether a host python3 is acceptable.
_vibecrafted_owned_python() {
  local resolved shebang py runtime_root
  runtime_root="$(_runtime_payload_root 2>/dev/null || true)"
  if [[ -n "$runtime_root" ]]; then
    if [[ -x "$runtime_root/bin/python3" ]]; then
      printf '%s\n' "$runtime_root/bin/python3"
      return 0
    fi
    # Warn, but keep resolving: a source checkout still owns its .venv even
    # when the selected runtime home has no interpreter (isolated test homes,
    # partial runtimes). Hard-returning here used to strand source checkouts
    # on a host python3 that can be older than vibecrafted_core requires.
    printf 'vibecrafted: selected runtime Python missing: %s/bin/python3\n' "$runtime_root" >&2
  fi
  if [[ -n "${VIBECRAFTED_PYTHON:-}" && -x "$VIBECRAFTED_PYTHON" ]] \
    && _vibecrafted_python_owned_by_current "$VIBECRAFTED_PYTHON"; then
    printf '%s\n' "$VIBECRAFTED_PYTHON"
    return 0
  fi
  if _is_framework_source_root "$(_script_owner_root)"; then
    # The development venv moved from vibecrafted-core/.venv to the checkout
    # root; own whichever layout this checkout actually carries.
    for py in \
      "$(_script_owner_root)/vibecrafted-core/.venv/bin/python" \
      "$(_script_owner_root)/.venv/bin/python"; do
      if [[ -x "$py" ]]; then
        printf '%s\n' "$py"
        return 0
      fi
    done
    return 1
  fi
  for resolved in \
    "$(command -v vc-server-supervisor 2>/dev/null || true)" \
    "$(command -v vibecrafted 2>/dev/null || true)"; do
    [[ -n "$resolved" && -f "$resolved" ]] || continue
    shebang="$(head -n 1 "$resolved" 2>/dev/null || true)"
    if [[ "$shebang" =~ ^#\! ]]; then
      py="${shebang#\#!}"
      # Strip leading/trailing whitespace
      py="${py#"${py%%[![:space:]]*}"}"
      py="${py%"${py##*[![:space:]]}"}"
      # A direct absolute path is not sufficient: installed product launchers
      # may be Bash wrappers. Accept only Python-shaped interpreter names so a
      # `#!/bin/bash` supervisor can never become `/bin/bash -m ...`.
      if [[ "$py" == /* && "$py" != *[[:space:]]* && -x "$py" ]]; then
        case "${py##*/}" in
          python|python[0-9]*|pypy|pypy[0-9]*)
            printf '%s\n' "$py"
            return 0
            ;;
        esac
      fi
    fi
  done
  return 1
}

# Resolve the interpreter that owns vibecrafted_core, accepting a host python
# as the last resort for development checkouts and best-effort tooling. Server
# control never takes that fallback: see _server_helper_python.
_vibecrafted_python() {
  _vibecrafted_owned_python && return 0
  # A partial physical runtime must never borrow the host interpreter.
  _is_installed_generation_root "$(_script_owner_root)" && return 1
  # vibecrafted_core.cli requires >=3.11 (tomllib); a bare `python3` on a
  # login PATH can be a stub too old to import the core. Prefer versioned
  # interpreters, mirroring _telemetry_python's order.
  local candidate
  for candidate in python3.13 python3.12 python3.11 python3 python; do
    command -v "$candidate" 2>/dev/null && return 0
  done
  printf 'python3\n'
}

_run_core_help() {
  local core_dir python_bin
  core_dir="$(_core_module_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || return 1
  python_bin="$(_vibecrafted_python)"
  VIBECRAFTED_HELP_VERSION="$(_version)" \
    PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
    "$python_bin" -m vibecrafted_core.cli help "$@"
}

_sync_control_plane_best_effort() {
  local core_dir
  core_dir="$(_core_module_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || return 0
  PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
    "$(_vibecrafted_python)" -m vibecrafted_core.control_plane sync >/dev/null 2>&1 || true
}

_voc_app_dir() {
  local repo_source candidate
  repo_source="$(_repo_source_root 2>/dev/null || true)"
  for candidate in \
    "${repo_source:+$repo_source/vibecrafted-app}" \
    "$crafted_tools/vibecrafted-app" \
    "$(_script_repo_root)/vibecrafted-app"; do
    [[ -f "$candidate/Cargo.toml" ]] || continue
    [[ -f "$candidate/tui-agent/Cargo.toml" ]] || continue
    printf '%s\n' "$candidate"
    return 0
  done
  return 1
}

_resolve_voc_binary() {
  # A declared Runtime Pack owns VOC.  Do not let an old host install or a
  # source build mask a generation that failed to carry its promised binary.
  local app_dir candidate runtime_root
  runtime_root="$(_runtime_payload_root 2>/dev/null || true)"
  if [[ -n "$runtime_root" ]]; then
    candidate="$runtime_root/bin/voc"
    if [[ -x "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
    return 1
  fi
  app_dir="$(_voc_app_dir 2>/dev/null || true)"
  if [[ -n "$app_dir" ]]; then
    for candidate in \
      "$app_dir/target/release/voc" \
      "$app_dir/target/debug/voc" \
      "$app_dir/tui-agent/target/release/voc" \
      "$app_dir/tui-agent/target/debug/voc"; do
      if [[ -x "$candidate" ]]; then
        printf '%s\n' "$candidate"
        return 0
      fi
    done
  fi
  # Development has no declared product generation, so keep the explicit
  # developer/host path for source workflows without taking over other tools.
  for candidate in \
    "${VIBECRAFTED_LAUNCHER_BIN:-$HOME/.local/bin}/voc" \
    "$HOME/.local/bin/voc"; do
    if [[ -n "$candidate" && -x "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
  done
  if candidate="$(command -v voc 2>/dev/null)" && [[ -n "$candidate" && -x "$candidate" ]]; then
    printf '%s\n' "$candidate"
    return 0
  fi
  # Compat: pre-rename operator binary / package names.
  local name found
  for name in vc-operator vibecrafted-operator; do
    found="$(command -v "$name" 2>/dev/null || true)"
    if [[ -n "$found" && -x "$found" ]]; then
      printf '%s\n' "$found"
      return 0
    fi
  done
  return 1
}

_is_help_flag() {
  local candidate="${1:-}"
  [[ "$candidate" == "--help" || "$candidate" == "-h" || "$candidate" == "help" ]]
}

_skill_summary() {
  case "$1" in
    audit) printf 'READ-ONLY falsification of a completed plan or multi-task implementation.\n' ;;
    canary) printf 'Ownership catalog: Loctree scopes, docstring cuts, one supervisor commit.\n' ;;
    decorate) printf 'Visual finishing and UX coherence pass.\n' ;;
    delegate) printf 'Native in-session subagent delegation.\n' ;;
    dou) printf 'Definition of Undone audit across the product surface.\n' ;;
    followup) printf 'Post-implementation direction audit for gaps, drift, regressions, and next leverage.\n' ;;
    guard) printf 'In-flight enforcer: inventory gates and refuse continuation on trust block.\n' ;;
    hydrate) printf 'Packaging and go-to-market hydration.\n' ;;
    implement) printf 'Ship WRITE stage: autonomous end-to-end implementation with followup and marbles built in.\n' ;;
    intents) printf 'Plan-to-runtime truth audit across prior intent and present repo state.\n' ;;
    justdo) printf 'Standalone Just Do posture: take the task (type from prompt); not an implement alias.\n' ;;
    marbles) printf 'Counterexample loop that keeps fixing what is still wrong until the surface is clean.\n' ;;
    ownership) printf 'Full-spectrum operational ownership across code, runtime, docs, packaging, and ship surface.\n' ;;
    partner) printf 'Collaborative debugging, architecture triage, and shared executive reasoning with the user in the loop.\n' ;;
    polarize) printf 'Post-marbles concept and product truth polarization skill.\n' ;;
    prune) printf 'Runtime and publish-cone cleanup with hard cuts and proof.\n' ;;
    release) printf 'Release mechanics, deployment reality, and ship-readiness work.\n' ;;
    research) printf 'Multi-agent research pass for ground truth before implementation.\n' ;;
    review) printf 'Bounded PR, branch, commit-range, or artifact-pack review with findings-first output.\n' ;;
    scaffold) printf 'Founder-first architecture planning from a vague idea.\n' ;;
    trust) printf 'READ-only post-hoc falsification of commit claims on the Living Tree.\n' ;;
    workflow) printf 'Examine -> Research -> Implement pipeline.\n' ;;
    *) printf 'Framework skill.\n' ;;
  esac
}

_skill_version() {
  case "$1" in
    audit) printf '1.0.0\n' ;;
    followup) printf '2.2.0\n' ;;
    review) printf '2.0.0\n' ;;
    *) return 1 ;;
  esac
}

_print_common_skill_flags() {
  printf '%bCommon flags:%b\n' "$_bold" "$_reset"
  printf '  -p, --prompt <text>            Inline prompt\n'
  printf '  -f, --file <path.md>           Input file as prompt context\n'
  printf '  --session <id|current|last>    Continue this provider-native session (never a work-* run id)\n'
}

_print_skill_specific_flags() {
  case "$1" in
    marbles)
      printf '\n%bSkill-specific flags:%b\n' "$_bold" "$_reset"
      printf '  --count <n>                    Marbles loop count (default: 3)\n'
      printf '  --depth <n>                    Marbles plan crawl depth (default: 3)\n'
      ;;
    polarize)
      printf '\n%bSkill-specific flags:%b\n' "$_bold" "$_reset"
      printf '  --count <n>                    Polarize loop count; same loop runtime as marbles\n'
      printf '  --task <text>                  Run loct prism preflight and inject the payload\n'
      printf '  --no-aicx                      Opt out of AICX evidence for the prism preflight\n'
      ;;
    resume)
      printf '\n%bResume flags:%b\n' "$_bold" "$_reset"
      printf '  --run-id <work-...>            Continue a stopped/failed control-plane run\n'
      printf '  --session <id|current|last>     Provider session selector (never a control-plane run ID)\n'
      printf '  --repo <path>                  Repository, usable from any directory (--root: legacy spelling)\n'
      printf '  -p, --prompt <text>            Continue with extra prompt text\n'
      printf '  -f, --file <path.md>           Continue with prompt context from file\n'
      printf '  fork <agent> --session <id>    Use the native fork command for a new child session\n'
      printf '  (no --session/--run-id)        AICX 48h multi-agent continuity fallback\n'
      ;;
  esac
}

_print_ship_path() {
  printf '  %bvc-ship codex --prompt "Run the full lifecycle"%b\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted dou claude --prompt "Audit launch readiness"%b\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted decorate codex --prompt "Polish the release surface"%b\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted hydrate codex --prompt "Package the product"%b\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted release codex --prompt "Prepare release steps"%b\n' "$_cyan" "$_reset"
}

cmd_skill_help() {
  local skill="$1"
  local agent="${2:-<claude|codex|agy|junie|grok|cursor|kimi|copilot|omp>}"
  local wrapper="vc-$skill"
  local display_skill="$skill"
  local version=""

  # Core owns the public workflow contract.  Keep the embedded renderer below
  # as a bootstrap fallback for a checkout/package missing vibecrafted_core.
  if _run_core_help "$skill"; then
    return 0
  fi

  if [[ "$skill" == "research" ]]; then
    agent=""
  fi
  if [[ "$skill" == "justdo" ]]; then
    display_skill="implement"
    wrapper="vc-implement"
  fi

  printf '\n'
  printf '%b⚒%b  %b%s%b\n' "$_copper" "$_reset" "$_bold" "$display_skill" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  version="$(_skill_version "$skill" 2>/dev/null || true)"
  if [[ -n "$version" ]]; then
    printf '  version %s\n' "$version"
  fi
  printf '  %s' "$(_skill_summary "$skill")"
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  if [[ -n "$agent" ]]; then
    printf '  vibecrafted %s %s [flags]\n' "$display_skill" "$agent"
    printf '  %s %s [flags]\n' "$wrapper" "$agent"
  else
    printf '  vibecrafted %s [flags]\n' "$display_skill"
    printf '  %s [flags]\n' "$wrapper"
  fi
  if [[ "$skill" == "marbles" ]]; then
    printf '  vibecrafted marbles <pause|stop|resume|session|inspect|delete> [args]\n'
    printf '  vc-marbles <pause|stop|resume|session|inspect|delete> [args]\n'
  fi
  if [[ "$skill" == "justdo" ]]; then
    printf '  Alias: vibecrafted justdo %s [flags] / vc-justdo %s [flags]\n' "$agent" "$agent"
  fi
  if [[ "$skill" == "implement" ]]; then
    printf '  Alias: vibecrafted justdo %s [flags] / vc-justdo %s [flags]\n' "$agent" "$agent"
  fi
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  case "$skill" in
    audit)
      printf '  vibecrafted audit codex --prompt "Verify this completed plan against runtime truth"\n'
      printf '  vc-audit claude --file /path/to/completed-plan.md\n'
      ;;
    implement)
      printf '  vibecrafted implement codex --prompt "Ship the feature"\n'
      printf '  vc-implement claude --file /path/to/brief.md\n'
      ;;
    justdo)
      printf '  vibecrafted justdo codex --prompt "Review the last five commits for X"\n'
      printf '  vc-justdo claude --file /path/to/brief.md\n'
      printf '  # not implement — own skill id, posture from prompt (ADR-0001)\n'
      ;;
    marbles)
      printf '  vibecrafted marbles codex --count 3 --depth 3\n'
      printf '  vc-marbles claude --prompt "Loop until clean"\n'
      printf '  vc-marbles resume marb-134707\n'
      ;;
    polarize)
      printf '  vibecrafted polarize codex --task "marbles versus polarize skills: polarize them"\n'
      printf '  vc-polarize claude --task "installer public contract" --no-aicx\n'
      printf '  vc-polarize agy --prompt "Choose one launch thesis after marbles"\n'
      ;;
    followup)
      printf '  vibecrafted followup codex --prompt "Audit post-implementation direction"\n'
      printf '  vc-followup claude --file /path/to/brief.md\n'
      ;;
    workflow)
      printf '  vibecrafted workflow claude --prompt "Plan and implement auth"\n'
      printf '  vc-workflow codex --file /path/to/brief.md\n'
      ;;
    review)
      printf '  vibecrafted review codex --prompt "Review PR #14"\n'
      printf '  vibecrafted review agy --prompt "Review HEAD~10..HEAD"\n'
      printf '  vc-review claude --file /path/to/pr-brief.md\n'
      ;;
    research)
      printf '  vibecrafted research --prompt "Research the API surface"\n'
      printf '  vc-research --file /path/to/question-set.md\n'
      printf '  vc-research-await --last\n'
      ;;
    *)
      printf '  vibecrafted %s codex --prompt "Run %s on this repository"\n' "$skill" "$skill"
      printf '  %s claude --file /path/to/brief.md\n' "$wrapper"
      ;;
  esac
  printf '\n'
  _print_common_skill_flags
  _print_skill_specific_flags "$skill"
  printf '\n'
}

cmd_agent_help() {
  local agent="$1"
  printf '\n'
  printf '%b⚒%b  %b%s%b\n' "$_copper" "$_reset" "$_bold" "$agent" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Canonical commands for %s. Actions come first; the agent comes last.\n' "$agent"
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted init %s\n' "$agent"
  printf '  vibecrafted <skill> %s [args]\n' "$agent"
  printf '  vibecrafted <observe|await|stop|resume> %s [args]\n' "$agent"
  printf '\n'
  printf '%bCanonical workflows:%b\n' "$_bold" "$_reset"
  printf '  implement %s <plan.md>         Execute a plan file\n' "$agent"
  printf '  research  %s <plan.md>         Research a topic or plan file\n' "$agent"
  printf '  review    %s <plan.md>         Review a bounded PR, branch, commit range, or artifact pack\n' "$agent"
  printf '  observe   %s --last|--run-id   Check the last report or transcript\n' "$agent"
  printf '  await     %s --last|--run-id   Join the shared vc-server monitor\n' "$agent"
  printf '            --timeout <s>        Idle window (resets on live/moving evidence)\n'
  printf '            --hard-cap <s>       Optional absolute wall-clock deadline\n'
  printf '  stop      %s --run-id|--last   TERM the launcher process group and mark stopped\n' "$agent"
  printf '  resume    %s --run-id <id>     Continue a recorded run; --session <id|current|last> selects native history\n' "$agent"
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted init %s\n' "$agent"
  printf '  vibecrafted implement %s .vibecrafted/plans/my-plan.md\n' "$agent"
  printf '  vibecrafted research %s .vibecrafted/plans/my-plan.md\n' "$agent"
  printf '  vibecrafted observe %s --last\n' "$agent"
  printf '  vibecrafted await %s --last\n' "$agent"
  printf '  vibecrafted stop %s --run-id <id>\n' "$agent"
  printf '  vibecrafted resume %s --session last\n' "$agent"
  printf '\n'
}

cmd_start_help() {
  printf '\n'
  printf '%b⚒%b  %bstart%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Create a vc-frame workspace for a repository and enter it (operator layout).\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted start [<workspace>] [--repo <project-path>]\n'
  printf '  vibecrafted start --root <project-path>          (legacy spelling of --repo)\n'
  printf '  vibecrafted start resume\n'
  printf '  vc-start [<workspace>] [--repo <project-path>]    (same contract, same owner)\n'
  printf '  vc-start --new-host [--repo <project-path>]      # another Operator Frame session\n'
  printf '  vc-start resume\n'
  printf '\n'
  printf '%bContract:%b\n' "$_bold" "$_reset"
  printf '  Root:   --repo wins; otherwise the Git top-level of the current directory\n'
  printf '          (a subdirectory names the same workspace); outside Git, the directory itself.\n'
  printf '  Name:   <workspace> if given, else the root directory name, used verbatim.\n'
  printf '          Rules: 1-24 characters, no / or \\, no leading -, no control characters,\n'
  printf '          no leading/trailing whitespace. Reserved words: operator, vibecrafted\n'
  printf '          (= default start), resume (= deliberate re-entry). Nothing is normalized.\n'
  printf '  Enter:  an existing live workspace is attached or switched to; an EXITED\n'
  printf '          workspace is restored in place; a missing workspace is created.\n'
  printf '          An unreadable inventory or a known name owned by another repository\n'
  printf '          refuses safely. Names are never silently changed or suffixed.\n'
  printf '          From a foreign terminal, open the active-generation VC Terminal.\n'
  printf '          Owned terminal re-entry attaches directly; unknown Frame host opens VC Terminal.\n'
  printf '          With multiple source clients, use the Sessions rail or Cmd-Up/Down.\n'
  printf '          The destination may already have multiple clients.\n'
  printf '          Each session owns its tabs and one chrome; multiple clients may attach.\n'
  printf '          Cmd-Up/Down switches sessions; Cmd-Left/Right switches local tabs.\n'
  printf '          Without a terminal, VC Terminal also opens on the requested repository.\n'
  printf '  Frame:  --new-host creates another Operator Frame session on the active generation.\n'
  printf '          Names: vc-host@<shortgen>, then -2, -3; existing sessions stay intact.\n'
  printf '          Ordinary project entry does not replace or join an older Operator Frame.\n'
  printf '          In scripts, pass --new-host explicitly; resume deliberately keeps its owner.\n'
  printf '          Operator Frame is session 00; projects start at 01 in the Sessions rail.\n'
  printf '  Exit:   0 entered · 2 usage/name/root · 3 foreign name collision · 4 inventory/restore/create\n'
  printf '          Native entry propagates the Frame exit status.\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vc-start                                   # workspace named after this repository\n'
  printf '  vc-start review-b --repo ~/Projects/example\n'
  printf '  vibecrafted start --repo ~/Projects/example\n'
  printf '  vc-start resume\n'
  printf '\n'
  printf '  Direct %bvc-<workflow> <agent>%b calls outside vc-frame auto-enter the\n' "$_cyan" "$_reset"
  printf '  operator session and run the workflow in a new tab.\n'
  printf '\n'
}

cmd_dashboard_help() {
  printf '\n'
  printf '%b⚒%b  %bdashboard%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Thin shim over native vc-frame for operator session management.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted dashboard [layout]          Open/switch to a dashboard layout\n'
  printf '  vibecrafted dashboard ls                List active vc-frame sessions\n'
  printf '  vibecrafted dashboard switch <name>     Switch session (inside vc-frame) or attach (outside)\n'
  printf '  vibecrafted dashboard attach <name>     Attach to a session from outside vc-frame\n'
  printf '  vibecrafted dashboard kill <name>       Kill a vc-frame session\n'
  printf '  vibecrafted dashboard gc [flags]        Prune dead sessions and optionally stale detached ones\n'
  printf '\n'
  printf '%bLayouts:%b  dashboard (default), marbles, workflow, research, operator\n' "$_bold" "$_reset"
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted dashboard                   # default dashboard\n'
  printf '  vibecrafted dashboard ls                # list sessions\n'
  printf '  vibecrafted dashboard gc --apply        # prune dead EXITED sessions\n'
  printf '  vibecrafted dashboard marbles           # marbles layout\n'
  printf '  vibecrafted dashboard switch my-session  # switch/attach\n'
  printf '\n'
}

cmd_loop_help() {
  printf '\n'
  printf '%b⚒%b  %bloop%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Interactive Agent-Operator continuation plus async worker await chaining.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted loop start --prompt "Conduct this dispatch to stop point"\n'
  printf '  vibecrafted loop start --file /path/to/master-dispatch.md --completion-promise READY\n'
  printf '  vibecrafted loop next\n'
  printf '  vibecrafted loop complete --promise READY\n'
  printf '  vibecrafted loop await-run --run-id wflw-123456-789 --then-cmd '"'"'vibecrafted workflow codex --file next.md'"'"'\n'
  printf '  vc-loop status\n'
  printf '\n'
  printf '%bState:%b\n' "$_bold" "$_reset"
  printf '  Default state file: <repo-root>/.vibecrafted/operator-loop.local.md\n'
  printf '  Local state is ignored by git via /.vibecrafted.\n'
  printf '\n'
  printf '%bSafety:%b\n' "$_bold" "$_reset"
  printf '  --then-cmd is an Operator-approved argv command executed after a successful await.\n'
  printf '  Do not use it for push/deploy/publish unless the active plan explicitly says so.\n'
  printf '\n'
  printf '%bWhy:%b\n' "$_bold" "$_reset"
  printf '  The front door stays small; the runtime script owns state, iteration,\n'
  printf '  completion promises, and background await chains for operator sessions.\n'
  printf '\n'
}

cmd_cron_help() {
  printf '\n'
  printf '%b⚒%b  %bcron%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Cron-safe LOOP heartbeat backed by Vibecrafted Core.\n'
  printf '  Captures Loctree + AICX context and can resume an operator-approved next command after an idle window.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted cron tick [--root <repo>] [--after-idle-minutes 10] [--then-cmd <cmd>]\n'
  printf '  vibecrafted cron line [--root <repo>] [--every-minutes 10] [--then-cmd <cmd>]\n'
  printf '  vc-cron tick --root /path/to/repo --no-context\n'
  printf '\n'
  printf '%bReal crontab line:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted cron line --root /path/to/repo --every-minutes 10 --then-cmd '"'"'vibecrafted loop next'"'"'\n'
  printf '\n'
  printf '%bSafety:%b\n' "$_bold" "$_reset"
  printf '  tick refuses hard-stop commands such as force-push, trunk push, deploy, publish, release, reset, checkout --, and rm -rf.\n'
  printf '  Runtime shell is only a wrapper; implementation lives in vibecrafted-core.\n'
  printf '\n'
}

cmd_dispatch_help() {
  printf '\n'
  printf '%b⚒%b  %bdispatch%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Run a vibecrafted.dispatch.v1 TOML plan through the deterministic supervisor.\n'
  printf '  Also preserves dispatch run for one-worker async lifecycle supervision.\n'
  printf '  dispatch run owns process spawn, transcript capture, artifact validation, and exit status.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted dispatch <agent> "<prompt>" [--skill implement] [--await] [launch flags]\n'
  printf '  vibecrafted dispatch <plan.dispatch.toml> [--doctor|--dry-run|--json|--resume <run-id>] [--allow-red-baseline]\n'
  printf '  vibecrafted dispatch run --run-id <id> --root <path> --report <path> --transcript <path> -- <command> [args]\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted dispatch analyzer-truth.dispatch.toml --doctor\n'
  printf '  vibecrafted dispatch analyzer-truth.dispatch.toml --dry-run --json\n'
  printf '  vibecrafted dispatch run --run-id demo --root . --report .vibecrafted/report.md --transcript .vibecrafted/trace.log --json -- bash worker.sh\n'
  printf '\n'
  printf '%bContract:%b\n' "$_bold" "$_reset"
  printf '  --doctor validates and runs unique verifiers in a clean detached baseline.\n'
  printf '  Red baseline verifiers block launch; --allow-red-baseline records an explicit override in the tracker.\n'
  printf '  --dry-run renders every worker prompt under reports_dir/dry-run without launching.\n'
  printf '  Full dispatch writes tracker.md and journal.md progressively from launch —\n'
  printf '  watch those for live state; stdout stays silent until the run settles,\n'
  printf '  then adds handoff.md and dispatch-result.json.\n'
  printf '  Exit code is the worker exit code when the worker fails.\n'
  printf '  Exit code 2 means the worker exited cleanly but the artifact contract failed.\n'
  printf '\n'
}
cmd_gui_help() {
  printf '\n'
  printf '%b⚒%b  %bgui%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Launch the localhost-only Python control plane.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted gui [--source <path>] [--host <host>] [--port <port>] [--no-open]\n'
  printf '\n'
  printf '%bFlags:%b\n' "$_bold" "$_reset"
  printf '  --source <path>                 Framework source directory to stage from\n'
  printf '  --host <host>                   Host to bind (default: 127.0.0.1)\n'
  printf '  --port <port>                   Port to bind (default: 0, ephemeral)\n'
  printf '  --no-open                       Do not open a browser tab\n'
  printf '  --bundle-dir <path>             Optional pre-built site bundle\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted gui\n'
  printf '  vibecrafted gui --no-open --port 4173\n'
  printf '\n'
}

cmd_tui_help() {
  printf '\n'
  printf '%b⚒%b  %btui%b  (product binary: %bvoc%b)\n' "$_copper" "$_reset" "$_bold" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Launch Voc Agent — the Rust terminal cockpit over shared control-plane state.\n'
  printf '  Installed by "make install-app-binaries" / "make install" as ~/.local/bin/voc.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted tui [voc flags...]\n'
  printf '  voc [flags...]\n'
  printf '  vibecrafted tui [--state-root <dir>] [--deck <path>] [--repo <path>] [--runtime <headless|terminal|visible>] [--tick-ms <ms>]\n'
  printf '\n'
  printf '%bRepository:%b\n' "$_bold" "$_reset"
  printf '  --repo <path>   workspace root passed through to launched workflows (--root: legacy spelling;\n'
  printf '                  both with different paths is an error, never a silent pick)\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted tui\n'
  printf '  voc --runtime headless\n'
  printf '  vibecrafted tui --tick-ms 500\n'
  printf '\n'
}

cmd_resume_help() {
  printf '\n'
  printf '%b⚒%b  %bresume%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Resume a stopped control-plane run, a provider session, or AICX continuity.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted resume <claude|codex|agy|junie|grok|cursor|kimi|copilot|omp> --run-id <work-...> [flags]\n'
  printf '  vibecrafted resume <claude|codex|agy|junie|grok|cursor|kimi|copilot|omp> --session <provider-uuid> [flags]\n'
  printf '  vibecrafted resume <claude|codex|agy|junie|grok|cursor|kimi|copilot|omp> [flags]\n'
  printf '\n'
  printf '%bAfter stop:%b\n' "$_bold" "$_reset"
  printf '  Stop kills the process group. There is no same-PGID restart.\n'
  printf '  --run-id launches a NEW tracked job that continues the stopped work.\n'
  printf '  If the run recorded a provider session, that session is resumed natively.\n'
  printf '  Do not put VIBECRAFTED_SESSION_ID or work-* into --session.\n'
  printf '\n'
  printf '%bWithout --run-id / --session:%b\n' "$_bold" "$_reset"
  printf '  Builds a bounded continuity pack from the AICX session chain.\n'
  printf '  A bare resume stays interactive; the AICX pack is continuity transport,\n'
  printf '  not operator job text and not a native attach. Never resumes the last\n'
  printf '  same-agent match. Native provider resume requires --session <id>.\n'
  printf '  --repo (or legacy --root) selects the repository from any directory and\n'
  printf '  narrows AICX; it does not pick an id.\n'
  printf '\n'
  printf '%bWith --repo / --root:%b\n' "$_bold" "$_reset"
  printf '  The repository is the declared workspace: the agent is resumed in THAT\n'
  printf '  repository'"'"'s own vc-frame session (created when absent, reused when live),\n'
  printf '  never in whatever session this shell happens to be attached to.\n'
  printf '  A live attached client is switched onto it; a plain terminal attaches.\n'
  printf '  The session catalog in the pack is evidence, not a swipe list.\n'
  printf '  Explicit --prompt/--file without --session starts a new tracked\n'
  printf '  headless job and does not adopt a historical session.\n'
  printf '  Override window: VIBECRAFTED_RESUME_AICX_HOURS=72\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted resume claude --run-id work-260816-213657-08420\n'
  printf '  vibecrafted resume claude --run-id work-260816-213657-08420 --prompt "continue"\n'
  printf '  vibecrafted resume claude --session last\n'
  printf '  vibecrafted resume claude --session abc123\n'
  printf '  vibecrafted resume codex --session abc123 --prompt "Continue from the failing test"\n'
  printf '  vibecrafted resume grok\n'
  printf '  vibecrafted resume codex --prompt "pick up where the fleet left off"\n'
  printf '\n'
  _print_skill_specific_flags "resume"
  printf '\n'
}

cmd_fork_help() {
  printf '\n'
  printf '%b⚒%b  %bfork%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Branch a provider session into a NEW session; the source session stays untouched.\n'
  printf '  Native forks: codex (codex fork), claude and grok (--resume <id> --fork-session), kimi (kimi fork <id> -y).\n'
  printf '  cursor, agy and junie have no verified native fork adapter: vibecrafted resume <agent> --session <id>\n'
  printf '  continues the ORIGINAL session there (a resume, never presented as a fork).\n'
  printf '\n%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted fork <claude|codex|grok|kimi> --session <provider-session-id> [flags]\n'
  printf '  vc-fork <claude|codex|grok|kimi> --session <provider-session-id> [flags]\n'
  printf '  vibecrafted fork <claude|codex|grok|kimi> --run-id <work-...> [flags]\n'
  printf '  vc-fork <claude|codex|grok|kimi> --run-id <work-...> [flags]\n'
  printf '  vibecrafted fork codex --session current|last [flags]   # explicit context or scoped run records\n'
  printf '  vc-fork codex --session current|last [flags]\n'
  printf '\n%bOptions:%b\n' "$_bold" "$_reset"
  printf '  --session <id|current|last>     provider session to branch from (never a work-* run id)\n'
  printf '  --run-id <work-...>                 control-plane run; its recorded provider session is the source\n'
  printf '  --repo <path|org/name>              canonical repository (--root: equivalent legacy alias)\n'
  printf '  --runtime visible|terminal          bare interactive fork (default: visible)\n'
  printf '  --runtime headless                  task fork with --prompt/--file (default with input)\n'
  printf '  --placement right|floating          pane shape (default: floating)\n'
  printf '  --model <name>                      provider model override\n'
  printf '  --permissions bypass|auto|accept-edits|read-only  provider permission contract (codex: no accept-edits)\n'
  printf '  -p, --prompt <text>                 optional first prompt in the fork\n'
  printf '  --file <plan> | --prompt-stdin      private source snapshot; model may come from YAML frontmatter\n'
  printf '  --base <ref>                        pinned branch, tag, commit or HEAD\n'
  printf '  --execution-runtime living-tree|local-worktrees; --worktree [true|false]\n'
  printf '\n%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted fork codex --session current --runtime visible\n'
  printf '  vibecrafted fork claude --run-id work-260908-194325-30219 --repo ~/Projects/app\n'
  printf '  vibecrafted fork grok --session 3f2b8c1e-0d2a-4f6b-9c1d-5e7a8b9c0d1e --placement floating -p "Try the other approach"\n'
  printf '\n'
}

cmd_init_help() {
  printf '\n'
  printf '%b⚒%b  %binit%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Start an interactive repository orientation session with an agent.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted init [claude|codex|agy|junie|grok|cursor|kimi|copilot|omp] [--runtime terminal|visible|plain] [--policy-runtime local-native|local-worktrees|local-vm|cloud-soon] [--permissions bypass|auto|accept-edits|read-only] [--token-budget safe|unlimited|N] [--continuity full-lineage|fresh|bare-fork] [--prompt "<context>"]\n'
  printf '  vc-init [claude|codex|agy|junie|grok|cursor|kimi|copilot|omp]\n'
  printf '\n'
  printf '%bRuntime:%b\n' "$_bold" "$_reset"
  printf '  terminal  (default) open a tab in the vc-frame cockpit; missing host support refuses\n'
  printf '  plain     start the agent in this terminal, no cockpit needed\n'
  printf '  Policy runtime defaults to local-native; unavailable runtimes fail closed.\n'
  printf '  Permission support is provider-specific; unsupported cells are rejected.\n'
  printf '  --repo <path|org/name> (--root alias), --base <ref>, --execution-runtime living-tree|local-worktrees\n'
  printf '  --worktree [true|false], --model <exact-id>, --file <plan>, --prompt-stdin\n'
  printf '  Model selection: --model > plan frontmatter > provider default; input remains interactive.\n'
  printf '  Token budget defaults to unmetered; safe or N explicitly require measured usage support.\n'
  printf '  unlimited is restricted to directly observed local-native sessions and still measures usage.\n'
  printf '  Measured quota currently requires a verified Claude transcript capability; unsupported providers fail closed.\n'
  printf '  Continuity defaults to fresh in the shell. full-lineage requires materialized AICX + active LOOP + parent lineage.\n'
  printf '  bare-fork is expert-only and requires --parent-session <exact-provider-session-id>.\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted init claude\n'
  printf '  vibecrafted init claude --runtime plain\n'
  printf '  vibecrafted init claude --runtime plain --policy-runtime local-native --permissions accept-edits\n'
  printf '  vibecrafted init claude --continuity full-lineage --continuity-parent <run-id>\n'
  printf '  vc-init codex\n'
  printf '\n'
}

cmd_partner_help() {
  printf '\n'
  printf '%b⚒%b  %bpartner%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Start an interactive partner session with an agent (shared steering).\n'
  printf '  Same family as init: TTY/frame face with /vc-partner. Never a headless worker.\n'
  printf '  --prompt/--file remain interactive; without a TTY the canonical VC Terminal handoff is used.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted partner [claude|codex|agy|junie|grok|cursor|kimi|copilot|omp] [--runtime terminal|visible|plain]\n'
  printf '  vc-partner [claude|codex|agy|junie|grok|cursor|kimi|copilot|omp]\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted partner claude\n'
  printf '  vibecrafted partner codex --runtime plain\n'
  printf '  vc-start / [New] with the partner ritual, then /vc-partner in that session\n'
  printf '\n'
}

cmd_operator_help() {
  printf '\n'
  printf '%b⚒%b  %boperator%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Start an interactive Agent Operator session (never the human Founder).\n'
  printf '  Opens a TTY face with /vc-operator — same family as init, not a worker job.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted operator [claude|codex|agy|junie|grok|cursor|kimi|copilot|omp] [--runtime terminal|visible]\n'
  printf '  vc-operator [claude|codex|agy|junie|grok|cursor|kimi|copilot|omp]\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted operator claude\n'
  printf '  vibecrafted operator codex --operator auto\n'
  printf '  vc-operator grok\n'
  printf '\n'
}

cmd_status_help() {
  printf '\n'
  printf '%b⚒%b  %bstatus%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Show today'"'"'s runs with their state and report path.\n'
  printf '  A run is one dispatched agent job; its report and transcript live under ~/.vibecrafted.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted status [--all] [--limit N] [--json]\n'
  printf '  vibecrafted stats skills     (skill context sizes)\n'
  printf '\n'
}

cmd_doctor_help() {
  printf '\n'
  printf '%b⚒%b  %bdoctor%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Verify installation health using the framework doctor gate.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted doctor\n'
  printf '  vibecrafted doctor --release\n'
  printf '  vibecrafted doctor --fix-server-service\n'
  printf '  vibecrafted check\n'
  printf '\n'
}

cmd_update_help() {
  printf '\n'
  printf '%b⚒%b  %bupdate%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Pull the latest framework release and reinstall the local command deck.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted update [--force] [--ref <channel>]\n'
  printf '  vibecrafted upgrade [--force] [--ref <channel>]\n'
  printf '\n'
}

cmd_uninstall_help() {
  printf '\n'
  printf '%b⚒%b  %buninstall%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Reverse the local Vibecrafted install.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted uninstall\n'
  printf '  vibecrafted uninstall --dry-run\n'
  printf '  vibecrafted uninstall --drain [--drain-timeout <seconds>]\n'
  printf '  vibecrafted remove\n'
  printf '\n'
}

cmd_version_help() {
  printf '\n'
  printf '%b⚒%b  %bversion%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Print the installed Vibecrafted version.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted version\n'
  printf '  vibecrafted --version\n'
  printf '\n'
}

cmd_server_help() {
  printf '\n'
  printf '%b⚒%b  %bserver%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Manage the local control-plane viewer server and its process guardian.\n'
  printf '  Persistent service management is macOS launchd-only in this release.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted server [start|stop|status|open|doctor|caretaker] [options]\n'
  printf '  vibecrafted server service [install|reconcile|restart|start|stop|status|logs|uninstall] [options]\n'
  printf '\n'
  printf '%bOptions:%b\n' "$_bold" "$_reset"
  printf '  --port, -p <port>  Specify the port (default: 3024)\n'
  printf '  --host, -h <host>  Specify the host (default: 127.0.0.1)\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted server start --port 3024\n'
  printf '  vibecrafted server service install --port 3024\n'
  printf '  vibecrafted server service start\n'
  printf '  vibecrafted server status\n'
  printf '  vibecrafted server service stop\n'
  printf '  vibecrafted server service logs --json\n'
  printf '  vibecrafted server caretaker --json\n'
  printf '\n'
}


cmd_telemetry_help() {
  printf '\n'
  printf '%b⚒%b  %btelemetry%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Local agent quota engines and the marbles smoke path.\n'
  printf '  Engines write quota.json on the host; voc reads those files.\n'
  printf '  Nothing is shipped to a Vibecrafted backend.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  telemetry agy line|once|sessions|daemon|archive\n'
  printf '  telemetry kimi line|once|daemon|archive\n'
  printf '  telemetry codex line|once|sessions|daemon|archive\n'
  printf '  telemetry claude line|once|sessions|daemon|archive\n'
  printf '  telemetry grok line|once|sessions|daemon|archive\n'
  printf '  telemetry junie line|once|sessions|daemon|archive\n'
  printf '  telemetry copilot line|once|sessions|daemon|archive\n'
  printf '  telemetry cursor line|once|sessions|daemon|archive\n'
  printf '  telemetry omp line|once|sessions|archive\n'
  printf '  telemetry line                        Statuslines of present engines\n'
  printf '  telemetry once                        JSON union of agy, kimi, codex, claude, grok, junie, copilot, cursor, omp\n'
  printf '  telemetry archive                     Backfill daily usage archives for present engines\n'
  printf '  telemetry smoke [--agent <claude|codex|agy|junie|grok|cursor|kimi|copilot|omp>] [--count <n>] [--repo <path>] [--no-watch|--watch]\n'
  printf '  vibecrafted telemetry <same>\n'
  printf '  (--root is the legacy spelling of --repo; the smoke root may be created on demand)\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  telemetry agy line\n'
  printf '  telemetry kimi daemon\n'
  printf '  telemetry codex sessions\n'
  printf '  telemetry grok archive\n'
  printf '  telemetry archive\n'
  printf '  telemetry once\n'
  printf '  telemetry line\n'
  printf '  telemetry smoke --count 1 --no-watch\n'
  printf '\n'
}

_telemetry_engine_script() {
  local engine="${1:-}"
  local package_root script
  case "$engine" in
    agy|kimi|codex|claude|grok|junie|copilot|cursor|omp) ;;
    *) return 1 ;;
  esac
  package_root="$(_package_resource_root 2>/dev/null || true)"
  [[ -n "$package_root" ]] || return 1
  script="$package_root/runtime/telemetry/${engine}-monitor/${engine}_monitor.py"
  [[ -f "$script" ]] || return 1
  printf '%s\n' "$script"
}

_telemetry_python() {
  local candidate
  for candidate in \
    "$(_vibecrafted_python 2>/dev/null || true)" \
    "${VIBECRAFTED_PYTHON:-}" \
    python3.13 python3.12 python3.11 python3; do
    [[ -n "$candidate" ]] || continue
    if [[ "$candidate" == /* ]]; then
      [[ -x "$candidate" ]] || continue
    else
      command -v "$candidate" >/dev/null 2>&1 || continue
    fi
    "$candidate" -c 'import tomllib' >/dev/null 2>&1 || continue
    printf '%s\n' "$candidate"
    return 0
  done
  printf '%b✗%b telemetry requires Python 3.11+ (tomllib).\n' "$_red" "$_reset" >&2
  return 1
}

_telemetry_run_engine() {
  local engine="$1"
  local mode="${2:-line}"
  shift 2 || true
  local script python_bin
  script="$(_telemetry_engine_script "$engine")" || {
    printf '%b✗%b telemetry engine not found: %s\n' "$_red" "$_reset" "$engine" >&2
    return 1
  }
  python_bin="$(_telemetry_python)" || return 1
  if [[ "$mode" == "daemon" ]]; then
    exec "$python_bin" "$script" "$mode" "$@"
  fi
  "$python_bin" "$script" "$mode" "$@"
}

_telemetry_engine_mode_ok() {
  local engine="$1"
  local mode="$2"
  case "$engine" in
    agy)
      case "$mode" in
        line|once|sessions|daemon|archive) return 0 ;;
      esac
      ;;
    kimi)
      case "$mode" in
        line|once|daemon|tui|archive) return 0 ;;
      esac
      ;;
    omp)
      case "$mode" in
        line|once|sessions|archive) return 0 ;;
      esac
      ;;
    codex|claude|grok|junie|copilot|cursor)
      case "$mode" in
        line|once|sessions|daemon|archive) return 0 ;;
      esac
      ;;
  esac
  return 1
}

cmd_telemetry_engine() {
  local engine="$1"
  local mode
  shift || true
  mode="${1:-line}"
  case "$mode" in
    help|-h|--help)
      cmd_telemetry_help
      return 0
      ;;
    -*)
      mode="line"
      ;;
    *)
      _telemetry_engine_mode_ok "$engine" "$mode" || {
        printf '%b✗%b unknown %s mode: %s\n' "$_red" "$_reset" "$engine" "$mode" >&2
        printf '\n' >&2
        cmd_telemetry_help >&2
        return 1
      }
      shift || true
      ;;
  esac
  _telemetry_run_engine "$engine" "$mode" "$@"
}

cmd_telemetry_line() {
  local engine ran=0 rc=0
  for engine in agy kimi codex claude grok junie copilot cursor omp; do
    _telemetry_engine_script "$engine" >/dev/null 2>&1 || continue
    ran=1
    _telemetry_run_engine "$engine" line "$@" || rc=$?
  done
  if ((ran == 0)); then
    printf '%b✗%b telemetry engines not installed in this generation.\n' "$_red" "$_reset" >&2
    return 1
  fi
  return "$rc"
}

cmd_telemetry_once() {
  local python_bin tmpdir engine script
  python_bin="$(_telemetry_python)" || return 1
  mkdir -p "$crafted_home/tmp"
  tmpdir="$(mktemp -d "$crafted_home/tmp/telemetry-once.XXXXXX")"
  for engine in agy kimi codex claude grok junie copilot cursor omp; do
    if script="$(_telemetry_engine_script "$engine")"; then
      "$python_bin" "$script" once "$@" > "$tmpdir/$engine.json" 2>"$tmpdir/$engine.err" || true
      if [[ ! -s "$tmpdir/$engine.json" ]]; then
        printf '{"agent":"%s","status":"error","reason":"engine failed","cache_semantics":null,"last_session":null,"metrics":null,"quota":{"status":"error"}}\n' "$engine" > "$tmpdir/$engine.json"
      fi
    else
      printf '{"agent":"%s","status":"absent","reason":"engine not installed in this generation","cache_semantics":null,"last_session":null,"metrics":null,"quota":{"status":"absent"}}\n' "$engine" > "$tmpdir/$engine.json"
    fi
  done
  ONCE_DIR="$tmpdir" "$python_bin" - <<'PY'
import json, os, pathlib

order = ["agy", "kimi", "codex", "claude", "grok", "junie", "copilot", "cursor", "omp"]
root = pathlib.Path(os.environ["ONCE_DIR"])
union = {}
for agent in order:
    raw = (root / f"{agent}.json").read_text(encoding="utf-8").strip()
    if not raw or raw == "null":
        union[agent] = {
            "agent": agent,
            "status": "absent",
            "reason": "engine not installed in this generation",
            "cache_semantics": None,
            "last_session": None,
            "metrics": None,
            "quota": {"status": "absent"},
        }
        continue
    try:
        union[agent] = json.loads(raw)
    except json.JSONDecodeError:
        union[agent] = {
            "agent": agent,
            "status": "error",
            "reason": "invalid engine output",
            "cache_semantics": None,
            "last_session": None,
            "metrics": None,
            "quota": {"status": "error"},
        }
print(json.dumps(union, indent=2, ensure_ascii=False))
PY
  local rc=$?
  rm -rf "$tmpdir"
  return "$rc"
}


_telemetry_smoke_root() {
  local requested_root="${1:-}"

  if [[ -n "$requested_root" ]]; then
    _expand_home_path "$requested_root"
    return 0
  fi

  mkdir -p "$crafted_home/tmp"
  mktemp -d "$crafted_home/tmp/telemetry-smoke.XXXXXX"
}

_telemetry_smoke_prepare_repo() {
  local target_root="$1"

  mkdir -p "$target_root"
  if ! git -C "$target_root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    git -C "$target_root" init -q
  fi

  git -C "$target_root" config --get user.name >/dev/null 2>&1 || \
    git -C "$target_root" config user.name "Vibecrafted Telemetry"
  git -C "$target_root" config --get user.email >/dev/null 2>&1 || \
    git -C "$target_root" config user.email "telemetry@local"
}

_telemetry_smoke_plan() {
  local target_root="$1"
  local plan_ts plan_path

  plan_ts="$(date +%Y%m%d_%H%M%S)"
  mkdir -p "$target_root/.vibecrafted/plans"
  plan_path="$target_root/.vibecrafted/plans/telemetry-smoke-${plan_ts}.md"
  cat > "$plan_path" <<'EOF'
---
focus: telemetry smoke
priority: P0
---

This is a bounded telemetry smoke run.
Prove the marbles runtime can operate in this workspace without recursion.

1. Create `SMOKE_OK.md` at the repo root with a short note that includes the current working directory.
2. Write the required report to the exact report path from the prompt.
3. Make exactly one git commit for the smoke marker and include the report file if it lives inside this repo.
4. Do not run `telemetry smoke` or any other nested spawn command.
5. Stop after the report and commit are complete.
EOF
  printf '%s\n' "$plan_path"
}

cmd_telemetry_archive() {
  local engine ran=0 rc=0
  for engine in agy kimi codex claude grok junie copilot cursor omp; do
    _telemetry_engine_script "$engine" >/dev/null 2>&1 || continue
    ran=1
    _telemetry_run_engine "$engine" archive "$@" || rc=$?
  done
  if [[ "$ran" -eq 0 ]]; then
    printf 'no telemetry engines are present in this package\n' >&2
    return 1
  fi
  return "$rc"
}

cmd_telemetry_smoke() {
  local agent="codex"
  local count="1"
  local root=""
  local telemetry_repo=""
  local telemetry_root_legacy=""
  local runtime="headless"
  local marbles_script=""
  local smoke_root=""
  local smoke_plan=""
  local telemetry_args=()

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --agent)
        shift
        [[ $# -gt 0 ]] || {
          echo "Missing value for --agent" >&2
          return 1
        }
        agent="$1"
        ;;
      --count)
        shift
        [[ $# -gt 0 ]] || {
          echo "Missing value for --count" >&2
          return 1
        }
        count="$1"
        ;;
      --root)
        shift
        [[ $# -gt 0 ]] || {
          echo "Missing value for --root" >&2
          return 1
        }
        telemetry_root_legacy="$1"
        ;;
      --root=*)
        telemetry_root_legacy="${1#--root=}"
        ;;
      --repo)
        shift
        [[ $# -gt 0 ]] || {
          echo "Missing value for --repo" >&2
          return 1
        }
        telemetry_repo="$1"
        ;;
      --repo=*)
        telemetry_repo="${1#--repo=}"
        ;;
      --watch)
        runtime="terminal"
        ;;
      --no-watch)
        runtime="headless"
        ;;
      --help|-h|help)
        cmd_telemetry_help
        return 0
        ;;
      *)
        printf '%b✗%b Unknown telemetry smoke flag: %s\n' "$_red" "$_reset" "$1" >&2
        printf '\n' >&2
        cmd_telemetry_help >&2
        return 1
        ;;
    esac
    shift
  done

  if [[ "$agent" == "gemini" ]]; then
    printf '%b✗ gemini CLI is deprecated.%b Use agy (Google Antigravity CLI) instead.\n' "$_red" "$_reset" >&2
    printf '  Example: vibecrafted workflow agy --prompt "..." \n' >&2
    return 1
  fi
  _has_agent "$agent" || {
    printf '%b✗%b Unknown agent: %s\n' "$_red" "$_reset" "$agent" >&2
    return 1
  }
  # Same words as _vetcoders_select_repo, but the smoke root is CREATED on
  # demand, so only the conflicting-pair rule applies here (no existence check).
  if [[ -n "$telemetry_repo" && -n "$telemetry_root_legacy" && "$telemetry_repo" != "$telemetry_root_legacy" ]]; then
    printf 'telemetry: conflicting --repo %s and --root %s; pass one repository (--repo is the standard spelling)\n' \
      "$telemetry_repo" "$telemetry_root_legacy" >&2
    return 2
  fi
  root="${telemetry_repo:-$telemetry_root_legacy}"
  _ensure_helpers_loaded || return 1
  marbles_script="$(_vetcoders_spawn_script "$agent" "marbles_spawn.sh")" || return 1
  smoke_root="$(_telemetry_smoke_root "$root")"
  _telemetry_smoke_prepare_repo "$smoke_root"
  smoke_plan="$(_telemetry_smoke_plan "$smoke_root")"
  printf '%b[telemetry]%b smoke root: %s\n' "$_copper" "$_reset" "$smoke_root"
  printf '%b[telemetry]%b smoke plan: %s\n' "$_copper" "$_reset" "$smoke_plan"
  telemetry_args=(--agent "$agent" --runtime "$runtime" --count "$count" --root "$smoke_root")
  [[ "$runtime" == "headless" ]] && telemetry_args+=(--no-watch)
  telemetry_args+=(--file "$smoke_plan")
  (
    # Smoke runs must start from a fresh marbles context even when they are
    # launched from inside another agent/session.
    unset VIBECRAFTED_MARBLES_RUN_ID VIBECRAFTED_RUN_ID VIBECRAFTED_RUN_LOCK
    unset VIBECRAFTED_SKILL_CODE VIBECRAFTED_SKILL_NAME VIBECRAFTED_LOOP_NR
    unset VIBECRAFTED_OPERATOR_SESSION
    unset SPAWN_AGENT SPAWN_ROOT SPAWN_PLAN SPAWN_RUN_ID SPAWN_RUN_LOCK
    unset SPAWN_LOOP_NR SPAWN_SKILL_CODE SPAWN_SKILL_NAME
    bash "$marbles_script" "${telemetry_args[@]}"
  )
}

cmd_telemetry() {
  local subcommand="${1:-help}"
  shift || true

  case "$subcommand" in
    help|-h|--help)
      cmd_telemetry_help
      ;;
    smoke)
      cmd_telemetry_smoke "$@"
      ;;
    agy|kimi|codex|claude|grok|junie|copilot|cursor|omp)
      cmd_telemetry_engine "$subcommand" "$@"
      ;;
    line)
      cmd_telemetry_line "$@"
      ;;
    once)
      cmd_telemetry_once "$@"
      ;;
    archive)
      cmd_telemetry_archive "$@"
      ;;
    *)
      printf '%b✗%b Unknown telemetry subcommand: %s\n' "$_red" "$_reset" "$subcommand" >&2
      printf '\n' >&2
      cmd_telemetry_help >&2
      return 1
      ;;
  esac
}

_gui_no_open_requested() {
  local arg
  for arg in "$@"; do
    [[ "$arg" == "--no-open" ]] && return 0
  done
  return 1
}

_gui_launch_notice() {
  local host="127.0.0.1"
  local port="0"

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --host)
        shift
        [[ $# -gt 0 ]] && host="$1"
        ;;
      --host=*)
        host="${1#--host=}"
        ;;
      --port)
        shift
        [[ $# -gt 0 ]] && port="$1"
        ;;
      --port=*)
        port="${1#--port=}"
        ;;
    esac
    shift || true
  done

  if [[ "$port" == "0" ]]; then
    printf '  Starting Vibecrafted control plane on %s:ephemeral.\n' "$host"
    printf '  The server will print its exact URL after binding. Press Ctrl-C to stop.\n'
    return 0
  fi

  printf '  Listening URL: http://%s:%s/\n' "$host" "$port"
  printf '  Press Ctrl-C to stop.\n'
}

cmd_gui() {
  local gui_script repo_source
  if _is_help_flag "${1:-}"; then
    cmd_gui_help
    return 0
  fi
  gui_script="$(_installer_gui_script 2>/dev/null || true)"
  [[ -n "$gui_script" ]] || {
    printf '%b✗%b installer_gui.py not found.\n' "$_red" "$_reset" >&2
    return 1
  }
  repo_source="$(_repo_source_root 2>/dev/null || true)"
  [[ -n "$repo_source" ]] || repo_source="$(cd "$(dirname "$gui_script")/.." && pwd)"
  _sync_control_plane_best_effort
  if _gui_no_open_requested "$@"; then
    _gui_launch_notice "$@"
  fi
  python3 "$gui_script" --source "$repo_source" "$@"
}

_server_runtime_dir() {
  printf '%s/server\n' "${VIBECRAFTED_HOME:-$HOME/.vibecrafted}"
}

_server_launcher_path() {
  local supervisor_bin="${1:-}"
  local candidate=""
  local declared="${VIBECRAFTED_DECLARED_LAUNCHER:-}"
  # The LaunchAgent binds the public wrapper digest. A generation-first PATH
  # can resolve vc-server-supervisor next to the inner deck; hashing that
  # sibling `vibecrafted` against the LaunchAgent is the false mismatch
  # restart then dumps on the Founder. Prefer the declared public wrapper.
  if [[ "$declared" == /* && -x "$declared" ]]; then
    _realpath_quiet "$declared"
    return 0
  fi
  if [[ -n "$supervisor_bin" ]]; then
    candidate="$(dirname "$supervisor_bin")/vibecrafted"
    [[ -x "$candidate" ]] || return 1
  else
    candidate="$(command -v vibecrafted 2>/dev/null || true)"
    [[ -n "$candidate" ]] || candidate="$0"
  fi
  _realpath_quiet "$candidate"
}

_server_supervisor_binary() {
  local candidate=""
  local declared_launcher="${VIBECRAFTED_DECLARED_LAUNCHER:-}"
  local sibling=""
  local uv_dir=""
  local user_bin=""
  # Public install wrappers declare the launcher whose digest is bound into
  # the LaunchAgent receipt. Resolve its sibling supervisor before PATH: a
  # generation-first PATH otherwise pairs the generation deck with a public
  # service identity and manufactures build-current=no / pair-healthy=no.
  if [[ "$declared_launcher" == /* && -x "$declared_launcher" ]]; then
    sibling="$(dirname "$declared_launcher")/vc-server-supervisor"
    if [[ -x "$sibling" ]]; then
      _realpath_quiet "$sibling"
      return 0
    fi
  fi
  candidate="$(command -v vc-server-supervisor 2>/dev/null || true)"
  if [[ -n "$candidate" && -x "$candidate" ]]; then
    _realpath_quiet "$candidate"
    return 0
  fi
  # Headless PATH often lacks the user bin that a login shell prepends.
  # Prefer the generation next to this deck, then the uv tool env, then
  # the XDG user bin — never a single frozen pin of one absolute path.
  sibling="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)/vc-server-supervisor"
  if [[ -x "$sibling" ]]; then
    _realpath_quiet "$sibling"
    return 0
  fi
  if command -v uv >/dev/null 2>&1; then
    uv_dir="$(uv tool dir --color never 2>/dev/null || true)"
    if [[ -n "$uv_dir" && -x "$uv_dir/vibecrafted/bin/vc-server-supervisor" ]]; then
      _realpath_quiet "$uv_dir/vibecrafted/bin/vc-server-supervisor"
      return 0
    fi
  fi
  user_bin="${XDG_BIN_HOME:-${HOME}/.local/bin}/vc-server-supervisor"
  if [[ -x "$user_bin" ]]; then
    _realpath_quiet "$user_bin"
    return 0
  fi
  return 1
}

_server_supervisor_cli() {
  local command_name="${1:-}"
  shift || true
  # Deck help promises `-h <host>` / `-p <port>`; the supervisor's argparse
  # owns `-h` as --help. Translate here so the promise the operator read is
  # the contract the tool receives ("service install -h X" once printed help
  # and exited 0 — an install that never happened).
  local -a normalized=()
  while [[ $# -gt 0 ]]; do
    case "$1" in
      -h)
        if [[ $# -ge 2 && "$2" != -* ]]; then
          normalized+=(--host "$2"); shift 2; continue
        fi
        normalized+=("$1"); shift ;;
      -p)
        if [[ $# -ge 2 && "$2" != -* ]]; then
          normalized+=(--port "$2"); shift 2; continue
        fi
        normalized+=("$1"); shift ;;
      *) normalized+=("$1"); shift ;;
    esac
  done
  # bash 3.2 + set -u: an empty array expands as "unbound variable" without
  # the ${arr[@]+...} guard — "server status" (no args) died on this line.
  set -- ${normalized[@]+"${normalized[@]}"}
  local core_dir python_bin launcher supervisor_bin
  local -a common_args command_args
  common_args=(
    --home "${VIBECRAFTED_HOME:-$HOME/.vibecrafted}"
    --runtime-home "${VIBECRAFTED_RUNTIME_HOME:-$HOME/.local/share/vibecrafted}"
    --operator-home "$HOME"
  )
  command_args=("$command_name" "$@")
  case "$command_name" in
    service)
      supervisor_bin="$(_server_supervisor_binary 2>/dev/null || true)"
      [[ -n "$supervisor_bin" ]] || {
        printf '%b✗%b vc-server-supervisor entrypoint not found; reinstall Vibecrafted.\n' \
          "$_red" "$_reset" >&2
        return 78
      }
      launcher="$(_server_launcher_path "$supervisor_bin" 2>/dev/null || true)"
      [[ -n "$launcher" ]] || {
        printf '%b✗%b Cannot resolve an absolute Vibecrafted launcher.\n' \
          "$_red" "$_reset" >&2
        return 78
      }
      command_args+=(--launcher "$launcher" --supervisor-bin "$supervisor_bin")
      # The exact staged executable which renders the LaunchAgent is also
      # written into ProgramArguments. Its sibling launcher is the only valid
      # service entrypoint, so PATH cannot mix two installed generations.
      env -u PYTHONHOME -u PYTHONPATH \
        PATH="$(dirname "$supervisor_bin"):${PATH:-}" \
        "$supervisor_bin" "${command_args[@]}" "${common_args[@]}"
      return $?
      ;;
    manual-stop)
      launcher="$(_server_launcher_path 2>/dev/null || true)"
      [[ -n "$launcher" ]] || {
        printf '%b✗%b Cannot resolve an absolute Vibecrafted launcher.\n' \
          "$_red" "$_reset" >&2
        return 78
      }
      command_args+=(--launcher "$launcher")
      ;;
  esac
  supervisor_bin="$(_server_supervisor_binary 2>/dev/null || true)"
  if [[ -n "$supervisor_bin" ]]; then
    env -u PYTHONHOME -u PYTHONPATH \
      "$supervisor_bin" "${command_args[@]}" "${common_args[@]}"
    return
  fi
  core_dir="$(_core_module_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || {
    printf '%b✗%b server_supervisor runtime module not found; reinstall Vibecrafted.\n' \
      "$_red" "$_reset" >&2
    return 78
  }
  python_bin="$(_vibecrafted_python)"
  PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
    "$python_bin" -m vibecrafted_core.server_supervisor \
    "${command_args[@]}" "${common_args[@]}"
}

_pid_file_value() {
  local pid_file="${1:-}"
  local value=""
  [[ -f "$pid_file" ]] || return 1
  IFS= read -r value < "$pid_file" || true
  printf '%s\n' "$value"
}

# Interpreter for the internal server helper (_server_python). The supervisor
# hands its children a PATH that starts with ~/.local/bin, so a bare python3
# there -- an operator's own toolchain link -- used to answer the product's
# origin and health probes, and its output became the server URL. An installed
# generation therefore runs the helper only on the interpreter it owns: the
# Runtime Pack's bin/python3, else the generation-owned chain. A missing or
# corrupt owned interpreter is a hard failure, never a host python3. A
# development checkout keeps the ordinary owner chain with its host fallback.
# The verified result is cached per process; cmd_server warms it up front.
_SERVER_HELPER_PYTHON=""

_server_helper_python_verify() {
  local candidate="${1:-}" origin="${2:-}" reason=""
  if [[ ! -e "$candidate" ]]; then
    reason="is missing"
  elif [[ -d "$candidate" || ! -x "$candidate" ]]; then
    reason="is not an executable file"
  elif [[ "$("$candidate" -I -c 'import sys; print("vibecrafted-python", sys.version_info[0])' 2>/dev/null || true)" \
    != "vibecrafted-python 3" ]]; then
    # Exit status alone is not proof: a shell script parked at bin/python3
    # ignores `-I -c` and exits 0, so the probe must answer as Python itself.
    reason="does not run as Python 3"
  fi
  [[ -n "$reason" ]] || return 0
  printf '%b✗%b %s Python interpreter %s: %s\n' \
    "$_red" "$_reset" "$origin" "$reason" "$candidate" >&2
  printf '  Server control never falls back to a host python3; reinstall Vibecrafted.\n' >&2
  return 78
}

_server_helper_python() {
  local runtime_root owner_root candidate origin
  if [[ -n "$_SERVER_HELPER_PYTHON" ]]; then
    printf '%s\n' "$_SERVER_HELPER_PYTHON"
    return 0
  fi
  runtime_root="$(_runtime_payload_root 2>/dev/null || true)"
  owner_root="$(_script_owner_root 2>/dev/null || true)"
  if [[ -n "$runtime_root" ]]; then
    candidate="$runtime_root/bin/python3"
    origin="Packaged"
  elif _is_installed_generation_root "$owner_root"; then
    candidate="$(_vibecrafted_owned_python 2>/dev/null || true)"
    if [[ -z "$candidate" ]]; then
      printf '%b✗%b Installed generation owns no Python interpreter for server control: %s\n' \
        "$_red" "$_reset" "$owner_root" >&2
      printf '  Server control never falls back to a host python3; reinstall Vibecrafted.\n' >&2
      return 78
    fi
    origin="Generation-owned"
  else
    candidate="$(_vibecrafted_python)"
    origin="Development"
  fi
  _server_helper_python_verify "$candidate" "$origin" || return $?
  _SERVER_HELPER_PYTHON="$candidate"
  printf '%s\n' "$candidate"
}

_server_python() {
  local python_bin core_dir owner_root
  python_bin="$(_server_helper_python)" || return $?
  if [[ "${1:-}" == "pair-health" && -f "${2:-}/guardian.execution.json" ]]; then
    # -I deliberately ignores ambient PYTHONPATH. Admit only the physical
    # launcher's selected core for the embedded Guardian probe.
    core_dir="$(_core_module_dir)" || return 78
    owner_root="$(_script_owner_root)" || return 78
    set -- "$@" "$core_dir" "$owner_root"
  fi
  "$python_bin" -I - "$@" <<'PY'
from __future__ import annotations

import ctypes
import datetime as dt
import errno
import fcntl
import hashlib
import http.client
import json
import os
import re
import shutil
import socket
import stat
import struct
import subprocess
import sys
import time
from pathlib import Path

IDENTITY_SCHEMA = "vibecrafted.managed-process.v1"
LAUNCH_WITNESS_SCHEMA = "vibecrafted.launch-witness.v1"
LOCK_SCHEMA = "vibecrafted.server-lifecycle-lock.v1"
READY_SCHEMA = "vibecrafted.guardian-ready.v1"


def fail(message: str, code: int = 2) -> None:
    print(message, file=sys.stderr)
    raise SystemExit(code)


def atomic_text(path: Path, data: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}")
    with temporary.open("w", encoding="utf-8") as handle:
        handle.write(data)
        handle.flush()
        os.fsync(handle.fileno())
    os.chmod(temporary, 0o600)
    os.replace(temporary, path)


def atomic_json(path: Path, payload: dict[str, object]) -> None:
    atomic_text(
        path,
        json.dumps(payload, ensure_ascii=False, sort_keys=True, indent=2) + "\n",
    )


def read_json(path: Path) -> dict[str, object]:
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        fail(f"invalid JSON evidence at {path}: {exc}", 5)
    if not isinstance(payload, dict):
        fail(f"JSON evidence at {path} is not an object", 5)
    return payload


def validate_endpoint(host_value: object, port_value: object) -> tuple[str, int]:
    if not isinstance(host_value, str):
        fail("host must be a string")
    host = host_value
    if (
        not host
        or host != host.strip()
        or len(host) > 253
        or host.startswith("-")
        or re.fullmatch(r"[A-Za-z0-9._:-]+", host) is None
    ):
        fail(f"invalid server host: {host!r}")
    raw_port = str(port_value)
    if re.fullmatch(r"[0-9]{1,5}", raw_port) is None:
        fail(f"invalid server port: {raw_port!r}")
    port = int(raw_port)
    if not 1 <= port <= 65535:
        fail(f"server port out of range: {port}")
    return host, port


def origin(host: str, port: int) -> str:
    rendered_host = f"[{host}]" if ":" in host else host
    return f"http://{rendered_host}:{port}"


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def process_alive(pid: int) -> bool:
    try:
        os.kill(pid, 0)
    except ProcessLookupError:
        return False
    except PermissionError:
        return True
    return True


class DarwinProcBSDInfo(ctypes.Structure):
    _fields_ = [
        ("pbi_flags", ctypes.c_uint32),
        ("pbi_status", ctypes.c_uint32),
        ("pbi_xstatus", ctypes.c_uint32),
        ("pbi_pid", ctypes.c_uint32),
        ("pbi_ppid", ctypes.c_uint32),
        ("pbi_uid", ctypes.c_uint32),
        ("pbi_gid", ctypes.c_uint32),
        ("pbi_ruid", ctypes.c_uint32),
        ("pbi_rgid", ctypes.c_uint32),
        ("pbi_svuid", ctypes.c_uint32),
        ("pbi_svgid", ctypes.c_uint32),
        ("rfu_1", ctypes.c_uint32),
        ("pbi_comm", ctypes.c_char * 16),
        ("pbi_name", ctypes.c_char * 32),
        ("pbi_nfiles", ctypes.c_uint32),
        ("pbi_pgid", ctypes.c_uint32),
        ("pbi_pjobc", ctypes.c_uint32),
        ("e_tdev", ctypes.c_uint32),
        ("e_tpgid", ctypes.c_uint32),
        ("pbi_nice", ctypes.c_int32),
        ("pbi_start_tvsec", ctypes.c_uint64),
        ("pbi_start_tvusec", ctypes.c_uint64),
    ]


_DARWIN_CTL_KERN = 1
_DARWIN_KERN_PROCARGS2 = 49
_DARWIN_MAX_PROCARGS = 16 * 1024 * 1024
_DARWIN_PROC_BSDINFO_SIZE = 136
_DARWIN_PROC_FLAG_INEXIT = 0x4
_DARWIN_PROC_FLAG_LP64 = 0x10
_DARWIN_PROC_PIDPATHINFO_MAXSIZE = 4096
_DARWIN_PROC_PIDTBSDINFO = 3
_DARWIN_STABLE_PROCESS_STATES = frozenset({1, 2, 3, 4})
_DARWIN_LIBPROC: ctypes.CDLL | None = None
_DARWIN_LIBC: ctypes.CDLL | None = None


def darwin_libraries() -> tuple[ctypes.CDLL, ctypes.CDLL]:
    global _DARWIN_LIBPROC, _DARWIN_LIBC
    if sys.platform != "darwin":
        fail("Darwin process APIs requested on a non-Darwin host", 4)
    if _DARWIN_LIBPROC is None:
        try:
            libproc = ctypes.CDLL("/usr/lib/libproc.dylib", use_errno=True)
        except OSError as exc:
            fail(f"cannot load Darwin process API: {exc}", 4)
        libproc.proc_pidinfo.argtypes = [
            ctypes.c_int,
            ctypes.c_int,
            ctypes.c_uint64,
            ctypes.c_void_p,
            ctypes.c_int,
        ]
        libproc.proc_pidinfo.restype = ctypes.c_int
        libproc.proc_pidpath.argtypes = [
            ctypes.c_int,
            ctypes.c_void_p,
            ctypes.c_uint32,
        ]
        libproc.proc_pidpath.restype = ctypes.c_int
        _DARWIN_LIBPROC = libproc
    if _DARWIN_LIBC is None:
        libc = ctypes.CDLL(None, use_errno=True)
        libc.sysctl.argtypes = [
            ctypes.POINTER(ctypes.c_int),
            ctypes.c_uint,
            ctypes.c_void_p,
            ctypes.POINTER(ctypes.c_size_t),
            ctypes.c_void_p,
            ctypes.c_size_t,
        ]
        libc.sysctl.restype = ctypes.c_int
        _DARWIN_LIBC = libc
    return _DARWIN_LIBPROC, _DARWIN_LIBC


def darwin_bsd_info(pid: int) -> tuple[str, int, int]:
    libproc, _ = darwin_libraries()
    info = DarwinProcBSDInfo()
    if ctypes.sizeof(info) != _DARWIN_PROC_BSDINFO_SIZE:
        fail("Darwin proc_bsdinfo ABI does not match the supported layout", 4)
    ctypes.set_errno(0)
    received_size = libproc.proc_pidinfo(
        pid,
        _DARWIN_PROC_PIDTBSDINFO,
        0,
        ctypes.byref(info),
        _DARWIN_PROC_BSDINFO_SIZE,
    )
    if received_size != _DARWIN_PROC_BSDINFO_SIZE:
        fail(
            f"cannot inspect Darwin process birth identity for {pid} "
            f"(errno {ctypes.get_errno()})",
            4,
        )
    if (
        int(info.pbi_pid) != pid
        or int(info.pbi_status) not in _DARWIN_STABLE_PROCESS_STATES
        or int(info.pbi_flags) & _DARWIN_PROC_FLAG_INEXIT
        or int(info.pbi_ppid) <= 0
        or int(info.pbi_start_tvsec) <= 0
        or not 0 <= int(info.pbi_start_tvusec) < 1_000_000
    ):
        fail(f"invalid Darwin process birth identity for {pid}", 4)
    return (
        "darwin:"
        f"{int(info.pbi_start_tvsec)}:{int(info.pbi_start_tvusec)}",
        int(info.pbi_ppid),
        8 if int(info.pbi_flags) & _DARWIN_PROC_FLAG_LP64 else 4,
    )


def darwin_pidpath(pid: int) -> str:
    libproc, _ = darwin_libraries()
    buffer = ctypes.create_string_buffer(_DARWIN_PROC_PIDPATHINFO_MAXSIZE)
    ctypes.set_errno(0)
    received_size = libproc.proc_pidpath(pid, buffer, len(buffer))
    if received_size <= 0 or received_size > len(buffer):
        fail(
            f"cannot inspect Darwin executable path for {pid} "
            f"(errno {ctypes.get_errno()})",
            4,
        )
    raw_path = buffer.raw[:received_size].split(b"\0", 1)[0]
    if not raw_path:
        fail(f"Darwin executable path is empty for {pid}", 4)
    executable = os.fsdecode(raw_path)
    if not os.path.isabs(executable):
        fail(f"Darwin executable path is not absolute for {pid}", 4)
    return executable


def darwin_procargs_raw(pid: int) -> bytes:
    _, libc = darwin_libraries()
    mib = (ctypes.c_int * 3)(
        _DARWIN_CTL_KERN,
        _DARWIN_KERN_PROCARGS2,
        pid,
    )
    last_errno = 0
    for _ in range(3):
        required_size = ctypes.c_size_t(0)
        ctypes.set_errno(0)
        if libc.sysctl(
            mib,
            len(mib),
            None,
            ctypes.byref(required_size),
            None,
            0,
        ) != 0:
            fail(
                f"cannot size Darwin process arguments for {pid} "
                f"(errno {ctypes.get_errno()})",
                4,
            )
        capacity = int(required_size.value)
        if not 4 <= capacity <= _DARWIN_MAX_PROCARGS:
            fail(f"invalid Darwin process argument size for {pid}", 4)
        buffer = ctypes.create_string_buffer(capacity)
        received_size = ctypes.c_size_t(capacity)
        ctypes.set_errno(0)
        if libc.sysctl(
            mib,
            len(mib),
            buffer,
            ctypes.byref(received_size),
            None,
            0,
        ) == 0:
            actual_size = int(received_size.value)
            if not 4 <= actual_size <= capacity:
                fail(f"invalid Darwin process argument payload for {pid}", 4)
            return buffer.raw[:actual_size]
        last_errno = ctypes.get_errno()
        if last_errno != errno.ENOMEM:
            fail(
                f"cannot inspect Darwin process arguments for {pid} "
                f"(errno {last_errno})",
                4,
            )
    fail(
        f"Darwin process arguments kept changing size for {pid} "
        f"(errno {last_errno})",
        4,
    )


def darwin_arguments(
    pid: int,
    *,
    include_environment: bool,
    pointer_size: int,
) -> tuple[str, list[str], str | None]:
    if pointer_size not in {4, 8}:
        fail(f"invalid Darwin process pointer size for {pid}", 4)
    raw = darwin_procargs_raw(pid)
    argc = struct.unpack_from("=i", raw)[0]
    if not 1 <= argc <= 4096:
        fail(f"invalid Darwin process argument count for {pid}", 4)

    position = struct.calcsize("=i")
    executable_end = raw.find(b"\0", position)
    if executable_end < 0 or executable_end == position:
        fail(f"cannot parse Darwin executable argument for {pid}", 4)
    executable_argument = os.fsdecode(raw[position:executable_end])
    position = executable_end + 1
    string_body_offset = position - struct.calcsize("=i")
    padding_size = (-string_body_offset) % pointer_size
    padding_end = position + padding_size
    if padding_end > len(raw) or any(raw[position:padding_end]):
        fail(f"invalid Darwin process argument alignment for {pid}", 4)
    position = padding_end

    argv: list[str] = []
    for _ in range(argc):
        argument_end = raw.find(b"\0", position)
        if argument_end < 0:
            fail(f"cannot parse Darwin argv for {pid}", 4)
        argv.append(os.fsdecode(raw[position:argument_end]))
        position = argument_end + 1
    if not argv or not argv[0]:
        fail(f"Darwin argv is empty for {pid}", 4)

    nonce: str | None = None
    if include_environment:
        while position < len(raw) and raw[position] == 0:
            position += 1
        environment: list[str] = []
        while position < len(raw):
            item_end = raw.find(b"\0", position)
            if item_end < 0:
                fail(f"cannot parse Darwin environment for {pid}", 4)
            if item_end == position:
                break
            environment.append(os.fsdecode(raw[position:item_end]))
            position = item_end + 1
        prefix = "VIBECRAFTED_PROCESS_NONCE="
        nonce_values = [
            item[len(prefix) :]
            for item in environment
            if item.startswith(prefix)
        ]
        if nonce_values:
            if (
                len(nonce_values) != 1
                or re.fullmatch(r"[0-9a-f]{64}", nonce_values[0]) is None
            ):
                fail(f"ambiguous Darwin process nonce for {pid}", 4)
            nonce = nonce_values[0]
    return executable_argument, argv, nonce


def darwin_process_record(
    pid: int,
    *,
    include_nonce: bool,
) -> tuple[str, int, str, list[str], str | None]:
    first_start, first_parent, first_pointer_size = darwin_bsd_info(pid)
    first_path = darwin_pidpath(pid)
    first_executable_argument, first_argv, first_nonce = darwin_arguments(
        pid,
        include_environment=include_nonce,
        pointer_size=first_pointer_size,
    )
    second_executable_argument, second_argv, second_nonce = darwin_arguments(
        pid,
        include_environment=include_nonce,
        pointer_size=first_pointer_size,
    )
    second_path = darwin_pidpath(pid)
    second_start, second_parent, second_pointer_size = darwin_bsd_info(pid)
    if (
        (first_start, first_parent, first_pointer_size, first_path)
        != (second_start, second_parent, second_pointer_size, second_path)
        or first_executable_argument != second_executable_argument
        or first_argv != second_argv
        or first_nonce != second_nonce
    ):
        fail(f"Darwin process {pid} changed while identity was captured", 4)
    return first_start, first_parent, first_path, first_argv, first_nonce


def process_launch_identity(pid: int) -> dict[str, object]:
    if pid <= 1 or not process_alive(pid):
        fail(f"process {pid} is not live", 3)
    proc_stat = Path(f"/proc/{pid}/stat")
    if proc_stat.is_file():
        def proc_birth() -> tuple[str, int]:
            raw = proc_stat.read_text(encoding="utf-8")
            closing = raw.rfind(")")
            if closing < 0:
                fail(f"cannot parse process launch identity for {pid}", 4)
            fields = raw[closing + 2 :].split()
            if len(fields) <= 19 or not fields[1].isdigit():
                fail(f"cannot parse process launch identity for {pid}", 4)
            return f"proc:{fields[19]}", int(fields[1])

        first_birth = proc_birth()
        process_nonce = managed_process_nonce(pid)
        second_birth = proc_birth()
        if first_birth != second_birth:
            fail(f"process {pid} changed while launch identity was captured", 4)
        return {
            "start_token": first_birth[0],
            "parent_pid": first_birth[1],
            "process_nonce": process_nonce,
        }
    if sys.platform == "darwin":
        audit_process_probe("launch", pid)
        start_token, parent_pid, _, _, process_nonce = darwin_process_record(
            pid,
            include_nonce=True,
        )
        return {
            "start_token": start_token,
            "parent_pid": parent_pid,
            "process_nonce": process_nonce,
        }
    audit_process_probe("launch", pid)
    result = subprocess.run(
        [
            "ps",
            "eww",
            "-ww",
            "-p",
            str(pid),
            "-o",
            "lstart=",
            "-o",
            "ppid=",
            "-o",
            "command=",
        ],
        check=False,
        capture_output=True,
        text=True,
        timeout=2,
    )
    raw = result.stdout.rstrip("\n")
    if result.returncode != 0 or len(raw) <= 24:
        fail(f"cannot inspect process launch identity for {pid}", 4)
    started = raw[:24].strip()
    remainder = raw[24:].strip().split(maxsplit=1)
    if len(remainder) != 2 or not started or not remainder[0].isdigit():
        fail(f"cannot parse process launch identity for {pid}", 4)
    match = re.search(
        r"(?:^|\s)VIBECRAFTED_PROCESS_NONCE=([0-9a-f]{64})(?:\s|$)",
        remainder[1],
    )
    return {
        "start_token": f"ps:{started}",
        "parent_pid": int(remainder[0]),
        "process_nonce": match.group(1) if match else None,
    }


def audit_process_probe(kind: str, pid: int) -> None:
    audit_raw = os.environ.get("VIBECRAFTED_TEST_PROCESS_AUDIT")
    if not audit_raw:
        return
    audit_path = Path(audit_raw)
    audit_path.parent.mkdir(parents=True, exist_ok=True)
    descriptor = os.open(
        audit_path,
        os.O_WRONLY | os.O_CREAT | os.O_APPEND,
        0o600,
    )
    with os.fdopen(descriptor, "a", encoding="utf-8") as handle:
        handle.write(
            json.dumps(
                {
                    "operation": sys.argv[1] if len(sys.argv) > 1 else "",
                    "kind": kind,
                    "pid": pid,
                    "probe_owner_pid": os.getpid(),
                },
                sort_keys=True,
            )
            + "\n"
        )


def ps_value(pid: int, field: str, *, wide: bool = False) -> str:
    argv = ["ps"]
    if wide:
        argv.append("-ww")
    argv.extend(["-p", str(pid), "-o", f"{field}="])
    audit_process_probe(field, pid)
    result = subprocess.run(
        argv,
        check=False,
        capture_output=True,
        text=True,
        timeout=2,
    )
    if result.returncode != 0:
        fail(f"cannot inspect process {pid} field {field}", 4)
    return result.stdout.strip()


def ps_process_record(pid: int) -> tuple[str, str, str]:
    start_header = "S" * 24
    executable_header = "E" * 1024
    command_header = "VIBECRAFTED_ARGV"
    audit_process_probe("record", pid)
    result = subprocess.run(
        [
            "ps",
            "-ww",
            "-p",
            str(pid),
            "-o",
            f"lstart={start_header}",
            "-o",
            f"comm={executable_header}",
            "-o",
            f"command={command_header}",
        ],
        check=False,
        capture_output=True,
        timeout=2,
    )
    lines = result.stdout.rstrip(b"\n").splitlines()
    if result.returncode != 0 or len(lines) != 2:
        fail(f"cannot inspect process record for {pid}", 4)
    header, record = lines
    start_header_bytes = start_header.encode("ascii")
    executable_header_bytes = executable_header.encode("ascii")
    command_header_bytes = command_header.encode("ascii")
    positions = [
        header.find(start_header_bytes),
        header.find(executable_header_bytes),
        header.find(command_header_bytes),
    ]
    if positions != sorted(positions) or any(position < 0 for position in positions):
        fail(f"cannot parse process record columns for {pid}", 4)
    started_raw = record[positions[0] : positions[1]].strip()
    executable_raw = record[positions[1] : positions[2]].strip()
    command_raw = record[positions[2] :].strip()
    if len(started_raw) != 24 or not executable_raw or not command_raw:
        fail(f"cannot parse process record for {pid}", 4)
    try:
        started = started_raw.decode("ascii")
    except UnicodeDecodeError:
        fail(f"cannot decode process start token for {pid}", 4)
    executable = os.fsdecode(executable_raw)
    command_line = os.fsdecode(command_raw)
    return f"ps:{started}", executable, command_line


def process_start_token(pid: int) -> str:
    proc_stat = Path(f"/proc/{pid}/stat")
    if proc_stat.is_file():
        raw = proc_stat.read_text(encoding="utf-8")
        closing = raw.rfind(")")
        fields = raw[closing + 2 :].split()
        if closing < 0 or len(fields) <= 19:
            fail(f"cannot parse process start token for {pid}", 4)
        return f"proc:{fields[19]}"
    if sys.platform == "darwin":
        start_token, _, _ = darwin_bsd_info(pid)
        return start_token
    started = ps_value(pid, "lstart")
    if not started:
        fail(f"cannot inspect process start token for {pid}", 4)
    return f"ps:{started}"


def managed_process_nonce(pid: int) -> str | None:
    proc_environ = Path(f"/proc/{pid}/environ")
    if proc_environ.is_file():
        prefix = b"VIBECRAFTED_PROCESS_NONCE="
        for item in proc_environ.read_bytes().split(b"\0"):
            if item.startswith(prefix):
                return item[len(prefix) :].decode("ascii", errors="strict")
        return None
    if sys.platform == "darwin":
        audit_process_probe("nonce", pid)
        _, _, _, _, process_nonce = darwin_process_record(
            pid,
            include_nonce=True,
        )
        return process_nonce
    audit_process_probe("nonce", pid)
    result = subprocess.run(
        ["ps", "eww", "-p", str(pid), "-o", "command="],
        check=False,
        capture_output=True,
        text=True,
        timeout=2,
    )
    if result.returncode != 0:
        fail(f"cannot inspect process nonce for {pid}", 4)
    match = re.search(
        r"(?:^|\s)VIBECRAFTED_PROCESS_NONCE=([0-9a-f]{64})(?:\s|$)",
        result.stdout,
    )
    return match.group(1) if match else None


def is_launch_wrapper(executable: object) -> bool:
    running = os.path.realpath(str(executable or ""))
    for name in ("env", "nohup"):
        candidates = {
            shutil.which(name),
            f"/bin/{name}",
            f"/usr/bin/{name}",
        }
        if any(
            candidate is not None
            and Path(candidate).exists()
            and running == os.path.realpath(candidate)
            for candidate in candidates
        ):
            return True
    return False


def process_snapshot(
    pid: int,
    *,
    include_nonce: bool = True,
    reject_launch_wrappers: bool = False,
) -> dict[str, object]:
    if pid <= 1 or not process_alive(pid):
        fail(f"process {pid} is not live", 3)
    proc_cmdline = Path(f"/proc/{pid}/cmdline")
    if proc_cmdline.is_file():
        first_start = process_start_token(pid)
        command: dict[str, object] = {
            "kind": "argv",
            "value": [
                item.decode("utf-8", errors="surrogateescape")
                for item in proc_cmdline.read_bytes().split(b"\0")
                if item
            ],
        }
        executable_probe = Path(f"/proc/{pid}/exe")
        try:
            executable = os.path.realpath(executable_probe)
            executable_sha256 = sha256_file(executable_probe)
        except OSError as exc:
            fail(f"cannot fingerprint executable for process {pid}: {exc}", 4)
        if reject_launch_wrappers and is_launch_wrapper(executable):
            fail(f"process {pid} is still a launch wrapper", 4)
        process_nonce = managed_process_nonce(pid) if include_nonce else None
        second_start = process_start_token(pid)
    elif sys.platform == "darwin":
        audit_process_probe("record", pid)
        if include_nonce:
            audit_process_probe("nonce", pid)
        (
            first_start,
            _,
            executable_raw,
            argv,
            process_nonce,
        ) = darwin_process_record(pid, include_nonce=include_nonce)
        if reject_launch_wrappers and is_launch_wrapper(executable_raw):
            fail(f"process {pid} is still a launch wrapper", 4)
        if not argv or not executable_raw:
            fail(f"cannot capture command identity for process {pid}", 4)
        command = {"kind": "argv", "value": argv}
        executable_path = Path(executable_raw)
        executable = (
            str(executable_path.resolve())
            if executable_path.exists()
            else executable_raw
        )
        try:
            executable_sha256 = (
                sha256_file(Path(executable)) if Path(executable).is_file() else None
            )
        except OSError as exc:
            fail(f"cannot fingerprint executable for process {pid}: {exc}", 4)
        second_start = first_start
    else:
        first_start, executable_raw, command_line = ps_process_record(pid)
        if reject_launch_wrappers and is_launch_wrapper(executable_raw):
            fail(f"process {pid} is still a launch wrapper", 4)
        if not command_line or not executable_raw:
            fail(f"cannot capture command identity for process {pid}", 4)
        command = {"kind": "command_line", "value": command_line}
        executable_path = Path(executable_raw)
        executable = (
            str(executable_path.resolve())
            if executable_path.exists()
            else executable_raw
        )
        try:
            executable_sha256 = (
                sha256_file(Path(executable)) if Path(executable).is_file() else None
            )
        except OSError as exc:
            fail(f"cannot fingerprint executable for process {pid}: {exc}", 4)
        process_nonce = managed_process_nonce(pid) if include_nonce else None
        if include_nonce:
            (
                second_start,
                second_executable_raw,
                second_command_line,
            ) = ps_process_record(pid)
            if (
                executable_raw != second_executable_raw
                or command_line != second_command_line
            ):
                fail(f"process {pid} command changed while identity was captured", 4)
        else:
            second_start = first_start
    if first_start != second_start:
        fail(f"process {pid} changed while identity was captured", 4)
    snapshot: dict[str, object] = {
        "start_token": first_start,
        "command": command,
        "executable": executable,
        "executable_sha256": executable_sha256,
    }
    if include_nonce:
        snapshot["process_nonce"] = process_nonce
    return snapshot


def lock_process_snapshot(pid: int) -> dict[str, object]:
    snapshot = process_snapshot(pid, include_nonce=False)
    snapshot["process_nonce"] = None
    return snapshot


def command_mentions_executable(
    command: object,
    candidates: tuple[str, ...],
) -> bool:
    if not isinstance(command, dict):
        return False
    if command.get("kind") == "argv":
        argv = command.get("value")
        return isinstance(argv, list) and any(
            candidate in argv for candidate in candidates
        )
    if command.get("kind") != "command_line":
        return False
    command_line = command.get("value")
    if not isinstance(command_line, str):
        return False
    for candidate in candidates:
        escaped = re.escape(candidate)
        if re.search(
            rf"(?<!\S)(?:{escaped}|'{escaped}'|\"{escaped}\")(?=\s|$)",
            command_line,
        ):
            return True
    return False


def verify_identity(path: Path, pid: int, role: str) -> dict[str, object]:
    payload = read_json(path)
    if (
        payload.get("schema") != IDENTITY_SCHEMA
        or payload.get("pid") != pid
        or payload.get("role") != role
        or not isinstance(payload.get("nonce"), str)
        or not payload.get("nonce")
        or not isinstance(payload.get("process"), dict)
    ):
        fail(f"managed identity metadata mismatch for {role} PID {pid}", 4)
    recorded = payload["process"]
    if recorded.get("process_nonce") != payload["nonce"]:
        fail(f"managed identity nonce mismatch for {role} PID {pid}", 4)
    stable_recorded = {
        key: value
        for key, value in recorded.items()
        if key != "process_nonce"
    }
    current = process_snapshot(pid, include_nonce=False)
    if current != stable_recorded:
        fail(f"managed identity changed for {role} PID {pid}", 4)
    return payload


def validate_lock_owner(payload: dict[str, object]) -> tuple[int, str]:
    process = payload.get("process")
    if (
        set(payload) != {"schema", "pid", "nonce", "acquired_at", "process"}
        or payload.get("schema") != LOCK_SCHEMA
        or not isinstance(payload.get("pid"), int)
        or isinstance(payload.get("pid"), bool)
        or int(payload["pid"]) <= 1
        or not isinstance(payload.get("nonce"), str)
        or re.fullmatch(r"[0-9a-f]{64}", str(payload["nonce"])) is None
        or not isinstance(payload.get("acquired_at"), str)
        or not isinstance(process, dict)
        or set(process)
        != {
            "start_token",
            "command",
            "executable",
            "executable_sha256",
            "process_nonce",
        }
    ):
        fail("invalid lifecycle lock owner", 5)

    try:
        acquired_at = dt.datetime.fromisoformat(str(payload["acquired_at"]))
    except ValueError:
        fail("invalid lifecycle lock acquisition timestamp", 5)
    if acquired_at.tzinfo is None:
        fail("lifecycle lock acquisition timestamp has no timezone", 5)

    command = process.get("command")
    command_valid = False
    if isinstance(command, dict) and set(command) == {"kind", "value"}:
        if command.get("kind") == "argv":
            argv = command.get("value")
            command_valid = (
                isinstance(argv, list)
                and bool(argv)
                and all(isinstance(item, str) for item in argv)
            )
        elif command.get("kind") == "command_line":
            command_valid = (
                isinstance(command.get("value"), str)
                and bool(command.get("value"))
            )
    executable_sha256 = process.get("executable_sha256")
    process_nonce = process.get("process_nonce")
    if (
        not isinstance(process.get("start_token"), str)
        or re.fullmatch(
            r"(?:darwin|proc|ps):.+",
            str(process["start_token"]),
        )
        is None
        or not command_valid
        or not isinstance(process.get("executable"), str)
        or not process.get("executable")
        or (
            executable_sha256 is not None
            and (
                not isinstance(executable_sha256, str)
                or re.fullmatch(r"[0-9a-f]{64}", executable_sha256) is None
            )
        )
        or (
            process_nonce is not None
            and (
                not isinstance(process_nonce, str)
                or re.fullmatch(r"[0-9a-f]{64}", process_nonce) is None
            )
        )
    ):
        fail("invalid lifecycle lock process identity", 5)
    return int(payload["pid"]), str(payload["nonce"])


def read_lock_owner(path: Path) -> dict[str, object]:
    try:
        lock_stat = path.parent.lstat()
    except OSError as exc:
        fail(f"cannot inspect lifecycle lock directory {path.parent}: {exc}", 5)
    if not stat.S_ISDIR(lock_stat.st_mode) or lock_stat.st_uid != os.getuid():
        fail("lifecycle lock directory is not an owned regular directory", 5)

    flags = os.O_RDONLY | os.O_NOFOLLOW
    try:
        descriptor = os.open(path, flags)
    except OSError as exc:
        fail(f"cannot open lifecycle lock owner {path}: {exc}", 5)
    try:
        opened_stat = os.fstat(descriptor)
        visible_stat = path.lstat()
        if (
            not stat.S_ISREG(opened_stat.st_mode)
            or opened_stat.st_uid != os.getuid()
            or opened_stat.st_nlink != 1
            or (opened_stat.st_dev, opened_stat.st_ino)
            != (visible_stat.st_dev, visible_stat.st_ino)
        ):
            fail("lifecycle lock owner is not a stable owned regular file", 5)
        with os.fdopen(descriptor, "r", encoding="utf-8") as handle:
            descriptor = -1
            try:
                payload = json.load(handle)
            except (OSError, json.JSONDecodeError) as exc:
                fail(f"invalid lifecycle lock owner JSON at {path}: {exc}", 5)
    finally:
        if descriptor >= 0:
            os.close(descriptor)
    if not isinstance(payload, dict):
        fail("lifecycle lock owner JSON is not an object", 5)
    validate_lock_owner(payload)
    return payload


def lock_owner_digest(payload: dict[str, object]) -> str:
    canonical = json.dumps(
        payload,
        ensure_ascii=True,
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    return hashlib.sha256(canonical).hexdigest()


def open_lifecycle_recovery_guard(path: Path) -> int:
    flags = os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW
    try:
        descriptor = os.open(path, flags, 0o600)
    except OSError as exc:
        fail(f"cannot open lifecycle recovery guard {path}: {exc}", 75)
    try:
        opened_stat = os.fstat(descriptor)
        visible_stat = path.lstat()
        if (
            not stat.S_ISREG(opened_stat.st_mode)
            or opened_stat.st_uid != os.getuid()
            or opened_stat.st_nlink != 1
            or (opened_stat.st_dev, opened_stat.st_ino)
            != (visible_stat.st_dev, visible_stat.st_ino)
        ):
            fail(
                "lifecycle recovery guard is not a stable owned regular file",
                75,
            )
        os.fchmod(descriptor, 0o600)
        return descriptor
    except BaseException:
        os.close(descriptor)
        raise


def fsync_directory(path: Path) -> None:
    flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
    descriptor = os.open(path, flags)
    try:
        os.fsync(descriptor)
    finally:
        os.close(descriptor)


operation = sys.argv[1] if len(sys.argv) > 1 else ""
args = sys.argv[2:]

if operation == "nonce":
    print(os.urandom(32).hex())
elif operation == "caller-pid":
    print(os.getppid())
elif operation == "validate-endpoint":
    host, port = validate_endpoint(args[0], args[1])
    print(f"{host}\t{port}")
elif operation == "origin":
    host, port = validate_endpoint(args[0], args[1])
    print(origin(host, port))
elif operation == "status-read":
    path = Path(args[0])
    default_host, default_port = validate_endpoint(args[1], args[2])
    if not path.is_file():
        print(f"{default_host}\t{default_port}")
    else:
        payload = read_json(path)
        host, port = validate_endpoint(
            payload.get("host", default_host),
            payload.get("port", default_port),
        )
        print(f"{host}\t{port}")
elif operation == "pair-health":
    runtime_dir = Path(args[0])
    if (runtime_dir / "guardian.execution.json").exists():
        if len(args) != 3:
            fail("selected launcher core missing for embedded Guardian probe", 78)
        core_dir = Path(args[-2])
        owner_root = Path(args[-1])
        package_dir = core_dir / "vibecrafted_core"
        resolved_core = core_dir.resolve()
        resolved_package = package_dir.resolve()
        if not (
            resolved_core == owner_root / "vibecrafted-core"
            and resolved_package == resolved_core / "vibecrafted_core"
        ) and not (
            owner_root.name == "vibecrafted_core"
            and resolved_package == owner_root
            and resolved_core == owner_root.parent
        ):
            fail("selected launcher core outside physical owner", 78)
        if not core_dir.is_absolute() or any(
            not path.is_file() or path.is_symlink()
            for path in (package_dir / "__init__.py", package_dir / "server_supervisor.py")
        ):
            fail("selected launcher core missing for embedded Guardian probe", 78)
        sys.path.insert(0, str(core_dir))
        from vibecrafted_core.server_supervisor import (
            SupervisorPaths, _managed_pair_in_process_healthy, _managed_pair_snapshot,
        )
        paths = SupervisorPaths.create(
            home=runtime_dir.parent,
            runtime_home=Path(os.environ.get("VIBECRAFTED_RUNTIME_HOME", str(Path.home() / ".local/share/vibecrafted"))),
            operator_home=Path.home(),
        )
        status = read_json(runtime_dir / "status.json")
        host, port = validate_endpoint(status.get("host", "127.0.0.1"), status.get("port", 3024))
        if not _managed_pair_in_process_healthy(paths, host=host, port=port):
            fail("server or embedded Guardian is not ready", 4)
        snapshot = _managed_pair_snapshot(paths)
        print(f"Server: RUNNING (PID {snapshot['server_pid']}, listening on {origin(host, port)})")
        print(f"Guardian: RUNNING (supervisor thread, owner PID {snapshot['guardian_owner_pid']})")
        raise SystemExit(0)
    audit_process_probe("pair-health", os.getpid())

    def first_line(path: Path) -> str:
        try:
            lines = path.read_text(encoding="utf-8").splitlines()
        except OSError as exc:
            fail(f"cannot read managed-pair evidence at {path}: {exc}", 5)
        if not lines or not lines[0]:
            fail(f"managed-pair evidence at {path} is empty", 5)
        return lines[0]

    status_path = runtime_dir / "status.json"
    if status_path.is_file():
        status_payload = read_json(status_path)
        host, port = validate_endpoint(
            status_payload.get("host", "127.0.0.1"),
            status_payload.get("port", 3024),
        )
    else:
        host, port = "127.0.0.1", 3024
    try:
        server_pid = int(first_line(runtime_dir / "server.pid"))
        guardian_pid = int(first_line(runtime_dir / "guardian.pid"))
    except ValueError:
        fail("managed-pair PID evidence is not an integer", 4)
    if server_pid <= 1 or guardian_pid <= 1 or server_pid == guardian_pid:
        fail("managed-pair PID evidence is invalid", 4)

    verify_identity(runtime_dir / "server.identity.json", server_pid, "server")
    guardian_identity = verify_identity(
        runtime_dir / "guardian.identity.json",
        guardian_pid,
        "guardian",
    )
    target_url = origin(host, port)
    if first_line(runtime_dir / "guardian.url") != target_url:
        fail("guardian endpoint does not match the managed server", 4)

    connection = http.client.HTTPConnection(host, port, timeout=1.0)
    try:
        connection.request(
            "GET",
            "/api/health",
            headers={"Accept": "application/json"},
        )
        response = connection.getresponse()
        if response.status != 200:
            fail(f"server health endpoint returned HTTP {response.status}", 4)
        response.read(1024)
    except (OSError, TimeoutError, http.client.HTTPException) as exc:
        fail(f"server health probe failed: {type(exc).__name__}: {exc}", 4)
    finally:
        connection.close()

    ready_path = Path(first_line(runtime_dir / "guardian.ready-path"))
    ready_payload = read_json(ready_path)
    if ready_payload != {
        "schema": READY_SCHEMA,
        "nonce": guardian_identity.get("nonce"),
        "pid": guardian_pid,
        "server_url": target_url,
    }:
        fail("guardian readiness receipt does not match the managed pair", 4)
    print(f"Server: RUNNING (PID {server_pid}, listening on {target_url})")
    print(f"Guardian: RUNNING (PID {guardian_pid}, server {target_url})")
elif operation in {"health", "health-wait"}:
    host, port = validate_endpoint(args[0], args[1])

    def probe_health(timeout: float) -> None:
        connection = http.client.HTTPConnection(host, port, timeout=timeout)
        try:
            connection.request(
                "GET",
                "/api/health",
                headers={"Accept": "application/json"},
            )
            response = connection.getresponse()
            if response.status != 200:
                raise OSError(
                    f"server health endpoint returned HTTP {response.status}"
                )
            response.read(1024)
        finally:
            connection.close()

    if operation == "health":
        probe_health(1.0)
    else:
        pid = int(args[2])
        timeout = float(args[3])
        if pid <= 1 or not 0 < timeout <= 60:
            fail("invalid bounded server health wait", 2)
        deadline = time.monotonic() + timeout
        last_error = "health endpoint has not answered"
        while True:
            if not process_alive(pid):
                fail(f"server process {pid} exited before health readiness", 3)
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                fail(
                    f"server health readiness timed out after {timeout:g}s "
                    f"(last probe: {last_error})",
                    1,
                )
            try:
                probe_health(min(1.0, remaining))
                break
            except (OSError, TimeoutError, http.client.HTTPException) as exc:
                last_error = f"{type(exc).__name__}: {exc}"
            time.sleep(min(0.2, max(0.0, deadline - time.monotonic())))
elif operation == "port-free":
    host, port = validate_endpoint(args[0], args[1])
    with socket.socket() as probe:
        probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        probe.bind((host, port))
elif operation == "write-text":
    atomic_text(Path(args[0]), args[1] + "\n")
elif operation == "launch-witness-write":
    path = Path(args[0])
    pid = int(args[1])
    role = args[2]
    parent_pid = int(args[3])
    nonce = args[4]
    launch_identity = process_launch_identity(pid)
    if (
        re.fullmatch(r"[0-9a-f]{64}", nonce) is None
        or launch_identity["parent_pid"] != parent_pid
        or launch_identity["process_nonce"] != nonce
    ):
        fail(
            f"process {pid} does not match its direct launch identity",
            4,
        )
    atomic_json(
        path,
        {
            "schema": LAUNCH_WITNESS_SCHEMA,
            "pid": pid,
            "role": role,
            "parent_pid": parent_pid,
            "start_token": launch_identity["start_token"],
            "nonce": nonce,
        },
    )
elif operation == "launch-witness-verify":
    path = Path(args[0])
    pid = int(args[1])
    role = args[2]
    parent_pid = int(args[3])
    nonce = args[4]
    payload = read_json(path)
    if (
        set(payload)
        != {"schema", "pid", "role", "parent_pid", "start_token", "nonce"}
        or payload.get("schema") != LAUNCH_WITNESS_SCHEMA
        or payload.get("pid") != pid
        or payload.get("role") != role
        or payload.get("parent_pid") != parent_pid
        or not isinstance(payload.get("start_token"), str)
        or payload.get("nonce") != nonce
        or re.fullmatch(r"[0-9a-f]{64}", nonce) is None
    ):
        fail(f"launch witness mismatch for {role} PID {pid}", 4)
    launch_identity = process_launch_identity(pid)
    if (
        launch_identity["parent_pid"] != parent_pid
        or launch_identity["start_token"] != payload["start_token"]
        or launch_identity["process_nonce"] != nonce
    ):
        fail(f"launched child identity changed for {role} PID {pid}", 4)
elif operation == "launch-witness-adopt":
    path = Path(args[0])
    pid = int(args[1])
    role = args[2]
    payload = read_json(path)
    nonce = payload.get("nonce")
    if (
        set(payload)
        != {"schema", "pid", "role", "parent_pid", "start_token", "nonce"}
        or payload.get("schema") != LAUNCH_WITNESS_SCHEMA
        or payload.get("pid") != pid
        or payload.get("role") != role
        or not isinstance(payload.get("start_token"), str)
        or not isinstance(nonce, str)
        or re.fullmatch(r"[0-9a-f]{64}", nonce) is None
    ):
        fail(f"launch witness mismatch for {role} PID {pid}", 4)
    launch_identity = process_launch_identity(pid)
    if (
        launch_identity["start_token"] != payload["start_token"]
        or launch_identity["process_nonce"] != nonce
    ):
        fail(f"launch witness cannot adopt {role} PID {pid}", 4)
    print(nonce)
elif operation == "write-status":
    path = Path(args[0])
    raw_pid = args[1]
    host, port = validate_endpoint(args[2], args[3])
    status = args[4]
    pid: int | None = None if raw_pid == "none" else int(raw_pid)
    atomic_json(
        path,
        {
            "pid": pid,
            "host": host,
            "port": port,
            "started_at": dt.datetime.now(dt.timezone.utc)
            .replace(microsecond=0)
            .isoformat()
            .replace("+00:00", "Z"),
            "status": status,
        },
    )
elif operation == "update-status":
    path = Path(args[0])
    status = args[1]
    raw_pid = args[2]
    try:
        payload = read_json(path) if path.is_file() else {}
    except SystemExit:
        payload = {}
    payload["status"] = status
    payload["pid"] = None if raw_pid == "none" else int(raw_pid)
    atomic_json(path, payload)
elif operation == "capture-identity":
    path = Path(args[0])
    pid = int(args[1])
    role = args[2]
    nonce = args[3]
    declared = Path(os.path.abspath(args[4]))
    declared_realpath = declared.resolve()
    if not nonce:
        fail("managed process nonce must not be empty")
    try:
        declared_sha256 = sha256_file(declared)
    except OSError as exc:
        fail(f"cannot fingerprint declared executable {declared}: {exc}", 4)
    snapshot = process_snapshot(pid, reject_launch_wrappers=True)
    if not command_mentions_executable(
        snapshot["command"],
        (str(declared), str(declared_realpath)),
    ):
        fail(
            f"process {pid} has not exec'd declared executable {declared}",
            4,
        )
    if snapshot.get("process_nonce") != nonce:
        fail(f"process {pid} does not carry its lifecycle nonce", 4)
    time.sleep(0.05)
    stable_snapshot = process_snapshot(pid, include_nonce=False)
    stable_recorded = {
        key: value
        for key, value in snapshot.items()
        if key != "process_nonce"
    }
    if stable_snapshot != stable_recorded:
        fail(f"process {pid} changed before identity publication", 4)
    atomic_json(
        path,
        {
            "schema": IDENTITY_SCHEMA,
            "pid": pid,
            "role": role,
            "nonce": nonce,
            "declared_executable": str(declared),
            "declared_executable_sha256": declared_sha256,
            "expected_argv": args[5:],
            "process": snapshot,
        },
    )
elif operation == "verify-identity":
    verify_identity(Path(args[0]), int(args[1]), args[2])
elif operation == "identity-nonce":
    payload = read_json(Path(args[0]))
    nonce = payload.get("nonce")
    if not isinstance(nonce, str) or not nonce:
        fail("identity nonce is missing", 5)
    print(nonce)
elif operation == "ready-check":
    path = Path(args[0])
    nonce = args[1]
    pid = int(args[2])
    server_url = args[3]
    payload = read_json(path)
    if payload != {
        "schema": READY_SCHEMA,
        "nonce": nonce,
        "pid": pid,
        "server_url": server_url,
    }:
        fail("guardian readiness receipt does not match this invocation", 4)
elif operation == "ready-remove":
    path = Path(args[0])
    if not path.is_file():
        raise SystemExit(0)
    nonce = args[1]
    pid = int(args[2])
    server_url = args[3]
    payload = read_json(path)
    if payload != {
        "schema": READY_SCHEMA,
        "nonce": nonce,
        "pid": pid,
        "server_url": server_url,
    }:
        fail("refusing to remove an unowned guardian readiness receipt", 4)
    path.unlink()
elif operation == "lock-owner-write":
    path = Path(args[0])
    pid = int(args[1])
    nonce = args[2]
    atomic_json(
        path,
        {
            "schema": LOCK_SCHEMA,
            "pid": pid,
            "nonce": nonce,
            "acquired_at": dt.datetime.now(dt.timezone.utc).isoformat(),
            "process": lock_process_snapshot(pid),
        },
    )
elif operation == "lock-state":
    path = Path(args[0])
    try:
        payload = read_lock_owner(path)
        pid, nonce = validate_lock_owner(payload)
        if not process_alive(pid):
            print(f"stale:{pid}:{nonce}:{lock_owner_digest(payload)}")
        else:
            try:
                current_process = lock_process_snapshot(pid)
            except SystemExit:
                if not process_alive(pid):
                    print(
                        f"stale:{pid}:{nonce}:{lock_owner_digest(payload)}"
                    )
                else:
                    print(f"unverified:{pid}")
            else:
                if current_process != payload["process"]:
                    print(f"unverified:{pid}")
                else:
                    print(f"live:{pid}")
    except SystemExit as exc:
        if exc.code == 5:
            print("invalid")
        else:
            raise
elif operation == "lock-reclaim":
    lock_dir = Path(args[0])
    owner_path = lock_dir / "owner.json"
    expected_pid = int(args[1])
    expected_nonce = args[2]
    expected_digest = args[3]
    if (
        expected_pid <= 1
        or re.fullmatch(r"[0-9a-f]{64}", expected_nonce) is None
        or re.fullmatch(r"[0-9a-f]{64}", expected_digest) is None
    ):
        fail("invalid expected lifecycle lock identity", 75)

    guard_path = lock_dir.parent / "lifecycle.recovery.lock"
    guard_descriptor = open_lifecycle_recovery_guard(guard_path)
    try:
        fcntl.flock(guard_descriptor, fcntl.LOCK_EX)
        opened_guard = os.fstat(guard_descriptor)
        visible_guard = guard_path.lstat()
        if (opened_guard.st_dev, opened_guard.st_ino) != (
            visible_guard.st_dev,
            visible_guard.st_ino,
        ):
            fail("lifecycle recovery guard changed while locked", 75)

        try:
            lock_dir.lstat()
        except FileNotFoundError:
            print("changed")
            raise SystemExit(0)
        try:
            owner_path.lstat()
        except FileNotFoundError:
            print("changed")
            raise SystemExit(0)

        payload = read_lock_owner(owner_path)
        pid, nonce = validate_lock_owner(payload)
        digest = lock_owner_digest(payload)
        if (
            pid != expected_pid
            or nonce != expected_nonce
            or digest != expected_digest
        ):
            print("changed")
            raise SystemExit(0)
        if process_alive(pid):
            try:
                current_process = lock_process_snapshot(pid)
            except SystemExit:
                fail(
                    "lifecycle lock owner is live but cannot be verified; "
                    "refusing recovery",
                    75,
                )
            if current_process == payload["process"]:
                fail("lifecycle lock owner became live; refusing recovery", 75)
            fail(
                "lifecycle lock points at an unverified live process; "
                "refusing recovery",
                75,
            )

        timestamp = (
            dt.datetime.now(dt.timezone.utc)
            .strftime("%Y%m%dT%H%M%S%fZ")
        )
        quarantine = lock_dir.with_name(
            "lifecycle.lock.stale."
            f"{timestamp}.{pid}.{nonce[:12]}.{os.urandom(16).hex()}"
        )
        if os.path.lexists(quarantine):
            fail("lifecycle lock quarantine collision", 75)
        os.rename(lock_dir, quarantine)
        fsync_directory(quarantine)
        fsync_directory(lock_dir.parent)
        print(f"reclaimed:{quarantine}")
    finally:
        os.close(guard_descriptor)
elif operation == "lock-owned":
    payload = read_json(Path(args[0]))
    if (
        payload.get("schema") != LOCK_SCHEMA
        or payload.get("pid") != int(args[1])
        or payload.get("nonce") != args[2]
    ):
        fail("lifecycle lock ownership changed", 4)
else:
    fail(f"unknown server helper operation: {operation!r}")
PY
}

_current_shell_pid() {
  local runtime_dir temp_file
  runtime_dir="$(_server_runtime_dir)"
  mkdir -p "$runtime_dir"
  temp_file="$runtime_dir/.caller-pid.${RANDOM}.$$"
  _CURRENT_SHELL_PID=""
  if ! _server_python caller-pid > "$temp_file"; then
    rm -f "$temp_file"
    return 1
  fi
  IFS= read -r _CURRENT_SHELL_PID < "$temp_file" || true
  rm -f "$temp_file"
  [[ "$_CURRENT_SHELL_PID" =~ ^[0-9]+$ ]] && \
    [[ "$_CURRENT_SHELL_PID" -gt 1 ]]
}

_server_identity_file() {
  local role="${1:-}"
  printf '%s/%s.identity.json\n' "$(_server_runtime_dir)" "$role"
}

_server_launch_witness_file() {
  local role="${1:-}"
  printf '%s/%s.launch-witness.json\n' "$(_server_runtime_dir)" "$role"
}

_capture_launch_witness() {
  local role="${1:-}"
  local pid="${2:-}"
  local parent_pid="${3:-}"
  local nonce="${4:-}"
  local witness_file attempts=0
  witness_file="$(_server_launch_witness_file "$role")"
  while [[ "$attempts" -lt 20 ]]; do
    if _server_python launch-witness-write \
      "$witness_file" "$pid" "$role" "$parent_pid" "$nonce" \
      >/dev/null 2>&1; then
      return 0
    fi
    if ! _shell_tracks_running_job "$pid"; then
      return 1
    fi
    sleep 0.05
    attempts=$((attempts + 1))
  done
  return 1
}

_adopt_launch_witness() {
  local role="${1:-}"
  local pid="${2:-}"
  local executable="${3:-}"
  shift 3 || true
  local witness_file nonce argument index
  local expected_argv=("$@")
  witness_file="$(_server_launch_witness_file "$role")"
  nonce="$(_server_python launch-witness-adopt \
    "$witness_file" "$pid" "$role" 2>/dev/null)" || return 1
  for index in "${!expected_argv[@]}"; do
    argument="${expected_argv[$index]}"
    if [[ "$argument" == "__VIBECRAFTED_LAUNCH_NONCE__" ]]; then
      expected_argv[index]="$nonce"
    fi
  done
  _capture_managed_identity \
    "$role" "$pid" "$nonce" "$executable" "${expected_argv[@]}" \
    >/dev/null 2>&1 || return 1
  [[ "$(_managed_pid_state "$(_server_runtime_dir)/$role.pid" "$role")" == "live" ]] \
    || return 1
}

_managed_pid_state() {
  local pid_file="${1:-}"
  local role="${2:-}"
  local pid=""
  local identity_file=""
  local verify_status=0

  [[ -f "$pid_file" ]] || {
    printf 'missing\n'
    return 0
  }
  pid="$(_pid_file_value "$pid_file" 2>/dev/null || true)"
  if [[ ! "$pid" =~ ^[0-9]+$ ]] || [[ "$pid" -le 1 ]]; then
    printf 'invalid\n'
    return 0
  fi
  if ! kill -0 "$pid" 2>/dev/null; then
    printf 'stale\n'
    return 0
  fi
  identity_file="$(_server_identity_file "$role")"
  if [[ ! -f "$identity_file" ]]; then
    printf 'foreign\n'
    return 0
  fi
  if _server_python verify-identity "$identity_file" "$pid" "$role" >/dev/null 2>&1; then
    printf 'live\n'
    return 0
  else
    verify_status=$?
  fi
  if [[ "$verify_status" -eq 3 ]]; then
    printf 'stale\n'
  else
    printf 'foreign\n'
  fi
}

_capture_managed_identity() {
  local role="${1:-}"
  local pid="${2:-}"
  local nonce="${3:-}"
  local executable="${4:-}"
  shift 4 || true
  local identity_file
  identity_file="$(_server_identity_file "$role")"
  _server_python capture-identity \
    "$identity_file" "$pid" "$role" "$nonce" "$executable" "$@" || return 1
}

_write_managed_pid() {
  local pid_file="${1:-}"
  local pid="${2:-}"
  _server_python write-text "$pid_file" "$pid"
}

_server_endpoint() {
  local status_file="${1:-}"
  _server_python status-read "$status_file" "127.0.0.1" "3024"
}

_server_healthcheck() {
  _server_python health "${1:-}" "${2:-}"
}

_server_port_available() {
  _server_python port-free "${1:-}" "${2:-}"
}

_server_origin() {
  _server_python origin "${1:-}" "${2:-}"
}

_wait_for_pid_exit() {
  local pid="${1:-}"
  local ticks="${2:-50}"
  local elapsed=0
  while [[ "$elapsed" -lt "$ticks" ]]; do
    if ! kill -0 "$pid" 2>/dev/null; then
      return 0
    fi
    sleep 0.1
    elapsed=$((elapsed + 1))
  done
  ! kill -0 "$pid" 2>/dev/null
}

_cleanup_managed_evidence() {
  local role="${1:-}"
  local pid="${2:-}"
  local runtime_dir pid_file identity_file witness_file nonce=""
  local ready_path="" guardian_url=""
  runtime_dir="$(_server_runtime_dir)"
  pid_file="$runtime_dir/$role.pid"
  identity_file="$(_server_identity_file "$role")"
  witness_file="$(_server_launch_witness_file "$role")"

  if [[ -f "$identity_file" ]]; then
    nonce="$(_server_python identity-nonce "$identity_file" 2>/dev/null || true)"
  fi
  if [[ "$role" == "guardian" ]]; then
    ready_path="$(_pid_file_value "$runtime_dir/guardian.ready-path" 2>/dev/null || true)"
    guardian_url="$(_pid_file_value "$runtime_dir/guardian.url" 2>/dev/null || true)"
    if [[ -n "$ready_path" && -n "$nonce" && "$pid" =~ ^[0-9]+$ && -n "$guardian_url" ]]; then
      _server_python ready-remove \
        "$ready_path" "$nonce" "$pid" "$guardian_url" >/dev/null 2>&1 || true
    fi
    rm -f "$runtime_dir/guardian.url" "$runtime_dir/guardian.ready-path"
  fi
  rm -f "$pid_file" "$identity_file" "$witness_file"
}

_shell_tracks_running_job() {
  local expected_pid="${1:-}"
  local job_pid="" process_state=""
  while IFS= read -r job_pid; do
    if [[ "$job_pid" == "$expected_pid" ]]; then
      process_state="$(ps -p "$expected_pid" -o stat= 2>/dev/null || true)"
      process_state="${process_state#"${process_state%%[![:space:]]*}"}"
      [[ -n "$process_state" && "${process_state:0:1}" != "Z" ]]
      return $?
    fi
  done < <(jobs -pr)
  return 1
}

_stop_launch_owned_process() {
  local role="${1:-}"
  local label="${2:-$role}"
  local pid="${3:-}"
  local parent_pid="${4:-}"
  local nonce="${5:-}"
  local witness_file
  witness_file="$(_server_launch_witness_file "$role")"

  if ! _shell_tracks_running_job "$pid" || \
    ! _server_python launch-witness-verify \
      "$witness_file" "$pid" "$role" "$parent_pid" "$nonce" \
      >/dev/null 2>&1 || \
    ! _shell_tracks_running_job "$pid"; then
    printf "%b✗%b %s launch ownership cannot be reverified; refusing to signal PID %s and retaining evidence.\n" \
      "$_red" "$_reset" "$label" "${pid:-unknown}" >&2
    return 1
  fi

  printf "Stopping launch-owned %s (PID %s)...\n" "$role" "$pid"
  if ! kill -15 "$pid" 2>/dev/null && kill -0 "$pid" 2>/dev/null; then
    printf "%b✗%b Failed to send SIGTERM to launch-owned %s PID %s; retaining evidence.\n" \
      "$_red" "$_reset" "$role" "$pid" >&2
    return 1
  fi
  if _wait_for_pid_exit "$pid" "${VIBECRAFTED_STOP_TERM_WAIT_TICKS:-50}"; then
    wait "$pid" 2>/dev/null || true
    _cleanup_managed_evidence "$role" "$pid"
    printf "%b✓%b %s stopped.\n" "$_green" "$_reset" "$label"
    return 0
  fi

  if ! _shell_tracks_running_job "$pid" || \
    ! _server_python launch-witness-verify \
      "$witness_file" "$pid" "$role" "$parent_pid" "$nonce" \
      >/dev/null 2>&1 || \
    ! _shell_tracks_running_job "$pid"; then
    printf "%b✗%b %s launch ownership changed after SIGTERM wait; refusing SIGKILL and retaining evidence.\n" \
      "$_red" "$_reset" "$label" >&2
    return 1
  fi
  printf "%s did not exit on SIGTERM, sending SIGKILL...\n" "$label"
  if ! kill -9 "$pid" 2>/dev/null && kill -0 "$pid" 2>/dev/null; then
    printf "%b✗%b Failed to send SIGKILL to launch-owned %s PID %s; retaining evidence.\n" \
      "$_red" "$_reset" "$role" "$pid" >&2
    return 1
  fi
  if ! _wait_for_pid_exit "$pid" "${VIBECRAFTED_STOP_KILL_WAIT_TICKS:-20}"; then
    printf "%b✗%b Launch-owned %s PID %s survived SIGKILL; retaining evidence.\n" \
      "$_red" "$_reset" "$label" "$pid" >&2
    return 1
  fi
  wait "$pid" 2>/dev/null || true
  _cleanup_managed_evidence "$role" "$pid"
  printf "%b✓%b %s stopped.\n" "$_green" "$_reset" "$label"
}

_stop_managed_process() {
  local role="${1:-}"
  local label="${2:-$role}"
  local runtime_dir pid_file pid state
  runtime_dir="$(_server_runtime_dir)"
  pid_file="$runtime_dir/$role.pid"
  pid="$(_pid_file_value "$pid_file" 2>/dev/null || true)"
  state="$(_managed_pid_state "$pid_file" "$role")"

  case "$state" in
    missing)
      printf "%s is not running.\n" "$label"
      return 0
      ;;
    invalid)
      printf "%s is not running (invalid pidfile: %s).\n" "$label" "${pid:-empty}"
      _cleanup_managed_evidence "$role" "$pid"
      return 0
      ;;
    stale)
      printf "%s is not running (stale pidfile: %s).\n" "$label" "${pid:-empty}"
      _cleanup_managed_evidence "$role" "$pid"
      return 0
      ;;
    foreign)
      printf "%b✗%b %s PID file points at an unverified live process (%s); refusing to signal it and retaining evidence.\n" \
        "$_red" "$_reset" "$label" "${pid:-unknown}" >&2
      return 1
      ;;
  esac

  printf "Stopping %s (PID %s)...\n" "$role" "$pid"
  if [[ "$(_managed_pid_state "$pid_file" "$role")" != "live" ]]; then
    printf "%b✗%b %s identity changed immediately before SIGTERM; refusing to signal and retaining evidence.\n" \
      "$_red" "$_reset" "$label" >&2
    return 1
  fi
  if ! kill -15 "$pid" 2>/dev/null; then
    if kill -0 "$pid" 2>/dev/null; then
      printf "%b✗%b Failed to send SIGTERM to %s PID %s; retaining evidence.\n" \
        "$_red" "$_reset" "$role" "$pid" >&2
      return 1
    fi
  fi

  if _wait_for_pid_exit "$pid" "${VIBECRAFTED_STOP_TERM_WAIT_TICKS:-50}"; then
    _cleanup_managed_evidence "$role" "$pid"
    printf "%b✓%b %s stopped.\n" "$_green" "$_reset" "$label"
    return 0
  fi

  if [[ "$(_managed_pid_state "$pid_file" "$role")" != "live" ]]; then
    printf "%b✗%b %s identity changed after SIGTERM wait; refusing SIGKILL and retaining evidence.\n" \
      "$_red" "$_reset" "$label" >&2
    return 1
  fi
  printf "%s did not exit on SIGTERM, sending SIGKILL...\n" "$label"
  if ! kill -9 "$pid" 2>/dev/null; then
    if kill -0 "$pid" 2>/dev/null; then
      printf "%b✗%b Failed to send SIGKILL to %s PID %s; retaining evidence.\n" \
        "$_red" "$_reset" "$role" "$pid" >&2
      return 1
    fi
  fi
  if ! _wait_for_pid_exit "$pid" "${VIBECRAFTED_STOP_KILL_WAIT_TICKS:-20}"; then
    printf "%b✗%b %s PID %s survived SIGKILL; retaining PID and identity evidence.\n" \
      "$_red" "$_reset" "$label" "$pid" >&2
    return 1
  fi
  _cleanup_managed_evidence "$role" "$pid"
  printf "%b✓%b %s stopped.\n" "$_green" "$_reset" "$label"
}

_acquire_server_lifecycle_lock() {
  local runtime_dir lock_dir owner_file state attempts=0 invalid_attempts=0
  local state_kind stale_pid stale_nonce stale_digest reclaim_result
  runtime_dir="$(_server_runtime_dir)"
  lock_dir="$runtime_dir/lifecycle.lock"
  owner_file="$lock_dir/owner.json"
  mkdir -p "$runtime_dir"
  _SERVER_LIFECYCLE_LOCK_NONCE="$(_server_python nonce)"
  _current_shell_pid || return 1
  _SERVER_LIFECYCLE_LOCK_PID="$_CURRENT_SHELL_PID"
  _SERVER_LIFECYCLE_LOCK_DIR="$lock_dir"

  while [[ "$attempts" -lt "${VIBECRAFTED_LIFECYCLE_LOCK_TICKS:-100}" ]]; do
    if mkdir "$lock_dir" 2>/dev/null; then
      if ! _server_python lock-owner-write \
        "$owner_file" "$_SERVER_LIFECYCLE_LOCK_PID" "$_SERVER_LIFECYCLE_LOCK_NONCE"; then
        rmdir "$lock_dir" 2>/dev/null || true
        return 1
      fi
      return 0
    fi
    state="$(_server_python lock-state "$owner_file" 2>/dev/null || printf 'initializing')"
    case "$state" in
      live:*)
        invalid_attempts=0
        sleep 0.05
        ;;
      initializing|invalid)
        invalid_attempts=$((invalid_attempts + 1))
        if [[ "$invalid_attempts" -lt 20 ]]; then
          sleep 0.05
        else
          printf "%b✗%b Server lifecycle lock has invalid owner evidence at %s; refusing mutation.\n" \
            "$_red" "$_reset" "$owner_file" >&2
          return 75
        fi
        ;;
      stale:*)
        IFS=':' read -r state_kind stale_pid stale_nonce stale_digest <<< "$state"
        if [[ "$state_kind" != "stale" || ! "$stale_pid" =~ ^[0-9]+$ || \
          ! "$stale_nonce" =~ ^[0-9a-f]{64}$ || \
          ! "$stale_digest" =~ ^[0-9a-f]{64}$ ]]; then
          printf "%b✗%b Server lifecycle lock has malformed stale owner evidence at %s; refusing mutation.\n" \
            "$_red" "$_reset" "$owner_file" >&2
          return 75
        fi
        if reclaim_result="$(_server_python lock-reclaim \
          "$lock_dir" "$stale_pid" "$stale_nonce" "$stale_digest")"; then
          if [[ "$reclaim_result" == reclaimed:* ]]; then
            printf "Recovered stale server lifecycle lock; retained owner evidence at %s.\n" \
              "${reclaim_result#reclaimed:}"
          elif [[ "$reclaim_result" != "changed" ]]; then
            printf "%b✗%b Lifecycle lock recovery returned an invalid result; refusing mutation.\n" \
              "$_red" "$_reset" >&2
            return 75
          fi
          invalid_attempts=0
        else
          printf "%b✗%b Could not safely recover stale server lifecycle lock; owner evidence retained at %s.\n" \
            "$_red" "$_reset" "$owner_file" >&2
          return 75
        fi
        ;;
      unverified:*)
        printf "%b✗%b Server lifecycle lock is %s; owner evidence retained at %s.\n" \
          "$_red" "$_reset" "$state" "$owner_file" >&2
        return 75
        ;;
    esac
    attempts=$((attempts + 1))
  done
  state="$(_server_python lock-state "$owner_file" 2>/dev/null || printf 'unknown')"
  printf "%b✗%b Timed out waiting for server lifecycle lock (%s); owner evidence: %s\n" \
    "$_red" "$_reset" "$state" "$owner_file" >&2
  return 75
}

_release_server_lifecycle_lock() {
  local owner_file
  [[ -n "${_SERVER_LIFECYCLE_LOCK_DIR:-}" ]] || return 0
  owner_file="$_SERVER_LIFECYCLE_LOCK_DIR/owner.json"
  if _server_python lock-owned \
    "$owner_file" "$_SERVER_LIFECYCLE_LOCK_PID" "$_SERVER_LIFECYCLE_LOCK_NONCE" \
    >/dev/null 2>&1; then
    rm -f "$owner_file"
    rmdir "$_SERVER_LIFECYCLE_LOCK_DIR" 2>/dev/null || true
  else
    printf "%b✗%b Lifecycle lock ownership changed; retaining evidence at %s\n" \
      "$_red" "$_reset" "$owner_file" >&2
    return 1
  fi
}

_server_lifecycle_lock_is_owned() {
  local owner_file
  [[ -n "${_SERVER_LIFECYCLE_LOCK_DIR:-}" ]] || return 1
  [[ -n "${_SERVER_LIFECYCLE_LOCK_PID:-}" ]] || return 1
  [[ -n "${_SERVER_LIFECYCLE_LOCK_NONCE:-}" ]] || return 1
  owner_file="$_SERVER_LIFECYCLE_LOCK_DIR/owner.json"
  _server_python lock-owned \
    "$owner_file" "$_SERVER_LIFECYCLE_LOCK_PID" "$_SERVER_LIFECYCLE_LOCK_NONCE" \
    >/dev/null 2>&1
}

_with_server_lifecycle_lock() (
  _acquire_server_lifecycle_lock || exit $?
  trap '_release_server_lifecycle_lock' EXIT
  trap 'exit 129' HUP
  trap 'exit 130' INT
  trap 'exit 143' TERM
  cmd_server "$@"
)

_guardian_binary() {
  local candidate="$HOME/.local/bin/vc-guardian"
  if [[ -x "$candidate" ]]; then
    printf '%s\n' "$candidate"
    return 0
  fi
  command -v vc-guardian 2>/dev/null || return 1
}

_stop_guardian() {
  # Embedded recovery is stopped by its supervisor owner, never by signalling
  # the shared PID as though it were an independent Guardian child.
  if [[ "${VIBECRAFTED_GUARDIAN_EXECUTION:-}" == "supervisor-thread" ]]; then
    return 0
  fi
  _stop_managed_process guardian Guardian
}

_guardian_ready_receipt_state() {
  local runtime_dir pid="${1:-}" target_url="${2:-}"
  local identity_file nonce ready_path
  runtime_dir="$(_server_runtime_dir)"
  identity_file="$(_server_identity_file guardian)"
  nonce="$(_server_python identity-nonce "$identity_file" 2>/dev/null || true)"
  ready_path="$(_pid_file_value "$runtime_dir/guardian.ready-path" 2>/dev/null || true)"
  if [[ -z "$nonce" || -z "$ready_path" ]]; then
    printf 'missing\n'
    return 0
  fi
  if _server_python ready-check "$ready_path" "$nonce" "$pid" "$target_url" \
    >/dev/null 2>&1; then
    printf 'ready\n'
  else
    printf 'unready\n'
  fi
}

_ensure_guardian() {
  if [[ "${VIBECRAFTED_GUARDIAN_EXECUTION:-}" == "supervisor-thread" ]]; then
    # The supervisor proves readiness itself after this bounded server start.
    return 0
  fi
  local host="${1:-127.0.0.1}"
  local port="${2:-3024}"
  local runtime_dir guardian_pid_file guardian_url_file guardian_ready_path_file
  local guardian_log identity_file state pid guardian_bin target_url configured_url
  local nonce ready_path elapsed captured
  local identity_error launcher_pid witness_file

  runtime_dir="$(_server_runtime_dir)"
  guardian_pid_file="$runtime_dir/guardian.pid"
  guardian_url_file="$runtime_dir/guardian.url"
  guardian_ready_path_file="$runtime_dir/guardian.ready-path"
  guardian_log="$runtime_dir/guardian.log"
  identity_file="$(_server_identity_file guardian)"
  witness_file="$(_server_launch_witness_file guardian)"
  identity_error="$runtime_dir/guardian.identity-error.log"
  target_url="$(_server_origin "$host" "$port")" || return 1
  mkdir -p "$runtime_dir"
  state="$(_managed_pid_state "$guardian_pid_file" "guardian")"
  pid="$(_pid_file_value "$guardian_pid_file" 2>/dev/null || true)"
  if [[ "$state" == "foreign" ]]; then
    guardian_bin="$(_guardian_binary 2>/dev/null || true)"
    ready_path="$(_pid_file_value "$guardian_ready_path_file" 2>/dev/null || true)"
    if [[ -n "$guardian_bin" && -x "$guardian_bin" && -n "$ready_path" ]] && \
      _adopt_launch_witness guardian "$pid" "$guardian_bin" \
        "$guardian_bin" \
        --server-url "$target_url" \
        --ready-file "$ready_path" \
        --ready-nonce "__VIBECRAFTED_LAUNCH_NONCE__"; then
      state="$(_managed_pid_state "$guardian_pid_file" "guardian")"
    fi
  fi

  if [[ "$state" == "live" ]]; then
    configured_url="$(_pid_file_value "$guardian_url_file" 2>/dev/null || true)"
    if [[ "$configured_url" == "$target_url" && \
      "$(_guardian_ready_receipt_state "$pid" "$target_url")" == "ready" ]]; then
      rm -f "$witness_file"
      printf "Guardian is already running (PID %s) for %s\n" "$pid" "$target_url"
      return 0
    fi
    if [[ "$configured_url" == "$target_url" ]]; then
      printf "Guardian is live but has no valid SSE readiness receipt. Restarting sidecar...\n"
    else
      printf "Guardian endpoint changed (%s -> %s). Restarting sidecar...\n" \
        "${configured_url:-unknown}" "$target_url"
    fi
    _stop_guardian || return 1
    state="missing"
    pid=""
  fi

  case "$state" in
    foreign)
      printf "%b✗%b Guardian PID file points at an unverified live process (%s); refusing to replace it.\n" \
        "$_red" "$_reset" "${pid:-unknown}" >&2
      return 1
      ;;
    invalid|stale)
      printf "Stale guardian PID file found (%s: %s). Healing sidecar...\n" "$state" "${pid:-empty}"
      _stop_guardian || return 1
      ;;
  esac

  guardian_bin="$(_guardian_binary 2>/dev/null || true)"
  if [[ -z "$guardian_bin" || ! -x "$guardian_bin" ]]; then
    printf "%b✗%b vc-guardian entrypoint not found or not executable. Reinstall vibecrafted-core.\n" "$_red" "$_reset" >&2
    return 1
  fi

  printf "Starting process guardian for %s...\n" "$target_url"
  nonce="$(_server_python nonce)"
  ready_path="$runtime_dir/guardian.ready.$nonce.json"
  _current_shell_pid || return 1
  launcher_pid="$_CURRENT_SHELL_PID"
  VIBECRAFTED_PROCESS_NONCE="$nonce" nohup "$guardian_bin" \
    --server-url "$target_url" \
    --ready-file "$ready_path" \
    --ready-nonce "$nonce" \
    > "$guardian_log" 2>&1 < /dev/null &
  pid=$!
  _write_managed_pid "$guardian_pid_file" "$pid"
  if ! _capture_launch_witness guardian "$pid" "$launcher_pid" "$nonce"; then
    sleep 0.05
    if _shell_tracks_running_job "$pid"; then
      printf "%b✗%b Guardian launch ownership could not be captured; retaining PID evidence and refusing to signal it.\n" \
        "$_red" "$_reset" >&2
    else
      wait "$pid" 2>/dev/null || true
      _cleanup_managed_evidence guardian "$pid"
      printf "%b✗%b Guardian failed SSE readiness: exited before launch identity capture. Check %s\n" \
        "$_red" "$_reset" "$guardian_log" >&2
    fi
    return 1
  fi
  _server_python write-text "$guardian_url_file" "$target_url"
  _server_python write-text "$guardian_ready_path_file" "$ready_path"

  # `$!` initially belongs to nohup; capture only after its exec handoff.
  sleep 0.1
  captured=0
  elapsed=0
  while [[ "$elapsed" -lt 20 ]]; do
    if _capture_managed_identity guardian "$pid" "$nonce" "$guardian_bin" \
      "$guardian_bin" \
      --server-url "$target_url" \
      --ready-file "$ready_path" \
      --ready-nonce "$nonce" \
      > /dev/null 2> "$identity_error"; then
      captured=1
      rm -f "$identity_error"
      break
    fi
    if ! kill -0 "$pid" 2>/dev/null; then
      break
    fi
    sleep 0.05
    elapsed=$((elapsed + 1))
  done
  if [[ "$captured" -ne 1 ]]; then
    if kill -0 "$pid" 2>/dev/null; then
      printf "%b✗%b Guardian identity could not be captured; cleaning up the launch-owned child.\n" \
        "$_red" "$_reset" >&2
      _stop_launch_owned_process \
        guardian Guardian "$pid" "$launcher_pid" "$nonce" || return 1
    else
      _server_python ready-remove "$ready_path" "$nonce" "$pid" "$target_url" \
        >/dev/null 2>&1 || true
      rm -f "$guardian_pid_file" "$guardian_url_file" \
        "$guardian_ready_path_file" "$identity_file"
      printf "%b✗%b Guardian failed SSE readiness: exited before identity capture. Check %s\n" \
        "$_red" "$_reset" "$guardian_log" >&2
    fi
    return 1
  fi

  elapsed=0
  while [[ "$elapsed" -lt "${VIBECRAFTED_GUARDIAN_READY_TICKS:-50}" ]]; do
    if [[ "$(_guardian_ready_receipt_state "$pid" "$target_url")" == "ready" ]]; then
      state="$(_managed_pid_state "$guardian_pid_file" "guardian")"
      if [[ "$state" == "foreign" ]] && \
        _capture_managed_identity guardian "$pid" "$nonce" "$guardian_bin" \
          "$guardian_bin" \
          --server-url "$target_url" \
          --ready-file "$ready_path" \
          --ready-nonce "$nonce" \
          > /dev/null 2> "$identity_error"; then
        rm -f "$identity_error"
        state="$(_managed_pid_state "$guardian_pid_file" "guardian")"
      fi
      if [[ "$state" == "live" ]]; then
        rm -f "$witness_file"
        printf "%b✓%b Guardian is running (PID %s).\n" "$_green" "$_reset" "$pid"
        return 0
      fi
      break
    fi
    if ! kill -0 "$pid" 2>/dev/null; then
      break
    fi
    sleep 0.1
    elapsed=$((elapsed + 1))
  done

  state="$(_managed_pid_state "$guardian_pid_file" "guardian")"
  if [[ "$state" == "live" ]]; then
    _stop_guardian || true
  elif [[ "$state" == "foreign" && -f "$witness_file" ]]; then
    _stop_launch_owned_process \
      guardian Guardian "$pid" "$launcher_pid" "$nonce" || true
  elif [[ "$state" == "stale" || "$state" == "invalid" ]]; then
    _stop_guardian >/dev/null || true
  fi
  printf "%b✗%b Guardian failed SSE readiness. Check %s\n" \
    "$_red" "$_reset" "$guardian_log" >&2
  return 1
}

cmd_server() {
  local verb="${1:-help}"
  shift || true
  local lifecycle_mutation=0

  if [[ "$verb" == "-h" || "$verb" == "--help" || "$verb" == "help" ]]; then
    cmd_server_help
    return 0
  fi
  # Every remaining verb drives the internal helper (locks, probes, status).
  # Resolve its interpreter once, up front, so a missing or corrupt owned
  # interpreter is reported here instead of vanishing inside a silenced
  # `$(... 2>/dev/null)` probe further down.
  _SERVER_HELPER_PYTHON="$(_server_helper_python)" || return $?
  case "$verb" in
    install|reconcile|uninstall)
      # Persistent service management lives under `service`; the bare verb is
      # what operators actually type first. Route it instead of refusing.
      set -- "$verb" "$@"
      verb="service"
      ;;
  esac
  case "$verb:${1:-}" in
    start:*|stop:*)
      if [[ "${VIBECRAFTED_SERVER_SUPERVISOR_CHILD:-0}" != "1" ]]; then
        lifecycle_mutation=1
      fi
      ;;
    service:install|service:reconcile|service:restart|service:start|service:stop|service:uninstall)
      lifecycle_mutation=1
      ;;
  esac
  if [[ "$lifecycle_mutation" -eq 1 ]] && ! _server_lifecycle_lock_is_owned; then
    _with_server_lifecycle_lock "$verb" "$@"
    return $?
  fi
  if [[ "$verb" == "start" && \
    "${VIBECRAFTED_SERVER_SUPERVISOR_CHILD:-0}" != "1" ]]; then
    _server_supervisor_cli service start "$@"
    return $?
  fi
  if [[ "$verb" == "stop" && \
    "${VIBECRAFTED_SERVER_SUPERVISOR_CHILD:-0}" != "1" ]]; then
    _server_supervisor_cli manual-stop "$@"
    return $?
  fi
  if [[ "$verb" == "stop" && \
    "${VIBECRAFTED_SERVER_SUPERVISOR_CHILD:-0}" == "1" && \
    -n "${VIBECRAFTED_TEST_SERVER_STOP_DELAY:-}" ]]; then
    sleep "$VIBECRAFTED_TEST_SERVER_STOP_DELAY"
  fi

  case "$verb" in
    start)
      local port="3024"
      local host="127.0.0.1"
      local endpoint=""
      while [[ $# -gt 0 ]]; do
        case "$1" in
          --port|-p)
            if [[ $# -lt 2 ]]; then
              printf "%b✗%b %s requires a value.\n" "$_red" "$_reset" "$1" >&2
              return 2
            fi
            port="$2"
            shift 2
            ;;
          --host|-h)
            if [[ $# -lt 2 ]]; then
              printf "%b✗%b %s requires a value.\n" "$_red" "$_reset" "$1" >&2
              return 2
            fi
            host="$2"
            shift 2
            ;;
          *)
            printf "%b✗%b Unknown server start option: %s\n" \
              "$_red" "$_reset" "$1" >&2
            return 2
            ;;
        esac
      done
      if ! endpoint="$(_server_python validate-endpoint "$host" "$port")"; then
        printf "%b✗%b Invalid server endpoint.\n" "$_red" "$_reset" >&2
        return 2
      fi
      IFS=$'\t' read -r host port <<< "$endpoint"

      local runtime_root server_bin site_root
      runtime_root="$(_runtime_payload_root 2>/dev/null || true)"
      server_bin="${runtime_root:+$runtime_root/bin/vc-server}"
      site_root="${runtime_root:+$runtime_root/server/site}"
      [[ -n "$server_bin" ]] || server_bin="$HOME/.local/bin/vc-server"
      [[ -n "$site_root" ]] || \
        site_root="${VIBECRAFTED_RUNTIME_HOME:-$HOME/.local/share/vibecrafted}/server/site"

      # 1. Check if already running
      local runtime_dir
      runtime_dir="$(_server_runtime_dir)"
      local pid_file="$runtime_dir/server.pid"
      local status_file="$runtime_dir/status.json"
      if [[ -f "$pid_file" ]]; then
        local existing_pid existing_state
        existing_pid="$(_pid_file_value "$pid_file" 2>/dev/null || true)"
        existing_state="$(_managed_pid_state "$pid_file" "server")"
        if [[ "$existing_state" == "foreign" ]] && \
          [[ -x "$server_bin" ]] && \
          _adopt_launch_witness \
            server "$existing_pid" "$server_bin" \
            "$server_bin"; then
          existing_state="$(_managed_pid_state "$pid_file" "server")"
        fi
        if [[ "$existing_state" == "live" ]]; then
          # Check health
          local actual_host="127.0.0.1"
          local actual_port="3024"
          if ! endpoint="$(_server_endpoint "$status_file")"; then
            printf "%b✗%b Managed server status has an invalid endpoint; refusing lifecycle mutation.\n" \
              "$_red" "$_reset" >&2
            return 1
          fi
          IFS=$'\t' read -r actual_host actual_port <<< "$endpoint"
          if _server_healthcheck "$actual_host" "$actual_port" >/dev/null 2>&1; then
            rm -f "$(_server_launch_witness_file server)"
            printf "Server is already running (PID %s) at %s\n" \
              "$existing_pid" "$(_server_origin "$actual_host" "$actual_port")"
            _ensure_guardian "$actual_host" "$actual_port"
            return $?
          else
            # Stale PID or unhealthy - stop/cleanup
            printf "Unhealthy or stale server process found at PID %s. Cleaning up...\n" "$existing_pid"
            _stop_guardian || return 1
            if ! _stop_managed_process server Server; then
              if [[ -f "$(_server_launch_witness_file server)" ]] && \
                _adopt_launch_witness \
                  server "$existing_pid" "$server_bin" \
                  "$server_bin"; then
                _stop_managed_process server Server || return 1
              else
                return 1
              fi
            fi
          fi
        elif [[ "$existing_state" == "foreign" ]]; then
          printf "%b✗%b Server PID file points at an unverified live process (%s); refusing to signal or replace it.\n" \
            "$_red" "$_reset" "${existing_pid:-unknown}" >&2
          return 1
        else
          printf "Healing %s server PID evidence (%s).\n" \
            "$existing_state" "${existing_pid:-empty}"
          local configured_guardian_url requested_guardian_url
          configured_guardian_url="$(_pid_file_value "$runtime_dir/guardian.url" 2>/dev/null || true)"
          requested_guardian_url="$(_server_origin "$host" "$port")"
          if [[ -n "$configured_guardian_url" && \
            "$configured_guardian_url" != "$requested_guardian_url" ]]; then
            printf "Guardian endpoint changed (%s -> %s). Restarting sidecar...\n" \
              "$configured_guardian_url" "$requested_guardian_url"
          fi
          _stop_guardian || return 1
          _stop_managed_process server Server || return 1
        fi
      fi

      # 2. Pre-check port sanity
      if ! _server_port_available "$host" "$port" >/dev/null 2>&1; then
        printf "%b✗%b Endpoint %s is unavailable.\n" \
          "$_red" "$_reset" "$(_server_origin "$host" "$port")" >&2
        return 1
      fi

      # 3. Locate binary & site root
      if [[ ! -x "$server_bin" ]]; then
        printf "%b✗%b vc-server binary not found at %s. Please run 'make install-all' or 'make install-server' first.\n" "$_red" "$_reset" "$server_bin" >&2
        return 1
      fi

      if [[ ! -d "$site_root" ]]; then
        printf "%b✗%b site assets directory not found at %s. Please run 'make install-all' or 'make install-server' first.\n" "$_red" "$_reset" "$site_root" >&2
        return 1
      fi

      # 4. Start process
      mkdir -p "$runtime_dir"
      printf "Starting local control-plane viewer at %s...\n" \
        "$(_server_origin "$host" "$port")"

      local server_nonce
      local identity_error
      local server_launcher_pid
      local server_witness_file
      identity_error="$runtime_dir/server.identity-error.log"
      server_witness_file="$(_server_launch_witness_file server)"
      server_nonce="$(_server_python nonce)"
      _current_shell_pid || return 1
      server_launcher_pid="$_CURRENT_SHELL_PID"
      VC_SERVER_ADDR="$host:$port" \
      VC_SERVER_SITE_ROOT="$site_root" \
      VIBECRAFTED_HOME="${VIBECRAFTED_HOME:-$HOME/.vibecrafted}" \
      VIBECRAFTED_PROCESS_NONCE="$server_nonce" \
        nohup "$server_bin" > "$runtime_dir/server.log" 2>&1 < /dev/null &
      local server_pid=$!
      local captured=0
      _write_managed_pid "$pid_file" "$server_pid"
      if ! _capture_launch_witness \
        server "$server_pid" "$server_launcher_pid" "$server_nonce"; then
        sleep 0.05
        if _shell_tracks_running_job "$server_pid"; then
          printf "%b✗%b Server launch ownership could not be captured; retaining PID evidence and refusing to signal it.\n" \
            "$_red" "$_reset" >&2
          _server_python write-status \
            "$status_file" "$server_pid" "$host" "$port" "failed"
        else
          wait "$server_pid" 2>/dev/null || true
          _cleanup_managed_evidence server "$server_pid"
          _server_python write-status \
            "$status_file" "none" "$host" "$port" "failed"
        fi
        return 1
      fi
      _server_python write-status \
        "$status_file" "$server_pid" "$host" "$port" "starting"
      # `$!` initially belongs to nohup; capture only after its exec handoff.
      sleep 0.1
      local capture_elapsed=0
      while [[ "$capture_elapsed" -lt 20 ]]; do
        if _capture_managed_identity server "$server_pid" "$server_nonce" \
          "$server_bin" "$server_bin" > /dev/null 2> "$identity_error"; then
          captured=1
          rm -f "$identity_error"
          break
        fi
        if ! kill -0 "$server_pid" 2>/dev/null; then
          break
        fi
        sleep 0.05
        capture_elapsed=$((capture_elapsed + 1))
      done
      if [[ "$captured" -ne 1 ]]; then
        if kill -0 "$server_pid" 2>/dev/null; then
          printf "%b✗%b Server identity could not be captured; cleaning up the launch-owned child.\n" \
            "$_red" "$_reset" >&2
          if _stop_launch_owned_process \
            server Server "$server_pid" "$server_launcher_pid" "$server_nonce"; then
            _server_python update-status "$status_file" "failed" "none"
          else
            _server_python update-status "$status_file" "failed" "$server_pid"
          fi
        else
          _cleanup_managed_evidence server "$server_pid"
          printf "%b✗%b Server exited before identity capture. Check %s/server.log\n" \
            "$_red" "$_reset" "$runtime_dir" >&2
        fi
        return 1
      fi

      # 5. Wait for health
      local healthy=0
      local current_state
      local health_error="$runtime_dir/server.health-error.log"
      if _server_python health-wait "$host" "$port" "$server_pid" "15" \
        > /dev/null 2> "$health_error"; then
        current_state="$(_managed_pid_state "$pid_file" "server")"
        if [[ "$current_state" == "foreign" ]] && \
          _capture_managed_identity server "$server_pid" "$server_nonce" \
            "$server_bin" "$server_bin" \
            > /dev/null 2> "$identity_error"; then
          rm -f "$identity_error"
          current_state="$(_managed_pid_state "$pid_file" "server")"
        fi
        if [[ "$current_state" != "live" ]]; then
          printf "%b✗%b Server became healthy but its managed identity could not be verified.\n" \
            "$_red" "$_reset" >&2
          if _stop_launch_owned_process \
            server Server "$server_pid" "$server_launcher_pid" "$server_nonce"; then
            _server_python update-status "$status_file" "failed" "none"
          else
            _server_python update-status "$status_file" "failed" "$server_pid"
          fi
          return 1
        fi
        rm -f "$server_witness_file" "$health_error"
        healthy=1
      elif ! kill -0 "$server_pid" 2>/dev/null; then
        current_state="$(_managed_pid_state "$pid_file" "server")"
        printf "%b✗%b Server process died immediately. Check log at %s/server.log\n" "$_red" "$_reset" "$runtime_dir" >&2
        if [[ "$current_state" == "stale" || "$current_state" == "invalid" ]]; then
          _stop_managed_process server Server >/dev/null || true
        fi
        _server_python update-status "$status_file" "failed" "none"
        return 1
      fi

      if [[ $healthy -eq 1 ]]; then
        printf "%b✓%b Server is up and healthy at %s\n" \
          "$_green" "$_reset" "$(_server_origin "$host" "$port")"
        _server_python update-status "$status_file" "running" "$server_pid"
        if ! _ensure_guardian "$host" "$port"; then
          printf "%b✗%b Guardian startup failed; rolling back the newly started server.\n" "$_red" "$_reset" >&2
          if _stop_managed_process server Server; then
            _server_python update-status "$status_file" "failed" "none"
          else
            _server_python update-status "$status_file" "failed" "$server_pid"
          fi
          return 1
        fi
        return 0
      else
        local health_detail=""
        health_detail="$(_pid_file_value "$health_error" 2>/dev/null || true)"
        printf "%b✗%b Server started but failed health check at %s/api/health after 15 seconds%s.\n" \
          "$_red" "$_reset" "$(_server_origin "$host" "$port")" \
          "${health_detail:+: $health_detail}" >&2
        if _stop_managed_process server Server; then
          _server_python update-status "$status_file" "failed" "none"
        elif [[ -f "$server_witness_file" ]] && \
          _stop_launch_owned_process \
            server Server "$server_pid" "$server_launcher_pid" "$server_nonce"; then
          _server_python update-status "$status_file" "failed" "none"
        else
          _server_python update-status "$status_file" "failed" "$server_pid"
        fi
        return 1
      fi
      ;;
    stop)
      local runtime_dir
      runtime_dir="$(_server_runtime_dir)"
      local pid_file="$runtime_dir/server.pid"
      local status_file="$runtime_dir/status.json"
      local stop_errors=0
      _stop_guardian || stop_errors=1
      if ! _stop_managed_process server Server; then
        stop_errors=1
      fi
      if [[ "$(_managed_pid_state "$pid_file" "server")" == "missing" && \
        -f "$status_file" ]]; then
        _server_python update-status "$status_file" "stopped" "none"
      fi
      return "$stop_errors"
      ;;
    supervisor-pair-health)
      _server_python pair-health "$(_server_runtime_dir)"
      return $?
      ;;
    status)
      local runtime_dir
      runtime_dir="$(_server_runtime_dir)"
      if [[ -f "$runtime_dir/guardian.execution.json" ]]; then
        _server_supervisor_cli runtime-status || return $?
        _server_python pair-health "$runtime_dir"
        return $?
      fi
      local pid_file="$runtime_dir/server.pid"
      local guardian_pid_file="$runtime_dir/guardian.pid"
      local status_file="$runtime_dir/status.json"
      local pid=""
      local guardian_pid=""
      local guardian_url=""
      local host="127.0.0.1"
      local port="3024"
      local server_state guardian_state
      local server_healthy=0
      local has_errors=0
      local endpoint_valid=1
      local endpoint=""
      local target_url=""

      _server_supervisor_cli runtime-status || has_errors=1

      if endpoint="$(_server_endpoint "$status_file" 2>/dev/null)"; then
        IFS=$'\t' read -r host port <<< "$endpoint"
        target_url="$(_server_origin "$host" "$port")"
      else
        printf "Server status: INVALID-ENDPOINT (refusing status.json values)\n"
        endpoint_valid=0
        has_errors=1
      fi

      if [[ -f "$pid_file" ]]; then
        pid="$(_pid_file_value "$pid_file" 2>/dev/null || true)"
      fi
      guardian_pid="$(_pid_file_value "$guardian_pid_file" 2>/dev/null || true)"
      guardian_url="$(_pid_file_value "$runtime_dir/guardian.url" 2>/dev/null || true)"
      server_state="$(_managed_pid_state "$pid_file" "server")"
      guardian_state="$(_managed_pid_state "$guardian_pid_file" "guardian")"

      case "$server_state" in
        missing)
          printf "Server: STOPPED\n"
          ;;
        invalid|stale)
          printf "Server: STALE-PID (%s: %s)\n" "$server_state" "${pid:-empty}"
          has_errors=1
          ;;
        foreign)
          printf "Server: PID-MISMATCH (%s is live but identity is unverified)\n" "${pid:-unknown}"
          has_errors=1
          ;;
        live)
          if [[ "$endpoint_valid" -eq 1 ]] && \
            _server_healthcheck "$host" "$port" >/dev/null 2>&1; then
            server_healthy=1
            printf "Server: RUNNING (PID %s, listening on %s)\n" "$pid" "$target_url"
          else
            printf "Server: UNHEALTHY (PID %s, endpoint is invalid or not responding)\n" "$pid"
            has_errors=1
          fi
          ;;
      esac

      case "$guardian_state" in
        missing)
          printf "Guardian: STOPPED\n"
          [[ $server_healthy -eq 0 ]] || has_errors=1
          ;;
        invalid|stale)
          printf "Guardian: STALE-PID (%s: %s)\n" "$guardian_state" "${guardian_pid:-empty}"
          has_errors=1
          ;;
        foreign)
          printf "Guardian: PID-MISMATCH (%s is live but identity is unverified)\n" "${guardian_pid:-unknown}"
          has_errors=1
          ;;
        live)
          if [[ $server_healthy -eq 1 && "$guardian_url" == "$target_url" && \
            "$(_guardian_ready_receipt_state "$guardian_pid" "$target_url")" == "ready" ]]; then
            printf "Guardian: RUNNING (PID %s, server %s)\n" "$guardian_pid" "$target_url"
          elif [[ $server_healthy -eq 1 && "$guardian_url" == "$target_url" ]]; then
            printf "Guardian: UNREADY (PID %s has no valid SSE readiness receipt)\n" "$guardian_pid"
            has_errors=1
          elif [[ $server_healthy -eq 1 ]]; then
            printf "Guardian: MISCONFIGURED (PID %s, %s != %s)\n" \
              "$guardian_pid" "${guardian_url:-unknown}" "$target_url"
            has_errors=1
          else
            printf "Guardian: ORPHANED (PID %s is live without a healthy managed server)\n" "$guardian_pid"
            has_errors=1
          fi
          ;;
      esac
      return "$has_errors"
      ;;
    service)
      _server_supervisor_cli service "$@"
      return $?
      ;;
    open)
      local status_file
      status_file="$(_server_runtime_dir)/status.json"
      local host="127.0.0.1"
      local port="3024"
      local endpoint=""
      local target_url=""
      if ! endpoint="$(_server_endpoint "$status_file")"; then
        printf "%b✗%b Server status contains an invalid endpoint; refusing to open it.\n" \
          "$_red" "$_reset" >&2
        return 1
      fi
      IFS=$'\t' read -r host port <<< "$endpoint"
      target_url="$(_server_origin "$host" "$port")"

      if _server_healthcheck "$host" "$port" >/dev/null 2>&1; then
        printf "Opening %s/ in browser...\n" "$target_url"
        if command -v open >/dev/null 2>&1; then
          open "$target_url/"
        elif command -v xdg-open >/dev/null 2>&1; then
          xdg-open "$target_url/"
        else
          printf "Please open %s/ manually.\n" "$target_url"
        fi
        return 0
      else
        printf "%b✗%b Server is not running or unhealthy. Start it first with 'vibecrafted server start'.\n" "$_red" "$_reset" >&2
        return 1
      fi
      ;;
    doctor)
      local has_errors=0
      printf "Checking vibecrafted-server and process guardian installation/runtime health...\n"
      _server_supervisor_cli runtime-status || has_errors=1

      # 1. Binary check
      local runtime_root server_bin site_root
      runtime_root="$(_runtime_payload_root 2>/dev/null || true)"
      server_bin="${runtime_root:+$runtime_root/bin/vc-server}"
      site_root="${runtime_root:+$runtime_root/server/site}"
      [[ -n "$server_bin" ]] || server_bin="$HOME/.local/bin/vc-server"
      [[ -n "$site_root" ]] || \
        site_root="${VIBECRAFTED_RUNTIME_HOME:-$HOME/.local/share/vibecrafted}/server/site"
      if [[ -f "$server_bin" ]]; then
        if [[ -x "$server_bin" ]]; then
          printf "  [%b✓%b] Binary present and executable at %s\n" "$_green" "$_reset" "$server_bin"
        else
          printf "  [%b✗%b] Binary at %s is not executable\n" "$_red" "$_reset" "$server_bin"
          has_errors=1
        fi
      else
        printf "  [%b✗%b] Binary missing at %s\n" "$_red" "$_reset" "$server_bin"
        has_errors=1
      fi
      local compat_server_bin="$HOME/.local/bin/vibecrafted-server-web"
      if [[ -f "$compat_server_bin" ]]; then
        printf "  [%b✓%b] Compatibility binary present at %s\n" "$_green" "$_reset" "$compat_server_bin"
      else
        printf "  [%b!%b] Compatibility binary missing at %s\n" "$_yellow" "$_reset" "$compat_server_bin"
      fi
      printf "  Guardian recovery owner: vc-server-supervisor (embedded thread)\n"

      # 2. Site root & Fonts check
      if [[ -d "$site_root" ]]; then
        printf "  [%b✓%b] Site root present at %s\n" "$_green" "$_reset" "$site_root"
        if [[ -d "$site_root/fonts" ]]; then
          local font_count
          font_count=$(find "$site_root/fonts" -type f | wc -l | tr -d ' ')
          if [[ "$font_count" -gt 0 ]]; then
            printf "  [%b✓%b] Fonts present in %s/fonts (%s files)\n" "$_green" "$_reset" "$site_root" "$font_count"
          else
            printf "  [%b✗%b] Fonts directory is empty: %s/fonts\n" "$_red" "$_reset" "$site_root"
            has_errors=1
          fi
        else
          printf "  [%b✗%b] Fonts directory missing at %s/fonts\n" "$_red" "$_reset" "$site_root"
          has_errors=1
        fi
      else
        printf "  [%b✗%b] Site root missing at %s\n" "$_red" "$_reset" "$site_root"
        has_errors=1
      fi

      # 3. Control plane check
      local cp_dir="${VIBECRAFTED_HOME:-$HOME/.vibecrafted}/control_plane"
      if [[ -d "$cp_dir" ]]; then
        printf "  [%b✓%b] Control plane directory exists and is readable at %s\n" "$_green" "$_reset" "$cp_dir"
      else
        printf "  [%b!%b] Control plane directory not found at %s (this is fine; it will be created when runs start)\n" "$_yellow" "$_reset" "$cp_dir"
      fi

      # 4. Pid-vs-http coherence check
      local runtime_dir
      runtime_dir="$(_server_runtime_dir)"
      local pid_file="$runtime_dir/server.pid"
      local guardian_pid_file="$runtime_dir/guardian.pid"
      local status_file="$runtime_dir/status.json"
      local pid=""
      local guardian_pid=""
      local guardian_url=""
      local host="127.0.0.1"
      local port="3024"
      local server_state guardian_state
      local server_healthy=0
      local endpoint_valid=1
      local endpoint=""
      local target_url=""

      if endpoint="$(_server_endpoint "$status_file" 2>/dev/null)"; then
        IFS=$'\t' read -r host port <<< "$endpoint"
        target_url="$(_server_origin "$host" "$port")"
      else
        printf "  [%b✗%b] status.json contains an invalid endpoint; values were not used\n" \
          "$_red" "$_reset"
        endpoint_valid=0
        has_errors=1
      fi

      if [[ -f "$pid_file" ]]; then
        pid="$(_pid_file_value "$pid_file" 2>/dev/null || true)"
      fi
      guardian_pid="$(_pid_file_value "$guardian_pid_file" 2>/dev/null || true)"
      guardian_url="$(_pid_file_value "$runtime_dir/guardian.url" 2>/dev/null || true)"
      server_state="$(_managed_pid_state "$pid_file" "server")"
      guardian_state="$(_managed_pid_state "$guardian_pid_file" "guardian")"

      if [[ "$server_state" == "live" ]]; then
        printf "  [%b✓%b] Server PID %s matches its durable process identity\n" \
          "$_green" "$_reset" "$pid"

        if [[ "$endpoint_valid" -eq 1 ]] && \
          _server_healthcheck "$host" "$port" >/dev/null 2>&1; then
          server_healthy=1
          printf "  [%b✓%b] HTTP server is healthy and responding at %s\n" \
            "$_green" "$_reset" "$target_url"
        else
          printf "  [%b✗%b] Process %s is running but its HTTP endpoint is invalid or not responding\n" \
            "$_red" "$_reset" "$pid"
          has_errors=1
        fi
      elif [[ "$server_state" == "missing" ]]; then
        printf "  [i] Server is stopped (no pid file)\n"
        if ! _server_port_available "127.0.0.1" "3024" >/dev/null 2>&1; then
          printf "  [%b!%b] Port 3024 is in use by another process (non-fatal, but 'vibecrafted server start' without custom port will fail)\n" "$_yellow" "$_reset"
        else
          printf "  [%b✓%b] Default port 3024 is free\n" "$_green" "$_reset"
        fi
      elif [[ "$server_state" == "foreign" ]]; then
        printf "  [%b✗%b] Server PID %s is live but its durable identity is unverified\n" \
          "$_red" "$_reset" "${pid:-unknown}"
        has_errors=1
      else
        printf "  [%b✗%b] Stale server PID file (%s: %s)\n" "$_red" "$_reset" "$server_state" "${pid:-empty}"
        has_errors=1
      fi

      if [[ -f "$runtime_dir/guardian.execution.json" ]]; then
        if _server_python pair-health "$runtime_dir"; then
          printf "  [%b✓%b] Embedded Guardian readiness verified\n" "$_green" "$_reset"
        else
          has_errors=1
        fi
      else
      case "$guardian_state" in
        missing)
          if [[ $server_healthy -eq 1 ]]; then
            printf "  [%b✗%b] Guardian is stopped while the server is healthy\n" "$_red" "$_reset"
            has_errors=1
          else
            printf "  [i] Guardian is stopped (no pid file)\n"
          fi
          ;;
        live)
          if [[ $server_healthy -eq 1 && "$guardian_url" == "$target_url" && \
            "$(_guardian_ready_receipt_state "$guardian_pid" "$target_url")" == "ready" ]]; then
            printf "  [%b✓%b] Guardian PID %s has durable identity and a valid SSE readiness receipt\n" \
              "$_green" "$_reset" "$guardian_pid"
          elif [[ $server_healthy -eq 1 && "$guardian_url" == "$target_url" ]]; then
            printf "  [%b✗%b] Guardian PID %s is live but lacks its exact SSE readiness receipt\n" \
              "$_red" "$_reset" "$guardian_pid"
            has_errors=1
          elif [[ $server_healthy -eq 1 ]]; then
            printf "  [%b✗%b] Guardian PID %s targets %s instead of %s\n" \
              "$_red" "$_reset" "$guardian_pid" "${guardian_url:-unknown}" "$target_url"
            has_errors=1
          else
            printf "  [%b✗%b] Guardian PID %s is orphaned without a healthy managed server\n" "$_red" "$_reset" "$guardian_pid"
            has_errors=1
          fi
          ;;
        foreign)
          printf "  [%b✗%b] Guardian PID %s is live but its durable identity is unverified\n" \
            "$_red" "$_reset" "${guardian_pid:-unknown}"
          has_errors=1
          ;;
        *)
          printf "  [%b✗%b] Stale guardian PID file (%s: %s)\n" "$_red" "$_reset" "$guardian_state" "${guardian_pid:-empty}"
          has_errors=1
          ;;
      esac

      fi
      if [[ "$server_state" == "missing" && "$guardian_state" == "missing" ]]; then
        printf "  [%b✓%b] Server/guardian lifecycle is cleanly stopped\n" "$_green" "$_reset"
      fi

      if [[ $has_errors -eq 0 ]]; then
        printf "\n%b✓%b Server and guardian doctor check passed.\n" "$_green" "$_reset"
        return 0
      else
        printf "\n%b✗%b Server and guardian doctor check failed.\n" "$_red" "$_reset" >&2
        return 1
      fi
      ;;
    caretaker)
      # The one caretaker truth. Builds the `vibecrafted.caretaker.v1` envelope
      # (server identity + observability + resume backlog + control-plane
      # upkeep), publishes it into the control plane so
      # `GET /api/control/caretaker` serves the same bytes, and prints the
      # already-derived verdict. Readers render that verdict; none re-derive it,
      # which is what keeps the tray, the CLI and the HTTP surface from drifting
      # into three opinions about one server.
      local core_dir publish_flag="--publish" caretaker_arg
      for caretaker_arg in "$@"; do
        [[ "$caretaker_arg" == "--read" ]] && publish_flag=""
      done
      core_dir="$(_core_module_dir 2>/dev/null || true)"
      [[ -n "$core_dir" ]] || {
        printf '%b✗%b Vibecrafted Core module not found.\n' "$_red" "$_reset" >&2
        return 1
      }
      PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
        "$(_vibecrafted_python)" -m vibecrafted_core.caretaker \
        ${publish_flag:+"$publish_flag"} "$@"
      ;;
    *)
      printf "%b✗%b Unknown server action: %s\n" "$_red" "$_reset" "$verb" >&2
      cmd_server_help >&2
      return 1
      ;;
  esac
}


cmd_tui() {
  local app_dir binary_path deck_path state_root runtime_root
  if _is_help_flag "${1:-}"; then
    cmd_tui_help
    return 0
  fi
  app_dir="$(_voc_app_dir 2>/dev/null || true)"
  runtime_root="$(_runtime_payload_root 2>/dev/null || true)"
  binary_path="$(_resolve_voc_binary 2>/dev/null || true)"
  deck_path="$(_repo_source_root 2>/dev/null || true)"
  if [[ -z "$deck_path" && -f "$crafted_tools/scripts/vibecrafted" ]]; then
    deck_path="$crafted_tools"
  fi
  if [[ -z "$deck_path" && -n "$app_dir" ]]; then
    deck_path="$(cd "$app_dir/.." && pwd)"
  fi
  [[ -n "$deck_path" ]] || deck_path="$(_script_repo_root)"
  deck_path="$deck_path/scripts/vibecrafted"
  state_root="$crafted_home/control_plane"

  # Voc draws its loading state immediately and reads the canonical projection
  # on its existing refresh worker; launching must not wait for a full sync.

  if [[ -n "${binary_path:-}" && -x "$binary_path" ]]; then
    "$binary_path" --state-root "$state_root" --deck "$deck_path" "$@"
    return $?
  fi

  if [[ -n "$runtime_root" ]]; then
    printf '%b✗%b Installed Runtime Pack is missing its VOC binary.\n' "$_red" "$_reset" >&2
    printf '  Repair the installed product Runtime Pack, then retry: vibecrafted update\n' >&2
    return 1
  fi

  [[ -n "$app_dir" ]] || {
    printf '%b✗%b voc not installed and vibecrafted-app is not in the current source tree.\n' "$_red" "$_reset" >&2
    printf '  Install the product TUI with: make install-app-binaries\n' >&2
    printf '  (or the full path: make install / make install-all)\n' >&2
    return 1
  }

  command -v cargo >/dev/null 2>&1 || {
    printf '%b✗%b cargo is required to build voc from source.\n' "$_red" "$_reset" >&2
    printf '  Expected workspace: %s\n' "$app_dir" >&2
    return 1
  }

  cargo run --manifest-path "$app_dir/Cargo.toml" -p voc -- --state-root "$state_root" --deck "$deck_path" "$@"
}

_help_topic_alias() {
  local topic="${1:-}"

  case "$topic" in
    vc-*) topic="${topic#vc-}" ;;
  esac

  case "$topic" in
    help) topic="" ;;
    check) topic="doctor" ;;
    mc|mission-control|sessions) topic="dashboard" ;;
    stats) topic="status" ;;
    upgrade) topic="update" ;;
    remove) topic="uninstall" ;;
    --version|-v) topic="version" ;;
  esac

  printf '%s\n' "$topic"
}

cmd_help() {
  local raw_topic="${1:-}"
  local topic
  if [[ "$raw_topic" == "-h" || "$raw_topic" == "--help" ]]; then
    raw_topic=""
  fi
  if [[ -z "$raw_topic" ]] && _run_core_help; then
    return 0
  fi
  topic="$(_help_topic_alias "$raw_topic")"
  case "$topic" in
    ""|-h|--help)
      ;;
    claude|codex|agy|junie|grok|cursor|kimi|copilot|omp)
      cmd_agent_help "$topic"
      return
      ;;
    gemini)
      printf '%b✗ gemini CLI is deprecated.%b Use agy (Google Antigravity CLI) instead.\n' "$_red" "$_reset" >&2
      printf '  Example: vibecrafted workflow agy --prompt "..." \n' >&2
      return 1
      ;;
    init)
      cmd_init_help
      return
      ;;
    partner)
      cmd_partner_help
      return
      ;;
    operator)
      cmd_operator_help
      return
      ;;
    start)
      cmd_start_help
      return
      ;;
    dashboard|mc|mission-control)
      cmd_dashboard_help
      return
      ;;
    housekeeping)
      cmd_housekeeping_help
      return
      ;;
    gui)
      cmd_gui_help
      return
      ;;
    tui)
      cmd_tui_help
      return
      ;;
    telemetry)
      cmd_telemetry_help
      return
      ;;
    loop)
      cmd_loop_help
      return
      ;;
    cron)
      cmd_cron_help
      return
      ;;
    dispatch)
      cmd_dispatch_help
      return
      ;;
    status)
      cmd_status_help
      return
      ;;
    doctor)
      cmd_doctor_help
      return
      ;;
    scaffold-doctor)
      cmd_scaffold_doctor --help
      return
      ;;
    server)
      cmd_server_help
      return
      ;;
    update)
      cmd_update_help
      return
      ;;
    uninstall)
      cmd_uninstall_help
      return
      ;;
    version)
      cmd_version_help
      return
      ;;
    resume)
      cmd_resume_help
      return
      ;;
    fork)
      cmd_fork_help
      return
      ;;
    claims|message|reinstall|relocate|resume-session|settlements)
      if _run_core_help "$topic"; then
        return 0
      fi
      ;;
    observe|await|stop)
      cmd_lifecycle_help "$topic"
      return
      ;;
    agents)
      cmd_agents
      return
      ;;
    implement)
      cmd_skill_help "implement"
      return
      ;;
    audit|canary|decorate|delegate|dou|followup|guard|hydrate|intents|justdo|marbles|ownership|polarize|prune|release|research|review|scaffold|trust|workflow)
      cmd_skill_help "$topic"
      return
      ;;
  esac
  if [[ "$raw_topic" == "--all" || "$raw_topic" == "--full" ]]; then
    cmd_help_full
    return
  fi
  if [[ -n "$raw_topic" ]]; then
    printf '%b✗%b unknown help topic: %s\n' "$_red" "$_reset" "$raw_topic" >&2
    printf '  %b→ try:%b %bvibecrafted help%b\n' "$_dim" "$_reset" "$_cyan" "$_reset" >&2
    return 1
  fi
  local ver
  ver="$(_version)"
  printf '\n'
  printf '%b⚒  𝚅𝚒𝚋𝚎𝚌𝚛𝚊𝚏𝚝𝚎𝚍. %s%b — release engine for AI-developed software\n' "$_bold$_copper" "$ver" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted <command> [args]\n'
  printf '  vibecrafted <skill> <agent> [-p <prompt> | -f <file>]\n'
  printf '\n'
  printf '%bCommands:%b\n' "$_bold" "$_reset"
  printf '  %binit%b [agent]         Orient an agent in this repo\n' "$_cyan" "$_reset"
  printf '  %b<skill> <agent>%b      Run a workflow with an agent\n' "$_cyan" "$_reset"
  printf '  %bresume%b <agent>       Continue a stopped run or a provider session\n' "$_cyan" "$_reset"
  printf '  %bfork%b <agent>         Branch a provider session (--session | --run-id) into a new one; claude, codex, grok\n' "$_cyan" "$_reset"
  printf '  %bobserve%b <agent>      Check a run report or transcript\n' "$_cyan" "$_reset"
  printf '  %bawait%b <agent>        Wait for a run to settle\n' "$_cyan" "$_reset"
  printf '  %bstop%b <agent>         Stop a tracked launcher process group\n' "$_cyan" "$_reset"
  printf '  %bstatus%b               Today'"'"'s agent activity\n' "$_cyan" "$_reset"
  printf '  %bdoctor%b               Installation health — pass/fail\n' "$_cyan" "$_reset"
  printf '  %breceipt%b              Delivery/runtime receipt (source ↔ installed)\n' "$_cyan" "$_reset"
  printf '  %bscaffold-doctor%b     Plan-package gate before implement handoff\n' "$_cyan" "$_reset"
  printf '  %bresume-session%b       Continue an exact provider session as a tracked run\n' "$_cyan" "$_reset"
  printf '  %brelocate%b             Snapshot open sessions + worktrees (snapshot|restore)\n' "$_cyan" "$_reset"
  printf '  %bmessage%b              Persist/inspect run-addressed Codex queue receipts\n' "$_cyan" "$_reset"
  printf '  %bcapabilities%b         Launcher catalog: agents, models, controls, environments (--json)\n' "$_cyan" "$_reset"
  printf '  %bclaims%b               Atomic Living Tree path claims (acquire|heartbeat|status|list|release)\n' "$_cyan" "$_reset"
  printf '  %bsettlements%b          Read-only f/x/n ledger query (summary|list|inspect)\n' "$_cyan" "$_reset"
  printf '  %bupdate%b               Update to the latest release\n' "$_cyan" "$_reset"
  printf '  %breinstall --clean%b    Stop everything, reinstall, resurrect sessions + agents\n' "$_cyan" "$_reset"
  printf '  %buninstall%b            Remove runtime; preserve Founder data and unknowns\n' "$_cyan" "$_reset"
  printf '  %bhelp%b [topic|--all]   This deck · full reference\n' "$_cyan" "$_reset"
  printf '\n'
  printf '%bShip cycle:%b\n' "$_bold" "$_reset"
  printf '  scaffold → implement → review → workflow → followup → marbles → audit → polarize → dou → hydrate → release\n'
  printf '  %b14 more skills: vibecrafted help --all%b\n' "$_dim" "$_reset"
  printf '\n'
  printf '%bAgents:%b  claude · codex · agy · junie · grok · cursor · kimi · copilot · omp\n' "$_bold" "$_reset"
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted init claude\n'
  printf '  vibecrafted implement codex -p "Ship dark mode"\n'
  printf '  vibecrafted marbles claude -p "Loop until clean"\n'
  printf '  vibecrafted uninstall --dry-run\n'
  printf '\n'
  printf '%bWords:%b\n' "$_bold" "$_reset"
  printf '  run        one dispatched agent job; its report + transcript live under ~/.vibecrafted\n'
  printf '  stage      one step of the ship cycle above (scaffold, implement, review, …)\n'
  printf '  workspace  the repository root a run works in, tracked by the control plane\n'
  printf '\n'
}

cmd_help_full() {
  local ver
  ver="$(_version)"
  printf '\n'
  printf '%b⚒  𝚅𝚒𝚋𝚎𝚌𝚛𝚊𝚏𝚝𝚎𝚍. %s%b (Full Reference)\n' "$_bold$_copper" "$ver" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Release engine for AI-developed software.\n'
  printf '  Install locally. Work from evidence.\n'
  printf '\n'
  printf '%b=== PIPELINE (canonical order) ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  %bscaffold%b   → Plan architecture from a vague idea\n' "$_copper" "$_reset"
  printf '  %binit%b       → Orient: history, eyes, verify\n' "$_copper" "$_reset"
  printf '  %bworkflow%b   → Examine → Research → Implement\n' "$_copper" "$_reset"
  printf '  %bfollowup%b   (vc-followup v2.2.0) → Audit post-implementation direction, gaps, and drift\n' "$_copper" "$_reset"
  printf '  %bmarbles%b    → Convergence loop (counterexample elimination)\n' "$_copper" "$_reset"
  printf '  %baudit%b      (vc-audit v1.0.0) → Plan-vs-code falsification with requirements matrix\n' "$_copper" "$_reset"
  printf '  %bdou%b        → Definition of Undone audit\n' "$_copper" "$_reset"
  printf '  %bdecorate%b   → Visual finishing and UX coherence\n' "$_copper" "$_reset"
  printf '  %bhydrate%b    → Packaging and go-to-market\n' "$_copper" "$_reset"
  printf '  %brelease%b    → Ship to production\n' "$_copper" "$_reset"
  printf '\n'
  printf '%b=== FIRST 5 MINUTES ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  %bvibecrafted init claude%b\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted gui%b\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted tui%b\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted workflow claude --prompt "Plan and implement <task>"%b\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted implement codex --prompt "Ship <task>"%b\n' "$_cyan" "$_reset"
  _print_ship_path
  printf '  Dashboard is optional. The plain-language guide lives at %b%s/START_HERE.md%b.\n' "$_cyan" "$crafted_home" "$_reset"
  printf '\n'
  printf '%b=== WORKFLOWS + LIFECYCLE (action first) ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  %bvibecrafted implement <agent>%b <plan.md>   Execute a plan file\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted research%b [agents...] [flags]  YAML lanes when uno|duo|trio is omitted\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted review <agent>%b    <plan.md>   Review bounded code artifacts\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted observe <agent>%b   --last      Check last agent report/transcript\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted await <agent>%b     --last      Join the shared vc-server monitor\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted stop <agent>%b      --last      Stop the tracked launcher process group\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted resume <agent>%b    --session last  Continue selected repo/provider history\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted fork codex%b        --session current --runtime visible\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted fork claude%b       --run-id work-... --repo ~/Projects/app\n' "$_cyan" "$_reset"
  printf '\n'
  printf '%b=== RESEARCH (launcher) ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  %bvibecrafted research%b [agents...] [flags]                 YAML research.yaml lanes (any N)\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted research <uno|duo|trio>%b <agents...> [flags]  Exact positional lane count\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted swarm%b [agents...] [flags]                   Alias for research\n' "$_cyan" "$_reset"
  printf '  %bEvery skill also installs a vc-<skill> shortcut.%b\n' "$_dim" "$_reset"
  printf '\n'
  printf '%b=== TELEMETRY ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  %btelemetry agy%b line|once|sessions|daemon   Google Antigravity quota / statusline\n' "$_cyan" "$_reset"
  printf '  %btelemetry kimi%b line|once|daemon           Kimi Code quota / statusline\n' "$_cyan" "$_reset"
  printf '  %btelemetry codex%b line|once|sessions|daemon Codex session ledger\n' "$_cyan" "$_reset"
  printf '  %btelemetry claude%b line|once|sessions|daemon Claude session ledger\n' "$_cyan" "$_reset"
  printf '  %btelemetry grok%b line|once|sessions|daemon  Grok session ledger\n' "$_cyan" "$_reset"
  printf '  %btelemetry junie%b line|once|sessions|daemon Junie session ledger\n' "$_cyan" "$_reset"
  printf '  %btelemetry copilot%b line|once|sessions|daemon Copilot session ledger\n' "$_cyan" "$_reset"
  printf '  %btelemetry cursor%b line|once|sessions|daemon Cursor has no local token ledger\n' "$_cyan" "$_reset"
  printf '  %btelemetry omp%b line|once|sessions|daemon    omp session ledger\n' "$_cyan" "$_reset"
  printf '  %btelemetry line%b                            Statuslines of present engines\n' "$_cyan" "$_reset"
  printf '  %btelemetry once%b                            JSON union of agy, kimi, codex, claude, grok, junie, copilot, cursor, omp\n' "$_cyan" "$_reset"
  printf '  %btelemetry smoke%b [flags]                   Smoke the headless marbles telemetry path\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted telemetry%b <same>               Same entrypoint through the main deck\n' "$_cyan" "$_reset"
  printf '\n'
  printf '%b=== OPERATOR SURFACE ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  %bvibecrafted dashboard%b [layout]        Open/switch to a vc-frame dashboard\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted loop%b                      Interactive operator loop + async awaits\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted cron%b                      Cron-safe LOOP heartbeat + context capture\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted ship%b                      Start VC-Ship loop and dispatch a checkpoint\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted dispatch%b <file.toml>      Deterministic dispatch.v1 supervisor\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted dispatch%b run ...          Async lifecycle supervisor for one worker\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted dashboard ls%b              List active vc-frame sessions\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted dashboard gc%b [flags]      Prune dead/stale vc-frame sessions\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted dashboard switch%b <name>   Switch to session (vc-frame-native)\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted housekeeping%b plan|run|schedule  Disk-space reclaim + auto schedule\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted start%b [<workspace>] [--repo <path>]  Enter the repository workspace\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted gui%b                       Public/local-web launch + observe surface\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted tui%b                       Rust operator console over shared state\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted server%b <action>           Manage local control-plane viewer server\n' "$_cyan" "$_reset"
  printf '\n'
  printf '%b  Agents: claude · codex · agy · junie · grok · cursor · kimi · copilot · omp%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '%b=== ADDITIONAL SKILLS ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  %bagents%b     External fleet delegation contract via agent modes\n' "$_copper" "$_reset"
  printf '  %bintents%b    Plan-to-runtime truth audit\n' "$_copper" "$_reset"
  printf '  %bimplement%b  Autonomous end-to-end implementation (vc-implement)\n' "$_copper" "$_reset"
  printf '  %bpartner%b    Shared steering and executive reasoning with the user\n' "$_copper" "$_reset"
  printf '  %bownership%b  Full-spectrum operational ownership and delivery\n' "$_copper" "$_reset"
  printf '  %bdelegate%b   In-session native subagent delegation\n' "$_copper" "$_reset"
  printf '  %bresearch%b   Multi-agent research; uno|duo|trio pin arity, else YAML lanes\n' "$_copper" "$_reset"
  printf '  %breview%b     (vc-review v2.0.0) Bounded PR, branch, commit-range, or artifact-pack review\n' "$_copper" "$_reset"
  printf '  %bprune%b      Runtime/publish cone extraction\n' "$_copper" "$_reset"
  printf '  %btrust%b      Post-hoc commit-claim falsification with f/x/n settlement projection\n' "$_copper" "$_reset"
  printf '  %bguard%b      In-flight gate enforcer: refuses continuation on trust block\n' "$_copper" "$_reset"
  printf '\n'
  printf '%b=== MANAGEMENT ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  %bvibecrafted help%b                      Compact command deck\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted help --all%b                This full reference\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted init%b [agent]              Interactive init session\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted gui%b                       Launch the localhost control plane\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted tui%b                       Launch the Rust operator console\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted dispatch%b <file.toml>      Deterministic dispatch.v1 supervisor\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted dispatch%b run ...          Async lifecycle supervisor for one worker\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted telemetry%b [agy|kimi|line|once|smoke]  Agent quota engines + marbles smoke\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted resume%b <agent> [flags]    Resume an existing agent session\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted resume-session%b <agent> --agent-session-id <id>  Tracked headless continue\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted message%b --session <id> --file <path>           Send to tracked run inbox\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted relocate%b snapshot|restore                      Machine-move session snapshot\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted claims%b acquire|heartbeat|status|list|release   Living Tree path claims\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted settlements%b summary|list|inspect               Read-only f/x/n ledger\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted status%b                    Today'"'"'s agent activity\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted update%b                     Pull latest + reinstall\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted reinstall%b --clean --dry-run  Snapshot sessions/agents; plan kill → install → resurrect\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted doctor%b                    Installation health check\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted version%b                   Print version\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted uninstall%b                 Reverse the install\n' "$_cyan" "$_reset"
  printf '\n'
  printf '%b=== ALIASES ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  %bstats%b = status       %bcheck%b = doctor       %bremove%b = uninstall\n' "$_dim" "$_reset" "$_dim" "$_reset" "$_dim" "$_reset"
  printf '  %bjustdo%b = Just Do posture (not implement)  %bvc-justdo%b = same skill id\n' "$_dim" "$_reset" "$_dim" "$_reset"
  printf '\n'
  printf '%b=== SKILL FLAGS (uniform contract) ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  -p, --prompt <text>            Inline prompt\n'
  printf '  -f, --file <path.md>           Input file as prompt context\n'
  printf '  --count <n>                    Marbles / Polarize loop count (default: 3)\n'
  printf '  --depth <n>                    Marbles plan crawl depth (default: 3)\n'
  printf '  --session <id|current|last>     Provider session for workflow/resume/fork (never a work-* run id)\n'
  printf '\n'
  printf '%b=== GLOBAL OPTIONS ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  --verbose                      Detailed output from all commands\n'
  printf '\n'
  printf '%b=== INFRASTRUCTURE ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  vibecrafted implement codex .vibecrafted/plans/my-plan.md\n'
  printf '  vibecrafted research claude .vibecrafted/plans/my-plan.md\n'
  printf '  vibecrafted review agy .vibecrafted/plans/my-plan.md   # (gemini deprecated)\n'
  printf '  vibecrafted observe codex --last\n'
  printf '  vibecrafted resume claude --session <id> --prompt "Continue the fix"\n'
  printf '  vibecrafted workflow agy --session <id> --file brief.md --runtime headless\n'
  printf '\n'
  printf '%b=== EXAMPLES ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  vibecrafted init claude\n'
  printf '  vibecrafted gui\n'
  printf '  vibecrafted tui\n'
  printf '  vibecrafted dashboard workflow\n'
  printf '  vibecrafted dispatch analyzer-truth.dispatch.toml --doctor\n'
  printf '  vibecrafted dispatch run --run-id demo --root . --report report.md --transcript trace.log -- bash worker.sh\n'
  printf '  telemetry agy line\n'
  printf '  telemetry kimi line\n'
  printf '  vibecrafted telemetry smoke --count 1 --no-watch\n'
  printf '  vibecrafted workflow claude --prompt "Plan and implement auth"\n'
  printf '  vibecrafted workflow claude --file /path/to/brief.md\n'
  printf '  vibecrafted intents codex --prompt "Audit what from the plan really landed"\n'
  printf '  vibecrafted marbles codex --count 3 --depth 3\n'
  printf '  vibecrafted implement codex --prompt "Ship the feature"\n'
  printf '  vibecrafted ownership codex --prompt "Take the repo from diagnosis to finished surface"\n'
  printf '  vibecrafted dou claude\n'
  printf '  vibecrafted decorate codex\n'
  printf '  vibecrafted hydrate codex\n'
  printf '  vibecrafted release codex\n'
  printf '  vibecrafted prune codex\n'
  printf '\n'
}

cmd_start() {
  if _is_help_flag "${1:-}"; then
    cmd_start_help
    return 0
  fi
  local owner_root
  # Product entrypoint choke: load full lifecycle helpers (shell modules,
  # frontier pin, frame launcher). Ordinary shells stay PATH-only.
  # Shell `vc-start` and this deck verb share ONE parser and ONE owner
  # (dashboard.sh _vetcoders_start_entry: root → name → live inventory →
  # exclusive create → enter / VC Terminal). Never re-enter the public
  # vc-start alias from here: Python→deck→helper→deck fork-bombs.
  owner_root="$(_script_owner_root)" || return $?
  _ensure_helpers_loaded "$owner_root" || return $?
  if ! declare -F _vetcoders_start_entry >/dev/null 2>&1 \
    || ! declare -F _vetcoders_product_entry_prepare >/dev/null 2>&1; then
    printf 'vc-start: required product start helper missing\n' >&2
    return 1
  fi
  _vetcoders_start_prepare_arguments "$@" || return $?
  # shellcheck disable=SC2154  # set by _vetcoders_start_prepare_arguments (dashboard.sh) just above
  _vetcoders_start_entry ${_vetcoders_start_frame_argv[@]+"${_vetcoders_start_frame_argv[@]}"}
}

cmd_loop() {
  local script_path
  if _is_help_flag "${1:-}"; then
    cmd_loop_help
    return 0
  fi
  script_path="$(_loop_script 2>/dev/null || true)"
  [[ -n "$script_path" ]] || {
    printf '%b✗%b Loop runtime script not found.\n' "$_red" "$_reset" >&2
    return 1
  }
  bash "$script_path" "$@"
}

cmd_cron() {
  local script_path
  if _is_help_flag "${1:-}"; then
    cmd_cron_help
    return 0
  fi
  script_path="$(_cron_script 2>/dev/null || true)"
  [[ -n "$script_path" ]] || {
    printf '%b✗%b Cron runtime wrapper not found.\n' "$_red" "$_reset" >&2
    return 1
  }
  bash "$script_path" "$@"
}

cmd_ship() {
  local core_dir
  if _is_help_flag "${1:-}"; then
    printf 'Usage: vibecrafted ship <agent> [--start-stage scaffold] (--file <path>|--prompt <text>) [--await-stages]\n'
    printf '       vc-ship <agent> [--checkpoint scaffold] (--file <path>|--prompt <text>)\n'
    return 0
  fi
  core_dir="$(_dispatcher_core_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || {
    printf '%b✗%b Vibecrafted Core module not found.\n' "$_red" "$_reset" >&2
    return 1
  }
  PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" "$(_vibecrafted_python)" -m vibecrafted_core.ship "$@"
}

cmd_dispatch() {
  local core_dir
  if _is_help_flag "${1:-}"; then
    cmd_dispatch_help
    return 0
  fi
  core_dir="$(_dispatcher_core_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || {
    printf '%b✗%b Async dispatcher module not found.\n' "$_red" "$_reset" >&2
    printf '  Expected vibecrafted-core/vibecrafted_core/dispatcher.py in the source or installed tools tree.\n' >&2
    return 1
  }
  if [[ "${1:-}" == "run" ]]; then
    PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" "$(_vibecrafted_python)" -m vibecrafted_core.dispatcher "$@"
    return $?
  fi
  PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" "$(_vibecrafted_python)" -m vibecrafted_core.dispatch.cli "$@"
}

cmd_core_workflow_skill() {
  local skill="$1"
  shift || true
  local core_dir core_skill
  core_skill="$skill"
  core_dir="$(_dispatcher_core_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || {
    printf '%b✗%b Vibecrafted Core module not found.\n' "$_red" "$_reset" >&2
    printf '  Expected vibecrafted-core/vibecrafted_core/cli.py in the source or installed tools tree.\n' >&2
    return 1
  }
  # Inline text is one argument. Move it to a private pipe before spawning
  # Python; core materializes the existing run-owned immutable prompt files.
  local inline_prompt="" has_inline=0 item
  local -a launch_args=()
  while (($#)); do
    item="$1"
    shift
    case "$item" in
      -p|--prompt)
        (($#)) || { printf 'Missing value for --prompt\n' >&2; return 2; }
        ((has_inline == 0)) || { printf 'Duplicate --prompt\n' >&2; return 2; }
        inline_prompt="$1"; has_inline=1; shift
        ;;
      --prompt=*)
        ((has_inline == 0)) || { printf 'Duplicate --prompt\n' >&2; return 2; }
        inline_prompt="${item#*=}"; has_inline=1
        ;;
      --) launch_args+=("$item" "$@"); break ;;
      *) launch_args+=("$item") ;;
    esac
  done
  if ((has_inline)); then
    printf '%s' "$inline_prompt" | PYTHONPATH="$core_dir" \
      "$(_vibecrafted_python)" -m vibecrafted_core.cli "$core_skill" ${launch_args[@]+"${launch_args[@]}"} --prompt-stdin --source-dir "$(_script_repo_root)"
  else
    PYTHONPATH="$core_dir" \
      "$(_vibecrafted_python)" -m vibecrafted_core.cli "$core_skill" ${launch_args[@]+"${launch_args[@]}"} --source-dir "$(_script_repo_root)"
  fi
}

cmd_init() {
  # Deck help is leading or immediately after a registered agent, before CLI
  # admission. Later flags belong to the helper; prompt values and -- tails
  # must never be scanned as help requests.
  if _is_help_flag "${1:-}" || {
    _has_agent "${1:-}" && _is_help_flag "${2:-}"
  }; then
    cmd_init_help
    return 0
  fi
  local agent="${1:-claude}"
  _prepend_repo_bin_path
  if [[ "$agent" == "gemini" ]]; then
    printf '%b✗ gemini CLI is deprecated.%b Use agy (Google Antigravity CLI) instead.\n' "$_red" "$_reset" >&2
    printf '  Example: vibecrafted workflow agy --prompt "..." \n' >&2
    return 1
  fi
  _has_agent "$agent" || {
    printf '%b✗%b Unknown agent: %s\n' "$_red" "$_reset" "$agent" >&2
    return 1
  }

  _require_agent_cli "$agent" || return 1

  [[ $# -gt 0 ]] && shift
  printf '%b⚒%b  Starting %b%s%b with vc-init...\n' "$_copper" "$_reset" "$_bold" "$agent" "$_reset"
  _ensure_helpers_loaded || return 1
  # Prefer the named per-agent helper; fall back to the generic entrypoint so a
  # missing wrapper (version skew / incomplete fleet surface) cannot brick
  # `vibecrafted init <agent>` the way Missing helper grok-skill-init did.
  local helper_name="${agent}-skill-init"
  if command -v "$helper_name" >/dev/null 2>&1; then
    _run_helper "$helper_name" "$@"
    return
  fi
  if command -v _vetcoders_skill_init >/dev/null 2>&1; then
    _vetcoders_skill_init "$agent" "$@"
    return
  fi
  printf '%b✗%b Missing helper %s and no generic skill-init is available.\n' "$_red" "$_reset" "$helper_name" >&2
  return 1
}

cmd_partner() {
  if _is_help_flag "${1:-}"; then
    cmd_partner_help
    return 0
  fi
  local agent="${1:-claude}"
  _prepend_repo_bin_path
  if [[ "$agent" == "gemini" ]]; then
    printf '%b✗ gemini CLI is deprecated.%b Use agy (Google Antigravity CLI) instead.\n' "$_red" "$_reset" >&2
    printf '  Example: vibecrafted partner agy\n' >&2
    return 1
  fi
  _has_agent "$agent" || {
    printf '%b✗%b Unknown agent: %s\n' "$_red" "$_reset" "$agent" >&2
    return 1
  }

  _require_agent_cli "$agent" || return 1

  [[ $# -gt 0 ]] && shift
  _ensure_helpers_loaded || return 1
  printf '%b⚒%b  Starting %b%s%b with vc-partner...\n' "$_copper" "$_reset" "$_bold" "$agent" "$_reset"
  local helper_name="${agent}-skill-partner"
  if command -v "$helper_name" >/dev/null 2>&1; then
    _run_helper "$helper_name" "$@"
    return
  fi
  if command -v _vetcoders_skill_partner >/dev/null 2>&1; then
    _vetcoders_skill_partner "$agent" "$@"
    return
  fi
  printf '%b✗%b Missing helper %s and no generic skill-partner is available.\n' "$_red" "$_reset" "$helper_name" >&2
  return 1
}

cmd_operator() {
  if _is_help_flag "${1:-}"; then
    cmd_operator_help
    return 0
  fi
  local agent="${1:-claude}"
  _prepend_repo_bin_path
  if [[ "$agent" == "gemini" ]]; then
    printf '%b✗ gemini CLI is deprecated.%b Use agy (Google Antigravity CLI) instead.\n' "$_red" "$_reset" >&2
    printf '  Example: vibecrafted operator agy\n' >&2
    return 1
  fi
  _has_agent "$agent" || {
    printf '%b✗%b Unknown agent: %s\n' "$_red" "$_reset" "$agent" >&2
    return 1
  }

  _require_agent_cli "$agent" || return 1

  [[ $# -gt 0 ]] && shift
  printf '%b⚒%b  Starting %b%s%b with vc-operator...\n' "$_copper" "$_reset" "$_bold" "$agent" "$_reset"
  _ensure_helpers_loaded || return 1
  local helper_name="${agent}-skill-operator"
  if command -v "$helper_name" >/dev/null 2>&1; then
    _run_helper "$helper_name" "$@"
    return
  fi
  if command -v _vetcoders_skill_operator >/dev/null 2>&1; then
    _vetcoders_skill_operator "$agent" "$@"
    return
  fi
  printf '%b✗%b Missing helper %s and no generic skill-operator is available.\n' "$_red" "$_reset" "$helper_name" >&2
  return 1
}


# Resolve monorepo root for scaffold-doctor without requiring VIBECRAFTED_ROOT.
# Walks env → known helpers → git toplevel → ancestors of this script until
# VERSION + vibecrafted-server/control-core/Cargo.toml both exist.
_scaffold_doctor_source_roots() {
  local candidate d seen=""
  _scaffold_doctor_emit_root() {
    local root="${1:-}"
    [[ -n "$root" && -d "$root" ]] || return 0
    case " $seen " in
      *" $root "*) return 0 ;;
    esac
    seen="$seen $root"
    printf '%s\n' "$root"
  }

  [[ -n "${VIBECRAFTED_ROOT:-}" ]] && _scaffold_doctor_emit_root "$VIBECRAFTED_ROOT"
  if type -t _repo_source_root >/dev/null 2>&1; then
    candidate="$(_repo_source_root 2>/dev/null || true)"
    _scaffold_doctor_emit_root "$candidate"
  fi
  if type -t _script_repo_root >/dev/null 2>&1; then
    candidate="$(_script_repo_root 2>/dev/null || true)"
    _scaffold_doctor_emit_root "$candidate"
  fi
  candidate="$(git rev-parse --show-toplevel 2>/dev/null || true)"
  _scaffold_doctor_emit_root "$candidate"

  d="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  while [[ -n "$d" && "$d" != "/" ]]; do
    if [[ -f "$d/VERSION" && -f "$d/vibecrafted-server/control-core/Cargo.toml" ]]; then
      _scaffold_doctor_emit_root "$d"
      break
    fi
    d="$(dirname "$d")"
  done
  unset -f _scaffold_doctor_emit_root
}

# Prefer the selected Runtime Pack, then release → debug under each source root.
# Returns 0 and prints the executable path when found.
_scaffold_doctor_find_bin() {
  local root candidate
  candidate="${VIBECRAFTED_RUNTIME_BIN:+$VIBECRAFTED_RUNTIME_BIN/scaffold-doctor}"
  if [[ -n "$candidate" && -x "$candidate" ]]; then
    printf '%s\n' "$candidate"
    return 0
  fi
  if [[ -n "${VIBECRAFTED_ROOT:-}" && -f "$VIBECRAFTED_ROOT/runtime-manifest.json" ]]; then
    candidate="$VIBECRAFTED_ROOT/bin/scaffold-doctor"
    if [[ -x "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
  fi
  while IFS= read -r root; do
    [[ -n "$root" ]] || continue
    for candidate in \
      "$root/vibecrafted-server/target/release/scaffold-doctor" \
      "$root/vibecrafted-server/target/debug/scaffold-doctor" \
      "$root/vibecrafted-server/control-core/target/release/scaffold-doctor" \
      "$root/vibecrafted-server/control-core/target/debug/scaffold-doctor" \
      "$root/target/release/scaffold-doctor" \
      "$root/target/debug/scaffold-doctor"
    do
      if [[ -n "$candidate" && -x "$candidate" ]]; then
        printf '%s\n' "$candidate"
        return 0
      fi
    done
  done < <(_scaffold_doctor_source_roots)
  if command -v scaffold-doctor >/dev/null 2>&1; then
    command -v scaffold-doctor
    return 0
  fi
  return 1
}

_scaffold_doctor_first_source_root() {
  local root
  while IFS= read -r root; do
    if [[ -n "$root" && -f "$root/vibecrafted-server/control-core/Cargo.toml" ]]; then
      printf '%s\n' "$root"
      return 0
    fi
  done < <(_scaffold_doctor_source_roots)
  return 1
}

cmd_scaffold_doctor() {
  # Deterministic plan-package gate (control-core). Not the install doctor.
  local bin="" plan="" repo="" json=0 source_root=""
  local args=()
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --plan)
        if [[ $# -lt 2 || -z "${2:-}" || "${2:-}" == -* ]]; then
          printf 'scaffold-doctor: --plan requires a path\n' >&2
          return 2
        fi
        plan="$2"
        shift 2
        ;;
      --repo)
        if [[ $# -lt 2 || -z "${2:-}" || "${2:-}" == -* ]]; then
          printf 'scaffold-doctor: --repo requires a path\n' >&2
          return 2
        fi
        repo="$2"
        shift 2
        ;;
      --json) json=1; shift ;;
      -h|--help)
        printf 'Usage: vibecrafted scaffold-doctor --plan <plan_root> [--repo <git-root>] [--json]\n'
        printf '       vibecrafted scaffold-doctor <home> <org> <repo> <day> <plan-id> [--repo <git-root>] [--json]\n'
        printf 'Exit 0=pass, 1=refuse (rule violations), 2=not a plan / usage.\n'
        return 0
        ;;
      *) args+=("$1"); shift ;;
    esac
  done

  bin="$(_scaffold_doctor_find_bin 2>/dev/null || true)"

  if [[ -z "$bin" || ! -x "$bin" ]]; then
    source_root="$(_scaffold_doctor_first_source_root 2>/dev/null || true)"
    if command -v cargo >/dev/null 2>&1 && [[ -n "$source_root" ]]; then
      cargo build -q \
        --manifest-path "$source_root/vibecrafted-server/control-core/Cargo.toml" \
        --bin scaffold-doctor || {
        printf '%b✗%b scaffold-doctor: cargo build failed under %s\n' "$_red" "$_reset" "$source_root" >&2
        return 2
      }
      bin="$(_scaffold_doctor_find_bin 2>/dev/null || true)"
    fi
  fi

  if [[ -z "$bin" || ! -x "$bin" ]]; then
    source_root="$(_scaffold_doctor_first_source_root 2>/dev/null || true)"
    printf '%b✗%b scaffold-doctor binary not found (looked release→debug under monorepo roots).\n' "$_red" "$_reset" >&2
    if [[ -n "$source_root" ]]; then
      printf '  Expected (after build):\n' >&2
      printf '    %s/vibecrafted-server/target/debug/scaffold-doctor\n' "$source_root" >&2
      printf '  Build:\n' >&2
      printf '    cargo build --manifest-path %s/vibecrafted-server/control-core/Cargo.toml --bin scaffold-doctor\n' "$source_root" >&2
    else
      printf '  Could not locate monorepo root (VERSION + vibecrafted-server/control-core).\n' >&2
      printf '  Run from a vibecrafted checkout, or export VIBECRAFTED_ROOT=/path/to/checkout.\n' >&2
      printf '  Build: cargo build --manifest-path vibecrafted-server/control-core/Cargo.toml --bin scaffold-doctor\n' >&2
    fi
    return 2
  fi

  if [[ -n "$plan" ]]; then
    if [[ -n "$repo" && "$json" -eq 1 ]]; then
      "$bin" --plan "$plan" --repo "$repo" --json
    elif [[ -n "$repo" ]]; then
      "$bin" --plan "$plan" --repo "$repo"
    elif [[ "$json" -eq 1 ]]; then
      "$bin" --plan "$plan" --json
    else
      "$bin" --plan "$plan"
    fi
  elif [[ ${#args[@]} -ge 5 ]]; then
    if [[ -n "$repo" ]]; then
      args+=(--repo "$repo")
    fi
    if [[ "$json" -eq 1 ]]; then
      "$bin" "${args[@]}" --json
    else
      "$bin" "${args[@]}"
    fi
  else
    printf 'Usage: vibecrafted scaffold-doctor --plan <plan_root> [--repo <git-root>] [--json]\n' >&2
    return 2
  fi
}


cmd_doctor() {
  # The package doctor composes installer, provenance, server supervision,
  # vc-frame delivery, and receipt truth. Calling the installer alone produced
  # a false green while the live server path was broken.
  local source_root="" installer="" core_dir="" python_bin="" doctor_rc=0
  if _is_help_flag "${1:-}"; then
    cmd_doctor_help
    return 0
  fi
  if [[ "${1:-}" == "--fix-server-service" ]]; then
    if [[ "$#" -ne 1 ]]; then
      printf 'Usage: vibecrafted doctor --fix-server-service\n' >&2
      return 2
    fi
    # Do not weaken the identity guard. The only repair for a mismatched
    # LaunchAgent is to render it again from the exact staged supervisor and
    # its sibling launcher, then let launchd verify the new pair.
    _server_supervisor_cli service install || return $?
    # A successful mutation is not a health claim. Re-run the full doctor
    # against the freshly reconciled runtime before returning success.
    cmd_doctor
    return $?
  fi
  case "${1:-}" in
    ""|--json|--release|--verbose)
      core_dir="$(_core_module_dir 2>/dev/null || true)"
      if [[ -n "$core_dir" ]]; then
        python_bin="$(_vibecrafted_python)"
        PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
          "$python_bin" -m vibecrafted_core.cli doctor "$@"
        return $?
      fi
      ;;
  esac
  # Repair flags remain owned by the installer CLI.
  source_root="$(_repo_source_root 2>/dev/null || true)"
  for candidate in \
    "${source_root:+$source_root/scripts/vetcoders_install.py}" \
    "$crafted_tools/scripts/vetcoders_install.py" \
    "$(_repo_root 2>/dev/null)/scripts/vetcoders_install.py"; do
    [[ -n "$candidate" && -f "$candidate" ]] && installer="$candidate" && break
  done
  [[ -n "$installer" ]] || {
    printf '%b✗%b Doctor installer not found. Is 𝚅𝚒𝚋𝚎𝚌𝚛𝚊𝚏𝚝𝚎𝚍. installed?\n' "$_red" "$_reset" >&2
    return 1
  }
  python3 "$installer" doctor "$@" || doctor_rc=$?
  # Delivery/runtime receipt rides doctor so operators see source↔installed
  # drift without a separate habit. Failure to import is non-fatal here —
  # the dedicated `vibecrafted receipt` command remains the sharp surface.
  cmd_receipt 2>/dev/null || true
  return "$doctor_rc"
}

cmd_receipt() {
  # Delegate to vibecrafted_core.runtime_receipt — never invent tool sources
  # from cwd (see Delivery/Runtime Receipt doctrine).
  local source_root="" core_path=""
  source_root="$(_repo_source_root 2>/dev/null || true)"
  if [[ -n "$source_root" && -d "$source_root/vibecrafted-core" ]]; then
    core_path="$source_root/vibecrafted-core"
  elif [[ -d "$crafted_tools/vibecrafted-core" ]]; then
    core_path="$crafted_tools/vibecrafted-core"
  fi
  if [[ -n "$core_path" ]]; then
    PYTHONPATH="$core_path${PYTHONPATH:+:$PYTHONPATH}" \
      "${VIBECRAFTED_PYTHON:-python3}" -c \
      'from vibecrafted_core.runtime_receipt import receipt_main; import sys; raise SystemExit(receipt_main(sys.argv[1:]))' \
      "$@"
    return
  fi
  "${VIBECRAFTED_PYTHON:-python3}" -c \
    'from vibecrafted_core.runtime_receipt import receipt_main; import sys; raise SystemExit(receipt_main(sys.argv[1:]))' \
    "$@"
}

cmd_core_cli() {
  local verb="$1" core_dir
  shift || true
  core_dir="$(_core_module_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || {
    printf '%b✗%b Vibecrafted Core module not found.\n' "$_red" "$_reset" >&2
    return 1
  }
  PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
    "$(_vibecrafted_python)" -m vibecrafted_core.cli "$verb" "$@"
}

cmd_settlements() {
  cmd_core_cli settlements "$@"
}

cmd_control_plane_revalidate() {
  local core_dir
  core_dir="$(_core_module_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || {
    printf '%b✗%b Vibecrafted Core module not found.\n' "$_red" "$_reset" >&2
    return 1
  }
  PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
    "$(_vibecrafted_python)" -m vibecrafted_core.cli control-plane-revalidate "$@"
}

cmd_workspace() {
  local core_dir
  core_dir="$(_core_module_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || {
    printf '%b✗%b Vibecrafted Core module not found.\n' "$_red" "$_reset" >&2
    return 1
  }
  PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
    "$(_vibecrafted_python)" -c \
      'from vibecrafted_core.workspace_catalog import workspace_cli_main; import sys; raise SystemExit(workspace_cli_main(sys.argv[1:]))' \
      "$@"
}

cmd_housekeeping_help() {
  printf '\n'
  printf '%b⚒%b  %bhousekeeping%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Receipt-driven disk-space reclaim for VIBECRAFTED_HOME, and the\n'
  printf '  schedule that runs it automatically over time.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted housekeeping plan [--retention-days N] [--json]\n'
  printf '  vibecrafted housekeeping run --confirm DELETE-REGENERABLE-VIBECRAFTED-STATE [flags]\n'
  printf '  vibecrafted housekeeping schedule status\n'
  printf '  vibecrafted housekeeping schedule install\n'
  printf '  vibecrafted housekeeping schedule uninstall\n'
  printf '\n'
  printf '%bSafety (two separate Founder opt-ins):%b\n' "$_bold" "$_reset"
  printf '  plan never deletes anything. schedule install requires\n'
  printf '  [housekeeping].enabled = true in ~/.config/vibecrafted/config.toml --\n'
  printf '  without it, nothing is scheduled. An installed schedule still only\n'
  printf '  plans (writes a receipt) unless you *also* set\n'
  printf '  [housekeeping].auto_execute = true -- only then does the recurring\n'
  printf '  run ever delete stale transient/build-cache state. store/ and\n'
  printf '  secrets/ are never cleanup candidates either way.\n'
  printf '\n'
}

cmd_housekeeping() {
  if _is_help_flag "${1:-}"; then
    cmd_housekeeping_help
    return 0
  fi
  local script_path
  script_path="$(_housekeeping_script_path 2>/dev/null || true)"
  [[ -n "$script_path" ]] || {
    printf '%b✗%b Housekeeping script not found.\n' "$_red" "$_reset" >&2
    return 1
  }

  local sub="${1:-}"
  case "$sub" in
    plan)
      shift || true
      "$(_vibecrafted_python)" "$script_path" "$@"
      return
      ;;
    run)
      shift || true
      "$(_vibecrafted_python)" "$script_path" --execute "$@"
      return
      ;;
    schedule)
      shift || true
      if _is_help_flag "${1:-}"; then
        cmd_housekeeping_help
        return 0
      fi
      local core_dir
      core_dir="$(_core_module_dir 2>/dev/null || true)"
      [[ -n "$core_dir" ]] || {
        printf '%b✗%b Vibecrafted Core module not found.\n' "$_red" "$_reset" >&2
        return 1
      }
      PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
        "$(_vibecrafted_python)" -c \
          'from vibecrafted_core.housekeeping_schedule import schedule_cli_main; import sys; raise SystemExit(schedule_cli_main(sys.argv[1:]))' \
          "$@" --script-path "$script_path"
      return
      ;;
    ""|-h|--help)
      cmd_housekeeping_help
      return 1
      ;;
    *)
      printf '%b✗%b Unknown housekeeping subcommand: %s\n' "$_red" "$_reset" "$sub" >&2
      cmd_housekeeping_help
      return 1
      ;;
  esac
}

_vc_frame_or_vc_frame_bin() {
  local bin=""
  bin="$(command -v vc-frame 2>/dev/null || true)"
  if [[ -n "$bin" ]]; then
    printf '%s\n' "$bin"
    return 0
  fi
  return 1
}

cmd_dashboard() {
  if _is_help_flag "${1:-}"; then
    cmd_dashboard_help
    return 0
  fi

  # Thin shim subcommands — delegate directly to vc-frame without loading
  # the full helper layer. This keeps ls/switch/attach/kill instant.
  case "${1:-}" in
    ls|list|sessions)
      local vc_frame_bin=""
      vc_frame_bin="$(_vc_frame_or_vc_frame_bin)" || {
        printf '%b✗%b vc-frame is required.\n' "$_red" "$_reset" >&2; return 1
      }
      "$vc_frame_bin" list-sessions
      return
      ;;
    switch)
      shift
      local vc_frame_bin=""
      vc_frame_bin="$(_vc_frame_or_vc_frame_bin)" || {
        printf '%b✗%b vc-frame is required.\n' "$_red" "$_reset" >&2; return 1
      }
      [[ -n "${1:-}" ]] || { printf '%b✗%b Session name required.\n' "$_red" "$_reset" >&2; return 1; }
      # Trusted attached-context signal (pane id + session name): stale
      # VC_FRAME/ZELLIJ leaks in a parent shell must not pick switch-session,
      # which has no live client to act on outside a real pane.
      if [[ -n "${VC_FRAME_PANE_ID:-}" && -n "${VC_FRAME_SESSION_NAME:-}" ]]; then
        "$vc_frame_bin" action switch-session "$1"
      else
        "$vc_frame_bin" attach "$1"
      fi
      return
      ;;
    attach)
      shift
      local vc_frame_bin=""
      vc_frame_bin="$(_vc_frame_or_vc_frame_bin)" || {
        printf '%b✗%b vc-frame is required.\n' "$_red" "$_reset" >&2; return 1
      }
      [[ -n "${1:-}" ]] || { printf '%b✗%b Session name required.\n' "$_red" "$_reset" >&2; return 1; }
      # Trusted attached-context signal (pane id + session name): stale
      # VC_FRAME/ZELLIJ leaks in a parent shell must not pick switch-session,
      # which has no live client to act on outside a real pane.
      if [[ -n "${VC_FRAME_PANE_ID:-}" && -n "${VC_FRAME_SESSION_NAME:-}" ]]; then
        "$vc_frame_bin" action switch-session "$1"
      else
        "$vc_frame_bin" attach "$1"
      fi
      return
      ;;
    kill)
      shift
      local vc_frame_bin=""
      vc_frame_bin="$(_vc_frame_or_vc_frame_bin)" || {
        printf '%b✗%b vc-frame is required.\n' "$_red" "$_reset" >&2; return 1
      }
      [[ -n "${1:-}" ]] || { printf '%b✗%b Session name required.\n' "$_red" "$_reset" >&2; return 1; }
      "$vc_frame_bin" kill-session "$1"
      return
      ;;
    gc)
      shift || true
      _ensure_helpers_loaded || return 1
      _vetcoders_launch_dashboard gc "$@"
      return
      ;;
  esac

  _ensure_helpers_loaded || return 1
  _vetcoders_launch_dashboard "$@"
}

cmd_stats() {
  case "${1:-}" in
    skills|skill-context|context)
      cmd_stats_skills
      return
      ;;
    help|-h|--help)
      cmd_status_help
      return 0
      ;;
  esac

  # Control-plane board (runs + reports) is the product truth; the legacy
  # artifacts scan below only runs when core is unavailable.
  local core_dir
  core_dir="$(_core_module_dir 2>/dev/null || true)"
  if [[ -n "$core_dir" ]]; then
    PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
      "$(_vibecrafted_python)" -c \
        'from vibecrafted_core.run_board import status_main; import sys; raise SystemExit(status_main(sys.argv[1:]))' \
        "$@"
    return
  fi

  local today_dir ts_prefix artifacts_dir local_artifacts_dir matches
  local search_dirs=()
  
  today_dir="$(date +%Y_%m%d)"
  ts_prefix="$(date +%Y%m%d)"
  artifacts_dir="$crafted_home/artifacts"
  local_artifacts_dir="$(_repo_root 2>/dev/null || pwd)/.vibecrafted/reports"

  [[ -d "$artifacts_dir" ]] && search_dirs+=("$artifacts_dir")
  [[ -d "$local_artifacts_dir" ]] && search_dirs+=("$local_artifacts_dir")

  printf '\n%b⚒  𝚅𝚒𝚋𝚎𝚌𝚛𝚊𝚏𝚝𝚎𝚍. Stats — %s%b\n' "$_bold$_copper" "$(date +%Y-%m-%d)" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  if [[ ${#search_dirs[@]} -eq 0 ]]; then
    printf "  No activity yet — run \`vibecrafted init <agent>\` to start.\n\n"
    return 0
  fi
  
  matches="$(find "${search_dirs[@]}" \( -path "*${today_dir}*" -o -name "${ts_prefix}_*.meta.json" \) -name "*.meta.json" -type f 2>/dev/null | sort -r | sed -n '1,8p' || true)"
  if [[ -z "$matches" ]]; then
    printf "  No activity yet — run \`vibecrafted init <agent>\` to start.\n\n"
    return 0
  fi

  printf '%s\n' "$matches" | sed 's#^#  #'
  printf '\n'
}

cmd_stats_skills() {
  command -v python3 >/dev/null 2>&1 || {
    printf '%b✗%b python3 is required for skill context stats.\n' "$_red" "$_reset" >&2
    return 1
  }

  python3 - <<'PY'
from __future__ import annotations

from collections import defaultdict
from pathlib import Path
import os
import re

home = Path.home()
roots = [
    home / ".codex" / "skills",
    home / ".agents" / "skills",
    home / ".local" / "share" / "vibecrafted" / "tools" / "vibecrafted-current" / "skills",
    home / ".local" / "share" / "vibecrafted" / "tools" / "vibecrafted-local" / "skills",
    home / ".codex" / "plugins" / "cache",
]

records = []
visited = set()
for root in roots:
    if not root.exists():
        continue
    for skill_file in sorted(root.rglob("SKILL.md")):
        try:
            real = skill_file.resolve()
        except OSError:
            real = skill_file
        if real in visited:
            continue
        visited.add(real)
        try:
            text = skill_file.read_text(encoding="utf-8", errors="ignore")
        except OSError:
            continue
        name_match = re.search(r"^name:\s*(.+)$", text, re.MULTILINE)
        name = name_match.group(1).strip().strip("'\"") if name_match else skill_file.parent.name
        desc_match = re.search(
            r"^description:\s*(?:>[-]?\s*)?\n?(.*?)(?:\n[a-zA-Z_-]+:|\n---)",
            text,
            re.MULTILINE | re.DOTALL,
        )
        desc = ""
        if desc_match:
            desc = " ".join(line.strip().strip("'\"") for line in desc_match.group(1).splitlines() if line.strip())
        records.append((name, len(desc), str(skill_file)))

by_name = defaultdict(list)
for name, desc_len, path in records:
    by_name[name].append((desc_len, path))

duplicates = {name: paths for name, paths in by_name.items() if len(paths) > 1}
desc_chars = sum(desc_len for _, desc_len, _ in records)
top = sorted(records, key=lambda row: row[1], reverse=True)[:12]

print()
print("⚒  Vibecrafted Skill Context Stats")
print("─────────────────────────────────────────")
print("  Codex announced skills metadata budget: 2%")
print("  Exact total context allocation is runtime-private; this report measures local skill metadata only.")
print()
print(f"  skill files:        {len(records)}")
print(f"  unique names:       {len(by_name)}")
print(f"  duplicate groups:   {len(duplicates)}")
print(f"  description chars:  {desc_chars}")
print()
if top:
    print("  largest descriptions:")
    for name, desc_len, path in top:
        short_path = path.replace(str(home), "~")
        print(f"    {desc_len:5d}  {name:28s} {short_path}")
print()
if duplicates:
    print("  duplicate names:")
    for name, paths in sorted(duplicates.items()):
        print(f"    {name}: {len(paths)}")
PY
}

cmd_uninstall() {
  # Bypass make for the same reason as cmd_doctor: prevent the
  # `make: Entering directory` and `*** Error N` traceback from
  # bleeding into the user-facing uninstall transcript.
  local source_root="" installer="" installer_python="python3"
  source_root="$(_repo_source_root 2>/dev/null || true)"
  for candidate in \
    "${source_root:+$source_root/scripts/vetcoders_install.py}" \
    "${VIBECRAFTED_RUNTIME_ROOT:+$VIBECRAFTED_RUNTIME_ROOT/scripts/vetcoders_install.py}" \
    "$crafted_tools/scripts/vetcoders_install.py" \
    "$(_repo_root 2>/dev/null)/scripts/vetcoders_install.py"; do
    [[ -n "$candidate" && -f "$candidate" ]] && installer="$candidate" && break
  done
  [[ -n "$installer" ]] || {
    printf '%b✗%b Uninstall installer not found.\n' "$_red" "$_reset" >&2
    return 1
  }
  if [[ -n "${VIBECRAFTED_RUNTIME_ROOT:-}" \
    && "$installer" == "$VIBECRAFTED_RUNTIME_ROOT/scripts/vetcoders_install.py" \
    && -x "$VIBECRAFTED_RUNTIME_ROOT/bin/python3" ]]; then
    installer_python="$VIBECRAFTED_RUNTIME_ROOT/bin/python3"
  fi
  # Forward argv verbatim: swallowing flags here once turned
  # `vibecrafted uninstall --dry-run` into a real, unconfirmed teardown.
  VIBECRAFTED_UNINSTALL_LAUNCHER="${VIBECRAFTED_DECLARED_LAUNCHER:-$0}" \
    "$installer_python" "$installer" uninstall "$@"
}

_fetch_channel_version() {
  local ref="${1:-main}"
  local channel_url="https://vibecrafted.io/channel/${ref}.json"
  local payload=""
  payload="$(curl -fsSL "$channel_url" 2>/dev/null)" || return 1
  python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('version',''),d.get('archive_url',''))" <<< "$payload" 2>/dev/null || return 1
}

_sha256_file() {
  local file="$1"
  local actual=""
  actual="$(shasum -a 256 "$file" 2>/dev/null || sha256sum "$file" 2>/dev/null)" || return 1
  printf '%s\n' "${actual%% *}"
}

_expected_sha_from_sums() {
  local sums_file="$1"
  local target_name="$2"
  awk -v target="$target_name" '
    NF >= 2 {
      name=$2
      sub(/^\*/, "", name)
      if (name == target) {
        print $1
        exit
      }
    }
  ' "$sums_file"
}

_fetch_checked_release_file() {
  local file_url="$1"
  local output_file="$2"
  local label="${3:-$(basename "$output_file")}"
  local base_url="${file_url%/*}"
  local sums_file expected actual

  sums_file="$(dirname "$output_file")/SHA256SUMS"

  if ! curl -fsSL "$file_url" -o "$output_file"; then
    printf '%b✗%b Could not fetch %s from %s.\n' "$_red" "$_reset" "$label" "$file_url" >&2
    return 1
  fi

  printf '  Verifying %s via SHA256SUMS\n' "$label"
  if ! curl -fsSL "${base_url}/SHA256SUMS" -o "$sums_file"; then
    printf '%b✗%b Could not fetch SHA256SUMS from %s.\n' "$_red" "$_reset" "${base_url}/SHA256SUMS" >&2
    return 1
  fi

  expected="$(_expected_sha_from_sums "$sums_file" "$(basename "$output_file")")"
  [[ -n "$expected" ]] || {
    printf '%b✗%b SHA256SUMS does not contain an entry for %s.\n' "$_red" "$_reset" "$(basename "$output_file")" >&2
    return 1
  }

  actual="$(_sha256_file "$output_file")" || {
    printf '%b✗%b Could not compute SHA256 for %s.\n' "$_red" "$_reset" "$label" >&2
    return 1
  }

  if [[ "$actual" != "$expected" ]]; then
    printf '%b✗%b SHA256 mismatch for %s: expected %s, got %s.\n' "$_red" "$_reset" "$label" "$expected" "$actual" >&2
    return 1
  fi

  printf '  %bSHA256 ✓%b\n' "$_green" "$_reset"
}

_run_remote_install_fallback() {
  local install_url="$1"
  local channel_ref="$2"
  local tmpdir install_file status=0

  tmpdir="$(mktemp -d "${TMPDIR:-/tmp}/vibecrafted-update.XXXXXX")" || {
    printf '%b✗%b Could not create a temporary directory for install.sh.\n' "$_red" "$_reset" >&2
    return 1
  }
  install_file="$tmpdir/install.sh"

  if ! _fetch_checked_release_file "$install_url" "$install_file" "install.sh"; then
    rm -rf "$tmpdir"
    return 1
  fi

  bash "$install_file" --ref "$channel_ref" || status=$?
  rm -rf "$tmpdir"
  return "$status"
}

_post_update_banner() {
  # The running deck may still belong to the prior generation. Only the
  # installer owns publication and cleanup; do not mutate or infer version
  # acceptance from this process after it returns.
  printf '\n  Installer completed; installed runtime acceptance pending.\n'
  printf '  Run %bvibecrafted doctor%b and %bvibecrafted receipt%b to inspect the installed runtime.\n\n' "$_cyan" "$_reset" "$_cyan" "$_reset"
}

cmd_update() {
  local makefile="" repo_source="" launcher_ver="" channel_ref="main"
  local force=0
  local _u_arg=""
  while (( $# )); do
    _u_arg="$1"
    case "$_u_arg" in
      --force|-f) force=1 ;;
      --ref)
        shift
        if [[ $# -eq 0 || "${1:-}" == --* ]]; then
          printf '%b✗%b --ref requires a channel value.\n' "$_red" "$_reset" >&2
          return 2
        fi
        channel_ref="$1"
        ;;
      --ref=*) channel_ref="${_u_arg#--ref=}" ;;
      -h|--help)
        # An unmatched flag used to fall through this case and run the update.
        # `vibecrafted update --help` mutating the install is not a help screen.
        cmd_help update
        return 0
        ;;
      --*)
        printf '%b✗%b update: unknown option %s\n' "$_red" "$_reset" "$_u_arg" >&2
        printf '  Try: vibecrafted help update\n' >&2
        return 2
        ;;
    esac
    shift
  done
  repo_source="$(_repo_source_root 2>/dev/null || true)"

  launcher_ver="$(_version)"
  printf '\n%b⚒  Vibecrafted Update%b\n' "$_bold$_copper" "$_reset"
  printf '  Launcher: %b%s%b\n' "$_cyan" "$launcher_ver" "$_reset"

  # Try to show available version from channel manifest.
  local channel_info="" available_ver="" available_url=""
  if channel_info="$(_fetch_channel_version "$channel_ref" 2>/dev/null)"; then
    available_ver="${channel_info%% *}"
    available_url="${channel_info#* }"
    if [[ -n "$available_ver" ]]; then
      printf '  Available: %b%s%b\n' "$_green" "$available_ver" "$_reset"
      if [[ "$launcher_ver" == "$available_ver" ]] && (( ! force )); then
        printf '  %b(channel version matches launcher; installation acceptance pending — use --force to reinstall)%b\n\n' "$_dim" "$_reset"
        return 0
      fi
    fi
  fi

  for candidate in \
    "${repo_source:+$repo_source/Makefile}" \
    "$crafted_tools/Makefile" \
    "$(_repo_root 2>/dev/null)/Makefile"; do
    [[ -n "$candidate" && -f "$candidate" ]] && makefile="$candidate" && break
  done

  if [[ -n "$makefile" ]]; then
    make -C "$(dirname "$makefile")" update BRANCH="$channel_ref" || return $?
    _post_update_banner
    return 0
  fi

  # No Makefile found — attempt direct tarball update via install.sh.
  local install_sh=""
  for candidate in \
    "${crafted_tools:+$crafted_tools/install.sh}" \
    "${repo_source:+$repo_source/install.sh}"; do
    [[ -n "$candidate" && -f "$candidate" ]] && install_sh="$candidate" && break
  done

  if [[ -n "$install_sh" ]]; then
    printf '  Tarball install detected — running install.sh --ref %s\n\n' "$channel_ref"
    bash "$install_sh" --ref "$channel_ref" || return $?
    _post_update_banner
    return 0
  fi

  # Last resort: fetch install.sh from the web.
  local remote_install_url="https://vibecrafted.io/install.sh"
  if [[ -n "$available_url" ]]; then
    remote_install_url="${available_url%/*}/install.sh"
  fi

  printf '  No local install surface found — fetching install.sh from %s\n\n' "$remote_install_url" >&2
  _run_remote_install_fallback "$remote_install_url" "$channel_ref" || return $?
  _post_update_banner
  return 0
}

cmd_agents() {
  cmd_core_cli agents "$@"
}

# Ask core for the stable provider identity a fork branches from. Prints
# `<agent_session_id>\t<source_run_id>\t<root>\t<selection-json>` on success. On refusal relays core's
# reason / detail / hint to stderr and returns 2. Core (workflow.resolve_fork_source)
# is the single owner of identity classification and of the provider fork
# capability verdict, so the deck never re-implements either.
_vibecrafted_fork_source() {
  local agent="$1" identity_flag="$2" identity="$3" selection_root="${4:-auto}"
  local payload="" status=0 python_bin core_dir
  # Same core resolver as cmd_lifecycle / cmd_core_workflow_skill: the deck's
  # own generation (checkout or installed), never whichever interpreter on the
  # caller's PATH happens to import an older vibecrafted_core.
  core_dir="$(_dispatcher_core_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || {
    printf '%b✗%b Vibecrafted Core module not found.\n' "$_red" "$_reset" >&2
    return 2
  }
  python_bin="$(_vibecrafted_python)"
  payload="$(PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" "$python_bin" -m vibecrafted_core.cli fork-source "$agent" "$identity_flag" "$identity" --root "$selection_root" --json)" || status=$?
  if [[ -z "$payload" ]]; then
    printf 'fork: Vibecrafted core did not answer the fork-source query (exit %s).\n' "$status" >&2
    return 2
  fi
  "$python_bin" - "$status" "$payload" <<'PYFORK'
import json
import sys

status = int(sys.argv[1])
try:
    payload = json.loads(sys.argv[2])
except ValueError:
    print("fork: core returned an unreadable fork-source receipt", file=sys.stderr)
    raise SystemExit(2)
if status != 0 or not payload.get("accepted"):
    reason = str(payload.get("reason") or "refused")
    print(f"fork: cannot resolve the source session ({reason})", file=sys.stderr)
    for key in ("detail", "hint"):
        value = str(payload.get(key) or "").strip()
        if value:
            print(f"  {key}: {value}", file=sys.stderr)
    raise SystemExit(2)
print(
    str(payload.get("agent_session_id") or "")
    + "\t"
    + str(payload.get("source_run_id") or "")
    + "\t"
    + str(payload.get("selection_root") or payload.get("source_root") or "")
    + "\t" + json.dumps(payload)
)
PYFORK
}

cmd_fork() {
  local agent="${1:-}"
  shift || true
  if _is_help_flag "$agent" || [[ -z "$agent" ]]; then
    cmd_fork_help
    [[ -n "$agent" ]] && return 0 || return 1
  fi
  if [[ "$agent" == "gemini" ]]; then
    printf '%b✗ gemini CLI is deprecated.%b Use agy (Google Antigravity CLI) instead.\n' "$_red" "$_reset" >&2
    return 1
  fi
  _has_agent "$agent" || {
    printf '%b✗%b Unknown agent: %s\n' "$_red" "$_reset" "$agent" >&2
    return 1
  }

  local selector="" run_id="" runtime="" placement="floating"
  local input_explicit=""
  local model="" permissions="" repo_dir="" root_dir="" prompt=""
  local plan_file="" base="" execution="" worktree=""
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --session) shift; [[ $# -gt 0 ]] || { echo "Missing value for --session" >&2; return 2; }; selector="$1" ;;
      --session=*) selector="${1#--session=}" ;;
      --run-id) shift; [[ $# -gt 0 ]] || { echo "Missing value for --run-id" >&2; return 2; }; run_id="$1" ;;
      --run-id=*) run_id="${1#--run-id=}" ;;
      --repo) shift; [[ $# -gt 0 ]] || { echo "Missing value for --repo" >&2; return 2; }; repo_dir="$1" ;;
      --repo=*) repo_dir="${1#--repo=}" ;;
      --root) shift; [[ $# -gt 0 ]] || { echo "Missing value for --root" >&2; return 2; }; root_dir="$1" ;;
      --root=*) root_dir="${1#--root=}" ;;
      --file) shift; [[ $# -gt 0 ]] || return 2; plan_file="$1"; input_explicit=1 ;;
      --prompt-stdin) input_explicit=1; IFS= read -r -d '' prompt || true; [[ -n "$prompt" ]] || { echo "Empty --prompt-stdin" >&2; return 2; } ;;
      --base) shift; [[ $# -gt 0 ]] || return 2; base="$1" ;;
      --execution-runtime) shift; [[ $# -gt 0 ]] || return 2; execution="$1" ;;
      --worktree) worktree=true; if [[ $# -gt 1 && "$2" =~ ^(true|false)$ ]]; then shift; worktree="$1"; fi ;;
      --worktree=*) worktree="${1#--worktree=}" ;;
      --runtime) shift; [[ $# -gt 0 ]] || { echo "Missing value for --runtime" >&2; return 2; }; runtime="$1" ;;
      --placement) shift; [[ $# -gt 0 ]] || { echo "Missing value for --placement" >&2; return 2; }; placement="$1" ;;
      --floating) placement="floating" ;;
      --model) shift; [[ $# -gt 0 ]] || { echo "Missing value for --model" >&2; return 2; }; model="$1" ;;
      --permissions) shift; [[ $# -gt 0 ]] || { echo "Missing value for --permissions" >&2; return 2; }; permissions="$1" ;;
      -p|--prompt) shift; [[ $# -gt 0 ]] || { echo "Missing value for --prompt" >&2; return 2; }; prompt="$1"; input_explicit=1 ;;
      -h|--help) cmd_fork_help; return 0 ;;
      *) printf 'Unknown fork argument: %s\n' "$1" >&2; return 2 ;;
    esac
    shift
  done
  [[ -n "$selector" || -n "$run_id" ]] || {
    echo "fork requires --session current|last|<provider-session-id> or --run-id <work-...>." >&2
    return 2
  }
  [[ -z "$selector" || -z "$run_id" ]] || {
    echo "fork takes one identity: --session or --run-id, not both." >&2
    return 2
  }
  if [[ -n "$input_explicit" ]]; then
    runtime="${runtime:-headless}"
    [[ "$runtime" == headless ]] || { echo "Task fork is noninteractive; use --runtime headless." >&2; return 2; }
    [[ -z "$plan_file" || -z "$prompt" ]] || { echo "Use one of --file or --prompt." >&2; return 2; }
  else
    runtime="${runtime:-visible}"
    case "$runtime" in visible|terminal) ;; *) echo "Bare fork requires visible or terminal runtime." >&2; return 2 ;; esac
  fi
  case "$placement" in
    right|floating) ;;
    *) echo "Unknown fork placement: ${placement} (use right or floating)." >&2; return 2 ;;
  esac
  case "$permissions" in
    ""|bypass|auto|accept-edits|read-only) ;;
    *) echo "Unsupported fork permissions: ${permissions} (use bypass, auto, accept-edits or read-only)." >&2; return 2 ;;
  esac
  if [[ "$agent" == codex && "$permissions" == accept-edits ]]; then
    echo "codex exposes no native accept-edits policy; use bypass, auto or read-only." >&2
    return 2
  fi

  _ensure_helpers_loaded || return 1
  # Provider capability first: a provider without a fork surface is refused
  # before any CLI or session lookup, with the capability table as evidence.
  case "$agent" in
    claude|codex|grok) ;;
    *)
      _vibecrafted_fork_source "$agent" --session "capability-probe" >/dev/null || return 2
      ;;
  esac
  _require_agent_cli "$agent" || return 1
  # Explicit --repo/--root wins. Without one, `current|last` mean "this
  # repository" (explicit context or scoped control-plane records), while an
  # explicit session id or a --run-id fall back to the repository the source
  # run recorded, and only then to the caller's checkout.
  local explicit_root=""
  if [[ -n "$repo_dir$root_dir" ]]; then
    explicit_root="$(_vetcoders_select_repo "fork" "$repo_dir" "$root_dir")" || return $?
  fi
  root_dir="${explicit_root:-$(_repo_root)}"
  root_dir="$(cd "$root_dir" 2>/dev/null && pwd -P)" || {
    printf 'Fork root is not a directory: %s\n' "$root_dir" >&2
    return 2
  }

  local session_id="" source_run_id="" source_root="" source_fields="" selection_json=""
  local selection_root="${explicit_root:-auto}"
  case "$selector" in current|last|previous) selection_root="$root_dir" ;; esac
  if [[ -n "$selector" ]]; then
    source_fields="$(_vibecrafted_fork_source "$agent" --session "$selector" "$selection_root")" || return 2
  else
    source_fields="$(_vibecrafted_fork_source "$agent" --run-id "$run_id" "$selection_root")" || return 2
  fi
  session_id="${source_fields%%$'\t'*}"
  source_fields="${source_fields#*$'\t'}"
  source_run_id="${source_fields%%$'\t'*}"
  source_fields="${source_fields#*$'\t'}"
  source_root="${source_fields%%$'\t'*}"
  selection_json="${source_fields#*$'\t'}"
  [[ -n "$session_id" && -n "$source_root" ]] || { echo "fork: incomplete source receipt" >&2; return 2; }
  root_dir="$source_root"

  if [[ -n "$input_explicit" ]]; then
    local -a task_args=(fork-session "$agent" --session "$session_id" --root "$root_dir" --session-selection "$selection_json")
    [[ -z "$permissions" ]] || task_args+=(--permissions "$permissions")
    [[ -z "$source_run_id" ]] || task_args+=(--parent-run-id "$source_run_id")
    [[ -z "$model" ]] || task_args+=(--model "$model")
    [[ -z "$base" ]] || task_args+=(--base "$base")
    [[ -z "$execution" ]] || task_args+=(--execution-runtime "$execution")
    [[ -z "$worktree" ]] || task_args+=(--worktree "$worktree")
    if [[ -n "$plan_file" ]]; then
      _vetcoders_run_core_cli "${task_args[@]}" --file "$plan_file"
    else
      printf '%s' "$prompt" | _vetcoders_run_core_cli "${task_args[@]}" --prompt-stdin
    fi
    return $?
  fi

  # The existing interactive owner admits the fork, snapshots its source and
  # owns the provider lifetime. Pane/window transport sees only that reference.
  local _vetcoders_contract_session_selection="$selection_json"
  local _vetcoders_interactive_skill=fork
  local _vetcoders_contract_model="$model" _vetcoders_contract_file="$plan_file"
  local _vetcoders_contract_base="$base" _vetcoders_contract_execution_runtime="$execution"
  local _vetcoders_contract_worktree="$worktree" _vetcoders_contract_root="$root_dir"
  local _vetcoders_contract_repo="" _vetcoders_contract_run_id=""
  local _vetcoders_contract_parent_run_id="$source_run_id" _vetcoders_contract_session=""
  local command_text admission_status=0
  command_text="$(_vetcoders_init_command_text "$agent" "$prompt" local-native "${permissions:-bypass}" unmetered none bare-fork "$session_id")" || return 1
  _vetcoders_enter_admitted_interactive fork "$command_text" || admission_status=$?
  case "$admission_status" in 0) return 0 ;; 1) return 1 ;; esac
  root_dir="$_vetcoders_contract_root"
  # A session name is a projection target only when the engine says that host
  # is usable. Pane id is not required: a tool shell inside vc-frame often has
  # VC_FRAME_SESSION_NAME and no TTY, and opening a second terminal there
  # starts a CLI client the frame warden retires while the child is still
  # starting (Founder 2026-10-03). A dead, missing, or unattended name is not
  # a target (2026-09-09 / fac246a7) and keeps the declaration path.
  local projection_host=""
  projection_host="$(_vetcoders_frame_projection_host)"
  if [[ -z "$projection_host" ]]; then
    if [[ "$runtime" == terminal ]]; then
      _vetcoders_init_in_current_terminal "$agent" "$command_text" plain fork
    else
      _vetcoders_launch_interactive_declaration fork "$runtime" "${agent} fork" "$command_text" "$root_dir" "" "$agent" "$placement"
    fi
    return $?
  fi

  local vc_frame_bin session_name pane_title cmd_script
  vc_frame_bin="$(_vetcoders_vc_frame_bin)" || return 1
  session_name="$projection_host"
  pane_title="$(_vetcoders_interactive_pane_title "$agent" "$root_dir" "$model")"
  cmd_script="$(_vetcoders_tmp_script_path "vc-fork-cmd" "$root_dir")"
  _vetcoders_write_command_script "$cmd_script" "$command_text" || return 1

  local -a pane_args=(action new-pane --near-current-pane --name "$pane_title" --cwd "$root_dir")
  if [[ "$placement" == floating ]]; then
    pane_args+=(--floating --width 62% --height 80%)
  else
    pane_args+=(--direction right)
  fi
  pane_args+=(-- "$cmd_script")
  local pane_id
  # Name the CLI client before its TTL window. The timer that retires a
  # still-live child lives in vc-frame (zellij-client ActionDeadline); this
  # is the handshake vibecrafted can complete without editing that tree.
  # Export before the substitution: a prefix on the assignment is expanded
  # away before the engine process starts.
  export VC_FRAME_CALLER="${VC_FRAME_CALLER:-vibecrafted-fork}"
  pane_id="$("$vc_frame_bin" --session "$session_name" "${pane_args[@]}")" || {
    echo "vc-frame refused the same-tab fork pane; no replacement session or tab was created." >&2
    return 1
  }
  printf 'Fork process admitted in current vc-frame tab (native child identity pending):\n'
  printf '  agent:     %s\n' "$agent"
  printf '  source-session: %s\n' "$session_id"
  [[ -z "$source_run_id" ]] || printf '  source:    %s\n' "$source_run_id"
  printf '  repo:      %s\n' "$root_dir"
  printf '  pane:      %s\n' "$placement"
  [[ -z "$pane_id" ]] || printf '  pane-id:   %s\n' "$pane_id"
  printf '  title:     %s\n' "$pane_title"
}

cmd_resume() {
  local agent="${1:-}"
  if _is_help_flag "$agent"; then
    cmd_resume_help
    return 0
  fi
  local _resume_arg
  for _resume_arg in "$@"; do
    if _is_help_flag "$_resume_arg"; then
      cmd_resume_help
      return 0
    fi
  done
  [[ -n "$agent" ]] || {
    cmd_resume_help >&2
    return 1
  }
  shift || true
  if [[ "$agent" == "gemini" ]]; then
    printf '%b✗ gemini CLI is deprecated.%b Use agy (Google Antigravity CLI) instead.\n' "$_red" "$_reset" >&2
    printf '  Example: vibecrafted workflow agy --prompt "..." \n' >&2
    return 1
  fi
  _has_agent "$agent" || {
    printf '%b✗%b Unknown agent: %s\n' "$_red" "$_reset" "$agent" >&2
    return 1
  }
  _ensure_helpers_loaded || return 1
  # Direct impl — public vc-resume must never be `command vibecrafted resume`
  # (same Python↔deck re-entry bomb as start).
  _vetcoders_resume_agent "$agent" "$@"
}

# Core owns the agent lifecycle verbs (observe / await / stop): they resolve a
# run read-follows-write via resolve_run (runtime_runs/ first, artifacts/ fallback,
# else a loud "still launching"). Route them straight to the core CLI — never the
# legacy shell helper / observe.sh, which reads only artifacts/ and would emit
# "No metadata" for a run the core already tracks. Closes the split-brain on the
# path the tarball puts on PATH (the deck), not just in cli:main.
cmd_lifecycle() {
  local agent="$1"
  local verb="$2"
  shift 2 || true
  local core_dir
  core_dir="$(_dispatcher_core_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || {
    printf '%b✗%b Vibecrafted Core module not found.\n' "$_red" "$_reset" >&2
    return 1
  }
  PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" "$(_vibecrafted_python)" -m vibecrafted_core.cli "$agent" "$verb" "$@"
}

# Launcher catalog for GUI/TUI clients: agents, model-pin support, permission /
# sandbox cells and environment availability, straight from core (read-only).
# VOC loads this instead of carrying its own agent list.
cmd_capabilities() {
  local core_dir
  core_dir="$(_dispatcher_core_dir 2>/dev/null || true)"
  [[ -n "$core_dir" ]] || {
    printf '%b✗%b Vibecrafted Core module not found.\n' "$_red" "$_reset" >&2
    return 1
  }
  PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" "$(_vibecrafted_python)" -m vibecrafted_core.cli capabilities "$@"
}

cmd_lifecycle_help() {
  local verb="$1"
  local agent="${2:-<claude|codex|agy|junie|grok|cursor|kimi|copilot|omp>}"
  local description=""
  local flags="--last|--run-id <id>"
  case "$verb" in
    observe) description="Check an agent report or transcript." ;;
    await) description="Join the shared vc-server monitor until the run settles." ;;
    stop) description="Stop a run by launcher process group." ;;
  esac
  printf '\n'
  printf '%b⚒%b  %b%s%b\n' "$_copper" "$_reset" "$_bold" "$verb" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  %s\n' "$description"
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  if [[ "$agent" == "swarm" ]]; then
    printf '  vibecrafted swarm %s %s\n' "$verb" "$flags"
    printf '\n'
    return 0
  fi
  printf '  vibecrafted %s %s %s\n' "$verb" "$agent" "$flags"
  printf '\n'
}

cmd_lifecycle_command() {
  local verb="$1"
  local agent="${2:-}"
  shift 2 || true
  if [[ -z "$agent" ]] || _is_help_flag "$agent"; then
    cmd_lifecycle_help "$verb"
    [[ -n "$agent" ]] && return 0
    return 1
  fi
  if [[ "$agent" == "gemini" ]]; then
    printf '%b✗ gemini CLI is deprecated.%b Use agy (Google Antigravity CLI) instead.\n' "$_red" "$_reset" >&2
    return 1
  fi
  # Even a single-agent dispatch is a swarm: the run meta says agent=swarm and
  # the dispatch banner prints "await swarm --run-id …". The lifecycle verbs
  # must accept that identity (core cli.py AGENTS already does); everything
  # else (init, fork, resume) keeps refusing it.
  if [[ "$agent" != "swarm" ]] && ! _has_agent "$agent"; then
    printf '%b✗%b Unknown agent: %s\n' "$_red" "$_reset" "$agent" >&2
    return 1
  fi
  local arg
  for arg in "$@"; do
    if _is_help_flag "$arg"; then
      cmd_lifecycle_help "$verb" "$agent"
      return 0
    fi
  done
  cmd_lifecycle "$agent" "$verb" "$@"
}

# Back-compat thin wrapper; prefer cmd_lifecycle.
cmd_stop() {
  cmd_lifecycle "$1" stop "${@:2}"
}

run_mode() {
  local agent="$1"
  local mode="$2"
  shift 2
  local _mode_arg
  for _mode_arg in "$@"; do
    if [[ "$_mode_arg" == "--help" || "$_mode_arg" == "-h" ]]; then
      set -- --help
      break
    fi
  done
  if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
    case "$mode" in
      observe|await|stop)
        cmd_lifecycle_help "$mode" "$agent"
        return 0
        ;;
    esac
    printf '%b⚒%b  %b%s %s%b\n\n' "$_copper" "$_reset" "$_bold" "$agent" "$mode" "$_reset"
    case "$mode" in
      implement) printf '  Execute a plan file with the agent.\n  Usage: vibecrafted implement %s <plan.md>\n' "$agent" ;;
      research)  printf '  Research a topic using the agent.\n  Usage: vibecrafted research %s <plan.md>\n' "$agent" ;;
      review)    printf '  Review a bounded PR, branch, commit range, or artifact pack.\n  Usage: vibecrafted review %s <plan.md>\n' "$agent" ;;
      plan)      printf '  Generate an implementation plan.\n  Usage: vibecrafted plan %s <plan.md>\n' "$agent" ;;
      resume)    cmd_resume_help; return 0 ;;
    esac
    printf '\n'
    return 0
  fi
  case "$mode" in
    observe|await|stop|resume)
      cmd_lifecycle "$agent" "$mode" "$@"
      return
      ;;
  esac
  _ensure_helpers_loaded || return 1
  _run_helper "${agent}-${mode}" "$@"
}

run_skill() {
  local skill="$1"
  local agent="${2:-}"
  shift 2 || true

  if _is_help_flag "$agent"; then
    cmd_skill_help "$skill"
    return 0
  fi

  if [[ "$skill" == "init" ]]; then
    cmd_init "$agent" "$@"
    return
  fi

  if [[ "$skill" == "partner" ]]; then
    cmd_partner "$agent" "$@"
    return
  fi

  if [[ "$skill" == "operator" ]]; then
    cmd_operator "$agent" "$@"
    return
  fi

  if [[ "$skill" == "agents" ]]; then
    cmd_agents "$@"
    return
  fi

  # Research owns an optional, variadic agent contract. Preserve its argv
  # verbatim for the core parser instead of forcing the shared one-agent skill
  # shape (which otherwise mistakes a leading --prompt for an agent).
  if [[ "$skill" == "research" ]]; then
    [[ -n "$agent" ]] || {
      cmd_skill_help "$skill" >&2
      return 1
    }
    cmd_core_workflow_skill "$skill" "$agent" "$@"
    return
  fi

  if [[ "$skill" == "marbles" ]] && _is_marbles_control_subcommand "$agent"; then
    _ensure_helpers_loaded || return 1
    _run_helper "marbles-$agent" "$@"
    return
  fi

  if [[ "$agent" == "dashboard" ]]; then
    cmd_dashboard "vc-${skill}" "$@"
    return
  fi

  if [[ "$skill" == "marbles" && "$agent" == --* ]]; then
    printf '%b✗%b Missing marbles agent before flags.\n' "$_red" "$_reset" >&2
    printf '  Try: vibecrafted marbles codex --file <plan>\n' >&2
    printf '\n' >&2
    cmd_skill_help "$skill" >&2
    return 1
  fi

  if _is_help_flag "${1:-}"; then
    cmd_skill_help "$skill" "$agent"
    return 0
  fi

  [[ -n "$agent" ]] || {
    cmd_skill_help "$skill" >&2
    return 1
  }

  _has_agent "$agent" || {
    printf '%b✗%b Unknown agent: %s\n' "$_red" "$_reset" "$agent" >&2
    printf '\n' >&2
    cmd_skill_help "$skill" >&2
    return 1
  }

  # All execution skills use the same admission/parser/resolver owner.
  cmd_core_workflow_skill "$skill" "$agent" "$@"
}

run_wrapper() {
  local wrapper="$1"
  shift
  if [[ "$wrapper" == "vc-help" ]]; then
    cmd_help "$@"
    return
  fi
  if [[ "$wrapper" == "vc-start" ]]; then
    cmd_start "$@"
    return
  fi
  if [[ "$wrapper" == "vc-init" ]]; then
    cmd_init "$@"
    return
  fi
  if [[ "$wrapper" == "vc-resume" ]]; then
    cmd_resume "$@"
    return
  fi
  if [[ "$wrapper" == "vc-fork" ]]; then
    cmd_fork "$@"
    return
  fi
  if [[ "$wrapper" == "vc-operator" ]]; then
    cmd_operator "$@"
    return
  fi
  if [[ "$wrapper" == "vc-agents" ]]; then
    cmd_agents "$@"
    return
  fi
  if [[ "$wrapper" == "vc-dashboard" ]]; then
    cmd_dashboard "$@"
    return
  fi
  if [[ "$wrapper" == "vc-loop" ]]; then
    cmd_loop "$@"
    return
  fi
  if [[ "$wrapper" == "vc-cron" ]]; then
    cmd_cron "$@"
    return
  fi
  if [[ "$wrapper" == "vc-ship" ]]; then
    cmd_ship "$@"
    return
  fi
  if [[ "$wrapper" == "vc-dispatch" ]]; then
    cmd_dispatch "$@"
    return
  fi
  if [[ "$wrapper" == "vc-gui" ]]; then
    cmd_gui "$@"
    return
  fi
  if [[ "$wrapper" == "vc-tui" || "$wrapper" == "voc" ]]; then
    cmd_tui "$@"
    return
  fi
  if [[ "$wrapper" == "telemetry" ]]; then
    cmd_telemetry "$@"
    return
  fi
  if [[ "$wrapper" == "vc-doctor" ]]; then
    cmd_doctor "$@"
    return
  fi
  if [[ "$wrapper" == "vc-status" ]]; then
    cmd_stats "$@"
    return
  fi
  if [[ "$wrapper" == "vc-update" ]]; then
    cmd_update "$@"
    return
  fi
  if [[ "$wrapper" == "vc-reinstall" ]]; then
    cmd_core_cli reinstall "$@"
    return
  fi
  if [[ "$wrapper" == "vc-receipt" ]]; then
    cmd_receipt "$@"
    return
  fi
  if [[ "$wrapper" == "vc-scaffold-doctor" ]]; then
    cmd_scaffold_doctor "$@"
    return
  fi
  if [[ "$wrapper" == "vc-capabilities" ]]; then
    cmd_capabilities "$@"
    return
  fi
  if [[ "$wrapper" == "vc-workspace" ]]; then
    cmd_workspace "$@"
    return
  fi
  if [[ "$wrapper" == "vc-settlements" ]]; then
    cmd_settlements "$@"
    return
  fi
  if [[ "$wrapper" == "vc-uninstall" ]]; then
    cmd_uninstall "$@"
    return
  fi
  if [[ "$wrapper" == "vc-message" || "$wrapper" == "vc-claims" || "$wrapper" == "vc-resume-session" ]]; then
    cmd_core_cli "${wrapper#vc-}" "$@"
    return
  fi
  if [[ "$wrapper" == "vc-observe" || "$wrapper" == "vc-await" || "$wrapper" == "vc-stop" ]]; then
    cmd_lifecycle_command "${wrapper#vc-}" "$@"
    return
  fi
  local skill="${wrapper#vc-}"
  _has_skill "$skill" || {
    printf '%b✗%b Unknown wrapper: %s\n' "$_red" "$_reset" "$wrapper" >&2
    return 1
  }
  run_skill "$skill" "$@"
}

cmd_unknown() {
  local attempted="$1"
  printf '\n'
  printf '%b⚒%b  "%s" is not in the command deck.\n' "$_copper" "$_reset" "$attempted"
  printf '  Try %bvibecrafted help%b for the current surface.\n\n' "$_cyan" "$_reset"
}

cmd_swarm() {
  local mode="${1:-}"
  case "$mode" in
    observe|await|stop)
      shift || true
      run_mode "swarm" "$mode" "$@"
      ;;
    help|-h|--help|"")
      cmd_skill_help "research"
      ;;
    *)
      run_skill "research" "$@"
      ;;
  esac
}

main() {
  local invoked cmd
  invoked="$(basename "$0")"

  # Global flags — strip before dispatch
  export VIBECRAFTED_VERBOSE="${VIBECRAFTED_VERBOSE:-0}"
  local filtered=() keep_value=0 literal_tail=0
  for _arg in "$@"; do
    if ((keep_value || literal_tail)); then
      filtered+=("$_arg")
      keep_value=0
      continue
    fi
    case "$_arg" in
      --verbose) VIBECRAFTED_VERBOSE=1 ;;
      --) filtered+=("$_arg"); literal_tail=1 ;;
      --prompt|-p|--file|-f|--model|--repo|--root|--base|--runtime|--execution-runtime|--session|--run-id) filtered+=("$_arg"); keep_value=1 ;;
      *) filtered+=("$_arg") ;;
    esac
  done
  set -- ${filtered[@]+"${filtered[@]}"}

  if [[ "$invoked" != "vibecrafted" ]]; then
    run_wrapper "$invoked" "$@"
    return
  fi

  cmd="${1:-help}"
  shift || true

  case "$cmd" in
    help|-h|--help) cmd_help "$@" ;;
    start) cmd_start "$@" ;;
    init) cmd_init "$@" ;;
    operator) cmd_operator "$@" ;;
    partner) cmd_partner "$@" ;;
    resume) cmd_resume "$@" ;;
    fork) cmd_fork "$@" ;;
    observe|await|stop) cmd_lifecycle_command "$cmd" "$@" ;;
    gui) cmd_gui "$@" ;;
    server) cmd_server "$@" ;;
    tui) cmd_tui "$@" ;;
    doctor|check) cmd_doctor "$@" ;;
    receipt) cmd_receipt "$@" ;;
    capabilities) cmd_capabilities "$@" ;;
    control-plane-revalidate) cmd_control_plane_revalidate "$@" ;;
    workspace) cmd_workspace "$@" ;;
    scaffold-doctor) cmd_scaffold_doctor "$@" ;;
    dashboard|mc|mission-control|sessions) cmd_dashboard "$@" ;;
    housekeeping) cmd_housekeeping "$@" ;;
    loop) cmd_loop "$@" ;;
    cron) cmd_cron "$@" ;;
    ship) cmd_ship "$@" ;;
    dispatch|dispatcher) cmd_dispatch "$@" ;;
    telemetry) cmd_telemetry "$@" ;;
    stats|status) cmd_stats "$@" ;;
    settlements) cmd_settlements "$@" ;;
    claims|message|pr-closure|relocate|resume-session|usage) cmd_core_cli "$cmd" "$@" ;;
    reinstall) cmd_core_cli reinstall "$@" ;;
    update|upgrade) cmd_update "$@" ;;
    uninstall|remove) cmd_uninstall "$@" ;;
    version|--version|-v) printf 'vibecrafted %s\n' "$(_version)" ;;
    agents) cmd_agents "$@" ;;
    swarm) cmd_swarm "$@" ;;
    claude|codex|gemini|agy|junie|grok|cursor|kimi|copilot|omp)
      local action="${1:-<action>}"
      printf '%b✗%b Agent-first grammar was removed: vibecrafted %s %s\n' "$_red" "$_reset" "$cmd" "$action" >&2
      if [[ "$action" == "<action>" ]] || _is_help_flag "$action"; then
        printf '  Use: vibecrafted help %s\n' "$cmd" >&2
      else
        printf '  Use: vibecrafted %s %s' "$action" "$cmd" >&2
        [[ "$#" -gt 1 ]] && printf ' [arguments]' >&2
        printf '\n' >&2
      fi
      printf '  Agent names belong at the end of public commands.\n' >&2
      return 2
      ;;
    implement) run_skill "implement" "$@" ;;
    audit|canary|decorate|delegate|dou|followup|guard|hydrate|intents|justdo|marbles|ownership|polarize|prune|release|research|review|scaffold|trust|workflow)
      run_skill "$cmd" "$@"
      ;;
    *)
      cmd_unknown "$cmd"
      return 1
      ;;
  esac
}

main "$@"
