Files
fleet/scripts/ci/org-drift-audit.sh
Cato 00215923f3 fix(ci): reduce shared GitHub API pressure (#282)
* fix(ci): isolate auto-merge API quota

* fix(ci): preserve drift audit read diagnostics

* fix(ci): cut package census API fanout

* fix(ci): retain organization audit read errors
2026-10-27 11:16:21 +00:00

516 lines
19 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() {
# One list, in registers/org.json (forbiddenClaims), so the served-page audit
# (live-claims-audit.mjs) and this document audit can never disagree.
python3 -c '
import json, sys
for c in json.load(open(sys.argv[1])).get("forbiddenClaims", []):
print(c["pattern"])
' "$REGISTER"
}
# 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_read <gh arguments...> — a bounded retry for an idempotent GitHub read
#
# Secondary API limits arrive as HTTP 403, but ordinary permission 403s are
# permanent. Retry only recognized transient responses and preserve the final
# diagnostic so the caller can distinguish unavailable evidence from absence.
GH_READ_FAILURE=''
gh_read() {
local output status attempt
for attempt in 1 2 3; do
if output="$(gh "$@" 2>&1)"; then
GH_READ_FAILURE=''
printf '%s' "$output"
return 0
else
status=$?
fi
GH_READ_FAILURE="$output"
[[ "$output" == *'(HTTP 404)'* ]] && return 4
if [[ "$output" =~ HTTP\ (429|5[0-9][0-9]) || "$output" =~ (secondary\ rate\ limit|rate\ limit\ exceeded|abuse\ detection|temporarily\ rate\ limited|timed\ out|ECONNRESET) ]]; then
[ "$attempt" -lt 3 ] || return "$status"
sleep "$((attempt * 10))"
continue
fi
return "$status"
done
return 1
}
# gh_list_repos — list names, visibility and default branches in one query
#
# `--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() {
local rows
rows="$(gh_read repo list "$ORG" --limit 1000 --no-archived --json name,isPrivate,defaultBranchRef --jq '.[] | [.name, (.defaultBranchRef.name // ""), (.isPrivate | tostring)] | @tsv')" || {
echo "gh repo list failed: $GH_READ_FAILURE" >&2
return 1
}
[ -n "$rows" ] || { echo "gh repo list returned no repositories" >&2; return 1; }
printf '%s\n' "$rows"
}
# gh_default_branch <repo> — get default branch name
gh_default_branch() {
local branch
branch="$(gh_read api "repos/$ORG/$1" --jq '.default_branch')" || return 2
[[ -n "$branch" && "$branch" != null ]] || return 2
printf '%s\n' "$branch"
}
# gh_check_file <repo> <path> <branch> — fetch and check one file
gh_check_file() {
local repo="$1" path="$2" branch="$3"
local private="${4:-true}" content response status body encoded_branch encoded_path response_file
GH_READ_FAILURE=''
if [[ "$private" == false ]]; then
encoded_branch="${branch//\//%2F}"
encoded_path="${path// /%20}"
response="$(curl --fail --silent --show-error --location --retry 3 --retry-delay 1 --max-time 20 \
--write-out $'\n%{http_code}' "https://raw.githubusercontent.com/$ORG/$repo/$encoded_branch/$encoded_path" 2>/dev/null)" || status=$?
status="${status:-0}"
local http_code="${response##*$'\n'}"
body="${response%$'\n'*}"
[[ "$http_code" == 404 ]] && return 4
[[ "$status" == 0 && "$http_code" == 200 ]] || return 2
printf '%s' "$body"
return 0
fi
# Do not put gh_read in command substitution: that runs in a subshell, so
# GH_READ_FAILURE (the diagnostic for a permission, quota, or transport
# failure) disappears exactly when the caller needs it. Redirecting to a
# temporary file keeps the retry helper in this shell and preserves the
# fail-closed distinction between absent docs and unreadable evidence.
response_file="$(mktemp)"
if gh_read api "repos/$ORG/$repo/contents/$path?ref=$branch" --jq '.content' > "$response_file"; then
content="$(cat "$response_file")"
rm -f "$response_file"
:
else
status=$?
rm -f "$response_file"
[[ "$status" == 4 ]] && return 4
return 2
fi
printf '%s' "$content" | base64 -d 2>/dev/null
}
# 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 curl >/dev/null 2>&1; then
echo "# apps.conf unavailable: curl not found" >&2
return 1
fi
# This public source is read by every Fleet CI run. Pulling its raw bytes
# avoids consuming GitHub's secondary API quota alongside the 61-repo
# currency census; retries are bounded and the caller still fails closed.
curl --fail --silent --show-error --location \
--retry 3 --retry-all-errors --retry-delay 1 --retry-max-time 30 \
--connect-timeout 10 --max-time 30 \
https://raw.githubusercontent.com/bitbaum/loki/main/scripts/hetzner/apps.conf || {
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=()
# The local pre-push helper may run outside any Fleet checkout. That is an
# explicit skip, not a remote coverage claim, and must need no network.
if [[ "$USE_LOCAL" == 1 ]]; then
local_root="${DEV_ROOT:-$HOME/dev}"
local_checkout=false
for gitdir in "$local_root"/*/.git; do
if [[ -d "$gitdir" ]]; then local_checkout=true; break; fi
done
if [[ "$local_checkout" == false ]]; then
echo "⊘ org-drift audit SKIPPED — no fleet checkout under $local_root."
exit 0
fi
fi
# 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)
else
echo "Org drift evidence incomplete: canonical door register unavailable." >&2
exit 2
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
if ! repo_list="$(gh_list_repos)"; then
echo "Org drift evidence incomplete: repository census unavailable." >&2
exit 2
fi
mapfile -t repo_rows <<< "$repo_list"
for row in "${repo_rows[@]}"; do
IFS=$'\t' read -r repo branch private <<< "$row"
[ -n "$repo" ] || continue
scanned_repos+=("$repo")
if [[ -z "$branch" || "$branch" == null || ( "$private" != true && "$private" != false ) ]]; then
echo "Org drift evidence incomplete: default branch unavailable for $repo." >&2
exit 2
fi
# Root agent files, plus the two docs that have repeatedly restated a
# retired auth rule after the root files were fixed. A scan that only
# reads AGENTS.md misses the page AGENTS.md tells the agent to open next.
for file in README.md CLAUDE.md AGENTS.md .claude/CLAUDE.md docs/UNIFIED_AUTH.md docs/SHARED_CONTEXT.md; do
# Keep gh_check_file in this shell so its original private-read failure
# survives for the fail-closed diagnostic below. Command substitution
# would run it in a subshell and erase GH_READ_FAILURE.
doc_file="$(mktemp)"
if gh_check_file "$repo" "$file" "$branch" "$private" > "$doc_file"; then
content="$(cat "$doc_file")"
rm -f "$doc_file"
[ -n "$content" ] || continue
else
status=$?
rm -f "$doc_file"
if [[ "$status" == 4 ]]; then continue; fi
detail="${GH_READ_FAILURE:-raw source unavailable}"
detail="${detail//$'\n'/ }"
detail="${detail//$'\r'/ }"
detail="$(printf '%s' "$detail" | sed -E 's/(gho|ghp|github_pat)_[A-Za-z0-9_]+/[redacted]/g' | cut -c1-300)"
echo "Org drift evidence incomplete: $repo/$file could not be read ($detail)." >&2
exit 2
fi
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"