#!/bin/bash
# CHECK-q173 -- two instruments advertised a selftest count they no longer printed,
# and the gate leg that grades exactly that was the one every tick skipped.
#
# The defect (Q173, 2026-11-05): `tools/queue_append_audit.py` advertises
# `# 25 cells` on its usage line, and `tools/selftest_baseline.tsv` pins 25 --
# while the selftest prints 43. `1ec068c` ("Q168 land -- the append audit grades
# the pin axis beside the index axis") added the eighteen pin-axis cells and moved
# neither the claim nor the pin. `d3805eb` ("Q171") added the path-str-add leg to
# `tools/verify.py`, moving its printed count 61 -> 67 and its docstring claim with
# it, but not the pin row. Both are graded by `tools/selftest_sweep.py`, whose
# verdict is fatal; every tick since ran `tools/verify.py --fast`, which prints
# that leg as SKIP, so the full gate has been red on two rows nobody read.
#
# Legs
#   claim            each tool's advertised count equals the count it prints --
#                    queue_append_audit's usage line and verify.py's docstring
#   pin              each tool's row in tools/selftest_baseline.tsv equals the
#                    count it prints, name/unit included
#   teeth-append     at 1ec068c the SAME tool prints 43, claims 25 and pins 25:
#                    a RED CONTROL ON REAL HISTORY for both rows at once
#   teeth-gate       at d3805eb verify.py prints 67, claims 67 and pins 61: the
#                    pin alone drifts, so a claim-only guard would pass here
#   sweep            the gate's own selftest-sweep leg reads rc 0 with 0 fatal
#                    and 0 drift over the whole tools/ population
#
# rc 0 every leg as expected | 1 a graded fault | 2 could not grade.
# Run from anywhere; the repo resolves from $0.
set -u

HERE="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
REPO="$(cd "$HERE/../.." && pwd)"
APPEND_REV="1ec068c"
GATE_REV="d3805eb"
APPEND_PY="tools/queue_append_audit.py"
GATE_PY="tools/verify.py"
BASELINE="tools/selftest_baseline.tsv"
legs=0
faults=0

ok()  { legs=$((legs + 1)); printf 'ok    %-15s %s\n' "$1" "$2"; }
bad() { legs=$((legs + 1)); faults=$((faults + 1)); printf 'FAULT %-15s %s\n' "$1" "$2"; }

[ -f "$REPO/$APPEND_PY" ] && [ -f "$REPO/$GATE_PY" ] && [ -f "$REPO/$BASELINE" ] \
  || { echo "cannot grade -- a subject file is missing under $REPO"; exit 2; }
command -v python3 >/dev/null || { echo "cannot grade -- no python3"; exit 2; }
git -C "$REPO" rev-parse --git-dir >/dev/null 2>&1 \
  || { echo "cannot grade -- not a git repository: $REPO"; exit 2; }
for r in "$APPEND_REV" "$GATE_REV"; do
  git -C "$REPO" rev-parse --verify "$r^{commit}" >/dev/null 2>&1 \
    || { echo "cannot grade -- control commit $r absent"; exit 2; }
done

TMP="$(mktemp -d "${TMPDIR:-/tmp}/q173.XXXXXX")" || { echo "cannot grade -- no tmp"; exit 2; }
trap 'rm -rf "$TMP"' EXIT

# printed <tool.py> -> the count on its `selftest: N cells, N passed, N failed` line
printed() {
  python3 "$1" --selftest 2>&1 | grep -o 'selftest: [0-9]* cells' | grep -o '[0-9]*' | head -1
}
# claimed <tool.py> -> the count on its advertised usage line ("... # N cells" or
# "fixture corpus, N cells"); the two tools word it differently and both count.
claimed() {
  grep -o -E '(#|corpus,) [0-9]+ cells' "$1" | grep -o '[0-9]*' | head -1
}
# pinned <name> -> the count in the pin file's row for that tool name
pinned() {
  awk -F'\t' -v n="$1" '$1 == n { print $2 }' "$REPO/$BASELINE"
}

# Each tool's selftest is run ONCE. verify.py's fixture corpus is the slowest
# cell in this file, and running it once per leg would quadruple the guard.
A_PRINTED="$(printed "$REPO/$APPEND_PY")"
G_PRINTED="$(printed "$REPO/$GATE_PY")"
A_CLAIMED="$(claimed "$REPO/$APPEND_PY")"
G_CLAIMED="$(claimed "$REPO/$GATE_PY")"
A_PIN="$(pinned queue_append_audit.py)"
G_PIN="$(pinned verify.py)"

# --- claim: what each tool says about itself is what it prints ---------------
c_bad=""
[ -n "$A_CLAIMED" ] && [ "$A_CLAIMED" = "$A_PRINTED" ] \
  || c_bad="$c_bad queue_append_audit.py:claims=${A_CLAIMED:-none}/prints=${A_PRINTED:-none}"
[ -n "$G_CLAIMED" ] && [ "$G_CLAIMED" = "$G_PRINTED" ] \
  || c_bad="$c_bad verify.py:claims=${G_CLAIMED:-none}/prints=${G_PRINTED:-none}"
if [ -z "$c_bad" ]; then
  ok claim "queue_append_audit=$A_PRINTED  verify=$G_PRINTED  both equal their usage lines"
else
  bad claim "count mismatch:$c_bad"
fi

# --- pin: the number outside the tool agrees with the number inside it ------
p_bad=""
[ -n "$A_PIN" ] && [ "$A_PIN" = "$A_PRINTED" ] \
  || p_bad="$p_bad queue_append_audit.py:pinned=${A_PIN:-none}/prints=${A_PRINTED:-none}"
[ -n "$G_PIN" ] && [ "$G_PIN" = "$G_PRINTED" ] \
  || p_bad="$p_bad verify.py:pinned=${G_PIN:-none}/prints=${G_PRINTED:-none}"
if [ -z "$p_bad" ]; then
  ok pin "baseline agrees: queue_append_audit=$A_PIN  verify=$G_PIN"
else
  bad pin "pin drift:$p_bad"
fi

# --- teeth-append: at 1ec068c the claim AND the pin are the stale pair ------
mkdir -p "$TMP/append" || { echo "cannot grade -- no tmp dir"; exit 2; }
if git -C "$REPO" archive "$APPEND_REV" -- tools | tar -x -C "$TMP/append" 2>/dev/null; then
  say="$(claimed "$TMP/append/$APPEND_PY")"
  got="$(cd "$TMP/append" && python3 "$APPEND_PY" --selftest 2>&1 | grep -o 'selftest: [0-9]* cells' | grep -o '[0-9]*' | head -1)"
  pin="$(awk -F'\t' '$1 == "queue_append_audit.py" { print $2 }' "$TMP/append/$BASELINE")"
  if [ "$say" = "25" ] && [ "$got" = "43" ] && [ "$pin" = "25" ]; then
    ok teeth-append "$APPEND_REV: claims $say, prints $got, pins $pin -- both rows were stale"
  else
    bad teeth-append "$APPEND_REV: claims=${say:-none} prints=${got:-none} pins=${pin:-none} (want 25/43/25)"
  fi
else
  bad teeth-append "cannot export $APPEND_REV"
fi

# --- teeth-gate: at d3805eb only the pin is stale ---------------------------
mkdir -p "$TMP/gate" || { echo "cannot grade -- no tmp dir"; exit 2; }
if git -C "$REPO" archive "$GATE_REV" -- tools | tar -x -C "$TMP/gate" 2>/dev/null; then
  say="$(claimed "$TMP/gate/$GATE_PY")"
  got="$(cd "$TMP/gate" && python3 "$GATE_PY" --selftest 2>&1 | grep -o 'selftest: [0-9]* cells' | grep -o '[0-9]*' | head -1)"
  pin="$(awk -F'\t' '$1 == "verify.py" { print $2 }' "$TMP/gate/$BASELINE")"
  if [ "$say" = "67" ] && [ "$got" = "67" ] && [ "$pin" = "61" ]; then
    ok teeth-gate "$GATE_REV: claims $say, prints $got, pins $pin -- the pin alone drifted"
  else
    bad teeth-gate "$GATE_REV: claims=${say:-none} prints=${got:-none} pins=${pin:-none} (want 67/67/61)"
  fi
else
  bad teeth-gate "cannot export $GATE_REV"
fi

# --- sweep: the leg every tick skipped, run whole ---------------------------
out="$(python3 "$REPO/tools/selftest_sweep.py" --repo "$REPO" 2>&1)"; rc=$?
last="$(printf '%s\n' "$out" | grep -E '^verdict: ' | tail -1)"
if [ $rc -eq 0 ] && printf '%s' "$last" | grep -q '0 fatal'; then
  ok sweep "${last:-rc 0}"
else
  bad sweep "rc=$rc  ${last:-<no verdict line>}"
fi

echo
if [ "$faults" -eq 0 ]; then
  echo "q173: $legs leg(s), 0 fault(s)"
  exit 0
fi
echo "q173: $legs leg(s), $faults fault(s)"
exit 1
