Files
fleet/scripts/ci/nav-contract-audit.sh
CatoandClaude Opus 5.5 31de29870b fix(scripts): grep -q is never the reader of a pipe under pipefail (#140)
* fix(scripts): grep -q is never the reader of a pipe under pipefail

`echo "$x" | grep -q PAT` under `set -o pipefail` can report "not found"
for text that IS there: grep -q exits on its first match and closes the
pipe, the writer takes SIGPIPE (141), and pipefail makes the pipeline
status 141, so an `if` takes the else branch on a successful match.

It is not confined to payloads past the ~4KB pipe buffer. Measured in
loki (loki#874) on a real 1,158-byte output, 3,000 calls: 2/3000 false
misses for a phrase near the top, 0/3000 via a here-string. Rare per
call; a suite makes hundreds. loki's retire-site suite went red on
exactly those phrases twice this week.

48 copies in 14 scripts here, rewritten to `grep -q PAT <<<"$x"`,
including:
- auto-merge-sweep.sh: the required-check coverage test. A false miss
  marks a green job "uncovered".
- gc-merged-worktrees.sh: `in_use`. A false miss reads a live session's
  worktree as unused. The pushed / clean / MERGED guards still stand, so
  it cannot lose work, but it can remove a directory from under a live
  session.
- cicd-hygiene, nav-contract, org-drift, verify-floor audits and
  verify-predicates: false passes and false findings.

Checked: all 14 files pass `bash -n`; every file is a 1:1 line swap (48
lines); the 8 line-continuation sites keep the here-string before the
trailing backslash; fleet's 30 CI test scripts pass before and after
(30/30 -> 30/30); workflows still parse.

Gate: scripts/ci/test-no-grep-q-in-a-pipe.sh, wired into ci.yml. Scans
scripts/ and templates/, self-tests its detector both ways, and was
proven by restoring the original auto-merge-sweep.sh line.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>

* fix(ci): main was red on a ratchet that fell, and a sweep test lied

Two failures on fleet main that were blocking every PR, including this
one. Neither was caused by the grep -q rewrite: main (7ed94a2, the base
of this branch) failed CI on the same step for the same reason.

1. org-drift ratchet fell. `org-drift-audit.sh --check` failed on main
   since c43464d with "baseline entries with no matching violation - the
   ratchet fell: bitbaum/README.md". Good news: someone fixed that drift.
   Nobody lowered the baseline, so main stayed red and the auto-merge
   sweep refused everything. Line removed; --check now passes (44 repos
   swept, 3 known violations, no new contradictions).

2. test-auto-merge-sweep.sh lied. Its verdict `[ "$FAIL" -eq 0 ]` sat at
   line 400 of 473, with ~70 lines of tests appended after it. A bash
   script exits with its LAST command's status, so the verdict was
   discarded: the suite exited 0 while printing "27 passed, 1 failed",
   and its later tests were not even counted. Verdict moved to the end;
   the suite now counts 38.

   The hidden failure was real and was mine: test 13 asserted the sweep
   always "waits for CI to catch up" when the newest base run is for an
   older commit. The deadlock fix changed that - it waits only while a
   run is in flight, and otherwise dispatches CI. Test 13 now asserts
   both cases (13a waits and dispatches nothing; 13b dispatches and does
   not merge). `rearms()` moved above its first use.

Proven by mutation: an injected late failure now fails the suite;
reverting the sweep to always-wait fails 13b; making it never wait fails
13a.

Gate: scripts/ci/test-verdict-is-last.sh, wired into ci.yml, requires
every suite's verdict to be its file's last command. Proven by restoring
the old mid-file verdict. All 34 fleet CI commands are now green, and
none exits 0 while reporting a failure.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>

---------

Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 11:58:34 -07:00

139 lines
6.1 KiB
Bash
Executable File

#!/usr/bin/env bash
# Fleet audit: a navigation that STYLES the current page but never ANNOUNCES it.
#
# The rendered audit (ui-defect-audit.mjs) already checks this, but only where
# it can reach: the public entry page of each orangecat.ch site. Every sidebar
# behind a login is invisible to it by construction — and the bug that started
# this was on exactly such a sidebar. This is the other half: a source sweep
# that sees authed surfaces, every framework, and the sites on their own
# domains the renderer never visits.
#
# THE RULE IS REPO-LEVEL, DELIBERATELY.
#
# The first draft asserted this per FILE: a file that renders nav links and
# computes which one is current must contain `aria-current`. Run across the
# fleet it produced 19 findings of which roughly a quarter were wrong, because
# the active state and the announcement legitimately live in different files:
#
# - evig spreads `{...navLinkProps(...)}`, a helper that supplies the
# attribute — the literal string never appears in the component.
# - loki's SidebarNav passes `current={...}` to SidebarNavItem, and the
# child is what announces.
# - a tab list correctly uses aria-selected, not aria-current.
#
# A gate that is wrong a quarter of the time gets ignored, and an ignored gate
# is worse than none because it manufactures confidence. So the assertion is
# the one that cannot be wrong: a repo whose navigation computes an active
# state must announce it SOMEWHERE. That catches the real class — a whole app
# where the highlight exists only for people who can see it — with no false
# positives. Per-surface stragglers are the rendered audit's job, because only
# a real DOM can tell which link actually got the attribute.
#
# CENTRAL, NOT A COPY PER REPO — the rule this repo already lives by.
#
# READS THE DEFAULT BRANCH, never the working tree: a local checkout sits on a
# feature branch as often as not. It reads the LAST-FETCHED origin ref and does
# not fetch, so a stale clone reports stale facts — the workflow clones fresh.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
DEV_ROOT="${DEV_ROOT:-$HOME/dev}"
BASELINE="${NAV_CONTRACT_BASELINE:-$HERE/nav-contract.baseline}"
NAV_PATH='(nav|sidebar|header|footer|menu)[^/]*\.(tsx|jsx|mjs|html)$'
ACTIVE='isActive|isCurrent|pathname *===|pathname\.startsWith|currentView|-active\b|data-active'
LINKS='<Link|<a [^>]*href|<NavLink'
TABS='aria-selected|role="tab"'
SKIP_FILE='(^|/)page\.(tsx|jsx)$|(^|/)[A-Za-z-]*sortable[A-Za-z-]*\.(tsx|jsx)$|(^|/)[A-Za-z-]*filter[A-Za-z-]*\.(tsx|jsx)$|(^|/)tabs?\.(tsx|jsx)$'
# Every alternative is anchored to a path boundary ((^|/)) so it matches a
# whole basename, never a substring. Unanchored, `tabs?\.(tsx|jsx)$` matched
# ANY file merely ending in "Tabs.tsx" — evig's AnalyseTabs.tsx included —
# and skipped it silently, which is exactly the kind of miss this script
# exists to prevent elsewhere.
offenders=()
evidence=()
repos_scanned=0
navfiles_scanned=0
allowed() {
[ -f "$BASELINE" ] || return 1
grep -vE '^\s*(#|$)' "$BASELINE" | awk '{print $1}' | grep -qxF "$1"
}
declare -A seen_remote=()
for gitdir in "$DEV_ROOT"/*/.git; do
[ -e "$gitdir" ] || continue
repo="$(dirname "$gitdir")"
name="$(basename "$repo")"
# Two directories are not two repos: loki/loki-scripts and
# hirnli/revamp-info are each ONE repo cloned twice.
remote="$(git -C "$repo" remote get-url origin 2>/dev/null || echo "local:$name")"
remote="${remote%.git}"
if [ -n "${seen_remote[$remote]:-}" ]; then continue; fi
seen_remote[$remote]=1
# `|| true`: origin/HEAD is unset in many clones. A question, not an error.
branch="$(git -C "$repo" symbolic-ref -q --short refs/remotes/origin/HEAD 2>/dev/null | sed 's|^origin/||' || true)"
[ -n "$branch" ] || branch=main
git -C "$repo" rev-parse --verify -q "origin/$branch" >/dev/null 2>&1 || branch=master
ref="origin/$branch"
git -C "$repo" rev-parse --verify -q "$ref" >/dev/null 2>&1 || continue
repos_scanned=$((repos_scanned + 1))
mapfile -t candidates < <(
{
git -C "$repo" ls-tree -r --name-only "$ref" 2>/dev/null | grep -iE "$NAV_PATH" || true
git -C "$repo" grep -l -I -E '<nav[ >]|role="navigation"' "$ref" \
-- '*.tsx' '*.jsx' '*.mjs' '*.html' 2>/dev/null | sed "s|^$ref:||" || true
} | grep -viE 'node_modules|/dist/|\.next/|__tests__|\.test\.|\.spec\.' \
| grep -viE "$SKIP_FILE" | sort -u
)
hits=()
for f in "${candidates[@]}"; do
[ -n "$f" ] || continue
body="$(git -C "$repo" show "$ref:$f" 2>/dev/null || true)"
[ -n "$body" ] || continue
navfiles_scanned=$((navfiles_scanned + 1))
if grep -qE "$TABS" <<<"$body"; then continue; fi
if ! grep -qE "$LINKS" <<<"$body"; then continue; fi
if ! grep -qE "$ACTIVE" <<<"$body"; then continue; fi
hits+=("$f")
done
# No nav computes an active state here — nothing to announce.
if [ "${#hits[@]}" -eq 0 ]; then continue; fi
# THE ASSERTION: somewhere in this repo, the current page is announced.
if git -C "$repo" grep -q -I 'aria-current' "$ref" 2>/dev/null; then continue; fi
if allowed "$name"; then continue; fi
offenders+=("$name")
evidence+=("$name|${hits[0]}|${#hits[@]}")
done
if [ "$repos_scanned" -eq 0 ] || [ "$navfiles_scanned" -eq 0 ]; then
echo "⊘ nav-contract audit SKIPPED — no fleet checkout under $DEV_ROOT" >&2
echo " (scanned $navfiles_scanned nav file(s) across $repos_scanned repo(s))" >&2
exit 2
fi
if [ "${#offenders[@]}" -gt 0 ]; then
echo "nav-contract audit FAILED — ${#offenders[@]} repo(s) paint a current page they never announce:"
echo
for e in "${evidence[@]}"; do
IFS='|' read -r r f n <<< "$e"
echo " $r — $n nav file(s) compute an active state, 0 aria-current in the repo"
echo " e.g. $f"
done
echo
echo "The highlight exists only for people who can see it. Set aria-current=\"page\""
echo "on the active link. If a repo's nav genuinely has no current page (a"
echo "single-page tool whose nav is anchors), add it to $(basename "$BASELINE") with a reason."
exit 1
fi
echo "nav-contract audit: ok — $navfiles_scanned nav file(s) across $repos_scanned repo(s), every repo announces its current page."