Files
fleet/scripts/ci/org-drift-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

402 lines
14 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# Fleet audit: does any public document contradict the org register?
#
# org-drift-audit.sh [--check] [--list]
#
# WHY
#
# Writing a fact down in many places is what failed. The org story has been
# restated across READMEs, CLAUDE.md files, and marketing copy — each time
# with slight variations — and those variations became contradictions. One
# repo says "incorporation pending", another says the legal name, a third
# describes a host that isn't the actual host. The fix is a small
# machine-readable register for facts that have no other producer, and a
# check that fails when a public document contradicts it.
#
# WHAT IS FORBIDDEN
#
# Per registers/org.json, these claims are contradictions:
# - "incorporation pending" (legalStatus is unregistered)
# - "bitbaum AG" (legalStatus is unregistered)
# - "AI-first product studio" or "AI product studio" as what bitbaum is
# - github.io/bitbaum as a host (host is Hetzner)
# - the legal personal name Georgy Butaev on public docs
# - a live door named in a README that disagrees with apps.conf
#
# AND, per registers/retired.json, a document using a name or host that has
# been REPLACED — a different failure with the same cause. A retirement that
# is only remembered drifts: aoz-wohnen.orangecat.ch, revampit.orangecat.ch and
# sbb.orangecat.ch all still answer 200, because each is a redirect, so a stale
# address looks perfectly healthy from the outside and nothing ever reports it.
# Found in 2026-09 only by tripping over them, including on the public studio
# page, which named a real transport company on a demo unconnected to it.
#
# Adding a retirement is a ROW in that register, not a change to this script.
# The finding says what to use instead and since when, because "this document
# is wrong" costs a reader a search and "say X instead" costs them an edit.
#
# CENTRAL, NOT A COPY PER REPO — the rule this repo already lives by. The
# register is SSOT; agents read it. They do not restate the org story. A
# new claim is a register row or it does not ship.
#
# DEFAULT SCAN: GitHub API via `gh`, not local checkouts. A ratchet that sees
# nothing prevents nothing. Scans public docs (README.md, CLAUDE.md, AGENTS.md,
# docs/*.md, site/*.md, marketing/*.md, *.html) from the bitbaum org's default
# branches. Set USE_LOCAL=1 to scan DEV_ROOT instead (for testing).
#
# THE BASELINE IS A RATCHET
#
# Existing violations are counted and baselined. The point is a new lie
# cannot land. The inventory is GENERATED by this script. Counts may FALL or
# hold; they may never RISE without that decision being visible in the same
# PR that adds the violation.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
REGISTER="${REGISTER:-$HERE/../../registers/org.json}"
BASELINE="${BASELINE:-$HERE/org-drift.baseline}"
RETIRED="${RETIRED:-$HERE/../../registers/retired.json}"
INVENTORY="${INVENTORY:-$HERE/org-drift-inventory.txt}"
ORG="${ORG:-bitbaum}"
USE_LOCAL="${USE_LOCAL:-0}"
# ---------------------------------------------------------------- pure helpers
# forbidden_patterns — regex alternatives for claims that contradict the register
forbidden_patterns() {
cat <<'EOF'
incorporation[- ]pending
bitbaum AG\b
AI-first product studio
AI product studio
github\.io/bitbaum
Georgy Butaev
EOF
}
# retired_entries — `from|to|since|why` per line, from registers/retired.json
#
# A rename that is only remembered is a rename that drifts, and every instance
# in 2026-09 was found by tripping over it rather than by looking: a public page
# linking a host that only redirects, the studio page naming a product by its
# repo name. None of them broke anything — a 308 answers 200 — which is exactly
# why nothing noticed. Recording the retirement is what makes it findable.
#
# python3 rather than jq: jq is not guaranteed on every runner, and `gh --jq`
# is gh's own and cannot read a local file.
retired_entries() {
[ -f "$RETIRED" ] || return 0
python3 -c '
import json, sys
d = json.load(open(sys.argv[1]))
for r in d.get("retired", []):
print("|".join([r["from"], r["to"], r.get("since", "?"), r.get("why", "")]))
' "$RETIRED" 2>/dev/null || true
}
# retired_patterns — the retired forms, regex-escaped, one per line
retired_patterns() {
retired_entries | cut -d'|' -f1 | sed -e 's/[][\.^$*+?(){}|]/\\&/g'
}
# retired_hint <line> — what a document using a retired form should say instead
retired_hint() {
local line="$1" from to since
while IFS='|' read -r from to since _why; do
[ -n "$from" ] || continue
case "$line" in *"$from"*) printf 'uses retired "%s" — say "%s" (since %s)' "$from" "$to" "$since"; return 0 ;; esac
done < <(retired_entries)
return 1
}
# is_public_doc <path> — only public-facing documentation and marketing
is_public_doc() {
case "$1" in
*README.md|*CLAUDE.md|*AGENTS.md) return 0 ;;
*docs/*.md|*site/*.md|*content/*.md|*marketing/*.md) return 0 ;;
*.html) return 0 ;;
*) return 1 ;;
esac
}
# is_exempt_path <path> — paths whose job is to describe history
is_exempt_path() {
case "$1" in
docs/archive/*|*/docs/archive/*) return 0 ;;
*org-drift-audit.sh|*org-drift.baseline|*org-drift-inventory.txt) return 0 ;;
*test-org-drift-audit.sh) return 0 ;;
*registers/org.json|*registers/retired.json) return 0 ;;
*SHARED.md|*STACK.md) return 0 ;;
*/.git/*|*/node_modules/*|*/dist/*|*/.next/*) return 0 ;;
*) return 1 ;;
esac
}
# baseline_keys <file> — `repo/path` per line, comments and blanks dropped
baseline_keys() {
[ -f "$1" ] || return 0
sed -e 's/#.*//' -e 's/[[:space:]]*$//' -e '/^[[:space:]]*$/d' "$1"
}
# in_baseline <key> <keys...>
in_baseline() {
local key="$1"; shift
local k
for k in "$@"; do [ "$k" = "$key" ] && return 0; done
return 1
}
# gh_list_repos — list repos in the org
#
# `--no-archived` is load-bearing, not tidiness. Archiving is how this fleet
# retires a repo, and six of the seven org sweeps already skip archived ones —
# this was the only sweep that did not, so a repo taken out of service still
# had its README judged against the org register and still reported drift that
# nobody could act on without unarchiving it first. It is also the exclusion
# path for throwaway repos (see scripts/local/prune-ephemeral-repos.sh): six
# scaffolds appeared in two days, and a sweep whose findings are mostly noise
# gets muted along with everything true inside it.
gh_list_repos() {
gh repo list "$ORG" --limit 1000 --no-archived --json name --jq '.[].name' 2>/dev/null || {
echo "gh repo list failed" >&2
return 1
}
}
# gh_default_branch <repo> — get default branch name
gh_default_branch() {
gh api "repos/$ORG/$1" --jq '.default_branch' 2>/dev/null || echo "main"
}
# gh_check_file <repo> <path> <branch> — fetch and check one file
gh_check_file() {
local repo="$1" path="$2" branch="$3"
gh api "repos/$ORG/$repo/contents/$path?ref=$branch" --jq '.content' 2>/dev/null | base64 -d 2>/dev/null || true
}
# repo_ref <dir> — audit the shared default branch, not a local feature branch
repo_ref() {
git -C "$1" rev-parse --verify -q origin/main >/dev/null 2>&1 && { printf 'origin/main'; return; }
git -C "$1" rev-parse --verify -q origin/master >/dev/null 2>&1 && { printf 'origin/master'; return; }
printf 'HEAD'
}
# fetch_apps_conf — retrieve the current apps.conf from loki
fetch_apps_conf() {
if ! command -v gh >/dev/null 2>&1; then
echo "# apps.conf unavailable: gh not found" >&2
return 1
fi
gh api repos/bitbaum/loki/contents/scripts/hetzner/apps.conf --jq '.content' 2>/dev/null | base64 -d 2>/dev/null || {
echo "# apps.conf unavailable: fetch failed" >&2
return 1
}
}
# parse_apps_conf_doors <apps_conf_content> — extract domain→repo mappings
parse_apps_conf_doors() {
awk -F'|' '
/^#/ || /^[[:space:]]*$/ { next }
NF >= 3 {
domains = $3
repo = $4
gsub(/^\/home\/g\/dev\//, "", repo)
n = split(domains, domainlist, ",")
for (i = 1; i <= n; i++) {
if (domainlist[i] != "-" && domainlist[i] != "") {
print domainlist[i] "|" repo
}
}
}
'
}
if [ -n "${ORG_DRIFT_AUDIT_LIB_ONLY:-}" ]; then return 0; fi
# ---------------------------------------------------------------------- sweep
MODE=check
case "${1:-}" in
--check|"") MODE=check ;;
--list) MODE=list ;;
*) echo "unknown flag: $1" >&2; exit 2 ;;
esac
mapfile -t KEYS < <(baseline_keys "$BASELINE")
# Build forbidden pattern as a single ERE
# Forbidden claims and retired forms are one sweep: both are "this document
# says something that is no longer true", and a second pass would be a second
# place to keep the exemption and baseline logic in step.
PATTERN="$( { forbidden_patterns; retired_patterns; } | paste -sd'|' - )"
new_hits=(); seen_keys=(); scanned_repos=()
declare -A doors=()
# Fetch apps.conf and parse door mappings
if APPS_CONF="$(fetch_apps_conf)"; then
while IFS='|' read -r domain repo; do
doors["$domain"]="$repo"
done < <(echo "$APPS_CONF" | parse_apps_conf_doors)
fi
# Scan via GitHub API (default) or local checkouts (USE_LOCAL=1)
if [ "$USE_LOCAL" = "1" ]; then
DEV_ROOT="${DEV_ROOT:-$HOME/dev}"
for gitdir in "$DEV_ROOT"/*/.git; do
[ -d "$gitdir" ] || continue
repo_dir="${gitdir%/.git}"
repo="$(basename "$repo_dir")"
ref="$(repo_ref "$repo_dir")"
scanned_repos+=("$repo")
while IFS= read -r line; do
[ -n "$line" ] || continue
path="${line%%:*}"
rest="${line#*:}"
is_exempt_path "$path" && continue
is_public_doc "$path" || continue
key="$repo/$path"
seen_keys+=("$key")
# Say what to use instead. "This document is wrong" costs a reader a
# search; "say X instead, since <date>" costs them an edit.
detail="$rest"
if hint="$(retired_hint "$rest")"; then detail="$rest [$hint]"; fi
in_baseline "$key" "${KEYS[@]:-}" || new_hits+=("$key:$detail")
done < <(git -C "$repo_dir" grep -nEI "$PATTERN" "$ref" -- '*.md' '*.html' 2>/dev/null | sed "s|^$ref:||" || true)
# Check for door disagreements in READMEs
if [ ${#doors[@]} -gt 0 ]; then
while IFS= read -r line; do
[ -n "$line" ] || continue
path="${line%%:*}"
rest="${line#*:}"
case "$path" in *README.md|*readme.md) ;; *) continue ;; esac
for domain in "${!doors[@]}"; do
if grep -qF "$domain" <<<"$rest"; then
expected_repo="${doors[$domain]}"
if [ "$repo" != "$expected_repo" ]; then
key="$repo/$path"
detail="claims door $domain (apps.conf says $expected_repo)"
seen_keys+=("$key")
in_baseline "$key" "${KEYS[@]:-}" || new_hits+=("$key:$detail")
fi
fi
done
done < <(git -C "$repo_dir" grep -nEI '\.(orangecat\.ch|[a-z-]+\.(com|ch|org))' "$ref" -- '*README.md' '*readme.md' 2>/dev/null | sed "s|^$ref:||" || true)
fi
done
else
# GitHub API scan (default)
if ! command -v gh >/dev/null 2>&1; then
echo "✗ gh CLI not found. Install it or set USE_LOCAL=1 to scan $HOME/dev" >&2
exit 2
fi
mapfile -t repos < <(gh_list_repos)
for repo in "${repos[@]}"; do
[ -n "$repo" ] || continue
scanned_repos+=("$repo")
branch="$(gh_default_branch "$repo")"
# Check root-level public docs
for file in README.md CLAUDE.md AGENTS.md; do
content="$(gh_check_file "$repo" "$file" "$branch")"
[ -n "$content" ] || continue
path="$file"
is_exempt_path "$path" && continue
# Check forbidden patterns
if matches="$(echo "$content" | grep -oEI "$PATTERN" | head -1)"; then
[ -n "$matches" ] || continue
key="$repo/$path"
detail="$matches"
if hint="$(retired_hint "$content")"; then detail="$matches [$hint]"; fi
seen_keys+=("$key")
in_baseline "$key" "${KEYS[@]:-}" || new_hits+=("$key:$detail")
fi
# Check for door disagreements in READMEs
if [ ${#doors[@]} -gt 0 ] && [ "$file" = "README.md" ]; then
for domain in "${!doors[@]}"; do
if grep -qF "$domain" <<<"$content"; then
expected_repo="${doors[$domain]}"
if [ "$repo" != "$expected_repo" ]; then
key="$repo/$path"
detail="claims door $domain (apps.conf says $expected_repo)"
seen_keys+=("$key")
in_baseline "$key" "${KEYS[@]:-}" || new_hits+=("$key:$detail")
fi
fi
done
fi
done
done
fi
# Generate inventory
{
echo "# org-drift inventory — GENERATED by org-drift-audit.sh"
echo "# $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "#"
echo "# Scanned ${#scanned_repos[@]} repos, found ${#seen_keys[@]} violation(s)"
echo ""
if [ ${#seen_keys[@]} -gt 0 ]; then
printf '%s\n' "${seen_keys[@]}" | sort -u
else
echo "# No violations found"
fi
} > "$INVENTORY"
# A runner that scans nothing passes vacuously
if [ ${#scanned_repos[@]} -eq 0 ]; then
if [ "$USE_LOCAL" = "1" ]; then
echo "⊘ org-drift audit SKIPPED — no fleet checkout under ${DEV_ROOT:-$HOME/dev}."
else
echo "⊘ org-drift audit SKIPPED — gh repo list returned nothing."
fi
echo " This is not a pass. A ratchet that scans nothing prevents nothing."
exit 0
fi
if [ "$MODE" = list ]; then
printf '%s\n' "${seen_keys[@]:-}" | sort -u
exit 0
fi
# Check baseline rise
stale=()
for k in "${KEYS[@]:-}"; do
[ -n "$k" ] || continue
repo="${k%%/*}"
# Only check for stale entries if we actually scanned that repo
scanned=0
for r in "${scanned_repos[@]}"; do
[ "$r" = "$repo" ] && { scanned=1; break; }
done
[ "$scanned" -eq 0 ] && continue
in_baseline "$k" "${seen_keys[@]:-}" || stale+=("$k")
done
if [ ${#new_hits[@]} -gt 0 ]; then
echo "✗ org-drift violations not in the baseline:" >&2
printf ' %s\n' "${new_hits[@]}" >&2
echo >&2
echo " These public documents contradict registers/org.json. Fix the claim," >&2
echo " or if this is a historical record, add the 'repo/path' line to" >&2
echo " $(basename "$BASELINE") WITH A REASON, in the same PR." >&2
exit 1
fi
if [ ${#stale[@]} -gt 0 ]; then
echo "✓ baseline entries with no matching violation — the ratchet fell:" >&2
printf ' %s\n' "${stale[@]}" >&2
echo " Delete these lines from $(basename "$BASELINE")." >&2
exit 1
fi
echo "✓ ${#scanned_repos[@]} repos swept, ${#seen_keys[@]} known violation(s), no new contradictions"