Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: scope the cached sync reason scan per engine so one brain never reuses another brain's tombstone-filtered scan
garrytan52b3e4214441
diff --git a/src/core/reason-trailers.ts b/src/core/reason-trailers.tsindex 06bb6d3f82..d424231d29 100644--- a/src/core/reason-trailers.ts+++ b/src/core/reason-trailers.ts@@ -237,17 +237,20 @@ export function reasonScanNotices(scan: SyncReasonScan | null | undefined, sourc}export const SOURCE_PURGE_EPOCH_SQL = 'SELECT purge_epoch FROM sources WHERE id = $1';-const cache = new Map<string, { at: number; scan: Promise<SyncReasonScan | null> }>();+let caches = new WeakMap<BrainEngine, Map<string, { at: number; scan: Promise<SyncReasonScan | null> }>>();const CACHE_TTL_MS = 10 * 60_000;/*** Managed sync prepares one request at a time, each naming its pass's range: the pass's scan runs once per process and* its later requests reuse it. The key carries the source's purge epoch, which every fact purge bumps in the transaction- * that writes its tombstones, so a purge from any process makes the next request scan again and read them.+ * that writes its tombstones, so a purge from any process makes the next request scan again and read them. The cache is+ * per engine: the scan holds that brain's tombstones, so another brain on the same checkout never reuses it.*/export async function cachedSyncReasonScan(engine: BrainEngine, input: Parameters<typeof scanSyncReasons>[1]): Promise<SyncReasonScan | null> {const [source] = await engine.executeRaw<{ purge_epoch: string | number }>(SOURCE_PURGE_EPOCH_SQL, [input.sourceId]);const key = [input.sourceId, String(source?.purge_epoch ?? 0), input.sourceRoot, input.from ?? '', input.to].join('\0');+ const cache = caches.get(engine) ?? new Map();+ caches.set(engine, cache);const hit = cache.get(key);if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.scan;const scan = scanSyncReasons(engine, input);@@ -256,7 +259,7 @@ export async function cachedSyncReasonScan(engine: BrainEngine, input: Parameterwhile (cache.size > 16) cache.delete(cache.keys().next().value!);return scan;}-export function clearReasonScanCache(): void { cache.clear(); }+export function clearReasonScanCache(): void { caches = new WeakMap(); }/** A7: what a purge's trailer scan found: the (commit, path) pairs whose reason quotes the claim, read up to HEAD. */export type PurgeTrailerScan =diff --git a/test/reason-trailers-gbra217.test.ts b/test/reason-trailers-gbra217.test.tsindex 4c625e650e..073b9ab641 100644--- a/test/reason-trailers-gbra217.test.ts+++ b/test/reason-trailers-gbra217.test.ts@@ -35,13 +35,14 @@ import { runImport } from '../src/commands/import.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { __setReasonGitStreamForTests, __setReasonScanCapsForTests, clearReasonScanCache, gitTopLevel, importHistoryFor, scanSyncReasons,- scanTrailersCarrying } from '../src/core/reason-trailers.ts';+import { __setReasonGitStreamForTests, __setReasonScanCapsForTests, cachedSyncReasonScan, clearReasonScanCache, gitTopLevel, importHistoryFor,+ scanSyncReasons, scanTrailersCarrying } from '../src/core/reason-trailers.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-reason-trailers-'));const engines: BrainEngine[] = [];+let otherBrain: PGLiteEngine;let closePostgres: (() => Promise<void>) | undefined;let serial = 0;@@ -142,6 +143,7 @@ const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home }, fn);beforeAll(async () => inHome(async () => {const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ otherBrain = new PGLiteEngine(); await otherBrain.connect({}); await otherBrain.initSchema();if (process.env.DATABASE_URL) {const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);engines.push(pg.engine); closePostgres = pg.close;@@ -152,6 +154,7 @@ afterEach(() => { __setReasonScanCapsForTests(); __setReasonGitStreamForTests();afterAll(async () => {await inHome(async () => { for (const engine of engines) await disposePersistenceConsumer(engine).catch(() => undefined); });await engines[0]?.disconnect();+ await otherBrain?.disconnect();await closePostgres?.();rmSync(home, { recursive: true, force: true });});@@ -270,6 +273,23 @@ describe('A6: sync mirrors gbrain-reason trailers', () => {expect(importHistoryFor(scan, join(root, 'bulk/f4321.md'))).toEqual({ reason: 'Only this file has a reason.', historyGap: false });expect(importHistoryFor(scan, join(root, 'bulk/f0001.md'))).toEqual({ reason: null, historyGap: false });}), 120_000);++ test('two brains in one process sharing a checkout, source id, range and purge epoch each read their own tombstones', async () => inHome(async () => {+ const id = `rt-shared-${++serial}`;+ const root = newRepo({ 'notes/a.md': page('A one.') });+ const from = git(root, 'rev-parse', 'HEAD');+ write(root, { 'notes/a.md': page('A two.') });+ const to = commit(root, 'edit', ['notes/a.md: Canary reason for source-a.']);+ for (const brain of [engines[0]!, otherBrain]) {+ await brain.executeRaw(`INSERT INTO sources(id, name, local_path, config) VALUES ($1, $1, $2, '{}')`, [id, root]);+ await brain.executeRaw('UPDATE sources SET purge_epoch = 1 WHERE id = $1', [id]);+ }+ await otherBrain.executeRaw('INSERT INTO reason_purge_tombstones(source_id, commit_sha, path) VALUES ($1, $2, $3)', [id, to, 'notes/a.md']);+ const range = { sourceId: id, sourceRoot: root, from, to };+ const file = join(root, 'notes/a.md');+ expect(importHistoryFor(await cachedSyncReasonScan(engines[0]!, range), file)).toEqual({ reason: 'Canary reason for source-a.', historyGap: false });+ expect(importHistoryFor(await cachedSyncReasonScan(otherBrain, range), file)).toEqual({ reason: null, historyGap: false });+ }), 120_000);});describe('A7: purge reaches change reasons', () => {