Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(B1): sources add tolerates subdirectories git gc prunes mid-walk

garrytan011728646f20
diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.ts
index bb1db4fbe9..5433e0e255 100644
--- a/src/core/persistence/physical-root-record.ts
+++ b/src/core/persistence/physical-root-record.ts
@@ -79,7 +79,12 @@ 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.
+ * The walk includes `.git` (another brain may reserve a path there). A subdirectory that vanishes
+ * or becomes a file mid-walk (git's auto-gc pruning `.git/objects`) holds no reservation and is
+ * skipped; errors on the root itself, and every other error such as EACCES, still refuse.
+ */
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 +92,14 @@ 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/src/core/persistence/topology-filesystem.ts b/src/core/persistence/topology-filesystem.ts
index cfac03f1b0..da6132e3f6 100644
--- a/src/core/persistence/topology-filesystem.ts
+++ b/src/core/persistence/topology-filesystem.ts
@@ -18,7 +18,11 @@ export function topologyDirectoryIdentity(path:string):{device:string;inode:stri
{fix:recoveryFix('Shows pending lifecycle requests and their recovery records, read-only.')});
return {device:info.dev.toString(),inode:info.ino.toString(),birthNs:info.birthtimeNs.toString()};
}
-/** Complete tree accounting includes .git, sparse files, and metadata headroom. */
+/**
+ * Complete tree accounting includes .git, sparse files, and metadata headroom. A path below the
+ * root that vanishes or stops being a directory mid-walk (git's auto-gc pruning .git/objects) is
+ * counted as already seen; errors on the root and every other error still throw.
+ */
export async function topologyDirectoryBytes(root:string,limit=Number.MAX_SAFE_INTEGER):Promise<number>{
let bytes=0;
const pending=[root];
@@ -30,7 +34,14 @@ export async function topologyDirectoryBytes(root:string,limit=Number.MAX_SAFE_I
if(!Number.isSafeInteger(bytes)||bytes>limit)throw opError('request_too_large','The staged checkout exceeds its reserved recovery capacity.',
`The checkout staged at ${root} is larger than the ${limit} bytes reserved for its recovery. Inspect the pending lifecycle request in writer status; it needs a smaller repository or a larger recovery budget, which is the user's call.`,
{fix:recoveryFix('Shows the pending lifecycle request and the recovery capacity it holds, read-only.')});
- if(info.isDirectory())for(const entry of await readdir(path))pending.push(join(path,entry));
+ if(!info.isDirectory())continue;
+ let entries:string[];
+ try{entries=await readdir(path);}catch(error){
+ const code=(error as NodeJS.ErrnoException).code;
+ if(path!==root&&(code==='ENOENT'||code==='ENOTDIR'))continue;
+ throw error;
+ }
+ for(const entry of entries)pending.push(join(path,entry));
}
return bytes;
}
diff --git a/test/large-brain-ceilings.serial.test.ts b/test/large-brain-ceilings.serial.test.ts
index 226577158b..6f84f3812f 100644
--- a/test/large-brain-ceilings.serial.test.ts
+++ b/test/large-brain-ceilings.serial.test.ts
@@ -42,7 +42,7 @@ afterAll(() => rmSync(dir, { recursive: true, force: true }));
async function freshBrain(name: string): Promise<string> {
const home = join(dir, name, 'home');
const init = await runCli(['init', '--pglite', '--no-embedding'], { home, env: KEYS, timeoutMs: 120_000 });
- expect(init.exitCode).toBe(0);
+ expect(init.exitCode, init.stderr).toBe(0);
return home;
}
@@ -51,7 +51,8 @@ describe('large-brain ceilings (CLI)', () => {
const home = await freshBrain('sync');
const repo = join(dir, 'sync', 'repo');
commitWorktree(repo, 150);
- expect((await runCli(['sources', 'add', 'notes', '--path', repo], { home, env: KEYS, timeoutMs: 120_000 })).exitCode).toBe(0);
+ const add = await runCli(['sources', 'add', 'notes', '--path', repo], { home, env: KEYS, timeoutMs: 120_000 });
+ expect(add.exitCode, add.stderr).toBe(0);
const sync = await runCli(['sync', '--source', 'notes', '--no-pull'], {
home, timeoutMs: 180_000,
@@ -60,7 +61,7 @@ describe('large-brain ceilings (CLI)', () => {
expect(sync.stderr).toContain('extends while the sync keeps progressing');
expect(sync.stderr).toContain('still progressing');
expect(sync.stdout).not.toContain('sync_deadline_stop');
- expect(sync.exitCode).toBe(0);
+ expect(sync.exitCode, sync.stderr).toBe(0);
expect(sync.stdout).toContain('150 file(s) imported');
}, 300_000);
@@ -70,7 +71,7 @@ describe('large-brain ceilings (CLI)', () => {
commitWorktree(repo, 20_000);
const add = await runCli(['sources', 'add', 'big', '--path', repo], { home, env: KEYS, timeoutMs: 180_000 });
expect(add.stderr).not.toContain('request_too_large');
- expect(add.exitCode).toBe(0);
+ expect(add.exitCode, add.stderr).toBe(0);
expect(JSON.parse(add.stdout.slice(add.stdout.indexOf('{')))).toMatchObject({ source_id: 'big', state: 'committed' });
}, 300_000);
});
diff --git a/test/persistence-physical-root.test.ts b/test/persistence-physical-root.test.ts
index d81f183d87..ae50e817ff 100644
--- a/test/persistence-physical-root.test.ts
+++ b/test/persistence-physical-root.test.ts
@@ -16,8 +16,12 @@ import { withEnv } from './helpers/with-env.ts';
const directory = mkdtempSync(join(tmpdir(), 'gbrain-physical-root-'));
let engine: PGLiteEngine;
-beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
-afterAll(async () => { await engine.disconnect(); rmSync(directory, { recursive: true, force: true }); });
+let otherBrain: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ otherBrain = new PGLiteEngine(); await otherBrain.connect({}); await otherBrain.initSchema();
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); await otherBrain.disconnect(); rmSync(directory, { recursive: true, force: true }); });
async function fixture() {
const base = join(directory, randomUUID()); mkdirSync(base);
const root = join(base, 'canonical'); mkdirSync(root); writeFileSync(join(root, 'page.md'), 'Canonical example');
@@ -92,6 +96,20 @@ test('an overlapping ancestor claim is refused across homes and retains the orig
const lock = await acquireWorktree(binding); expect(lock).not.toBeNull(); await lock?.release();
});
+test('another brain\'s reservation under the checkout\'s .git refuses the outer claim', async () => {
+ const f = await fixture();
+ const nested = join(f.root, '.git', 'child'); mkdirSync(nested, { recursive: true });
+ const source = `physical-${randomUUID()}`;
+ await otherBrain.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, nested]);
+ const binding = await withEnv({ GBRAIN_HOME: f.homes[1] }, () => claimWorktree(otherBrain, source, nested, f.hosts[1]));
+ expect(readPhysicalRootReservation(nested)?.worktreeId).toBe(binding.worktree_id);
+ await withEnv({ GBRAIN_HOME: f.homes[0] }, async () => {
+ await expect(claimWorktree(engine, f.sources[0], f.root, f.hosts[0])).rejects.toMatchObject({ code: 'recovery_required' });
+ });
+ expect(await getWorktreeBinding(engine, f.sources[0], f.hosts[0])).toBeNull();
+ const lock = await acquireWorktree(binding); expect(lock).not.toBeNull(); await lock?.release();
+});
+
test('missing or torn ownership metadata fails closed even for an existing owner', async () => {
const f = await fixture();
const binding = await withEnv({ GBRAIN_HOME: f.homes[0] }, () => claimWorktree(engine, f.sources[0], f.root, f.hosts[0]));
diff --git a/test/physical-root-walk.test.ts b/test/physical-root-walk.test.ts
new file mode 100644
index 0000000000..7f412f4189
--- /dev/null
+++ b/test/physical-root-walk.test.ts
@@ -0,0 +1,172 @@
+/**
+ * Checkout walks that race a concurrent pruner (#B1: `gbrain sources add`
+ * crashed with `internal_error: ENOENT … scandir '<repo>/.git/objects/06'`
+ * when git's detached auto-gc pruned loose-object directories mid-walk).
+ *
+ * Protects:
+ * - assertNoPhysicalRootOverlap and topologyDirectoryBytes skip a
+ * subdirectory that vanishes or becomes a file between listing and
+ * descent, and still refuse on errors at the root and on EACCES.
+ * - The overlap walk keeps descending into `.git`, so a reservation marker
+ * nested there is still found after a sibling vanished.
+ * Fails when: the walk loses its ENOENT/ENOTDIR tolerance below the root (the
+ * vanished-subdir cases throw), the tolerance widens to the root or to other
+ * errors (the refusal cases resolve), or the walk starts skipping `.git`
+ * (the nested-marker case resolves).
+ * Why new: test/persistence-physical-root.test.ts covers ownership claims over
+ * stable trees; nothing raced the walk. The 20k-file CLI case in
+ * test/large-brain-ceilings.serial.test.ts hit the race only by chance.
+ * Seam: none. The race is injected by wrapping node:fs (restored after each
+ * test), the same listing-then-descent window git's gc opens.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { assertNoPhysicalRootOverlap, physicalRootReservationPath, PHYSICAL_ROOT_MARKER } from '../src/core/persistence/physical-root-record.ts';
+import { topologyDirectoryBytes } from '../src/core/persistence/topology-filesystem.ts';
+import { writeLargeWorktree } from './helpers/large-worktree.ts';
+import { testWaitMs } from './helpers/wait-for.ts';
+
+let directory: string;
+let counter = 0;
+const restores: Array<() => void> = [];
+beforeAll(() => { directory = mkdtempSync(join(tmpdir(), 'gbrain-root-walk-')); });
+afterEach(() => { while (restores.length) restores.pop()!(); });
+afterAll(() => rmSync(directory, { recursive: true, force: true }));
+
+function checkout(): string {
+ const root = join(directory, `repo-${++counter}`);
+ mkdirSync(join(root, '.git', 'objects', '06'), { recursive: true });
+ mkdirSync(join(root, '.git', 'objects', 'pack'), { recursive: true });
+ writeFileSync(join(root, '.git', 'objects', '06', 'loose'), 'x');
+ writeFileSync(join(root, 'page.md'), 'Example page');
+ return root;
+}
+function errno(code: string, path: string): NodeJS.ErrnoException {
+ return Object.assign(new Error(`${code}: simulated, scandir '${path}'`), { code });
+}
+
+/** Runs `onList(directory)` right after the real listing of each directory returns. */
+function afterSyncListing(onList: (directory: string) => void): void {
+ const real = fs.readdirSync;
+ const spy = spyOn(fs, 'readdirSync').mockImplementation(((path: fs.PathLike, options?: unknown) => {
+ const entries = (real as (p: fs.PathLike, o?: unknown) => unknown)(path, options);
+ onList(String(path));
+ return entries;
+ }) as typeof fs.readdirSync);
+ restores.push(() => spy.mockRestore());
+}
+function failSyncListing(target: string, code: string): void {
+ const real = fs.readdirSync;
+ const spy = spyOn(fs, 'readdirSync').mockImplementation(((path: fs.PathLike, options?: unknown) => {
+ if (String(path) === target) throw errno(code, target);
+ return (real as (p: fs.PathLike, o?: unknown) => unknown)(path, options);
+ }) as typeof fs.readdirSync);
+ restores.push(() => spy.mockRestore());
+}
+/** Runs `onStat(path)` right after the real lstat of each path resolves, before its readdir. */
+function afterAsyncStat(onStat: (path: string) => void): void {
+ const real = fsp.lstat;
+ const spy = spyOn(fsp, 'lstat').mockImplementation((async (path: fs.PathLike, options?: unknown) => {
+ const info = await (real as (p: fs.PathLike, o?: unknown) => Promise<unknown>)(path, options);
+ onStat(String(path));
+ return info;
+ }) as typeof fsp.lstat);
+ restores.push(() => spy.mockRestore());
+}
+function failAsyncListing(target: string, code: string): void {
+ const real = fsp.readdir;
+ const spy = spyOn(fsp, 'readdir').mockImplementation((async (path: fs.PathLike, options?: unknown) => {
+ if (String(path) === target) throw errno(code, target);
+ return (real as (p: fs.PathLike, o?: unknown) => Promise<unknown>)(path, options);
+ }) as typeof fsp.readdir);
+ restores.push(() => spy.mockRestore());
+}
+
+describe('assertNoPhysicalRootOverlap walk', () => {
+ test('a subdirectory pruned between listing and descent is skipped', () => {
+ const root = checkout();
+ afterSyncListing(path => { if (path === join(root, '.git', 'objects')) rmSync(join(root, '.git', 'objects', '06'), { recursive: true }); });
+ expect(() => assertNoPhysicalRootOverlap(root)).not.toThrow();
+ });
+
+ test('a subdirectory replaced by a file between listing and descent is skipped', () => {
+ const root = checkout();
+ const target = join(root, '.git', 'objects', '06');
+ afterSyncListing(path => {
+ if (path !== join(root, '.git', 'objects')) return;
+ rmSync(target, { recursive: true }); writeFileSync(target, 'now a file');
+ });
+ expect(() => assertNoPhysicalRootOverlap(root)).not.toThrow();
+ });
+
+ test('a reservation nested under .git is still found after a sibling vanished', () => {
+ const root = checkout();
+ const nested = join(root, '.git', 'objects', 'pack', 'child');
+ mkdirSync(nested);
+ writeFileSync(physicalRootReservationPath(nested), '{}');
+ afterSyncListing(path => { if (path === join(root, '.git', 'objects')) rmSync(join(root, '.git', 'objects', '06'), { recursive: true }); });
+ expect(() => assertNoPhysicalRootOverlap(root)).toThrow('contains another reserved canonical root');
+ });
+
+ test('a nested ownership stamp under .git is found', () => {
+ const root = checkout();
+ const nested = join(root, '.git', 'child');
+ mkdirSync(nested);
+ writeFileSync(join(nested, PHYSICAL_ROOT_MARKER), '{}');
+ expect(() => assertNoPhysicalRootOverlap(root)).toThrow('contains another reserved canonical root');
+ });
+
+ test('a root that vanishes after the existence check still throws', () => {
+ const root = checkout();
+ failSyncListing(root, 'ENOENT');
+ expect(() => assertNoPhysicalRootOverlap(root)).toThrow('ENOENT');
+ });
+
+ test('an unreadable subdirectory still throws', () => {
+ const root = checkout();
+ failSyncListing(join(root, '.git', 'objects', '06'), 'EACCES');
+ expect(() => assertNoPhysicalRootOverlap(root)).toThrow('EACCES');
+ });
+
+ test('walks a 20,000-file checkout within its budget', () => {
+ const root = checkout();
+ writeLargeWorktree(root, 20_000);
+ const started = performance.now();
+ assertNoPhysicalRootOverlap(root);
+ const elapsed = performance.now() - started;
+ console.log(`[physical-root-walk] 20,000-file overlap walk took ${elapsed.toFixed(0)}ms`);
+ expect(elapsed).toBeLessThan(testWaitMs(10_000));
+ }, 120_000);
+});
+
+describe('topologyDirectoryBytes walk', () => {
+ test('a subdirectory pruned between lstat and readdir is counted and skipped', async () => {
+ const root = checkout();
+ const target = join(root, '.git', 'objects', '06');
+ afterAsyncStat(path => { if (path === target) rmSync(target, { recursive: true }); });
+ expect(await topologyDirectoryBytes(root)).toBeGreaterThan(0);
+ });
+
+ test('a subdirectory replaced by a file between lstat and readdir is skipped', async () => {
+ const root = checkout();
+ const target = join(root, '.git', 'objects', '06');
+ afterAsyncStat(path => { if (path === target) { rmSync(target, { recursive: true }); writeFileSync(target, 'now a file'); } });
+ expect(await topologyDirectoryBytes(root)).toBeGreaterThan(0);
+ });
+
+ test('a root that vanishes after lstat still throws', async () => {
+ const root = checkout();
+ failAsyncListing(root, 'ENOENT');
+ await expect(topologyDirectoryBytes(root)).rejects.toThrow('ENOENT');
+ });
+
+ test('an unreadable subdirectory still throws', async () => {
+ const root = checkout();
+ failAsyncListing(join(root, '.git', 'objects', '06'), 'EACCES');
+ await expect(topologyDirectoryBytes(root)).rejects.toThrow('EACCES');
+ });
+});