#!/bin/bash
# umwelt-stall-diagnose - capture the state of a stalled umwelt sandbox.
#
# Run this ON THE HOST, from anywhere, while the sandbox is still stuck
# (do NOT restart it first):
#
#     bash umwelt/bin/umwelt-stall-diagnose                 # every sandbox
#     bash umwelt/bin/umwelt-stall-diagnose <workspace>     # this workspace
#     bash umwelt/bin/umwelt-stall-diagnose --in-sandbox    # inside the box
#
# A "stall" is: commands stop coming back and a restart is the only way out.
# Three mechanisms are in play and this script separates them:
#
#   A. CPU starvation - the sandbox is capped at [resources] cpus (2 in the
#      shipped base config). A build, or several parallel podman execs,
#      saturate the cap and starve the shell itself: processes are alive but
#      never scheduled. Look at cpu.stat -> nr_throttled / throttled_usec,
#      and at cpu.pressure.
#   B. OOM kill - the container is capped at [resources] memory (2g) and is
#      subject to the host's own memory pressure. A killed shell shows up in
#      memory.events -> oom_kill, or as a dead/restarting container.
#   C. Watchdog recreate loop - run.py's watchdog polls every 5s and calls
#      recreate() when the container is not running; `podman run` may take
#      up to 300s. A host-side podman that wedges (or a dead container under
#      host pressure) makes recreate retry forever while exec calls queue
#      behind it. run.py does not log this loop - the host log is the only
#      place it shows.
#
# Output: a timestamped directory under $HOME/.local/share/umwelt/diagnostics
# holding one file per probe. Read REPORT.txt first: it is the summary plus
# a one-line verdict for each of the three mechanisms.
#
# This script only reads. It never restarts or mutates anything, and it does
# not need root (except for a `dmesg` probe that degrades to a note).

set -u

# Absolute path to this script, resolved through symlinks. Everything that
# re-invokes the script (the `podman exec --in-sandbox` call) uses this, so
# nothing depends on the caller's cwd.
SELF_PATH="$(
    p=""
    for arg in "${BASH_SOURCE[@]}"; do
        case "$arg" in
            /*) p="$arg" ;;
            *)  p="$(pwd)/$arg" ;;
        esac
    done
    while [ -L "$p" ]; do
        d="$(cd "$(dirname "$p")" && pwd)"
        p="$(readlink "$p")"
        case "$p" in /*) ;; *) p="$d/$p" ;; esac
    done
    d="$(cd "$(dirname "$p")" && pwd)"
    printf '%s/%s' "$d" "$(basename "$p")"
)"

UMWELT_HOME="${UMWELT_AUDIT_HOME:-$HOME/.local/share/umwelt}"
OUT_ROOT="$UMWELT_HOME/diagnostics"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
OUT="$OUT_ROOT/$STAMP"

# The three mechanisms, decided while probing. Populated by the in-sandbox
# half (which is where the cgroup evidence lives) and written into REPORT.txt.
VERDICT_CPU="unknown - no cgroup evidence collected"
VERDICT_OOM="unknown - no cgroup evidence collected"
VERDICT_WATCH="unknown - run on the host to probe podman and the logs"

say()  { printf '%s\n' "$*"; }
note() { printf '%s\n' "$*" >> "$OUT/REPORT.txt"; }
hr()   { printf '%s\n' "----------------------------------------------------------"; }
# For use inside a command substitution: stdout there is a return value, so
# both the console line and the REPORT line must go elsewhere. Writing the
# note line to the file (not stdout) is already safe; the console line must
# go to stderr.
say_err()  { printf '%s\n' "$*" >&2; }
hr_err()   { printf '%s\n' "----------------------------------------------------------" >&2; }

# ---------------------------------------------------------------------------
# Host half
# ---------------------------------------------------------------------------

host_main() {
    local want="${1:-}"

    say "umwelt stall diagnostics: $STAMP"
    if ! mkdir -p "$OUT" 2>/dev/null; then
        say ""
        say "cannot create $OUT"
        say ""
        say "The diagnostics directory is host-side state and is not writable"
        say "from inside a sandbox (read-only rootfs). Run this on the HOST."
        say "To test from inside a sandbox, point it at writable scratch:"
        say "    UMWELT_AUDIT_HOME=/tmp/tools <script>"
        exit 1
    fi
    : > "$OUT/REPORT.txt"

    note "umwelt stall diagnostics"
    note "captured: $STAMP"
    note "host:     $(hostname) / $(uname -sr)"
    note ""

    probe_host_load
    probe_containers "$want"
    probe_control_planes
    probe_host_podman_children
    probe_host_memory
    probe_kernel_log

    # The container's own view is the decisive evidence (cgroup counters).
    # Do it from the host so the user only has to run one thing.
    local running_names
    running_names="$(probe_inside_containers "$want")"

    # One control-plane log per workspace: probe each running sandbox's own
    # log rather than picking one arbitrary file from the runtime dir.
    local n
    while read -r n; do
        [ -z "$n" ] && continue
        probe_log "$(control_plane_log_for "$n")" "$n"
    done <<< "$running_names"
    if [ -z "$running_names" ]; then
        probe_log "" ""
    fi

    write_verdict
    finish
}

# Which sandbox container(s) to probe. Argument: a workspace path, a session
# id, a container name, or empty for all of them. Gateway sidecars are
# excluded: they are umwelt's own plumbing, not the sandbox the agent uses,
# and probing them only adds confusing rows.
target_container_names() {
    local want="${1:-}"
    local all
    all="$(podman ps -a --format '{{.Names}}' 2>/dev/null \
        | grep '^umwelt-' | grep -v '^umwelt-egress-gw-' || true)"
    [ -z "$all" ] && return 0

    # Narrow to the requested workspace/session, if one was given, before
    # inspecting anything.
    if [ -n "$want" ]; then
        local sid="$want"
        [ -d "$want" ] && sid="$(workspace_sid "$want")"
        all="$(printf '%s\n' "$all" | grep -E "$sid" || true)"
        [ -z "$all" ] && return 0
    fi

    # A container that is not Running cannot be exec'd, and attempting it
    # only yields podman's "container state improper" - report its state
    # instead of probing it. `podman ps -a` includes them on purpose: an
    # Exited sandbox is itself a finding.
    #
    # This function runs inside a command substitution, so a shell variable
    # set here is lost with the subshell. Mechanism C's finding is handed
    # back through a file instead.
    local name state
    while read -r name; do
        [ -z "$name" ] && continue
        state="$(podman inspect --format '{{.State.Status}}' "$name" 2>/dev/null)"
        if [ "$state" = "running" ]; then
            printf '%s\n' "$name"
            continue
        fi
        say_err "  (skipping $name: state=${state:-unknown}, not Running)"
        note "SKIPPED $name: state=${state:-unknown} - cannot exec a container"
        note "  that is not Running. An Exited sandbox points at mechanism B"
        note "  (OOM kill) or C (watchdog recreate loop); see"
        note "  host-containers.txt and host-memory-oom.txt."
        case "${state:-}" in
            exited|dead|stopped)
                printf '%s\n' "LIKELY - $name is ${state} (a sandbox that was not recreated)" \
                    >> "$OUT/.verdict-watch" ;;
        esac
    done <<< "$all"
}

workspace_sid() {
    local ws="$1" py
    py="$(command -v python3 || command -v python)"
    [ -z "$py" ] && return 1
    ( cd "$(dirname "$0")/.." 2>/dev/null || exit 1
      PYTHONPATH="umwelt" "$py" - "$ws" <<'PY' 2>/dev/null
import sys
try:
    from client import session_id
    print(session_id(sys.argv[1]))
except Exception:
    pass
PY
    )
}

probe_host_load() {
    say ""; hr; say "HOST: load and CPU"; hr
    {
        echo "== uptime =="; uptime
        echo; echo "== /proc/loadavg =="; cat /proc/loadavg
        echo; echo "== cpu count =="; nproc
        echo; echo "== memory =="; free -h
        echo; echo "== swap pressure =="; grep -E '^(pswpin|pswpout|pgmajfault)' /proc/vmstat
    } > "$OUT/host-load.txt" 2>&1
    sed -n '1,12p' "$OUT/host-load.txt"
    local l1 ncpu
    l1="$(awk '{print $1}' /proc/loadavg)"
    # nproc reflects the calling process's CPU affinity, which is the right
    # denominator only where the capture runs. On the host that is the host's
    # capacity; note which it was so the ratio is not misread.
    ncpu="$(nproc)"
    local where="host"
    [ -r /proc/1/environ ] && grep -qa 'container=' /proc/1/environ 2>/dev/null && where="container"
    note "load(1m)=$l1 over $ncpu visible cpus (captured from: $where)"
    if awk "BEGIN{exit !($l1 > $ncpu)}"; then
        note "  -> load exceeds the visible CPU count: whatever is stalled may"
        note "     simply not be getting scheduled (host contention, mechanism A)."
    fi
}

probe_containers() {
    local want="${1:-}"
    say ""; hr; say "HOST: umwelt containers"; hr
    if ! command -v podman >/dev/null 2>&1; then
        say "podman not found; skipping"
        note "podman: NOT FOUND on this host (cannot inspect containers)"
        return
    fi
    {
        echo "== podman ps -a (umwelt) =="
        podman ps -a --filter name=umwelt --format \
            '{{.Names}}\t{{.Status}}\t{{.CreatedHuman}}\t{{.RunningFor}}' 2>&1
        echo
        echo "== podman events (last 30 min, umwelt) =="
        timeout 15 podman events --since 30m \
            --filter 'event=create' --filter 'event=died' \
            --filter 'event=start' --filter 'event=stop' \
            --filter 'event=remove' --filter 'event=restart' \
            --format '{{.Time}} {{.Type}} {{.Name}} {{.Status}}' 2>&1 | tail -60
    } > "$OUT/host-containers.txt" 2>&1
    sed -n '1,12p' "$OUT/host-containers.txt"
}

probe_control_planes() {
    say ""; hr; say "HOST: control plane processes"; hr
    {
        echo "== run.py processes =="
        # ps is the portable probe; show age and CPU time so a hot loop is
        # visible (a recreate loop burns CPU in repeated podman spawns).
        ps -eo pid,ppid,etimes,stat,pcpu,pmem,rss,args 2>/dev/null \
            | grep -E '[r]un\.py' || echo "(none)"
        echo
        echo "== podman processes =="
        ps -eo pid,ppid,etimes,stat,pcpu,args 2>/dev/null \
            | grep -E '[p]odman' || echo "(none)"
        echo
        echo "== zombie processes (all) =="
        ps -eo pid,ppid,stat,args 2>/dev/null \
            | awk '$3 ~ /^Z/' || true
        echo
        echo "== inotify/fd pressure =="
        cat /proc/sys/fs/file-nr 2>/dev/null
    } > "$OUT/host-processes.txt" 2>&1
    sed -n '1,12p' "$OUT/host-processes.txt"
}

# The recreate loop's signature: a long-lived podman child under run.py whose
# children keep respawning. Count podman spawns over a short window.
probe_host_podman_children() {
    say ""; hr; say "HOST: podman spawn rate (recreate loop detector)"; hr
    {
        echo "Sampling podman pids twice, 6s apart (the watchdog polls at 5s)."
        echo "A growing/cycling set means recreate is being retried in a loop."
        echo
        echo "== t0 =="
        ps -eo pid,ppid,etimes,args 2>/dev/null | grep -E '[p]odman' || echo "(none)"
        sleep 6
        echo
        echo "== t+6s =="
        ps -eo pid,ppid,etimes,args 2>/dev/null | grep -E '[p]odman' || echo "(none)"
    } > "$OUT/host-podman-spawn.txt" 2>&1
    local n
    n="$(grep -c . "$OUT/host-podman-spawn.txt")"
    local pod
    pod="$(ps -eo args 2>/dev/null | grep -cE '[p]odman (run|rm)' || true)"
    note "podman run/rm processes at capture: $pod"
    if [ "${pod:-0}" -gt 1 ]; then
        VERDICT_WATCH="LIKELY - $pod concurrent 'podman run/rm' processes: recreate"
        note "  -> multiple podman run/rm in flight is the recreate-loop signature."
    fi
    say "podman run/rm in flight: $pod  (see host-podman-spawn.txt)"
}

probe_host_memory() {
    say ""; hr; say "HOST: memory pressure and OOM kill"; hr
    {
        echo "== free -h =="; free -h
        echo; echo "== vmstat pressure =="; grep -E '^(pswpin|pswpout)' /proc/vmstat
        echo; echo "== dmesg (OOM / kill) =="
        if command -v dmesg >/dev/null 2>&1; then
            dmesg 2>&1 | grep -iE 'oom|killed process|umwelt' | tail -30 \
                || echo "(no OOM lines, or dmesg unreadable)"
        else
            echo "(dmesg unavailable)"
        fi
        echo; echo "== journalctl (user, umwelt) =="
        if command -v journalctl >/dev/null 2>&1; then
            journalctl --user --since '-60 min' 2>&1 \
                | grep -iE 'umwelt|oom|podman' | tail -50 \
                || echo "(no matching journal lines / no user journal)"
        else
            echo "(journalctl unavailable)"
        fi
    } > "$OUT/host-memory-oom.txt" 2>&1
    sed -n '1,14p' "$OUT/host-memory-oom.txt"
    if grep -qiE 'killed process|oom-kill|oom_kill' "$OUT/host-memory-oom.txt" 2>/dev/null; then
        VERDICT_OOM="LIKELY - the kernel log shows an OOM kill"
    fi
}

probe_kernel_log() {
    # nft drops are logged by the static ruleset; useful context for egress
    # stalls (a proxy-less client hitting the default-drop rules).
    say ""; hr; say "HOST: nft drop log (egress context)"; hr
    {
        if command -v dmesg >/dev/null 2>&1; then
            dmesg 2>&1 | grep -i 'umwelt-tcp-drop' | tail -20 \
                || echo "(no umwelt-tcp-drop lines)"
        fi
    } > "$OUT/host-nft-drops.txt" 2>&1
    say "(see host-nft-drops.txt)"
}

# ---------------------------------------------------------------------------
# In-sandbox half: the decisive cgroup evidence
# ---------------------------------------------------------------------------

# Probes each running sandbox and prints the names it probed, on stdout, for
# the caller to reuse (the per-workspace log lookup). Every human-readable
# line therefore goes to stderr: stdout here is a return value, and writing
# console text to it previously leaked into the container list.
probe_inside_containers() {
    local want="${1:-}"
    local names
    names="$(target_container_names "$want")"
    if [ -z "$names" ]; then
        say_err ""; say_err "no umwelt container found; skipping in-sandbox probes"
        note "containers: none found (sandbox may already be gone)"
        return
    fi
    local n
    while read -r n; do
        [ -z "$n" ] && continue
        say_err ""; hr_err; say_err "SANDBOX: $n"; hr_err
        # Self path: absolute, from BASH_SOURCE, so it is correct no matter
        # what the caller's cwd is. A relative path here silently became
        # "<cwd>/umwelt-stall-diagnose" and every probe failed rc=1.
        local self="$SELF_PATH"
        if [ ! -f "$self" ]; then
            say_err "!! cannot locate this script ($self); skipping"
            note "in-sandbox probe: script not found at $self"
            continue
        fi
        # Bound it hard: if the container is stalled, podman exec itself may
        # hang. A timeout here is itself evidence (mechanism A or C).
        local rc=0
        timeout 25 podman exec -i "$n" bash -s -- "$STAMP" \
            < "$self" --in-sandbox \
            > "$OUT/inside-$n.txt" 2>&1 || rc=$?
        case "$rc" in
            0)   say_err "in-sandbox probe completed"
                 absorb_inside "$n" ;;
            124) say_err "!! in-sandbox probe TIMED OUT after 25s"
                 note "PROBE $n: podman exec accepted but the probe did not"
                 note "  complete in 25s - processes alive, not progressing."
                 VERDICT_CPU="LIKELY - podman exec accepted but made no progress in 25s: CPU starvation (A)" ;;
            # podman's exit codes here are not the shell convention:
            # an Exited/Paused container gives 255 with "container state
            # improper" on stderr, not 125. Match the message as well as the
            # code so the classification does not depend on guessing podman's
            # numbering.
            125|255) say_err "!! podman refused the exec (rc=$rc): container not Running"
                 note "PROBE $n: podman refused the exec (rc=$rc): the container"
                 note "  is Exited or Paused. This is NOT a CPU stall."
                 note "  A container that is Exited points at mechanism B (OOM"
                 note "  kill) or C (watchdog recreate loop); read"
                 note "  host-containers.txt and host-memory-oom.txt."
                 VERDICT_WATCH="LIKELY - $n is not Running (podman refused exec, rc=$rc)" ;;
            126|127) say_err "!! podman exec ran but the probe could not start (rc=$rc)"
                 note "PROBE $n: podman exec reached the container but bash/script"
                 note "  setup failed (rc=$rc) - a probe problem, NOT sandbox"
                 note "  evidence. Read inside-$n.txt and fix before trusting"
                 note "  anything else here."
                 VERDICT_CPU="unknown - probe could not start inside the container (rc=$rc)" ;;
            *)   say_err "!! in-sandbox probe failed (rc=$rc)"
                 note "PROBE $n: podman exec FAILED (rc=$rc). Read"
                 note "  inside-$n.txt first: this may be a probe error rather"
                 note "  than sandbox state. Mechanisms A/B/C remain otherwise."
                 ;;
        esac
        printf '%s\n' "$n"
    done <<< "$names"
}

# Pull the verdict lines the in-sandbox half appended into its own output.
absorb_inside() {
    local n="$1"
    local v
    v="$(grep '^VERDICT-CPU: ' "$OUT/inside-$n.txt" | head -1 | sed 's/^VERDICT-CPU: //')"
    [ -n "$v" ] && { VERDICT_CPU="$v"; note "cpu:     $v"; }
    v="$(grep '^VERDICT-OOM: ' "$OUT/inside-$n.txt" | head -1 | sed 's/^VERDICT-OOM: //')"
    [ -n "$v" ] && { VERDICT_OOM="$v"; note "memory:  $v"; }
}

insandbox_main() {
    say "== identity =="
    id; echo "cgroup: $(cat /proc/self/cgroup)"
    echo "uptime: $(cat /proc/uptime)"
    echo
    local SL
    SL="$(sed 's/^0:://' /proc/self/cgroup)"
    local CG="/sys/fs/cgroup$SL"
    # In this container /proc/self/cgroup is "/" and the delegated limits are
    # at the cgroup root; fall back to /sys/fs/cgroup directly.
    [ -d "$CG" ] || CG="/sys/fs/cgroup"

    say "== cgroup: $CG =="
    for f in memory.max memory.current memory.peak memory.pressure \
             memory.events cpu.max cpu.stat cpu.pressure \
             pids.max pids.current; do
        if [ -r "$CG/$f" ]; then
            echo "--- $f ---"
            cat "$CG/$f"
        fi
    done
    echo

    # -- mechanism A: CPU starvation --------------------------------------
    local throttled="" nr_throttled="" cpu_full=""
    if [ -r "$CG/cpu.stat" ]; then
        nr_throttled="$(awk '/^nr_throttled/{print $2}' "$CG/cpu.stat")"
        throttled="$(awk '/^throttled_usec/{print $2}' "$CG/cpu.stat")"
    fi
    if [ -r "$CG/cpu.pressure" ]; then
        cpu_full="$(awk '/^full/{for(i=1;i<=NF;i++) if($i ~ /^avg10=/){sub("avg10=","",$i); print $i}}' \
            "$CG/cpu.pressure")"
    fi
    local cpu_max; cpu_max="$(cat "$CG/cpu.max" 2>/dev/null)"
    echo "cpu.max=$cpu_max nr_throttled=${nr_throttled:-?} throttled_usec=${throttled:-?}"

    # -- mechanism B: OOM --------------------------------------------------
    local oom=""
    [ -r "$CG/memory.events" ] && oom="$(awk '/^oom_kill/{print $2}' "$CG/memory.events")"
    local pids_max=""
    [ -r "$CG/pids.max" ] && pids_max="$(cat "$CG/pids.max")"
    echo "oom_kill=${oom:-?} pids.max=${pids_max:-?}"

    # -- what the processes are actually doing ------------------------------
    say ""
    say "== processes (state + wchan) =="
    ps -eo pid,ppid,stat,etimes,pcpu,wchan:24,comm 2>/dev/null || ps -ef
    say ""
    say "== process count =="
    ps -e --no-headers 2>/dev/null | wc -l
    say ""
    say "== load =="
    cat /proc/loadavg
    say ""
    say "== top CPU consumers (snapshot) =="
    ps -eo pid,pcpu,pmem,etimes,args --sort=-pcpu 2>/dev/null | head -15
    say ""
    say "== /proc/*/status State tally =="
    for s in /proc/[0-9]*/stat; do
        awk '{print $3}' "$s" 2>/dev/null
    done | sort | uniq -c | sort -rn
    say ""
    say "== D-state (uninterruptible) processes =="
    for s in /proc/[0-9]*/stat; do
        if [ "$(awk '{print $3}' "$s" 2>/dev/null)" = "D" ]; then
            awk '{print "pid="$1" comm="$2}' "$s" 2>/dev/null
        fi
    done
    say ""
    say "== mount/fd pressure =="
    df -h 2>/dev/null | head -20
    say ""

    # -- mechanism C hints from inside --------------------------------------
    say "== recent /tmp (recreate wipes it; freshness implies a recreate) =="
    ls -la --time-style=full-iso /tmp 2>/dev/null | head -20

    # -- verdicts ----------------------------------------------------------
    # A container that gets *any* CPU still reports small avg10 values, and
    # nr_throttled is a cumulative counter that never decays - so neither is
    # a stall test on its own. The settled state is the period ratio and the
    # pressure averages; the probe-time delta is what tells them apart.
    local nr_periods="" cpu_usage="" throttle_ratio="" verdict_cpu=""
    if [ -r "$CG/cpu.stat" ]; then
        nr_periods="$(awk '/^nr_periods/{print $2}' "$CG/cpu.stat")"
        cpu_usage="$(awk '/^usage_usec/{print $2}' "$CG/cpu.stat")"
    fi
    if [ -n "${nr_throttled:-}" ] && [ -n "${nr_periods:-}" ] \
       && [ "${nr_periods:-0}" -gt 0 ] 2>/dev/null; then
        throttle_ratio="$(awk -v t="$nr_throttled" -v p="$nr_periods" \
            'BEGIN{printf "%.1f%%", 100*t/p}')"
    fi
    echo "throttle ratio: ${throttle_ratio:-?} (nr_throttled/nr_periods over the container's whole life)"

    # Thresholds: avg10 >= 50% means runnable work spent half of the last 10s
    # waiting for CPU - that is starvation. 10-50% is heavy contention, which
    # slows everything down without a hard stall.
    local pf_num
    pf_num="$(awk -v v="${cpu_full:-0}" 'BEGIN{print (v+0)}' 2>/dev/null)"
    if awk "BEGIN{exit !($pf_num >= 50)}" 2>/dev/null; then
        verdict_cpu="LIKELY - cpu.pressure full avg10=$cpu_full: runnable work waits on CPU more than half the time"
    elif awk "BEGIN{exit !($pf_num >= 10)}" 2>/dev/null; then
        verdict_cpu="PARTIAL - cpu.pressure full avg10=$cpu_full: heavy CPU contention, not a hard stall on its own"
    elif [ -n "$throttle_ratio" ] && awk "BEGIN{exit !(${throttle_ratio%\%} >= 50)}" 2>/dev/null; then
        verdict_cpu="PARTIAL - throttled in ${throttle_ratio} of all periods (lifetime average; check the probe-time delta below)"
    else
        verdict_cpu="not indicated - cpu.pressure full avg10=${cpu_full:-0}, throttled ${throttle_ratio:-0} of periods"
    fi
    echo "VERDICT-CPU: $verdict_cpu"

    if [ -n "${oom:-}" ] && [ "${oom:-0}" -gt 0 ] 2>/dev/null; then
        echo "VERDICT-OOM: LIKELY - cgroup memory.events oom_kill=$oom"
    else
        echo "VERDICT-OOM: not indicated by this cgroup (oom_kill=${oom:-unreadable})"
    fi

    # -- probe-time delta: the only measurement that can see a stall that is
    #    happening *now*. Counters above are lifetime averages; if the sandbox
    #    was healthy for an hour and stalled for one minute, they barely move.
    #    5s is the floor for a meaningful signal: idle noise alone produces
    #    tens of usec of pressure, and the watchdog's own poll is 5s.
    local WINDOW=5
    say ""
    say "== probe-time sample (${WINDOW}s) =="
    local t0_periods t0_throttled t0_usage t0_some t0_pids
    t0_periods="$nr_periods"; t0_throttled="$nr_throttled"
    t0_usage="$cpu_usage"
    t0_some="$(awk '/^some/{for(i=1;i<=NF;i++) if($i ~ /^total=/){sub("total=","",$i); print $i}}' \
        "$CG/cpu.pressure" 2>/dev/null)"
    t0_pids="$(cat "$CG/pids.current" 2>/dev/null)"
    sleep "$WINDOW"
    local t1_periods t1_throttled t1_usage t1_some t1_pids
    t1_periods="$(awk '/^nr_periods/{print $2}' "$CG/cpu.stat" 2>/dev/null)"
    t1_throttled="$(awk '/^nr_throttled/{print $2}' "$CG/cpu.stat" 2>/dev/null)"
    t1_usage="$(awk '/^usage_usec/{print $2}' "$CG/cpu.stat" 2>/dev/null)"
    t1_some="$(awk '/^some/{for(i=1;i<=NF;i++) if($i ~ /^total=/){sub("total=","",$i); print $i}}' \
        "$CG/cpu.pressure" 2>/dev/null)"
    t1_pids="$(cat "$CG/pids.current" 2>/dev/null)"
    echo "nr_periods     ${t0_periods:-?} -> ${t1_periods:-?}"
    echo "nr_throttled   ${t0_throttled:-?} -> ${t1_throttled:-?}"
    echo "usage_usec     ${t0_usage:-?} -> ${t1_usage:-?}"
    echo "pressure some  ${t0_some:-?} -> ${t1_some:-?} (total usec)"
    echo "pids.current   ${t0_pids:-?} -> ${t1_pids:-?}"
    local d_thr d_use d_prs
    d_thr=$(( ${t1_throttled:-0} - ${t0_throttled:-0} ))
    d_use=$(( ${t1_usage:-0} - ${t0_usage:-0} ))
    d_prs=$(( ${t1_some:-0} - ${t0_some:-0} ))
    echo "delta: throttled=$d_thr usage_usec=$d_use pressure_some_usec=$d_prs"
    # A healthy idle sandbox still accrues tens of usec of pressure from the
    # watchdog's own sleep/wake. Only a delta that is large in absolute terms
    # AND large relative to the CPU actually consumed means starvation; a
    # delta near zero with low usage is simply an idle container.
    if [ "$d_thr" -ge 5 ] 2>/dev/null; then
        echo "VERDICT-CPU-NOW: LIKELY - throttled $d_thr times during the ${WINDOW}s probe: CPU starvation is happening right now"
    elif [ "$d_prs" -ge 100000 ] 2>/dev/null && [ "$d_use" -lt 200000 ] 2>/dev/null; then
        echo "VERDICT-CPU-NOW: LIKELY - runnable work waited ${d_prs}us while consuming almost no CPU (${d_use}us): starved, not busy"
    elif [ "$d_use" -lt 100000 ] 2>/dev/null && [ "$d_prs" -lt 10000 ] 2>/dev/null; then
        echo "VERDICT-CPU-NOW: not indicated - the container is effectively idle (${d_use}us CPU, ${d_prs}us pressure in ${WINDOW}s). If the agent is stuck, it is NOT a CPU stall."
    elif [ "$d_prs" -ge 100000 ] 2>/dev/null; then
        echo "VERDICT-CPU-NOW: LIKELY - pressure ${d_prs}us in ${WINDOW}s while consuming CPU: contended and busy"
    else
        echo "VERDICT-CPU-NOW: inconclusive - CPU ${d_use}us / pressure ${d_prs}us in ${WINDOW}s (below the starvation threshold)"
    fi
    if [ -n "${t1_pids:-}" ] && [ "${t1_pids:-0}" -ge 400 ] 2>/dev/null; then
        echo "VERDICT-PIDS: LIKELY - pids.current=$t1_pids of pids.max=${pids_max:-?}: process spawns are hitting the cap"
    fi
}

# ---------------------------------------------------------------------------
# Log + report
# ---------------------------------------------------------------------------

# The control-plane log for a container. The name is the session id
# (umwelt-<sid>), and mcp_server redirects run.py's output to
# "<socket>.log" = $XDG_RUNTIME_DIR/umwelt-<sid>.sock.log. Derived from the
# container name, deliberately: picking the newest *.sock.log in the runtime
# dir silently reads an unrelated (often stale) workspace's log, and an empty
# watchdog section then looks exactly like a healthy system.
control_plane_log_for() {
    local name="$1"
    [ -z "$name" ] && return 1
    local rt="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
    local sid="${name#umwelt-}"
    local c
    for c in "$rt/$name.sock.log" "$rt/umwelt-$sid.sock.log"; do
        [ -f "$c" ] && { echo "$c"; return 0; }
    done
    # Hand-started run.py with no session socket: fall back to the state dir.
    for c in "$UMWELT_HOME"/run.log "$UMWELT_HOME"/*.log; do
        [ -f "$c" ] && { echo "$c"; return 0; }
    done
    return 1
}

probe_log() {
    local log="${1:-}" name="${2:-}"
    say ""; hr; say "control plane log${name:+ for $name}"; hr
    if [ -z "$log" ] || [ ! -f "$log" ]; then
        say "no control-plane log found${name:+ for $name}."
        say "(expected \$XDG_RUNTIME_DIR/umwelt-<sid>.sock.log)"
        note ""
        note "LOG${name:+ $name}: none found. The MCP server redirects run.py's"
        note "  output to <socket>.log; if that is missing, the control plane"
        note "  was started some other way (or the sandbox is not this host's)."
        return
    fi
    local out="$OUT/control-plane-log${name:+-$name}.txt"
    say "log: $log"
    local wd
    # `grep -c` exits 1 when it matched nothing, so `|| echo 0` would append a
    # second 0 and the numeric test below would fail. Take the count from
    # wc -l instead, which always exits 0.
    wd="$(grep -c 'watchdog:' "$log" 2>/dev/null)" || true
    wd="${wd:-0}"
    say "watchdog lines: $wd"
    {
        echo "log: $log"
        echo "== tail =="; tail -200 "$log"
        echo; echo "== watchdog lines ($wd) =="
        grep -n 'watchdog:' "$log" | tail -100
        echo; echo "== other errors =="
        grep -inE 'Traceback|podman run failed|is not running|recreate' "$log" \
            | grep -v 'watchdog:' | tail -40
    } > "$out" 2>&1
    if [ "${wd:-0}" -eq 0 ]; then
        note "LOG${name:+ $name}: 0 watchdog lines in $log."
        note "  A healthy sandbox that has not had a container death writes"
        note "  one 'watchdog: started' line per control-plane start. Zero"
        note "  lines means either no recreate ever happened, or this log is"
        note "  from a control plane old enough to predate watchdog logging."
    fi
}

write_verdict() {
    # Fold in findings that were produced inside a command substitution
    # (which cannot set a variable in this shell).
    if [ -s "$OUT/.verdict-watch" ]; then
        VERDICT_WATCH="$(head -1 "$OUT/.verdict-watch")"
    fi
    {
        note ""
        note "=========================================================="
        note "PER-CONTAINER PROBES (what each sandbox reported)"
        note "=========================================================="
        note ""
        note "Each container's own cpu.stat / cpu.pressure / memory.events"
        note "verdict is recorded above with a 'PROBE <name>:' prefix, and its"
        note "full capture is in inside-<name>.txt. A container that was not"
        note "Running is reported there, not here."
        note ""
        note "=========================================================="
        note "MECHANISM SUMMARY (A/B/C)"
        note "=========================================================="
        note ""
        note "A. CPU starvation ... $VERDICT_CPU"
        note "B. OOM kill .......... $VERDICT_OOM"
        note "C. recreate loop ..... $VERDICT_WATCH"
        note ""
        note "These are heuristics over the captured evidence, not proof. The"
        note "files under $OUT hold the raw state; read them before acting."
        note ""
        note "If all three read 'not indicated' while the sandbox was stuck,"
        note "the stall is NOT one of these three: look at host-load.txt for"
        note "host contention, and at the audit-*.jsonl timeline for the last"
        note "control-plane operation before the silence began."
    } >> "$OUT/REPORT.txt"
}

finish() {
    # audit log timeline, if present (cheap and often revealing: audit lines
    # stop exactly where the stall began)
    if [ -d "$UMWELT_HOME" ]; then
        for f in "$UMWELT_HOME"/audit-*.jsonl; do
            [ -f "$f" ] || continue
            {
                echo "== $f (last 30) =="
                tail -30 "$f"
            } > "$OUT/audit-$(basename "$f").txt" 2>&1
        done
    fi

    say ""; hr
    say "ARTIFACTS: $OUT"
    ls -1 "$OUT"
    hr
    say ""
    cat "$OUT/REPORT.txt"
    say ""
    say "Next: read REPORT.txt and the raw files beside it. Do NOT restart the"
    say "sandbox before this script finishes - the cgroup counters reset when"
    say "the container is recreated and the evidence is gone."
}

# ---------------------------------------------------------------------------
# Dispatch
#
# The in-sandbox invocation is `bash -s -- <stamp> --in-sandbox < script`, so
# the mode flag is a *later* positional - scanning "$@" rather than reading
# "$1" is what makes it work. Reading "$1" here silently ran the host half
# inside the container (mkdir on a read-only path) and reported the failure
# as sandbox evidence.
# ---------------------------------------------------------------------------

MODE="host"
ARGS=()
for arg in "$@"; do
    case "$arg" in
        --in-sandbox) MODE="sandbox" ;;
        -h|--help)    MODE="help" ;;
        -*)           say "unknown option: $arg"; exit 2 ;;
        *)            ARGS+=("$arg") ;;
    esac
done

case "$MODE" in
    sandbox) insandbox_main ;;
    help)    sed -n '2,32p' "$SELF_PATH" | sed 's/^# \{0,1\}//' ;;
    *)       host_main "${ARGS[0]:-}" ;;
esac
