#!/usr/bin/env node // Fleet audit: does a repository's documentation describe the repository? // // docs-truth-audit.mjs --dir DIR [--ref REF] judge a working tree (or REF in it) // docs-truth-audit.mjs --repo NAME [--ref SHA] judge a repo in the org at a commit // docs-truth-audit.mjs --repo NAME --pr N only what PR N ADDS (head minus base) // docs-truth-audit.mjs --sweep [--check] [--emit-baseline] // every non-archived repo, ratcheted // // WHY // // Agents read README.md, CLAUDE.md, AGENTS.md and .claude/ before they read // code, and they act on what those files say. On 2026-10-19 one pass over nine // repos found, in the agent-read files alone: a merge policy said to live in a // repository that no longer holds it, eleven paths to files that had been // deleted or never existed, scripts that are not in package.json, "Next 15 / // TypeScript 5.8 / Tailwind 3.3" in a repo on 16 / 6 / 4, and a retired host // presented as production in forty files. Every one of them was a claim a // machine could have checked, and every one cost the next session time. // // org-drift-audit.sh already holds docs to the ORG register (names, hosts, // legal status). Nothing held a doc to its OWN repository. This does, and only // for claims that are mechanical: // // path a `backticked/repo/path` whose first segment exists in the repo, // but which itself does not // file a `backticked-file.ext` (a config-shaped name) that exists nowhere // in the repo // link a relative markdown link that resolves to nothing // script `pnpm run X` / `npm run X` where X is not a script in the nearest // package.json (or the root one) // stack "Next.js 15", "React 18", "TypeScript 5", "Tailwind 3" where // package.json declares a different major // retired a form registers/retired.json has retired (host, name, repo, // account), with what to say instead // // It never judges prose. A line that says the thing is gone — "deleted", // "removed", "retired", "there is no", "redirects", "formerly" … — is a line // ABOUT history, and every check skips it. That is also the way out when a // finding is wrong: say on the line that the thing no longer exists, which is // what a reader needs to know anyway. // // WHAT IS READ // // README / CLAUDE / AGENTS / CONTRIBUTING / SECURITY / REVIEW / ROADMAP .md // anywhere in the tree, everything under .claude/ and docs/, as markdown. // Never: CHANGELOG, archive/history/handoffs/sessions directories, files // whose name carries a date (a dated record describes its date), content/ // (published writing), templates/ (placeholders by design), vendored code. // // WHERE IT RUNS // // * In the auto-merge sweep, on the PR about to merge (--pr): a PR may not // ADD a finding — including by deleting a file a doc still names. The // sweep is the one workflow every repo already calls, so this needs no // per-repo copy and reaches every caller the day it lands. // * Daily from this repo (--sweep --check): the count per repo may fall or // hold, never rise. docs-truth.baseline is that count. // // Exit codes: 0 clean / no regression, 1 findings / regression, 2 could not // look. "Could not look" is never reported as "nothing to see". import { execFileSync } from "node:child_process"; import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, posix } from "node:path"; import { fileURLToPath } from "node:url"; const here = dirname(fileURLToPath(import.meta.url)); const ORG = process.env.ORG ?? "bitbaum"; const RETIRED_PATH = process.env.RETIRED ?? join(here, "../../registers/retired.json"); const BASELINE_PATH = process.env.BASELINE ?? join(here, "docs-truth.baseline"); // ------------------------------------------------------------- pure helpers const DOC_NAMES = /(^|\/)(README|CLAUDE|AGENTS|CONTRIBUTING|SECURITY|REVIEW|ROADMAP)\.md$/i; const SKIP_DIRS = /(^|\/)(node_modules|vendor|\.next|dist|build|out|coverage|\.git|archive|archived|history|handoffs|sessions|worktrees|proofs|content|templates|fixtures|__fixtures__|\.changeset)(\/|$)/i; const DATED = /(^|[^\d])20\d\d-[01]\d([^\d]|$)/; /** Which files are documentation this audit holds to the tree. */ export function isJudgedDoc(path) { if (!path.endsWith(".md")) return false; if (SKIP_DIRS.test(path)) return false; if (/(^|\/)CHANGELOG\.md$/i.test(path)) return false; if (DATED.test(posix.basename(path))) return false; if (DOC_NAMES.test(path)) return true; return path.startsWith(".claude/") || path.startsWith("docs/"); } /** A line about history. Every check skips it. */ export const HISTORICAL = new RegExp( "\\b(retired|retire[sd]?|deprecated|formerly|previously|renamed|rename[sd]?|" + "redirect(s|ed|ing)?|no longer|used to|deleted|removed|replaced|superseded|" + "legacy|historical|was called|there is no|there are no|does not exist|" + "never existed|not yet|planned|will be|moved (to|from|out)|old (name|host|path|address)|" + "dropped|instead of|not\\b[^.]*\\byet)\\b", "i", ); /** Strip fenced code blocks' markers but keep their lines: commands in a fence * are claims too ("pnpm run verify"), paths in a fence are not (they are * usually illustrative trees or sample code), so callers get both views. */ export function scanLines(text) { const out = []; let fence = false; const lines = text.split("\n"); for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (/^\s*(```|~~~)/.test(line)) { fence = !fence; continue; } out.push({ n: i + 1, line, fence }); } return out; } const PATH_RE = /^[\w.@()[\]+~-]+(\/[\w.@()[\]*+~{},-]+)+\/?$/; // Config-shaped names only: a bare "watch.sh" may be a script on the box, but // a ".eslintrc.json" or "vitest.config.ts" is a claim about THIS repo's setup. const FILE_RE = /^(\.[\w-]+rc(\.[\w]+)?|\.[\w-]+\.(json|ya?ml)|[\w-]+\.config\.(ts|mts|js|mjs|cjs)|tsconfig(\.[\w-]+)?\.json|docker-compose(\.[\w-]+)?\.ya?ml)$/; /** Normalise one backticked token to a repo-relative path candidate, or null. */ export function pathCandidate(raw) { let t = raw.trim().replace(/[.,;:)]+$/, "").replace(/:\d+(-\d+)?$/, "").replace(/#.*$/, ""); if (!t || /\s|\$|<|>|\.\.\.|…|=|\\|^@|^\/|^~|^\w+:\/\//.test(t)) return null; if (t.startsWith("./")) t = t.slice(2); if (!PATH_RE.test(t)) return null; // Only a token that LOOKS like a file (an extension on its last segment) or // says it is a directory (a trailing slash) is a path claim. "image/x-icon", // "white/NN", "next/link" and "SECOND/MINUTE/HOUR" are not. const last = t.replace(/\/$/, "").split("/").pop(); if (!t.endsWith("/") && !/\.[A-Za-z][\w-]{0,9}$/.test(last)) return null; // A template, not a file: "NNN_name.sql", "YYYYMMDD_x.sql", "XXX.md", or a // bracketed stem outside a router directory ("providers/[name].ts"). Inside // app/ or pages/, "[slug]" is a real dynamic segment and stays a claim. const stem = last.replace(/\.[^.]*$/, ""); if (/^(?:N{3,}|X{3,}|Y{4}[MDHS]*)(?:[_-]|$)/.test(stem)) return null; if (/^\[[\w.]+\]$/.test(stem) && !/(?:^|\/)(?:app|pages)\//.test(t)) return null; return t.replace(/\/$/, ""); } /** Does `p` (possibly a glob, possibly a directory) exist in the tree set? */ export function existsIn(tree, dirs, p) { if (tree.has(p) || dirs.has(p)) return true; if (/[*{]/.test(p)) { const prefix = p.split(/[*{]/)[0].replace(/\/[^/]*$/, ""); return dirs.has(prefix) || [...tree].some((f) => f.startsWith(prefix + "/")); } // a route-group or dynamic segment written loosely, e.g. app/(app)/x vs app/x return false; } export function dirsOf(tree) { const dirs = new Set(); for (const f of tree) { const parts = f.split("/"); for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join("/")); } return dirs; } /** Major version a package.json declares for `name`, or null if not a semver. */ export function declaredMajor(pkg, name) { for (const k of ["dependencies", "devDependencies", "peerDependencies"]) { const v = pkg?.[k]?.[name]; if (typeof v !== "string") continue; const m = v.replace(/^npm:[^@]+@/, "").match(/^[\^~>=<\s]*v?(\d+)/); if (m) return Number(m[1]); } return null; } const STACK = [ { pkg: "next", re: /\bNext(?:\.js)?\s+v?(\d{2})(?![\d.]*\s*(?:ms|px|%|(?:[Dd]ays?|[Ww]eeks?|[Mm]onths?|[Yy]ears?|[Hh]ours?|[Mm]inutes?|[Ss]teps?)\b))\b/g, label: "Next.js" }, { pkg: "react", re: /\bReact\s+v?(\d{2})\b/g, label: "React" }, { pkg: "typescript", re: /\bTypeScript\s+v?(\d)(?:\.\d+)?(?:\.x)?\b/g, label: "TypeScript" }, { pkg: "tailwindcss", re: /\bTailwind(?:\s+CSS)?\s+v?(\d)(?:\.\d+)?(?:\.x)?\b/g, label: "Tailwind CSS" }, ]; // Used when the org's repo list cannot be read: a line naming a sibling repo // is describing that repo's tree, not this one's. export const FALLBACK_REPOS = ["orangecat", "loki", "solon", "fleet", "dotfiles", "evig", "heidi", "substrata", "bitbaum", "causius", "diplodoctor", "hirnli", "botsmann", "datacat", "petvity", "kivvi", "sitekit", "chatkit", "searchkit", "accountkit", "whenkit", "listkit", "design-tokens", "aoz-begleitung"]; // First segments that are always this repo's own, even when a change has just // removed the last file under them (that removal is the drift to catch). const KNOWN_ROOTS = new Set(["src", "app", "lib", "scripts", "docs", "components", "packages", "public", "supabase", "drizzle", ".github", ".claude", "tests", "__tests__", "e2e", "config", "hooks", "messages"]); const ILLUSTRATIVE = /\b(e\.g\.|i\.e\.|for example|for instance|example:|such as|placeholder|would (go|live|be))/i; const CODE_ROOTS = ["src", "app", "apps", "packages", "lib"]; const GENERATED = /^(\.claude\/worktrees|\.tmp|tmp|\.next|node_modules|dist|build|out|coverage|\.env|\.turbo|\.vercel|test-results|playwright-report)(\/|$)/; const OTHER_REPO = /\bbitbaum\/[\w.-]+|github\.com\/|\b(in|from|of) (the )?(fleet|orangecat|loki|solon|dotfiles|evig|heidi|substrata|bitbaum)(\b| repo)/i; /** A deliberately small .gitignore reader: enough to know that a doc naming * public/widget.js (built, never committed) is not naming a missing file. */ export function gitignoreMatcher(text) { const rules = (text ?? "").split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#") && !l.startsWith("!")); const res = rules.map((r) => { const anchored = r.startsWith("/"); const body = r.replace(/^\//, "").replace(/\/$/, ""); const rx = body.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\u0000").replace(/\*/g, "[^/]*").replace(/\u0000/g, ".*").replace(/\?/g, "."); return new RegExp(anchored || body.includes("/") ? `^${rx}(/|$)` : `(^|/)${rx}(/|$)`); }); return (p) => res.some((r) => r.test(p)); } const SCRIPT_RE = /\b(?:pnpm|npm|yarn|bun)((?:\s+--?[\w-]+(?:[= ][^\s`]+)?)*)\s+run\s+([\w:.@/-]+)/g; /** The retired register as [{from, to, since}] — forms specific enough to grep. */ export function parseRetired(json) { try { return (JSON.parse(json).retired ?? []).filter((r) => r.from && r.from.length >= 5); } catch { return []; } } /** * The judgement, isolated from the network so it can be tested. * repo: { name, tree: Set, read(path) -> string|null } */ export function judgeRepo({ name, tree, read }, retired = [], otherRepos = FALLBACK_REPOS) { const others = otherRepos.filter((r) => r !== name && r.length >= 4).map((r) => r.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); const otherRepo = others.length ? new RegExp(`\\b(${others.join("|")})\\b`, "i") : null; const dirs = dirsOf(tree); const top = new Set([...tree, ...dirs].map((p) => p.split("/")[0])); const basenames = new Set([...tree].map((f) => posix.basename(f))); const ignore = gitignoreMatcher(tree.has(".gitignore") ? read(".gitignore") : ""); const ignored = (p) => GENERATED.test(p) || ignore(p); const exts = ["", ".ts", ".tsx", ".js", ".mjs", ".cjs", ".jsx", ".md", ".json", "/index.ts", "/index.tsx", "/index.js", "/route.ts", "/page.tsx"]; // `lib/x.ts` in an app whose code is under src/ means src/lib/x.ts; a doc in // docs/ may name a sibling; and "Composer" may be written without ".tsx". const resolves = (p, docDir) => { const bases = [p, docDir ? posix.normalize(posix.join(docDir, p)) : null, ...CODE_ROOTS.map((r) => `${r}/${p}`)].filter(Boolean); return bases.some((b) => exts.some((e) => existsIn(tree, dirs, b + e))); }; const pkgCache = new Map(); const pkgAt = (dir) => { if (pkgCache.has(dir)) return pkgCache.get(dir); const p = dir ? `${dir}/package.json` : "package.json"; let v = null; if (tree.has(p)) { try { v = JSON.parse(read(p) ?? ""); } catch { v = null; } } pkgCache.set(dir, v); return v; }; const nearestPkgs = (doc) => { const out = []; let d = posix.dirname(doc); while (true) { const dd = d === "." ? "" : d; const p = pkgAt(dd); if (p) out.push(p); if (!dd) break; d = posix.dirname(d); } return out; }; const rootPkg = pkgAt(""); const findings = []; const add = (file, n, kind, token, detail) => findings.push({ repo: name, file, line: n, kind, token, detail }); for (const file of [...tree].filter(isJudgedDoc).sort()) { const text = read(file); if (text == null) continue; const docDir = posix.dirname(file) === "." ? "" : posix.dirname(file); const pkgs = nearestPkgs(file); const scripts = new Set(pkgs.flatMap((p) => Object.keys(p.scripts ?? {}))); // A file that describes OTHER repositories by design (a global agent file // installed into ~/.claude from dotfiles) opts its paths out, on the // record: ``. Retired names still count. const elsewhere = //.test(text); const rows = scanLines(text); let para = ""; for (let i = 0; i < rows.length; i++) { const { n, line, fence } = rows[i]; // The paragraph (or list item) so far: a wrapped sentence names its // repository once, often lines before the path it then quotes. if (!line.trim() || /^(\s{0,1}[-*+] |\s{0,1}\d+\. |#)/.test(line)) para = ""; para += " " + line; // Judge the PROSE for history words, not the names it quotes: a file // called removed.ts is not a sentence about something being removed. // A name kept ON PURPOSE (a JWT issuer, a cookie key) is a decision, not // drift: `` on the line records it. if (/