#!/usr/bin/env bash
# tests/test_settle_late_wedge.sh — the upgrade gate must not declare success
# while a container it just recreated goes unhealthy afterwards (#522).
#
# Motivating case, measured converging the fleet onto v0.16.9 on 2026-07-30:
# upgrade.sh printed `upgraded to latest successfully` on node-a and ruoxp and
# settle_healthcheck saw no regression. MINUTES LATER both nodes'
# oxpulse-partner-xray were unhealthy (FailingStreak 10 and 9) with
# `Connection reset by peer` on :3080 — a stale outbound from the compose
# recreate. While wedged, xray kept accepting and forwarding connections, so it
# looked alive from every angle except the end-to-end probe, and the control
# plane had already dropped node-a-seed from the handout pool.
#
# Two load-bearing cases:
#   T5 — the FUNCTIONAL snapshot is clean and the gate must STILL fail because
#        a watched container went unhealthy after it passed.
#   T8 — the watch stays open long enough for that signal to be able to EXIST.
#        Docker writes `unhealthy` only after `retries` consecutive failures
#        following start_period, so a watch shorter than that can never fire
#        and reads as coverage while catching nothing.
#
# Plain bash, no bats (repo convention).
set -euo pipefail
REPO_ROOT="${REPO_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
UPGRADE="$REPO_ROOT/upgrade.sh"
[[ -f "$UPGRADE" ]] || { echo "FAIL: $UPGRADE not found"; exit 1; }
PASS=0
FAIL=0
ok()  { echo "  PASS: $*"; PASS=$((PASS + 1)); }
bad() { echo "  FAIL: $*" >&2; FAIL=$((FAIL + 1)); }
echo "test_settle_late_wedge.sh"
echo

TC=$(mktemp -d)
trap 'rm -rf "$TC"' EXIT

_extract_fn() { awk -v fn="$1" '$0 ~ "^"fn"\\(\\) \\{"{f=1} f{print} /^\}$/ && f{exit}' "$UPGRADE"; }

PRE="$TC/preamble.sh"
{
    echo 'log(){ printf "LOG: %s\n" "$*" >> "'"$TC"'/logs"; }'
    echo 'warn(){ printf "WARN: %s\n" "$*" >> "'"$TC"'/warns"; }'
    echo '_settle_emit_rollback_metric(){ printf "%s\n" "$1" >> "'"$TC"'/metrics"; }'
    _extract_fn settle_healthcheck_with_retry
    _extract_fn _settle_derive_recheck_window
    _extract_fn _settle_docker_health_watch
    _extract_fn _settle_baseline_prebroken
    _extract_fn _settle_docker_baseline_capture
} > "$PRE"

if bash -n "$PRE" 2>/dev/null; then
    ok "T0: settle + late-wedge watch extract and parse together"
else
    bad "T0: preamble parse failed"
fi

# ── docker stub ─────────────────────────────────────────────────────────────
# `docker ps ... --format {{.Names}}`                -> $TC/names
# `docker inspect -f {{.State.Health.Status}} NAME`  -> $TC/health_NAME
# `docker inspect -f {{...Config.Healthcheck...}}`   -> $TC/hcfg_NAME
# An absent file means an absent HEALTHCHECK: the real docker emits a template
# ERROR there, not an empty field, and upgrade.sh discards it to empty.
mkdir -p "$TC/bin"
cat > "$TC/bin/docker" <<STUB
#!/usr/bin/env bash
if [ "\$1" = "ps" ]; then cat "$TC/names" 2>/dev/null; exit 0; fi
if [ "\$1" = "inspect" ]; then
  _n="\${!#}"
  case "\$*" in
    *Config.Healthcheck*) [ -f "$TC/hcfg_\$_n" ]   && cat "$TC/hcfg_\$_n";   exit 0 ;;
    *State.Status*)       [ -f "$TC/state_\$_n" ]  && cat "$TC/state_\$_n";  exit 0 ;;
    *)                    [ -f "$TC/health_\$_n" ] && cat "$TC/health_\$_n"; exit 0 ;;
  esac
fi
exit 0
STUB
chmod +x "$TC/bin/docker"
export PATH="$TC/bin:$PATH"

_reset() { : > "$TC/warns"; : > "$TC/metrics"; : > "$TC/logs"; rm -f "$TC"/health_* "$TC"/hcfg_* "$TC"/state_*; }

# _watch -> echoes rc of _settle_docker_health_watch
_watch() {
    bash -c "source '$PRE'
             export OXPULSE_UPGRADE_SETTLE_RECHECK_SECS='${WINDOW:-2}'
             export OXPULSE_UPGRADE_SETTLE_RECHECK_INTERVAL=1
             _settle_docker_health_watch t; echo rc=\$?" 2>/dev/null | sed -n 's/^rc=//p'
}

# ── T1 — a watched container goes unhealthy -> the watch FAILS ───────────────
_reset
printf 'oxpulse-partner-xray\noxpulse-partner-caddy\n' > "$TC/names"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-xray"
printf 'healthy\n'   > "$TC/health_oxpulse-partner-caddy"
rc=$(_watch)
[[ "$rc" != "0" ]] && ok "T1: unhealthy container -> watch fails (rc=$rc)" \
                   || bad "T1: unhealthy container did NOT fail the watch"

# ── T2 — everything healthy -> passes ───────────────────────────────────────
_reset
printf 'oxpulse-partner-xray\n' > "$TC/names"
printf 'healthy\n' > "$TC/health_oxpulse-partner-xray"
rc=$(_watch)
[[ "$rc" == "0" ]] && ok "T2: all healthy -> watch passes" \
                   || bad "T2: all-healthy wrongly failed (rc=$rc)"

# ── T3 — container declares NO healthcheck -> SKIPPED, never failed ─────────
# This is the objection that kept a docker-health gate off the critical path.
_reset
printf 'oxpulse-partner-awg\n' > "$TC/names"
# no health_ file at all => docker inspect emits nothing
rc=$(_watch)
[[ "$rc" == "0" ]] && ok "T3: container without a HEALTHCHECK is skipped, not failed" \
                   || bad "T3: absent HEALTHCHECK wrongly failed the watch (rc=$rc)"

# ── T4 — window=0 disables the watch ───────────────────────────────────────
_reset
printf 'oxpulse-partner-xray\n' > "$TC/names"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-xray"
rc=$(WINDOW=0 _watch)
[[ "$rc" == "0" ]] && ok "T4: OXPULSE_UPGRADE_SETTLE_RECHECK_SECS=0 disables the watch" \
                   || bad "T4: window=0 did not disable the watch (rc=$rc)"

# ── T5 — THE REGRESSION: functional snapshot CLEAN, container unhealthy ─────
# The exact 2026-07-30 shape. Before this change the gate returned 0 here.
_reset
cat > "$TC/hc" <<'HCSTUB'
#!/bin/sh
[ "$1" = "--snapshot" ] && { cat "$HC_POST"; exit 0; }
exit 1
HCSTUB
chmod +x "$TC/hc"
printf 'check_01=GREEN\ncheck_02=GREEN\n' > "$TC/hc_baseline"
printf 'check_01=GREEN\ncheck_02=GREEN\n' > "$TC/hc_post"
printf 'oxpulse-partner-xray\n' > "$TC/names"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-xray"

rc=$(bash -c "source '$PRE'
    export HEALTHCHECK='$TC/hc'
    export HC_POST='$TC/hc_post'
    export OXPULSE_UPGRADE_HEALTH_TIMEOUT=3
    export OXPULSE_UPGRADE_SETTLE_RECHECK_SECS=2
    export OXPULSE_UPGRADE_SETTLE_RECHECK_INTERVAL=1
    settle_healthcheck_with_retry late-wedge '$TC/hc_baseline' ''; echo rc=\$?" 2>/dev/null \
    | sed -n 's/^rc=//p')
[[ "$rc" != "0" ]] && ok "T5: clean functional snapshot + unhealthy container -> gate FAILS (rc=$rc)" \
                   || bad "T5: gate declared SUCCESS over a late wedge — this is #522 (rc=$rc)"

# T5b asserts the OPERATOR-VISIBLE signal, not the metric. _settle_emit_rollback_metric
# is defined INSIDE settle_healthcheck_with_retry (upgrade.sh:1694), so it shadows any
# top-level stub, and its real body is a no-op unless _reconcile_emit_prom_gauge exists.
# Asserting on it would be testing the stub rather than the code.
if grep -q 'LATE WEDGE' "$TC/warns" 2>/dev/null; then
    ok "T5b: the upgrade log carries a LATE WEDGE warning naming the container"
else
    bad "T5b: no LATE WEDGE warning — an operator would see a silent rollback"
fi

# ── T6 — the declare -F guard keeps the isolation harness behaviour ─────────
# A preamble WITHOUT the helper must still return 0 on a clean snapshot.
PRE2="$TC/preamble_noguard.sh"
{
    echo 'log(){ :; }'
    echo 'warn(){ :; }'
    echo '_settle_emit_rollback_metric(){ :; }'
    _extract_fn settle_healthcheck_with_retry
} > "$PRE2"
rc=$(bash -c "source '$PRE2'
    export HEALTHCHECK='$TC/hc'
    export HC_POST='$TC/hc_post'
    export OXPULSE_UPGRADE_HEALTH_TIMEOUT=3
    settle_healthcheck_with_retry noguard '$TC/hc_baseline' ''; echo rc=\$?" 2>/dev/null \
    | sed -n 's/^rc=//p')
[[ "$rc" == "0" ]] && ok "T6: without the helper the guard is a no-op (isolation harness unchanged)" \
                   || bad "T6: guard changed behaviour when the helper is absent (rc=$rc)"

# ── T7 — the detection budget must outlast TIME-TO-UNHEALTHY (arithmetic) ───
# Measured on node-a 2026-08-07: oxpulse-partner-xray declares
#   start_period=30s  interval=30s  retries=3  timeout=10s
# Docker cannot write `unhealthy` before start_period + retries*interval = 120s.
# A budget shorter than that closes before the signal can exist.
_reset
printf 'oxpulse-partner-xray\n' > "$TC/names"
printf '30 30 10 3\n' > "$TC/hcfg_oxpulse-partner-xray"
w=$(bash -c "source '$PRE'; _settle_derive_recheck_window \"\$(cat '$TC/names')\"" 2>/dev/null)
if [[ "${w:-0}" =~ ^[0-9]+$ ]] && [[ "$w" -ge 130 ]]; then
    ok "T7: budget derived from the container's own healthcheck config (${w}s >= 130s)"
else
    bad "T7: derived budget ${w:-?}s cannot outlast time-to-unhealthy (30+3*30+10=130s) — the watch would close before the signal exists"
fi

# ── T7b — a container with no HEALTHCHECK still yields the floor, not 0 ─────
# An old docker whose inspect template lacks these fields must degrade to the
# previous fixed behaviour, never to a disabled watch.
_reset
printf 'oxpulse-partner-awg\n' > "$TC/names"
w=$(bash -c "source '$PRE'; _settle_derive_recheck_window \"\$(cat '$TC/names')\"" 2>/dev/null)
[[ "${w:-0}" -ge 60 ]] && ok "T7b: no derivable config -> floor (${w}s), watch never silently disabled" \
                       || bad "T7b: undeclared healthcheck collapsed the budget to ${w:-?}s"

# ── T8 — the WATCH uses the derived budget (the call site, not the helper) ──
# Run with the container already unhealthy so the watch returns on the first
# poll and the test does not actually sleep the derived window.
_reset
printf 'oxpulse-partner-xray\n' > "$TC/names"
printf '30 30 10 3\n' > "$TC/hcfg_oxpulse-partner-xray"
printf 'unhealthy\n'  > "$TC/health_oxpulse-partner-xray"
bash -c "source '$PRE'
    unset OXPULSE_UPGRADE_SETTLE_RECHECK_SECS
    export OXPULSE_UPGRADE_SETTLE_RECHECK_INTERVAL=1
    _settle_docker_health_watch t" >/dev/null 2>&1 || true
# First match only, without piping into a truncating reader: under
# `set -o pipefail` such a reader exits early, SIGPIPEs its producer and can
# mask a failure, which the repo's pipefail guard rejects. `q` after the first
# substitution does the same job inside sed.
logged=$(sed -n '/late-wedge watch for/{s/.*late-wedge watch for \([0-9]*\)s.*/\1/p;q;}' "$TC/logs" 2>/dev/null)
if [[ "${logged:-0}" =~ ^[0-9]+$ ]] && [[ "$logged" -ge 130 ]]; then
    ok "T8: the watch opens for the DERIVED budget (${logged}s), not a fixed default"
else
    bad "T8: watch opened for ${logged:-?}s — it is not using the derived budget, so it closes before docker can report unhealthy"
fi

# ── T9 — an explicit override still wins (the escape hatch stays real) ─────
_reset
printf 'oxpulse-partner-xray\n' > "$TC/names"
printf '30 30 10 3\n' > "$TC/hcfg_oxpulse-partner-xray"
printf 'unhealthy\n'  > "$TC/health_oxpulse-partner-xray"
rc=$(WINDOW=7 _watch)
# First match only, without piping into a truncating reader: under
# `set -o pipefail` such a reader exits early, SIGPIPEs its producer and can
# mask a failure, which the repo's pipefail guard rejects. `q` after the first
# substitution does the same job inside sed.
logged=$(sed -n '/late-wedge watch for/{s/.*late-wedge watch for \([0-9]*\)s.*/\1/p;q;}' "$TC/logs" 2>/dev/null)
[[ "$logged" == "7" ]] && ok "T9: OXPULSE_UPGRADE_SETTLE_RECHECK_SECS overrides the derivation (${logged}s)" \
                       || bad "T9: explicit override ignored — logged ${logged:-?}s instead of 7s"

# ── T10..T15 — pre-upgrade BASELINE: only a container that WAS healthy can wedge ─
# 2026-10-12 node-a v0.16.28 -> v0.16.31: oxpulse-partner-hysteria2 was crash-looping
# before the upgrade (never recreated by it); the watch flagged it and rolled back a
# clean upgrade. _watchb runs the watch with a baseline file as the 2nd argument.
_watchb() {
    bash -c "source '$PRE'
             export OXPULSE_UPGRADE_SETTLE_RECHECK_SECS='${WINDOW:-2}'
             export OXPULSE_UPGRADE_SETTLE_RECHECK_INTERVAL=1
             _settle_docker_health_watch t '$1'; echo rc=\$?" 2>/dev/null | sed -n 's/^rc=//p'
}
_mkbase() { { echo '#baseline-v1'; cat; } > "$TC/base"; }

# T10 — baseline-unhealthy/restarting hy2 + healthy core: NO rollback, and it says so.
_reset
printf 'oxpulse-partner-xray\noxpulse-partner-hysteria2\n' > "$TC/names"
printf 'healthy\n'   > "$TC/health_oxpulse-partner-xray"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-hysteria2"
printf 'oxpulse-partner-xray running healthy\noxpulse-partner-hysteria2 restarting unhealthy\n' | _mkbase
rc=$(_watchb "$TC/base")
[[ "$rc" == "0" ]] && ok "T10: container unhealthy in the BASELINE does not fail the watch" \
                   || bad "T10: pre-existing unhealthy hy2 still fails the watch (rc=$rc) - false-positive rollback"
grep -q 'ignores oxpulse-partner-hysteria2' "$TC/warns" \
    && ok "T10b: the ignored container is named in the log (not a silent skip)" \
    || bad "T10b: ignored container not logged"

# T11 — control: the same hy2 failure but healthy in the baseline IS a late wedge.
printf 'oxpulse-partner-xray running healthy\noxpulse-partner-hysteria2 running healthy\n' | _mkbase
rc=$(_watchb "$TC/base")
[[ "$rc" != "0" ]] && ok "T11: a container healthy in the baseline that goes unhealthy still fails (rc=$rc)" \
                   || bad "T11: baseline filtering swallowed a REAL late wedge"

# T12 — a bad hy2 must not mask a real wedge in the core.
_reset
printf 'oxpulse-partner-xray\noxpulse-partner-hysteria2\n' > "$TC/names"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-xray"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-hysteria2"
printf 'oxpulse-partner-xray running healthy\noxpulse-partner-hysteria2 restarting unhealthy\n' | _mkbase
rc=$(_watchb "$TC/base")
[[ "$rc" != "0" ]] && ok "T12: xray wedge still fails while hy2 is ignored (rc=$rc)" \
                   || bad "T12: ignoring hy2 also hid the xray wedge"

# T13 — ABSENT from the baseline (container new in this release) is watched: only names
# PRESENT in the baseline and already broken are ignored. Ignoring absent names would hide
# a real wedge in a container the release added.
_reset
printf 'oxpulse-partner-xray\noxpulse-partner-hysteria2\n' > "$TC/names"
printf 'healthy\n'   > "$TC/health_oxpulse-partner-xray"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-hysteria2"
printf 'oxpulse-partner-xray running healthy 0\n' | _mkbase
rc=$(_watchb "$TC/base")
[[ "$rc" != "0" ]] && ok "T13: container absent from the baseline is WATCHED (rc=$rc)" \
                   || bad "T13: absent-in-baseline container was ignored - a new container's wedge is hidden"

# T13b — header-only baseline (stack down / docker ps -a listed nothing) = no baseline:
# every name is absent, so the watch must stay strict, not become a no-op.
_reset
printf 'oxpulse-partner-xray\n' > "$TC/names"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-xray"
printf '' | _mkbase
rc=$(_watchb "$TC/base")
[[ "$rc" != "0" ]] && ok "T13b: header-only baseline -> strict, wedge still fails (rc=$rc)" \
                   || bad "T13b: header-only baseline turned the watch into a no-op"

# T14 — an unusable baseline (no header = capture failed) degrades to STRICT, never to "ignore all".
_reset
printf 'oxpulse-partner-hysteria2\n' > "$TC/names"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-hysteria2"
: > "$TC/base"
rc=$(_watchb "$TC/base")
[[ "$rc" != "0" ]] && ok "T14: empty/headerless baseline -> strict (watch still fails on unhealthy)" \
                   || bad "T14: failed baseline capture silently disabled the watch"

# T15 — the capture records state+health (restarting hy2 included, no-HEALTHCHECK as none).
_reset
printf 'oxpulse-partner-xray\noxpulse-partner-hysteria2\n' > "$TC/names"
printf 'healthy\n'   > "$TC/health_oxpulse-partner-xray"
printf 'running healthy 0\n' > "$TC/state_oxpulse-partner-xray"
printf 'restarting unhealthy 30439\n' > "$TC/state_oxpulse-partner-hysteria2"
bash -c "source '$PRE'; _settle_docker_baseline_capture '$TC/cap'" >/dev/null 2>&1
if [[ "$(head -n1 "$TC/cap")" == "#baseline-v2" ]] && grep -qx 'oxpulse-partner-hysteria2 restarting unhealthy 30439' "$TC/cap" \
   && grep -qx 'oxpulse-partner-xray running healthy 0' "$TC/cap"; then
    ok "T15: baseline capture records header + name/state/health/restarts per container"
else
    bad "T15: baseline capture malformed: $(tr '\n' '|' < "$TC/cap")"
fi

# T16 — end to end through the gate: clean functional snapshot, hy2 pre-broken, 4th arg threaded.
_reset
printf 'oxpulse-partner-xray\noxpulse-partner-hysteria2\n' > "$TC/names"
printf 'healthy\n'   > "$TC/health_oxpulse-partner-xray"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-hysteria2"
printf 'oxpulse-partner-xray running healthy\noxpulse-partner-hysteria2 restarting unhealthy\n' | _mkbase
rc=$(bash -c "source '$PRE'
    export HEALTHCHECK='$TC/hc' HC_POST='$TC/hc_post'
    export OXPULSE_UPGRADE_HEALTH_TIMEOUT=3 OXPULSE_UPGRADE_SETTLE_RECHECK_SECS=2 OXPULSE_UPGRADE_SETTLE_RECHECK_INTERVAL=1
    settle_healthcheck_with_retry baseline '$TC/hc_baseline' '' '$TC/base'; echo rc=\$?" 2>/dev/null | sed -n 's/^rc=//p')
[[ "$rc" == "0" ]] && ok "T16: gate with a baseline does not roll back on a pre-broken hy2" \
                   || bad "T16: gate rolled back on a pre-broken hy2 (rc=$rc) - baseline not threaded through settle_healthcheck_with_retry"
# T18 - a container still `starting` in the baseline has not been judged yet: it stays accountable.
_reset
printf 'oxpulse-partner-xray\n' > "$TC/names"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-xray"
printf 'oxpulse-partner-xray running starting 0\n' | _mkbase
rc=$(_watchb "$TC/base")
[[ "$rc" != "0" ]] && ok "T18: baseline 'starting' (RestartCount 0) is still watched (rc=$rc)" || bad "T18: a fresh starting container was ignored"

# T19 - FLAPPER: a crash-looper sampled at `running starting` with a high RestartCount
# (node-a hysteria2: 2 of 20 samples, RestartCount 30439) is pre-broken, not "healthy before".
# Mutation: drop the `$3 == "starting" && r < flap` RestartCount clause in
# _settle_baseline_prebroken (upgrade.sh) -> this case goes RED.
_reset
printf 'oxpulse-partner-xray\noxpulse-partner-hysteria2\n' > "$TC/names"
printf 'healthy\n'   > "$TC/health_oxpulse-partner-xray"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-hysteria2"
printf 'oxpulse-partner-xray running healthy 0\noxpulse-partner-hysteria2 running starting 30439\n' | _mkbase
rc=$(_watchb "$TC/base")
[[ "$rc" == "0" ]] && ok "T19: flapper sampled at running+starting with RestartCount 30439 is ignored" \
                   || bad "T19: flapping crash-looper recorded as starting still rolls the upgrade back (rc=$rc)"
# boundary: 2 restarts = fresh (watched), 3 = flapper (ignored)
printf 'oxpulse-partner-hysteria2 running starting 2\n' | _mkbase
bash -c "source '$PRE'; _settle_baseline_prebroken '$TC/base' oxpulse-partner-hysteria2" && r2=0 || r2=1
printf 'oxpulse-partner-hysteria2 running starting 3\n' | _mkbase
bash -c "source '$PRE'; _settle_baseline_prebroken '$TC/base' oxpulse-partner-hysteria2" && r3=0 || r3=1
[[ "$r2" == 1 && "$r3" == 0 ]] && ok "T19b: RestartCount 2 -> watched, 3 -> pre-broken" || bad "T19b: threshold wrong (r2=$r2 r3=$r3)"

# T20 - a v1 baseline (no RESTARTS column) is still read: `restarting unhealthy` ignored,
# `running starting` watched (RESTARTS defaults to 0).
_reset
printf 'oxpulse-partner-xray\noxpulse-partner-hysteria2\n' > "$TC/names"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-xray"
printf 'unhealthy\n' > "$TC/health_oxpulse-partner-hysteria2"
{ echo '#baseline-v1'; printf 'oxpulse-partner-xray running starting\noxpulse-partner-hysteria2 restarting unhealthy\n'; } > "$TC/base"
rc=$(_watchb "$TC/base")
[[ "$rc" != "0" ]] && grep -q 'ignores oxpulse-partner-hysteria2' "$TC/warns" && ! grep -q 'ignores oxpulse-partner-xray' "$TC/warns" \
    && ok "T20: v1 baseline still honoured (hy2 ignored, starting xray watched)" || bad "T20: v1 baseline mishandled (rc=$rc)"

# T21 - an inspect that fails (container vanished between `ps -a` and `inspect`) must leave
# NO line for that name, so the watch keeps it strict. Writing `unknown unknown 0` made it
# pre-broken = silently ignored.
# Mutation: restore `[[ -z "$_line" ]] && _line="unknown unknown 0"` in
# _settle_docker_baseline_capture (upgrade.sh) -> T21 goes RED.
_reset
printf 'oxpulse-partner-xray\noxpulse-partner-gone\n' > "$TC/names"
printf 'running healthy 0\n' > "$TC/state_oxpulse-partner-xray"
bash -c "source '$PRE'; _settle_docker_baseline_capture '$TC/cap'" >/dev/null 2>&1
if grep -qx 'oxpulse-partner-xray running healthy 0' "$TC/cap" && ! grep -q 'oxpulse-partner-gone' "$TC/cap"; then
    ok "T21: failed inspect omits the line (name stays watched)"
else
    bad "T21: failed inspect left a baseline line: $(tr '\n' '|' < "$TC/cap")"
fi
printf 'oxpulse-partner-gone\n' > "$TC/names"; printf 'unhealthy\n' > "$TC/health_oxpulse-partner-gone"
rc=$(_watchb "$TC/cap")
[[ "$rc" != "0" ]] && ok "T21b: container with no baseline line is watched (wedge fails the watch)" || bad "T21b: vanished-at-capture container was ignored"

# T22 - the flapper rule needs RECENT restarts. RestartCount 5, last started 1 h ago =
# stable now -> watched; same count started 20 s ago = live crash-looper -> ignored.
# A line without the AGE column keeps the old count-only rule.
# Mutation: drop `|| !fresh` from _settle_baseline_prebroken (upgrade.sh) -> T22 goes RED.
_pb() { printf 'oxpulse-partner-coturn running starting %s\n' "$1" | _mkbase
        bash -c "source '$PRE'; _settle_baseline_prebroken '$TC/base' oxpulse-partner-coturn" && echo ignored || echo watched; }
[[ "$(_pb '5 3600')" == watched && "$(_pb '5 20')" == ignored && "$(_pb '5')" == ignored && "$(_pb '1 20')" == watched ]] \
    && ok "T22: flapper needs RestartCount>=3 AND a recent start (stable-for-1h watched, 20s ignored, no AGE = legacy)" \
    || bad "T22: recency rule wrong (old=$(_pb '5 3600') new=$(_pb '5 20') legacy=$(_pb '5') few=$(_pb '1 20'))"
# T22b - the capture itself emits AGE from State.StartedAt.
_reset
printf 'oxpulse-partner-coturn\n' > "$TC/names"
printf 'running starting 5 %s\n' "$(date -u -d '2 hours ago' +%FT%T.123456789Z)" > "$TC/state_oxpulse-partner-coturn"
bash -c "source '$PRE'; _settle_docker_baseline_capture '$TC/cap'" >/dev/null 2>&1
age=$(awk '$1=="oxpulse-partner-coturn"{print $5}' "$TC/cap")
[[ "$age" =~ ^[0-9]+$ && "$age" -ge 7190 && "$age" -le 7300 ]] && ok "T22b: capture records AGE seconds from StartedAt (${age}s)" || bad "T22b: AGE column wrong ('$age'): $(tr '\n' '|' < "$TC/cap")"

# T17 - wiring: every settle_healthcheck_with_retry CALL SITE passes a container baseline
# captured before the change (plain, --with-templates, render gate). A site that does not
# silently reverts to the strict watch and re-opens the hy2 false-positive rollback.
sites=$(grep -E '^[[:space:]]*(if !? ?)?settle_healthcheck_with_retry "' "$UPGRADE" | wc -l | tr -d ' ')
with4=$(grep -E 'settle_healthcheck_with_retry "[^"]*" "[^"]*" "[^"]*" "\$_(wt_)?(docker_baseline|dbase)"' "$UPGRADE" | wc -l | tr -d ' ')
caps=$(grep -c '^[[:space:]]*_settle_docker_baseline_capture "' "$UPGRADE" | tr -d ' ')
if [[ "$sites" -ge 3 && "$sites" == "$with4" && "$caps" -ge 3 ]]; then
    ok "T17: all $sites settle call sites carry a container baseline ($caps capture sites)"
else
    bad "T17: settle call sites=$sites, with baseline arg=$with4, capture sites=$caps"
fi

echo
echo "Results: $PASS passed, $FAIL failed"
[[ "$FAIL" -eq 0 ]]
