#!/usr/bin/env bash
# 𝚅𝚒𝚋𝚎𝚌𝚛𝚊𝚏𝚝𝚎𝚍. command deck
set -euo pipefail
readonly VIBECRAFTED_SERVICE_LIFECYCLE_LOCK_CONTRACT=1

_vc_source_launcher_ulimits() {
  local script_dir candidate
  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  for candidate in \
    "$script_dir/../runtime/scripts/lib/ulimits.sh" \
    "${VIBECRAFTED_ROOT:-}/vibecrafted-core/vibecrafted_core/runtime/scripts/lib/ulimits.sh" \
    "${VIBECRAFTED_TOOLS_HOME:-${XDG_DATA_HOME:-$HOME/.local/share}/vibecrafted/tools}/vibecrafted-current/vibecrafted-core/vibecrafted_core/runtime/scripts/lib/ulimits.sh" \
    "${VIBECRAFTED_HOME:-$HOME/.vibecrafted}/runtime/scripts/lib/ulimits.sh"; do
    [[ -n "$candidate" && -r "$candidate" ]] || continue
    # shellcheck disable=SC1090
    source "$candidate"
    vc_raise_launcher_limits
    return 0
  done
  printf '[warn] launcher ulimit helper not found; continuing without rlimit raise\n' >&2
  return 0
}
_vc_source_launcher_ulimits
unset -f _vc_source_launcher_ulimits

_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

_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)
_modes=(implement research review plan prompt observe await stop)
_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 "$(dirname "$script_path")" && pwd)"
    link_target="$(readlink "$script_path")"
    if [[ "$link_target" == /* ]]; then
      script_path="$link_target"
    else
      script_path="$script_dir/$link_target"
    fi
  done
  script_dir="$(cd "$(dirname "$script_path")" && pwd)"
  cd "$script_dir/.." && pwd
}

_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" ]]
}

_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
  env -u PYTHONHOME -u PYTHONPATH python3 - "$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) return 0 ;;
    gemini) return 1 ;;  # deprecated - see migration error below
    *) return 1 ;;
  esac
}

# 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:-}"
  command -v "$agent" >/dev/null 2>&1 && return 0
  local staged="$crafted_agent_bin/$agent"
  printf '%b✗%b %s CLI is not available.\n' "$_red" "$_reset" "$agent" >&2
  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 ;;
    esac
    printf '  Or check the whole fleet: vibecrafted doctor\n' >&2
  fi
  return 1
}

_has_mode() {
  local candidate="${1:-}"
  local mode
  for mode in "${_modes[@]}"; do
    [[ "$candidate" == "$mode" ]] && return 0
  done
  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
}

_skill_candidates() {
  local skill="$1"
  local runtime="${2:-}"
  local repo_source package_root
  repo_source="$(_repo_source_root 2>/dev/null || true)"
  package_root="$(_package_resource_root 2>/dev/null || true)"

  if [[ -n "$repo_source" ]]; then
    printf '%s\n' "$repo_source/skills/${skill}/SKILL.md"
    printf '%s\n' "$repo_source/vibecrafted-core/vibecrafted_core/skills/${skill}/SKILL.md"
  fi

  if [[ -n "$package_root" ]]; then
    printf '%s\n' "$package_root/skills/${skill}/SKILL.md"
  fi

  if [[ -n "$runtime" ]]; then
    printf '%s\n' "$HOME/.${runtime}/skills/${skill}/SKILL.md"
  fi

  printf '%s\n' \
    "$crafted_tools/skills/${skill}/SKILL.md" \
    "$crafted_skills/${skill}/SKILL.md" \
    "$HOME/.agents/skills/${skill}/SKILL.md"
}

_resolve_skill_path() {
  local skill="$1"
  local runtime="${2:-}"
  local candidate

  while IFS= read -r candidate; do
    [[ -r "$candidate" ]] || continue
    printf '%s\n' "$candidate"
    return 0
  done < <(_skill_candidates "$skill" "$runtime")

  printf '%b✗%b Could not find %s.\n' "$_red" "$_reset" "$skill" >&2
  printf '  Expected one of:\n' >&2
  _skill_candidates "$skill" "$runtime" | sed 's/^/    - /' >&2
  return 1
}

_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" \
    "${XDG_CONFIG_HOME:-$HOME/.config}/vetcoders/vc-skills.sh" \
    "$crafted_skills/runtime/shell/vetcoders.sh" \
    "$repo_helper"
}

_ensure_helpers_loaded() {
  local helper
  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
    # shellcheck disable=SC1090
    source "$helper"
    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
}

_control_plane_script() {
  local repo_source candidate
  repo_source="$(_repo_source_root 2>/dev/null || true)"
  for candidate in \
    "${repo_source:+$repo_source/scripts/control_plane_state.py}" \
    "$crafted_tools/scripts/control_plane_state.py" \
    "$(_script_repo_root)/scripts/control_plane_state.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
}

_core_module_dir() {
  _dispatcher_core_dir
}

_dispatcher_core_dir() {
  local repo_source candidate
  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
}

# Resolve the interpreter that owns vibecrafted_core by reading the shebang
# from the uv-tool shim on PATH, since it carries the correct uv python.
_vibecrafted_python() {
  local resolved shebang py
  if [[ -n "${VIBECRAFTED_PYTHON:-}" && -x "$VIBECRAFTED_PYTHON" ]]; then
    printf '%s\n' "$VIBECRAFTED_PYTHON"
    return 0
  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
  command -v python3 2>/dev/null || command -v python 2>/dev/null || 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)"
  PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
    "$python_bin" -m vibecrafted_core.cli help "$@"
}

_sync_control_plane_best_effort() {
  local script_path
  script_path="$(_control_plane_script 2>/dev/null || true)"
  [[ -n "$script_path" ]] || return 0
  python3 "$script_path" 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
}

# Legacy name kept for older call sites; resolves the product TUI workspace.
_operator_tui_dir() {
  _voc_app_dir
}

_resolve_voc_binary() {
  # Canonical product binary is `voc` (make install-app-binaries). Prefer an
  # installed real file, then a local release/debug build, then legacy names.
  local app_dir candidate
  if candidate="$(command -v voc 2>/dev/null)" && [[ -n "$candidate" && -x "$candidate" ]]; then
    printf '%s\n' "$candidate"
    return 0
  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
  # 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 'Triple-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'
}

_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 '  --session <id>                 Session ID to resume (optional)\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-session                 Branch into a NEW session id, base untouched (claude only)\n'
      printf '  (no --session)                 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>}"
  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 '  Plan-based helper modes for %s.\n' "$agent"
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted %s <implement|research|review|plan|prompt|observe|await|stop> [args]\n' "$agent"
  printf '\n'
  printf '%bModes:%b\n' "$_bold" "$_reset"
  printf '  implement <plan.md>            Execute a plan file\n'
  printf '  research  <plan.md>            Research a topic or plan file\n'
  printf '  review    <plan.md>            Review a bounded PR, branch, commit range, or artifact pack\n'
  printf '  plan      <plan.md>            Generate an implementation plan\n'
  printf '  prompt    <plan.md>            Free-form prompt with plan context\n'
  printf '  observe   --last               Check the last report or transcript\n'
  printf '  await     --last               Wait for metadata completion + summary\n'
  printf '  stop      --run-id <id>        TERM the launcher process group and mark stopped\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted %s implement .vibecrafted/plans/my-plan.md\n' "$agent"
  printf '  vibecrafted %s research .vibecrafted/plans/my-plan.md\n' "$agent"
  printf '  vibecrafted %s observe --last\n' "$agent"
  printf '  vibecrafted %s await --last\n' "$agent"
  printf '  vibecrafted %s stop --run-id <id>\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 '  Start the operator vc-frame session (default board: operator).\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted start\n'
  printf '  vibecrafted start operator\n'
  printf '  vc-start\n'
  printf '  vc-start operator\n'
  printf '  vc-start resume\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted start\n'
  printf '  vc-start operator\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 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 <plan.dispatch.toml> [--doctor|--dry-run|--json|--resume <run-id>]\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 only and exits non-zero on dispatch-doctor errors.\n'
  printf '  --dry-run renders every worker prompt under reports_dir/dry-run without launching.\n'
  printf '  Full dispatch writes tracker.md, journal.md, 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>] [--root <path>] [--runtime <headless|terminal|visible>] [--tick-ms <ms>]\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 an existing agent session, or continue from AICX multi-agent context.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted resume <claude|codex|agy|junie|grok> --session <session_id> [flags]\n'
  printf '  vibecrafted resume <claude|codex|agy|junie|grok> [flags]\n'
  printf '\n'
  printf '%bWithout --session:%b\n' "$_bold" "$_reset"
  printf '  Builds a bounded continuity pack from aicx sessions list + intents + overlay.\n'
  printf '  A bare resume stays interactive; the AICX pack is continuity transport,\n'
  printf '  not operator job text. A same-agent candidate resumes provider-native;\n'
  printf '  otherwise a new interactive session starts with the bounded context.\n'
  printf '  Explicit --prompt/--file without --session skips historical candidates and\n'
  printf '  starts a new tracked headless job.\n'
  printf '  Override window: VIBECRAFTED_RESUME_AICX_HOURS=72\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  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_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]\n'
  printf '  vc-init [claude|codex|agy|junie|grok]\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted init claude\n'
  printf '  vc-init codex\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 recent agent activity from today.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  vibecrafted status\n'
  printf '  vibecrafted stats\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 --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 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] [options]\n'
  printf '  vibecrafted server service [install|start|stop|status|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 '\n'
}


cmd_telemetry_help() {
  printf '\n'
  printf '%b⚒%b  %btelemetry%b\n' "$_copper" "$_reset" "$_bold" "$_reset"
  printf '%b─────────────────────────────────────────%b\n' "$_steel" "$_reset"
  printf '  Smoke the marbles telemetry path through the installed command deck.\n'
  printf '\n'
  printf '%bUsage:%b\n' "$_bold" "$_reset"
  printf '  telemetry smoke [--agent <claude|codex|agy|junie|grok>] [--count <n>] [--root <path>] [--no-watch|--watch]\n'
  printf '  vibecrafted telemetry smoke [--agent <claude|codex|agy|junie|grok>] [--count <n>] [--root <path>] [--no-watch|--watch]\n'
  printf '\n'
  printf '%bExamples:%b\n' "$_bold" "$_reset"
  printf '  telemetry smoke --count 1 --no-watch\n'
  printf '  telemetry smoke --agent claude --count 2 --watch\n'
  printf '\n'
}

_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_smoke() {
  local agent="codex"
  local count="1"
  local root=""
  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
        }
        root="$1"
        ;;
      --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
  }
  _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 "$@"
      ;;
    *)
      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=""
  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=""
  candidate="$(command -v vc-server-supervisor 2>/dev/null || true)"
  [[ -n "$candidate" && -x "$candidate" ]] || return 1
  _realpath_quiet "$candidate"
}

_server_supervisor_cli() {
  local command_name="${1:-}"
  shift || true
  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 \
        "$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"
}

_server_python() {
  python3 - "$@" <<'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 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() {
  _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() {
  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
  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" == "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"

      # 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 "$HOME/.local/bin/vc-server" ]] && \
          _adopt_launch_witness \
            server "$existing_pid" "$HOME/.local/bin/vc-server" \
            "$HOME/.local/bin/vc-server"; 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" "$HOME/.local/bin/vc-server" \
                  "$HOME/.local/bin/vc-server"; 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
      local server_bin="$HOME/.local/bin/vc-server"
      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

      local site_root="${VIBECRAFTED_RUNTIME_ROOT:-${VIBECRAFTED_RUNTIME_HOME:-$HOME/.local/share/vibecrafted}}/server/site"
      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"
      ;;
    status)
      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 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 "$@"
      ;;
    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 server_bin="$HOME/.local/bin/vc-server"
      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
      local guardian_bin
      guardian_bin="$(_guardian_binary 2>/dev/null || true)"
      if [[ -n "$guardian_bin" && -x "$guardian_bin" ]]; then
        printf "  [%b✓%b] Guardian entrypoint present and executable at %s\n" "$_green" "$_reset" "$guardian_bin"
      else
        printf "  [%b✗%b] Guardian entrypoint vc-guardian is missing or not executable\n" "$_red" "$_reset"
        has_errors=1
      fi

      # 2. Site root & Fonts check
      local site_root="${VIBECRAFTED_RUNTIME_ROOT:-${VIBECRAFTED_RUNTIME_HOME:-$HOME/.local/share/vibecrafted}}/server/site"
      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

      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

      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
      ;;
    *)
      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
  if _is_help_flag "${1:-}"; then
    cmd_tui_help
    return 0
  fi
  app_dir="$(_voc_app_dir 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"

  _sync_control_plane_best_effort

  if [[ -n "${binary_path:-}" && -x "$binary_path" ]]; then
    "$binary_path" --state-root "$state_root" --deck "$deck_path" "$@"
    return $?
  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)
      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
      ;;
    start)
      cmd_start_help
      return
      ;;
    dashboard|mc|mission-control)
      cmd_dashboard_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
      ;;
    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
      ;;
    agents)
      cmd_agents
      return
      ;;
    implement)
      cmd_skill_help "implement"
      return
      ;;
    audit|decorate|delegate|dou|followup|guard|hydrate|intents|justdo|marbles|ownership|partner|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 previous session\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 '  %bupdate%b               Update to the latest release\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\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 '\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=== MODES (per agent) ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  %bvibecrafted <agent> implement%b <plan.md>   Execute a plan file\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted <agent> research%b  <plan.md>   Single-agent research mode\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted <agent> review%b    <plan.md>   Review bounded code artifacts\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted <agent> plan%b      <plan.md>   Generate an implementation plan\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted <agent> prompt%b    <plan.md>   Free-form prompt with context\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted <agent> observe%b   --last      Check last agent report/transcript\n' "$_cyan" "$_reset"
  printf '\n'
  printf '%b=== RESEARCH (launcher) ===%b\n' "$_bold" "$_reset"
  printf '\n'
  printf '  %bvibecrafted research%b [--prompt "text" | --file plan.md]   Launch Claude + codex + junie swarm\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 smoke%b [flags]                Smoke the headless marbles telemetry path\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted telemetry smoke%b [flags]    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 start%b [layout]            Alias for %bvibecrafted dashboard%b\n' "$_cyan" "$_reset" "$_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%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   Triple-agent research (claude + codex + junie)\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 smoke%b [flags]  Smoke the marbles telemetry path\n' "$_cyan" "$_reset"
  printf '  %bvibecrafted resume%b <agent> [flags]    Resume an existing agent session\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 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>                 Session ID for vibecrafted resume\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 codex implement .vibecrafted/plans/my-plan.md\n'
  printf '  vibecrafted claude research .vibecrafted/plans/my-plan.md\n'
  printf '  vibecrafted agy review .vibecrafted/plans/my-plan.md   # (gemini deprecated)\n'
  printf '  vibecrafted codex observe --last\n'
  printf '  vibecrafted resume claude --session <id> --prompt "Continue the fix"\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 '  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 previous_repo_vc_frame_pref="${VIBECRAFTED_PREFER_REPO_VC_FRAME-}"
  local status
  # Product entrypoint choke: load full lifecycle helpers (shell modules,
  # frontier pin, frame launcher). Ordinary shells stay PATH-only.
  # Note: live operator path is shell `vc-start` → same prepare function;
  # deck start is secondary (vibecrafted start) and must share that choke.
  _ensure_helpers_loaded || return 1
  export VIBECRAFTED_PREFER_REPO_VC_FRAME=1
  if declare -F _vetcoders_product_entry_prepare >/dev/null 2>&1; then
    _vetcoders_product_entry_prepare
  fi
  if [[ "${VIBECRAFTED_PRODUCT_ENTRY_PROBE:-0}" == "1" ]]; then
    if declare -F _vetcoders_product_entry_probe_print >/dev/null 2>&1; then
      _vetcoders_product_entry_probe_print
    else
      printf 'VC_FRAME_CONFIG_DIR=%s\n' "${VC_FRAME_CONFIG_DIR:-}"
    fi
    status=0
  elif [[ "${1:-}" == "resume" ]]; then
    # Call frame launcher directly — never re-enter via public vc-start alias
    # (thin passthrough to `vibecrafted start` fork-bombs: Python→deck→helper).
    shift || true
    _vetcoders_resume_operator_session "$@"
    status=$?
  else
    if [[ "${1:-}" == "operator" || "${1:-}" == "vibecrafted" ]]; then
      shift || true
    fi
    _vetcoders_launch_dashboard operator "$@"
    status=$?
  fi
  if [[ -n "${previous_repo_vc_frame_pref}" ]]; then
    export VIBECRAFTED_PREFER_REPO_VC_FRAME="${previous_repo_vc_frame_pref}"
  else
    unset VIBECRAFTED_PREFER_REPO_VC_FRAME
  fi
  return "$status"
}

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_skill" != "justdo" ]] || core_skill="implement"
  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
  }
  PYTHONPATH="$core_dir${PYTHONPATH:+:$PYTHONPATH}" \
    "$(_vibecrafted_python)" -m vibecrafted_core.cli "$core_skill" "$@" --source-dir "$(_script_repo_root)"
}

cmd_init() {
  # Leading --help must never be parsed as an agent name (vc-init --help audit).
  if _is_help_flag "${1:-}"; 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
}


# 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 release → debug under each root. Returns 0 and prints path when found.
_scaffold_doctor_find_bin() {
  local root candidate
  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="" 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
        ;;
      --json) json=1; shift ;;
      -h|--help)
        printf 'Usage: vibecrafted scaffold-doctor --plan <plan_root> [--json]\n'
        printf '       vibecrafted scaffold-doctor <home> <org> <repo> <day> <plan-id> [--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 [[ "$json" -eq 1 ]]; then
      "$bin" --plan "$plan" --json
    else
      "$bin" --plan "$plan"
    fi
  elif [[ ${#args[@]} -ge 5 ]]; then
    if [[ "$json" -eq 1 ]]; then
      "$bin" "${args[@]}" --json
    else
      "$bin" "${args[@]}"
    fi
  else
    printf 'Usage: vibecrafted scaffold-doctor --plan <plan_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)
      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_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:]))' \
      "$@"
}

_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
      ;;
  esac

  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=""
  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 Uninstall installer not found.\n' "$_red" "$_reset" >&2
    return 1
  }
  python3 "$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_cleanup() {
  # Remove known stale files that may survive across version transitions.
  local tools_dir="${crafted_tools:-$HOME/.local/share/vibecrafted/tools/vibecrafted-current}"
  local stale_candidates=(
    "$tools_dir/scripts/vibecraft"
    "$tools_dir/scripts/vc-implement"
  )
  local removed=0
  for f in "${stale_candidates[@]}"; do
    if [[ -e "$f" ]]; then
      rm -f "$f"
      (( removed++ ))
    fi
  done
  if (( removed )); then
    printf '  %bCleaned %d stale file(s) from previous install.%b\n' "$_dim" "$removed" "$_reset"
  fi
}

_post_update_banner() {
  local old_ver="$1"
  local new_ver
  new_ver="$(_version)"
  _post_update_cleanup
  if [[ "$new_ver" != "$old_ver" ]]; then
    printf '\n  %bUpdated:%b %s -> %b%s%b\n' "$_bold" "$_reset" "$old_ver" "$_green" "$new_ver" "$_reset"
  fi
  printf '  Run %bvibecrafted doctor%b to verify the update.\n\n' "$_cyan" "$_reset"
}

cmd_update() {
  local makefile="" repo_source="" installed_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=}" ;;
    esac
    shift
  done
  repo_source="$(_repo_source_root 2>/dev/null || true)"

  installed_ver="$(_version)"
  printf '\n%b⚒  Vibecrafted Update%b\n' "$_bold$_copper" "$_reset"
  printf '  Installed: %b%s%b\n' "$_cyan" "$installed_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 [[ "$installed_ver" == "$available_ver" ]] && (( ! force )); then
        printf '  %b(up to date — use --force to reinstall)%b\n\n' "$_dim" "$_reset"
        return 0
      fi
    fi
  fi

  local update_status=0

  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"
    update_status=$?
    _post_update_banner "$installed_ver"
    return "$update_status"
  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"
    update_status=$?
    _post_update_banner "$installed_ver"
    return "$update_status"
  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
  if ! _run_remote_install_fallback "$remote_install_url" "$channel_ref"; then
    return 1
  fi
  update_status=0
  _post_update_banner "$installed_ver"
  return "$update_status"
}

cmd_agents() {
  printf '\n'
  printf '%bVibecrafted agent helpers%b\n' "$_bold" "$_reset"
  printf '  Use %bvibecrafted <agent> implement|research|review|plan%b for plan-based helper flows.\n' "$_cyan" "$_reset"
  printf '  Example: vibecrafted codex implement .vibecrafted/plans/my-plan.md\n'
  printf '\n'
}

cmd_resume() {
  local agent="${1:-}"
  if _is_help_flag "$agent"; then
    cmd_resume_help
    return 0
  fi
  [[ -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" "$@"
}

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

run_mode() {
  local agent="$1"
  local mode="$2"
  shift 2
  if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
    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 %s implement <plan.md>\n' "$agent" ;;
      research)  printf '  Research a topic using the agent.\n  Usage: vibecrafted %s research <plan.md>\n' "$agent" ;;
      review)    printf '  Review a bounded PR, branch, commit range, or artifact pack.\n  Usage: vibecrafted %s review <plan.md>\n' "$agent" ;;
      plan)      printf '  Generate an implementation plan.\n  Usage: vibecrafted %s plan <plan.md>\n' "$agent" ;;
      prompt)    printf '  Free-form prompt with plan context.\n  Usage: vibecrafted %s prompt <plan.md>\n' "$agent" ;;
      observe)   printf '  Check the last agent report or transcript.\n  Usage: vibecrafted %s observe --last\n' "$agent" ;;
      await)     printf '  Wait for the last agent run to finish via metadata.\n  Usage: vibecrafted %s await --last\n' "$agent" ;;
      stop)      printf '  Stop a run by launcher process group.\n  Usage: vibecrafted %s stop --run-id <id>\n' "$agent" ;;
    esac
    printf '\n'
    return 0
  fi
  case "$mode" in
    observe|await|stop)
      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" == "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 %s %s\n' "$agent" "$*" >&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
  }

  case "$skill" in
    implement|justdo|workflow|review|marbles)
      cmd_core_workflow_skill "$skill" "$agent" "$@"
      return
      ;;
  esac

  local dispatch_skill="$skill"
  [[ "$dispatch_skill" != "implement" ]] || dispatch_skill="justdo"
  local helper_name="${agent}-skill-${skill}"
  _ensure_helpers_loaded || return 1
  if command -v "$helper_name" >/dev/null 2>&1; then
    _run_helper "$helper_name" "$@"
    return
  fi
  if command -v _vetcoders_skill_entry >/dev/null 2>&1; then
    _vetcoders_skill_entry "$agent" "$dispatch_skill" "$@"
    return
  fi
  printf '%b✗%b Missing helper %s and no generic skill entry is available.\n' "$_red" "$_reset" "$helper_name" >&2
  return 1
}

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-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
  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=()
  for _arg in "$@"; do
    case "$_arg" in
      --verbose) VIBECRAFTED_VERBOSE=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 "$@" ;;
    resume) cmd_resume "$@" ;;
    gui) cmd_gui "$@" ;;
    server) cmd_server "$@" ;;
    tui) cmd_tui "$@" ;;
    doctor|check) cmd_doctor "$@" ;;
    receipt) cmd_receipt "$@" ;;
    workspace) cmd_workspace "$@" ;;
    scaffold-doctor) cmd_scaffold_doctor "$@" ;;
    dashboard|mc|mission-control|sessions) cmd_dashboard "$@" ;;
    loop) cmd_loop "$@" ;;
    cron) cmd_cron "$@" ;;
    ship) cmd_ship "$@" ;;
    dispatch|dispatcher) cmd_dispatch "$@" ;;
    telemetry) cmd_telemetry "$@" ;;
    stats|status) cmd_stats "$@" ;;
    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)
      local mode="${1:-}"
      if _is_help_flag "$mode"; then
        cmd_agent_help "$cmd"
        return 0
      fi
      [[ -n "$mode" ]] || {
        cmd_agent_help "$cmd" >&2
        return 1
      }
      shift || true
      _has_mode "$mode" || {
        printf '%b✗%b Unknown mode: %s\n' "$_red" "$_reset" "$mode" >&2
        return 1
      }
      run_mode "$cmd" "$mode" "$@"
      ;;
    implement) run_skill "implement" "$@" ;;
    audit|canary|decorate|delegate|dou|followup|guard|hydrate|intents|justdo|marbles|ownership|partner|polarize|prune|release|research|review|scaffold|trust|workflow)
      run_skill "$cmd" "$@"
      ;;
    *)
      cmd_unknown "$cmd"
      return 1
      ;;
  esac
}

main "$@"
