#!/usr/bin/env bash
# infra/bin/fly-shadow-run — start, stop, guard and read SHADOW-01's shadow run on the release
# container. Pushed to /opt/fly/bin/fly-shadow-run by 05-deploy.sh. Run as root inside the
# container, by the coordinator, with the container claimed in the host's agent claim log (one
# agent at a time).
#
#   fly-shadow-run start     baseline the live fly (10 min), turn flysim's trace on, start flyshadow.service
#                            and the live-impact guard, restart flysim once. The shadow runs on a
#                            build box (SHADOW-02, below); --local runs it on this container
#                            instead, which the live fly paid for on 2026-09-30 (RTF 0.999 -> 0.93)
#   fly-shadow-run stop      stop the shadow and the guard, turn the trace off (at flysim's next
#                            restart; --restart-flysim restarts it now), remove trace and spool
#   fly-shadow-run status    the verdict in one screen
#   fly-shadow-run check     CUT-01's hook: exit 0 only if the verdict allows the automatic cutover
#                            into the release /opt/fly/current points to, onto flysim-session
#   fly-shadow-run guard     (flyshadow-guard.timer, every 60 s) stop everything and restart flysim
#                            without the trace if the live fly pays for the shadow
#   fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl   the guard's rule over recorded samples
#   fly-shadow-run baseline SAMPLES.jsonl                  the baseline those samples give
#
# The shadow is report-only (infra/units/flyshadow.service). `start` restarts flysim.service once,
# the same operator action as the unstick rule's restart: a restore keeps the rung and clears the
# ledgers. It is needed because flysim reads FLY_TRACE_DIR at start, and because the shadow can
# only follow a process from that process's own startup save.
#
# The trace cannot outlive the shadow: flysim starts no trace, and stops a running one within a
# minute, when the shadow's heartbeat (<trace dir>/consumer, every 30 s) is missing or older than
# 10 minutes; flysim also keeps the trace directory under 8 GiB, and the shadow deletes every file
# it has compared.
#
# The guard (SHADOW-01 review N2, recalibrated by round 2, G1). The live fly does not always run
# at real time (the release CT has run at a realtime factor of 0.66, and 0.77-0.99 after its cpuset
# rebalance), so the guard judges the live fly against ITSELF, before the shadow existed:
#   - `start` first samples the live fly over FLY_SHADOW_BASELINE_SECONDS (600): sixty 10-s means
#     of fly_realtime_factor and fly_lag_seconds. The BASELINE is robust: the median RTF, its
#     spread (1.4826 x the median absolute deviation) and the lag growth rate over the most recent
#     half (seconds of lag per wall second: about 1 - RTF when the loop is behind real time), so a
#     step within the window neither sets the baseline nor widens the margin. It refuses to start
#     on fewer than half the samples running.
#   - Every 60 s the guard takes one 10-s sample. Over the last 5 samples of the same flysim
#     process (a restart starts the window again) it compares the mean RTF and the lag growth
#     rate with the baseline. The margin is max(0.05, 4 x the baseline spread / sqrt(5)), so it
#     scales with how noisy this fly already was.
#   - It TRIPS only on a SUSTAINED degradation: 3 checks in a row with the 5-sample mean RTF below
#     the baseline mean minus the margin, or the lag growth rate above the baseline rate plus it.
#     A paused, booting or recovering fly is not judged.
# `fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl` runs this rule over recorded samples;
# lint drives it over real and synthetic RTF traces (infra/tests/fixtures/shadow-guard/).
# Tripping stops flyshadow.service and the guard timer, removes the trace drop-in, restarts
# flysim.service without the trace, and writes /srv/fly/shadow/guard-tripped.json. When the shadow
# is no longer running (it diverged, passed and stopped, or crashed), the guard stops its own
# timer and changes nothing: it only ever acts against a running shadow. "No longer running" means
# ActiveState inactive or failed (systemctl show), never activating: the shadow's 10-s crash-restart
# delay must not switch the guard off. `check` also requires the guard timer active and baseline.json.
#
# REMOTE (SHADOW-02). With /etc/fly/shadow-remote.env present (the operator's private file:
# FLY_SHADOW_REMOTE=<user>@<box>, FLY_SHADOW_REMOTE_KEY, FLY_SHADOW_REMOTE_KNOWN_HOSTS, optional
# FLY_SHADOW_REMOTE_PORT), `start` gives flyshadow.service a drop-in (remote.conf) that runs
# `fly-shadow relay` instead of the shadow: a light process, normal scheduling, off flysim's CPUs,
# that streams the trace, the new saves and the sugar journal over one ssh connection to the box's
# `fly-shadow ingest` (the key's forced command) and writes the box shadow's verdict back to
# /srv/fly/shadow/verdict.json. The box runs the same release, at the same path, on its own cores
# (infra/box/flyshadow-remote.service). Everything else here is unchanged: the unit name, the
# guard, `check`, CUT-01. The relay keeps flysim's heartbeat fresh only while the box's shadow of
# THIS run (FLY_SHADOW_RUN_ID, the start's Unix ms) is alive and the box has everything that was on
# this disk a minute ago, so a dead box, shadow or network stops the trace like a dead local shadow.
# `check` in remote mode also needs /srv/fly/shadow/relay.json healthy and less than a minute old.
#
# Files (all owned by fly):
#   /srv/fly/shadow/trace/trace-<ms>-<pid>.jsonl   flysim's per-process trace (4 GiB each, 8 in all)
#   /srv/fly/shadow/trace/consumer                  the shadow's heartbeat
#   /srv/fly/shadow/spool/                          copies of the live saves, bounded (512 MiB)
#   /srv/fly/shadow/verdict.json                    fly-shadow-verdict-v1 (the CUT-01 contract)
#   /srv/fly/shadow/divergence.json                 the first divergence with its context
#   /srv/fly/shadow/baseline.json                   the guard's baseline (and baseline-samples.jsonl)
#   /srv/fly/shadow/guard-state.json                the guard's recent samples
#   /srv/fly/shadow/relay.json                      remote mode: the relay's health
set -euo pipefail

SHADOW_DIR="${FLY_SHADOW_DIR:-/srv/fly/shadow}"
DROPIN_DIR=/etc/systemd/system/flysim.service.d
DROPIN="$DROPIN_DIR/shadow-trace.conf"
REMOTE_ENV="${FLY_SHADOW_REMOTE_ENV:-/etc/fly/shadow-remote.env}"
REMOTE_DROPIN_DIR="${FLY_SHADOW_REMOTE_DROPIN_DIR:-/etc/systemd/system/flyshadow.service.d}"
REMOTE_DROPIN="$REMOTE_DROPIN_DIR/remote.conf"
# How long start waits for the first heartbeat (remote: at least 300 s, because the box's shadow
# restarts for the new run and the ingest hashes the release first).
HEARTBEAT_WAIT="${FLY_SHADOW_HEARTBEAT_WAIT_SECONDS:-60}"
BIN="${FLY_SHADOW_BIN:-/opt/fly/current/fly-shadow}"
METRICS_URL="${FLY_METRICS_URL:-http://127.0.0.1:9101}"
CONTROL_URL="${FLY_CONTROL_URL:-http://127.0.0.1:7401}"
# The ledger digest period in transitions: about one a second. Every boundary is proved in the
# offline rehearsal (the SHADOW-01 report); on the stream a digest a second bounds the extra work.
LEDGERS_EVERY="${FLY_SHADOW_LEDGERS_EVERY:-60}"
BASELINE_SECONDS="${FLY_SHADOW_BASELINE_SECONDS:-600}"

die() { echo "fly-shadow-run: $*" >&2; exit 2; }
log() { echo "fly-shadow-run: $*"; }

need_root() { [ "$(id -u)" = 0 ] || die "run as root (it installs a drop-in and restarts flysim)"; }

# One JSON sample of the live fly: {t, status, rtMean, lag, uptime}, the realtime factor averaged
# over 10 one-second reads.
sample() {
    python3 - "$METRICS_URL" "$CONTROL_URL" <<'PY'
import json, sys, time, urllib.request
metrics_url, control_url = sys.argv[1], sys.argv[2]
def metrics():
    text = urllib.request.urlopen(metrics_url + "/metrics", timeout=3).read().decode()
    out = {}
    for line in text.splitlines():
        if line.startswith("#"):
            continue
        parts = line.split()
        if len(parts) == 2:
            try:
                out[parts[0]] = float(parts[1])
            except ValueError:
                pass
    return out
factors = []
for _ in range(10):
    factors.append(metrics().get("fly_realtime_factor", 0.0))
    time.sleep(1)
m = metrics()
try:
    status = json.load(urllib.request.urlopen(control_url + "/status", timeout=3)).get("status")
except Exception:
    status = None
print(json.dumps({"t": time.time(), "status": status, "rtMean": sum(factors) / len(factors),
                  "lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")}))
PY
}

# The guard's rule, one definition for `baseline`, `decide` and `simulate`.
GUARD_PY='
import json, math, sys
WINDOW, SUSTAIN, MIN_MARGIN = 5, 3, 0.05

def running(s):
    return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None

def rate(samples):
    """Lag growth per wall second over the longest same-process run of samples."""
    best, run = None, []
    for s in samples:
        if run and s["uptime"] < run[-1]["uptime"]:
            run = []
        run.append(s)
        if len(run) >= 2 and (best is None or len(run) > len(best)):
            best = list(run)
    if not best or best[-1]["t"] <= best[0]["t"]:
        return None
    return max(0.0, (best[-1]["lag"] - best[0]["lag"]) / (best[-1]["t"] - best[0]["t"]))

def baseline(samples):
    """Robust statistics of the running samples: a step in the live fly within the window (its own
    warm-up, a load coming or going) must neither set the baseline nor widen the margin, as long
    as most of the window is on one side of it. The RTF is the median; its spread is 1.4826 x the
    median absolute deviation, which estimates the standard deviation without the step; the lag
    growth rate is taken over the most recent half, after any early step."""
    ok = [s for s in samples if running(s)]
    if len(ok) < max(3, len(samples) // 2):
        raise SystemExit("baseline: only %d of %d samples running" % (len(ok), len(samples)))
    recent = ok[len(ok) // 2:]
    rtf = sorted(s["rtMean"] for s in ok)
    median = rtf[len(rtf) // 2] if len(rtf) % 2 else (rtf[len(rtf) // 2 - 1] + rtf[len(rtf) // 2]) / 2
    dev = sorted(abs(x - median) for x in rtf)
    mad = dev[len(dev) // 2] if len(dev) % 2 else (dev[len(dev) // 2 - 1] + dev[len(dev) // 2]) / 2
    sd = 1.4826 * mad
    lag_rate = rate(recent)
    return {"rtfMean": median, "rtfSd": sd, "lagRate": lag_rate if lag_rate is not None else 0.0,
            "samples": len(ok), "margin": max(MIN_MARGIN, 4 * sd / math.sqrt(WINDOW))}

def decide(base, state, s):
    """Returns (state, verdict); the verdict starts with ok or trip."""
    history, run = state.get("history", []), state.get("degradedRun", 0)
    if not running(s):
        return state, "ok (flysim is %s: not judged)" % s.get("status")
    if history and s["uptime"] < history[-1]["uptime"]:
        history, run = [], 0
    history = (history + [s])[-WINDOW:]
    state = {"history": history, "degradedRun": run}
    if len(history) < WINDOW:
        state["degradedRun"] = 0
        return state, "ok (warming: %d of %d samples in this process)" % (len(history), WINDOW)
    rtf = sum(h["rtMean"] for h in history) / WINDOW
    lag_rate = rate(history) or 0.0
    m = base["margin"]
    why = []
    if rtf < base["rtfMean"] - m:
        why.append("realtime factor %.3f < baseline %.3f - %.3f" % (rtf, base["rtfMean"], m))
    if lag_rate > base["lagRate"] + m:
        why.append("lag growth %.3f s/s > baseline %.3f + %.3f" % (lag_rate, base["lagRate"], m))
    state["degradedRun"] = run + 1 if why else 0
    if state["degradedRun"] >= SUSTAIN:
        return state, "trip " + "; ".join(why) + " (%d checks in a row)" % state["degradedRun"]
    if why:
        return state, "ok degraded %d/%d: %s" % (state["degradedRun"], SUSTAIN, "; ".join(why))
    return state, "ok"

def load_jsonl(path):
    return [json.loads(line) for line in open(path) if line.strip()]

mode = sys.argv[1]
if mode == "baseline":
    print(json.dumps(baseline(load_jsonl(sys.argv[2]))))
elif mode == "decide":
    base, state = json.load(open(sys.argv[2])), json.load(open(sys.argv[3]))
    state, verdict = decide(base, state, json.load(open(sys.argv[4])))
    json.dump(state, open(sys.argv[3], "w"))
    print(verdict)
    sys.exit(1 if verdict.startswith("trip") else 0)
elif mode == "simulate":
    base = baseline(load_jsonl(sys.argv[2]))
    state, n = {}, 0
    for n, s in enumerate(load_jsonl(sys.argv[3]), 1):
        state, verdict = decide(base, state, s)
        if verdict.startswith("trip"):
            print("trip at check %d: %s (baseline %s)" % (n, verdict, json.dumps(base)))
            sys.exit(1)
    print("no trip over %d checks (baseline %s)" % (n, json.dumps(base)))
'

# The shadow must never share a CPU with the live fly (review N2): refuse unless the unit's cpuset
# drop-in exists (05-deploy skips every cpuset drop-in when the CT conf and CPUSET disagree) and its
# AllowedCPUs is non-empty and disjoint from flysim.service's.
check_cpuset() {
    local dropin="${FLY_SHADOW_CPUSET_DROPIN:-/etc/systemd/system/flyshadow.service.d/cpuset.conf}"
    [ -f "$dropin" ] || die "$dropin is missing: flyshadow would run on every CPU, including flysim's. Run 05-deploy with CPUSET set; nothing started"
    local shadow_cpus sim_cpus
    shadow_cpus="$(systemctl show -p AllowedCPUs --value flyshadow.service 2>/dev/null || true)"
    sim_cpus="$(systemctl show -p AllowedCPUs --value flysim.service 2>/dev/null || true)"
    [ -n "$shadow_cpus" ] || die "flyshadow.service has an empty AllowedCPUs; nothing started"
    [ -n "$sim_cpus" ] || die "flysim.service has an empty AllowedCPUs, so the shadow cannot be kept off it; nothing started"
    local overlap rc=0
    overlap="$(python3 -c '
import sys
def cpus(t):
    out = set()
    for part in t.replace(",", " ").split():
        a, _, b = part.partition("-")
        out.update(range(int(a), int(b or a) + 1))
    return out
try:
    both = cpus(sys.argv[1]) & cpus(sys.argv[2])
except ValueError:
    sys.exit(2)
if both:
    print(",".join(str(c) for c in sorted(both)))
    sys.exit(1)
' "$shadow_cpus" "$sim_cpus" 2>/dev/null)" || rc=$?
    case "$rc" in
        0) ;;
        1) die "flyshadow.service AllowedCPUs ($shadow_cpus) overlaps flysim.service's ($sim_cpus) on CPU $overlap; nothing started" ;;
        *) die "cannot parse AllowedCPUs (flyshadow '$shadow_cpus', flysim '$sim_cpus'); nothing started" ;;
    esac
}

# Remote mode's prerequisites, checked before anything changes.
check_remote() {
    [ -r "$REMOTE_ENV" ] || die "$REMOTE_ENV is not readable"
    local target key known
    target="$(sed -n 's/^FLY_SHADOW_REMOTE=//p' "$REMOTE_ENV" | tail -n 1)"
    key="$(sed -n 's/^FLY_SHADOW_REMOTE_KEY=//p' "$REMOTE_ENV" | tail -n 1)"
    known="$(sed -n 's/^FLY_SHADOW_REMOTE_KNOWN_HOSTS=//p' "$REMOTE_ENV" | tail -n 1)"
    [ -n "$target" ] || die "$REMOTE_ENV sets no FLY_SHADOW_REMOTE"
    { [ -n "$key" ] && [ -f "$key" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KEY ($key) is not a file"
    { [ -n "$known" ] && [ -f "$known" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KNOWN_HOSTS ($known) is not a file"
    [ "$(stat -c %U "$key")" = "${FLY_SHADOW_KEY_OWNER:-fly}" ] || die "$key must be owned by fly (the relay runs as fly)"
    command -v ssh >/dev/null || die "no ssh client in this container (apt-get install openssh-client)"
}

start() {
    need_root
    local mode=remote
    for arg in "$@"; do
        case "$arg" in
            --local) mode=local ;;
            *) die "start: unknown option $arg" ;;
        esac
    done
    [ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01"
    systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running"
    if [ "$mode" = remote ]; then
        [ -f "$REMOTE_ENV" ] || die "no $REMOTE_ENV: the shadow runs on a build box (SHADOW-02; runbook). Pass --local to run it on this container instead, at the live fly's expense"
        check_remote
    fi
    check_cpuset
    install -d -o fly -g fly -m 0755 "$SHADOW_DIR" "$SHADOW_DIR/trace"
    # A previous run's verdict is kept beside, never read as this run's.
    if [ -f "$SHADOW_DIR/verdict.json" ]; then
        mv "$SHADOW_DIR/verdict.json" "$SHADOW_DIR/verdict.$(date -u +%Y%m%dT%H%M%SZ).json"
    fi
    rm -f "$SHADOW_DIR/divergence.json" "$SHADOW_DIR/guard-tripped.json"
    log "recording the live fly's baseline over ${BASELINE_SECONDS} s, before the shadow exists"
    local n samples base
    n=$(( BASELINE_SECONDS / 10 ))
    [ "$n" -ge 3 ] || die "FLY_SHADOW_BASELINE_SECONDS must be at least 30"
    samples="$SHADOW_DIR/baseline-samples.jsonl"
    : > "$samples"
    for _ in $(seq 1 "$n"); do
        sample >> "$samples" || die "could not read flysim's metrics for the baseline"
    done
    base="$(python3 -c "$GUARD_PY" baseline "$samples")" \
        || die "flysim did not run normally during the baseline; not starting the shadow"
    printf '%s\n' "$base" > "$SHADOW_DIR/baseline.json"
    printf '{}\n' > "$SHADOW_DIR/guard-state.json"
    chown fly:fly "$SHADOW_DIR/baseline.json" "$samples" "$SHADOW_DIR/guard-state.json"
    log "baseline: $base"
    mkdir -p "$DROPIN_DIR" "$REMOTE_DROPIN_DIR"
    if [ "$mode" = remote ]; then
        local run_id
        run_id="$(date +%s%3N)"
        [ "$HEARTBEAT_WAIT" -ge 300 ] || HEARTBEAT_WAIT=300
        cat > "$REMOTE_DROPIN" <<EOF
# written by fly-shadow-run start (SHADOW-02); removed by fly-shadow-run stop and by its guard.
# The shadow runs on a build box; this unit is its relay: light, normal scheduling, off flysim's CPUs.
[Service]
EnvironmentFile=$REMOTE_ENV
Environment=FLY_SHADOW_RUN_ID=$run_id
ExecStart=
ExecStart=$BIN relay
CPUSchedulingPolicy=other
Nice=5
CPUWeight=50
IOSchedulingClass=best-effort
MemoryMax=512M
EOF
        log "remote shadow, run $run_id: flyshadow.service relays to the build box in $REMOTE_ENV"
    else
        rm -f "$REMOTE_DROPIN"
        log "LOCAL shadow on this container (--local)"
    fi
    cat > "$DROPIN" <<EOF
# written by fly-shadow-run start (SHADOW-01); removed by fly-shadow-run stop and by its guard.
[Service]
Environment=FLY_TRACE_DIR=$SHADOW_DIR/trace
Environment=FLY_TRACE_LEDGERS=$LEDGERS_EVERY
EOF
    systemctl daemon-reload
    rm -f "$SHADOW_DIR/relay.json" "$SHADOW_DIR/trace/consumer"
    systemctl start flyshadow.service
    # flysim starts no trace without a live consumer: wait for the shadow's heartbeat (remote: the
    # relay writes it once the box's shadow of this run is alive and the sync is caught up).
    for _ in $(seq 1 "$HEARTBEAT_WAIT"); do
        [ -f "$SHADOW_DIR/trace/consumer" ] && break
        sleep 1
    done
    [ -f "$SHADOW_DIR/trace/consumer" ] || { stop_all "the shadow wrote no heartbeat"; die "flyshadow.service did not come up (remote: journalctl -u flyshadow; $SHADOW_DIR/relay.json)"; }
    log "flyshadow.service started; restarting flysim.service so the shadow follows it from its start"
    systemctl restart flysim.service
    systemctl start flyshadow-guard.timer
    log "started, guarded every 60 s. Read progress with: fly-shadow-run status"
}

# Stops the shadow and the guard and turns the trace off. $1: why (logged).
stop_all() {
    systemctl stop flyshadow-guard.timer 2>/dev/null || true
    systemctl stop flyshadow.service 2>/dev/null || true
    rm -f "$DROPIN" "$REMOTE_DROPIN"
    systemctl daemon-reload
    log "stopped the shadow: $1"
}

stop() {
    need_root
    local restart_flysim=0 keep=0
    for arg in "$@"; do
        case "$arg" in
            --restart-flysim) restart_flysim=1 ;;
            --keep) keep=1 ;;
            *) die "stop: unknown option $arg" ;;
        esac
    done
    stop_all "fly-shadow-run stop"
    if [ "$restart_flysim" = 1 ]; then
        systemctl restart flysim.service
        log "flysim.service restarted without the trace"
    else
        log "flysim stops its current trace within a minute (no consumer) and starts none at its next restart"
    fi
    rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json"
    if [ "$keep" = 0 ]; then
        rm -rf "$SHADOW_DIR/spool" "$SHADOW_DIR/work"
        find "$SHADOW_DIR/trace" -name 'trace-*.jsonl' -delete 2>/dev/null || true
    fi
    log "the verdict stays in $SHADOW_DIR/verdict.json"
}

# "ActiveState/SubState" of a unit, from `systemctl show` (`is-active` cannot tell a crashed unit
# waiting out its restart delay, activating/auto-restart, from a stopped one).
unit_state() {
    local out active
    out="$(systemctl show -p ActiveState,SubState "$1" 2>/dev/null)" || true
    active="$(printf '%s\n' "$out" | sed -n 's/^ActiveState=//p')"
    # An unreadable state is not "stopped": the guard keeps running and judges the fly.
    case "$active" in
        active|inactive|failed|activating|deactivating|reloading) printf '%s\n' "$active" ;;
        *) printf 'unknown\n' ;;
    esac
}

guard() {
    need_root
    if [ ! -f "$SHADOW_DIR/baseline.json" ]; then
        log "no baseline: nothing to guard"
        systemctl stop flyshadow-guard.timer 2>/dev/null || true
        exit 0
    fi
    # The guard acts only against a shadow that is up or on its way up. One that diverged, passed
    # and stopped, or was stopped costs the live fly nothing more (ActiveState inactive/failed), and
    # flysim stops its trace without the shadow's heartbeat. During the shadow's crash-restart delay
    # (Restart=on-failure, RestartSec=10) the unit is `activating` (auto-restart): the guard must
    # keep running, or the restarted shadow runs unguarded while `check` still allows a cutover
    # (SHADOW-01 review round 3, G1-a).
    local active_state
    active_state="$(unit_state flyshadow.service)"
    case "$active_state" in
        inactive|failed)
            log "flyshadow.service is $active_state: the guard stops itself and changes nothing"
            systemctl stop flyshadow-guard.timer 2>/dev/null || true
            exit 0
            ;;
    esac
    [ -f "$SHADOW_DIR/guard-state.json" ] || printf '{}\n' > "$SHADOW_DIR/guard-state.json"
    local now tmp verdict
    now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; }
    tmp="$(mktemp)"
    printf '%s\n' "$now" > "$tmp"
    if verdict="$(python3 -c "$GUARD_PY" decide "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json" "$tmp")"; then
        rm -f "$tmp"
        log "guard: $verdict ($now)"
        exit 0
    fi
    rm -f "$tmp"
    log "guard TRIPPED: $verdict ($now)"
    stop_all "guard: $verdict"
    rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json"
    python3 -c 'import json,sys,datetime; json.dump({"at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "reason": sys.argv[1], "sample": json.loads(sys.argv[2])}, open(sys.argv[3], "w"))' \
        "$verdict" "$now" "$SHADOW_DIR/guard-tripped.json"
    systemctl restart flysim.service
    log "flysim.service restarted without the trace; see $SHADOW_DIR/guard-tripped.json"
}

status() {
    systemctl is-active flyshadow.service || true
    systemctl is-active flyshadow-guard.timer || true
    [ -f "$SHADOW_DIR/guard-tripped.json" ] && echo "GUARD TRIPPED: $(cat "$SHADOW_DIR/guard-tripped.json")"
    if [ -f "$REMOTE_DROPIN" ] && [ -f "$SHADOW_DIR/relay.json" ]; then
        python3 - "$SHADOW_DIR/relay.json" <<'PY'
import json, sys
r = json.load(open(sys.argv[1]))
print(f"remote relay: {'healthy' if r.get('healthy') else 'NOT HEALTHY'} (connected {r.get('connected')}, "
      f"box shadow alive {r.get('remoteAlive')} {r.get('remoteWhy') or ''}); caught up "
      f"{r.get('caughtUpSecondsAgo')} s ago; unsynced {r.get('unsyncedBytes')} B; updated {r.get('updatedAt')}")
PY
    fi
    [ -f "$SHADOW_DIR/verdict.json" ] || { echo "no verdict yet"; return 0; }
    python3 - "$SHADOW_DIR/verdict.json" <<'PY'
import json, sys
v = json.load(open(sys.argv[1]))
c = v["compared"]
print(f"verdict {v['status']}: {v['reason']}")
print(f"  compared {c['brainSeconds']:.0f} of {v['required']['brainSeconds']:.0f} brain s "
      f"({c['transitions']} transitions, {c['segments']} segments); updated {v['updatedAt']}")
print(f"  sugar {c['sugar']}, rewards {c['rewards']} {c['rewardKinds']}, macro events {c['macroEvents']}, "
      f"slot saves {c['slotSaves']}, rollbacks {c['rollbacks']}, ledger checks {c['ledgerChecks']}")
print(f"  checkpoints {c['checkpoints']}; skipped {v['skipped']}; spool evicted {v['spoolEvicted']}")
print(f"  behind the live trace ~{v['lagTransitions']} transitions; live lag {v['liveLagSeconds']} s; cost {v['cost']}")
if v["firstDivergence"]:
    print(f"  FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}")
PY
}

check() {
    # A tripped guard, a shadow that is not running, or a run that no guard watched never allows a
    # cutover, whatever the verdict file says: the guard timer must be active and its baseline
    # present (G1-a).
    if [ -f "$SHADOW_DIR/guard-tripped.json" ]; then
        echo "cutover refused: the guard tripped ($(cat "$SHADOW_DIR/guard-tripped.json"))"
        exit 1
    fi
    if ! systemctl is-active --quiet flyshadow.service; then
        echo "cutover refused: flyshadow.service is not running"
        exit 1
    fi
    if ! systemctl is-active --quiet flyshadow-guard.timer; then
        echo "cutover refused: flyshadow-guard.timer is not active (this run is not guarded)"
        exit 1
    fi
    if [ ! -f "$SHADOW_DIR/baseline.json" ]; then
        echo "cutover refused: no baseline.json (this run was not baselined by fly-shadow-run start)"
        exit 1
    fi
    # Remote (SHADOW-02): the relay must be healthy now (connected, the box's shadow of this run
    # alive, the sync caught up), not just have relayed a pass lately.
    if [ -f "$REMOTE_DROPIN" ]; then
        local why rc=0
        why="$(python3 - "$SHADOW_DIR/relay.json" <<'PY'
import datetime, json, sys
try:
    r = json.load(open(sys.argv[1]))
    t = datetime.datetime.fromisoformat(r["updatedAt"].replace("Z", "+00:00"))
except Exception as e:
    print("no readable relay.json (%s)" % e); sys.exit(1)
age = (datetime.datetime.now(datetime.timezone.utc) - t).total_seconds()
if not -60 <= age <= 60:
    print("relay.json is %.0f s old" % age); sys.exit(1)
if not r.get("healthy"):
    print("the relay is not healthy (connected %s, box shadow alive %s %s)" % (r.get("connected"), r.get("remoteAlive"), r.get("remoteWhy") or "")); sys.exit(1)
PY
)" || rc=$?
        if [ "$rc" != 0 ]; then
            echo "cutover refused: remote shadow: $why"
            exit 1
        fi
    fi
    [ -x "$BIN" ] || die "$BIN is missing"
    # The live service's configuration, for its compatibility string.
    set -a
    # shellcheck disable=SC1091
    . /etc/fly/fly.env
    set +a
    # The release CUT-01 switches into and the binary it switches to: SERVE-01's service there.
    "$BIN" check --verdict "$SHADOW_DIR/verdict.json" --current /opt/fly/current \
        --binary flysim-session "$@"
}

cmd="${1:-}"
[ $# -gt 0 ] && shift
case "$cmd" in
    start) start "$@" ;;
    stop) stop "$@" ;;
    status) status ;;
    check) check "$@" ;;
    guard) guard ;;
    baseline) [ $# = 1 ] || die "baseline SAMPLES.jsonl"; python3 -c "$GUARD_PY" baseline "$1" ;;
    simulate) [ $# = 2 ] || die "simulate BASELINE.jsonl CHECKS.jsonl"; python3 -c "$GUARD_PY" simulate "$1" "$2" ;;
    *) echo "usage: fly-shadow-run start [--local]|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]|guard|baseline SAMPLES.jsonl|simulate BASELINE.jsonl CHECKS.jsonl" >&2; exit 2 ;;
esac
