Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): the managed-worktree refusal names its root, source and evidence (#5279)

garrytan09b401aa27d5
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index f130911bb6..e1048206b6 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -96,7 +96,7 @@ a receipt can report has a row here.
| `writer_registration_required` | `writer_registration_required` | The source needs an active canonical owner before this operation, for example activation. | Claim the source on its owner host (`gbrain sources writer status <source>` names the next step). |
| `writer_identity_invalid` | `writer_identity_invalid` | This host's local writer identity file is unreadable or has an unknown format. | Run `gbrain doctor` on the host; it names the identity file to repair. |
| `writer_not_initialized` | `writer_not_initialized` | The brain has no persistence identity yet, usually because migrations have not run. | Run `gbrain apply-migrations --yes` on the brain host. |
-| `writer_coordinator_required` | `writer_coordinator_required` | The operation needs managed persistence (the write coordinator) and this brain or call path does not use it. | Run the operation through the command the message names, on a managed brain. |
+| `writer_coordinator_required` | `writer_coordinator_required` | The operation needs managed persistence (the write coordinator) and this brain or call path does not use it. A file write refused because the path sits in a managed canonical worktree names that worktree in the message, and its `detail` reads `root=<directory> source=<id or unknown> evidence=<marker file, managed-root registry or source binding>`. | Run the operation through the command the message names, on a managed brain. When the brain is not managed and the evidence is an ownership file (`.gbrain-owner.json`, `.gbrain-owner-<hash>.json`, `.gbrain-managed`), check it with `gbrain sources writer status` before removing anything: a half-finished claim is finished or rolled back through writer administration. |
| `fact_already_expired` | `fact_already_expired` | The fact the write targets is already expired or withdrawn. | Nothing to do; list active facts to find the current one. |
| `source_writeback_required` | `source_writeback_required` | The write needs a correction to the source's repository files, and this caller or profile never writes them. | Make the correction in the source repository, then sync. |
| `writer_upgrade_required` | `writer_upgrade_required` | The brain's schema is older than this operation needs. | Run `gbrain upgrade` (or `gbrain apply-migrations --yes`) on the brain host. |
diff --git a/src/core/persistence/filesystem-guard.ts b/src/core/persistence/filesystem-guard.ts
index 03033e91cc..f947fdc9df 100644
--- a/src/core/persistence/filesystem-guard.ts
+++ b/src/core/persistence/filesystem-guard.ts
@@ -3,11 +3,11 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import { isAbsolute, relative, resolve, sep } from 'node:path';
import { OperationError } from '../ops/contract.ts';
import type { SqlEngine } from './model.ts';
-import { canonicalFilesystemPath, hasManagedRootMarker, recordManagedRoots, registeredManagedRoots, type ManagedRootRecord } from './root-registry.ts';
+import { canonicalFilesystemPath, managedRootMarkerFor, recordManagedRoots, registeredManagedRootRecords, type ManagedRootRecord } from './root-registry.ts';
interface FileCapability { roots: string[]; active: boolean; }
const active = new AsyncLocalStorage<FileCapability>();
-const managedRoots = new Map<string, Set<string>>();
+const managedRoots = new Map<string, Map<string, string | undefined>>();
const datastorePaths = new WeakMap<SqlEngine, string>();
export function managedFilesystemDatastorePath(engine: SqlEngine): string | undefined { return datastorePaths.get(engine); }
/** Record the selected engine path, never a guessed default from ambient config. */
@@ -34,20 +34,39 @@ export async function refreshManagedFilesystemRoots(engine: SqlEngine, databaseP
signal?.throwIfAborted();
if (brain.enabled && databasePath) roots.push({ local_path: databasePath });
if (brain.enabled) recordManagedRoots(brain.brain_id, roots, brain.mode_epoch == null ? undefined : Number(brain.mode_epoch));
- managedRoots.set(brain.brain_id, new Set(roots.map(row => resolve(row.local_path))));
+ managedRoots.set(brain.brain_id, new Map(roots.map(row => [resolve(row.local_path), row.source_id])));
}
export function hasFilesystemPublication(path: string): boolean {
const held = active.getStore();
return held?.active === true && held.roots.some(root => encloses(root, path));
}
+export interface ManagedFilesystemRoot { root: string; sourceId?: string; evidence: string }
+/** The managed canonical worktree the path is inside (or encloses), with the evidence that marks it. */
+export function managedFilesystemRootFor(path: string): ManagedFilesystemRoot | null {
+ const related = (root: string) => encloses(root, path) || encloses(path, root);
+ const known = [...registeredManagedRootRecords().map(record => ({ root: record.root, sourceId: record.source_id, evidence: 'managed-root registry' })),
+ ...[...managedRoots.values()].flatMap(roots => [...roots].map(([root, sourceId]) => ({ root, sourceId, evidence: 'source binding' })))];
+ const marker = managedRootMarkerFor(path);
+ if (marker) {
+ const sourceId = known.find(entry => entry.sourceId && canonicalFilesystemPath(entry.root) === marker.root)?.sourceId;
+ return { root: marker.root, evidence: marker.marker, ...(sourceId ? { sourceId } : {}) };
+ }
+ const match = known.find(entry => related(entry.root));
+ return match ? { root: match.root, evidence: match.evidence, ...(match.sourceId ? { sourceId: match.sourceId } : {}) } : null;
+}
/** True when the path is inside (or encloses) a managed canonical worktree. */
export function isManagedFilesystemPath(path: string): boolean {
- return hasManagedRootMarker(path) || registeredManagedRoots().some(root => encloses(root, path) || encloses(path, root))
- || [...managedRoots.values()].some(roots => [...roots].some(root => encloses(root, path) || encloses(path, root)));
+ return managedFilesystemRootFor(path) !== null;
}
export function assertManagedFilesystemWrite(path: string): void {
- if (isManagedFilesystemPath(path) && !hasFilesystemPublication(path)) throw new OperationError('writer_coordinator_required',
- 'This file belongs to a managed canonical worktree.', 'Submit the change through the persistence coordinator.');
+ const managed = managedFilesystemRootFor(path);
+ if (!managed || hasFilesystemPublication(path)) return;
+ // #5279: name the root, its source and the evidence, so a stray ownership file is findable.
+ const error = new OperationError('writer_coordinator_required',
+ `This file belongs to the managed canonical worktree ${managed.root}${managed.sourceId ? ` (source ${managed.sourceId})` : ''}.`,
+ 'Submit the change through the persistence coordinator; check the root with gbrain sources writer status.');
+ error.detail = `root=${managed.root} source=${managed.sourceId ?? 'unknown'} evidence=${managed.evidence}`;
+ throw error;
}
/** Invalidate inherited async contexts before the owner releases the kernel lock. */
export async function withFilesystemPublication<T>(roots: string[], fn: () => Promise<T>): Promise<T> {
diff --git a/src/core/persistence/root-registry.ts b/src/core/persistence/root-registry.ts
index a1e3f6df65..b872799673 100644
--- a/src/core/persistence/root-registry.ts
+++ b/src/core/persistence/root-registry.ts
@@ -53,19 +53,25 @@ function markerExists(path: string): boolean {
}
/** Shared refusal marker helps installations with separate homes. It NEVER grants ownership. */
export function hasManagedRootMarker(path: string): boolean {
+ return managedRootMarkerFor(path) !== null;
+}
+/** The nearest ownership marker covering `path`: the root it marks and the marker file that proves it. */
+export function managedRootMarkerFor(path: string): { root: string; marker: string } | null {
let current = canonicalFilesystemPath(path);
for (;;) {
// A prepared claim is already a durable refusal, including when its target
// directory does not yet exist. Ownership still requires SQL/native proof.
const reservation = join(dirname(current), `.gbrain-owner-${createHash('sha256').update(current).digest('hex')}.json`);
- if (markerExists(reservation)) return true;
+ if (markerExists(reservation)) return { root: current, marker: reservation };
if (existsSync(current) && statSync(current).isDirectory()) {
- if (markerExists(join(current, '.gbrain-owner.json'))) return true;
+ for (const marker of [join(current, '.gbrain-owner.json'), join(current, '.gbrain-managed')]) {
+ if (markerExists(marker)) return { root: current, marker };
+ }
const metadata = gitMetadataDirectory(current);
- if (markerExists(join(current, '.gbrain-managed')) || metadata && markerExists(join(metadata, 'gbrain-managed.json'))) return true;
+ if (metadata && markerExists(join(metadata, 'gbrain-managed.json'))) return { root: current, marker: join(metadata, 'gbrain-managed.json') };
}
const parent = dirname(current);
- if (parent === current) return false;
+ if (parent === current) return null;
current = parent;
}
}
@@ -117,20 +123,24 @@ export function recordManagedRoots(brainId: string, records: ManagedRootRecord[]
}
/** Available before connect, including while another process owns local PGLite. */
export function registeredManagedRoots(): string[] {
+ return registeredManagedRootRecords().map(record => record.root);
+}
+/** The registry records with the source each root was recorded for (when the binding named one). */
+export function registeredManagedRootRecords(): Array<{ root: string; source_id?: string }> {
const directory = registryDirectory();
let files: string[];
try { files = readdirSync(directory); }
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; }
- const roots: string[] = [];
+ const records: Array<{ root: string; source_id?: string }> = [];
for (const file of files.filter(file => file.endsWith('.json'))) {
try {
const value = JSON.parse(readFileSync(join(directory, file), 'utf8'));
if (value.version !== 1 || typeof value.root !== 'string' || !isAbsolute(value.root)) throw new Error('invalid record');
- roots.push(canonicalFilesystemPath(value.root));
+ records.push({ root: canonicalFilesystemPath(value.root), ...(typeof value.source_id === 'string' ? { source_id: value.source_id } : {}) });
} catch {
throw new OperationError('writer_coordinator_required', 'Managed-root ownership records are unreadable.',
'Repair the local persistence registry through writer administration before running filesystem maintenance.');
}
}
- return roots;
+ return records;
}
diff --git a/test/filesystem-guard-names-root-5279.test.ts b/test/filesystem-guard-names-root-5279.test.ts
new file mode 100644
index 0000000000..fa03e83bf4
--- /dev/null
+++ b/test/filesystem-guard-names-root-5279.test.ts
@@ -0,0 +1,46 @@
+/**
+ * #5279: the managed-worktree refusal named no root, so an operator with a
+ * stray ownership file could not tell which directory or source it came from.
+ * The writer_coordinator_required error now names the matched root, its source
+ * when the registry recorded one, and the evidence (marker file or record).
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { assertManagedFilesystemWrite } from '../src/core/persistence/filesystem-guard.ts';
+import { canonicalFilesystemPath, recordManagedRoots } from '../src/core/persistence/root-registry.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const dir = mkdtempSync(join(tmpdir(), 'gbrain-guard-5279-'));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+function refusal(path: string): { code?: string; message: string; detail?: string } {
+ try { assertManagedFilesystemWrite(path); } catch (error) { return error as { code?: string; message: string; detail?: string }; }
+ throw new Error('expected a writer_coordinator_required refusal');
+}
+
+describe('managed worktree refusal names its root (#5279)', () => {
+ test('a stray ownership marker: the error names the marked root and the marker file', () =>
+ withEnv({ GBRAIN_HOME: join(dir, 'home-a') }, () => {
+ const root = join(dir, 'stray');
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, '.gbrain-owner.json'), '{}');
+ const error = refusal(join(root, 'notes', 'a.md'));
+ const canonical = canonicalFilesystemPath(root);
+ expect(error.code).toBe('writer_coordinator_required');
+ expect(error.message).toContain(canonical);
+ expect(error.detail).toBe(`root=${canonical} source=unknown evidence=${join(canonical, '.gbrain-owner.json')}`);
+ }));
+
+ test('a registered root: the error names the source the registry recorded', () =>
+ withEnv({ GBRAIN_HOME: join(dir, 'home-b') }, () => {
+ const root = join(dir, 'registered');
+ mkdirSync(root, { recursive: true });
+ recordManagedRoots('00000000-0000-4000-8000-000000000001', [{ local_path: root, source_id: 'source-example' }]);
+ const error = refusal(join(root, 'b.md'));
+ const canonical = canonicalFilesystemPath(root);
+ expect(error.message).toContain(`${canonical} (source source-example)`);
+ expect(error.detail).toContain(`root=${canonical} source=source-example`);
+ }));
+});