Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Fix four more flaky tests at their cause

garrytana17de44106a3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3defaa405c..707bc2d959 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+### Five flaky tests fixed at their cause
+
+**Five tests that failed by chance on some machines now pass or fail for a real reason. No assertion, bound or timeout was loosened, and nothing in `src/` changed.** Each fix comes with a probe that forces the failure every time on master and passes with the fix.
+
+- `test/helpers/statement-counter.ts`: the PGLite statement counter named a Bind by the last Parse it had seen. The engine's statement cache (`src/core/pglite-statements.ts`) prepares a statement the second time it runs, so a statement prepared before counting started was recorded under the text of the statement before it. `test/fold-hook-noop-6712.test.ts` then failed whenever background config reads had prepared `SELECT value FROM config WHERE key = $1` before its window. The counter now reads a bound statement's text from the engine's cache, and records an unknown name as a placeholder. `test/statement-counter-warm-cache.test.ts` pins it.
+- `test/persistence-consumer-idle.test.ts`: the first tick's maintenance count read 8, 9 or 10. On a slow machine the next tick's idle probe landed inside the count, and the compacted-receipt sweep added a statement until an earlier test had finished its cursor. The test now walks that cursor to done first and holds later ticks until the first tick is counted. The count is still exactly 8.
+- `test/e2e/evidence-long-page.test.ts`: with provider keys in the environment, every search called the live reranker, whose scores for identical calls differ in the last digits, so the byte comparison failed. The file now runs keyless, as CI's Selected E2E runs it.
+- `test/e2e/source-retire-batched-postgres.test.ts` ran into its 180 s cap. It now retires 2,017 pages (four full batches and a partial one) instead of 60,000, and a statement trigger records every committed page delete. So each test asserts the batches themselves: their sizes, the per-batch bound and one transaction each. Removing the batch `LIMIT` fails the remove and purge tests. The file takes about 57 s.
+- `test/config-file-plane-keys.test.ts`, `test/consent.test.ts`: the memorable enable tests hung waiting for a `[y/N]` answer when stdin was a terminal. They now pin `process.stdin.isTTY` to false while the command runs, so they test the non-interactive refusal however the runner's stdin is set up.
+
## [0.60.664.0] - 2026-11-11
**The Git effects of page writes no longer publish a script's secret.** A script that commits into a managed checkout with plain `git commit` never passes the write path's secret scan. The refresh publish refused such a commit with `publish_secret_found`, but the next page write's Git effect pushed it anyway. Its plain push published every unpublished commit unscanned, and when the remote had moved its keep-checkout publish ran without the scan. Both paths now scan the exact commits they push, except the ones gbrain made itself for page writes (a Git effect's commit, recorded only after checking it holds exactly the bytes the effect wrote, or a hosted repository's door commit, as its commit ledger records them): page bodies are stored raw by design and their Git backups keep going, and the refresh publish now skips them the same way. A value that looks like a secret, added text too large to scan, a commit that changes `.gbrain-scan-allow` or a `.gitattributes` holds the effects with `publish_secret_found`; commits the scan cannot read in full hold them with `publish_scan_unreadable`. A first push to a remote that has no such branch yet scans the branch's whole history and creates the branch only when that scan passes. A commit that changes `.gbrain-scan-allow` or a `.gitattributes` is never published automatically, so the user reviews it and pushes it. Nothing is pushed, and the page writes stay safe in the database and in local commits. `gbrain sync status` and doctor name the user's choice, which is to remove the value from those commits or to allowlist a false positive by fingerprint. Then `gbrain sources writer retry-effects <source> --parked-pushes` runs the effects that parked. Every scanned push is also leased on the remote tip it scanned against. Before, a remote rewound past a pushed secret (an admin removing it with a force-push) left a stale tracking ref that hid the commit from the scan, and the next fast-forward put it back; now the scan runs against the remote's real tip. The in-process scan on the owner's event loop is capped at 10 seconds, inside the writer heartbeat's live window; a longer range goes to the keep-checkout publish, whose child process scans with the full budget.
diff --git a/test/config-file-plane-keys.test.ts b/test/config-file-plane-keys.test.ts
index 5548aa34e7..82c2c69c06 100644
--- a/test/config-file-plane-keys.test.ts
+++ b/test/config-file-plane-keys.test.ts
@@ -254,9 +254,10 @@ describe('config set — vendor API keys are FILE-plane canonical', () => {
* Enabling requires the gbrain-authored disclosure stamp (a separate 0600
* file the external memorable CLI has never written — it full-file-rewrites
* config.json, so a config-key stamp could be forged by habit, lost to a
- * rewrite race, or resurrected after revocation). Under bun test stdin is not
- * a TTY, so the non-interactive posture is what these tests exercise:
- * refuse without --yes, consent with it.
+ * rewrite race, or resurrected after revocation). captureAll pins stdin to
+ * non-TTY, so the non-interactive posture is what these tests exercise:
+ * refuse without --yes, consent with it. Under a terminal the gate would
+ * otherwise prompt on stdin and the test would wait for an answer.
*/
import {
memorableConsentPath,
@@ -268,9 +269,11 @@ async function captureAll(fn: () => Promise<void>): Promise<{ out: string; err:
const origLog = console.log;
const origErr = console.error;
const origExit = process.exit;
+ const origStdinTTY = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
let out = '';
let err = '';
let exitCode: number | null = null;
+ Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true });
console.log = (...a: unknown[]) => { out += a.map(String).join(' ') + '\n'; };
console.error = (...a: unknown[]) => { err += a.map(String).join(' ') + '\n'; };
process.exit = ((code?: number) => { exitCode = code ?? 0; throw new Error(`__exit_${code}`); }) as never;
@@ -282,6 +285,8 @@ async function captureAll(fn: () => Promise<void>): Promise<{ out: string; err:
console.log = origLog;
console.error = origErr;
process.exit = origExit;
+ if (origStdinTTY) Object.defineProperty(process.stdin, 'isTTY', origStdinTTY);
+ else delete (process.stdin as { isTTY?: boolean }).isTTY;
}
return { out, err, exitCode };
}
diff --git a/test/consent.test.ts b/test/consent.test.ts
index 7159be27c8..41163854ed 100644
--- a/test/consent.test.ts
+++ b/test/consent.test.ts
@@ -441,6 +441,8 @@ describe("memorable's relay-only gate (stays hard)", () => {
const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errors.push(a.join(' ')); });
const logSpy = spyOn(console, 'log').mockImplementation(() => {});
const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => { throw new Error(`exit:${code}`); }) as never);
+ const origStdinTTY = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
+ Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true });
try {
await inHome(async () => {
const engine = { getConfig: async () => null, setConfig: async () => {}, unsetConfig: async () => 0 } as never;
@@ -451,6 +453,8 @@ describe("memorable's relay-only gate (stays hard)", () => {
errSpy.mockRestore();
logSpy.mockRestore();
exitSpy.mockRestore();
+ if (origStdinTTY) Object.defineProperty(process.stdin, 'isTTY', origStdinTTY);
+ else delete (process.stdin as { isTTY?: boolean }).isTTY;
}
const relay = errors.find(l => l.startsWith('[AGENT] Relay this to your operator'));
expect(relay).toContain("If the user has no terminal on this machine, this can't be enabled from this session.");
diff --git a/test/e2e/evidence-long-page.test.ts b/test/e2e/evidence-long-page.test.ts
index f06684a532..c121f1e5ee 100644
--- a/test/e2e/evidence-long-page.test.ts
+++ b/test/e2e/evidence-long-page.test.ts
@@ -10,7 +10,8 @@
* assemble_evidence unchanged with the key on, and the d5b/F4 instruction
* config readers, all on the same engine.
*
- * Runs when DATABASE_URL is set.
+ * Runs when DATABASE_URL is set, keyless as CI's Selected E2E runs it: run-e2e.sh keeps ambient provider keys, and
+ * with them every search calls a live reranker whose scores for identical calls differ in the last digits.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
@@ -21,6 +22,7 @@ import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../
import { assembleEvidenceForHits } from '../../src/core/search/evidence-delivery.ts';
import { buildMcpInstructions, readInstructionContent } from '../../src/mcp/instructions.ts';
import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';
+import { PROVIDER_ENV_KEYS } from '../helpers/provider-env.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { DECIDING, LONG_SLUG, MEDIUM_SLUG, mcpCall, opCall, seedLongPages, withConfig } from '../helpers/long-page-fixture.ts';
@@ -29,15 +31,22 @@ const KEY = 'search.long_page_unit';
const run = process.env.DATABASE_URL ? describe : describe.skip;
let engine: PostgresEngine;
let close: () => Promise<void> = async () => {};
+const ambientProviderEnv = PROVIDER_ENV_KEYS.map(key => [key, process.env[key]] as const);
beforeAll(async () => {
if (!process.env.DATABASE_URL) return;
+ for (const key of PROVIDER_ENV_KEYS) delete process.env[key];
+ resetGateway();
const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL);
engine = isolated.engine;
close = isolated.close;
await seedLongPages(engine);
}, 240_000);
-afterAll(async () => { await close(); }, 120_000);
+afterAll(async () => {
+ await close();
+ for (const [key, value] of ambientProviderEnv) if (value !== undefined) process.env[key] = value;
+ resetGateway();
+}, 120_000);
const long = (rows: Array<Record<string, unknown>>) => rows.find(r => r.slug === LONG_SLUG)!;
diff --git a/test/e2e/source-retire-batched-postgres.test.ts b/test/e2e/source-retire-batched-postgres.test.ts
index ef6121e89f..9876813306 100644
--- a/test/e2e/source-retire-batched-postgres.test.ts
+++ b/test/e2e/source-retire-batched-postgres.test.ts
@@ -1,7 +1,9 @@
/**
* #7702 / #8905: a managed remove or purge of a large source deletes its pages in bounded batches, each in its own
* short topology transaction, so no statement meets the 5 s topology bound; a retry with the same request_id
- * resumes after an interrupted batch and finishes.
+ * resumes after an interrupted batch and finishes. A statement trigger records every committed page DELETE, so each
+ * test pins the batches themselves (count, SOURCE_RETIRE_BATCH_PAGES bound, one transaction each) on a source of
+ * four full batches and a partial one.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
@@ -11,14 +13,15 @@ import { tmpdir } from 'node:os';
import type { BrainEngine } from '../../src/core/engine.ts';
import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
import { claimWorktree } from '../../src/core/persistence/ownership.ts';
-import { runManagedSourceLifecycle } from '../../src/core/persistence/source-lifecycle.ts';
+import { runManagedSourceLifecycle, SOURCE_RETIRE_BATCH_PAGES } from '../../src/core/persistence/source-lifecycle.ts';
import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
import { persistencePostgresTemplate } from '../helpers/persistence-postgres.ts';
import { requirePostgresTestDatabase } from '../helpers/test-backends.ts';
import { withEnv } from '../helpers/with-env.ts';
-const PAGES = 60_000;
-const STALL_AFTER = PAGES / 2;
+const PAGES = SOURCE_RETIRE_BATCH_PAGES * 4 + 17;
+const BATCHES = [...Array(4).fill(SOURCE_RETIRE_BATCH_PAGES), 17];
+const STALL_AFTER = SOURCE_RETIRE_BATCH_PAGES * 2;
const databaseUrl = requirePostgresTestDatabase();
let template: Awaited<ReturnType<typeof persistencePostgresTemplate>>;
beforeAll(async () => {
@@ -26,6 +29,10 @@ beforeAll(async () => {
for (const id of ['retire-large', 'keep-other']) await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]);
await seed(engine, 'retire-large', PAGES);
await seed(engine, 'keep-other', 50);
+ await engine.executeRaw('CREATE TABLE retire_batches(seq serial PRIMARY KEY, tx bigint NOT NULL, pages integer NOT NULL)');
+ await engine.executeRaw(`CREATE FUNCTION retire_batches_fn() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
+ INSERT INTO retire_batches(tx,pages) SELECT txid_current(),count(*) FROM gone HAVING count(*)>0; RETURN NULL; END $$`);
+ await engine.executeRaw('CREATE TRIGGER retire_batches AFTER DELETE ON pages REFERENCING OLD TABLE AS gone FOR EACH STATEMENT EXECUTE FUNCTION retire_batches_fn()');
});
}, 600_000);
afterAll(async () => { await template?.dispose(); });
@@ -38,6 +45,10 @@ async function seed(engine: BrainEngine, source: string, pages: number) {
await engine.executeRaw(`INSERT INTO links(from_page_id,to_page_id) SELECT p.id,q.id FROM pages p
JOIN pages q ON q.source_id=p.source_id AND q.slug='notes/p-'||(split_part(p.slug,'-',2)::int % $2::int + 1) WHERE p.source_id=$1`, [source, pages]);
}
+async function batches(engine: BrainEngine) {
+ const rows = await engine.executeRaw<{ tx: string; pages: number }>('SELECT tx::text,pages FROM retire_batches ORDER BY seq');
+ return { pages: rows.map(r => r.pages), transactions: new Set(rows.map(r => r.tx)).size };
+}
async function counts(engine: BrainEngine, source: string) {
const [row] = await engine.executeRaw<{ pages: number; chunks: number; links: number }>(`SELECT
(SELECT count(*)::int FROM pages WHERE source_id=$1) AS pages,
@@ -66,11 +77,12 @@ describe('managed remove/purge of a large source (postgres)', () => {
} finally { await disposePersistenceConsumer(engine); await close(); rmSync(home, { recursive: true, force: true }); }
}
- test('remove deletes every page, chunk and link of a source too large for one bounded statement', () => fixture(async (engine, source) => {
+ test('remove deletes every page, chunk and link of a source larger than one batch, in bounded batches', () => fixture(async (engine, source) => {
const started = performance.now();
const receipt = await runManagedSourceLifecycle(engine, { operation: 'remove', sourceId: source, confirmDestructive: true })
.finally(() => console.log(`[retire-batched] remove of ${PAGES} pages: ${Math.round(performance.now() - started)} ms`));
expect(receipt).toMatchObject({ state: 'committed', operation: 'remove', pages_deleted: PAGES });
+ expect(await batches(engine)).toEqual({ pages: BATCHES, transactions: BATCHES.length });
expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', [source])).toHaveLength(0);
expect(await engine.executeRaw('SELECT source_id FROM persistence_source_bindings WHERE source_id=$1', [source])).toHaveLength(0);
expect(await counts(engine, source)).toEqual({ pages: 0, chunks: 0, links: 0 });
@@ -80,6 +92,7 @@ describe('managed remove/purge of a large source (postgres)', () => {
await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: source });
const receipt = await runManagedSourceLifecycle(engine, { operation: 'purge', sourceId: source, confirmDestructive: true });
expect(receipt).toMatchObject({ state: 'committed', operation: 'purge', pages_deleted: PAGES });
+ expect(await batches(engine)).toEqual({ pages: BATCHES, transactions: BATCHES.length });
expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', [source])).toHaveLength(0);
expect(await counts(engine, source)).toEqual({ pages: 0, chunks: 0, links: 0 });
}), 300_000);
@@ -96,11 +109,13 @@ describe('managed remove/purge of a large source (postgres)', () => {
await expect(remove()).rejects.toMatchObject({ code: 'write_pending' });
const left = (await counts(engine, source)).pages;
expect(left).toBe(PAGES - STALL_AFTER);
+ expect(await batches(engine)).toEqual({ pages: BATCHES.slice(0, 2), transactions: 2 });
expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', [source])).toHaveLength(1);
expect(await engine.executeRaw('SELECT state,recovery FROM persistence_topology_changes WHERE request_id=$1::uuid', [requestId])).toEqual([{ state: 'recovering', recovery: null }]);
await engine.executeRaw('DELETE FROM retire_stall');
const receipt = await remove();
expect(receipt).toMatchObject({ state: 'committed', operation: 'remove', pages_deleted: left });
+ expect(await batches(engine)).toEqual({ pages: BATCHES, transactions: BATCHES.length });
expect(await remove()).toEqual(receipt);
expect(await counts(engine, source)).toEqual({ pages: 0, chunks: 0, links: 0 });
expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', [source])).toHaveLength(0);
diff --git a/test/persistence-consumer-idle.test.ts b/test/persistence-consumer-idle.test.ts
index f895fc7440..eb9ce5eaf3 100644
--- a/test/persistence-consumer-idle.test.ts
+++ b/test/persistence-consumer-idle.test.ts
@@ -7,6 +7,7 @@ import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';
import { admitWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';
+import { sweepCompactedReservations } from '../src/core/persistence/receipt-true-up.ts';
import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';
import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -98,15 +99,26 @@ test('idle polling backs off to the cap, then a wake runs a full tick immediatel
{ hostId: config.hostId, onError: () => {} });
(withoutPass as unknown as { nextMaintenance: number }).nextMaintenance = Number.POSITIVE_INFINITY;
try { await withoutPass.tick(); await settled(withoutPass); } finally { await withoutPass.stop(); }
+ // The pass's one-shot compacted-receipt sweep reads the journal until its cursor is done (an earlier test's pass may have
+ // finished it); the count is the steady-state pass.
+ while (!(await sweepCompactedReservations(engine)).done) { /* walk the cursor to done */ }
+ // The first tick's workers can outlive it by more than the 20 ms poll on a slow machine; the next tick waits until the
+ // first tick's statements are counted, so its probe never lands in that count.
+ const counted = Promise.withResolvers<void>();
const ticks: Promise<void>[] = [];
const tick = consumer.tick.bind(consumer);
- consumer.tick = (afterProgress?: boolean) => { const run = tick(afterProgress); ticks.push(run); return run; };
+ consumer.tick = (afterProgress?: boolean) => {
+ const run = ticks.length ? counted.promise.then(() => tick(afterProgress)) : tick(afterProgress);
+ ticks.push(run);
+ return run;
+ };
consumer.start();
try {
await waitFor(() => ticks.length > 0, { timeoutMs: 1_000 });
await ticks[0];
await settled(consumer);
const firstTick = statements.length;
+ counted.resolve();
// The first full tick carries the maintenance pass; a statement added to that pass changes this count on purpose.
expect(firstTick - bare.statements.length).toBe(8);
await Bun.sleep(2_000);
@@ -115,7 +127,7 @@ test('idle polling backs off to the cap, then a wake runs a full tick immediatel
const full = refreshes();
consumer.wake();
await waitFor(() => refreshes() > full, { timeoutMs: 1_000 });
- } finally { await consumer.stop(); }
+ } finally { counted.resolve(); await consumer.stop(); }
}));
test('concurrent wakes during a tick coalesce into one follow-up tick', async () => {