Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(testing): pathological states and the allowlist-catch ratchet (GBRA-130)

garrytan331232a7b8eb
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 440aed3897..2a7dd932c3 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -852,16 +852,8 @@ build. A guard whose pattern rots into a permanently-green no-op fails CI
instead of masquerading as coverage.
A guard may carry extra known-bad trees named `bad-<variant>/`; each one must
-fail on its own. Refactor wave 1 uses them to prove that every scanner naming
-a file the wave splits also scans the new module locations
-(`src/core/engine-sql/`, `src/core/schema-migrations/`, `src/commands/sync/`,
-`src/commands/doctor/checks/`, `src/commands/serve-http-*.ts`,
-`src/core/minions/handlers/`): `check-jsonb-pattern.sh`,
-`check-engine-dynamic-import.sh`, `check-source-config-leak.sh`,
-`check-no-legacy-getconnection.sh`, `check-operations-filter-bypass.sh`,
-`check-source-id-projection.sh` (engine-sql) and `check-search-path.sh` (the
-generated PGLite template) each have a bad fixture placed inside the new path. The checklist
-of every script, workflow, helper and doc that names a split file is
+fail on its own. Refactor wave 1 adds one inside each split module location for
+every scanner that names a split file, listed in
[`docs/designs/refactor-wave-1/path-consumers.md`](designs/refactor-wave-1/path-consumers.md).
#### Layering guard
@@ -1090,18 +1082,15 @@ general; the authoring gate above owns that.
`scripts/check-function-size.ts` (`bun run check:function-size`, in
`bun run verify`, about 1.5 s) measures every function-like node in
`src/**/*.ts` except `*.generated.ts` and `.d.ts` with the TypeScript compiler
-API: function declarations, methods, constructors, accessors, arrow functions
-and function expressions, including object-literal and class-property forms.
-A nested function is measured on its own, and its lines also count toward the
-function that contains it. Code under `test/` is out of scope.
+API, every function form included. A nested function is measured on its own
+and also counts toward its parent. Code under `test/` is out of scope.
`scripts/function-size-baseline.tsv` holds one row per function over 300
lines: `path`, `name`, `lines`, `justification`. The name is a path built from
declarations, property names and call context, never line numbers, so edits
above a function do not touch its row: `PGLiteEngine.initSchema`,
-`runServeHttp>app.post('/mcp')`, `MIGRATIONS[v131].handler`. `>` enters a
-function, `.` a member, `=` a call whose result is bound, and a repeated key
-gets a `#2` ordinal. The guard fails when a function over 300 lines has no
+`runServeHttp>app.post('/mcp')`, `MIGRATIONS[v131].handler` (key grammar in the
+script header). The guard fails when a function over 300 lines has no
row, a baselined function grows, a baselined function drops to 300 lines or
fewer (remove the row), a row has more than 50 lines of stale slack (lower
it), a row names a function that no longer exists, or a row is malformed,
@@ -1113,17 +1102,31 @@ raise.
Each failure prints `FAIL: <file:line> <what>` with the computed key, then one
`Why:` / `Fix:` / `See:` block. The fix is extraction: move a cohesive block
into a named helper or sibling module (phase, stage or handler-table pattern).
-After a move-only commit changes a function's key, run
-`bun scripts/check-function-size.ts --transfer`. It rewrites a missing row to
-the one unbaselined over-limit function whose whitespace-normalized text is
-identical to the old function at `HEAD` (`--from <ref>` for another base),
-apart from an added leading `export` and module specifiers re-relativized to
-the new directory (each resolved against its own file, so a retargeted
-specifier still refuses), keeping lines and justification, and leaves
-everything else for review.
+After a move-only commit changes a function's key,
+`bun scripts/check-function-size.ts --transfer` moves the row to the
+verified identical function (rules in the script header).
Fixtures: `test/fixtures/guards/check-function-size.ts/{bad,good}`; every rule
is driven in `test/scripts/check-function-size.test.ts`.
+### Pathological states
+
+`test/pathological/` holds one file per GBRA-130 inventory row,
+`<row>-<short-name>.test.ts`. `catalogue.ts` maps each `ISOLATE_SITES` key
+(`src/core/item-failure.ts`) to its file, item-case and run-case titles;
+`sites.test.ts` enforces it. `harness.ts` asserts the unit was not aborted
+(`expectUnitNotAborted`), the bad item has a typed code and fix
+(`expectItemFailure`) and nothing else changed (`snapshotItems`,
+`expectOthersUnchanged`; `expectProgress` names siblings that must move). The run
+case injects `runScopedErrors()` and expects a stop with no hold.
+`pathologicalArms()` is PGLite always plus Postgres with `DATABASE_URL`; list
+Postgres-arm files in `test/postgres-unit-arms.txt`.
+
+`bun run check:item-allowlist-catches` (verify) counts catches in a loop body or
+`.forEach`/`.map` callback that test the caught error's code against a set, list or
+literal and rethrow it. Per-file counts in `scripts/item-allowlist-catches-baseline.tsv`
+only shrink; stale, empty or malformed rows fail. `--update` rewrites it after a
+shrink; a raised row fails review. Rules and blind spots: script header.
+
### SyncRun state guard
`scripts/check-sync-run-state.ts` (`bun run check:sync-run-state`, in
diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.md
index 02ffd36f37..bc5300bf68 100644
--- a/docs/architecture/key-files/ci-health-and-test-guards.md
+++ b/docs/architecture/key-files/ci-health-and-test-guards.md
@@ -20,6 +20,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/scale/watchdog.ts` — out-of-process phase watchdog for the scale harness. `scripts/scale/run.ts` re-runs itself as a child; the supervisor times the `import`, `extract`, `vectors` and `budgets` phases from the child's `[scale] phase <name> start` lines and kills the child's process group at 1.5x the phase's gate ceiling (`scripts/scale/gates.ts` `phaseLimitsMs`), names the phase, elapsed time and last progress line, then removes the brain home and scale database. `GBRAIN_SCALE_PHASE_LIMIT_MS_<PHASE>` overrides one limit; `GBRAIN_SCALE_SUPERVISED` is the internal handshake. Tests: `test/scripts/scale-watchdog.test.ts`.
- `scripts/check-test-env-opt-ins.ts` + `test/helpers/operator-env-policy.ts` — the opt-in naming rule. The policy (`STRIP_PREFIX`, `KEEP_EXACT`, `KEEP_PREFIX`, `RENAMED`, `isStripped`) is shared by `test/helpers/operator-env-preload.ts`, which deletes stripped `GBRAIN_*` names before any test loads and stops the run with the rename command when an old opt-in name is set, and by the guard (`check:test-env-opt-ins`, in `verify`), which parses test files and fails on a test that gates execution on a stripped name. Test opt-ins are `GBRAIN_TEST_<AREA>_<WHAT>`, paid ones `GBRAIN_TEST_LIVE_<WHAT>`. The same guard fails `test_env_snapshot_module_scope`: a `delete` of or assignment to `process.env.GBRAIN_PGLITE_SNAPSHOT` outside every function body in a file the unit matrix loads (`*.serial.test.ts`, `test/e2e/` and `*-preload.ts` are exempt: own process, or process-wide by design). `scripts/test-shard.sh` runs a whole shard in one bun process, so such a change persists for every later file and each of their PGLite engines cold-boots (~3 s); the accepted shape is save+delete in `beforeAll`, restore in `afterAll`, or `test/helpers/with-snapshot.ts` per test. Tests: `test/scripts/test-env-opt-ins-guard.test.ts`, `test/operator-env-preload.test.ts`.
- `scripts/check-postgres-lane-coverage.ts` — `check:postgres-lanes` (in `verify`). TypeScript-AST scan of every `test/` file outside `test/e2e/` and `test/fixtures/` for a `DATABASE_URL`-gated PostgreSQL arm (zero-argument `testBackends()`, or a `DATABASE_URL` read used as a condition, connection argument or `database_url` value; `withEnv`-supplied URLs excluded) and a lane that runs it (a workflow step with `DATABASE_URL` naming the file, a `test/e2e/` importer, a `tests/heavy/` script, or a `scripts/e2e-backend-matrix.txt` row). `ALLOWLIST` rows name a reason and TODO; stale rows fail. A `test/postgres-unit-arms.txt` row is a lane; a malformed, duplicate, unsorted, missing-file or arm-less row fails (`postgres_arm_list_invalid`, `postgres_arm_list_stale`). `postgresArm`, `postgresLanes` and `armedFiles` are exported for the stress runner. Tests: `test/scripts/postgres-lane-coverage.test.ts`.
+- `scripts/check-item-allowlist-catches.ts` + `scripts/item-allowlist-catches-baseline.tsv` — `check:item-allowlist-catches` (in `verify`). TypeScript-AST scan of `src/**/*.ts` (no `*.generated.ts`, `.d.ts`) for catch clauses in a per-item loop (a for/for-of/for-in/while/do-while body, or a `.forEach`/`.map` callback, up to the nearest function boundary) whose block tests the caught error's code against a set, list or literal (direct, cast, aliased or destructured) and rethrows the caught error. Per-file counts only shrink: growth, a new file, a count under its row, a row with no sites or no file, and malformed, duplicate or unsorted rows fail, pointing at `classifyItemFailure` / `ItemRun` (`src/core/item-failure.ts`) and `test/pathological/`. `--update` rewrites the baseline after a shrink. `findAllowlistCatches` and `compareBaseline` are exported for `test/scripts/check-item-allowlist-catches.test.ts`; self-test fixtures under `test/fixtures/guards/check-item-allowlist-catches.ts/`.
- `test/postgres-unit-arms.txt` + `scripts/postgres-unit-arms.ts` + `scripts/postgres-arm-weights.json` — the one list of unit-lane files whose PostgreSQL arm has no other owner (sorted, one path per line, `#` comments). Read by persistence-validation.yml's `unit-postgres-arms` job (`ARM_SHARDS` = 14 shards, `shard <n> <m>`: LPT over the mined per-file weights, p75 fallback; one Bun process per file; each shard's weighted sum at most `ARM_SHARD_BUDGET_MS`, 570 s, so twice that still ends a minute inside the 20-minute `ARM_STEP_TIMEOUT_MS` step), the scheduled race hunt and the lane guard. `mine <job.log>…` rewrites the weights from a green run's shard logs (`##[group]<file>` to the next group or endgroup). Tests: `test/scripts/postgres-unit-arms.test.ts`.
- `scripts/serial-files.tsv` + `scripts/lib/serial-manifest.ts` — the serial manifest: every `*.serial.test.ts` outside `test/e2e/` with its class (`R1`, `R2`, `global-state`, `exclusive`) and a reason. `checkSerialManifest` (pure) requires the manifest to match the tree exactly, classes to match what the file does (env mutation, `mock.module`, `EXCLUSIVE_FILES`) and reasons to be specific; each failure prints Why/Fix/Docs with `bash scripts/check-test-isolation.sh --as-parallel <file>` as the first step. Tests: `test/scripts/serial-files.test.ts`.
- `test/helpers/brain-template.ts` — disk-backed PGLite brains cloned from one initialized template per process and embedding shape. The template is captured right after `initSchema` with no source, writer or physical-root reservation (asserted); only the data directory is copied; each clone regenerates `brain_id`, the default source incarnation and the shared-skill token secret and serving epoch. Used by `test/helpers/connector-fixture.ts`. Tests: `test/helpers/brain-template.test.ts`.