Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): chmod managed-root registry entries only when the mode differs (#5297)

garrytan9c4b8846ea9b
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 8f9f7bf579..f908074eb8 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -11,7 +11,7 @@
- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work; the call then rebuilds the withdrawn pages' text projections before acknowledging, because a CLI process has no resident projection worker (a failed rebuild stays queued). `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL; `test/withdrawal-followup-writes.test.ts` covers writes after a forget whose effects stay queued. #5836: an omitted `entity` is inferred before admission (`inferRememberTarget`), and the inferred slug is used only when `planRememberTarget`'s checks pass as predicates (plus withdrawal, fence parse, no owner claim); otherwise the save is unattributed with `warnings` (`NO_ENTITY`/`ENTITY_LINK_FAILED`) + `hint`. The `entity_inferred` intent marker makes preparation dedup exact text only (never supersede) and notes the context; `test/remember-entity-inference.test.ts`.
- `src/core/page-state/import-guard.ts` — imported canonical bytes publish only after source/page identity and knowledge-revision CAS, including unchanged-file and legacy hash-repair paths. Prepared same-hash imports compare full canonical metadata and additive tags, since captured timestamps are excluded from content hashes. Tests: `import-revision-concurrency.test.ts`.
-- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.
+- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (`root-registry-idle-chmod-5297.test.ts`). The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.
- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths.
diff --git a/src/core/persistence/root-registry.ts b/src/core/persistence/root-registry.ts
index ede940af63..3b59aa626a 100644
--- a/src/core/persistence/root-registry.ts
+++ b/src/core/persistence/root-registry.ts
@@ -36,9 +36,13 @@ function syncDirectory(directory: string): void {
if (!(process.platform === 'win32' && ['EISDIR', 'EPERM', 'EINVAL', 'ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? ''))) throw error;
} finally { if (fd !== undefined) closeSync(fd); }
}
+/** An idle refresh must not touch inode metadata, so chmod only when the mode differs (#5297). */
+function ensureMode(path: string, mode: number): void {
+ if ((statSync(path).mode & 0o777) !== mode) chmodSync(path, mode);
+}
/** Returns whether the record changed; a changed record is already durable with its directory entry. */
function writePrivateRecord(file: string, value: string): boolean {
- if (existsSync(file) && readFileSync(file, 'utf8') === value) { chmodSync(file, 0o600); return false; }
+ if (existsSync(file) && readFileSync(file, 'utf8') === value) { ensureMode(file, 0o600); return false; }
const temporary = `${file}.${randomUUID()}.tmp`;
const fd = openSync(temporary, 'wx', 0o600);
try { writeFileSync(fd, value); fsyncSync(fd); } finally { closeSync(fd); }
@@ -99,7 +103,7 @@ function resolveFilesystemPath(path: string, realpath: (path: string) => string)
export function recordManagedRoots(brainId: string, records: ManagedRootRecord[], modeEpoch?: number): void {
if (!/^[a-f0-9-]{36}$/i.test(brainId)) throw new OperationError('storage_error', 'Invalid managed-root brain identity.');
if (!records.length) return;
- const directory = registryDirectory(); mkdirSync(directory, { recursive: true, mode: 0o700 }); chmodSync(directory, 0o700);
+ const directory = registryDirectory(); mkdirSync(directory, { recursive: true, mode: 0o700 }); ensureMode(directory, 0o700);
let changed = false;
for (const record of records) {
const root = canonicalFilesystemPath(record.local_path);
diff --git a/test/root-registry-idle-chmod-5297.test.ts b/test/root-registry-idle-chmod-5297.test.ts
new file mode 100644
index 0000000000..8194a9675a
--- /dev/null
+++ b/test/root-registry-idle-chmod-5297.test.ts
@@ -0,0 +1,41 @@
+/**
+ * #5297: the persistence consumer refreshes managed roots every tick. An idle
+ * refresh whose records are unchanged must not chmod the registry directory
+ * or its records (chmod updates inode ctime even when the mode is already
+ * right), while a drifted mode is still corrected.
+ */
+import { afterAll, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { recordManagedRoots } from '../src/core/persistence/root-registry.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-root-registry-5297-'));
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+const posix = process.platform !== 'win32';
+
+test.if(posix)('an unchanged refresh leaves registry inode metadata untouched; a drifted mode is repaired', async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const brainId = randomUUID();
+ const root = join(home, 'clones', 'source-example');
+ mkdirSync(root, { recursive: true });
+ const record = { local_path: root, source_id: 'source-example', topology_generation: 1 };
+ recordManagedRoots(brainId, [record]);
+ const directory = join(home, '.gbrain', 'persistence', 'managed-roots');
+ const file = join(directory, readdirSync(directory).find(name => name.endsWith('.json'))!);
+ const before = { dir: statSync(directory, { bigint: true }).ctimeNs, file: statSync(file, { bigint: true }).ctimeNs };
+ await Bun.sleep(20);
+ for (let tick = 0; tick < 3; tick++) recordManagedRoots(brainId, [record]);
+ expect(statSync(directory, { bigint: true }).ctimeNs).toBe(before.dir);
+ expect(statSync(file, { bigint: true }).ctimeNs).toBe(before.file);
+
+ chmodSync(file, 0o644);
+ chmodSync(directory, 0o755);
+ recordManagedRoots(brainId, [record]);
+ expect(statSync(directory).mode & 0o777).toBe(0o700);
+ expect(statSync(file).mode & 0o777).toBe(0o600);
+ });
+});