#!/bin/bash
# CHECK-q174 -- two CHECK entry points answered "could not grade" (rc 2) for
# reasons no leg of any gate read, and 37 entry points stood outside the
# baseline behind them.
#
# The defect (Q174, 2026-11-06):
#   (a) `wizard-work/ledger/CHECK-troupe-gitfile-loc-census` is a Python script
#       whose first line opens a docstring and whose mode is 644. It carries no
#       shebang and no `.py` suffix, so the sweep's own dispatcher
#       (`check_sweep.interpreter`) falls through to `bash`, and bash dies on
#       line 15 (`def main():`). rc 2 == "could not grade" -- which is not the
#       same thing as "graded it and disagreed", and the archive's whole exit
#       contract turns on that difference.
#   (b) `wizard-work/sol/CHECK-untracked-classify-2026-11-03` cd's to its own
#       directory and then computes its repo root as ONE level up, so it runs
#       `python3 wizard-work/wizard-work/sol/verify_untracked_classify_2026_11_03.py`
#       -- a path that does not exist. rc 2 again, on a script whose comment
#       says "the repo root is two levels up".
#   (c) `check_sweep.py --paths` read 37 NEW rows (195 entry points, 158 named)
#       at c95a339. That leg is not a leg of `tools/verify.py`, so a baseline
#       that names two thirds of the tree was never graded by the gate every
#       tick runs.
#
# Legs
#   paths      the entry-point set is fully named: entry points == baseline rows,
#              0 faults, rc 0 -- the reading this tick signed 37 rows to reach
#   dispatch   no entry point whose first line opens a Python docstring is
#              dispatched to bash (class (a), measured over all 195)
#   runs       both repaired entry points, run through the lane's OWN run_entry,
#              answer a graded verdict (rc 0/1) and never rc 2/124/125
#   teeth      at the control rev c95a339 the same two subjects carry the defect:
#              one first line opens a docstring with no shebang, one computes its
#              root with a single `cd ..` -- a red control on real history
#
# 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)"
SWEEP="wizard-work/volt/q143-check-sweep/check_sweep.py"
BASELINE="wizard-work/volt/q143-check-sweep/check_entry_baseline.tsv"
DISPATCHED="wizard-work/ledger/CHECK-troupe-gitfile-loc-census"
SHORTCD="wizard-work/sol/CHECK-untracked-classify-2026-11-03"
CONTROL_REV="c95a339"
legs=0
faults=0

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

for f in "$SWEEP" "$BASELINE" "$DISPATCHED" "$SHORTCD"; do
  [ -f "$REPO/$f" ] || { echo "cannot grade -- missing $f under $REPO"; exit 2; }
done
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; }
git -C "$REPO" rev-parse --verify "$CONTROL_REV^{commit}" >/dev/null 2>&1 \
  || { echo "cannot grade -- control rev $CONTROL_REV absent"; exit 2; }

# --- paths: every entry point in the tree is named in the baseline -----------
out="$(python3 "$REPO/$SWEEP" --repo "$REPO" --paths 2>&1)"; rc=$?
last="$(printf '%s\n' "$out" | grep -E '^paths: ' | tail -1)"
entry="$(printf '%s' "$last" | sed -n 's/^paths: \([0-9]*\) entry point.*/\1/p')"
named="$(printf '%s' "$last" | sed -n 's/.*, \([0-9]*\) baseline path.*/\1/p')"
if [ "$rc" -eq 0 ] && [ -n "$entry" ] && [ "$entry" = "$named" ] \
   && printf '%s' "$last" | grep -q ' 0 fault(s)$'; then
  ok paths "${last:-rc 0}"
else
  bad paths "rc=$rc  ${last:-<no paths line>}"
fi

# --- dispatch: python bytes whose first line opens a docstring go to python ---
res="$(python3 - "$REPO" "$SWEEP" <<'PY'
import os, sys
repo, sweep = sys.argv[1], sys.argv[2]
sys.path.insert(0, os.path.join(repo, os.path.dirname(sweep)))
import check_sweep
Q = ('"' * 3, "'" * 3)
bad, total = [], 0
for rel in check_sweep.entry_points(repo):
    total += 1
    full = os.path.join(repo, rel)
    try:
        with open(full, encoding="utf-8", errors="replace") as fh:
            first = fh.readline()
    except OSError:
        continue
    base = os.path.basename(check_sweep.interpreter(full)[0])
    if base == "bash" and any(first.startswith(q) for q in Q):
        bad.append(rel)
print("%d %d %s" % (total, len(bad), ",".join(bad) if bad else "-"))
PY
)"; drc=$?
set -- $res
if [ "$drc" -eq 0 ] && [ "${2:-x}" = "0" ]; then
  ok dispatch "${1:-?} entry point(s), 0 dispatched to bash with a docstring first line"
else
  bad dispatch "rc=$drc  ${2:-?} misdispatch(es): ${3:-<none printed>}"
fi

# --- runs: the two repaired subjects grade, rather than refuse ---------------
res="$(python3 - "$REPO" "$SWEEP" "$DISPATCHED" "$SHORTCD" <<'PY'
import os, sys
repo, sweep = sys.argv[1], sys.argv[2]
subjects = sys.argv[3:]
sys.path.insert(0, os.path.join(repo, os.path.dirname(sweep)))
import check_sweep
bad = []
for rel in subjects:
    rc, note = check_sweep.run_entry(repo, rel, 120)
    cls = check_sweep.classify(rc)
    print("  %-62s rc=%-3d %s" % (rel[-62:], rc, cls), file=sys.stderr)
    if rc not in (0, 1):
        bad.append((rel, rc))
sys.stderr.flush()
print("%d %s" % (len(bad), ",".join(r for r, _ in bad) if bad else "-"))
PY
)" 2>/dev/null; rrc=$?
set -- $res
if [ "$rrc" -eq 0 ] && [ "${1:-x}" = "0" ]; then
  ok runs "2 subject(s) answer a graded verdict (rc 0/1), 0 refused"
else
  bad runs "rc=$rrc  not graded: ${2:-<none printed>}"
fi

# --- teeth: at the control rev both defects are present ---------------------
t1="$(git -C "$REPO" show "$CONTROL_REV:$DISPATCHED" 2>/dev/null | head -1)"
t2="$(git -C "$REPO" show "$CONTROL_REV:$SHORTCD" 2>/dev/null \
      | grep -c 'REPO_ROOT="\$(cd \.\. && pwd)"')"
case "$t1" in
  '"""'*) d1="docstring-first, no shebang" ;;
  *)      d1="shebang present" ;;
esac
if [ "$d1" = "docstring-first, no shebang" ] && [ "$t2" = "1" ]; then
  ok teeth "$CONTROL_REV: ${d1}; shortcd computed its root with one 'cd ..'"
else
  bad teeth "$CONTROL_REV: ${d1}; single-cd lines=${t2:-0} (want docstring-first + 1)"
fi

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