Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sources): the physical-root overlap scan skips directories git gc removes mid-walk; isolate the sweep query-count test

garrytan9e537b94d106
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 155d57793d..c6abebfebc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -111,6 +111,7 @@ gbrain config set facts.extraction_enabled false # turn automat
- `gbrain extract timeline --source db` refreshes PGLite planner statistics on batch boundaries during the walk.
- `gbrain migrate --to` refusals carry why and a filled fix naming the refusing side; an unknown engine is `invalid_params`; `postgres` is the canonical engine name (`supabase` stays an alias).
- `gbrain sources refresh` runs inside a resident PGLite owner (`writer_refresh` administration operation); delegated syncs keep the progress-aware deadline; the consumer's idle probe honors the refresh fence.
+- `gbrain sources add` no longer fails with `internal_error` (ENOENT under `.git/objects`) when a background `git gc` prunes the checkout while it is being registered.
- Search reuses its projection-readiness answer until the brain changes (`GBRAIN_PROJECTION_READINESS_CACHE=0` turns it off).
- The OpenClaw context-engine heartbeat reports seat write failures with their hints; a pattern page drops a seat its reflections no longer share (#4618).
diff --git a/docs/fix-wave-notes/capy-foundations-2.md b/docs/fix-wave-notes/capy-foundations-2.md
index b442defab1..fb842de690 100644
--- a/docs/fix-wave-notes/capy-foundations-2.md
+++ b/docs/fix-wave-notes/capy-foundations-2.md
@@ -58,6 +58,18 @@ Every P0 item shipped. Nothing was cut.
PGLite `releaseAbandonedClaims` with Lane F's refresh-fence predicate in the
idle probe; released claims are still fenced when they are claimed again.
+- `gbrain sources add` on a 20,000-file checkout failed intermittently on
+ 4-vCPU runners (also on branches without this wave): the background `git gc`
+ that the fixture's large commit starts pruned `.git/objects/<xx>` while the
+ physical-root overlap scan walked the checkout, and the scan's `readdirSync`
+ threw ENOENT. The scan now skips a subdirectory that vanished mid-walk
+ (`test/persistence-physical-root.test.ts` races it against a churning
+ directory). Reproduced 4 of 5 times on a standard-4 VM before the fix.
+- `test/sweep.test.ts` counted 4 raw queries instead of 3 when an earlier file
+ in the same process had registered a local CLI writer in the shared test
+ home: snapshot brains share one `brain_id`, so the maintenance principal
+ lookup found and verified that registration. The test now runs with its own
+ `GBRAIN_HOME`.
- PR-budget coverage cut: the 150 s pull-request robot run on Postgres skips
the seams and the fault that can wait out a dead owner's 2-minute claim
lease (`effect:*`, `consumer:prepared`, `publication:prepared`,
diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.ts
index bb1db4fbe9..6114267cb7 100644
--- a/src/core/persistence/physical-root-record.ts
+++ b/src/core/persistence/physical-root-record.ts
@@ -79,7 +79,10 @@ export function reservePhysicalRootRecord(root: string, identity: Omit<PhysicalR
createPrivate(physicalRootReservationPath(root), value);
return readPhysicalRootReservation(root)!;
}
-/** Every contender reserves before this scan, so racing ancestor/child claims cannot both succeed. */
+/**
+ * Every contender reserves before this scan, so racing ancestor/child claims cannot both succeed.
+ * A subdirectory removed while the scan runs (git gc pruning loose objects) holds no reservation.
+ */
export function assertNoPhysicalRootOverlap(root: string): void {
for (let parent = dirname(root); parent !== root; parent = dirname(parent)) {
if (readPhysicalRootReservation(parent) || existsSync(join(parent, PHYSICAL_ROOT_MARKER))) throw physicalRootError('This path lies inside another reserved canonical root.');
@@ -87,7 +90,13 @@ export function assertNoPhysicalRootOverlap(root: string): void {
}
if (!existsSync(root)) return;
const visit = (directory: string) => {
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
+ let entries;
+ try { entries = readdirSync(directory, { withFileTypes: true }); } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (directory !== root && (code === 'ENOENT' || code === 'ENOTDIR')) return;
+ throw error;
+ }
+ for (const entry of entries) {
if (entry.name.startsWith(RESERVATION_PREFIX) && entry.name.endsWith('.json') || directory !== root && entry.name === PHYSICAL_ROOT_MARKER) {
throw physicalRootError('This root contains another reserved canonical root.');
}
diff --git a/test/persistence-physical-root.test.ts b/test/persistence-physical-root.test.ts
index d81f183d87..47ee4aedea 100644
--- a/test/persistence-physical-root.test.ts
+++ b/test/persistence-physical-root.test.ts
@@ -167,3 +167,27 @@ test.skipIf(!process.env.DATABASE_URL)('two real PostgreSQL processes with disti
expect(await pg.engine.executeRaw('SELECT source_id FROM persistence_source_bindings')).toHaveLength(1);
} finally { release?.(); for (const child of children) if (child.exitCode === null) child.kill(); await holding; await Promise.allSettled(children.map(child => child.exited)); await pg.close(); }
}, 120_000);
+
+test('the overlap scan tolerates directories a concurrent git gc removes mid-walk', async () => {
+ const root = join(directory, randomUUID()); const objects = join(root, '.git', 'objects');
+ mkdirSync(objects, { recursive: true });
+ const churn = Bun.spawn(['bun', '-e', `
+ const { mkdirSync, rmSync, writeFileSync } = require('node:fs'); const { join } = require('node:path');
+ const end = Date.now() + 3000;
+ while (Date.now() < end) for (let i = 0; i < 64; i++) {
+ const dir = join(${JSON.stringify(objects)}, i.toString(16).padStart(2, '0'));
+ mkdirSync(join(dir, 'pack'), { recursive: true }); writeFileSync(join(dir, 'pack', 'o'), 'x');
+ rmSync(dir, { recursive: true, force: true });
+ }`]);
+ const { assertNoPhysicalRootOverlap } = await import('../src/core/persistence/physical-root-record.ts');
+ const failures: string[] = [];
+ let scans = 0;
+ while (churn.exitCode === null) {
+ try { assertNoPhysicalRootOverlap(root); } catch (error) { failures.push((error as Error).message); }
+ scans++;
+ await delay(0);
+ }
+ expect(await churn.exited).toBe(0);
+ expect(scans).toBeGreaterThan(10);
+ expect(failures).toEqual([]);
+});
diff --git a/test/sweep.test.ts b/test/sweep.test.ts
index 82c2e725ec..b021ca7fee 100644
--- a/test/sweep.test.ts
+++ b/test/sweep.test.ts
@@ -670,15 +670,22 @@ describe('runMaintenanceSweep — bounded link resolution (no listAllPageRefs)',
['# TL', '', '## Timeline', '', '- **2026-03-04** | timeline only entry', ''].join('\n'),
);
const log: string[] = [];
- const r = await runMaintenanceSweep(loggingEngine(engine, log), {
+ // A fresh GBRAIN_HOME holds no local CLI registration. Snapshot brains in
+ // one test process share a brain_id, so a registration another file wrote
+ // into the shared test home would add its verification query here.
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-sweep-home-'));
+ tmpDirs.push(home);
+ const r = await withEnv({ GBRAIN_HOME: home }, () => runMaintenanceSweep(loggingEngine(engine, log), {
sourceId: 'default',
capabilities: KEYLESS,
- });
+ }));
expect(r.timelineExtracted).toBe(1);
expect(log).not.toContain('listAllPageRefs');
// Exactly three raw queries: the pass-1 fence scan, the pass-2 recency
- // scan and the maintenance principal lookup the attributed timeline batch
- // makes. No candidates ⇒ no ref-lookup query.
+ // scan and the maintenance principal's brain_id lookup the attributed
+ // timeline batch makes (an installation with a CLI registration adds one
+ // query that verifies it, once per engine). No candidates ⇒ no ref-lookup
+ // query.
expect(log.filter((m) => m === 'executeRaw').length).toBe(3);
});
});