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

# Portable sha256: macOS ships `shasum`, most Linux (Fedora/…) ship only
# `sha256sum`. Both print "<hash>  <file>".
_sha256() {
    if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | awk '{print $1}'
    else sha256sum "$1" | awk '{print $1}'; fi
}
# Yes/No prompt on an interactive TTY; defaults to No when non-interactive
# (piped installer, ssh without a tty). Defined here so ext dep-provisioning
# doesn't hit an undefined-function error under `set -e`.
ask_tty() {
    # Open the controlling tty on fd 3; if there is none (piped installer,
    # ssh without -t), bail to No silently — [ -r /dev/tty ] can pass while
    # the open still fails with "No such device or address".
    { exec 3<>/dev/tty; } 2>/dev/null || return 1
    printf '%s [y/N] ' "$1" >&3 2>/dev/null || { exec 3>&- 3<&-; return 1; }
    local a; read a <&3 2>/dev/null || { exec 3>&- 3<&-; return 1; }
    exec 3>&- 3<&-
    case "$a" in y|Y|yes|YES) return 0 ;; *) return 1 ;; esac
}

# vera-ctl — lifecycle for the metal-installed Vera (launchd / systemd).
#
#   vera-ctl status    service + health + model-server reachability
#   vera-ctl start     start (and enable) the service
#   vera-ctl stop      stop the service
#   vera-ctl restart   stop + start
#   vera-ctl update    rebuild from VERA_SRC, atomic binary swap, restart
#   vera-ctl logs      tail the structured log
#
# Data (keystore, audit chain, hub-id) lives in $VERA_HOME/data and is
# never touched by lifecycle operations. The keystore/audit are
# single-writer: stop-then-start, never two hubs on one data dir.

# An INSTALLED vera-ctl remembers the instance it LIVES IN (vera#131).
#
# The copy the installer places at $VERA_HOME/bin/vera-ctl used to be
# byte-identical to this file, so it carried only the generic default below:
# run it with no environment and `restart`, `stop`, `disable`, `uninstall`
# and `converge` all targeted ~/.vera — the DEFAULT install — instead of the
# tree the script is sitting in. The row-7 drive caught it on the read-only
# `status` (a pre-flight assertion, in place because an env-less invocation
# had already reached the owner's real daemon that day); every mutating verb
# shares the resolution.
#
# `bin/vera-ctl.env` is dropped beside this script by install-metal.sh and is
# located from $0 — NEVER from the environment, which is the ambient input
# this exists to stop trusting. It supplies DEFAULTS only: every assignment
# in it is `${VAR:-…}`, so an exported VERA_HOME still wins, which is what
# the loop harness and CI rely on. This is vera#115's constraint (probes
# target the instance's OWN ports) applied to the process lane.
#
# The repo copy has no such sibling, so `deploy/vera-ctl` behaves exactly as
# before.
#
# The ports the CALLER named EXPLICITLY, captured BEFORE the sibling env file
# is sourced: that file assigns `VERA_PORT="${VERA_PORT:-…}"`, after which
# "exported by the caller" and "stamped at install time" are indistinguishable.
# The difference is load-bearing — `VERA_HOME=<other> vera-ctl status --json`
# moved the home and left the port at the DEFAULT install's, so `hub.healthy`
# probed :8443 while `home` truthfully named the other instance: one record,
# two provenances (vera#137).
_env_port="${VERA_PORT:-}"
_env_admin_port="${VERA_ADMIN_PORT:-}"
_ctl_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd -P)" || _ctl_dir=""
if [ -n "$_ctl_dir" ] && [ -r "$_ctl_dir/vera-ctl.env" ]; then
    # shellcheck source=/dev/null
    . "$_ctl_dir/vera-ctl.env"
fi

VERA_HOME="${VERA_HOME:-$HOME/.vera}"
VERA_SRC="${VERA_SRC:-}"
# Hub ports — env-overridable so a hermetic test instance (loop harness, CI)
# never collides with — or kills — a real daemon on the default ports.
#
# THE PORT FOLLOWS THE HOME (vera#115/#137/#138). Resolution, most specific
# first:
#   1. an explicitly exported VERA_PORT / VERA_ADMIN_PORT — CI, the loop
#      harness, an operator pointing this ctl somewhere on purpose;
#   2. THIS instance's own config: `[server] bind` / `admin_bind` in
#      $VERA_HOME/config/vera.toml. That is the daemon's actual truth and it
#      moves with $VERA_HOME by construction, which a constant cannot;
#   3. the install-time stamp in bin/vera-ctl.env (vera#131);
#   4. the shipped defaults.
# `return 0` is load-bearing: `set -o pipefail` + `set -e` means a `sed` that
# cannot open a not-yet-installed config kills the whole script from a plain
# assignment (the `local x="$(…)"` idiom used elsewhere in this file masks that
# by accident — this one is at top level and has no builtin in front of it).
_cfg_port() { # toml key (bind|admin_bind) -> port, or nothing
    [ -f "$VERA_HOME/config/vera.toml" ] || return 0
    sed -nE "s/^[[:space:]]*$1[[:space:]]*=[[:space:]]*\"[^\"]*:([0-9]+)\".*/\1/p" \
        "$VERA_HOME/config/vera.toml" 2>/dev/null | head -1
    return 0
}
if [ -z "$_env_port" ]; then
    _p="$(_cfg_port bind)"
    if [ -n "$_p" ]; then VERA_PORT="$_p"; fi
fi
if [ -z "$_env_admin_port" ]; then
    _p="$(_cfg_port admin_bind)"
    if [ -n "$_p" ]; then VERA_ADMIN_PORT="$_p"; fi
fi
VERA_PORT="${VERA_PORT:-8443}"
VERA_ADMIN_PORT="${VERA_ADMIN_PORT:-9090}"
# SERVICE-SCOPED — and it FOLLOWS THE HOME (vera#150).
#
# This used to be a constant, on the reasoning that install-metal.sh registers
# ONE launchd label / ONE systemd unit per USER whatever home it installed, so
# a second instance "SHARES" it. That reading is coherent for a READ (status
# can honestly say "the unit is loaded, and no hub of MY home is behind it").
# It does not survive contact with the MUTATING verbs: install rewrote the
# shared unit's ExecStart and restarted it — killing the first install's hub —
# and `disable` `rm -f`'d the shared file, deleting the OTHER install's
# service with a verb the user ran against their own home. That is not
# sharing; it is one install taking the unit away from another, silently, and
# it made every service verb untestable on any box that already runs Vera.
#
# So the identity is derived, exactly the way the PORT already is (vera#137):
#   * the DEFAULT home ($HOME/.vera) keeps `vera.service` / `ai.sozenta.vera`
#     verbatim, so every existing install is untouched — migration is a no-op;
#   * any other home gets `vera-<hash>.service` / `ai.sozenta.vera.<hash>`,
#     where <hash> is the first 8 hex of sha256 over the home's absolute path.
#     A hash, not a basename: two homes can share a basename, and a path is
#     not a unit-name character set.
#
# The DERIVATION IS DUPLICATED in install-metal.sh (the two scripts ship
# separately — one at the bundle root, one in bin/ — and a third sourced file
# would be a new missing-file failure mode in the field). The duplication is
# not trusted: deploy/tests/install-config.test.sh carves BOTH copies out and
# asserts they answer identically over a table of homes. Change one and the
# gate goes red.
#
# ── BEGIN vera-unit-name (contract: deploy/tests/install-config.test.sh) ──
vera_unit_slug() { # abs home -> "" for the DEFAULT home, else 8 hex of sha256
    local home="${1:-}" def="${HOME:-}/.vera"
    while [ "$home" != "${home%/}" ]; do home="${home%/}"; done
    while [ "$def"  != "${def%/}"  ]; do def="${def%/}";   done
    if [ "$home" = "$def" ]; then return 0; fi
    if command -v shasum >/dev/null 2>&1; then
        printf '%s' "$home" | shasum -a 256 | cut -c1-8
    else
        printf '%s' "$home" | sha256sum | cut -c1-8
    fi
}
# ── END vera-unit-name ──────────────────────────────────────────────────
_unit_slug="$(vera_unit_slug "$VERA_HOME")"
LABEL="ai.sozenta.vera${_unit_slug:+.$_unit_slug}"
UNIT_BASE="vera${_unit_slug:+-$_unit_slug}"
SD_UNIT="$UNIT_BASE.service"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
SD_DIR="$HOME/.config/systemd/user"
UNIT_PATH="$SD_DIR/$SD_UNIT"
# The unit definition `disable` sets aside so `enable` can put it back without
# a payload (vera#151): disable's own receipt promises it KEEPS everything, and
# the unit is part of everything.
UNIT_KEPT="$VERA_HOME/service-unit.disabled"

# THE OWNERSHIP GUARD, and the reason it exists beside the derived name.
#
# The default home still answers to `vera.service` / `ai.sozenta.vera` for
# compatibility, so on a box where a pre-#150 second install already hijacked
# that unit, the name alone does not prove whose it is. A teardown verb must
# never remove a registration whose ExecStart points at somebody else's home —
# that is vera#150's whole cost, and the name-derivation alone does not close
# it for the one name that is shared by construction.
# FIXED strings, and both of them ANCHORED at the start of the path — a home
# is a path, so `grep` on a bare substring both interprets `.` as a wildcard
# and matches `/x/a/bin/vera-hub` for the home `/a`. `ExecStart=` and
# `<string>` are the anchors the two formats give us.
unit_is_ours() { # unit-file / plist path -> 0 when its ExecStart names THIS home
    local f="${1:-}"
    [ -f "$f" ] || return 1
    grep -qF -- "ExecStart=$VERA_HOME/bin/vera-hub " "$f" 2>/dev/null && return 0
    grep -qF -- "<string>$VERA_HOME/bin/vera-hub</string>" "$f" 2>/dev/null && return 0
    return 1
}

# MAY WE DRIVE THE MANAGER FOR THIS UNIT AT ALL? (vera#150, gate M2.)
#
# `unit_is_ours` was only consulted at the REMOVAL, which is one step too late:
# `svc_stop` had already issued `systemctl --user stop vera.service` /
# `launchctl bootout` before the refusal printed, so on the exact population
# the migration is designed to protect — a box where a pre-fix second install
# already hijacked the shared default name — `stop`, `disable`, `restart` and
# `uninstall` knocked the OTHER install's daemon over and then said they were
# refusing to touch it. The stop is the destructive act; the guard has to come
# before it.
#
# ABSENT registration => permitted. There is nothing on disk to contradict us,
# the name is ours by derivation, and refusing here would break the ordinary
# case where `disable` has already removed the file.
manager_owns_unit() {
    local f
    if [ "$SVC" = launchd ]; then f="$PLIST"; else f="$UNIT_PATH"; fi
    [ -f "$f" ] || return 0
    unit_is_ours "$f"
}
# Set by `unregister_service` when it REFUSED — read by the receipts, which
# must describe what happened rather than what the verb usually does.
SERVICE_LEFT_IN_PLACE=""

# Unregister THIS home's service, and ONLY this home's. `disable` and
# `uninstall` are the two callers, and the ownership guard lives here rather
# than in each of them — the vera#150 accident is exactly a teardown verb that
# grew its own copy of the removal and forgot whose unit it was removing.
#
# keep_unit=1 (disable) copies the unit definition into the home BEFORE
# removing it, so `enable` can put it back with no payload. `disable`'s own
# receipt promises it KEEPS everything, and the registration is part of
# everything — without this, the documented restore path needs the original
# tarball a channel user has already deleted (vera#151).
unregister_service() { # keep_unit
    local keep="${1:-}" f
    SERVICE_LEFT_IN_PLACE=""
    [ -z "${VERA_NO_SERVICE:-}" ] || return 0
    if [ "$SVC" = launchd ]; then f="$PLIST"; else f="$UNIT_PATH"; fi
    if [ -f "$f" ] && ! unit_is_ours "$f"; then
        SERVICE_LEFT_IN_PLACE="$f"
        echo "  service: $f does not name this home's hub ($VERA_HOME/bin/vera-hub) — LEFT IN PLACE; another install owns that registration" >&2
        return 0
    fi
    if [ -n "$keep" ] && [ -f "$f" ]; then
        mkdir -p "$VERA_HOME"
        cp -f "$f" "$UNIT_KEPT" 2>/dev/null || true
    fi
    if [ "$SVC" = launchd ]; then
        launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
        rm -f "$PLIST"
    else
        systemctl --user disable --now "$SD_UNIT" 2>/dev/null || true
        rm -f "$UNIT_PATH"
        systemctl --user daemon-reload 2>/dev/null || true
    fi
    return 0
}

case "$(uname -s)" in Darwin) SVC=launchd; OS=macos ;; *) SVC=systemd; OS=linux ;; esac

# Release channel — what Veya (or a manual `update`) pulls. The daemon
# self-updates from a signed artifact; no package manager, no source.
CHANNEL_BASE="${VERA_CHANNEL_BASE:-https://sozenta-releases.s3.us-east-2.amazonaws.com/vera}"
MANIFEST_URL="${VERA_MANIFEST_URL:-$CHANNEL_BASE/vera-metal-$OS.json}"
# minisign public key (the Veya updater key) — authenticity of artifacts,
# checked ONLY when a manifest carries a signature. None does today (vera#345).
CHANNEL_PUBKEY="RWQKsqvImyn/fZ6DAtGn2Nec29HbRgrqhAwztLTD0bAYM4II6oFFLQZr"

# WHAT A DOWNLOAD IS CHECKED AGAINST — and what it is NOT (vera#345).
#
# RELEASE.md and these comments said every download was verified "sha256 +
# minisign". It was sha256 only: every channel manifest carries
# `signature: null`, so the minisign branch never ran, and when it did not run
# it said "skipped (minisign not installed)" — the wrong cause, printed even on
# a machine WITH minisign. sha256 proves the bytes match the manifest served
# over HTTPS; it proves nothing about who wrote the manifest.
#
# So the one verifier below says exactly which case it is in:
#   * sha256 is REQUIRED — a manifest without one is refused;
#   * a signature, when present, is verified with minisign against the pinned
#     channel key and a bad one is refused;
#   * a signature that cannot be checked (no minisign) and a manifest with no
#     signature at all are LOUD warnings — and refusals under
#     VERA_REQUIRE_SIGNATURE=1, the switch for once a channel key exists
#     (provisioning one is an owner decision; nothing here creates a key).
#
# DUPLICATED, DELIBERATELY, in deploy/get-vera.sh: the one-liner ships alone
# (curl | sh) and cannot source this file. POSIX sh on purpose, so the same
# bytes run in both; deploy/tests/channel-verify.test.sh carves both copies
# and fails if they differ.
# ── BEGIN vera-verify-artifact (contract: deploy/tests/channel-verify.test.sh) ──
verify_artifact() { # file want_sha256 signature_b64 what -> 0 = use it, 1 = refuse
    va_file="$1"; va_want="$2"; va_sig="$3"; va_what="$4"
    if [ -z "$va_want" ]; then
        echo "  $va_what: the manifest carries NO sha256 — refusing a download nothing can verify"
        return 1
    fi
    va_got="$(shasum -a 256 "$va_file" 2>/dev/null | awk '{print $1}' || true)"
    [ -n "$va_got" ] || va_got="$(sha256sum "$va_file" 2>/dev/null | awk '{print $1}' || true)"
    [ -n "$va_got" ] || va_got="$(openssl dgst -sha256 -r "$va_file" 2>/dev/null | awk '{print $1}' || true)"
    # Nothing was hashed, so nothing was compared: that is not a MISMATCH
    # (vera#364 — a PATH with no working hash tool read as a tampered download).
    if [ -z "$va_got" ]; then
        echo "  $va_what: could not compute sha256 (no working shasum/sha256sum/openssl) — refusing"
        return 1
    fi
    if [ "$va_got" != "$va_want" ]; then
        echo "  $va_what: sha256 MISMATCH — refusing"
        return 1
    fi
    echo "  $va_what: sha256 ok"
    if [ -z "$va_sig" ]; then
        if [ "${VERA_REQUIRE_SIGNATURE:-}" = 1 ]; then
            echo "  $va_what: the manifest is UNSIGNED and VERA_REQUIRE_SIGNATURE=1 — refusing"
            return 1
        fi
        echo "  WARNING: $va_what: the channel manifest is UNSIGNED (signature: null) — provenance is NOT verified."
        echo "           sha256 only proves these bytes match the manifest served over HTTPS."
        return 0
    fi
    if ! command -v minisign >/dev/null 2>&1; then
        if [ "${VERA_REQUIRE_SIGNATURE:-}" = 1 ]; then
            echo "  $va_what: signature present but minisign is not installed and VERA_REQUIRE_SIGNATURE=1 — refusing"
            return 1
        fi
        echo "  WARNING: $va_what: the manifest is signed but the signature was NOT verified — minisign is not installed."
        echo "           Provenance is unverified; sha256 was checked. Install minisign to verify it."
        return 0
    fi
    printf '%s' "$va_sig" > "$va_file.sig.b64"
    if ! { base64 --decode < "$va_file.sig.b64" > "$va_file.minisig" 2>/dev/null \
           || base64 -d < "$va_file.sig.b64" > "$va_file.minisig" 2>/dev/null; }; then
        echo "  $va_what: the manifest signature is not valid base64 — refusing"
        return 1
    fi
    if minisign -Vm "$va_file" -x "$va_file.minisig" -P "$CHANNEL_PUBKEY" >/dev/null 2>&1; then
        echo "  $va_what: signature verified (minisign, pinned channel key)"
        return 0
    fi
    echo "  $va_what: signature INVALID — refusing"
    return 1
}
# ── END vera-verify-artifact ────────────────────────────────────────────

# Kill any lingering hub still holding our config/port, so start/restart
# never races a zombie — launchd-over-SSH that didn't replace the GUI
# agent, a crashed-but-unreaped copy, or a hand-started instance. Fully
# automated: the operator never hand-kills a stale process.
#
# `local` IS THE FIX, not hygiene. bash has DYNAMIC scope: an assignment to an
# undeclared name lands in the CALLER's frame. This function's loop variable was
# `pid`, and its caller is `stop_until_gone`, whose own `pid` local holds the
# wedged hub it just identified. Every restart therefore threw that answer away
# and waited on whatever `lsof` listed LAST — in the field the Veya app's
# 2s /healthz poll, so a socket holder was essentially always present. The
# wedge survived `restart --force` and a second hub booted on a single-writer
# data dir: the exact outcome `restart_hub` exists to prevent (vera#136).
# CI never saw it because a hermetic hub is usually the ONLY socket holder, so
# the clobbered value happened to equal the correct one.
#
# The port loop signals BY IDENTITY (`is_our_hub`), not by `comm=` containing
# "vera-hub": a SECOND instance's hub bound to this port is a vera-hub and is
# NOT ours, and TERMing it is the bystander accident one indirection out
# (vera#115/#128/#131). It also REPORTS what it reaped — `stop` used to print
# "hub not running" from the pidfile reaper and then silently kill the running
# hub here, a receipt that was wrong about what happened (vera#138).
#
# AND IT REPORTS WHAT HAPPENED, NOT WHAT IT ASKED FOR (vera#149). The receipt
# used to be printed on the strength of having SIGNALLED: against a hub that
# cannot service SIGTERM — SIGSTOPped, in D-state, in a slow shutdown — nothing
# died and "reaped this instance's hub (pid N)" was printed anyway, for a
# process still on the box holding :$VERA_PORT and the single-writer redb
# locks. So: signal, then POLL, then split the list by what is provably gone.
# Survivors are named in `LINGERING_ALIVE` for `stop_until_gone`, which owns
# the TERM -> grace -> SIGKILL ladder; escalating here would put two ladders in
# one stop.
LINGERING_ALIVE=""
kill_lingering() {
    local pid found="" gone="" alive="" i=0 n
    LINGERING_ALIVE=""
    # Ours by identity, found by home-scoped scan. Same predicate, same shape
    # as `our_hub_by_scan` — that one wants the first, this one wants them all.
    if command -v pgrep >/dev/null 2>&1; then
        for pid in $(pgrep -f "vera-hub --config $VERA_HOME" 2>/dev/null || true); do
            is_our_hub "$pid" || continue
            kill "$pid" 2>/dev/null || true
            found="${found:+$found }$pid"
        done
    else
        pkill -f "vera-hub --config $VERA_HOME" 2>/dev/null || true
    fi
    # Anything still bound to OUR port that is OUR hub — free the port.
    if command -v lsof >/dev/null 2>&1; then
        for pid in $(lsof -ti tcp:$VERA_PORT 2>/dev/null); do
            case " $found " in *" $pid "*) continue ;; esac
            is_our_hub "$pid" || continue
            kill "$pid" 2>/dev/null || true
            found="${found:+$found }$pid"
        done
    fi
    [ -n "$found" ] || return 0
    # Poll at 4 Hz — a hub that handles TERM is gone in well under a second,
    # and this must not add a fixed second to every stop.
    n=$(( ${VERA_LINGER_GRACE:-2} * 4 ))
    while [ "$i" -lt "$n" ]; do
        alive=""
        for pid in $found; do
            if kill -0 "$pid" 2>/dev/null; then alive="${alive:+$alive }$pid"; fi
        done
        [ -n "$alive" ] || break
        sleep 0.25
        i=$(( i + 1 ))
    done
    for pid in $found; do
        if kill -0 "$pid" 2>/dev/null; then :; else gone="${gone:+$gone }$pid"; fi
    done
    LINGERING_ALIVE="$alive"
    [ -z "$gone" ]  || echo "  stop: reaped this instance's hub (pid $gone)" >&2
    [ -z "$alive" ] || echo "  stop: this instance's hub (pid $alive) did NOT exit on TERM" >&2
    return 0
}

# ── Identity: is this pid THIS instance's hub? ─────────────────────────
# The one guard between a lifecycle verb and a bystander.
#
# `stop_until_gone` used to take whatever number the pidfile held and
# escalate TERM -> SIGKILL against it. In the row-7 control-plane drive that
# number had been recycled onto an unrelated process (the Veya app), which
# vera-ctl duly SIGKILLed -- and then reported `restarted (healthy)`, because
# a different hub answered the probe. Both halves of that receipt were false.
# A pid is not evidence of anything on its own (vera#128).
#
# BOTH facts must hold, and neither alone is enough:
#   * the process is a `vera-hub` -- a recycled pid usually is not one at all;
#   * it belongs to THIS $VERA_HOME -- a SECOND instance's hub IS a vera-hub,
#     and signalling it is the multi-instance form of the same accident
#     (vera#115, vera#131).
# The hub is always exec'd as `$VERA_HOME/bin/vera-hub --config
# $VERA_HOME/config/vera.toml` -- pidfile mode, the launchd plist and the
# systemd unit all agree -- so one pattern carries both facts.
#
# Pattern 1 is ANCHORED at the start of the command, because `ps -o command=`
# begins with argv0 and only argv0 says what is RUNNING. Unanchored, the
# binary path merely had to appear SOMEWHERE in the argv -- so
# `tail -f $VERA_HOME/bin/vera-hub` was accepted as the hub, published as
# `hub.pid`, and signalled by `stop`, which is the same bystander accident
# one indirection further out (caught by the gate on PR #132). Pattern 2 stays
# unanchored on purpose: it is the interpreter / relocated-binary shape
# (`/usr/local/bin/vera-hub --config $VERA_HOME/...`), where argv0 is not our
# path but the process is still ours, and it demands BOTH `--config` and this
# home, which no reader of the file carries.
#
# SHARED on purpose: every signal site in this script goes through it, and
# the Windows per-user pid source (#1418/#1419) inherits the check rather
# than growing a second copy of it.
pid_cmd() { # pid -> full argv, or nothing
    ps -ww -p "${1:-0}" -o command= 2>/dev/null || ps -p "${1:-0}" -o command= 2>/dev/null || true
}
is_our_hub() { # pid
    local pid="${1:-}" cmd
    case "$pid" in ''|*[!0-9]*) return 1 ;; esac
    kill -0 "$pid" 2>/dev/null || return 1
    cmd="$(pid_cmd "$pid")"
    case "$cmd" in
        "$VERA_HOME/bin/vera-hub"*)       return 0 ;;   # argv0 IS our binary
        *vera-hub*--config*"$VERA_HOME"*) return 0 ;;   # relocated/interpreted
        *)                                return 1 ;;
    esac
}

PIDFILE="$VERA_HOME/data/hub.pid"
# The pid the pidfile names -- but ONLY when it is provably this instance's
# hub. A pidfile is a HINT, not evidence: `svc_start` writes it before the
# child has proven it survived, a start that dies immediately (the redb
# single-writer lock) leaves the number behind, and the OS recycles it onto
# something unrelated. Filtering at the READER makes status, svc_state and
# restart honest in one place instead of three.
pidfile_pid() {
    local p; p="$(cat "$PIDFILE" 2>/dev/null || true)"
    is_our_hub "$p" && printf '%s' "$p"
    return 0
}
pidfile_alive() { [ -n "$(pidfile_pid)" ]; }
# A pidfile naming a LIVE process that is not our hub is the dangerous shape:
# it makes `svc_start` skip the start AND `stop_until_gone` aim at a stranger.
# Report it and clear it -- never signal it. Returns 0 when it cleared one.
pidfile_reap_foreign() {
    [ -f "$PIDFILE" ] || return 1
    local p; p="$(cat "$PIDFILE" 2>/dev/null || true)"
    case "$p" in ''|*[!0-9]*) return 1 ;; esac
    kill -0 "$p" 2>/dev/null || return 1   # a dead pid is merely stale
    is_our_hub "$p" && return 1
    # NOT "hub not running": clearing a poisoned pidfile proves only that the
    # FILE named a stranger. A hub of ours can still be running — it was, in the
    # drive, and `kill_lingering` reaped it a moment later while this line
    # claimed otherwise (vera#138). Each step now reports only what it did.
    echo "  pidfile named a foreign process ($p: $(pid_cmd "$p")), cleared — it was NOT signalled" >&2
    rm -f "$PIDFILE"
    return 0
}
# A live hub of ours that the pidfile does NOT name -- the state the drive
# produced: the file was poisoned while the real (wedged) hub kept holding the
# single-writer data dir, so every restart "succeeded" against a pid that was
# not it and the wedge survived forever. Identity is the source of truth; the
# file is only an index into it. Pidfile mode only -- launchd/systemd name the
# pid themselves and cannot name an unrelated recycled process.
our_hub_by_scan() {
    command -v pgrep >/dev/null 2>&1 || return 0
    local p
    for p in $(pgrep -f "vera-hub --config $VERA_HOME" 2>/dev/null || true); do
        if is_our_hub "$p"; then printf '%s' "$p"; return 0; fi
    done
    return 0
}
svc_start() {
    if [ -n "${VERA_NO_SERVICE:-}" ]; then
        # A poisoned pidfile used to make this a silent no-op: the recycled
        # pid was "alive", so the hub was never started (vera#128).
        pidfile_reap_foreign || true
        if ! pidfile_alive; then
            mkdir -p "$VERA_HOME/logs" "$VERA_HOME/data"
            nohup "$VERA_HOME/bin/vera-hub" --config "$VERA_HOME/config/vera.toml" \
                >> "$VERA_HOME/logs/hub.out.log" 2>> "$VERA_HOME/logs/hub.err.log" &
            echo $! > "$PIDFILE"
        fi
        push_edge_qos &
        return 0
    fi
    # Same guard as `svc_stop`, with the sign flipped: asking the manager to
    # START a unit whose ExecStart names another home boots THEIR daemon under
    # our verb (gate M2). The refusal is loud, because a `start` that quietly
    # does nothing is the receipt defect vera#149 is about.
    if ! manager_owns_unit; then
        echo "  start: the $SVC registration for '$([ "$SVC" = launchd ] && printf '%s' "$LABEL" || printf '%s' "$SD_UNIT")' names a DIFFERENT install — NOT asking the manager to start it. Re-register this home with: vera-ctl converge --payload <dir>" >&2
        return 0
    fi
    if [ "$SVC" = launchd ]; then
        launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/dev/null \
            || launchctl load "$PLIST" 2>/dev/null || true
        # `kickstart -k` SIGKILLs a RUNNING job to force a fresh binary —
        # the very signal install-metal.sh's own comments forbid ("NO
        # kickstart -k"), because a SIGKILLed hub never runs Drop and its
        # backend children survive to squat :11434 / :8090 until the next
        # boot's reaper finds them. It is now reachable ONLY through
        # `restart --force`, where the caller has explicitly accepted a
        # SIGKILL (control-plane doc §1, "Hub restart").
        #
        # The plain `kickstart` that replaces it starts a loaded-but-dead
        # job and is a no-op on a live one — the "ensure it is running"
        # intent, without the kill.
        if [ -n "${VERA_FORCE_KICKSTART:-}" ]; then
            launchctl kickstart -k "gui/$(id -u)/$LABEL" 2>/dev/null || true
        else
            launchctl kickstart "gui/$(id -u)/$LABEL" 2>/dev/null || true
        fi
    else
        systemctl --user start "$SD_UNIT" 2>/dev/null || true
    fi
    push_edge_qos &
}

# Edge QoS posture: ONE local upstream. The default upstream-failure
# cooldown (1s→60s exponential) is cloud backpressure — on the edge a
# 60s lockout of localhost after a slow model cold-load looks like
# "chat is broken". Push fail-fast knobs (0.5s→3s) after every start.
# QoS policy is in-memory, so this re-applies on each restart.
push_edge_qos() {
    local KEY _   # bash is DYNAMICALLY scoped: an undeclared name here is an
                  # assignment in the CALLER's frame (vera#136).
    KEY=$(cat "$VERA_HOME/data/key-veya.txt" 2>/dev/null) || return 0
    [ -n "$KEY" ] || return 0
    for _ in $(seq 1 20); do
        curl -fsSk --max-time 2 https://127.0.0.1:$VERA_PORT/healthz >/dev/null 2>&1 && break
        sleep 1
    done
    curl -fs --max-time 3 -X POST         -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json'         -d '{"default_principal_rps":{"burst":60,"refill_per_sec":5.0},
             "principal_rps":{},"principal_connector_rps":{},
             "principal_groups":{},"group_rps":{},
             "upstream_cooldown":{"base_seconds":0.5,"max_seconds":3.0,"multiplier":2.0}}'         http://127.0.0.1:$VERA_ADMIN_PORT/admin/qos >/dev/null 2>&1         && echo "  qos: edge cooldown posture applied (0.5s→3s)" >&2 || true
}
svc_stop() {
    if [ -n "${VERA_NO_SERVICE:-}" ]; then
        # The pidfile is signalled ONLY when it names this instance's hub.
        # The foreign case is reported and cleared, never killed (vera#128).
        if [ -f "$PIDFILE" ] && ! pidfile_reap_foreign; then
            local p; p="$(pidfile_pid)"
            [ -n "$p" ] && kill "$p" 2>/dev/null || true
            rm -f "$PIDFILE"
        fi
        kill_lingering
        sleep 1
        return 0
    fi
    # THE MANAGER STOP IS THE DESTRUCTIVE ACT, so the ownership guard goes in
    # front of it, not in front of the later removal (gate M2). `kill_lingering`
    # below is identity-scoped and safe either way — it only ever signals a hub
    # of THIS home, so a foreign unit's daemon is never reached through it.
    if manager_owns_unit; then
        if [ "$SVC" = launchd ]; then
            launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
        else
            systemctl --user stop "$SD_UNIT" 2>/dev/null || true
        fi
    else
        echo "  stop: the $SVC registration for '$([ "$SVC" = launchd ] && printf '%s' "$LABEL" || printf '%s' "$SD_UNIT")' names a DIFFERENT install — NOT asking the manager to stop it. Only hubs of $VERA_HOME are signalled." >&2
    fi
    kill_lingering   # belt-and-suspenders: never leave a zombie on :8443
    sleep 1
}
# The hub's pid, straight from the SERVICE MANAGER that owns it — never a
# pgrep guess. Prints the pid on stdout, or NOTHING when no live process
# backs the unit. The pid is `kill -0`-verified before it is reported: a
# manager can name a pid that has already gone, and a status field that
# lies about liveness is the exact defect `svc_state` had.
#
# Sources (control-plane doc §1, "Hub restart"):
#   launchd  — `launchctl print gui/<uid>/<label>` prints `pid = N` for a
#              RUNNING job and OMITS the key for a loaded-but-dead one.
#   systemd  — `MainPID` is 0 for a loaded-but-not-running unit.
#   pidfile  — VERA_NO_SERVICE mode: $VERA_HOME/data/hub.pid.
#
# This is the RAW manager answer on the launchd/systemd branches (the pidfile
# branch is already identity-filtered by `pidfile_pid`, and must stay that way
# — vera#128). It is NOT the publish path: `hub_pid` wraps it in `is_our_hub`.
# The stop path deliberately takes the raw number, because it has to be able to
# say WHY it will not signal a pid the manager named ("no longer this
# instance's hub — refusing to signal it"); a filter here would make that pid
# vanish and turn an honest refusal into a silent "restarted (healthy)".
svc_named_pid() {
    local p=""
    if [ -n "${VERA_NO_SERVICE:-}" ]; then
        p="$(pidfile_pid)"
    elif [ "$SVC" = launchd ]; then
        p="$(launchctl print "gui/$(id -u)/$LABEL" 2>/dev/null \
             | sed -nE 's/^[[:space:]]*pid[[:space:]]*=[[:space:]]*([0-9]+).*/\1/p' | head -1)"
    else
        p="$(systemctl --user show -p MainPID "$SD_UNIT" 2>/dev/null \
             | sed -nE 's/^MainPID=([0-9]+)$/\1/p' | head -1)"
    fi
    case "$p" in ''|0|*[!0-9]*) return 0 ;; esac
    kill -0 "$p" 2>/dev/null && printf '%s' "$p"
    return 0
}

# The pid this instance may PUBLISH as its hub. vera#128 put every SIGNAL site
# behind `is_our_hub` and said `status --json` therefore "never PUBLISHES a
# stranger's pid" — true of the pidfile branch only. The launchd and systemd
# branches read a per-USER unit (see $LABEL) and were merely `kill -0`-verified,
# so on a host running two instances `status --json` reported the OTHER
# install's daemon as this home's `hub.pid` while `home` named this one — the
# mixed-provenance record Veya's watchdog then reads as consent (vera#137).
#
# ONE filter, at the one exit every reader shares: status_json, svc_state and
# restart_hub's post-probe pid all go through here.
hub_pid() {
    local p; p="$(svc_named_pid)"
    [ -n "$p" ] || return 0
    is_our_hub "$p" && printf '%s' "$p"
    return 0
}

# Is the service unit REGISTERED with the manager (loaded), regardless of
# whether a process is currently alive behind it?
svc_registered() {
    if [ -n "${VERA_NO_SERVICE:-}" ]; then
        [ -f "$PIDFILE" ]
    elif [ "$SVC" = launchd ]; then
        launchctl print "gui/$(id -u)/$LABEL" >/dev/null 2>&1
    else
        [ -f "$UNIT_PATH" ]
    fi
}

# THREE states, not two. `launchctl list | grep $LABEL` matched a unit that
# was merely LOADED — its process long dead — and called that "running";
# that conflation is precisely the watchdog's `dead` tier, so it could never
# fire. `running` now requires a LIVE pid; `loaded` is registered-but-dead
# (KeepAlive/Restart=always should be respawning it — if it stays `loaded`
# it is crash-looping); `stopped` is not registered at all.
#
# NOTE (deliberate, documented): the systemd branch used to echo
# `is-active`'s own vocabulary (`active` / `inactive` / `failed`), so the
# field's value domain DIFFERED by platform. It is now uniform.
svc_state() {
    if [ -n "${VERA_NO_SERVICE:-}" ]; then
        pidfile_alive && echo running || { [ -f "$PIDFILE" ] && echo loaded || echo stopped; }
        return 0
    fi
    if [ "$SVC" = launchd ]; then
        if svc_registered; then
            [ -n "$(hub_pid)" ] && echo running || echo loaded
        else
            echo stopped
        fi
    else
        local st; st="$(systemctl --user is-active "$SD_UNIT" 2>/dev/null || true)"
        case "$st" in
            active) [ -n "$(hub_pid)" ] && echo running || echo loaded ;;
            ''|inactive) svc_registered && echo loaded || echo stopped ;;
            *) echo "$st" ;;     # activating / failed / deactivating — verbatim
        esac
    fi
}

# Absolute paths of the durable log sinks (control-plane doc §1, the "Logs"
# row: `status --json` named NONE of them).
#
# `log_svc_err` prints NOTHING on a shape that has no such file — systemd
# sends the manager's stderr to the journal (`journalctl --user -u
# vera.service`), not to a path. Callers must then OMIT the key: an empty
# string TYPES AS A PATH, and a reader that opens it gets "" — a fake datum
# where the truth is "this shape has no file to open" (#1206, and the same
# rule the telemetry DTOs follow with skip_serializing_if).
log_hub()     { printf '%s' "$VERA_HOME/logs/vera.log"; }
log_converge(){ printf '%s' "$VERA_HOME/logs/converge.log"; }
log_svc_err() {
    if [ -n "${VERA_NO_SERVICE:-}" ]; then printf '%s' "$VERA_HOME/logs/hub.err.log"
    elif [ "$SVC" = launchd ]; then printf '%s' "$VERA_HOME/logs/launchd.err.log"
    else printf ''; fi
}

# The `logs` object, with `launchd_err` present ONLY where a file exists.
logs_json() {
    local err; err="$(log_svc_err)"
    if [ -n "$err" ]; then
        printf '{"hub":"%s","converge":"%s","launchd_err":"%s"}' \
            "$(log_hub)" "$(log_converge)" "$err"
    else
        printf '{"hub":"%s","converge":"%s"}' "$(log_hub)" "$(log_converge)"
    fi
}

# WHY a backend is not serving — ONE ordered table, read by both the human
# `status` line and `status --json`'s `runtimes_why`, so the two cannot
# disagree (vera#356: the reason existed only as text; vera#362: a whisper with
# no model yet printed a bare DOWN). The order is the installer receipt's: a
# runtime that cannot start, one that is absent, then each backend's own gate.
# Sets BACKEND_WHY_KIND — cannot-start | not-installed | hub-down | no-model |
# on-demand | not-answering — and BACKEND_WHY_TEXT. `hub-down` comes after the
# runtime's own facts (a broken or missing binary needs repair either way) and
# before every backend gate: the backends are the hub's children, so a stopped
# or disabled hub is the reason, not something to find in the logs. Costs one `--help` exec when a runtime
# is present (runtime_check), so call it only for a backend that is DOWN.
# Veya polls `status --json` every 10 s, so the exec gets a 2 s watchdog here,
# not the installer's 10 s: a runtime still running at 2 s has loaded (a loader
# failure is immediate), so it still counts as "starts" — no false failure, and
# three DOWN backends cost at most ~6 s, never the ctl's timeout.
BACKEND_WHY_KIND=""; BACKEND_WHY_TEXT=""
backend_down_why() { # runtime-under-$VERA_HOME/bin health-url hub-up(true|false)
    local rt="$1" url="$2" hub="${3:-true}" bin="$VERA_HOME/bin/$1"
    local RUNTIME_WATCHDOG_TICKS="${VERA_STATUS_WATCHDOG_TICKS:-8}"   # 4 Hz → 2 s (dynamic scope: runtime_check reads it)
    if [ -e "$bin" ] || [ -L "$bin" ]; then
        if ! runtime_check "$bin"; then
            # vera#347: "DOWN" alone sent GD2 to the logs for a dyld error one exec answers.
            BACKEND_WHY_KIND=cannot-start
            BACKEND_WHY_TEXT="$rt cannot start: $RUNTIME_WHY (repair: vera-ctl dep install $rt)"
            return 0
        fi
    else
        BACKEND_WHY_KIND=not-installed
        case "$rt" in
            kokoro) BACKEND_WHY_TEXT="kokoro is opt-in and not installed — vera-ctl model install kokoro --backend tts" ;;
            *)      BACKEND_WHY_TEXT="$rt is not installed in $VERA_HOME/bin and nothing answers $url — vera-ctl dep install $rt" ;;
        esac
        return 0
    fi
    if [ "$hub" != true ]; then
        BACKEND_WHY_KIND=hub-down
        if [ -f "$VERA_HOME/disabled" ]; then
            BACKEND_WHY_TEXT="$rt runs under the Vera hub, which is disabled — vera-ctl enable"
        else
            BACKEND_WHY_TEXT="$rt runs under the Vera hub, which is not serving — vera-ctl start"
        fi
        return 0
    fi
    case "$rt" in
        whisper-server)
            if [ ! -e "$VERA_HOME/models/current.bin" ]; then
                BACKEND_WHY_KIND=no-model
                BACKEND_WHY_TEXT="whisper-server starts, no model yet — vera-ctl model install whisper-medium --backend asr"
                return 0
            fi ;;
        kokoro)
            # The kokoro stanza needs BOTH model files (install-metal.sh's
            # `needs`): without them it is parked, and the first request 404s.
            if [ ! -f "$VERA_HOME/kokoro/kokoro-v1.0.onnx" ] || [ ! -f "$VERA_HOME/kokoro/voices-v1.0.bin" ]; then
                BACKEND_WHY_KIND=no-model
                BACKEND_WHY_TEXT="kokoro starts, no model yet — vera-ctl model install kokoro --backend tts"
                return 0
            fi
            BACKEND_WHY_KIND=on-demand
            BACKEND_WHY_TEXT="kokoro starts on demand at the first /v1/audio/speech"
            return 0 ;;
    esac
    BACKEND_WHY_KIND=not-answering
    BACKEND_WHY_TEXT="$rt starts, but nothing answers $url — vera-ctl logs"
}

# A string as the inside of a JSON string literal: backslash and quote escaped,
# control characters (a loader line can carry a tab) flattened to spaces.
json_str() { printf '%s' "$1" | tr '\000-\037' ' ' | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'; }

# `runtimes_why` for status --json: one entry per backend that is DOWN, keyed
# like `runtimes`; a backend that serves has NO entry (absent, not "" — the
# logs.launchd_err rule). Reads "key runtime up(true|false) health-url" lines.
runtimes_why_json() { # hub-up(true|false)
    local hub="$1" key rt up url out="" sep=""
    while read -r key rt up url; do
        [ -n "$key" ] || continue
        [ "$up" = true ] && continue
        backend_down_why "$rt" "$url" "$hub"
        out="$out$sep\"$key\":{\"kind\":\"$BACKEND_WHY_KIND\",\"why\":\"$(json_str "$BACKEND_WHY_TEXT")\"}"
        sep=","
    done
    printf '{%s}' "$out"
}

probe() { # url, label, [runtime under $VERA_HOME/bin, hub-up(true|false)] -> 0 when up
    if curl -fsSk --max-time 2 "$1" >/dev/null 2>&1; then echo "  $2: up"; return 0; fi
    if [ -n "${3:-}" ]; then
        backend_down_why "$3" "$1" "${4:-true}"
        echo "  $2: DOWN — $BACKEND_WHY_TEXT"
    else
        echo "  $2: DOWN"
    fi
    return 1
}

# The health URL THIS instance declares for a supervised backend, read from its
# own $VERA_HOME/config/vera.toml (`[[local_backends]]` id/health), falling back
# to the shipped default when there is no config yet.
#
# `status` hardcoded :11434 / :8090 / :8091 in the probe URLs *and* in the
# labels, so on an instance with its own backends it printed ANOTHER instance's
# ollama and whisper as if they were this one's — vera#115's constraint ("probes
# target the instance's OWN ports") not applied to the status verb (vera#138).
# The config is the right source: the installer generates it, and it is the
# ONLY place an operator's edit to a backend port is recorded.
backend_health() { # id, fallback_url
    local id="$1" fb="$2" u=""
    # `inb` scopes the scan to [[local_backends]] stanzas: [[mcp_upstreams]]
    # carries an `id` too, and a cur that leaked across stanza boundaries would
    # answer with a neighbour's URL.
    u="$(awk -v want="$id" '
        /^[[:space:]]*\[/ { inb = ($0 ~ /^[[:space:]]*\[\[local_backends\]\]/); cur = ""; next }
        inb && /^[[:space:]]*id[[:space:]]*=/     { split($0, a, "\""); cur = a[2]; next }
        inb && /^[[:space:]]*health[[:space:]]*=/ { if (cur == want) { split($0, a, "\""); print a[2]; exit } }
    ' "$VERA_HOME/config/vera.toml" 2>/dev/null || true)"
    printf '%s' "${u:-$fb}"
}
# ":port" for a label, or the whole URL when it names no port — never a bare
# ":" (a label that says nothing is worse than a long one).
url_port() { # url
    local pt; pt="$(printf '%s' "$1" | sed -nE 's#^[a-zA-Z][a-zA-Z0-9+.-]*://[^/]*:([0-9]+).*#\1#p')"
    if [ -n "$pt" ]; then printf ':%s' "$pt"; else printf '%s' "$1"; fi
}

# Pull one field from the cached $manifest JSON (jq if present, else sed).
jget() {
    if command -v jq >/dev/null 2>&1; then printf '%s' "$manifest" | jq -r ".$1 // empty"
    else printf '%s' "$manifest" | sed -nE "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"([^\"]*)\".*/\1/p" | head -1; fi
}

# Short git sha of the running daemon — the real version discriminator
# (CARGO_PKG_VERSION is 0.0.0), with a persisted fallback.
installed_sha() {
    curl -fsSk --max-time 3 https://127.0.0.1:$VERA_PORT/version 2>/dev/null \
        | sed -nE 's/.*"git_sha"[[:space:]]*:[[:space:]]*"([0-9a-f]{7}).*/\1/p' | head -1
}

# THE ONE WRITER for the identity markers (data/installed-sha, VERSION).
#
# vera#346: the update rollback re-stamped with `installed_sha > marker`
# straight after restarting the hub — before it had bound — so /version did not
# answer and the redirect truncated a good `364a358` to 0 bytes. A marker is a
# claim about which binary is installed; an unanswered probe is not a value.
# So: an empty value writes NOTHING (returns 1), and a real one lands tmp+mv,
# so no reader ever sees half of it.
write_marker() { # file value
    local f="$1" v="${2:-}"
    [ -n "$v" ] || return 1
    mkdir -p "$(dirname "$f")"
    printf '%s\n' "$v" > "$f.new" && mv -f "$f.new" "$f"
}

# Release-mode update (INV-SIDECAR-003): manifest -> download -> verify
# (`verify_artifact`: sha256 required; a signature when the manifest carries
# one) -> run the bundled installer -> /healthz gate, with automatic rollback
# to the prior binary on failure. This is exactly what Veya's "Update local
# Vera" invokes.
release_update() {
    local force="${1:-}" healthy rolled _
    command -v curl >/dev/null 2>&1 || { echo "ERROR: curl required"; return 1; }
    echo "checking $MANIFEST_URL ..."
    local manifest; manifest="$(curl -fsSL --max-time 15 "$MANIFEST_URL")" \
        || { echo "  channel unreachable (offline?) — nothing to do"; return 1; }
    local remote_sha url want256 sig
    remote_sha="$(jget sha)"; url="$(jget url)"; want256="$(jget sha256)"; sig="$(jget signature)"
    [ -n "$url" ] || { echo "  manifest has no url — aborting"; return 1; }
    # `|| true` IS THE FIX, not hygiene: under `set -o pipefail` a hub that
    # does not answer makes `installed_sha` return curl's 7, the assignment
    # inherits it, and `set -e` ended `update` right here, silently, rc 7 —
    # so the marker fallback below (the whole point of the marker) was
    # unreachable exactly when the hub is down.
    local local_sha; local_sha="$(installed_sha || true)"
    [ -z "$local_sha" ] && local_sha="$(head -1 "$VERA_HOME/data/installed-sha" 2>/dev/null || true)"
    echo "  installed: ${local_sha:-unknown}   channel: ${remote_sha:-?}"
    if [ -n "$remote_sha" ] && [ "$remote_sha" = "$local_sha" ] && [ "$force" != "--force" ]; then
        echo "already up to date"; return 0
    fi
    if [ "$force" = "--if-newer" ] && [ -n "$remote_sha" ] && [ "$remote_sha" = "$local_sha" ]; then
        return 0   # quiet no-op for the background timer
    fi

    local tmp art; tmp="$(mktemp -d)"; art="$tmp/$(basename "$url")"
    echo "  downloading $(basename "$url") ..."
    curl -fsSL --max-time 600 -o "$art" "$url" || { echo "  download failed"; rm -rf "$tmp"; return 1; }
    verify_artifact "$art" "$want256" "$sig" "artifact" || { rm -rf "$tmp"; return 1; }

    tar -xzf "$art" -C "$tmp" 2>/dev/null || { echo "  extract failed"; rm -rf "$tmp"; return 1; }
    local inst; inst="$(find "$tmp" -maxdepth 3 -name install.sh -type f | head -1)"
    [ -n "$inst" ] || { echo "  installer not found in archive"; rm -rf "$tmp"; return 1; }

    # Rollback prep: keep the binary we're replacing AND the markers that
    # describe it. A rollback restores both from here — never from a /version
    # read against a hub that is still starting (vera#346).
    cp -f "$VERA_HOME/bin/vera-hub" "$VERA_HOME/bin/vera-hub.prev" 2>/dev/null || true
    local prev_marker prev_version
    prev_marker="$(head -1 "$VERA_HOME/data/installed-sha" 2>/dev/null || true)"
    prev_version="$(head -1 "$VERA_HOME/VERSION" 2>/dev/null || true)"
    echo "  installing (data preserved) ..."
    # Health is a POLL, not a single shot: the installer's restart
    # (bootout→bootstrap→kickstart) leaves a few-second window before the
    # new binary binds :8443. A one-shot check here would race it and
    # roll back a perfectly good update.
    healthy=
    # The installer's own receipt — runtime REPAIRED / STILL BROKEN (vera#347)
    # and what serves (vera#349) — goes to a durable log and its verdict lines
    # are shown under this one. It used to go to /dev/null, so the user on
    # exactly the path vera#347 is about saw only "updated + healthy".
    local ulog="$tmp/install.out"
    mkdir -p "$VERA_HOME/logs"
    if VERA_HOME="$VERA_HOME" bash "$inst" > "$ulog" 2>&1; then
        for _ in $(seq 1 20); do
            curl -fsSk --max-time 3 https://127.0.0.1:$VERA_PORT/healthz >/dev/null 2>&1 && { healthy=1; break; }
            sleep 1
        done
    fi
    if [ -n "$healthy" ]; then
        # Stamp what the RUNNING binary says (/version), not what the manifest
        # claims — a manifest can lie (GD2's forced-failure artifact said
        # `deadbee`). A disagreement is printed, never papered over.
        local _v; for _v in 1 2 3 4 5; do write_version_marker && break; sleep 1; done
        local running; running="$(installed_sha || true)"
        if [ -z "$running" ] && [ -n "$remote_sha" ]; then
            # Health answered but /version did not, five times. A marker left
            # at the OLD sha would make every `update --if-newer` re-install
            # forever, so fall back to the manifest's claim — and say so.
            write_marker "$VERA_HOME/data/installed-sha" "$remote_sha" || true
            echo "  WARNING: /version did not answer after the update — installed-sha set from the manifest's claim ($remote_sha)"
        fi
        rm -f "$VERA_HOME/bin/vera-hub.prev"
        echo "updated + healthy (${running:-version unknown})"
        if [ -n "$remote_sha" ] && [ -n "$running" ] && [ "$running" != "$remote_sha" ]; then
            echo "  WARNING: the channel manifest says $remote_sha but the running binary says $running"
        fi
        update_report "$ulog"
        rm -rf "$tmp"
    else
        echo "  update unhealthy — rolling back ..."
        local restored=
        if [ -f "$VERA_HOME/bin/vera-hub.prev" ]; then
            svc_stop
            mv -f "$VERA_HOME/bin/vera-hub.prev" "$VERA_HOME/bin/vera-hub" && restored=1
            svc_start
        fi
        # The binary is the previous one again, so are its markers — put back
        # exactly what described it before the installer ran (which may have
        # stamped the failed build's identity).
        write_marker "$VERA_HOME/data/installed-sha" "$prev_marker" || true
        write_marker "$VERA_HOME/VERSION" "$prev_version" || true
        rolled=
        for _ in $(seq 1 20); do
            curl -fsSk --max-time 3 https://127.0.0.1:$VERA_PORT/healthz >/dev/null 2>&1 && { rolled=1; break; }
            sleep 1
        done
        # No marker before the update (a pre-fix install, or one this very bug
        # emptied): stamp from the restored hub — AFTER it answers, and through
        # write_marker, so a silent /version still writes nothing.
        if [ -n "$rolled" ] && { [ -z "$prev_marker" ] || [ -z "$prev_version" ]; }; then
            write_version_marker || true
        fi
        [ -n "$rolled" ] && echo "rolled back to previous (healthy)" || echo "ROLLBACK uncertain — check: vera-ctl logs"
        if [ -n "$restored" ]; then
            echo "  restored: bin/vera-hub + its version markers. The new installer's vera-ctl, config migrations and service unit stay."
        fi
        update_report "$ulog"
        rm -rf "$tmp"
        return 1
    fi
}

# A run log (update.log, converge.log) is append-only and one run starts at a
# line beginning with its header. Keep the newest <keep> runs and drop the rest
# (vera#358: update.log grew without bound — every update appended the whole
# installer transcript and nothing ever trimmed it). The rewrite goes to a temp
# file in the same directory and lands with one mv, so a reader sees the old
# file or the new one, never half of either. converge trims under its lock;
# update has none, so two updates racing (which already race on the installer
# itself) can lose one run's transcript from update.log — accepted: the log is
# a transcript, not a record anything decides on.
LOG_KEEP_RUNS="${VERA_LOG_KEEP_RUNS:-20}"
case "$LOG_KEEP_RUNS" in ''|*[!0-9]*|0) LOG_KEEP_RUNS=20 ;; esac
log_keep_runs() { # file header-prefix keep
    local f="$1" hdr="$2" keep="$3" n
    [ -f "$f" ] || return 0
    n="$(awk -v h="$hdr" 'index($0, h) == 1 { c++ } END { print c + 0 }' "$f" 2>/dev/null || echo 0)"
    [ "$n" -gt "$keep" ] || return 0
    awk -v h="$hdr" -v skip="$(( n - keep ))" 'index($0, h) == 1 { c++ } c > skip' "$f" > "$f.trim.$$" 2>/dev/null \
        && mv -f "$f.trim.$$" "$f" || rm -f "$f.trim.$$"
}

# The installer's verdict lines under `update`'s own (vera#347/#349): the
# whole transcript is appended to logs/update.log (the newest LOG_KEEP_RUNS
# runs are kept); the lines that change what the user must do are echoed here.
update_report() { # installer-output-file
    local out="$1" log="$VERA_HOME/logs/update.log"
    [ -f "$out" ] || return 0
    mkdir -p "$VERA_HOME/logs"
    { echo "== update $(date -u '+%Y-%m-%dT%H:%M:%SZ')"; cat "$out"; } >> "$log" 2>/dev/null || true
    log_keep_runs "$log" "== update " "$LOG_KEEP_RUNS"
    awk '
      /CANNOT START|REPAIRED|STILL BROKEN|ERROR:/ { print "  " $0; next }
      /^  (serving now|not serving|to add the missing)/ { blk = 1 }
      /^  Add to PATH/ { blk = 0 }
      blk && NF { print "  " $0 }
    ' "$out"
    echo "  installer transcript: $log"
}

# ---- Extensions (federated MCP tool servers) ------------------------
# An "ext" is a local MCP server (e.g. the printer) that vera-metal
# supervises and registers as an [[mcp_upstreams]] upstream — reusing the
# signed channel, verify, supervise, and rollback primitives. Layout:
#   $VERA_HOME/ext/<id>/{bin/, ext.json, data/}
EXT_DIR="$VERA_HOME/ext"

# Read one field from an ext.json (jq if present, else sed).
extjson() { # file, key
    if command -v jq >/dev/null 2>&1; then jq -r ".$2 // empty" "$1"
    else sed -nE "s/.*\"$2\"[[:space:]]*:[[:space:]]*\"([^\"]*)\".*/\1/p" "$1" | head -1; fi
}

# A whole-number field of an ext's manifest, or the default (jq when present, else sed).
extnum() { # file, key, default
    local v
    if command -v jq >/dev/null 2>&1; then v="$(jq -r ".$2 // empty" "$1" 2>/dev/null)"
    else v="$(sed -nE "s/.*\"$2\"[[:space:]]*:[[:space:]]*([0-9]+).*/\1/p" "$1" | head -1)"; fi
    case "$v" in ''|*[!0-9]*) echo "$3" ;; *) echo "$v" ;; esac
}
# The upstream limits an ext declares in its manifest (ext.json): `timeout_ms` (default 60 s: an ext
# tool may do real work — a CAD compile, a slice — the hub's 5 s default would cut off) and
# `max_body_bytes` (0 = none: the hub's own request limit). The printer declares 300 s and 256 MiB
# (decided 2026-10-11 (coordinator): a map-sized STL, a slice of ≤ 120 s plus the send).
ext_timeout_ms() { extnum "$EXT_DIR/$1/ext.json" timeout_ms 60000; }   # id
ext_max_body() { extnum "$EXT_DIR/$1/ext.json" max_body_bytes 0; }     # id

# Register/deregister an upstream with the running hub (hot, no bounce).
ext_register() { # id, mcp_url, acl
    local KEY body max
    KEY=$(cat "$VERA_HOME/data/key-veya.txt" 2>/dev/null) || return 1
    max="$(ext_max_body "$1")"
    body="{\"id\":\"$1\",\"url\":\"$2\",\"acl\":\"$3\",\"auth\":\"none\",\"enabled\":true,\"timeout_ms\":$(ext_timeout_ms "$1")"
    [ "$max" -gt 0 ] && body="$body,\"max_body_bytes\":$max"
    curl -fs --max-time 5 -X POST -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
        -d "$body}" \
        http://127.0.0.1:$VERA_ADMIN_PORT/admin/mcp/upstreams >/dev/null 2>&1
}
ext_deregister() { # id
    local KEY
    KEY=$(cat "$VERA_HOME/data/key-veya.txt" 2>/dev/null) || return 1
    curl -fs --max-time 5 -X DELETE -H "Authorization: Bearer $KEY" \
        "http://127.0.0.1:$VERA_ADMIN_PORT/admin/mcp/upstreams/$1" >/dev/null 2>&1
}

# Persist the upstream to vera.toml so it survives a hub restart. The
# admin register above is in-memory (live, no bounce); the config block
# is the durable source the hub reloads at boot. vera-metal is the source
# of truth for what's federated — not the client.
ext_persist_config() { # id, mcp_url, acl
    local cfg="$VERA_HOME/config/vera.toml" max
    [ -f "$cfg" ] || return 0
    # A re-install re-reads the manifest: its block is rewritten (the limits it declares may have changed).
    grep -q "id   = \"$1\"" "$cfg" && ext_unpersist_config "$1"
    grep -q "id   = \"$1\"" "$cfg" && return 0   # no python3 to edit it: the old block stands
    max="$(ext_max_body "$1")"
    printf '\n[[mcp_upstreams]]\nid   = "%s"\nurl  = "%s"\nacl  = "%s"\nauth = "none"\nenabled = true\ntimeout_ms = %s\n' \
        "$1" "$2" "$3" "$(ext_timeout_ms "$1")" >> "$cfg"
    [ "$max" -gt 0 ] && printf 'max_body_bytes = %s\n' "$max" >> "$cfg"
    return 0
}
# Remove an upstream's persisted block by id (python for safe TOML edit;
# skipped if python3 absent — a stale block just skips gracefully).
ext_unpersist_config() { # id
    local cfg="$VERA_HOME/config/vera.toml"
    [ -f "$cfg" ] || return 0
    command -v python3 >/dev/null 2>&1 || return 0
    python3 - "$cfg" "$1" <<'PY'
import sys, re
cfg, rid = sys.argv[1], sys.argv[2]
lines = open(cfg).read().split('\n'); out=[]; i=0
while i < len(lines):
    if lines[i].strip() == '[[mcp_upstreams]]':
        block=[lines[i]]; i+=1
        while i < len(lines) and not lines[i].lstrip().startswith('['):
            block.append(lines[i]); i+=1
        if any(re.match(r'\s*id\s*=\s*"%s"\s*$' % re.escape(rid), b) for b in block):
            if out and out[-1]=='' : out.pop()
            continue
        out.extend(block)
    else:
        out.append(lines[i]); i+=1
open(cfg,'w').write('\n'.join(out))
PY
}

# Provision an ext's declared deps (the slicer, cq-cli — third-party,
# never bundled). Opt-in: runs each dep's per-OS recipe only with
# --with-deps, or a y/N on an interactive TTY. Recipes get $DEP_DIR,
# $VERA_HOME, $EXT_DIR in env and symlink their binary into ~/.vera/bin
# (which the ext service has on PATH), so a successful install flips the
# ext out of dry-run on the next restart.
ext_provision_deps() { # id, with_deps(1/0)
    local id="$1" want="$2" extj="$EXT_DIR/$id/ext.json" name check
    [ -f "$extj" ] || return 0
    command -v python3 >/dev/null 2>&1 || return 0
    python3 - "$extj" <<'PY' | while IFS=$'\t' read -r name check; do
import json, sys
d = json.load(open(sys.argv[1]))
for dep in d.get("deps", []):
    if isinstance(dep, str):
        continue
    print("\t".join([dep.get("name", ""), dep.get("check", "") or dep.get("name", "")]))
PY
        [ -z "$name" ] && continue
        if command -v "$check" >/dev/null 2>&1 || [ -x "$VERA_HOME/bin/$check" ]; then
            echo "  dep '$name': present"; continue
        fi
        local go=
        if [ "$want" = 1 ]; then go=1
        elif ask_tty "  dep '$name' missing — pull it now (signed, prebuilt channel artifact)?"; then go=1; fi
        if [ -z "$go" ]; then
            echo "  dep '$name': skipped — ext runs in dry-run (add --with-deps)"; continue
        fi
        dep_pull "$name" || echo "  dep '$name': not on the channel yet — ext stays in dry-run"
    done
}

# ── A RUNTIME STARTS, or it does not (vera#347) ─────────────────────────
#
# Every runtime check here used to be `[ -x "$VERA_HOME/bin/<dep>" ]`: the
# FILE exists. On the GD2 Air the pinned whisper-server existed, was
# executable, and could not start — dyld looked for libwhisper under the build
# machine's /tmp/whisper.cpp/build — so it crash-looped under the hub forever,
# and install + update skipped it as "already installed" every time.
#
# So "present" now means "runs": exec `<bin> --help` (whisper-server, ollama
# and kokoro all exit 0 on it) with no stdin and a watchdog (macOS has no
# `timeout`). The verdict:
#   FAIL  missing, not executable, or a dangling symlink;
#   FAIL  the loader complained (dyld "Library not loaded", glibc "error while
#         loading shared libraries") — whatever the exit code;
#   FAIL  it died of a signal (rc > 128: dyld aborts with SIGABRT, 134) or
#         could not be exec'd at all (126/127);
#   PASS  any other exit — the image loaded and ran, which is all "starts"
#         means here (a usage error is still a running program);
#   PASS  still running at the watchdog — a loader failure is immediate.
# RUNTIME_WHY carries the one-line reason. `vera-ctl dep check <name>` exposes
# it, and the installer calls THAT (through the vera-ctl it ships with)
# rather than growing a second copy of the rule.
RUNTIME_WHY=""
RUNTIME_WATCHDOG_TICKS="${VERA_RUNTIME_WATCHDOG_TICKS:-40}"   # 4 Hz → 10 s
runtime_check() { # path -> 0 when it loads + runs; else 1 with RUNTIME_WHY
    local bin="$1" out rc="" i=0 loader
    RUNTIME_WHY=""
    if [ ! -e "$bin" ]; then
        if [ -L "$bin" ]; then RUNTIME_WHY="dangling symlink -> $(readlink "$bin" 2>/dev/null || echo '?')"
        else RUNTIME_WHY="not installed"; fi
        return 1
    fi
    if [ ! -x "$bin" ]; then RUNTIME_WHY="not executable"; return 1; fi
    out="$(mktemp)"
    # The probe runs in its OWN subshell with stderr discarded: bash (5.x, on
    # Linux) prints a job notice — "line N: PID Aborted (core dumped) …" — when
    # it reaps a child killed by a signal, and that notice belongs to no one's
    # verdict. The child's own output goes to $out; the subshell prints only
    # its exit status, or `running` when the watchdog had to stop it.
    rc="$(
        exec 2>/dev/null
        "$bin" --help > "$out" 2>&1 < /dev/null &
        pid=$!
        while [ "$i" -lt "$RUNTIME_WATCHDOG_TICKS" ] && kill -0 "$pid"; do
            sleep 0.25
            i=$(( i + 1 ))
        done
        if kill -0 "$pid"; then kill -9 "$pid"; wait "$pid"; echo running; exit 0; fi
        if wait "$pid"; then echo 0; else echo "$?"; fi
    )" || true
    if [ "$rc" = running ]; then rm -f "$out"; return 0; fi
    case "$rc" in ''|*[!0-9]*) rc=0 ;; esac
    loader="$(grep -m1 -E 'Library not loaded|image not found|dyld\[[0-9]+\]|dyld: |error while loading shared libraries|cannot open shared object' "$out" 2>/dev/null || true)"
    rm -f "$out"
    if [ -n "$loader" ]; then
        RUNTIME_WHY="$(printf '%s' "$loader" | sed -E 's/^[[:space:]]+//' | cut -c1-200)"
        return 1
    fi
    if [ "$rc" -gt 128 ]; then RUNTIME_WHY="killed by signal $(( rc - 128 )) running '--help'"; return 1; fi
    if [ "$rc" -ge 126 ]; then RUNTIME_WHY="cannot be executed (exit $rc)"; return 1; fi
    return 0
}

# Pull one PREBUILT dep binary from the channel, verify it, and drop it into
# ~/.vera/bin. Same verifier as the hub/ext (`verify_artifact`) — no brew, no
# pip, no compiler, no Python on the host. The binary is built ONCE in our CI
# per os/arch (see deploy/package-dep.sh) and pinned by sha256 (a signature
# too, once the channel carries one), so every customer gets the same bytes.
#
# The STAGED binary must START before it replaces anything (vera#347): a
# pulled dep that cannot load is refused and the installed copy is left as it
# was — a repair must never swap one broken binary for another silently.
dep_pull() { # name
    local name="$1"
    local manifest; manifest="$(curl -fsSL --max-time 15 "$CHANNEL_BASE/vera-dep-$name-$OS.json")" || return 1
    local url want256 sig
    url="$(printf '%s' "$manifest" | sed -nE 's/.*"url"[: ]*"([^"]*)".*/\1/p' | head -1 || true)"
    want256="$(printf '%s' "$manifest" | sed -nE 's/.*"sha256"[: ]*"([^"]*)".*/\1/p' | head -1 || true)"
    sig="$(printf '%s' "$manifest" | sed -nE 's/.*"signature"[: ]*"([^"]*)".*/\1/p' | head -1 || true)"
    [ -n "$url" ] || return 1
    local tmp art; tmp="$(mktemp -d)"; art="$tmp/$(basename "$url")"
    echo "  dep '$name': downloading $(basename "$url") …"
    curl -fsSL --max-time 600 -o "$art" "$url" || { rm -rf "$tmp"; return 1; }
    verify_artifact "$art" "$want256" "$sig" "dep '$name'" || { rm -rf "$tmp"; return 1; }
    tar -xzf "$art" -C "$tmp" 2>/dev/null || { rm -rf "$tmp"; return 1; }
    # Bundle layout: a dir named <name> holding the <name> executable (+
    # co-located libs, e.g. PyInstaller --onedir's _internal/). Install the
    # whole bundle to ~/.vera/bin/<name>.d and symlink ~/.vera/bin/<name>
    # → it, so PATH finds it and the libs resolve next to the real binary
    # (no per-run extraction — onedir starts instantly).
    local bundle; bundle="$(find "$tmp" -maxdepth 2 -type d -name "$name" -exec test -x '{}'/"$name" ';' -print | head -1)"
    if [ -n "$bundle" ]; then
        # Atomic swap: stage the slow (hundreds of MB) copy into <name>.d.new
        # while the existing <name>.d stays fully valid, then replace with two
        # near-instant metadata ops. If a concurrent/killed pull interrupts the
        # copy, the live bundle is untouched (only a stray .d.new is left, which
        # we clear up-front) — no dangling symlink, no half-copied bundle.
        rm -rf "$VERA_HOME/bin/$name.d.new"
        # ditto on macOS preserves a signed .app's seal (framework symlinks +
        # _CodeSignature); cp -R can invalidate it → Gatekeeper kills the dep.
        if [ "$OS" = macos ] && command -v ditto >/dev/null 2>&1; then
            ditto "$bundle" "$VERA_HOME/bin/$name.d.new"
        else
            cp -Rf "$bundle" "$VERA_HOME/bin/$name.d.new"
        fi
        chmod +x "$VERA_HOME/bin/$name.d.new/$name" 2>/dev/null || true
        if ! runtime_check "$VERA_HOME/bin/$name.d.new/$name"; then
            echo "  dep '$name': the pulled binary CANNOT START ($RUNTIME_WHY) — refused; the installed copy was left as it was"
            rm -rf "$VERA_HOME/bin/$name.d.new" "$tmp"
            return 1
        fi
        rm -rf "$VERA_HOME/bin/$name.d"
        mv -f "$VERA_HOME/bin/$name.d.new" "$VERA_HOME/bin/$name.d"
        ln -sf "$name.d/$name" "$VERA_HOME/bin/$name"
    else
        local f; f="$(find "$tmp" -type f -name "$name" | head -1)"
        [ -n "$f" ] || { echo "  dep '$name': no '$name' in artifact"; rm -rf "$tmp"; return 1; }
        cp -f "$f" "$VERA_HOME/bin/$name.new"; chmod +x "$VERA_HOME/bin/$name.new" 2>/dev/null || true
        if ! runtime_check "$VERA_HOME/bin/$name.new"; then
            echo "  dep '$name': the pulled binary CANNOT START ($RUNTIME_WHY) — refused; the installed copy was left as it was"
            rm -f "$VERA_HOME/bin/$name.new"; rm -rf "$tmp"
            return 1
        fi
        # mv, not cp: `cp` onto a symlink (a previous bundle install) writes
        # THROUGH it into the old bundle; a rename replaces the link itself.
        mv -f "$VERA_HOME/bin/$name.new" "$VERA_HOME/bin/$name"
    fi
    rm -rf "$tmp"
    echo "  dep '$name': installed (verified, starts, prebuilt from channel)"
}

# Write + (re)start the per-user service that runs an ext's MCP server.
ext_service() { # id, exec_path, args
    local id="$1" exe="$2" argv="$3" a
    if [ "$SVC" = launchd ]; then
        local LA="$HOME/Library/LaunchAgents" label="ai.sozenta.vera.ext.$id"
        mkdir -p "$LA"
        { echo '<?xml version="1.0" encoding="UTF-8"?>'
          echo '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'
          echo "<plist version=\"1.0\"><dict><key>Label</key><string>$label</string>"
          echo "<key>ProgramArguments</key><array><string>$exe</string>"
          for a in $argv; do echo "<string>$a</string>"; done
          echo "</array><key>RunAtLoad</key><true/><key>KeepAlive</key><true/>"
          echo "<key>WorkingDirectory</key><string>$EXT_DIR/$id</string>"
          # PATH includes ~/.vera/bin so the ext finds provisioned deps
          # (cq-cli, prusa-slicer) that --with-deps symlinks there.
          echo "<key>EnvironmentVariables</key><dict><key>PATH</key><string>$VERA_HOME/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string></dict>"
          echo "<key>StandardErrorPath</key><string>$EXT_DIR/$id/ext.err.log</string>"
          echo "</dict></plist>"; } > "$LA/$label.plist"
        launchctl bootout "gui/$(id -u)/$label" 2>/dev/null || true
        launchctl bootstrap "gui/$(id -u)" "$LA/$label.plist" 2>/dev/null || launchctl load "$LA/$label.plist" 2>/dev/null || true
    else
        local SD="$HOME/.config/systemd/user" unit="vera-ext-$id"
        mkdir -p "$SD"
        { echo "[Unit]"; echo "Description=Vera ext: $id"; echo "After=network.target"
          echo "[Service]"; echo "ExecStart=$exe $argv"; echo "WorkingDirectory=$EXT_DIR/$id"
          echo "Environment=PATH=$VERA_HOME/bin:/usr/local/bin:/usr/bin:/bin"
          echo "Restart=always"; echo "RestartSec=2"; echo "[Install]"; echo "WantedBy=default.target"; } > "$SD/$unit.service"
        systemctl --user daemon-reload 2>/dev/null || true
        systemctl --user enable --now "$unit.service" 2>/dev/null || true
    fi
}
ext_service_stop() { # id
    if [ "$SVC" = launchd ]; then
        launchctl bootout "gui/$(id -u)/ai.sozenta.vera.ext.$1" 2>/dev/null || true
        rm -f "$HOME/Library/LaunchAgents/ai.sozenta.vera.ext.$1.plist"
    else
        systemctl --user disable --now "vera-ext-$1.service" 2>/dev/null || true
        rm -f "$HOME/.config/systemd/user/vera-ext-$1.service"; systemctl --user daemon-reload 2>/dev/null || true
    fi
}

# Install an ext from a local tarball or the channel.
#   vera-ctl ext install printer [--with-deps]
#   vera-ctl ext install ./VeraExt-printer.tar.gz [--with-deps]
ext_install() {
    local src="" with_deps=0 a _
    for a in "$@"; do case "$a" in
        --with-deps) with_deps=1 ;;
        --*) ;; *) [ -z "$src" ] && src="$a" ;;
    esac; done
    [ -n "$src" ] || { echo "usage: vera-ctl ext install <id|tarball> [--with-deps]"; return 64; }
    local tmp; tmp="$(mktemp -d)"; local art
    if [ -f "$src" ]; then
        art="$src"
    else
        local manifest; manifest="$(curl -fsSL --max-time 15 "$CHANNEL_BASE/vera-ext-$src-$OS.json")" \
            || { echo "  no channel ext '$src' for $OS"; rm -rf "$tmp"; return 1; }
        local url want256 sig; url="$(printf '%s' "$manifest" | sed -nE 's/.*"url"[: ]*"([^"]*)".*/\1/p' | head -1 || true)"
        want256="$(printf '%s' "$manifest" | sed -nE 's/.*"sha256"[: ]*"([^"]*)".*/\1/p' | head -1 || true)"
        sig="$(printf '%s' "$manifest" | sed -nE 's/.*"signature"[: ]*"([^"]*)".*/\1/p' | head -1 || true)"
        art="$tmp/$(basename "$url")"; echo "  downloading $url"; curl -fsSL -o "$art" "$url" || { rm -rf "$tmp"; return 1; }
        # The ext channel had sha256 only, and silently skipped even that when
        # the manifest had none (vera#345). Same verifier as every download.
        verify_artifact "$art" "$want256" "$sig" "ext '$src'" || { rm -rf "$tmp"; return 1; }
    fi
    tar -xzf "$art" -C "$tmp" || { echo "  extract failed"; rm -rf "$tmp"; return 1; }
    local extj; extj="$(find "$tmp" -maxdepth 3 -name ext.json | head -1)"
    [ -n "$extj" ] || { echo "  ext.json not found in archive"; rm -rf "$tmp"; return 1; }
    local id mcp_url acl exe; id="$(extjson "$extj" id)"; mcp_url="$(extjson "$extj" mcp_url)"
    acl="$(extjson "$extj" acl)"; exe="$(extjson "$extj" exec)"
    local stage; stage="$(dirname "$extj")"
    echo "  installing ext '$id' → $EXT_DIR/$id"
    mkdir -p "$EXT_DIR/$id"; cp -Rf "$stage/." "$EXT_DIR/$id/"; chmod +x "$EXT_DIR/$id/$exe" 2>/dev/null || true
    # Provision declared deps (opt-in) BEFORE starting the service, so it
    # comes up already out of dry-run when a dep installs.
    ext_provision_deps "$id" "$with_deps"
    # Flatten first: ext.json is pretty-printed, so the args array spans lines;
    # a line-based grep misses it (and under `set -e` the empty match aborts the
    # whole install before the service is ever created). `|| true` keeps a
    # no-args ext working too.
    local args; args="$(tr '\n' ' ' < "$EXT_DIR/$id/ext.json" | grep -o '"args"[^]]*]' | sed -E 's/.*\[(.*)\]/\1/; s/[",]/ /g' || true)"
    ext_service "$id" "$EXT_DIR/$id/$exe" "$args"
    # Egress: the upstream host must be allowed — add it if missing.
    local host; host="$(printf '%s' "$mcp_url" | sed -E 's#https?://([^:/]+).*#\1#')"
    echo "  ensure [egress] allow_hosts includes: $host"
    # macOS: a launchd ext is denied LAN access until the user grants
    # Local Network (System Settings → Privacy & Security → Local Network).
    # Without it, discovery + LAN device control silently fail. Surface it
    # — and open the pane when there's a GUI session to open it in.
    local lan; lan="$(extjson "$EXT_DIR/$id/ext.json" local_network)"
    if [ "$SVC" = launchd ] && [ "$lan" = "true" ]; then
        echo ""
        echo "  ⚠ macOS: this ext reaches devices on your LAN. Grant it Local Network:"
        echo "     System Settings → Privacy & Security → Local Network → enable 'vera-tools-$id' (or the binary)"
        echo "     Until granted, the background service can't discover/reach LAN devices."
        launchctl asuser "$(id -u)" open "x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_LocalNetwork" 2>/dev/null \
            && echo "     (opened the Local Network settings pane)" || true
    fi
    # Wait for the ext's MCP endpoint, then register it with the hub.
    for _ in $(seq 1 20); do curl -fs --max-time 2 "${mcp_url%/mcp}/healthz" >/dev/null 2>&1 && break; sleep 1; done
    ext_persist_config "$id" "$mcp_url" "$acl"   # durable across hub restarts
    if ext_register "$id" "$mcp_url" "$acl"; then
        echo "ext '$id' installed + federated (tools surface as $id.<tool>)"
    else
        echo "ext '$id' installed + persisted; live register failed — it'll federate on next restart"
    fi
    rm -rf "$tmp"
}
ext_uninstall() { # id, [--purge]
    local id="$1"; [ -n "$id" ] || { echo "usage: vera-ctl ext uninstall <id> [--purge]"; return 64; }
    ext_deregister "$id"; ext_unpersist_config "$id"; ext_service_stop "$id"
    if [ "${2:-}" = "--purge" ]; then rm -rf "$EXT_DIR/$id"; echo "ext '$id' removed (incl. data)"
    else find "$EXT_DIR/$id" -mindepth 1 -maxdepth 1 ! -name data -exec rm -rf {} + 2>/dev/null; echo "ext '$id' removed (kept $EXT_DIR/$id/data)"; fi
}
ext_list() {
    local d
    [ -d "$EXT_DIR" ] || { echo "(no extensions installed)"; return 0; }
    for d in "$EXT_DIR"/*/; do [ -f "$d/ext.json" ] || continue
        local id; id="$(extjson "$d/ext.json" id)"
        local up; up="$(curl -fs --max-time 2 "$(extjson "$d/ext.json" mcp_url | sed 's#/mcp#/healthz#')" >/dev/null 2>&1 && echo up || echo down)"
        echo "  $id: server $up"
    done
}

# ---- Converger (DECISION-vera-install) --------------------------------
# converge = install = enable = repair: one idempotent verb that converges
# from ANY state and ends in a probe-verified running daemon or ONE honest,
# nonzero-exit error. Single-flight via an atomic mkdir lock (flock(1) does
# not exist on macOS); a stale lock (dead pid) is broken automatically.
CONVERGE_LOCK="$VERA_HOME/.converge.lock"
converge_lock() {
    mkdir -p "$VERA_HOME"
    if mkdir "$CONVERGE_LOCK" 2>/dev/null; then
        echo $$ > "$CONVERGE_LOCK/pid"; return 0
    fi
    local holder; holder="$(cat "$CONVERGE_LOCK/pid" 2>/dev/null || true)"
    if [ -z "$holder" ]; then
        # Empty-holder window: the owner may be BETWEEN mkdir and pid-write.
        # Give it a beat; only a still-empty (or dead) holder is stale.
        sleep 1
        holder="$(cat "$CONVERGE_LOCK/pid" 2>/dev/null || true)"
    fi
    if [ -n "$holder" ] && kill -0 "$holder" 2>/dev/null; then
        return 1   # a live converge owns it — the caller statuses, never races
    fi
    # Stale lock: break it by ATOMIC rename — two concurrent breakers cannot
    # both win (only the mv that succeeds proceeds), so two converges can
    # never both enter over one grave.
    local grave="$CONVERGE_LOCK.stale.$$"
    mv "$CONVERGE_LOCK" "$grave" 2>/dev/null || return 1
    rm -rf "$grave"
    mkdir "$CONVERGE_LOCK" 2>/dev/null || return 1
    echo $$ > "$CONVERGE_LOCK/pid"
}
# Unlock ONLY a lock we own — after any race, the loser must never remove
# the winner's lock.
converge_unlock() {
    [ "$(cat "$CONVERGE_LOCK/pid" 2>/dev/null || true)" = "$$" ] && rm -rf "$CONVERGE_LOCK" || true
}

# Where the payload (installer + binaries) lives: an explicit --payload dir,
# else VERA_SRC (repo dev / extracted bundle). The bundled layout has
# install.sh next to bin/vera-hub; the repo has deploy/install-metal.sh.
resolve_installer() {
    local base="${1:-$VERA_SRC}"
    [ -n "$base" ] || return 1
    if [ -x "$base/install.sh" ] && [ -x "$base/bin/vera-hub" ]; then echo "$base/install.sh"; return 0; fi
    if [ -f "$base/deploy/install-metal.sh" ]; then echo "$base/deploy/install-metal.sh"; return 0; fi
    return 1
}

# Persist the running hub's identity for status/update comparisons.
# Both markers from the running hub's /version — through `write_marker`, so a
# /version that does not answer writes nothing (vera#346).
write_version_marker() { # 0 = both markers written; 1 = /version silent, NOTHING written
    local sha; sha="$(installed_sha || true)"
    local ver; ver="$(curl -fsSk --max-time 3 https://127.0.0.1:$VERA_PORT/version 2>/dev/null \
        | sed -nE 's/.*"version"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' | head -1 || true)"
    [ -n "$sha" ] || return 1
    write_marker "$VERA_HOME/VERSION" "${ver:-0.0.0}+$sha" || true
    write_marker "$VERA_HOME/data/installed-sha" "$sha" || true
}

converge() {
    local payload="" jsonout="" _
    local pass=()
    while [ $# -gt 0 ]; do case "$1" in
        --payload) payload="$2"; shift 2 ;;
        --json)    jsonout=1; shift ;;
        --no-service) export VERA_NO_SERVICE=1; pass+=("--no-service"); shift ;;
        *) pass+=("$1"); shift ;;
    esac; done
    if ! converge_lock; then
        echo "converge already running (pid $(cat "$CONVERGE_LOCK/pid" 2>/dev/null || echo '?')) — status it, don't race it" >&2
        [ -n "$jsonout" ] && printf '{"ok":false,"state":"in-progress"}\n'
        return 75   # EX_TEMPFAIL: observe, retry later
    fi
    trap converge_unlock EXIT
    local inst
    if ! inst="$(resolve_installer "$payload")"; then
        echo "ERROR: no payload — need VERA_SRC (repo/bundle) or --payload DIR" >&2
        [ -n "$jsonout" ] && printf '{"ok":false,"state":"no-payload"}\n'
        converge_unlock; trap - EXIT; return 66   # EX_NOINPUT
    fi
    # converge IS the consent gesture: it clears the disable marker (install =
    # enable = repair) — but only once a payload EXISTS; a doomed enable exits
    # 66 above with the user's OFF state intact. `disable` is the only writer.
    rm -f "$VERA_HOME/disabled"
    local logdir="$VERA_HOME/logs"; mkdir -p "$logdir"
    local clog="$logdir/converge.log"
    # Bounded like update.log (vera#358), trimmed under converge's own lock
    # before this run's header lands: the newest LOG_KEEP_RUNS runs survive.
    log_keep_runs "$clog" "== converge " "$(( LOG_KEEP_RUNS - 1 ))"
    echo "== converge $(date -u '+%Y-%m-%dT%H:%M:%SZ') installer=$inst args=${pass[*]:-}" >> "$clog"
    # The installer is idempotent (layout/config/service) and now exits
    # NONZERO when the hub never answers /healthz — converge trusts that and
    # adds the machine verdict on top. All output lands in the durable log.
    local rc=0
    VERA_HOME="$VERA_HOME" bash "$inst" ${pass[@]+"${pass[@]}"} >> "$clog" 2>&1 || rc=$?
    if [ "$rc" -ne 0 ]; then
        echo "converge FAILED (installer exit $rc) — tail of $clog:" >&2
        tail -n 15 "$clog" >&2 || true
        [ -n "$jsonout" ] && printf '{"ok":false,"state":"install-failed","exit":%d,"log":"%s"}\n' "$rc" "$clog"
        converge_unlock; trap - EXIT; return 1
    fi
    # Verdict = the PROBE, never the exit code alone: poll healthz with a
    # startup grace window (the daemon may still be binding :8443).
    local healthy=
    for _ in $(seq 1 45); do
        curl -fsSk --max-time 2 https://127.0.0.1:$VERA_PORT/healthz >/dev/null 2>&1 && { healthy=1; break; }
        sleep 1
    done
    if [ -z "$healthy" ]; then
        echo "converge FAILED: hub never answered /healthz — tail of $clog:" >&2
        tail -n 15 "$clog" >&2 || true
        [ -n "$jsonout" ] && printf '{"ok":false,"state":"unhealthy","log":"%s"}\n' "$clog"
        converge_unlock; trap - EXIT; return 2
    fi
    write_version_marker || echo "converged, but /version did not answer — markers NOT written" >> "$clog"
    echo "converged: hub healthy" >> "$clog"
    if [ -n "$jsonout" ]; then status_json; else echo "converged + healthy"; fi
    converge_unlock; trap - EXIT; return 0
}

# How long to wait for a stopping hub to actually exit before escalating to
# SIGKILL. `restart --force` uses the short grace.
STOP_GRACE="${VERA_STOP_GRACE:-10}"
STOP_GRACE_FORCE="${VERA_STOP_GRACE_FORCE:-2}"

# Wait up to `secs` for `pid` to disappear. 0 = gone (or never given), 1 =
# still alive. Polls at 4 Hz — a stop that takes 300ms must not cost 1s.
wait_pid_gone() { # pid, secs
    local pid="$1" secs="$2" i=0 n
    [ -n "$pid" ] || return 0
    n=$(( secs * 4 ))
    while [ "$i" -lt "$n" ]; do
        kill -0 "$pid" 2>/dev/null || return 0
        sleep 0.25
        i=$(( i + 1 ))
    done
    ! kill -0 "$pid" 2>/dev/null
}

# Stop, and PROVE it: the old pid must be GONE before anything starts.
# `svc_stop; sleep 1` did not wait — a wedged, TERM-ignoring hub survived
# while a second hub booted against a SINGLE-WRITER data dir (keystore +
# audit chain). Escalation is TERM (the manager's own stop) → grace →
# SIGKILL.
#
# The kill is aimed THROUGH the manager wherever a unit exists: launchd
# `KeepAlive` and systemd `Restart=always` respawn a directly-killed pid,
# so a bare `kill -9` would produce a NEW hub rather than a stopped one —
# the escalation doing the exact opposite of what it claims. `svc_stop`
# boots the unit out / `systemctl stop`s it first, which unregisters the
# respawn; only after that is a direct signal to a straggler meaningful.
# The pid `stop_until_gone` last fought, published for the caller's failure
# message. Load-bearing: by the time that message prints, `svc_stop` has
# booted the unit out / removed the pidfile, so `hub_pid` returns NOTHING —
# it would print "pid=" exactly when the pid matters most.
STUCK_PID=""
# The pids that survived the WHOLE ladder — TERM, grace, SIGKILL, and a final
# wait. Non-empty is the only definition of "stop failed" any caller may use.
STUCK_PIDS=""
stop_until_gone() { # grace_seconds
    local grace="${1:-$STOP_GRACE}" pid targets="" p rc=0
    # RAW, not `hub_pid`: see svc_named_pid. A pid the manager names that is not
    # ours must reach the refusal below by NAME, not be filtered into silence.
    pid="$(svc_named_pid)"
    # PIDFILE mode: the file is a hint, not evidence. When it names nothing of
    # ours — cleared as foreign, or lost in a crash — a wedged hub can STILL be
    # holding the single-writer data dir. Find it by IDENTITY, the same
    # predicate that refuses to signal a stranger. This is the half the drive
    # needed: the wedged hub survived every restart because, once the file was
    # poisoned, nothing ever looked for it (vera#128).
    if [ -z "$pid" ] && [ -n "${VERA_NO_SERVICE:-}" ]; then
        pid="$(our_hub_by_scan)"
    fi
    STUCK_PID="$pid"
    STUCK_PIDS=""
    svc_stop                 # manager stop (TERM) + kill_lingering
    # EVERY hub of this home must be gone, not only the one the manager named.
    # `kill_lingering` finds the ones the manager does not — a hand-started
    # copy, a survivor of a crashed manager, a second hub that raced in — and
    # now reports which of them ignored TERM. They are targets of the SAME
    # ladder: a survivor left here holds the port and the redb lock, which is
    # precisely what turns the next `start` into a false success (vera#149).
    targets="$pid"
    for p in ${LINGERING_ALIVE:-}; do
        case " $targets " in *" $p "*) continue ;; esac
        targets="${targets:+$targets }$p"
    done
    for p in $targets; do
        wait_pid_gone "$p" "$grace" && continue
        # Re-prove identity in the frame that SIGNALS, not in the one that
        # decided: a pid that died and was recycled during the grace window now
        # names someone else, and `kill -9` on that number is the bystander
        # accident this guard exists to prevent (house rule: decide, then await,
        # then act — re-validate against the state at the instant of the act).
        if ! is_our_hub "$p"; then
            kill -0 "$p" 2>/dev/null || continue
            echo "  stop: pid $p is no longer this instance's hub ($(pid_cmd "$p")) — refusing to signal it" >&2
            continue
        fi
        echo "  stop: pid $p alive ${grace}s after TERM — escalating to SIGKILL" >&2
        kill -9 "$p" 2>/dev/null || true
        if ! wait_pid_gone "$p" 5; then
            STUCK_PIDS="${STUCK_PIDS:+$STUCK_PIDS }$p"
            rc=1
        fi
    done
    return $rc
}

# `restart` — stop until the old pid is provably gone, start, then let a
# BOUNDED /healthz poll pass the verdict.
#
# The old body was `svc_stop; sleep 1; svc_start; echo restarted`: an
# unconditional success claim that was false whenever `disable` had removed
# the unit and nothing started at all. Control-plane doc §0, second
# principle — a receipt's verdict comes from a post-act probe, never from an
# exit code (and never from no check at all).
#
# Exit codes, so a watchdog rung can tell the failures apart:
#   0  restarted, /healthz answered
#   1  the old hub would not die (nothing was started — refusing to run two
#      hubs on one single-writer data dir is the whole point)
#   2  started, but /healthz never answered within the window
#   3  nothing to start: no service unit is registered (disabled/uninstalled)
restart_hub() { # force
    local force="${1:-}" grace="$STOP_GRACE"
    [ -n "$force" ] && grace="$STOP_GRACE_FORCE"
    # The marker is checked HERE too, not only in `start`: vera#151 is about the
    # marker and the running daemon disagreeing, and `restart` also starts a hub.
    refuse_if_disabled restart || return 3
    if ! stop_until_gone "$grace"; then
        echo "restart FAILED: hub pid ${STUCK_PIDS:-${STUCK_PID:-unknown}} survived TERM+KILL — NOT starting a second hub on one data dir" >&2
        return 1
    fi
    if [ -n "$force" ]; then
        VERA_FORCE_KICKSTART=1 svc_start
        unset VERA_FORCE_KICKSTART
    else
        svc_start
    fi
    local healthy= tries="${VERA_RESTART_HEALTH_TRIES:-30}"
    local i=0
    while [ "$i" -lt "$tries" ]; do
        curl -fsSk --max-time 2 "https://127.0.0.1:$VERA_PORT/healthz" >/dev/null 2>&1 && { healthy=1; break; }
        sleep 1
        i=$(( i + 1 ))
    done
    if [ -n "$healthy" ]; then
        local np; np="$(hub_pid)"
        # A PROBE IS NOT A RESTART. In the row-7 drive `/healthz` answered
        # while the original hub was still alive — a second hub had booted
        # against the same data dir — and the receipt said
        # "restarted (healthy)". The verdict now needs BOTH halves: the probe
        # answered AND the pid we set out to stop is gone. The receipt names
        # the transition, so "which hub is this" is on the receipt itself.
        if [ -n "${STUCK_PID:-}" ] && kill -0 "$STUCK_PID" 2>/dev/null; then
            if is_our_hub "$STUCK_PID"; then
                echo "restart FAILED: /healthz answers but the ORIGINAL hub pid $STUCK_PID is STILL ALIVE — something else is serving :$VERA_PORT and no restart happened" >&2
            else
                echo "restart FAILED: /healthz answers but pid $STUCK_PID still exists and is no longer this instance's hub ($(pid_cmd "$STUCK_PID")) — cannot prove the old hub stopped" >&2
            fi
            return 1
        fi
        echo "restarted (healthy${force:+, forced}) pid=${STUCK_PID:-none}→${np:-unknown}"
        return 0
    fi
    local st; st="$(svc_state)"
    if [ "$st" = stopped ]; then
        echo "restart FAILED: no service unit is registered — nothing was started. Vera Local is off (disabled or uninstalled); run 'vera-ctl enable'." >&2
        return 3
    fi
    local np; np="$(hub_pid)"
    # Counted in PROBES, not seconds: one iteration costs between ~1s (a
    # refused connection returns instantly, then `sleep 1`) and ~3s (curl
    # burning its full --max-time 2 against a hung socket). "${tries}s" named
    # neither bound and was wrong at both.
    echo "restart FAILED: hub never answered /healthz after ${tries} probes (service=$st, pid=${np:-none}) — logs: $(log_svc_err) $(log_hub)" >&2
    return 2
}

# `start` — refuse over a live hub, refuse over a disabled install, and let a
# POST-CHECK pass the verdict.
#
# The old body was `svc_start; echo "started"`. Both halves of that could be
# false at once (vera#149): a wedged hub of this home still held :$VERA_PORT
# and the single-writer redb locks, so the child `svc_start` spawned died
# immediately on "Database already open. Cannot acquire lock." — and `start`
# printed `started` over the corpse. Two false receipts in a row (`stop` then
# `start`) left the install down with nothing in either receipt pointing at the
# pid that was actually holding it.
#
# It also ran a DISABLED install (vera#151): the marker stayed set while the
# daemon it exists to suppress was up and serving, so `status --json` reported
# `disabled: true` beside `healthy: true` and no reader could tell whether the
# install was meant to be running.
#
# Exit codes, so a watchdog rung can tell the failures apart:
#   0  running — started now, or already running and healthy
#   1  refused: a hub of THIS home is already alive and not healthy
#   2  started, but /healthz never answered within the window
#   3  refused: this install is disabled
# ONE marker guard, shared by the two verbs that start a hub. `start` and
# `restart` had a copy each; the property is "no verb runs a disabled install",
# and a property enforced by N copies is a census of the parts.
refuse_if_disabled() { # verb
    [ -f "$VERA_HOME/disabled" ] || return 0
    echo "${1:-start} REFUSED: this install is DISABLED — $VERA_HOME/disabled is set, and running a hub while it is set makes 'disabled' meaningless. Turn it back on with:  vera-ctl enable" >&2
    return 3
}
start_hub() {
    refuse_if_disabled start || return 3
    # A hub of THIS home already on the box is the single-writer constraint,
    # not a race to lose. Identity, not the pidfile: the drive's wedged hub was
    # invisible to every file-based check.
    local live; live="$(hub_pid)"
    [ -n "$live" ] || live="$(our_hub_by_scan)"
    if [ -n "$live" ]; then
        if curl -fsSk --max-time 2 "https://127.0.0.1:$VERA_PORT/healthz" >/dev/null 2>&1; then
            # Already up. install-metal.sh calls `vera-ctl start` after its own
            # restart precisely to land the QoS posture, so this path must
            # still push it — returning early without it would silently drop
            # the edge cooldown knobs on every install.
            push_edge_qos &
            echo "already running (pid $live, healthy on :$VERA_PORT)"
            return 0
        fi
        echo "start REFUSED: this home's hub (pid $live: $(pid_cmd "$live")) is ALREADY ALIVE and not answering /healthz. It still holds :$VERA_PORT and the single-writer $VERA_HOME/data locks, so a second hub would die on 'Database already open'. Stop it first:  vera-ctl stop   (or: vera-ctl restart --force)" >&2
        return 1
    fi
    svc_start
    local healthy= tries="${VERA_RESTART_HEALTH_TRIES:-30}" i=0
    while [ "$i" -lt "$tries" ]; do
        curl -fsSk --max-time 2 "https://127.0.0.1:$VERA_PORT/healthz" >/dev/null 2>&1 && { healthy=1; break; }
        sleep 1
        i=$(( i + 1 ))
    done
    if [ -n "$healthy" ]; then
        local np; np="$(hub_pid)"
        echo "started (pid ${np:-unknown}, healthy on :$VERA_PORT)"
        return 0
    fi
    local st; st="$(svc_state)"
    if [ "$st" = stopped ] && [ -z "${VERA_NO_SERVICE:-}" ]; then
        echo "start FAILED: no service unit is registered for this home — there was nothing to start. Vera Local is off (disabled or uninstalled); run 'vera-ctl enable'." >&2
        return 3
    fi
    local np; np="$(hub_pid)"
    echo "start FAILED: the hub never answered /healthz after ${tries} probes (service=$st, pid=${np:-none}) — logs: $(log_svc_err) $(log_hub)" >&2
    return 2
}

# `enable` with NOTHING to install — the restore path `disable` promises.
#
# `enable` was a bare alias for `converge`, which hard-requires a payload. But
# `disable` KEEPS binaries, runtimes, models, config and (since vera#151) the
# unit definition, so a restore needs no payload at all — and a channel user's
# payload is an extracted tarball in /tmp they deleted after installing, which
# is the normal thing to do. For them the documented restore path did not
# exist, and the verb that did work (`start`) left the marker set.
enable_intact() {
    [ -x "$VERA_HOME/bin/vera-hub" ] || {
        echo "ERROR: nothing to enable — $VERA_HOME has no hub binary, so there is no install to turn back on." >&2
        echo "  re-install from the channel:  vera-ctl update --force" >&2
        echo "  or converge from a payload:   vera-ctl enable --payload <extracted bundle dir>" >&2
        return 66   # EX_NOINPUT
    }
    # Put the registration back before starting, so the install survives a
    # reboot exactly as it did before `disable`.
    if [ -z "${VERA_NO_SERVICE:-}" ] && [ -f "$UNIT_KEPT" ]; then
        if [ "$SVC" = launchd ]; then
            mkdir -p "$HOME/Library/LaunchAgents"
            cp -f "$UNIT_KEPT" "$PLIST"
        else
            mkdir -p "$SD_DIR"
            cp -f "$UNIT_KEPT" "$UNIT_PATH"
            systemctl --user daemon-reload 2>/dev/null || true
            systemctl --user enable "$SD_UNIT" 2>/dev/null || true
        fi
        rm -f "$UNIT_KEPT"
        echo "  enable: autostart registration restored ($([ "$SVC" = launchd ] && printf '%s' "$LABEL" || printf '%s' "$SD_UNIT"))" >&2
    elif [ -z "${VERA_NO_SERVICE:-}" ] && ! svc_registered; then
        # Honest, not silent: the hub will run, but nothing will start it at
        # boot until a converge re-registers the unit.
        echo "  enable: no autostart registration for this home and none kept — the hub will run now but NOT after a reboot. Re-register with: vera-ctl converge --payload <dir>" >&2
    fi
    # The marker is cleared BEFORE the start, because `start_hub` refuses while
    # it is set — and it is put back if the start fails, so a failed enable
    # never leaves the install in the incoherent "disabled but running" state
    # this issue is about.
    rm -f "$VERA_HOME/disabled"
    local rc=0
    start_hub || rc=$?
    if [ "$rc" -ne 0 ]; then
        # PUT THE INSTALL BACK OFF BEFORE CLAIMING IT IS OFF (gate M1).
        #
        # Re-touching the marker on its own recreated the very vera#151
        # incoherence this function exists to close, inside the fix for it, in
        # BOTH modes: on the pidfile shape `start_hub` may have spawned a hub
        # that simply never answered /healthz — still running, still pidfiled —
        # and on the service shape the registration this function restored
        # moments ago is now ENABLED with `$UNIT_KEPT` already consumed, so
        # `disabled: true` sits beside a live, autostarting daemon.
        #
        # The undo is the whole of what `enable` did, in reverse and in order:
        # stop until PROVABLY gone, then re-keep + unregister, and only then
        # write the marker. If the hub will not die, the marker is NOT written —
        # a marker over a running daemon is the lie, not the cure.
        local sc=0
        stop_until_gone || sc=$?
        unregister_service keep
        if [ "$sc" -ne 0 ]; then
            echo "enable FAILED (start exit $rc) AND the hub it started (pid ${STUCK_PIDS:-unknown}) survived TERM+KILL — the install is NOT off and the marker was NOT written. Investigate before re-running." >&2
            return "$rc"
        fi
        touch "$VERA_HOME/disabled"
        echo "enable FAILED (start exit $rc) — the install was stopped again and left DISABLED; nothing of this home is running." >&2
        return "$rc"
    fi
    echo "enabled"
    return 0
}

# WHICH FIELDS ARE ABOUT THE HOME, AND WHICH ARE ABOUT THE SERVICE.
# The honest split, because `status --json` used to mix them in one record
# (vera#137) and Veya's watchdog reads that record as consent:
#
#   HOME-SCOPED — everything derived from $VERA_HOME, and from ITS OWN config
#     for the ports: home, installed, disabled, version, hub.{healthy,pid,port},
#     logs.*, backends.*, runtimes.*, models.*. Point this ctl at another home
#     and every one of them moves with it.
#
#   SERVICE-SCOPED — facts about the ONE per-user unit (see $LABEL):
#     service.kind, service.label, service.state. install-metal.sh registers a
#     single launchd label / systemd unit per USER regardless of which home it
#     installed, so a second instance SHARES it. `state` is therefore a claim
#     about that unit — plus, via `hub_pid`'s `is_our_hub` filter, whether a hub
#     of THIS home is alive behind it. `running` means both; `loaded` means the
#     unit is registered and no hub of this home is running behind it (a
#     crash-loop, or a unit another instance owns).
#
# `label` is OMITTED on the pidfile shape: there is no unit, and "" types as an
# identifier (#1206, the rule logs.launchd_err follows).
service_json() {
    local kind="$SVC" label=""
    if [ -n "${VERA_NO_SERVICE:-}" ]; then kind=pidfile
    elif [ "$SVC" = launchd ];      then label="$LABEL"
    else                                 label="$SD_UNIT"; fi
    if [ -n "$label" ]; then
        printf '{"kind":"%s","state":"%s","label":"%s"}' "$kind" "$(svc_state)" "$label"
    else
        printf '{"kind":"%s","state":"%s"}' "$kind" "$(svc_state)"
    fi
}

# Machine-readable status — THE probe contract Veya reads. Exit 0 always;
# the fields carry the truth.
status_json() {
    local up_hub=false up_ollama=false up_whisper=false up_kokoro=false
    # Every probe targets THIS instance: the hub on its resolved port, the
    # backends on the URLs its own config declares (vera#115/#138).
    local u_ollama u_whisper u_kokoro
    u_ollama="$(backend_health ollama  http://127.0.0.1:11434/api/tags)"
    u_whisper="$(backend_health whisper http://127.0.0.1:8090/)"
    u_kokoro="$(backend_health kokoro  http://127.0.0.1:8091/health)"
    curl -fsSk --max-time 2 "https://127.0.0.1:$VERA_PORT/healthz" >/dev/null 2>&1 && up_hub=true
    curl -fs  --max-time 2 "$u_ollama"  >/dev/null 2>&1 && up_ollama=true
    curl -fs  --max-time 2 "$u_whisper" >/dev/null 2>&1 && up_whisper=true
    curl -fs  --max-time 2 "$u_kokoro"  >/dev/null 2>&1 && up_kokoro=true
    local installed=false; [ -x "$VERA_HOME/bin/vera-hub" ] && installed=true
    local disabled=false;  [ -f "$VERA_HOME/disabled" ] && disabled=true
    local rt_ollama=false rt_whisper=false rt_kokoro=false
    [ -x "$VERA_HOME/bin/ollama" ] && rt_ollama=true
    [ -x "$VERA_HOME/bin/whisper-server" ] && rt_whisper=true
    [ -x "$VERA_HOME/bin/kokoro" ] && rt_kokoro=true
    local wm=false; [ -e "$VERA_HOME/models/current.bin" ] && wm=true
    local mkb; mkb="$(du -sk "$VERA_HOME/models" 2>/dev/null | cut -f1 || true)"
    local mbytes=$(( ${mkb:-0} * 1024 ))
    local vfile; vfile="$(cat "$VERA_HOME/VERSION" 2>/dev/null || true)"
    # ADDITIVE (control-plane doc §1 + §5.1): `hub.pid`, `hub.port`,
    # `service.label` and `logs.*` are new keys beside the existing ones.
    # Nothing here is renamed or removed — this object is THE probe contract
    # Veya reads.
    #   hub.pid   JSON number, or `null` when no live process backs the unit
    #             *and belongs to this home*. `null` beside `"state":"loaded"`
    #             is the crash-loop signal — and also the honest answer when
    #             the per-user unit is another instance's.
    #   hub.port  the port `healthy` was probed on. veya#1450's ownership guard
    #             compares a URL to a constant and says in its own comment that
    #             it is waiting for this field; without it a reader cannot tell
    #             which daemon a record is about.
    #   logs.*    absolute paths; the key is absent where the shape has no file.
    #   runtimes_why  (vera#356) why each DOWN backend is down: {"kind","why"}
    #             per backend key of `runtimes`, from backend_down_why (the
    #             same table the human `status` line prints). Absent key =
    #             that backend serves.
    local pid; pid="$(hub_pid)"; [ -n "$pid" ] || pid=null
    local portj; case "$VERA_PORT" in ''|*[!0-9]*) portj=null ;; *) portj="$VERA_PORT" ;; esac
    local why
    why="$(printf '%s\n' "ollama ollama $up_ollama $u_ollama" \
                         "whisper_server whisper-server $up_whisper $u_whisper" \
                         "kokoro kokoro $up_kokoro $u_kokoro" | runtimes_why_json "$up_hub")"
    printf '{"home":"%s","installed":%s,"disabled":%s,"version":"%s","service":%s,"hub":{"healthy":%s,"pid":%s,"port":%s},"logs":%s,"backends":{"ollama":%s,"whisper":%s,"kokoro":%s},"runtimes":{"ollama":%s,"whisper_server":%s,"kokoro":%s},"runtimes_why":%s,"models":{"whisper_current":%s,"dir_bytes":%s}}\n' \
        "$VERA_HOME" "$installed" "$disabled" "$vfile" \
        "$(service_json)" "$up_hub" "$pid" "$portj" \
        "$(logs_json)" \
        "$up_ollama" "$up_whisper" "$up_kokoro" \
        "$rt_ollama" "$rt_whisper" "$rt_kokoro" \
        "$why" \
        "$wm" "$mbytes"
}

# ── vera#348: the models Vera put in a SHARED ollama store ──────────────
#
# `uninstall --purge` printed "removed service + ~/.vera (INCLUDING data +
# models)" and left 4.6 GB behind: install-metal.sh points the hub's ollama at
# a PRE-EXISTING ~/.ollama/models (so the user's own models keep working), and
# removing $VERA_HOME cannot reach it. Removing that whole store would delete
# the user's own models; removing nothing made the receipt false.
#
# What makes the purge exact:
#   * WHICH store — this home's config (`OLLAMA_MODELS` of the ollama
#     [[local_backends]]) while it exists; on the kept-stub path, where a
#     keep-uninstall already removed config/, the copy install-metal.sh
#     recorded in data/ollama-store. The receipt names the source.
#   * WHICH models — models/ollama-pulled-by-vera.txt, written by the hub's job
#     door (jobs.rs PULLED_RECORD) only for pulls that ADDED a model, one line
#     each: <name> TAB <manifest sha256> TAB <store-relative manifest path>.
#     This script parses no model names: it removes the recorded path, and
#     only while the manifest's bytes still hash to the recorded digest — a
#     user who later re-pulled the same name has a different manifest, and
#     keeps it.
#   * NOT WHILE IN USE — another ollama serving the same store (the user's own
#     Ollama.app, say) could be mid-pull; the purge then removes nothing there
#     and prints the `ollama rm` line to run instead. Never a foreign
#     server's API: on a dev box that would be somebody's live daemon.
OLLAMA_STORE_RECORD="$VERA_HOME/data/ollama-store"
PULLED_RECORD="$VERA_HOME/models/ollama-pulled-by-vera.txt"

# OLLAMA_MODELS of the ollama [[local_backends]] stanza — that stanza only,
# never a comment or another table's key.
ollama_models_from_config() { # vera.toml
    awk '
      /^[ \t]*#/ { next }
      /^[ \t]*\[/ { lb = ($0 ~ /^[ \t]*\[\[local_backends\]\]/); isid = 0 }
      lb && /^[ \t]*id[ \t]*=[ \t]*"ollama"/ { isid = 1 }
      lb && isid && /OLLAMA_MODELS[ \t]*=/ { v = $0; sub(/.*OLLAMA_MODELS[ \t]*=[ \t]*"/, "", v); sub(/".*$/, "", v); print v; exit }
    ' "$1" 2>/dev/null || true
}
# Sets STORE_DIR + STORE_SOURCE — globals, not stdout: a `$(…)` caller would
# run it in a subshell and lose the source the receipt names.
STORE_DIR=""; STORE_SOURCE=""
resolve_ollama_store() {
    local d=""
    STORE_DIR=""; STORE_SOURCE=""
    if [ -f "$VERA_HOME/config/vera.toml" ]; then
        d="$(ollama_models_from_config "$VERA_HOME/config/vera.toml")"
        [ -z "$d" ] || STORE_SOURCE="config/vera.toml"
    fi
    if [ -z "$d" ]; then
        d="$(head -1 "$OLLAMA_STORE_RECORD" 2>/dev/null || true)"
        [ -z "$d" ] || STORE_SOURCE="data/ollama-store (recorded at install)"
    fi
    while [ "$d" != "${d%/}" ]; do d="${d%/}"; done
    STORE_DIR="$d"
}

canon_dir() { (cd -P -- "$1" 2>/dev/null && pwd) || printf '%s' "$1"; }

# Is another ollama using <store> right now? Sets STORE_USE to
#   using:<pid>    an ollama process whose store resolves to <store>
#   unknown:<pid>  an ollama process whose environment cannot be read (another
#                  user's — e.g. Linux's system ollama service — or a `ps`
#                  without -E): when in doubt, KEEP
#   writing        a partial blob in <store> changed within the last minute (a
#                  download under way — Docker, a renamed binary, anything)
#   ""             none of those
# Its store is OLLAMA_MODELS, else $HOME/.ollama/models, read from the
# process environment (/proc on Linux, `ps -E` on macOS). This home's own
# ollama is already stopped when the purge asks.
#
# Why the environment and not open files (`lsof +D <store>`): an IDLE
# `ollama serve` holds no descriptor under its store — blobs are mapped only
# while a model is loaded — so "no open file" would call a live server unused
# and the purge would delete under it. The environment names the store
# whether or not a model is loaded.
STORE_USE=""

# One value from a `ps -wwE` line (macOS). `ps -E` appends the environment to
# the command line, space-separated, with nothing marking where a value ends:
# a value runs to whitespace followed by ANY env name and `=` — mixed case
# included (launchd sets __CFBundleIdentifier, Apple_PubSub_Socket_Render,
# LaunchInstanceID; GitHub's macOS runners set ImageOS) — or to the end of the
# line. Never split on a bare space: a store on an external volume can have one.
ps_env_value() { # ps-line NAME
    printf '%s\n' "$1" | sed -nE "s/.*[[:space:]]$2=//p" \
        | sed -E 's/[[:space:]]+[A-Za-z_][A-Za-z0-9_]*=.*$//' | head -1
}
store_in_use() { # store
    local want pid env m h
    STORE_USE=""
    want="$(canon_dir "$1")"
    if command -v pgrep >/dev/null 2>&1; then
        for pid in $(pgrep -x ollama 2>/dev/null || true); do
            m=""; h=""
            if [ -r "/proc/$pid/environ" ]; then
                env="$(tr '\0' '\n' < "/proc/$pid/environ" 2>/dev/null || true)"
                m="$(printf '%s\n' "$env" | sed -n 's/^OLLAMA_MODELS=//p' | head -1)"
                h="$(printf '%s\n' "$env" | sed -n 's/^HOME=//p' | head -1)"
            else
                env="$(ps -wwE -p "$pid" -o command= 2>/dev/null || true)"
                m="$(ps_env_value "$env" OLLAMA_MODELS)"
                h="$(ps_env_value "$env" HOME)"
            fi
            if [ -z "$m" ] && [ -z "$h" ]; then STORE_USE="unknown:$pid"; return 0; fi
            [ -n "$m" ] || m="$h/.ollama/models"
            if [ "$(canon_dir "$m")" = "$want" ]; then STORE_USE="using:$pid"; return 0; fi
        done
    fi
    if [ -d "$1/blobs" ] && [ -n "$(find "$1/blobs" -maxdepth 1 -name '*-partial*' -mmin -1 2>/dev/null | head -1)" ]; then
        STORE_USE="writing"
    fi
    return 0
}

_sha256_of() { if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | awk '{print $1}'; else sha256sum "$1" | awk '{print $1}'; fi; }

# Every model in a store as `name:tag` — DISPLAY ONLY (the receipt's KEPT
# list); nothing is ever removed by a name this produces.
ollama_store_models() { # store
    local store="$1" f rel host ns model tag
    [ -d "$store/manifests" ] || return 0
    find "$store/manifests" -type f 2>/dev/null | sort | while IFS= read -r f; do
        rel="${f#"$store/manifests/"}"
        host="${rel%%/*}"; rel="${rel#*/}"
        ns="${rel%%/*}";   rel="${rel#*/}"
        model="${rel%%/*}"; tag="${rel#*/}"
        case "$tag" in */*|'') continue ;; esac
        if [ "$host" = registry.ollama.ai ] && [ "$ns" = library ]; then printf '%s:%s\n' "$model" "$tag"
        elif [ "$host" = registry.ollama.ai ]; then printf '%s/%s:%s\n' "$ns" "$model" "$tag"
        else printf '%s/%s/%s:%s\n' "$host" "$ns" "$model" "$tag"; fi
    done
}

# Remove ONE recorded model at file level: its manifest — only while it still
# hashes to the recorded digest — then every blob it referenced that NO
# remaining manifest references (a layer shared with a kept model stays).
# File level because the hub and its ollama are stopped by now, and this must
# also run from the kept stub after a keep-uninstall, with no ollama to ask.
# Sets OSR_RESULT: removed | changed | gone | refused. Adds freed KiB to
# OSR_FREED_KB, counted from blobs that are provably gone afterwards.
OSR_FREED_KB=0; OSR_RESULT=""
ollama_store_remove() { # store relpath digest
    local store="$1" rel="$2" want="$3" mf d digests hex blob kb
    OSR_RESULT=refused
    case "$rel" in manifests/*) ;; *) return 1 ;; esac
    case "/$rel/" in */../*|*/./*|*//*) return 1 ;; esac
    case "$rel" in *[!A-Za-z0-9._:/-]*) return 1 ;; esac
    mf="$store/$rel"
    if [ ! -f "$mf" ]; then
        # ollama lowercases names on case-insensitive volumes; older stores
        # kept the case they were pulled with. Same path, any case — unless
        # the store path itself holds glob characters (-ipath is a pattern).
        case "$store" in
            *[][*?]*) mf="" ;;
            *) mf="$(find "$store/manifests" -type f -ipath "$store/$rel" 2>/dev/null | head -1 || true)" ;;
        esac
    fi
    if [ -z "$mf" ] || [ ! -f "$mf" ]; then OSR_RESULT=gone; return 1; fi
    if [ "$(_sha256_of "$mf" 2>/dev/null || true)" != "$want" ]; then OSR_RESULT=changed; return 1; fi
    digests="$(grep -oE 'sha256:[0-9a-f]{64}' "$mf" 2>/dev/null | sort -u || true)"
    rm -f -- "$mf"
    if [ -e "$mf" ]; then OSR_RESULT=refused; return 1; fi
    d="$(dirname "$mf")"
    while [ "$d" != "$store/manifests" ] && rmdir "$d" 2>/dev/null; do d="$(dirname "$d")"; done
    for d in $digests; do
        hex="${d#sha256:}"
        if grep -rqF "sha256:$hex" "$store/manifests" 2>/dev/null; then continue; fi
        blob="$store/blobs/sha256-$hex"
        [ -f "$blob" ] || continue
        kb="$(du -sk "$blob" 2>/dev/null | cut -f1 || true)"
        rm -f -- "$blob"
        if [ ! -e "$blob" ]; then OSR_FREED_KB=$(( OSR_FREED_KB + ${kb:-0} )); fi
    done
    OSR_RESULT=removed
    return 0
}

human_kb() { # KiB -> "1.9G" / "340M" / "12K"
    awk -v k="${1:-0}" 'BEGIN { if (k >= 1048576) printf "%.1fG", k/1048576; else if (k >= 1024) printf "%.0fM", k/1024; else printf "%dK", k }'
}
list_names() { # max name... -> "a, b, c" (+ " and N more")
    local max="$1" n=0 out="" x; shift
    for x in "$@"; do
        n=$(( n + 1 ))
        if [ "$n" -le "$max" ]; then out="${out:+$out, }$x"; fi
    done
    if [ "$n" -gt "$max" ]; then out="$out and $(( n - max )) more"; fi
    printf '%s' "$out"
}

# Purge's half of vera#348: runs BEFORE the home is removed (both records live
# inside it) and prints exactly what it removed and kept.
#
# The record describes what went through the ollama on :11434, which is not
# always the store the config names: on Linux `--with-ollama` installs the
# SYSTEM ollama service (its own store), and the hub never spawns its own.
# So the record is read on EVERY branch; a recorded model that is not in the
# resolved store is named, with the command that removes it from whichever
# ollama has it — never silently dropped with the home.
purge_ollama_store() {
    local store name digest rel inside="" removed=() changed=() elsewhere=() refused=() recorded=() kept=() outside_names=()
    resolve_ollama_store; store="$STORE_DIR"
    if [ -s "$PULLED_RECORD" ]; then
        while IFS="$(printf '\t')" read -r name digest rel; do
            if [ -n "$name" ] && [ -n "$digest" ] && [ -n "$rel" ]; then recorded+=("$name"); fi
        done < "$PULLED_RECORD"
    fi
    if [ -n "$store" ] && [ -d "$store" ]; then
        case "$(canon_dir "$store")/" in "$(canon_dir "$VERA_HOME")/"*) inside=1 ;; esac
    fi
    if [ -z "$store" ] || [ ! -d "$store" ] || [ -n "$inside" ]; then
        # The store goes with the home (or there is none). Recorded models
        # that are NOT in it were pulled into some other ollama's store.
        if [ "${#recorded[@]}" -gt 0 ]; then
            while IFS="$(printf '\t')" read -r name digest rel; do
                { [ -n "$name" ] && [ -n "$digest" ] && [ -n "$rel" ]; } || continue
                if [ -n "$inside" ] && [ -f "$store/$rel" ]; then continue; fi
                outside_names+=("$name")
            done < "$PULLED_RECORD"
        fi
        if [ "${#outside_names[@]}" -gt 0 ]; then
            echo "  Vera recorded pulling ${#outside_names[@]} model(s) through the ollama on :11434 that are NOT in ${store:-a store this home knows} — they are in that ollama's own store, and were NOT removed: $(list_names 20 "${outside_names[@]}")"
            echo "    remove them through that ollama:  ollama rm ${outside_names[*]}"
        fi
    else
        echo "  ollama store $store (from $STORE_SOURCE) — outside $VERA_HOME, shared with any ollama of your own:"
        store_in_use "$store"
        if [ "${#recorded[@]}" -eq 0 ]; then
            echo "    removed none — Vera has no record of pulling any model there (it records pulls made through its model door; older installs recorded nothing)"
        elif [ -n "$STORE_USE" ]; then
            case "$STORE_USE" in
                using:*)   echo "    removed NONE — an ollama (pid ${STORE_USE#using:}) is running from this store, and deleting under a live server can break it." ;;
                unknown:*) echo "    removed NONE — an ollama (pid ${STORE_USE#unknown:}) is running and its store cannot be read (not your process?) — refusing to delete under it." ;;
                writing)   echo "    removed NONE — a download is in progress in this store (a partial blob changed within the last minute)." ;;
            esac
            echo "    The ${#recorded[@]} model(s) Vera pulled are still on disk; remove them through that ollama:  ollama rm ${recorded[*]}"
        else
            OSR_FREED_KB=0
            while IFS="$(printf '\t')" read -r name digest rel; do
                { [ -n "$name" ] && [ -n "$digest" ] && [ -n "$rel" ]; } || continue
                ollama_store_remove "$store" "$rel" "$digest" || true
                case "$OSR_RESULT" in
                    removed) removed+=("$name") ;;
                    changed) changed+=("$name") ;;
                    gone)    elsewhere+=("$name") ;;
                    *)       refused+=("$name") ;;
                esac
            done < "$PULLED_RECORD"
            if [ "${#removed[@]}" -gt 0 ]; then
                echo "    removed ${#removed[@]} model(s) Vera pulled: $(list_names 20 "${removed[@]}") ($(human_kb "$OSR_FREED_KB") freed)"
            else
                echo "    removed none of the ${#recorded[@]} model(s) Vera recorded pulling there"
            fi
            if [ "${#changed[@]}" -gt 0 ]; then echo "    KEPT — changed since Vera pulled it (re-pulled or edited outside Vera): $(list_names 20 "${changed[@]}")"; fi
            if [ "${#elsewhere[@]}" -gt 0 ]; then
                echo "    not in this store (removed outside Vera, or pulled into another ollama's store): $(list_names 20 "${elsewhere[@]}")"
                echo "      if an ollama still lists them:  ollama rm ${elsewhere[*]}"
            fi
            if [ "${#refused[@]}" -gt 0 ]; then echo "    NOT touched — the record's path for it is not a manifest path: $(list_names 20 "${refused[@]}")"; fi
        fi
        while IFS= read -r name; do
            if [ -n "$name" ]; then kept+=("$name"); fi
        done < <(ollama_store_models "$store")
        if [ "${#kept[@]}" -gt 0 ]; then
            echo "    now in the store (KEPT): ${#kept[@]} model(s): $(list_names 20 "${kept[@]}")"
        else
            echo "    the store now holds no models"
        fi
    fi
    # ollama writes its keypair + cache under $HOME/.ollama. Older Vera builds
    # let the hub's ollama do that even when its models lived under the home
    # (GD2 B3); it may as well be the user's own ollama's. Name it, keep it.
    if [ -d "$HOME/.ollama" ]; then
        case "$store/" in
            "$HOME/.ollama/"*) ;;   # the shared store above already named it
            *) echo "  KEPT $HOME/.ollama — outside $VERA_HOME (an ollama keypair/cache, possibly your own ollama's)"
               # vera#362: a 0.4.0 upgrader's Vera-created keypair + cache was
               # kept forever with no way out. It may be the user's, so nothing
               # is deleted — but when it holds no model at all and no running
               # ollama uses it (Ollama.app before its first pull has exactly
               # this shape), the one command that removes it is printed.
               # No pgrep = no way to see a running ollama: say nothing (fail closed).
               store_in_use "$HOME/.ollama/models"
               if command -v pgrep >/dev/null 2>&1 && [ -z "$STORE_USE" ] \
                   && [ -z "$(find "$HOME/.ollama/models/manifests" -type f 2>/dev/null | head -1)" ]; then
                   echo "    it holds no models (a keypair/cache only) — if no ollama of your own uses it: rm -rf \"$HOME/.ollama\""
               fi ;;
        esac
    fi
    return 0
}

# vera#350: `uninstall` deletes bin/ — vera-ctl included — and then told the
# user to run `vera-ctl uninstall --purge`. Keep a copy of THIS script beside
# the kept data, with the instance stamp it reads from beside itself (the
# vera#131 mechanism), so the printed next step works on the machine as it
# now stands. `--purge` removes it with the home; a reinstall removes it too.
keep_purge_stub() { # -> 0 when $VERA_HOME/vera-ctl is runnable
    local self="${BASH_SOURCE[0]:-$0}"
    [ -f "$self" ] || return 1
    cp -f "$self" "$VERA_HOME/vera-ctl.new" 2>/dev/null || return 1
    chmod +x "$VERA_HOME/vera-ctl.new"
    if [ -f "$VERA_HOME/bin/vera-ctl.env" ]; then
        cp -f "$VERA_HOME/bin/vera-ctl.env" "$VERA_HOME/vera-ctl.env.new"
    else
        { echo "# Written by 'vera-ctl uninstall' (vera#350). DEFAULTS ONLY."
          echo "VERA_HOME=\"\${VERA_HOME:-$VERA_HOME}\""
          if [ -n "${VERA_NO_SERVICE:-}" ]; then echo "VERA_NO_SERVICE=\"\${VERA_NO_SERVICE:-1}\""; fi
        } > "$VERA_HOME/vera-ctl.env.new"
    fi
    mv -f "$VERA_HOME/vera-ctl.env.new" "$VERA_HOME/vera-ctl.env"
    mv -f "$VERA_HOME/vera-ctl.new" "$VERA_HOME/vera-ctl"
}

case "${1:-status}" in
  status)
    if [ "${2:-}" = "--json" ]; then status_json; exit 0; fi
    echo "service ($SVC): $(svc_state)"
    # Labels AND URLs come from the instance, never from a literal: this form
    # printed "vera :8443" for a daemon on :28443 and probed another instance's
    # ollama/whisper as if they were this one's (vera#138).
    _hub=false; probe "https://127.0.0.1:$VERA_PORT/healthz" "vera     :$VERA_PORT" && _hub=true
    _u="$(backend_health ollama  http://127.0.0.1:11434/api/tags)"; probe "$_u" "ollama   $(url_port "$_u")" ollama "$_hub" || true
    _u="$(backend_health whisper http://127.0.0.1:8090/)";          probe "$_u" "whisper  $(url_port "$_u")" whisper-server "$_hub" || true
    if [ -f "$VERA_HOME/data/hub-id" ]; then
        echo "  hub_id: $(cat "$VERA_HOME/data/hub-id")"
    fi
    ;;
  start)   start_hub ;;
  converge) shift; converge "$@" ;;
  enable)
    shift
    # A payload was NAMED, or one is discoverable (VERA_SRC / a repo checkout)
    # -> converge, which is the full install-or-repair and clears the marker
    # itself. Otherwise restore the intact home in place (vera#151).
    _has_payload=
    for _a in "$@"; do case "$_a" in --payload) _has_payload=1 ;; esac; done
    if [ -n "$_has_payload" ] || resolve_installer >/dev/null 2>&1; then
        converge "$@"
    else
        enable_intact
    fi
    ;;
  disable)
    # Stop + unregister autostart + set the marker. KEEPS binaries, runtimes,
    # models, config — and now the unit definition too, so `enable` can restore
    # without a payload (DECISION-vera-install §2, vera#151).
    #
    # `svc_stop` is not enough on its own: it TERMs once and waits for nothing,
    # so a wedged hub outlived `disable` holding :$VERA_PORT and the
    # single-writer redb locks while the marker said the install was off
    # (vera#149). Stop until PROVABLY gone, and say so if it will not go.
    if ! stop_until_gone; then
        echo "disable FAILED: hub pid ${STUCK_PIDS:-${STUCK_PID:-unknown}} survived TERM+KILL — it still holds :$VERA_PORT and $VERA_HOME/data, so the install is NOT off. Marker NOT written." >&2
        exit 1
    fi
    mkdir -p "$VERA_HOME"
    unregister_service keep
    touch "$VERA_HOME/disabled"
    if [ -n "$SERVICE_LEFT_IN_PLACE" ]; then
        echo "disabled (binaries, runtimes, models and config kept — 'vera-ctl enable' restores)."
        echo "  NOTE: $SERVICE_LEFT_IN_PLACE was LEFT REGISTERED — it names another install, so autostart for THAT install is untouched. Nothing of $VERA_HOME is running."
    else
        echo "disabled (binaries, runtimes, models and config kept — 'vera-ctl enable' restores)"
    fi
    ;;
  stop)
    # `stop` IS stop-until-gone (vera#149). It used to be `svc_stop; echo
    # stopped`: ONE TERM, no wait, no escalation — and then "stopped" printed
    # for a hub still on the box. `kill_lingering` printed "reaped this
    # instance's hub (pid N)" on the same evidence, so both halves of the
    # receipt were false at once; `status --json` then reported
    # `pid: null` / `state: "stopped"` for a live process, which is the one
    # machine-readable contract Veya reads. The identity work of vera#128/#140
    # built the TERM -> grace -> SIGKILL -> wait ladder and wired it into
    # `restart` only; the plain verb kept the old body.
    #
    # THE VERDICT COMES FROM THE POST-CHECK. `stop_until_gone` returns nonzero
    # only when a pid survived the whole ladder, and it names them.
    if stop_until_gone; then
        if [ -n "${STUCK_PID:-}" ]; then
            echo "stopped (pid $STUCK_PID gone)"
        else
            echo "stopped (no hub of this home was running)"
        fi
    else
        # NOT MUTATION-KILLED, AND HERE IS WHY — the argument is the deliverable.
        #
        # Reaching this branch needs a process that BOTH satisfies `is_our_hub`
        # (so: a real hub of this home, with its argv intact) AND survives
        # SIGKILL for more than five seconds. On POSIX that means uninterruptible
        # sleep (D state) or an unkillable kernel state, and neither is creatable
        # from a test running as an ordinary user: SIGKILL is not maskable, a
        # SIGSTOPped process dies on it (which is exactly what T27/L22 prove), and
        # a zombie's argv is gone — so a zombie takes the `is_our_hub` refusal
        # above, not this branch. A process owned by another user would make
        # `kill -9` fail with EPERM, but it cannot be given this home's hub argv
        # without root.
        #
        # What IS covered: `wait_pid_gone` is exercised in both outcomes (L16,
        # L19, T27), `STUCK_PIDS` is written on exactly the path that reaches
        # here, and `restart_hub` reads the same variable for the same message.
        # The unexercised remainder is the wording of one `echo`.
        echo "stop FAILED: hub pid $STUCK_PIDS survived TERM+KILL and is STILL RUNNING — it holds :$VERA_PORT and the single-writer $VERA_HOME/data locks, so the next 'start' cannot succeed. Investigate:" >&2
        for _p in $STUCK_PIDS; do echo "  pid $_p: $(pid_cmd "$_p")" >&2; done
        exit 1
    fi
    ;;
  restart)
    # `--force` = the impatient rung (control-plane doc §3, ladder rung 4):
    # a 2s grace instead of 10s before SIGKILL, and launchd's own
    # `kickstart -k` is permitted. The verdict is a probe either way.
    case "${2:-}" in
      "")      restart_hub "" ;;
      --force) restart_hub 1 ;;
      *)       echo "usage: vera-ctl restart [--force]" >&2; exit 64 ;;
    esac
    ;;
  update)
    # Dev checkout present (VERA_SRC points at the repo) → build from
    # source. Otherwise → release mode: pull the signed channel artifact.
    # `update --if-newer` is the quiet form the background timer / Veya use.
    if [ -n "$VERA_SRC" ] && [ -d "$VERA_SRC/crates/vera-hub" ]; then
        echo "updating from source ($VERA_SRC) ..."
        ( cd "$VERA_SRC" && git pull --ff-only 2>/dev/null || echo "  (git pull skipped)" )
        ( cd "$VERA_SRC" && cargo build --release -p vera-hub 2>&1 | tail -1 )
        cp -f "$VERA_SRC/target/release/vera-hub" "$VERA_HOME/bin/vera-hub.new"
        svc_stop; sleep 1
        mv -f "$VERA_HOME/bin/vera-hub.new" "$VERA_HOME/bin/vera-hub"
        svc_start
        sleep 2
        curl -fsSk --max-time 3 https://127.0.0.1:$VERA_PORT/healthz >/dev/null 2>&1 \
            && echo "updated + healthy" \
            || { echo "WARNING: not healthy after update — check vera-ctl logs"; exit 1; }
    else
        release_update "${2:-}"
    fi
    ;;
  uninstall)
    # Frictionless removal: stop + drop the service unit, remove binaries.
    # KEEPS data/ (audit chain + keys) unless --purge — the one thing you
    # never want silently destroyed.
    purge=
    [ "${2:-}" = "--purge" ] && purge=1
    echo "stopping + removing the Vera service ..."
    svc_stop || true
    # Gate the OS-service teardown exactly like `disable` does: a hermetic
    # (VERA_NO_SERVICE) instance must NEVER bootout or delete the real
    # daemon's launchd/systemd registration on a dev machine (gate P2).
    if [ -n "${VERA_NO_SERVICE:-}" ]; then
        :
    elif [ "$SVC" = launchd ]; then
        unregister_service
        # Legacy per-backend units (pre-unification installs) — the hub now
        # supervises ollama/whisper/kokoro, but boot out + remove any that linger
        # so a stale KeepAlive backend can't survive uninstall holding a port.
        # Namespaced by $LABEL, so a NON-default home names units that never
        # existed (harmless no-ops) instead of the default install's (vera#150).
        for legacy in whisper ollama kokoro; do
            launchctl bootout "gui/$(id -u)/$LABEL.$legacy" 2>/dev/null || true
            rm -f "$HOME/Library/LaunchAgents/$LABEL.$legacy.plist"
        done
    else
        unregister_service
        # Legacy per-backend units, namespaced the same way.
        systemctl --user disable --now "$UNIT_BASE-whisper.service" 2>/dev/null || true
        systemctl --user disable --now "$UNIT_BASE-kokoro.service" 2>/dev/null || true
        rm -f "$SD_DIR/$UNIT_BASE-whisper.service" \
              "$SD_DIR/$UNIT_BASE-kokoro.service"
        systemctl --user daemon-reload 2>/dev/null || true
    fi
    if [ -n "$purge" ]; then
        # Measure BEFORE removing — the receipt states what was removed, so it
        # is read off the disk while the disk still has it (vera#348).
        _home_sz="$(du -sh "$VERA_HOME" 2>/dev/null | cut -f1 | tr -d ' ' || true)"
        _store_lines="$(purge_ollama_store)" \
            || _store_lines="  (the ollama store report failed — nothing is claimed about models outside $VERA_HOME)"
        rm -rf "${VERA_HOME:?}"
        if [ -e "$VERA_HOME" ]; then
            echo "purge FAILED: $VERA_HOME is still there — nothing below is claimed." >&2
            exit 1
        fi
        _what="everything under it: data (audit chain + keys), config, binaries, models${_home_sz:+ — $_home_sz}"
        if [ -n "$SERVICE_LEFT_IN_PLACE" ]; then
            echo "removed $VERA_HOME ($_what). The service registration $SERVICE_LEFT_IN_PLACE was NOT removed — it names another install."
        else
            echo "removed service + $VERA_HOME ($_what)."
        fi
        if [ -n "$_store_lines" ]; then printf '%s\n' "$_store_lines"; fi
    else
        # models/ (multi-GB, expensive to re-pull) and kokoro/ voices are KEPT
        # alongside data/ — reinstall must not re-download them. Purge is the
        # explicit, size-labelled full removal (DECISION-vera-install §2).
        # The purge helper goes in BEFORE bin/ goes away (vera#350).
        _stub=""
        if keep_purge_stub; then _stub="$VERA_HOME/vera-ctl"; fi
        rm -rf "${VERA_HOME:?}"/{bin,config,tls,connectors,plugins,agents,logs}
        rm -f "$VERA_HOME/disabled" "$VERA_HOME/VERSION" "$UNIT_KEPT"
        _kept="data (audit chain + keys)"
        [ -d "$VERA_HOME/models" ] && _kept="$_kept + models ($(du -sh "$VERA_HOME/models" 2>/dev/null | cut -f1 || echo '?'))"
        # A RECEIPT IS A CLAIM ABOUT WHAT HAPPENED. "removed service" was
        # printed verbatim even when `unregister_service` had just refused,
        # which is the vera#138/#149 shape in the one verb whose whole job is
        # removal.
        if [ -n "$SERVICE_LEFT_IN_PLACE" ]; then
            echo "removed binaries. The service registration $SERVICE_LEFT_IN_PLACE was NOT removed — it names another install. KEPT $VERA_HOME: $_kept."
        else
            echo "removed service + binaries. KEPT $VERA_HOME: $_kept."
        fi
        # A next step the machine can RUN as it now stands: bin/vera-ctl is
        # gone, the kept helper is not (vera#350).
        if [ -n "$_stub" ] && [ -x "$_stub" ] && [ -r "$VERA_HOME/vera-ctl.env" ]; then
            echo "  full removal (deletes the kept data + models too): $_stub uninstall --purge"
        else
            echo "  full removal: rm -rf $VERA_HOME   ($(du -sh "$VERA_HOME" 2>/dev/null | cut -f1 || echo '?'); no purge helper could be kept — models Vera pulled into a shared ollama store are listed in $PULLED_RECORD)"
        fi
    fi
    ;;
  logs)
    tail -n 100 -f "$VERA_HOME/logs/vera.log"
    ;;
  asr-setup)
    # One-time ASR runtime setup for DEV installs (the Veya DMG bundles
    # whisper-server and never needs this). Veya may spawn this after a
    # 409 runtime_missing from POST /admin/models/install — package
    # installation lives HERE, in the operator CLI, never in the hub.
    if ! command -v whisper-server >/dev/null 2>&1; then
        if command -v brew >/dev/null 2>&1; then
            echo "installing whisper-cpp via brew…"
            brew install whisper-cpp
        else
            echo "ERROR: whisper-server not found and brew unavailable."
            echo "Install whisper.cpp manually, then re-run: vera-ctl asr-setup"
            exit 1
        fi
    fi
    if [ -n "${VERA_SRC:-}" ] && [ -x "$VERA_SRC/deploy/install-metal.sh" ]; then
        "$VERA_SRC/deploy/install-metal.sh" --no-build
    else
        echo "whisper-server ready. Re-run the metal installer to add the"
        echo "service unit + default model:  ./deploy/install-metal.sh --no-build"
    fi
    ;;
  model)
    # #113 THIN CLIENT of the hub's authed model-jobs API — one door for the
    # UI, the operator and the agent tool alike (attributed + audited there).
    # vera-ctl model available            catalog + installed (GET /admin/models)
    # vera-ctl model install <name> [--backend llm|asr|tts]   (tts also fetches the opt-in engine)
    # vera-ctl model uninstall <name> [--backend llm|asr|tts] (DELETE /admin/models/<backend>/<name>)
    # vera-ctl model status              all jobs (id/state/percent)
    # vera-ctl model cancel <job-id>
    KEY="$(cat "$VERA_HOME/data/key-veya.txt" 2>/dev/null || true)"
    [ -n "$KEY" ] || { echo "ERROR: no key at \$VERA_HOME/data/key-veya.txt — is Vera installed?"; exit 1; }
    api() { # method path [json-body]
        if [ -n "${3:-}" ]; then
            curl -fsSk --max-time 30 -X "$1" -H "Authorization: Bearer $KEY" \
                -H 'Content-Type: application/json' -d "$3" "https://127.0.0.1:$VERA_PORT$2"
        else
            curl -fsSk --max-time 30 -X "$1" -H "Authorization: Bearer $KEY" \
                "https://127.0.0.1:$VERA_PORT$2"
        fi
    }
    sub="${2:-status}"
    case "$sub" in
      available) api GET /admin/models ;;
      status)    api GET /admin/models/jobs ;;
      install)
        name="${3:-}"; [ -n "$name" ] || { echo "usage: vera-ctl model install <name> [--backend llm|asr|tts]"; exit 64; }
        backend=llm
        [ "${4:-}" = "--backend" ] && backend="${5:-llm}"
        # JSON-safe body: python3 escapes (registry-derived names can carry
        # quotes — raw interpolation let a crafted name inject fields); the
        # no-python fallback REFUSES suspicious names rather than injecting.
        if command -v python3 >/dev/null 2>&1; then
            body="$(python3 -c 'import json,sys; print(json.dumps({"backend": sys.argv[1], "model": sys.argv[2]}))' "$backend" "$name")"
        else
            case "$name$backend" in *[\"\\]*) echo "ERROR: refusing name with quote/backslash (no python3 to escape it)"; exit 64 ;; esac
            body="{\"backend\":\"$backend\",\"model\":\"$name\"}"
        fi
        # Kokoro is OPT-IN (Veya DV-079): the installer no longer ships its
        # engine, so asking for the tts model is the consent to fetch it — the
        # pinned channel dep (sha256-verified; signature too once the channel
        # carries one — vera#345), then the weights via
        # the hub's job door. The hub's on-demand backend starts it on the
        # first /v1/audio/speech.
        if [ "$backend" = tts ] && [ ! -x "$VERA_HOME/bin/kokoro" ]; then
            dep_pull kokoro || { echo "ERROR: kokoro engine dep install failed (not on channel for $OS, or offline)"; exit 1; }
        fi
        api POST /admin/models/jobs "$body" && echo ;;
      uninstall)
        # vera-ctl model uninstall <name> --backend asr|llm|tts
        name="${3:-}"; [ -n "$name" ] || { echo "usage: vera-ctl model uninstall <name> [--backend llm|asr|tts]"; exit 64; }
        backend=llm
        [ "${4:-}" = "--backend" ] && backend="${5:-llm}"
        case "$name$backend" in *[!A-Za-z0-9._:-]*) echo "ERROR: refusing unsafe model name"; exit 64 ;; esac
        api DELETE "/admin/models/$backend/$name" && echo "uninstalled $backend/$name" ;;
      cancel)
        id="${3:-}"; [ -n "$id" ] || { echo "usage: vera-ctl model cancel <job-id>"; exit 64; }
        api DELETE "/admin/models/jobs/$id" && echo ;;
      *) echo "usage: vera-ctl model {available|install <name> [--backend llm|asr|tts]|uninstall <name> [--backend …]|status|cancel <job-id>}"; exit 64 ;;
    esac
    ;;
  dep)
    # Pull a pinned channel dep (ollama, whisper-server, …) into
    # $VERA_HOME/bin — brew-free, sha256-verified, and refused unless the
    # pulled binary actually starts (`dep check` re-asks that). The metal
    # installer calls this; users can too, to add a runtime after the fact.
    sub="${2:-}"; name="${3:-}"
    case "$sub" in
      install|update)
        [ -n "$name" ] || { echo "usage: vera-ctl dep install <name>"; exit 64; }
        dep_pull "$name" && echo "dep '$name' installed → $VERA_HOME/bin/$name" \
          || { echo "dep '$name' install failed (not on the channel for $OS, offline, or the pulled binary cannot start)"; exit 1; } ;;
      stamp)
        # Internal: the installer's one way to write the identity markers
        # (vera#346) — the SAME writer converge and update use.
        # Exit 1 when nothing was written: printing the OLD marker as if it
        # were fresh would be a receipt for a stamp that did not happen.
        write_version_marker || exit 1
        cat "$VERA_HOME/VERSION" ;;
      check)
        # Does THIS home's copy of <name> START? (vera#347) exit 0 = yes.
        [ -n "$name" ] || { echo "usage: vera-ctl dep check <name>"; exit 64; }
        if runtime_check "$VERA_HOME/bin/$name"; then echo "dep '$name': ok (starts)"
        else echo "dep '$name': CANNOT START — $RUNTIME_WHY"; exit 1; fi ;;
      *) echo "usage: vera-ctl dep {install|update|check} <name>"; exit 64 ;;
    esac
    ;;
  ext)
    sub="${2:-list}"; shift 2 2>/dev/null || shift $#
    case "$sub" in
      list)      ext_list ;;
      install)   ext_install "$@" ;;
      uninstall) ext_uninstall "$@" ;;
      update)    ext_install "$@" ;;   # re-install the channel artifact (re-registers)
      *) echo "usage: vera-ctl ext {list|install <id|tarball> [--with-deps]|update <id> [--with-deps]|uninstall <id> [--purge]}"; exit 64 ;;
    esac
    ;;
  *)
    echo "usage: vera-ctl {status [--json]|model <cmd>|converge [--with-deps|--with-ollama|--with-asr|--no-service|--payload DIR|--json]|enable|disable|start|stop|restart [--force]|update [--force|--if-newer]|uninstall [--purge]|dep <cmd>|ext <cmd>|logs|asr-setup}"; exit 64 ;;
esac
