#!/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
#   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.
#
# 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
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"
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)))
'

start() {
    need_root
    [ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01"
    systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running"
    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"
    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
    systemctl start flyshadow.service
    # flysim starts no trace without a live consumer: wait for the shadow's heartbeat.
    for _ in $(seq 1 60); 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"; }
    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"
    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")"
    [ -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
    [ -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|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]|guard|baseline SAMPLES.jsonl|simulate BASELINE.jsonl CHECKS.jsonl" >&2; exit 2 ;;
esac
