Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chore(guards): item allowlist-catch ratchet (GBRA-130 F9)
garrytanad4ae0d051da
diff --git a/package.json b/package.jsonindex 7a7378a67b..0ef77803bd 100644--- a/package.json+++ b/package.json@@ -154,6 +154,7 @@"check:module-size": "bash scripts/check-module-size.sh","check:core-guard-coverage": "node scripts/check-core-guard-coverage.mjs","check:function-size": "bun scripts/check-function-size.ts",+ "check:item-allowlist-catches": "bun scripts/check-item-allowlist-catches.ts","check:layering": "bun scripts/check-layering.ts","check:ai-sdk-importers": "bun scripts/check-ai-sdk-importers.ts","check:durable-flush": "bun scripts/check-durable-flush.ts",diff --git a/scripts/check-item-allowlist-catches.ts b/scripts/check-item-allowlist-catches.tsnew file mode 100644index 0000000000..af97e1f749--- /dev/null+++ b/scripts/check-item-allowlist-catches.ts@@ -0,0 +1,270 @@+#!/usr/bin/env bun+/**+ * Item allowlist-catch ratchet (GBRA-130; docs/TESTING.md#pathological-states).+ *+ * A per-item loop that hand-rolls its own item-vs-run decision, a catch that+ * compares the caught error's code against a list and rethrows everything+ * else, is the shape that lets one bad item stop a whole unit: every code the+ * list misses aborts the run. src/core/item-failure.ts (`classifyItemFailure`,+ * `ItemRun`) owns that decision, and test/pathological/ proves each adopted+ * site. This guard keeps the hand-rolled shape from spreading.+ *+ * A catch clause in src/**\/*.ts (excluding *.generated.ts and .d.ts) is a site when:+ * 1. it sits in a per-item loop: walking up from the catch to the nearest+ * enclosing function boundary passes through the body of a for, for-of,+ * for-in, while or do-while statement, or that boundary is a callback+ * passed to `.forEach(...)` / `.map(...)`. A function declared inside a+ * loop body is its own boundary, so a catch in it counts only when that+ * function is itself a forEach/map callback or holds the loop;+ * 2. the catch block tests the caught error's code against a set, list or+ * literal: `X.has(e.code)`, `[...].includes(e.code)`, `e.code === '23503'`,+ * `e?.code !== CODE`, `switch (e.code)`, through parentheses, `as`+ * casts and non-null assertions, a `const err = e as T` alias, or a code+ * alias (`const code = (e as {code?: string}).code`, `const { code } = e`);+ * 3. the catch block rethrows the caught error: `throw e` (or an alias)+ * anywhere in the block outside nested functions, including nested if/else.+ *+ * Rules (every violation is reported, then one exit):+ * - a file with more sites than its baseline row, or sites and no row -> FAIL+ * - a file with fewer sites than its row -> FAIL (lower the row)+ * - a row for a file with no sites, or a file that no longer exists -> FAIL (remove the row)+ * - malformed, duplicate or unsorted rows, or a missing header -> FAIL+ *+ * `--update` rewrites scripts/item-allowlist-catches-baseline.tsv from the+ * current tree. It exists for shrinking: a raised or added row does not pass+ * review; adopt classifyItemFailure / ItemRun instead.+ *+ * Seam: GBRAIN_GUARD_ROOT (fixture root; baseline read from+ * <root>/scripts/item-allowlist-catches-baseline.tsv).+ */+import { spawnSync } from 'node:child_process';+import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { join, relative } from 'node:path';+import ts from 'typescript';++const BASELINE_REL = 'scripts/item-allowlist-catches-baseline.tsv';+const HEADER = 'path\tcount';+const ANCHOR = 'docs/TESTING.md#pathological-states';+const CALLBACK_METHODS = new Set(['forEach', 'map']);+const EQUALITY = new Set([ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken,+ ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken]);++export interface AllowlistCatch {+ path: string;+ line: number;+}++function strip(node: ts.Expression): ts.Expression {+ let current = node;+ while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isTypeAssertionExpression(current)+ || ts.isNonNullExpression(current) || ts.isSatisfiesExpression(current)) current = current.expression;+ return current;+}++function isFunctionBoundary(node: ts.Node): boolean {+ return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node)+ || ts.isConstructorDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node);+}++function loopBody(node: ts.Node): ts.Statement | undefined {+ if (ts.isForStatement(node) || ts.isForOfStatement(node) || ts.isForInStatement(node) || ts.isWhileStatement(node) || ts.isDoStatement(node)) {+ return node.statement;+ }+ return undefined;+}++function isLoopCallback(fn: ts.Node): boolean {+ const call = fn.parent;+ if (!call || !ts.isCallExpression(call) || !call.arguments.some(arg => arg === fn)) return false;+ const callee = strip(call.expression);+ return ts.isPropertyAccessExpression(callee) && CALLBACK_METHODS.has(callee.name.text);+}++/** Rule 1: the catch is in a loop body, or its nearest function boundary is a forEach/map callback. */+function inPerItemLoop(clause: ts.CatchClause): boolean {+ let child: ts.Node = clause;+ for (let node: ts.Node | undefined = clause.parent; node && !ts.isSourceFile(node); child = node, node = node.parent) {+ if (isFunctionBoundary(node)) return isLoopCallback(node);+ if (loopBody(node) === child) return true;+ }+ return false;+}++/** A value a code can be compared with: a literal or a named constant, never `undefined`. */+function isComparand(node: ts.Expression): boolean {+ const n = strip(node);+ if (ts.isStringLiteral(n) || ts.isNoSubstitutionTemplateLiteral(n) || ts.isNumericLiteral(n)) return true;+ if (ts.isIdentifier(n)) return n.text !== 'undefined';+ return ts.isPropertyAccessExpression(n) || ts.isElementAccessExpression(n);+}++/** Rules 2 and 3 over one catch block: the caught error's code is tested, and the error is rethrown. */+function testsCodeAndRethrows(block: ts.Block, catchVar: string): boolean {+ const errors = new Set([catchVar]);+ const codes = new Set<string>();+ const isError = (e: ts.Expression) => { const n = strip(e); return ts.isIdentifier(n) && errors.has(n.text); };+ const isCodeRead = (e: ts.Expression): boolean => {+ const n = strip(e);+ if (ts.isIdentifier(n)) return codes.has(n.text);+ if (ts.isPropertyAccessExpression(n)) return n.name.text === 'code' && isError(n.expression);+ return ts.isElementAccessExpression(n) && ts.isStringLiteral(n.argumentExpression) && n.argumentExpression.text === 'code' && isError(n.expression);+ };+ const collectAliases = (node: ts.Node): void => {+ if (ts.isVariableDeclaration(node) && node.initializer) {+ if (ts.isIdentifier(node.name) && isError(node.initializer)) errors.add(node.name.text);+ else if (ts.isIdentifier(node.name) && isCodeRead(node.initializer)) codes.add(node.name.text);+ else if (ts.isObjectBindingPattern(node.name) && isError(node.initializer)) {+ for (const el of node.name.elements) {+ const key = el.propertyName ?? el.name;+ if (ts.isIdentifier(key) && key.text === 'code' && ts.isIdentifier(el.name)) codes.add(el.name.text);+ }+ }+ }+ ts.forEachChild(node, collectAliases);+ };+ ts.forEachChild(block, collectAliases);++ let tested = false;+ const findTest = (node: ts.Node): void => {+ if (ts.isBinaryExpression(node) && EQUALITY.has(node.operatorToken.kind)) {+ if ((isCodeRead(node.left) && isComparand(node.right)) || (isCodeRead(node.right) && isComparand(node.left))) tested = true;+ } else if (ts.isCallExpression(node) && node.arguments[0] && isCodeRead(node.arguments[0])) {+ const callee = strip(node.expression);+ if (ts.isPropertyAccessExpression(callee) && (callee.name.text === 'has' || callee.name.text === 'includes')) tested = true;+ } else if (ts.isSwitchStatement(node) && isCodeRead(node.expression)) {+ tested = true;+ }+ ts.forEachChild(node, findTest);+ };+ ts.forEachChild(block, findTest);+ if (!tested) return false;++ let rethrows = false;+ const findRethrow = (node: ts.Node): void => {+ if (ts.isThrowStatement(node) && isError(node.expression)) rethrows = true;+ if (!isFunctionBoundary(node)) ts.forEachChild(node, findRethrow);+ };+ ts.forEachChild(block, findRethrow);+ return rethrows;+}++/** Every allowlist-and-rethrow catch inside a per-item loop in one source file. */+export function findAllowlistCatches(path: string, text: string): AllowlistCatch[] {+ const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ const found: AllowlistCatch[] = [];+ const visit = (node: ts.Node): void => {+ if (ts.isCatchClause(node) && node.variableDeclaration && ts.isIdentifier(node.variableDeclaration.name)+ && inPerItemLoop(node) && testsCodeAndRethrows(node.block, node.variableDeclaration.name.text)) {+ found.push({ path, line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1 });+ }+ ts.forEachChild(node, visit);+ };+ visit(sf);+ return found;+}++/**+ * Compares per-file site counts with the baseline text and returns every+ * violation. `exists` says whether a baselined path is still a scanned source+ * file, so a row for a deleted file reads differently from one whose sites are gone.+ */+export function compareBaseline(sites: AllowlistCatch[], baselineText: string, exists: (path: string) => boolean = () => true): string[] {+ const problems: string[] = [];+ const rows = new Map<string, number>();+ let sawHeader = false;+ let prev = '';+ baselineText.split('\n').forEach((raw, i) => {+ if (!raw.trim() || raw.startsWith('#')) return;+ if (raw === HEADER) { sawHeader = true; return; }+ const cols = raw.split('\t');+ const count = Number(cols[1]);+ if (cols.length !== 2 || !cols[0] || !/^\d+$/.test(cols[1] ?? '') || count < 1) {+ problems.push(`FAIL: ${BASELINE_REL}:${i + 1} malformed row (want path<TAB>count, count >= 1)`);+ return;+ }+ if (rows.has(cols[0])) problems.push(`FAIL: ${BASELINE_REL}:${i + 1} duplicate row for ${cols[0]}`);+ if (prev && cols[0] < prev) problems.push(`FAIL: ${BASELINE_REL}:${i + 1} rows must be sorted by path`);+ prev = cols[0];+ rows.set(cols[0], count);+ });+ if (!sawHeader) problems.push(`FAIL: ${BASELINE_REL} is missing the header line "path<TAB>count"`);++ const byFile = new Map<string, number[]>();+ for (const site of sites) byFile.set(site.path, [...(byFile.get(site.path) ?? []), site.line]);+ for (const [path, lines] of byFile) {+ const allowed = rows.get(path) ?? 0;+ if (lines.length > allowed) {+ problems.push(`FAIL: ${path} has ${lines.length} allowlist-and-rethrow catch(es) in per-item loops, over its baseline of ${allowed}\n`+ + ` sites: ${lines.map(line => `${path}:${line}`).join(', ')}`);+ } else if (lines.length < allowed) {+ problems.push(`FAIL: ${path} dropped to ${lines.length} site(s); lower its baseline row from ${allowed} to ${lines.length}`);+ }+ }+ for (const path of rows.keys()) {+ if (byFile.has(path)) continue;+ problems.push(exists(path) ? `FAIL: ${path} has no allowlist-and-rethrow catches left: remove its baseline row`+ : `FAIL: ${path} no longer exists: remove its baseline row`);+ }+ return problems;+}++/** The baseline for `sites`: header, then one `path<TAB>count` row per file, sorted by path. */+export function formatBaseline(sites: AllowlistCatch[], preamble = ''): string {+ const counts = new Map<string, number>();+ for (const site of sites) counts.set(site.path, (counts.get(site.path) ?? 0) + 1);+ const rows = [...counts.keys()].sort().map(path => `${path}\t${counts.get(path)}`);+ return preamble + [HEADER, ...rows].join('\n') + '\n';+}++function srcFiles(root: string): string[] {+ const out: string[] = [];+ const walk = (dir: string): void => {+ if (!existsSync(dir)) return;+ for (const entry of readdirSync(dir).sort()) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) walk(full);+ else if (entry.endsWith('.ts') && !entry.endsWith('.generated.ts') && !entry.endsWith('.d.ts')) out.push(relative(root, full));+ }+ };+ walk(join(root, 'src'));+ return out;+}++function main(): number {+ const git = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' });+ const root = process.env.GBRAIN_GUARD_ROOT ?? (git.status === 0 ? git.stdout.trim() : process.cwd());+ const baselinePath = join(root, BASELINE_REL);+ const files = srcFiles(root);+ const sites = files.flatMap(f => findAllowlistCatches(f, readFileSync(join(root, f), 'utf8')));+ const summary = `${sites.length} site(s) in ${new Set(sites.map(s => s.path)).size} file(s)`;+ const baselineText = existsSync(baselinePath) ? readFileSync(baselinePath, 'utf8') : null;++ if (process.argv.includes('--update')) {+ const preamble = (baselineText ?? '').split('\n').findIndex(line => !line.startsWith('#'));+ const kept = baselineText && preamble > 0 ? baselineText.split('\n').slice(0, preamble).join('\n') + '\n' : '';+ writeFileSync(baselinePath, formatBaseline(sites, kept));+ console.log(`wrote ${BASELINE_REL}: ${summary}; review the diff (rows only shrink)`);+ return 0;+ }+ if (baselineText === null) {+ console.error(`FAIL: ${BASELINE_REL} not found under ${root}`);+ return 1;+ }+ const scanned = new Set(files);+ const problems = compareBaseline(sites, baselineText, path => scanned.has(path));+ if (problems.length) {+ for (const p of problems) console.error(p);+ console.error('Why: a per-item catch that rethrows every error code its list misses lets one bad item stop the whole unit;');+ console.error(' the baseline only shrinks.');+ console.error('Fix: classify the failure with classifyItemFailure / ItemRun (src/core/item-failure.ts), register the site in');+ console.error(' ISOLATE_SITES and cover it in test/pathological/ (catalogue.ts + harness.ts); after a shrink run');+ console.error(` bun scripts/check-item-allowlist-catches.ts --update. Raising or adding a row does not pass review.`);+ console.error(`See: ${ANCHOR}`);+ console.error(`item-allowlist-catches: ${problems.length} violation(s); ${summary}`);+ return 1;+ }+ console.log(`OK: item allowlist catches match ${BASELINE_REL} (${summary})`);+ return 0;+}++if (import.meta.main) process.exit(main());diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex 9c3a3352b8..5dd43da431 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -64,6 +64,7 @@ check-no-tracked-symlinks.sh repostate exempt git index state checkcheck-grok-pin.sh repostate exempt pin-stamp drift check (GROK-CLI-PIN.md stamps vs heavy-tests grok-door env); own bun guard tests in test/check-bootstrap-guards.test.tscheck-module-size.sh scanner yes committed per-file line ceilings (module-size-limits.tsv); growth + stale-ceiling + missing-row + new-file capcheck-function-size.ts scanner yes W5 per-function line ratchet (TS compiler API): new >300-line function, growth, shrink-below-limit, stale slack, missing row, raise without issue/TODO id; baseline scripts/function-size-baseline.tsv keyed by path + name path; --transfer for verified move-only commits+check-item-allowlist-catches.ts scanner yes GBRA-130 per-item allowlist-catch ratchet (TS compiler API): a catch in a loop body or forEach/map callback that tests the caught error code against a set/list/literal and rethrows it; per-file counts in scripts/item-allowlist-catches-baseline.tsv only shrink (growth, stale row, zero/missing-file row, malformed rows fail); --update rewrites for shrinkscheck-engine-sql-ratchet.ts scanner yes goal (a) engine-sql ratchet (TS AST): SQL-bearing engine members (façade classes + pglite-engine/ and postgres-engine/ modules) need a baseline row or an engine-sql-ok marker; stale/duplicate rows and unbacked migrated domains fail; baseline scripts/engine-sql-baseline.tsv; --prune drops stale rows onlycheck-page-body-readers.ts scanner yes Wave B segmented storage (spec 1.5 layer 4, TS AST): src units reading .compiled_truth/.timeline, SQL literals naming the body columns or p.* from pages, and whole-body calls (serializePageToMarkdown, putPage, ...) need a baseline row with an action code; stale/duplicate/malformed rows fail; boundedBodyPrefixSql allowed by name; baseline scripts/page-body-readers-baseline.tsv; --prune drops stale rows onlycheck-engine-sql-dynamic.ts scanner yes CQ3/EO17 dynamic SQL in src/core/engine-sql/** (TS AST; fragment.ts exempt as the renderer): trustedSql args and composed .query/.unsafe/.executeRaw/executeRawJsonb SQL splice only literals, as-const/allowlisted constants, VETTED_BUILDERS calls or Number.isFinite-checked numbers; no $<digit> in composed strings; no expanded IN listsdiff --git a/scripts/item-allowlist-catches-baseline.tsv b/scripts/item-allowlist-catches-baseline.tsvnew file mode 100644index 0000000000..4c6698441b--- /dev/null+++ b/scripts/item-allowlist-catches-baseline.tsv@@ -0,0 +1,36 @@+path count+src/commands/extract-timeline-db.ts 1+src/commands/frontmatter.ts 1+src/commands/lint.ts 1+src/commands/reconcile-links.ts 1+src/commands/reindex-aliases.ts 1+src/core/agent-install/state.ts 1+src/core/autopilot-paths.ts 1+src/core/belief/backfill.ts 1+src/core/bootstrap/render.ts 1+src/core/context/ipc-path.ts 1+src/core/cycle/conversation-facts-backfill.ts 1+src/core/cycle/extract-facts.ts 2+src/core/cycle/extract-takes.ts 1+src/core/destructive-guard.ts 1+src/core/export-publish.ts 1+src/core/persistence/bundle-files.ts 2+src/core/persistence/control.ts 1+src/core/persistence/git-durability-administration.ts 1+src/core/persistence/native-file-target.ts 1+src/core/persistence/provider.ts 1+src/core/persistence/reconcile-audit.ts 1+src/core/persistence/root-registry.ts 1+src/core/persistence/staging.ts 1+src/core/persistence/sync-drain.ts 1+src/core/persistence/topology-filesystem.ts 2+src/core/persistence/topology-recovery.ts 1+src/core/persistence/worktree-manifest.ts 1+src/core/persistence/worktree-refresh.ts 1+src/core/pglite-lock.ts 1+src/core/pglite-repair.ts 1+src/core/repair/core.ts 1+src/core/repair/extractor-facts.ts 1+src/core/repair/file-drift.ts 1+src/core/skillpack/harness-bridge.ts 1+src/core/skillpack/writer-guard.ts 1diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex bf06fb9d24..ba6a3a1ec3 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -162,6 +162,9 @@ CHECKS=(# W5 (refactor wave 1): per-function line ratchet over src/**/*.ts (TS AST,# ~1.5s); baseline scripts/function-size-baseline.tsv."check:function-size"+ # GBRA-130: per-item catches that test an error code against a list and+ # rethrow the rest only shrink; baseline scripts/item-allowlist-catches-baseline.tsv.+ "check:item-allowlist-catches"# EO10 (refactor wave 1): engine-sql/ and schema-migrations/ never import# back up into the engine façades or migrate.ts (ESM TDZ cycles)."check:layering"diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 1352064a01..ba3faad5d9 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -284,6 +284,7 @@ test/schema-pack/suggest.test.ts runSuggest — source-text contract (structuraltest/scripts/build-schema-migrations.test.ts generator diagnostics (FAIL/Why/Fix/See) 9 exec-scantest/scripts/build-schema-migrations.test.ts out-of-order landing check 2 exec-scantest/scripts/check-function-size.test.ts check-function-size.ts rules 11 readFileSync+test/scripts/check-item-allowlist-catches.test.ts CLI 2 readFileSynctest/scripts/chunk-visibility-ratchet.test.ts check-chunk-visibility.ts 6 readFileSynctest/scripts/ci-bounded-run.test.ts (file-level) 7 readFileSynctest/scripts/ci-executed-counts.test.ts CLI 2 readFileSyncdiff --git a/test/fixtures/guards/check-item-allowlist-catches.ts/bad-stale/scripts/item-allowlist-catches-baseline.tsv b/test/fixtures/guards/check-item-allowlist-catches.ts/bad-stale/scripts/item-allowlist-catches-baseline.tsvnew file mode 100644index 0000000000..245f3b0b11--- /dev/null+++ b/test/fixtures/guards/check-item-allowlist-catches.ts/bad-stale/scripts/item-allowlist-catches-baseline.tsv@@ -0,0 +1,2 @@+path count+src/import-all.ts 2diff --git a/test/fixtures/guards/check-item-allowlist-catches.ts/bad-stale/src/contract.ts b/test/fixtures/guards/check-item-allowlist-catches.ts/bad-stale/src/contract.tsnew file mode 100644index 0000000000..7caef958b3--- /dev/null+++ b/test/fixtures/guards/check-item-allowlist-catches.ts/bad-stale/src/contract.ts@@ -0,0 +1,3 @@+export class OperationError extends Error {+ constructor(readonly code: string, message: string) { super(message); }+}diff --git a/test/fixtures/guards/check-item-allowlist-catches.ts/bad-stale/src/import-all.ts b/test/fixtures/guards/check-item-allowlist-catches.ts/bad-stale/src/import-all.tsnew file mode 100644index 0000000000..55dc9abcc6--- /dev/null+++ b/test/fixtures/guards/check-item-allowlist-catches.ts/bad-stale/src/import-all.ts@@ -0,0 +1,16 @@+import { OperationError } from './contract.ts';++const SKIP = new Set(['page_not_found', 'revision_conflict']);++export async function importAll(slugs: string[], put: (slug: string) => Promise<void>): Promise<string[]> {+ const skipped: string[] = [];+ for (const slug of slugs) {+ try {+ await put(slug);+ } catch (error) {+ if (!(error instanceof OperationError) || !SKIP.has(error.code)) throw error;+ skipped.push(slug);+ }+ }+ return skipped;+}diff --git a/test/fixtures/guards/check-item-allowlist-catches.ts/bad/scripts/item-allowlist-catches-baseline.tsv b/test/fixtures/guards/check-item-allowlist-catches.ts/bad/scripts/item-allowlist-catches-baseline.tsvnew file mode 100644index 0000000000..26db5da9c9--- /dev/null+++ b/test/fixtures/guards/check-item-allowlist-catches.ts/bad/scripts/item-allowlist-catches-baseline.tsv@@ -0,0 +1 @@+path countdiff --git a/test/fixtures/guards/check-item-allowlist-catches.ts/bad/src/contract.ts b/test/fixtures/guards/check-item-allowlist-catches.ts/bad/src/contract.tsnew file mode 100644index 0000000000..7caef958b3--- /dev/null+++ b/test/fixtures/guards/check-item-allowlist-catches.ts/bad/src/contract.ts@@ -0,0 +1,3 @@+export class OperationError extends Error {+ constructor(readonly code: string, message: string) { super(message); }+}diff --git a/test/fixtures/guards/check-item-allowlist-catches.ts/bad/src/import-all.ts b/test/fixtures/guards/check-item-allowlist-catches.ts/bad/src/import-all.tsnew file mode 100644index 0000000000..55dc9abcc6--- /dev/null+++ b/test/fixtures/guards/check-item-allowlist-catches.ts/bad/src/import-all.ts@@ -0,0 +1,16 @@+import { OperationError } from './contract.ts';++const SKIP = new Set(['page_not_found', 'revision_conflict']);++export async function importAll(slugs: string[], put: (slug: string) => Promise<void>): Promise<string[]> {+ const skipped: string[] = [];+ for (const slug of slugs) {+ try {+ await put(slug);+ } catch (error) {+ if (!(error instanceof OperationError) || !SKIP.has(error.code)) throw error;+ skipped.push(slug);+ }+ }+ return skipped;+}diff --git a/test/fixtures/guards/check-item-allowlist-catches.ts/good/scripts/item-allowlist-catches-baseline.tsv b/test/fixtures/guards/check-item-allowlist-catches.ts/good/scripts/item-allowlist-catches-baseline.tsvnew file mode 100644index 0000000000..971de03aaf--- /dev/null+++ b/test/fixtures/guards/check-item-allowlist-catches.ts/good/scripts/item-allowlist-catches-baseline.tsv@@ -0,0 +1,2 @@+path count+src/import-all.ts 1diff --git a/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/clean.ts b/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/clean.tsnew file mode 100644index 0000000000..b4fb62136d--- /dev/null+++ b/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/clean.ts@@ -0,0 +1,17 @@+import { OperationError } from './contract.ts';++export async function once(put: () => Promise<void>): Promise<boolean> {+ try {+ await put();+ return true;+ } catch (error) {+ if (error instanceof OperationError && error.code === 'page_not_found') return false;+ throw error;+ }+}++export async function each(slugs: string[], put: (slug: string) => Promise<void>, log: (e: unknown) => void): Promise<void> {+ for (const slug of slugs) {+ try { await put(slug); } catch (error) { log(error); }+ }+}diff --git a/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/contract.ts b/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/contract.tsnew file mode 100644index 0000000000..7caef958b3--- /dev/null+++ b/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/contract.ts@@ -0,0 +1,3 @@+export class OperationError extends Error {+ constructor(readonly code: string, message: string) { super(message); }+}diff --git a/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/import-all.ts b/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/import-all.tsnew file mode 100644index 0000000000..55dc9abcc6--- /dev/null+++ b/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/import-all.ts@@ -0,0 +1,16 @@+import { OperationError } from './contract.ts';++const SKIP = new Set(['page_not_found', 'revision_conflict']);++export async function importAll(slugs: string[], put: (slug: string) => Promise<void>): Promise<string[]> {+ const skipped: string[] = [];+ for (const slug of slugs) {+ try {+ await put(slug);+ } catch (error) {+ if (!(error instanceof OperationError) || !SKIP.has(error.code)) throw error;+ skipped.push(slug);+ }+ }+ return skipped;+}diff --git a/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/table.generated.ts b/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/table.generated.tsnew file mode 100644index 0000000000..55dc9abcc6--- /dev/null+++ b/test/fixtures/guards/check-item-allowlist-catches.ts/good/src/table.generated.ts@@ -0,0 +1,16 @@+import { OperationError } from './contract.ts';++const SKIP = new Set(['page_not_found', 'revision_conflict']);++export async function importAll(slugs: string[], put: (slug: string) => Promise<void>): Promise<string[]> {+ const skipped: string[] = [];+ for (const slug of slugs) {+ try {+ await put(slug);+ } catch (error) {+ if (!(error instanceof OperationError) || !SKIP.has(error.code)) throw error;+ skipped.push(slug);+ }+ }+ return skipped;+}diff --git a/test/scripts/check-item-allowlist-catches.test.ts b/test/scripts/check-item-allowlist-catches.test.tsnew file mode 100644index 0000000000..3b978a3a5f--- /dev/null+++ b/test/scripts/check-item-allowlist-catches.test.ts@@ -0,0 +1,171 @@+/**+ * scripts/check-item-allowlist-catches.ts (GBRA-130): which catches count as+ * per-item allowlist-and-rethrow sites, how per-file counts compare with the+ * shrink-only baseline, and the CLI's exit code and FAIL/Why/Fix/See block,+ * driven through GBRAIN_GUARD_ROOT temp trees.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { compareBaseline, findAllowlistCatches, formatBaseline } from '../../scripts/check-item-allowlist-catches.ts';++const GUARD = join(resolve(import.meta.dir, '..', '..'), 'scripts', 'check-item-allowlist-catches.ts');+const HEADER = 'path\tcount';+const tempDirs: string[] = [];++afterEach(() => {+ for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++const lines = (src: string) => findAllowlistCatches('src/x.ts', src).map(s => s.line);+const allowlistCatch = (v = 'e') => `catch (${v}) { if (!SKIP.has((${v} as any).code)) throw ${v}; }`;++describe('findAllowlistCatches', () => {+ test('an allowlist-and-rethrow catch inside for, for-of, for-in, while and do-while counts', () => {+ const src = [+ 'for (const slug of slugs) {',+ ` try { put(slug); } ${allowlistCatch()}`,+ '}',+ `for (let i = 0; i < n; i++) { try { put(i); } ${allowlistCatch()} }`,+ `for (const k in table) { try { put(k); } ${allowlistCatch()} }`,+ `while (more()) { try { put(next()); } ${allowlistCatch()} }`,+ `do { try { put(next()); } ${allowlistCatch()} } while (more());`,+ ].join('\n');+ expect(lines(src)).toEqual([2, 4, 5, 6, 7]);+ });++ test('inside a .forEach or .map callback it counts', () => {+ const src = [+ `slugs.forEach((slug) => { try { put(slug); } ${allowlistCatch('err')} });`,+ `await Promise.all(slugs.map(async function (slug) { try { await put(slug); } ${allowlistCatch()} }));`,+ ].join('\n');+ expect(lines(src)).toEqual([1, 2]);+ });++ test('every code-test form counts, through casts, optional chains and aliases', () => {+ const forms = [+ "if (e.code === '23503') { blocked.push(slug); continue; } throw e;",+ "if (e?.code !== 'ENOENT') throw e;",+ "if (![\"a\", \"b\"].includes((e as { code: string }).code)) throw e;",+ "const code = (e as { code?: string }).code; if (code === 'ENOENT') continue; throw e;",+ 'const { code } = e as NodeJS.ErrnoException; if (!SKIP.has(code!)) throw e;',+ "const err = e as PgError; if (err.code !== CODES.FK) { throw err; }",+ "switch (e.code) { case 'ENOENT': continue; default: throw e; }",+ "if (e instanceof OperationError && e.code === 'page_not_found') { skipped++; } else { if (ready) throw e; }",+ ];+ const src = forms.map(body => `for (const slug of slugs) { try { put(slug); } catch (e) { ${body} } }`).join('\n');+ expect(lines(src)).toEqual(forms.map((_, i) => i + 1));+ });++ test('a loop catch without a code test, without a rethrow, or rethrowing something else does not count', () => {+ const src = [+ 'for (const s of slugs) { try { put(s); } catch (e) { log(e); throw e; } }',+ "for (const s of slugs) { try { put(s); } catch (e) { if (SKIP.has(e.code)) skipped.push(s); } }",+ "for (const s of slugs) { try { put(s); } catch (e) { if (e.code !== 'x') throw new Error('wrapped'); } }",+ "for (const s of slugs) { try { put(s); } catch (e) { if (e.code === undefined) throw e; } }",+ "for (const s of slugs) { try { put(s); } catch (e) { if (e.code !== 'x') later(() => { throw e; }); } }",+ "for (const s of slugs) { try { put(s); } catch { skipped++; } }",+ ].join('\n');+ expect(lines(src)).toEqual([]);+ });++ test('outside a loop, in a loop header, or in a function declared in a loop body it does not count', () => {+ const src = [+ `function once() { try { put(); } ${allowlistCatch()} }`,+ `for (const s of (() => { try { return load(); } ${allowlistCatch()} })()) put(s);`,+ `for (const s of slugs) { const run = () => { try { put(s); } ${allowlistCatch()} }; queue(run); }`,+ `slugs.filter((s) => { try { return check(s); } ${allowlistCatch()} });`,+ ].join('\n');+ expect(lines(src)).toEqual([]);+ });++ test('a loop inside a nested function counts at that function\'s level', () => {+ const src = [+ 'function outer() {',+ ` const each = (slugs: string[]) => { for (const s of slugs) { try { put(s); } ${allowlistCatch()} } };`,+ '}',+ ].join('\n');+ expect(lines(src)).toEqual([2]);+ });+});++describe('compareBaseline', () => {+ const sites = [{ path: 'src/a.ts', line: 3 }, { path: 'src/a.ts', line: 9 }, { path: 'src/b.ts', line: 1 }];++ test('an exact match passes and formatBaseline writes it', () => {+ const text = formatBaseline(sites);+ expect(text).toBe(`${HEADER}\nsrc/a.ts\t2\nsrc/b.ts\t1\n`);+ expect(compareBaseline(sites, text)).toEqual([]);+ });++ test('growth past a row, and sites in a file with no row, fail with the site lines', () => {+ const problems = compareBaseline(sites, `${HEADER}\nsrc/a.ts\t1\n`);+ expect(problems).toHaveLength(2);+ expect(problems[0]).toContain('src/a.ts has 2 allowlist-and-rethrow catch(es) in per-item loops, over its baseline of 1');+ expect(problems[0]).toContain('sites: src/a.ts:3, src/a.ts:9');+ expect(problems[1]).toContain('src/b.ts has 1 allowlist-and-rethrow catch(es) in per-item loops, over its baseline of 0');+ });++ test('a shrink without lowering the row fails', () => {+ expect(compareBaseline(sites, `${HEADER}\nsrc/a.ts\t3\nsrc/b.ts\t1\n`))+ .toEqual(['FAIL: src/a.ts dropped to 2 site(s); lower its baseline row from 3 to 2']);+ });++ test('a row for a file with no sites, or a missing file, fails', () => {+ const text = `${HEADER}\nsrc/a.ts\t2\nsrc/b.ts\t1\nsrc/c.ts\t1\nsrc/gone.ts\t1\n`;+ expect(compareBaseline(sites, text, path => path !== 'src/gone.ts')).toEqual([+ 'FAIL: src/c.ts has no allowlist-and-rethrow catches left: remove its baseline row',+ 'FAIL: src/gone.ts no longer exists: remove its baseline row',+ ]);+ });++ test('malformed, zero, duplicate and unsorted rows and a missing header fail', () => {+ const ok = 'src/a.ts\t2\nsrc/b.ts\t1';+ expect(compareBaseline(sites, `${HEADER}\n${ok}\nsrc/c.ts\ttwo\n`).join('\n')).toContain(':4 malformed row');+ expect(compareBaseline(sites, `${HEADER}\n${ok}\nsrc/c.ts\t0\n`).join('\n')).toContain(':4 malformed row');+ expect(compareBaseline(sites, `${HEADER}\n${ok}\nsrc/b.ts\t1\n`).join('\n')).toContain(':4 duplicate row for src/b.ts');+ expect(compareBaseline(sites, `${HEADER}\nsrc/b.ts\t1\nsrc/a.ts\t2\n`).join('\n')).toContain(':3 rows must be sorted by path');+ expect(compareBaseline(sites, `${ok}\n`).join('\n')).toContain('missing the header line');+ });+});++describe('CLI', () => {+ const site = `for (const s of slugs) { try { put(s); } ${allowlistCatch()} }\n`;++ function makeTree(files: Record<string, string>, baseline: string): string {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-item-allowlist-'));+ tempDirs.push(root);+ for (const [rel, content] of Object.entries({ ...files, 'scripts/item-allowlist-catches-baseline.tsv': baseline })) {+ mkdirSync(join(root, rel, '..'), { recursive: true });+ writeFileSync(join(root, rel), content);+ }+ return root;+ }++ function runGuard(root: string, args: string[] = []) {+ const res = spawnSync('bun', [GUARD, ...args], { encoding: 'utf8', env: { ...process.env, GBRAIN_GUARD_ROOT: root }, timeout: 30_000 });+ return { code: res.status ?? -1, stdout: res.stdout, stderr: res.stderr };+ }++ test('growth exits 1 with FAIL/Why/Fix/See pointing at item-failure.ts and test/pathological/; a match exits 0 with a summary', () => {+ const files = { 'src/a.ts': site + site, 'src/a.generated.ts': site, 'src/a.d.ts': 'export declare const x: number;\n', 'test/a.test.ts': site };+ const bad = runGuard(makeTree(files, `${HEADER}\nsrc/a.ts\t1\n`));+ expect(bad.code).toBe(1);+ expect(bad.stderr).toContain('FAIL: src/a.ts has 2 allowlist-and-rethrow catch(es) in per-item loops, over its baseline of 1');+ for (const label of ['Why:', 'Fix:', 'src/core/item-failure.ts', 'classifyItemFailure / ItemRun', 'test/pathological/', 'See: docs/TESTING.md#pathological-states']) {+ expect(bad.stderr).toContain(label);+ }+ const good = runGuard(makeTree(files, `${HEADER}\nsrc/a.ts\t2\n`));+ expect({ code: good.code, stdout: good.stdout.trim() }).toEqual({ code: 0, stdout: 'OK: item allowlist catches match scripts/item-allowlist-catches-baseline.tsv (2 site(s) in 1 file(s))' });+ });++ test('--update rewrites the baseline from the tree, keeping the comment preamble', () => {+ const root = makeTree({ 'src/b.ts': site, 'src/a.ts': site }, `# shrink-only\n${HEADER}\nsrc/a.ts\t3\nsrc/z.ts\t1\n`);+ expect(runGuard(root).code).toBe(1);+ expect(runGuard(root, ['--update']).code).toBe(0);+ expect(readFileSync(join(root, 'scripts/item-allowlist-catches-baseline.tsv'), 'utf8')).toBe(`# shrink-only\n${HEADER}\nsrc/a.ts\t1\nsrc/b.ts\t1\n`);+ expect(runGuard(root).code).toBe(0);+ });+});