#!/bin/sh
# 2026-10-30 tool_map drift repair -- CHECK (bounded rebuild).
#
# The first version of this script ran `tools/verify.py` un-flagged, i.e. with
# the selftest-sweep leg, and measured 107.93s wall on a clean tree. Inside the
# caller's harness it was killed just after printing this section's header, so
# the script read as a failure while every graded property in it was green
# (the un-flagged gate, run by hand on the same tree, reads 9/9 and rc 0).
# A CHECK that cannot finish inside its own harness is not a check.
#
# So each leg now has an explicit `timeout`, the sweep is out of the budget
# (it is a wrapper over the same cells this script grades directly -- the
# drift guard IS the selftest cell that caught the stale render), and the
# total is printed. Budget: <45s measured, 60s per leg worst case.
#
# rc 0 = docs/TOOLS.md is the render of this tree at HEAD and in the WORKTREE,
#        tool_map's 20-cell selftest is 20/20, and the repo gate's 8 graded
#        fast legs are green.
# rc 1 = a leg graded red.  rc 2 = the repo does not resolve.  rc 124 = a leg
#        outlived its timeout (a hang is not a pass).
set -u
REPO="$(cd "$(dirname "$0")/../.." 2>/dev/null && pwd)" || exit 2
cd "$REPO" || exit 2
T0=$(date +%s)
OUT="${TMPDIR:-/tmp}/toolsmd-drift.$$"

fail() { tail -16 "$OUT" 2>/dev/null; rm -f "$OUT"; echo "TOOLSMD FAIL: $1" >&2; exit 1; }

echo "== 1. tool_map drift guard (HEAD) =="
timeout 120 python3 tools/tool_map.py --repo . --rev HEAD --check docs/TOOLS.md \
    >"$OUT" 2>&1 || fail "drift guard at HEAD"
[ -s "$OUT" ] && tail -2 "$OUT" || echo "   CURRENT: document matches the render of HEAD"
rm -f "$OUT"

echo "== 2. tool_map drift guard (WORKTREE) =="
timeout 120 python3 tools/tool_map.py --repo . --rev WORKTREE --check docs/TOOLS.md \
    >"$OUT" 2>&1 || fail "drift guard in the WORKTREE"
[ -s "$OUT" ] && tail -2 "$OUT" || echo "   CURRENT: document matches the render of the WORKTREE"
rm -f "$OUT"

echo "== 3. tool_map --selftest (20 cells, incl. the currency cell) =="
timeout 180 python3 tools/tool_map.py --repo . --rev HEAD --selftest >"$OUT" 2>&1 \
    || fail "tool_map selftest graded red"
grep -q "selftest: 20 cells, 20 passed, 0 failed" "$OUT" \
    || fail "selftest did not read 20/20"
grep -qE "^  ok +HEAD: .*the drift guard" "$OUT" \
    || fail "the currency cell is not among the passes"
grep "selftest: " "$OUT"; rm -f "$OUT"

echo "== 4. repo gate, 8 graded fast legs (sweep skipped by design) =="
timeout 180 python3 tools/verify.py --repo . --fast >"$OUT" 2>&1 \
    || fail "a graded gate leg ran red"
grep -q "gate: OK" "$OUT" || fail "gate did not read OK"
grep -q "verify: 9 legs, 8 pass, 0 fault, 0 ungradable, 1 skipped" "$OUT" \
    || fail "leg tally is not 8 pass / 0 fault / 1 known skip"
grep -E "verify: |gate: " "$OUT"; rm -f "$OUT"

echo "TOOLSMD OK: drift 0 at HEAD and WORKTREE; selftest 20/20; gate 8/8 fast legs ($(( $(date +%s) - T0 ))s)"
