#!/usr/bin/env bash
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Remote execution resolves inventory and cluster identity on the server.
# Keep the client independent of local cluster files and Python YAML packages.
if [[ "${1:-}" == remote ]]; then
    exec "${REPO_ROOT}/scripts/jeannie-remote" "${@:2}"
fi

BUILDX_CONFIG="/tmp/buildx-config.toml"
HOMELAB_STATE_DIR="${HOMELAB_STATE_DIR:-${XDG_DATA_HOME:-${HOME}/.local/share}/homelab}"
COSIGN_KEY_PREFIX="${COSIGN_KEY_PREFIX:-${HOMELAB_STATE_DIR}/cosign/cosign}"
COSIGN_KEY_PATH="${COSIGN_KEY_PATH:-${COSIGN_KEY_PREFIX}.key}"
COSIGN_PUBLIC_KEY_PATH="${COSIGN_PUBLIC_KEY_PATH:-${COSIGN_KEY_PREFIX}.pub}"
COSIGN_PASSWORD_FILE="${COSIGN_PASSWORD_FILE:-${HOMELAB_STATE_DIR}/cosign/cosign.password}"
COSIGN_VERSION="${COSIGN_VERSION:-2.6.3}"
COSIGN_BIN="${COSIGN_BIN:-}"
HOMELAB_COSIGN_PUBLIC_KEY_CONFIGMAP="${HOMELAB_COSIGN_PUBLIC_KEY_CONFIGMAP:-homelab-cosign-public-key}"
HOMELAB_SBOM_PREDICATE_TYPE="${HOMELAB_SBOM_PREDICATE_TYPE:-https://spdx.dev/Document}"
JEANNIE_LOG_DIR="${JEANNIE_LOG_DIR:-${HOMELAB_STATE_DIR}/logs}"
JEANNIE_LOG_FILE="${JEANNIE_LOG_FILE:-}"
JEANNIE_ERROR_LOG_FILE="${JEANNIE_ERROR_LOG_FILE:-}"
JEANNIE_STEP_INDEX=0
JEANNIE_STEP_TOTAL=0

# shellcheck disable=SC1091
source "${REPO_ROOT}/scripts/report-ui"
source "${REPO_ROOT}/scripts/status-focus"
source "${REPO_ROOT}/scripts/doctor-focus"
source "${REPO_ROOT}/scripts/doctor-runner-report"
source "${REPO_ROOT}/lib/jeannie/core.sh"
source "${REPO_ROOT}/lib/jeannie/env.sh"
source "${REPO_ROOT}/lib/jeannie/cluster-context.sh"
source "${REPO_ROOT}/lib/jeannie/toolchain.sh"
source "${REPO_ROOT}/lib/jeannie/pimox.sh"
source "${REPO_ROOT}/lib/jeannie/preflight.sh"
source "${REPO_ROOT}/lib/jeannie/pipeline.sh"
source "${REPO_ROOT}/lib/jeannie/security.sh"
# shellcheck disable=SC1091
source "${REPO_ROOT}/lib/jeannie/commands.sh"

trap 'rm -f "${BUILDX_CONFIG}"' EXIT

# Load persisted OCI discoveries before inventory defaults so a replacement
# edge VM's public IP takes precedence over the static bootstrap inventory.
oci_foundation_load_config
load_homelab_inventory_defaults
source "${REPO_ROOT}/scripts/cluster-env.sh"
export_homelab_inventory_tf_vars
export KUBECONFIG_PATH="${LAB_KUBECONFIG_PATH}"
cluster_context_enable

print_usage() {
    cat <<'EOF'
Usage: ./jeannie <command> [args]

Base, Inventory, And Planning
  help | -h | --help                         Show this grouped help.
  validate                                   Run repo validation checks.
  inventory-check                            Validate the canonical homelab inventory.
  cluster-profile [select NAME]             Show or persist the operational profile for CLI/API/self-healing.
  cluster-runtime check                     Verify other cluster profiles are stopped.
  cluster-transition k3s-to-native [--yes]    Move accidental laptop K3s to the native ARM host.
  cluster-transition k3s-runtime-to-ssd [--yes] Move native K3s runtime to declared SSD storage.
  cluster-context {status|check|enroll|migrate} [--yes] [--stack NAME]
                                             Review pinned cluster identity and scoped state.
  preflight                                  Run non-mutating infrastructure preflight checks.
  gateway-lab {plan|apply|status|test}        Manage the isolated Gateway API and FastAPI lab.
  progressive-lab {plan|apply|status|run|rollback} Practice canary rollout and rollback.
  secrets-lab {plan|apply|status|test|rotate|recover|recover-cert} Practice secret and certificate lifecycle.
  doctor-preapply                            Run deeper pre-apply safety checks.
  plan [all|provisioning|cluster|platform|apps|edge]
                                             Run OpenTofu plans without applying changes.

Build And Bootstrap
  up                                         Deploy the full homelab pipeline.
  cluster                                    Apply the selected cluster runtime only.
  deploy-gitea                               Deploy the Debian-hosted Gitea container.
  deploy-api                                  Deploy the Temporal-backed Jeannie API on Debian.
  deploy-heimdall                            Deploy the Debian-hosted Heimdall dashboard.
  deploy-searxng                             Deploy Debian-hosted SearXNG and Valkey.
  deploy-privatebin                          Deploy Debian-hosted encrypted paste service.
  deploy-miniflux                            Deploy Debian-hosted private RSS reader.
  deploy-opsproof                            Build and deploy the Debian-hosted OpsProof UI.
  deploy-dex                                 Deploy the Debian-hosted Dex SSO stack.
  monitoring {plan|migrate|apply|refresh|exporters|status|validate} Manage Debian monitoring; preserve cluster discovery and Dex.
  deploy-office                              Deploy Nextcloud + ONLYOFFICE online office.
  deploy-matrix                              Deploy the Matrix homeserver (Synapse + Element + Postgres).
  deploy-ai-stack                            Deploy the Debian-hosted AI gateway stack.
  deploy-ai-tools                            Install/wire local AI CLIs to the AI gateway.
  goose-graph <update|context|learn|propose> [question]
                                             Explore the repo with Goose and Graphify.
  ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench BACKEND|suite [REPEATS]|doctor-prepare|doctor-suite [REPEATS]|doctor-auto-rank REPORT|doctor-add-external REPORT RANKING MODEL|doctor-rank REPORT REVIEW} Manage AI experiments.
  compose-intent {stopped|running|clear|list} [PROJECT/SERVICE...] Record Debian Compose desired state.
  ai-lab headroom-install                    Install the pinned optional compression lab environment.
  ai-lab doctor-retrieval-plan                  Preview committed repository evidence for Doctor lab cases.
  ai-lab doctor-retrieval-bench [REPEATS]       Compare fixed 7B decisions with/without targeted retrieval.
  ai-lab doctor-context-bench baseline CONVERSATION [REPEATS]
  ai-lab doctor-context-bench compare BASELINE Compare Headroom with a saved Doctor decision baseline.
  lab-window <start|stop|status>              Apply the scheduled lab power window.
  deploy-omniroute                           Deploy the OmniRoute LLM routing gateway.
  deploy-hermes                              Deploy the Hermes agent (git-install + venv + gateway service).
  hermes-connect                             Connect Hermes to read-only Jeannie status and runbooks.
  bootstrap-gitea-repo                       Ensure the Gitea repo and SSH key wiring exist.
  repo-sync [--remote REMOTE] [--branch BRANCH]
                                             Safely fast-forward the Debian pipeline checkout.
  rpi-services                               Deploy Pi-hole, Unbound, and Uptime Kuma on RPi4.
  host-bootstrap rpi4 [status|plan|nfs-stage|install-image|apply --yes]
                                             Provision/check the physical RPi4, then bootstrap host services.
  ollama-setup                               Install/configure Ollama on the Debian host.
  artifact-cache {status|up|down|instructions}
                                             Manage optional Debian artifact caches.
  blockchain-devnet {status|up|down|logs|rpc}
                                             Manage the local Ethereum Anvil devnet.
  blockchain-test [forge args...]            Run Foundry tests for labs/blockchain.
  blockchain-wallet {instructions|new|address|sign-message}
                                             Practice dev wallet and signing workflows.
  golden-ledger {show|check}                 Show or validate Pimox golden image versions.

Cluster Lifecycle
  rebuild-cluster                            Refuses automatic rebuild until an identity transition is reviewed.
  stop-cluster                               Stop Kubernetes and worker VMs without destroy.
  start-cluster                              Start Kubernetes and desired worker VMs.
  shutdown {plan|apply --yes}                Stop homelab services on every managed host; keep Jeannie API.
  start {plan|apply}                         Start homelab services on every managed host.
  cleanup-debian-k8s                         Remove old Debian kubeadm runtime after Pimox offload.
  workers <list|tailnet|start|stop|restart|drain|uncordon|recreate-plan|rebalance|disk-status|disk-cleanup>
                                             Manage Pimox/Kubernetes workers.
  move-prometheus-stack-workers              Move monitoring workloads to worker nodes.
  doctor-versions [--all|--details|--verbose|--json]
                                             Check Kubernetes/container tooling versions.

Operator View And Reports
  status [--fast|--deep] [--ai] [--all|--details|--verbose|--json] Check health; --deep includes logs and backups.
  status {all|oci|rpi|opi5|debian|cluster} [--json|--details] Fast inventory-scoped overview.
  status --heal-plan                         Build a guarded self-heal plan from status.
  status --heal                              Dry-run auto-eligible self-heal actions.
  scorecard                                  Compact pass/warn/fail operator scorecard.
  capacity                                   Compact capacity and placement report.
  capacity-advisor                          Decide whether to add VMs or fix placement/resources.
  capacity-limits [namespace]               Recommend requests/limits YAML snippets.
  recover-plan                               Print disaster recovery order and prerequisites.
  recover-power [--dry-run]                  Run or preview post-outage recovery.
  heal {plan|apply|cleanup-stale-pods}        Plan/apply guarded self-healing actions.
  self-heal {dry-run|serve|install-service [--apply]}
                                             Run Alertmanager-driven Jeannie self-heal loop.
  incident {list|replay|triage}              Classify incident text and suggest read-only next steps.
  safety-case [--since REF] [PATH...]        Generate risk, blast-radius, test, and rollback case.
  agent-sandbox {check|policy}               Classify proposed commands against agent policy.
  impact [--since REF] [PATH...]             Explain affected lab areas before changes.
  review-last-change [REF]                   Summarize changed files, impact, validation.
  map [--dot]                                Print the homelab dependency map.
  remote <read-only-command> [args...]      Execute an allowlisted command on Debian.
  change-journal {list|path}                 Show risky-command journal entries.
  release-snapshot                           Write a pre-change release snapshot.

Observability And GitOps
  grafana-dashboards {list|apply}            List or apply repo-managed Grafana dashboards.
  sso {plan|apply}                           Deploy Dex and enable Grafana + Gitea SSO.
  sso-grafana {plan|apply}                   Enable Grafana SSO through Dex.
  sso-gitea {plan|apply}                     Enable Gitea SSO through Dex.
  dex-secret {ensure|file}                   Generate/check SOPS-encrypted Dex bootstrap secrets.
  gitea-runner-secret {migrate|apply|file}   Convert/apply the Gitea runner SOPS secret.
  gitops-status                              Print focused Argo CD health and sync status.
  gitops {diff [APP]|refresh APP|--all}      Inspect drift or request an Argo CD refresh.
  storage {status|cleanup|snapshot|expand|rebalance} Manage and inspect storage safely.
  mesh doctor [--json]                      Run read-only Kubernetes, Calico, SSH, and Tailscale checks.
  platform [all|calico|metrics|dns|metallb|ingress|storage|argocd|security|logging|monitoring|tools]
                                             Deploy one platform component or the full platform stack.
  edge                                       Deploy/check the OCI edge stack only.
  email-vm {status|plan|apply|setup|status-server|destroy --yes}
                                             Manage the OCI email VM and its mail-server baseline.
  oci-foundation {verify|status|plan|review-edge-plan PLAN|apply|destroy --yes}
                                             Create the opt-in OCI compartment, network, edge VM, and email VM.
  oci-auth {install|init [--force]|check}     Install/check OCI CLI and API-key authentication on Debian.
  oci {status|doctor|agent-status|restart-edge|bastion ssh [--print-command]|cleanup}
                                             Inspect OCI resources, open Bastion SSH, or clean up infrastructure.
  edge-cache-flush                          Clear Nginx, Varnish, and Squid edge caches.
  edge diagnose                             Inspect edge startup errors and port listeners.
  promote {plan|validate|rollback APP}       Run canary promotion gates and rollback plan.
  cert-check                                 Check public DNS, TLS, and edge URL health.
  backup-status                              Check backup and restore-drill freshness.
  backup oci {status|plan|upload|restore-verify|schedule|lifecycle|freshness}
                                             Manage encrypted OCI Object Storage backups.
  synthetic-checks                           Run end-to-end service probes.
  resource-budget                            Report Kubernetes resource request/limit gaps.
  route-inventory                            Report routes and Uptime Kuma coverage.
  control-plane {status|taint|untaint|pods}
                                             Keep normal pods off the Debian control plane.
  explain <command>|output                   Explain warnings/errors and fix commands.

Recovery And State
  backup-gitea                               Back up the Debian-hosted Gitea data.
  backup                                     Run Pimox-aware encrypted backup profile.
  drill-restore                              Run all restore drills.
  drill-gitea-restore                        Run the Gitea restore drill.
  drill-pihole-restore                       Run the Pi-hole restore drill.
  state-backup                               Back up local OpenTofu state files.
  state status [STACK] [--json]              Inspect OpenTofu locks and drift (provisioning, cluster, platform, apps, edge, oci).
  pimox {status [VMID]|console VMID}         Inspect Pimox VMs or open a serial emergency console.

Focused Doctors
  doctor {oci|rpi|opi5|debian|cluster|APPLICATION} [ITEM] [--ai|--json|--details]
                                             Diagnose one area or named item.
  doctor-edge [--all|--details|--verbose|--json]
                                             Diagnose edge routing and public exposure.
  doctor-homelab [--all|--details|--verbose|--json]
                                             Run post-migration Pimox/Debian/edge checks.
  doctor-gitea [--all|--details|--verbose|--json]
                                             Diagnose Gitea local/public access.
  doctor-dex                                 Check encrypted Dex source against its rendered config.
  doctor-rpi [--all|--details|--verbose|--json]
                                             Diagnose RPi services and DNS.
  doctor-cluster [--all|--details|--verbose|--json]
                                             Diagnose Kubernetes cluster health.
  doctor-k8s [--no-holmes|--json]            Save read-only Kubernetes + Holmes triage artifacts.

Access, Secrets, And Policy
  access-audit                               Audit SSH, Gitea, Kubernetes, and Tailscale access.
  kubeconfig-readonly                        Create/check read-only kubeconfig material.
  secrets-init                               Initialize SOPS/age secret tooling.
  secrets-check                              Validate repo-managed secret prerequisites.
  secrets rotate {status|plan|SERVICE}       Report rotation age or rotate a supported service.
  tailnet-policy-check                       Validate Tailscale ACL policy as code.
  fix-debian-docker-root                     Repair Debian Docker root placement.

Apps And Services
  apps                                       Deploy application stack only.
  website-translation-model                  Prepare website translation model support.
  website-ollama-listen                      Configure website Ollama access.
  install-gitea-runner [TOKEN]               Install the Gitea Actions runner.
  network-sandbox {plan|prepare|provision|start|stop|verify|isolation-tests|wan-probe|wan-reset|capture} Manage the independent network lab.

Security Learning
  security-scan                              Run the security scan bundle.
  security-prepare                           Prepare defensive security tools.
  security-zap                               Run OWASP ZAP checks.
  security-k8s                               Run Kubernetes security checks.
  security-host                              Run host security checks.
  security-trivy                             Run Trivy scans.
  security-secrets                           Run secret leak checks.
  security-nuclei                            Run Nuclei web checks.
  security-web                               Run web security checks.
  security-logs                              Review security-relevant logs.
  security-runtime                           Check runtime security sensors.
  security-attack-path                       Print prioritized attack-path findings.
  prompt-injection-lab {list|run|show}       Run local prompt-injection defense drills.
  red-blue {plan|run|ledger}                 Run or plan safe red-team/blue-team loop.

AI And Indexing
  ai-index                                   Build the local homelab RAG index.
  ai-check                                   Query/check the local AI index.
  ask [--citations] QUESTION...              Find relevant docs/runbooks/commands.
  ai-evals {list|run|show}                   Run deterministic Jeannie/RAG eval cases.
  ai-scheduler {simulate|recommend NAME}     Simulate AI workload placement policy.
  ai-memory {check}                          Check local RAG index provenance freshness.
  model-observe {prompts|run|report}         Track model behavior over stable prompts.

Destructive
  nuke                                       Guarded cluster state destruction path.
EOF
}

if [[ "${JEANNIE_LIBRARY_MODE:-false}" == "true" ]]; then
    # shellcheck disable=SC2317
    return 0 2>/dev/null || exit 0
fi

# Serialize top-level cluster pipelines, including callers from the API. The
# inherited descriptor keeps the lock until this pipeline exits. Internal DAG
# tasks perform read-only checks beneath their parent's lock.
runtime_pipeline=false
case "${1:-}" in
    up|cluster|platform|apps|start-cluster) runtime_pipeline=true ;;
    monitoring) case "${2:-status}" in migrate|apply) runtime_pipeline=true ;; esac ;;
    start) [[ "${2:-plan}" != apply ]] || runtime_pipeline=true ;;
    gateway-lab) [[ "${2:-plan}" != apply ]] || runtime_pipeline=true ;;
    progressive-lab) case "${2:-plan}" in apply|run|rollback) runtime_pipeline=true ;; esac ;;
    secrets-lab) case "${2:-plan}" in apply|test|rotate|recover|recover-cert) runtime_pipeline=true ;; esac ;;
esac
if "${runtime_pipeline}"; then
    if [[ "${JEANNIE_RUNTIME_PIPELINE_LOCK:-}" != "${LAB_CLUSTER_PROFILE}" ||
          ! "${JEANNIE_RUNTIME_PIPELINE_LOCK_FD:-}" =~ ^[0-9]+$ ||
          ! -e "/proc/$$/fd/${JEANNIE_RUNTIME_PIPELINE_LOCK_FD:-invalid}" ]]; then
        exec python3 "${REPO_ROOT}/scripts/cluster-runtime-guard.py" \
            --profile "${LAB_CLUSTER_PROFILE}" run -- "${REPO_ROOT}/jeannie" "$@"
    fi
fi

# Check conflicting runtimes before any cluster pipeline changes hosts.
case "${1:-}" in
    up|cluster|platform|apps|start-cluster)
        cluster_runtime_require || exit 1
        ;;
    start)
        if [[ "${2:-plan}" == apply ]]; then cluster_runtime_require || exit 1; fi
        ;;
    gateway-lab)
        if [[ "${2:-plan}" == apply ]]; then cluster_runtime_require || exit 1; fi
        ;;
    progressive-lab)
        case "${2:-plan}" in apply|run|rollback) cluster_runtime_require || exit 1 ;; esac
        ;;
    secrets-lab)
        case "${2:-plan}" in apply|test|rotate|recover|recover-cert) cluster_runtime_require || exit 1 ;; esac
        ;;
    __up-task)
        cluster_runtime_require || exit 1
        ;;
esac

# Guard operations that also mutate hosts over SSH, beyond kubectl/Tofu.
case "${1:-}" in
    up|stop-cluster|nuke|cleanup-debian-k8s|move-prometheus-stack-workers)
        cluster_context_require || exit 1
        ;;
    start-cluster)
        cluster_context_require_startup || exit 1
        ;;
    rebuild-cluster)
        cluster_context_require || exit 1
        echo "Automatic rebuild changes the pinned cluster identity; refusing before destruction. A reviewed bootstrap/re-enrollment transition is required." >&2
        exit 1
        ;;
    start)
        if [[ "${2:-plan}" == "apply" ]]; then cluster_context_require_startup || exit 1; fi
        ;;
    shutdown)
        if [[ "${2:-plan}" == "apply" ]]; then cluster_context_require || exit 1; fi
        ;;
    __up-task)
        if [[ "${2:-}" == "pimox-workers" ]]; then cluster_context_require || exit 1; fi
        ;;
esac

case "${1:-}" in
    compose-intent)
        require_debian_server "compose-intent"
        python3 "${REPO_ROOT}/scripts/compose-intent.py" --file "${HOMELAB_STATE_DIR}/compose-intent.json" "${@:2}"
        ;;
    ai-lab)
        require_debian_server "ai-lab"
        case "${2:-plan}" in
            plan|install|devices|colibri-install|colibri-prepare|doctor-prepare) [[ $# -le 2 ]] || { echo "Invalid ai-lab arguments" >&2; exit 2; } ;;
            bench) [[ $# -eq 3 && "${3}" =~ ^(ollama|cpu|vulkan|colibri|qwen-cpu)$ ]] || { echo "Usage: ./jeannie ai-lab bench {ollama|cpu|vulkan|colibri|qwen-cpu}" >&2; exit 2; } ;;
            suite) [[ $# -le 3 && "${3:-3}" =~ ^([1-9]|10)$ ]] || { echo "Usage: ./jeannie ai-lab suite [REPEATS 1-10]" >&2; exit 2; } ;;
            doctor-retrieval-plan) [[ $# -eq 2 ]] || exit 2 ;;
            doctor-retrieval-bench) [[ $# -le 3 && "${3:-3}" =~ ^[1-5]$ ]] || { echo "Usage: ./jeannie ai-lab doctor-retrieval-bench [REPEATS 1-5]" >&2; exit 2; } ;;
            doctor-suite) [[ $# -le 3 && "${3:-2}" =~ ^[1-5]$ ]] || { echo "Usage: ./jeannie ai-lab doctor-suite [REPEATS 1-5]" >&2; exit 2; } ;;
            headroom-install) [[ $# -eq 2 ]] || exit 2 ;;
            doctor-context-bench) [[ $# -ge 4 && $# -le 5 && "${3}" =~ ^(baseline|compare)$ ]] || { echo "Usage: ./jeannie ai-lab doctor-context-bench {baseline CONVERSATION [REPEATS]|compare BASELINE}" >&2; exit 2; } ;;
            doctor-rank) [[ $# -eq 4 ]] || { echo "Usage: ./jeannie ai-lab doctor-rank REPORT REVIEW" >&2; exit 2; } ;;
            doctor-auto-rank) [[ $# -eq 3 ]] || { echo "Usage: ./jeannie ai-lab doctor-auto-rank REPORT" >&2; exit 2; } ;;
            doctor-add-external) [[ $# -eq 5 ]] || { echo "Usage: ./jeannie ai-lab doctor-add-external REPORT RANKING MODEL" >&2; exit 2; } ;;
            *) echo "Usage: ./jeannie ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench|suite|doctor-prepare|doctor-suite|doctor-rank|doctor-retrieval-plan|doctor-retrieval-bench}" >&2; exit 2 ;;
        esac
        case "${2:-plan}" in install|colibri-install|colibri-prepare|doctor-prepare) record_change_journal "ai-lab" "$@" ;; esac
        if [[ "${2:-plan}" == doctor-retrieval-plan ]]; then
            python3 "${REPO_ROOT}/scripts/doctor-retrieval-lab.py" plan
        elif [[ "${2:-plan}" == doctor-retrieval-bench ]]; then
            python3 "${REPO_ROOT}/scripts/doctor-retrieval-lab.py" run "${3:-3}"
        elif [[ "${2:-plan}" == headroom-install ]]; then
            record_change_journal "ai-lab-headroom-install"
            python3 "${REPO_ROOT}/scripts/doctor-context-lab.py" install
        elif [[ "${2:-plan}" == doctor-context-bench ]]; then
            "${LAB_HOLMES_ADAPTER_PYTHON:-/home/jv/.local/share/pipx/venvs/holmesgpt/bin/python}" "${REPO_ROOT}/scripts/doctor-context-lab.py" "${@:3}"
        elif [[ "${2:-plan}" == suite ]]; then
            python3 "${REPO_ROOT}/scripts/ai-lab-suite.py" "${@:3}"
        elif [[ "${2:-plan}" == doctor-prepare ]]; then
            python3 "${REPO_ROOT}/scripts/doctor-model-lab.py" prepare
        elif [[ "${2:-plan}" == doctor-suite ]]; then
            python3 "${REPO_ROOT}/scripts/doctor-model-lab.py" suite "${@:3}"
        elif [[ "${2:-plan}" == doctor-rank ]]; then
            python3 "${REPO_ROOT}/scripts/doctor-model-rank.py" "${@:3}"
        elif [[ "${2:-plan}" == doctor-auto-rank ]]; then
            python3 "${REPO_ROOT}/scripts/doctor-model-lab.py" auto-rank "$3"
        elif [[ "${2:-plan}" == doctor-add-external ]]; then
            python3 "${REPO_ROOT}/scripts/doctor-model-lab.py" add-external "${@:3}"
        else
            python3 "${REPO_ROOT}/scripts/ai-lab.py" "${@:2}"
        fi
        ;;
    progressive-lab)
        [[ $# -le 3 && ( $# -le 2 || "${2:-}" == run ) ]] || { echo "Usage: ./jeannie progressive-lab {plan|apply|status|run [errors|readiness]|rollback}" >&2; exit 2; }
        case "${2:-plan}" in
            plan|apply|status|run|rollback) ;;
            *) echo "Usage: ./jeannie progressive-lab {plan|apply|status|run [errors|readiness]|rollback}" >&2; exit 2 ;;
        esac
        if [[ "${2:-plan}" != plan ]]; then cluster_context_require || exit 1; fi
        case "${2:-plan}" in apply|run|rollback) record_change_journal "progressive-lab" "$@" ;; esac
        KUBECONFIG="${KUBECONFIG_PATH}" python3 "${REPO_ROOT}/scripts/progressive-lab.py" "${@:2}"
        ;;
    secrets-lab)
        [[ $# -le 2 ]] || { echo "Usage: ./jeannie secrets-lab {plan|apply|status|test|rotate|recover|recover-cert}" >&2; exit 2; }
        case "${2:-plan}" in
            plan|apply|status|test|rotate|recover|recover-cert) ;;
            *) echo "Usage: ./jeannie secrets-lab {plan|apply|status|test|rotate|recover|recover-cert}" >&2; exit 2 ;;
        esac
        if [[ "${2:-plan}" != plan ]]; then cluster_context_require || exit 1; fi
        case "${2:-plan}" in apply|rotate|recover|recover-cert) record_change_journal "secrets-lab" "$@" ;; esac
        KUBECONFIG="${KUBECONFIG_PATH}" python3 "${REPO_ROOT}/scripts/secrets-lab.py" "${2:-plan}"
        ;;
    gateway-lab)
        [[ $# -le 2 ]] || { echo "Usage: ./jeannie gateway-lab {plan|apply|status|test}" >&2; exit 2; }
        case "${2:-plan}" in
            plan|apply|status|test) ;;
            *) echo "Usage: ./jeannie gateway-lab {plan|apply|status|test}" >&2; exit 2 ;;
        esac
        if [[ "${2:-plan}" != plan ]]; then cluster_context_require || exit 1; fi
        if [[ "${2:-plan}" == apply ]]; then record_change_journal "gateway-lab" "$@"; fi
        KUBECONFIG="${KUBECONFIG_PATH}" python3 "${REPO_ROOT}/scripts/gateway-lab.py" "${2:-plan}"
        ;;
    goose-graph)
        python3 "${REPO_ROOT}/scripts/goose-graph.py" "${@:2}"
        ;;
    lab-window)
        lab_window "${@:2}"
        ;;
    cluster-transition)
        python3 "${REPO_ROOT}/scripts/cluster-transition.py" "${@:2}"
        ;;
    cluster-runtime)
        if [[ "${2:-}" != check ]]; then
            echo "Usage: ./jeannie cluster-runtime check" >&2
            exit 2
        fi
        python3 "${REPO_ROOT}/scripts/cluster-runtime-guard.py" "${@:2}"
        ;;
    cluster-context)
        python3 "${REPO_ROOT}/scripts/cluster-context.py" "${@:2}"
        ;;
    __up-task)
        up_task "${2:-}"
        ;;
    __heal-check)
        case "${2:-}" in
            api) status_kubernetes_api_ok ;;
            nodes) status_kubernetes_nodes_ready ;;
            runtime) status_cluster_control_runtime ;;
            control-vm) status_pimox_control_plane_running ;;
            worker-vms) status_pimox_workers_running ;;
            pihole) check_pihole_dns_query ;;
            rpi-storage) check_rpi_docker_root_state ;;
            uptime-kuma) status_rpi_uptime_kuma_ok ;;
            gitea-container) status_container_running "${GITEA_CONTAINER_NAME:-homelab-gitea}" ;;
            gitea-http) status_http_ok "http://127.0.0.1:${LAB_GITEA_HTTP_PORT:-3000}/" ;;
            *) echo "Unknown heal verification check." >&2; exit 2 ;;
        esac
        ;;
    "" | help | -h | --help)
        print_usage
        ;;
    up)
        record_change_journal "up" "$@"
        up
        ;;
    cluster)
        cluster_apply "${@:2}"
        ;;
    plan)
        plan_homelab "${2:-all}"
        ;;
    cluster-profile)
        if [[ "${2:-}" == select ]]; then
            python3 "${REPO_ROOT}/scripts/cluster_runtime_context.py" select "${3:?Select a declared profile}"
        else
            cluster_profile_report
        fi
        ;;
    rebuild-cluster)
        record_change_journal "rebuild-cluster" "$@"
        rebuild_cluster
        ;;
    stop-cluster)
        record_change_journal "stop-cluster" "$@"
        stop_cluster
        ;;
    shutdown)
        record_change_journal "shutdown" "$@"
        homelab_shutdown "${@:2}"
        ;;
    start)
        record_change_journal "start" "$@"
        homelab_start "${@:2}"
        ;;
    start-cluster)
        record_change_journal "start-cluster" "$@"
        start_cluster
        ;;
    cleanup-debian-k8s)
        record_change_journal "cleanup-debian-k8s" "$@"
        require_debian_server "cleanup-debian-k8s"
        jeannie_log_start "cleanup-debian-k8s"
        jeannie_step_plan 1
        run_step "Debian Kubernetes offload cleanup" cleanup_debian_k8s_after_pimox_offload
        echo "Log: ${JEANNIE_LOG_FILE}"
        ;;
    status)
        status_report "${@:2}"
        ;;
    capacity)
        capacity_report "$@"
        ;;
    capacity-advisor)
        capacity_advisor "$@"
        ;;
    capacity-limits)
        capacity_limits "$@"
        ;;
    recover-plan)
        recover_plan
        ;;
    gitops-status)
        gitops_status
        ;;
    gitops)
        gitops_manage "${@:2}"
        ;;
    storage)
        storage_manage "${@:2}"
        ;;
    mesh)
        mesh_doctor "${@:2}"
        ;;
    platform)
        record_change_journal "platform" "$@"
        require_debian_server "platform"
        jeannie_log_start "platform"
        jeannie_step_plan 1
        run_step "Platform OpenTofu apply" platform_apply "${2:-all}"
        echo "Log: ${JEANNIE_LOG_FILE}"
        ;;
    edge)
        if [[ "${2:-}" == "diagnose" ]]; then
            edge_diagnose
            exit "$?"
        elif [[ -n "${2:-}" && "${2}" != "apply" ]]; then
            echo "Usage: ./jeannie edge [apply|diagnose]" >&2
            exit 2
        fi
        record_change_journal "edge" "$@"
        require_debian_server "edge"
        jeannie_log_start "edge"
        jeannie_step_plan 1
        run_step "Edge OpenTofu apply" edge_apply
        echo "Log: ${JEANNIE_LOG_FILE}"
        ;;
    email-vm)
        email_vm_manage "${@:2}"
        ;;
    oci-foundation)
        oci_foundation_manage "${@:2}"
        ;;
    oci-auth)
        oci_auth_manage "${@:2}"
        ;;
    oci)
        case "${2:-status}" in
            status) oci_status ;;
            doctor) oci_doctor ;;
            agent-status) oci_agent_status "${@:3}" ;;
            restart-edge) record_change_journal "oci-restart-edge" "$@"; oci_restart_edge "${@:3}" ;;
            bastion) oci_bastion_ssh "${@:3}" ;;
            cleanup) oci_cleanup "${@:3}" ;;
            *) echo "Usage: ./jeannie oci {status|doctor|agent-status|restart-edge|bastion ssh|cleanup plan|cleanup apply --confirm TENANCY-CLEANUP}" >&2; exit 2 ;;
        esac
        ;;
    edge-cache-flush)
        edge_flush_caches
        ;;
    promote)
        promote "$@"
        ;;
    cert-check)
        cert_check
        ;;
    release-snapshot)
        record_change_journal "release-snapshot" "$@"
        release_snapshot
        ;;
    backup-status)
        backup_status
        ;;
    synthetic-checks)
        synthetic_checks
        ;;
    resource-budget)
        resource_budget "$@"
        ;;
    control-plane)
        control_plane "$@"
        ;;
    artifact-cache)
        artifact_cache "$@"
        ;;
    blockchain-devnet)
        blockchain_devnet "$@"
        ;;
    blockchain-test)
        blockchain_test "$@"
        ;;
    blockchain-wallet)
        blockchain_wallet "$@"
        ;;
    golden-ledger)
        golden_ledger "$@"
        ;;
    route-inventory)
        route_inventory
        ;;
    explain)
        explain "$@"
        ;;
    recover-power)
        recover_power "$@"
        ;;
    heal)
        heal "$@"
        ;;
    self-heal)
        self_heal "$@"
        ;;
    incident)
        incident_commander "$@"
        ;;
    safety-case)
        safety_case "$@"
        ;;
    agent-sandbox)
        agent_sandbox "$@"
        ;;
    scorecard)
        scorecard
        ;;
    grafana-dashboards)
        grafana_dashboards "$@"
        ;;
    monitoring)
        monitoring_debian "${2:-status}"
        ;;
    sso-grafana)
        grafana_sso "${2:-plan}"
        ;;
    sso-gitea)
        gitea_sso "${2:-plan}"
        ;;
    sso)
        sso "${2:-plan}"
        ;;
    dex-secret)
        dex_secret "${2:-ensure}"
        ;;
    gitea-runner-secret)
        gitea_runner_secret "${2:-apply}"
        ;;
    workers)
        workers_manage "$@"
        ;;
    change-journal)
        change_journal "$@"
        ;;
    map)
        homelab_map "$@"
        ;;
    validate)
        validate_homelab
        ;;
    access-audit)
        access_audit
        ;;
    kubeconfig-readonly)
        kubeconfig_readonly
        ;;
    apps)
        record_change_journal "apps" "$@"
        require_debian_server "apps"
        jeannie_log_start "apps"
        jeannie_step_plan 1
        run_step "Applications" apps "${2:-all}"
        echo "Log: ${JEANNIE_LOG_FILE}"
        ;;
    website-translation-model)
        website_translation_model
        ;;
    website-ollama-listen)
        website_ollama_listen
        ;;
    ollama-setup)
        ollama_setup
        ;;
    deploy-gitea)
        record_change_journal "deploy-gitea" "$@"
        deploy_gitea
        ;;
    deploy-api)
        deploy_api
        ;;
    deploy-heimdall)
        record_change_journal "deploy-heimdall" "$@"
        deploy_heimdall
        ;;
    deploy-searxng)
        record_change_journal "deploy-searxng" "$@"
        deploy_searxng
        ;;
    deploy-privatebin)
        record_change_journal "deploy-privatebin" "$@"
        deploy_privatebin
        ;;
    deploy-miniflux)
        record_change_journal "deploy-miniflux" "$@"
        deploy_miniflux
        ;;
    deploy-opsproof)
        record_change_journal "deploy-opsproof" "$@"
        deploy_opsproof
        ;;
    deploy-dex)
        record_change_journal "deploy-dex" "$@"
        deploy_dex
        ;;
    deploy-office)
        record_change_journal "deploy-office" "$@"
        deploy_office
        ;;
    deploy-matrix)
        record_change_journal "deploy-matrix" "$@"
        deploy_matrix
        ;;
    deploy-ai-stack)
        record_change_journal "deploy-ai-stack" "$@"
        deploy_ai_stack
        ;;
    deploy-ai-tools)
        record_change_journal "deploy-ai-tools" "$@"
        deploy_ai_tools
        ;;
    deploy-omniroute)
        record_change_journal "deploy-omniroute" "$@"
        deploy_omniroute
        ;;
    deploy-hermes)
        record_change_journal "deploy-hermes" "$@"
        deploy_hermes
        ;;
    hermes-connect)
        require_debian_server "hermes-connect"
        bash "${REPO_ROOT}/scripts/hermes-connect"
        ;;
    rpi-services)
        record_change_journal "rpi-services" "$@"
        deploy_rpi_services
        ;;
    host-bootstrap)
        record_change_journal "host-bootstrap" "$@"
        host_bootstrap_manage "${2:-}" "${3:-plan}" "${4:-}"
        ;;
    bootstrap-gitea-repo)
        bootstrap_gitea_repo
        ;;
    repo-sync)
        repo_sync "${@:2}"
        ;;
    backup-gitea)
        backup_gitea
        ;;
    backup)
        if [[ "${2:-}" == "oci" ]]; then
            backup_oci "${3:-status}"
        else
            homelab_backup
        fi
        ;;
    drill-restore)
        drill_restore
        ;;
    drill-gitea-restore)
        drill_gitea_restore
        ;;
    drill-pihole-restore)
        drill_pihole_restore
        ;;
    install-gitea-runner)
        install_gitea_runner "${2:-}"
        ;;
    move-prometheus-stack-workers)
        move_prometheus_stack_workers
        ;;
    doctor)
        doctor_focus "${@:2}"
        ;;
    doctor-versions)
        doctor_versions "${@:2}"
        ;;
    doctor-edge)
        doctor_edge "${@:2}"
        ;;
    doctor-homelab)
        doctor_homelab "${@:2}"
        ;;
    doctor-gitea)
        doctor_gitea "${@:2}"
        ;;
    doctor-dex)
        doctor_dex "${@:2}"
        ;;
    doctor-rpi)
        doctor_rpi "${@:2}"
        ;;
    doctor-cluster)
        doctor_cluster "${@:2}"
        ;;
    doctor-k8s)
        doctor_k8s "${@:2}"
        ;;
    preflight)
        homelab_preflight "full"
        ;;
    doctor-preapply)
        doctor_preapply
        ;;
    inventory-check)
        inventory_check
        ;;
    state-backup)
        backup_tofu_state
        ;;
    state)
        if [[ "${2:-}" != "status" ]]; then
            echo "Usage: ./jeannie state status [STACK] [--json]" >&2
            exit 2
        fi
        state_status "${@:3}"
        ;;
    pimox)
        pimox_oob "${@:2}"
        ;;
    fix-debian-docker-root)
        fix_debian_docker_root
        ;;
    secrets-init)
        secrets_init
        ;;
    secrets-check)
        secrets_check
        ;;
    secrets)
        if [[ "${2:-}" != "rotate" ]]; then
            echo "Usage: ./jeannie secrets rotate {status|plan|SERVICE [--yes]}" >&2
            exit 2
        fi
        secrets_rotate "${@:3}"
        ;;
    tailnet-policy-check)
        tailnet_policy_check
        ;;
    ai-index)
        ai_index
        ;;
    ai-check)
        ai_check
        ;;
    ask)
        ask_homelab "$@"
        ;;
    ai-evals)
        ai_evals "$@"
        ;;
    ai-scheduler)
        ai_scheduler "$@"
        ;;
    ai-memory)
        ai_memory "$@"
        ;;
    model-observe)
        model_observe "$@"
        ;;
    impact)
        impact "$@"
        ;;
    review-last-change)
        review_last_change "$@"
        ;;
    security-scan)
        security_scan
        ;;
    security-prepare)
        security_prepare
        ;;
    security-zap)
        security_zap
        ;;
    security-k8s)
        security_k8s
        ;;
    security-host)
        security_host
        ;;
    security-trivy)
        security_trivy
        ;;
    security-secrets)
        security_secrets
        ;;
    security-nuclei)
        security_nuclei
        ;;
    security-web)
        security_web
        ;;
    security-logs)
        security_logs
        ;;
    security-runtime)
        security_runtime
        ;;
    security-attack-path)
        security_attack_path "$@"
        ;;
    prompt-injection-lab)
        prompt_injection_lab "$@"
        ;;
    red-blue)
        red_blue_loop "$@"
        ;;
    network-sandbox)
        require_debian_server "network-sandbox"
        [[ $# -le 2 || ( $# -eq 3 && "${2:-}" == capture ) ]] || { echo "Usage: ./jeannie network-sandbox capture {vlan10|vlan20|trunk|wan}" >&2; exit 2; }
        case "${2:-plan}" in
            plan) python3 "${REPO_ROOT}/scripts/network-sandbox-plan.py" ;;
            prepare|provision|start)
                record_change_journal "network-sandbox" "$@"
                echo "Checking sandbox configuration and host preparation logic..."
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \
                    -p 'test_network_sandbox_config.py' || exit 1
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \
                    -p 'test_network_sandbox_host.py' || exit 1
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \
                    -p 'test_network_sandbox_guests.py' || exit 1
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \
                    -p 'test_network_sandbox_guard.py' || exit 1
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \
                    -p 'test_network_sandbox_lifecycle.py' || exit 1
                case "${2}" in
                    prepare) python3 "${REPO_ROOT}/scripts/network-sandbox-prepare.py" ;;
                    provision) python3 "${REPO_ROOT}/scripts/network-sandbox-guests.py" ;;
                    start) python3 "${REPO_ROOT}/scripts/network-sandbox-lifecycle.py" start ;;
                esac
                ;;
            stop)
                record_change_journal "network-sandbox" "$@"
                python3 "${REPO_ROOT}/scripts/network-sandbox-lifecycle.py" stop
                ;;
            verify)
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" \
                    -p 'test_network_sandbox_verify.py' || exit 1
                python3 "${REPO_ROOT}/scripts/network-sandbox-verify.py"
                ;;
            isolation-tests)
                record_change_journal "network-sandbox" "$@"
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_verify.py' || exit 1
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_isolation.py' || exit 1
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_wan.py' || exit 1
                python3 "${REPO_ROOT}/scripts/network-sandbox-verify.py" || exit 1
                python3 "${REPO_ROOT}/scripts/network-sandbox-isolation.py" || exit 1
                python3 "${REPO_ROOT}/scripts/network-sandbox-wan.py" probe
                ;;
            capture)
                [[ $# -eq 3 ]] || { echo "Usage: ./jeannie network-sandbox capture {vlan10|vlan20|trunk|wan}" >&2; exit 2; }
                record_change_journal "network-sandbox" "$@"
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_capture.py' || exit 1
                python3 "${REPO_ROOT}/scripts/network-sandbox-capture.py" "$3"
                ;;
            wan-probe)
                record_change_journal "network-sandbox" "$@"
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_wan.py' || exit 1
                python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_network_sandbox_verify.py' || exit 1
                python3 "${REPO_ROOT}/scripts/network-sandbox-verify.py" || exit 1
                python3 "${REPO_ROOT}/scripts/network-sandbox-wan.py" probe
                ;;
            wan-reset)
                record_change_journal "network-sandbox" "$@"
                python3 "${REPO_ROOT}/scripts/network-sandbox-wan.py" reset
                ;;
            *) echo "Usage: ./jeannie network-sandbox {plan|prepare|provision|start|stop|verify|isolation-tests|wan-probe|wan-reset|capture}" >&2; exit 2 ;;
        esac
        ;;
    nuke)
        record_change_journal "nuke" "$@"
        require_debian_server "nuke"
        jeannie_log_start "nuke"
        jeannie_step_plan 1
        run_step "Nuke homelab cluster state" nuke
        echo "Log: ${JEANNIE_LOG_FILE}"
        ;;
    *)
        printf 'Unknown command: %s\n\n' "$1" >&2
        print_usage >&2
        exit 1
        ;;
esac
