#!/bin/bash
#
# rebuild-check.sh — verify a rebuilt brain, and say what was not verified.
#
# WHY THE SECOND HALF EXISTS
# --------------------------
# A script that prints twenty green lines and stops is worse than no script,
# because a clean run reads as "the machine is fine" when it only ever meant
# "these twenty things answered". The gap between those two sentences is where
# a rebuild goes wrong: not in a check that failed, but in a check nobody wrote.
#
# So this writes a RESIDUAL REGISTER — the same move ingest.py makes with
# not-in-corpus.md. Three lists, and the third is the one to read:
#
#   NOT CHECKABLE    no script can establish this. A person must.
#   NOT CHECKED      skippable, and skipped: a prerequisite failed or a
#                    dependency was absent. Silence here is not consent.
#   WEAK             passed, but proves less than it appears to. The most
#                    dangerous category, because it looks like coverage.
#
# Runs at ANY point during a rebuild. Checks whose prerequisites are missing
# report SKIP rather than failing, so it doubles as a progress indicator: run
# it after every step and watch the skips turn into passes.
#
#   ./rebuild-check.sh                 # check and write the register
#   ./rebuild-check.sh --quiet         # register only, no per-check output
#
# No dependencies beyond coreutils and curl. It must run at step 1, before
# Python, the venv or anything else exists.

set -uo pipefail          # deliberately NOT -e: a failed check is data

STATE_DIR="${BT_STATE_DIR:-/mnt/data/brain-test/state}"
REGISTER="$STATE_DIR/rebuild-not-verified.md"
LIBRARY="${BT_LIBRARY:-/mnt/data/Library}"
BRAIN="${BT_BRAIN_DIR:-/home/bart/brain}"
WEB="${BT_WEB_DIR:-/home/bart/brain-web}"
NAS_DATA="/mnt/data_NAS"
QUIET=0
[ "${1:-}" = "--quiet" ] && QUIET=1

PASS=0; FAIL=0; SKIP=0
FAILED_IDS=(); SKIPPED=(); WEAK=(); PASSED_IDS=()

if [ -t 1 ]; then G=$'\033[32m'; R=$'\033[31m'; Y=$'\033[33m'; D=$'\033[2m'; N=$'\033[0m'
else G=""; R=""; Y=""; D=""; N=""; fi

say() { [ "$QUIET" = 0 ] && echo "$@"; return 0; }
head2() { say ""; say "${D}── $* ────────────────────────────────${N}"; }

# check <id> <label> <command...>
check() {
    local id="$1" label="$2"; shift 2
    if "$@" >/dev/null 2>&1; then
        PASS=$((PASS+1)); PASSED_IDS+=("$id"); say "  ${G}pass${N}  $label"
    else
        FAIL=$((FAIL+1)); FAILED_IDS+=("$id — $label")
        say "  ${R}FAIL${N}  $label"
    fi
}

# skip <id> <label> <reason>  — recorded, never silent
skip() {
    SKIP=$((SKIP+1)); SKIPPED+=("$1 — $2 (not checked: $3)")
    say "  ${Y}skip${N}  $2  ${D}($3)${N}"
}

# weak <id> <label> <what it does not prove>
# Only emitted if that check PASSED. A caveat about a check that failed or was
# skipped is noise at best and misleading at worst — it reads as coverage of
# something that was never covered.
weak() { WEAK+=("$1|$2 — $3"); }

# Membership in PASSED, not absence from FAILED. A check inside a block that
# was skipped under a DIFFERENT id never ran at all, so it is neither failed
# nor skipped by name — and an exclusion test lets it through.
weak_applies() {           # $1 = id; true only if that exact check passed
    local id="$1" e
    for e in ${PASSED_IDS+"${PASSED_IDS[@]}"}; do [ "$e" = "$id" ] && return 0; done
    return 1
}

mkdir -p "$STATE_DIR" 2>/dev/null

say ""
say "rebuild-check — $(date '+%Y-%m-%d %H:%M') on $(hostname)"

# ===========================================================================
head2 "1–2  system and volumes"

check OS-1 "Ubuntu 24.04" bash -c "lsb_release -rs | grep -q '^24'"
check FS-1 "/mnt/data is a mount point" mountpoint -q /mnt/data
check FS-2 "/mnt/data survives reboot (in fstab)" grep -qE '^[^#]*[[:space:]]/mnt/data[[:space:]]' /etc/fstab
check SW-1 "swap is active" bash -c "free -b | awk '/Swap:/ {exit (\$2 > 8000000000) ? 0 : 1}'"
check SW-2 "swap survives reboot (in fstab)" grep -q 'swap-tabby' /etc/fstab
weak FS-1 "/mnt/data is mounted" \
     "does not prove it is the right disk, or that it is not an empty new one"

# ===========================================================================
head2 "3  GPU, driver, MOK"

if command -v nvidia-smi >/dev/null 2>&1; then
    check GPU-1 "nvidia-smi sees a GPU" bash -c "nvidia-smi -L | grep -qi 'GPU 0'"
    check GPU-2 "power limit is 280W" bash -c \
        "nvidia-smi -q -d POWER | grep -m1 'Power Limit' | grep -q '280'"
    check GPU-3 "power cap re-applies at boot" systemctl is-enabled -q nvidia-powerlimit
    check GPU-4 "no VRAM already held by a stray process" bash -c \
        "[ \$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits) -lt 2000 ]"
else
    skip GPU-1 "GPU checks" "nvidia-smi not installed — step 3 incomplete"
fi
weak GPU-1 "nvidia-smi answers" \
     "the driver loading is not the model loading; a 26B at 131072 Q4 can still OOM (it has, at 65536)"
weak GPU-1 "MOK is enrolled today" \
     "says nothing about the NEXT kernel update, which is the failure this actually guards"

# ===========================================================================
head2 "4  tailnet"

if command -v tailscale >/dev/null 2>&1; then
    check TS-1 "tailscale is up" bash -c "tailscale status >/dev/null 2>&1"
    check TS-2 "has a tailnet address" bash -c "tailscale ip -4 | grep -q '^100\.'"
    check TS-3 "brain-web is served" bash -c "tailscale serve status 2>/dev/null | grep -q '8765'"
    check TS-4 "brain-test is served" bash -c "tailscale serve status 2>/dev/null | grep -q '8766'"
    # The negative check. Funnel publishes to the open internet; test results
    # and corpus metadata must never leave through a path with no gate.
    check TS-5 "funnel is OFF (nothing is public)" bash -c \
        "! tailscale funnel status 2>/dev/null | grep -qi 'https://'"
else
    skip TS-1 "tailnet checks" "tailscale not installed — step 4 incomplete"
fi

# ===========================================================================
head2 "5  embeddings"

if curl -sf -m 3 http://localhost:11434/api/tags >/dev/null 2>&1; then
    check EMB-1 "ollama is answering" true
    check EMB-2 "bge-m3 is pulled" bash -c \
        "curl -sf -m 5 http://localhost:11434/api/tags | grep -q 'bge-m3'"
    # THE check. Installing ollama and pulling nothing looks identical to a
    # working install from every angle except this one, and cost three weeks.
    check EMB-3 "bge-m3 returns a real 1024-dim vector" bash -c \
        "curl -sf -m 30 http://localhost:11434/api/embeddings \
          -d '{\"model\":\"bge-m3\",\"prompt\":\"verify\"}' \
          | tr ',' '\n' | grep -c '[0-9]' | awk '{exit (\$1 > 1000) ? 0 : 1}'"
else
    skip EMB-1 "embedding checks" "ollama not answering on 11434 — step 5 incomplete"
fi

# ===========================================================================
head2 "6  generation"

TABBY_URL="${BRAIN_GEN_BASE_URL:-http://127.0.0.1:5000/v1}"
if curl -s -m 3 -o /dev/null "$TABBY_URL/models" 2>/dev/null; then
    CODE=$(curl -s -m 5 -o /dev/null -w '%{http_code}' "$TABBY_URL/models")
    # 401 without a key is CORRECT: disable_auth is false and must stay false.
    check GEN-1 "TabbyAPI requires authentication" bash -c "[ '$CODE' = '401' ]"
    if [ -n "${BRAIN_GEN_API_KEY:-}" ]; then
        check GEN-2 "the key in this environment works" bash -c \
            "[ \$(curl -s -m 5 -o /dev/null -w '%{http_code}' \
               -H 'Authorization: Bearer $BRAIN_GEN_API_KEY' '$TABBY_URL/models') = '200' ]"
        check GEN-3 "the served model matches BRAIN_GEN_MODEL" bash -c \
            "curl -sf -m 5 -H 'Authorization: Bearer $BRAIN_GEN_API_KEY' '$TABBY_URL/models' \
             | grep -q \"\${BRAIN_GEN_MODEL:-gemma-4-26B-A4B-it-exl3-4.10bpw}\""
    else
        skip GEN-2 "key and model identity" \
             "BRAIN_GEN_API_KEY unset in this shell — source brainweb.secrets"
    fi
    check GEN-4 "config.yml is not logging prompts" bash -c \
        "! grep -qE '^\s*(log_prompt|log_chat_completion_requests):\s*[Tt]rue' /opt/tabby/app/config.yml"
else
    skip GEN-1 "generation checks" "nothing answering at $TABBY_URL — step 6 incomplete"
fi
weak GEN-3 "/v1/models returns the right id" \
     "the model is loaded; it does not follow that it generates, or at the configured window"

# ===========================================================================
head2 "7  code and environment"

for d in "$BRAIN" "$WEB" "$HOME/signals-agent" "$HOME/brain-test"; do
    check "CODE-$(basename "$d")" "$(basename "$d")/ restored" test -d "$d"
done
check VENV-1 "venv imports its runtime" bash -c \
    "'$BRAIN/venv/bin/python' -c 'import chromadb, ollama, docx, rank_bm25'"
check SEC-1 "brainweb.secrets exists" test -f "$WEB/brainweb.secrets"
check SEC-2 "brainweb.secrets is 600" bash -c \
    "[ \"\$(stat -c %a '$WEB/brainweb.secrets' 2>/dev/null)\" = '600' ]"
check SEC-3 "brainweb.conf carries no populated key" bash -c \
    "! grep -E '^[^#]*(_KEY|_TOKEN|SECRET|PASSWORD)=..' '$WEB/brainweb.conf'"

# ===========================================================================
head2 "8  data — the part that matters"

if [ -d "$LIBRARY" ]; then
    MD=$(find "$LIBRARY" -name '*.md' -not -path '*/.*' 2>/dev/null | wc -l)
    check DATA-1 "Library holds roughly the expected file count ($MD)" \
        bash -c "[ $MD -gt 80 ]"
    check DATA-2 "the sidecar exists and is valid JSON" bash -c \
        "python3 -c \"import json;json.load(open('$LIBRARY/_Brain/classifications.json'))\""
    check DATA-3 "conversation logs restored" bash -c \
        "[ \$(ls /mnt/data/memory/conversations 2>/dev/null | wc -l) -gt 0 ]"
    check DATA-4 "escalation log restored" test -d /mnt/data/memory/escalations
    check DATA-5 "no zero-length markdown (truncated transfer)" bash -c \
        "[ \$(find '$LIBRARY' -name '*.md' -size 0 | wc -l) -eq 0 ]"

    # The strong one: compare against the source, not against an expectation.
    if mountpoint -q "$NAS_DATA" 2>/dev/null; then
        NAS_MD=$(find "$NAS_DATA/Library" -name '*.md' -not -path '*/_versions/*' 2>/dev/null | wc -l)
        check DATA-6 "file count matches the NAS ($MD vs $NAS_MD)" \
            bash -c "[ $MD -eq $NAS_MD ]"
    else
        skip DATA-6 "count against the NAS" "$NAS_DATA not mounted — cannot compare to source"
    fi
else
    skip DATA-1 "all data checks" "$LIBRARY absent — step 8 incomplete"
fi
weak DATA-1 "the file count matches" \
     "counts files, not content. A file can be present, current-looking and half-written"

# ===========================================================================
head2 "9  index"

if [ -d "$BRAIN/chroma" ]; then
    CHUNKS=$("$BRAIN/venv/bin/python" -c "
import chromadb
c=chromadb.PersistentClient(path='$BRAIN/chroma')
print(sum(col.count() for col in c.list_collections()))" 2>/dev/null || echo 0)
    check IDX-1 "chroma holds chunks ($CHUNKS)" bash -c "[ ${CHUNKS:-0} -gt 150 ]"
    check IDX-2 "not-in-corpus.md was written" test -f "$LIBRARY/_Brain/not-in-corpus.md"
else
    skip IDX-1 "index checks" "no chroma directory — step 9 not run"
fi
weak IDX-1 "the chunk count is right" \
     "chunks exist and are countable; nothing here says they are retrievable or correctly ranked"

# ===========================================================================
head2 "10  services"

check SVC-1 "brain-web is running" systemctl is-active -q brain-web
check SVC-2 "brain-web starts at boot" systemctl is-enabled -q brain-web
# The specific historic defect: one EnvironmentFile line instead of two, which
# left BRAIN_GEN_API_KEY unset under systemd while the CLI worked perfectly.
check SVC-3 "brain-web sources BOTH environment files" bash -c \
    "[ \$(systemctl show brain-web -p EnvironmentFiles --value | grep -c 'brainweb') -ge 2 ]"
check SVC-4 "brain-web answers on 8765" bash -c \
    "curl -sf -m 5 -o /dev/null http://127.0.0.1:8765/"
check SVC-5 "brain-test is running" systemctl is-active -q brain-test
check SVC-6 "brain-test answers on 8766" bash -c \
    "curl -sf -m 5 -o /dev/null http://127.0.0.1:8766/api/state"
check SVC-7 "nothing is bound to 0.0.0.0" bash -c \
    "! ss -ltn 2>/dev/null | grep -E '0\.0\.0\.0:(8765|8766)'"

# ===========================================================================
head2 "11  backups — conditional timer model"

if [ "$(id -u)" != "0" ]; then
    skip BK-ROOT "privileged backup checks" "not running as root — re-run with sudo"
else
# --- the programs and their configuration -----------------------------------
check BK-BIN    "brain-backup installed" test -x /usr/local/sbin/brain-backup
check BK-PROMO  "brain-backup-promote installed" test -x /usr/local/sbin/brain-backup-promote
check BK-CONF-D "data.conf exists" test -r /etc/brain-backup/data.conf
check BK-CONF-H "home.conf exists" test -r /etc/brain-backup/home.conf
check BK-CONF-M "confs are 600 (they hold the sentinel tokens)" bash -c \
    "[ \"\$(stat -c %a /etc/brain-backup/data.conf 2>/dev/null)\" = 600 ]"

# If install.sh's sed ever failed, the sentinel is the literal placeholder and
# every share would accept every job. The guard would be present and inert.
check BK-SENT-SET "sentinels were generated, not left as the placeholder" bash -c \
    "! grep -q 'REPLACED_BY_INSTALLER' /etc/brain-backup/*.conf"

check BK-KEEP "KEEP_ROLLING is at least 3" bash -c \
    "[ \"\$(grep -hoP '^KEEP_ROLLING=\\K[0-9]+' /etc/brain-backup/data.conf)\" -ge 3 ]"
check BK-EXCL "home job excludes chroma and venv" bash -c \
    "grep -q 'brain/chroma' /etc/brain-backup/home.conf && \
     grep -q 'brain/venv'  /etc/brain-backup/home.conf"

# --- systemd ----------------------------------------------------------------
check BK-TIMER-E "brain-backup.timer is enabled" systemctl is-enabled -q brain-backup.timer
check BK-TIMER-A "brain-backup.timer is active" systemctl is-active -q brain-backup.timer
check BK-TIMER-M "the timer is monotonic, not calendar-based" bash -c \
    "systemctl cat brain-backup.timer | grep -qE '^On(Boot|UnitInactive)Sec=' && \
     ! systemctl cat brain-backup.timer | grep -qE '^OnCalendar='"
check BK-VERIFY "systemd accepts both units" bash -c \
    "systemd-analyze verify /etc/systemd/system/brain-backup.service \
                            /etc/systemd/system/brain-backup.timer 2>&1 | grep -qv ."

# A oneshot with two bare ExecStart lines STOPS at the first non-zero exit. A
# failing data job then means the home job never runs and writes no event at
# all — indistinguishable, in the log, from a home job that was never due.
check BK-SVC-SEQ "a failing first job cannot suppress the second" bash -c \
    "[ \"\$(systemctl cat brain-backup.service | grep -c '^ExecStart=')\" -eq 1 ]"
check BK-SVC-BOTH "the service still runs both jobs" bash -c \
    "systemctl cat brain-backup.service | grep -E '^ExecStart=' \
     | grep -qE 'brain-backup-all|backup data.*backup home'"

# The old model must not run alongside the new one. Two systems backing up the
# same trees to the same shares is worse than either alone.
check BK-NOCRON "the old cron jobs are gone" bash -c \
    "! crontab -l 2>/dev/null | grep -qE 'backup_(data|bart)_nas\\.sh'"

# --- evidence that it has actually run --------------------------------------
EVLOG=/mnt/data/backup/events.log
check BK-LOG "the event log exists" test -f "$EVLOG"
check BK-LOG-APPEND "the event log is append-only" bash -c \
    "lsattr $EVLOG 2>/dev/null | grep -q 'a'"

for job in data home; do
    ST="/var/lib/brain-backup/${job}.last_success_epoch"
    if [ -s "$ST" ]; then
        AGE=$(( ( $(date +%s) - $(cat "$ST") ) / 3600 ))
        check "BK-FRESH-$job" "$job backed up within 48h (${AGE}h ago)" \
            bash -c "[ $AGE -lt 48 ]"
    else
        skip "BK-FRESH-$job" "$job freshness" "no success stamp — this job has never completed"
    fi
    check "BK-SUCCESS-$job" "$job has a SUCCESS event on record" bash -c \
        "grep -q \"job=$job.*event=SUCCESS\" $EVLOG"
done

# --- THE BASELINE. Without one, the runbook's restore path does not exist. ---
for job in data home; do
    check "BK-BASE-$job" "$job has a promoted baseline" bash -c \
        "grep -q \"job=$job\" /mnt/data/backup/promotions.log 2>/dev/null"
done

# --- can the backup system restore itself? ----------------------------------
# /usr/local/sbin and /etc are in neither SOURCE. Without a copy inside a
# backed-up tree, recovering the backup system depends on an artifact kept
# somewhere this checker cannot see.
check BK-SELF "the kit is inside a backed-up tree" bash -c \
    "[ -f /home/bart/brain-backup-kit/brain-backup ] && \
     [ -f /home/bart/brain-backup-kit/data.conf ]"

# --- share-side checks, only when something is already mounted --------------
for m in /mnt/data_NAS /mnt/bart_NAS; do
    n=$(basename "$m")
    if mountpoint -q "$m" 2>/dev/null; then
        check "BK-CUR-$n" "$n baseline/current is complete" \
            test -f "$m/_brain_backup/baseline/current/.complete"
        check "BK-PART-$n" "$n has no accumulating partials" bash -c \
            "[ \$(find $m/_brain_backup/rolling -maxdepth 1 -name '.partial-*' 2>/dev/null | wc -l) -le 1 ]"
    else
        skip "BK-CUR-$n" "$n share-side checks" \
             "not mounted — normal between runs; mount read-only to check by hand"
    fi
done
fi

weak BK-TIMER-A "the timer is enabled and active" \
     "it fires. Nothing here says a run has ever reached the NAS"
weak BK-SUCCESS-data "a SUCCESS event is on record" \
     "rsync completed and wrote a tree. It does not follow that the tree can be read back"
weak BK-BASE-data "a baseline has been promoted" \
     "records a human act, not a good snapshot. Promoting a corrupt snapshot freezes corruption as the thing you would restore from"
weak BK-SENT-SET "sentinels are generated" \
     "reads the local conf. Whether the share carries the matching value is only proven by a run"

# ===========================================================================
head2 "15  OS rollback (Timeshift)"

if command -v timeshift >/dev/null 2>&1; then
    check TS-INST "timeshift is installed" true
    if [ "$(id -u)" = "0" ]; then
        check TS-MODE "snapshots are in RSYNC mode" bash -c \
            "grep -q '\"btrfs_mode\" : \"false\"' /etc/timeshift/timeshift.json 2>/dev/null"
        check TS-EXCL "/home and /mnt/data are excluded" bash -c \
            "grep -q '/home' /etc/timeshift/timeshift.json && \
             grep -q '/mnt/data' /etc/timeshift/timeshift.json"
        check TS-HAVE "at least one snapshot exists" bash -c \
            "timeshift --list 2>/dev/null | grep -qE '^[0-9]+\\s'"
        check TS-KNOWN "a tagged known-good snapshot exists" bash -c \
            "timeshift --list 2>/dev/null | grep -q 'O'"
    else
        skip TS-MODE "timeshift configuration" "not running as root — re-run with sudo"
    fi
else
    skip TS-INST "OS rollback checks" "timeshift not installed — step 15 incomplete"
fi
weak TS-HAVE "a snapshot exists" \
     "a snapshot is not a restore. Rolling one back from a machine that will not boot needs a live USB and a procedure you have not walked through"

head2 "12  proof of life"

if [ -x "$BRAIN/venv/bin/python" ] && [ -d "$BRAIN/chroma" ]; then
    ANSWER=$(cd "$BRAIN" && timeout 180 ./venv/bin/python ask.py \
             "what did I decide about the escalation gate" 2>/dev/null | head -c 4000)
    check LIFE-1 "ask.py returns a substantial answer" bash -c \
        "[ \${#ANSWER} -gt 200 ]"
    check LIFE-2 "the answer cites a source" bash -c \
        "echo \"\$ANSWER\" | grep -qE '\.(md|docx)'"
else
    skip LIFE-1 "end-to-end question" "venv or index missing — steps 7/9 incomplete"
fi
weak LIFE-1 "ask.py answered and cited a file" \
     "one question. It shows the pipe is connected, not that answers are correct — and a confident wrong answer with a citation attached is the failure mode this system is best at producing"

# ===========================================================================
# THE REGISTER
# ===========================================================================

{
cat <<EOF
---
title: Rebuild verification — what was NOT confirmed
doc_type: status
authority: informative
date: $(date +%F)
---

# Rebuild verification — $(date '+%Y-%m-%d %H:%M')

**$PASS passed · $FAIL failed · $SKIP not checked**

This file exists because the line above is not an answer. It is the count of
questions that were asked. What follows is the questions that were not.

EOF

if [ ${#FAILED_IDS[@]} -gt 0 ]; then
    echo "## Failed"; echo
    printf -- '- %s\n' "${FAILED_IDS[@]}"; echo
fi

if [ ${#SKIPPED[@]} -gt 0 ]; then
    echo "## Not checked in this run"; echo
    echo "A prerequisite was absent. Silence here is not consent — each of these"
    echo "is an open question, not a passing one."; echo
    printf -- '- %s\n' "${SKIPPED[@]}"; echo
fi

cat <<'EOF'
## Passed, but proving less than it appears

The most dangerous list, because every line here reads as coverage.

EOF
SHOWN=0
for w in ${WEAK+"${WEAK[@]}"}; do
    id="${w%%|*}"; text="${w#*|}"
    weak_applies "$id" || continue
    echo "- $text"; SHOWN=$((SHOWN+1))
done
[ "$SHOWN" = 0 ] && echo "_Nothing in this category: no check that carries a caveat passed._"

cat <<'EOF'

## Not checkable by any script

No automation establishes these. A person does, or nobody does.

- **The MOK enrolment survives the next kernel update.** Today's `nvidia-smi`
  says nothing about it. Only the next update does.
- **The backup can be read back.** Every check above reads local state: config
  files, systemd units, success stamps, log lines. None reads a snapshot. A
  SUCCESS event proves rsync finished writing, not that anything can be restored
  from what it wrote. That is `R-restore`, half an hour, and the only test that
  speaks to total loss.
- **The promoted baseline is a good one.** Promotion records that a person
  approved a snapshot. Nothing validated its contents. Promote a corrupt
  snapshot and you have frozen the corruption as the thing you would restore
  from — and frozen it precisely so that nothing automatic can replace it.
- **Hard-linking is actually saving space.** The run-time probe proves the NAS
  accepts `ln`. It does not prove `--link-dest` matched, and a mismatch (usually
  ownership, from a share mounted by hand with different options) makes every
  snapshot a full copy. Visible only as `du` on the mounted share.
- **The NAS's own storage is healthy.** Its replication, its disks and its SMART
  state are outside everything here. Both shares live on one device in one room.
- **The Timeshift rollback works from a machine that will not boot.** Snapshots
  existing is not a restore performed. That needs a live USB and a walkthrough.
- **The restored content is correct, not merely present.** File counts match
  file counts. A truncated file has a full-looking name and a plausible date.
- **The answers are any good.** Nothing here evaluates retrieval quality,
  ranking, or whether the right document came back. That needs the golden set,
  which does not exist yet.
- **The system abstains when it should.** Untested before the rebuild, untested
  after. An untested abstention path plus a strong citation habit produces
  confabulation with sources attached.
- **The escalation gate holds.** Deliberately not exercised. A script that could
  test the send path by running it is the thing the gate denies exists. The
  static checks in brain-test cover the shape; nothing covers the behaviour.
- **The iron rule is intact.** No script knows what should not be here.
- **Sustained thermals and power under real load.** A 30-second check is not an
  hour of generation in a warm room.
- **Whether the runbook was followed or improvised.** Every step you had to work
  around is a defect in the runbook. Only you know which ones those were —
  write them in now, while you still remember.

## Next

1. Record the elapsed rebuild time against the runbook's 4–6 hour estimate.
2. Fix the runbook where you improvised. It is only true on the day it was last
   followed.
3. Attest it:

       cd ~/brain-test
       python runner.py --attest R-runbook "rebuilt <date>, Xh, improvised at N"

4. Then the one this cannot do:

       python runner.py --attest R-restore "..."
EOF
} > "$REGISTER"

say ""
say "${D}────────────────────────────────────────────${N}"
NWEAK=0
for w in ${WEAK+"${WEAK[@]}"}; do weak_applies "${w%%|*}" && NWEAK=$((NWEAK+1)); done
if [ "$FAIL" -eq 0 ]; then
    say "  ${G}$PASS passed${N}, ${Y}$SKIP not checked${N}, $NWEAK passed-but-weak"
else
    say "  ${G}$PASS passed${N}, ${R}$FAIL FAILED${N}, ${Y}$SKIP not checked${N}, $NWEAK passed-but-weak"
fi
say ""
say "  A clean run means these checks answered. It does not mean the machine"
say "  is well. Read what was not covered:"
say ""
say "      $REGISTER"
say ""

exit $(( FAIL > 0 ? 1 : 0 ))
