Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): say when GBRAIN_COORDINATION_HOME is overridden by a recorded lock (#6765)

garrytanfaf3f0708a97
diff --git a/docs/architecture/key-files/page-identity-and-administration.md b/docs/architecture/key-files/page-identity-and-administration.md
index 61a46d56d4..5c793b3d8b 100644
--- a/docs/architecture/key-files/page-identity-and-administration.md
+++ b/docs/architecture/key-files/page-identity-and-administration.md
@@ -29,7 +29,8 @@ records refuse without deleting uncertain state. Regression coverage:
changes, not against a malicious trusted local administrator. Read the
[operator procedure](../topologies.md) before changing its preconditions.
- `src/core/persistence/onboarding.ts` + `legacy-locks.ts` + `physical-root-recovery.ts` — read-only source onboarding states; exact same-host dead-lock cleanup under explicit activation opt-in; and state-bound same-owner root repair using a durable manifest and token-verified temporary stamp. #5914: `inspectPhysicalRootRecovery(root, identity, { relocated })` (`--confirm-relocated-root`) waives only the inode/birth comparison, requires the outside-root reservation and every other field to agree, returns the reservation with the live directory identity and marks the recovery `relocated: true`; `repairPhysicalRoot` then rewrites the reservation through `physical-root-record.ts` `replacePhysicalRootReservation` (compare-and-swap: already-equal is a no-op, anything else refuses with detail `stale_record`) before adopting the stamp. `physical-root-record.ts` also holds `assertPhysicalRootReservation` (native-lock callers that publish nothing: reservation worktree id plus stamp token, no inode), `readRecordedPhysicalRootReservation`, `inspectRelocatedPhysicalRoot` and `relocatePhysicalRoot` (P1.3c: a recorded path that now resolves through a symlink keeps its worktree; the reservation moves under the new `sha256(root)` name and the stamp names the new root). `physical-root.ts` `restampPhysicalRoot` handles a filesystem device id that changed while the owner token, brain, worktree, root, inode and a non-zero birth time still match (macOS can renumber `st_dev` across reboots): under the caller's outside-root native lock, one transaction verifies owner host, brain and host binding and rewrites the recorded self-transfer copies and retained topology staging identities (each only while it still names the old device); after commit the stamp and the reservation's initial device are rewritten and the event is logged, so an interruption between the two leaves a device-only change the next locked acquisition finishes. Ownership markers inside a retained topology clone stage are not re-stamped; an interrupted clone recovery that spans a device renumbering still needs source recovery. `assertPhysicalRoot` stays read-only; zero birth time or any other difference keeps the refusal. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.
-- `src/core/persistence/coordination-lock.ts` — the one resolver of a worktree's native coordination lock path, used by `claimWorktree`, `reservePhysicalRoot` (managed claim and clone), `runManagedSourceClone` and `acceptWriterTransfer`. `resolveCoordinationLock(root, worktreeId, { reservation, binding }, hostId)` returns `{ path, rule }`: the recorded reservation path (always wins over env), then a transfer's recorded binding path when absolute, canonical and outside the root, then `coordinationLockDirectory`: `persistenceHome()/locks` when outside the canonical root (`persistence_home`), else `$GBRAIN_COORDINATION_HOME/locks/<sha256(root\0host)[:32]>` (`coordination_home`, absolute and no `..`, else `invalid_params`) or `~/.gbrain/persistence/locks/<namespace>` (`home_default`); a result still inside the root refuses `storage_error` before any reservation is written. `GBRAIN_COORDINATION_HOME` is on the cwd `.env` quarantine list. `repairWedgedReservation(engine, root, hostId)` (called before `claimWorktree`'s transaction and at the top of `reservePhysicalRoot`) returns at once for a missing or healthy reservation; for one whose recorded lock is inside the root (`physical-root-record.ts` `readWedgedPhysicalRootReservation`) it takes the env-independent guard `reservationRepairGuardPath` (beside the reservation, 2 s wait, else `writer_lock_unavailable`), re-checks, requires the brain id, the claiming host id and no `persistence_worktrees` row, and `repairReservationCoordinationPath` rewrites only `coordinationPath` (digest re-read before the atomic rename, `stale_record` otherwise). `onboarding.ts` reports each source's `coordination_lock` (`path`, `rule`, `old_path_wedge`, or the `directory` an unclaimed root would use; never mints a host id) and uses it for the storage preflight's `coordination_directory`. Tests: `test/coordination-lock.serial.test.ts`.
+- `src/core/persistence/coordination-lock.ts` — the one resolver of a worktree's native coordination lock path, used by `claimWorktree`, `reservePhysicalRoot` (managed claim and clone), `runManagedSourceClone` and `acceptWriterTransfer`. `resolveCoordinationLock(root, worktreeId, { reservation, binding }, hostId)` returns `{ path, rule }`: the recorded reservation path (always wins over env), then a transfer's recorded binding path when absolute, canonical and outside the root, then `coordinationLockDirectory`: `persistenceHome()/locks` when outside the canonical root (`persistence_home`), else `$GBRAIN_COORDINATION_HOME/locks/<sha256(root\0host)[:32]>` (`coordination_home`, absolute and no `..`, else `invalid_params`) or `~/.gbrain/persistence/locks/<namespace>` (`home_default`); a result still inside the root refuses `storage_error` before any reservation is written. `GBRAIN_COORDINATION_HOME` is on the cwd `.env` quarantine list. `repairWedgedReservation(engine, root, hostId)` (called before `claimWorktree`'s transaction and at the top of `reservePhysicalRoot`) returns at once for a missing or healthy reservation; for one whose recorded lock is inside the root (`physical-root-record.ts` `readWedgedPhysicalRootReservation`) it takes the env-independent guard `reservationRepairGuardPath` (beside the reservation, 2 s wait, else `writer_lock_unavailable`), re-checks, requires the brain id, the claiming host id and no `persistence_worktrees` row, and `repairReservationCoordinationPath` rewrites only `coordinationPath` (digest re-read before the atomic rename, `stale_record` otherwise). `onboarding.ts` reports each source's `coordination_lock` (`path`, `rule`, `old_path_wedge`, or the `directory` an unclaimed root would use; never mints a host id) and uses it for the storage preflight's `coordination_directory`. Tests: `test/coordination-lock.serial.test.ts`. `coordinationHomeIgnored(root, recorded)` reports a set `GBRAIN_COORDINATION_HOME` that applies to the root (rule 4) but names another directory than the recorded lock (`configured_directory`, `recorded_path`, `move_step`); writer status adds it as `coordination_lock.coordination_home_ignored`.
+- `src/commands/doctor/checks/coordination-lock.ts` — doctor `coordination_lock_location` (read-only): warns, per source checkout or host binding of this host, when `coordinationHomeIgnored` reports the recorded lock wins over `GBRAIN_COORDINATION_HOME`, naming the recorded path and the move step. Test: `test/coordination-lock.serial.test.ts`.
`stampDeepResearchIds` uses each result's own source, including query fallback
and image paths. `fetch` independently applies the current source grant and
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index 2d22739611..47c34911c8 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -591,6 +591,17 @@ quarantine list). `gbrain sources writer status --json` prints
that chose it; an unclaimed checkout without a reservation reports the
`directory` a claim would use, and an unreadable setting reports `error`.
+<a id="coordination-home-ignored"></a>Because a recorded path wins, changing
+`GBRAIN_COORDINATION_HOME` after a checkout's reservation was written moves
+nothing: every process keeps locking the recorded file. When the variable applies
+to a checkout (rule 4) and names another directory than the recorded lock's,
+`writer status --json` adds `coordination_lock.coordination_home_ignored`
+(`configured_directory`, `recorded_path`, `move_step`) and doctor's
+`coordination_lock_location` warns with the same move step: make the recorded
+lock's directory survive container recreation (mount it), and unset the variable
+for that checkout's processes if it was meant to move the lock. No gbrain command
+relocates a recorded lock yet; never edit or delete the reservation to force one.
+
A reservation written before this rule existed, for a checkout that contains
`GBRAIN_HOME`, records its lock inside the checkout, so every claim refused with
"The stable coordination lock must live outside the canonical checkout". Status
diff --git a/src/commands/doctor/checks/coordination-lock.ts b/src/commands/doctor/checks/coordination-lock.ts
new file mode 100644
index 0000000000..f3aee578e5
--- /dev/null
+++ b/src/commands/doctor/checks/coordination-lock.ts
@@ -0,0 +1,43 @@
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+
+const DOCS = 'docs/architecture/topologies.md#coordination-lock';
+
+/**
+ * v3 review (#6765): a checkout's recorded coordination lock always wins over
+ * GBRAIN_COORDINATION_HOME. When the variable applies to a checkout (its
+ * persistence home lies inside it) and names another directory than the lock
+ * its reservation records, warn: the operator expects the lock under the
+ * variable (often a mounted directory in a container) while every process keeps
+ * using the recorded file. Read-only; names the recorded path and the move step.
+ */
+export async function checkCoordinationLockLocation(engine: BrainEngine): Promise<Check> {
+ const name = 'coordination_lock_location';
+ try {
+ const { existsSync } = await import('node:fs');
+ const { readPhysicalRootReservation } = await import('../../../core/persistence/physical-root-record.ts');
+ const { coordinationHomeIgnored } = await import('../../../core/persistence/coordination-lock.ts');
+ const { existingLocalHostId } = await import('../../../core/persistence/identity.ts');
+ const roots = await engine.executeRaw<{ root: string; source_id: string | null }>(`
+ SELECT DISTINCT local_path AS root,id AS source_id FROM sources WHERE local_path IS NOT NULL AND NOT COALESCE(archived,false)
+ UNION SELECT DISTINCT h.local_path,NULL FROM persistence_host_bindings h WHERE h.host_id=$1::uuid`, [existingLocalHostId()]);
+ const ignored: Array<{ root: string; source_id: string | null; configured_directory: string; recorded_path: string; move_step: string }> = [];
+ for (const { root, source_id } of roots) {
+ if (!existsSync(root)) continue;
+ let recorded: string | undefined;
+ try { recorded = readPhysicalRootReservation(root)?.coordinationPath; } catch { continue; }
+ const mismatch = recorded ? coordinationHomeIgnored(root, recorded) : null;
+ if (mismatch && !ignored.some(row => row.root === root)) ignored.push({ root, source_id, ...mismatch });
+ }
+ const details = { count: ignored.length, checkouts: ignored, docs: DOCS };
+ if (!ignored.length) return { name, status: 'ok', details,
+ message: 'Every checkout\'s recorded coordination lock agrees with GBRAIN_COORDINATION_HOME, or the variable does not apply.' };
+ const first = ignored[0]!;
+ return { name, status: 'warn', details, fix_unavailable_reason: 'operator_judgement',
+ message: `GBRAIN_COORDINATION_HOME names ${first.configured_directory}, but ${ignored.map(row => `${row.source_id ?? row.root} records its lock at ${row.recorded_path}`).join('; ')}; `
+ + `the recorded lock wins. ${first.move_step}` };
+ } catch (error) {
+ return { name, status: 'warn', details: { health: 'unknown' },
+ message: `Coordination lock locations could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };
+ }
+}
diff --git a/src/core/persistence/coordination-lock.ts b/src/core/persistence/coordination-lock.ts
index 3110e65850..9244a40bff 100644
--- a/src/core/persistence/coordination-lock.ts
+++ b/src/core/persistence/coordination-lock.ts
@@ -1,5 +1,5 @@
import { homedir } from 'node:os';
-import { isAbsolute, join } from 'node:path';
+import { dirname, isAbsolute, join, sep } from 'node:path';
import { opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { sha256 } from './digest.ts';
@@ -62,6 +62,28 @@ export function resolveCoordinationLock(path: string, worktreeId: string, record
return { path: lock, rule };
}
+export interface CoordinationHomeIgnored { configured_directory: string; recorded_path: string; move_step: string }
+
+/**
+ * v3 review: a recorded lock always wins over GBRAIN_COORDINATION_HOME, so when the variable applies to `root`
+ * (rule 4) and names another directory than the recorded lock's, say so: the recorded file stays in use by every
+ * process, and the step that changes where it lives is the operator's (no claim or env change moves it). Null when
+ * the variable is unset, invalid, not read for this root, or already names the recorded location.
+ */
+export function coordinationHomeIgnored(root: string, recordedPath: string): CoordinationHomeIgnored | null {
+ const override = process.env.GBRAIN_COORDINATION_HOME?.trim();
+ if (!override) return null;
+ let resolved: ReturnType<typeof coordinationLockDirectory>;
+ try { resolved = coordinationLockDirectory(root, null); } catch { return null; }
+ if (resolved.rule !== 'coordination_home') return null;
+ const recorded = canonicalFilesystemPath(recordedPath);
+ if (recorded.startsWith(resolved.directory + sep)) return null;
+ return { configured_directory: resolved.directory, recorded_path: recorded,
+ move_step: `Nothing moves: every process keeps locking ${recorded}, because GBRAIN_COORDINATION_HOME only places the lock of a checkout that has no reservation yet, and no claim, transfer or environment change rewrites a recorded one. `
+ + `Make ${dirname(recorded)} survive container recreation (mount it), and unset GBRAIN_COORDINATION_HOME for this checkout's processes if it was meant to move the lock. `
+ + 'No gbrain command relocates a recorded lock yet (docs/architecture/topologies.md#coordination-lock).' };
+}
+
/** How long a repair waits for another repairer of the same root before refusing. */
const REPAIR_GUARD_WAIT_MS = 2000;
diff --git a/src/core/persistence/onboarding.ts b/src/core/persistence/onboarding.ts
index 97159d2093..3983add270 100644
--- a/src/core/persistence/onboarding.ts
+++ b/src/core/persistence/onboarding.ts
@@ -5,7 +5,7 @@ import { existingLocalHostId, persistenceHome } from './identity.ts';
import { containsPath, getWorktreeBinding, readManagedMode, type WorktreeBinding } from './ownership.ts';
import { assertPhysicalRoot } from './physical-root.ts';
import { readPhysicalRootReservation, readWedgedPhysicalRootReservation } from './physical-root-record.ts';
-import { coordinationLockDirectory } from './coordination-lock.ts';
+import { coordinationHomeIgnored, coordinationLockDirectory } from './coordination-lock.ts';
import { inspectLegacyWriterLocks } from './legacy-locks.ts';
import { UNSUPPORTED_MANAGED_BULK_WRITERS } from './maintenance.ts';
import { isConnectorSourceKind } from './connector-identity.ts';
@@ -40,8 +40,11 @@ function coordinationLockStatus(root: string, binding: WorktreeBinding | null, h
const wedged = readWedgedPhysicalRootReservation(root);
if (wedged) return { path: wedged.coordinationPath, rule: 'reservation', old_path_wedge: true };
const reservation = readPhysicalRootReservation(root)?.coordinationPath;
- if (reservation) return { path: reservation, rule: 'reservation' };
- if (binding?.coordination_path) return { path: binding.coordination_path, rule: 'binding' };
+ const recorded = reservation ? { path: reservation, rule: 'reservation' } : binding?.coordination_path ? { path: binding.coordination_path, rule: 'binding' } : null;
+ if (recorded) {
+ const ignored = coordinationHomeIgnored(root, recorded.path);
+ return ignored ? { ...recorded, coordination_home_ignored: ignored } : recorded;
+ }
return { path: null, ...coordinationLockDirectory(root, host) };
} catch (error) {
return { path: binding?.coordination_path ?? null, rule: null, error: error instanceof Error ? error.message : String(error) };
diff --git a/test/coordination-lock.serial.test.ts b/test/coordination-lock.serial.test.ts
index 792311937b..b3cd0eb1d8 100644
--- a/test/coordination-lock.serial.test.ts
+++ b/test/coordination-lock.serial.test.ts
@@ -18,7 +18,7 @@ import { afterAll, beforeAll, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
-import { isAbsolute, join, relative, sep } from 'node:path';
+import { dirname, isAbsolute, join, relative, sep } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { acceptWriterTransfer, claimWorktree, getWorktreeBinding, prepareWriterTransfer } from '../src/core/persistence/ownership.ts';
import { localHostId, persistenceHome } from '../src/core/persistence/identity.ts';
@@ -107,6 +107,34 @@ test('two processes with different GBRAIN_COORDINATION_HOME values on one root l
expect(existsSync(join(homeB, 'locks'))).toBe(false);
}, 30_000);
+test('GBRAIN_COORDINATION_HOME changed after the reservation: the recorded lock still wins, and writer status and doctor say so with the move step', async () => {
+ const { checkCoordinationLockLocation } = await import('../src/commands/doctor/checks/coordination-lock.ts');
+ const root = join(base, 'env-changed'), homeA = join(base, 'env-changed-a'), homeB = join(base, 'env-changed-b');
+ const sourceId = await source(root);
+ const claimed = await withEnv({ GBRAIN_HOME: root, GBRAIN_COORDINATION_HOME: homeA }, async () => {
+ const binding = await claimWorktree(engine, sourceId, root);
+ expect((await checkCoordinationLockLocation(engine)).details).toMatchObject({ checkouts: expect.not.arrayContaining([expect.objectContaining({ root })]) });
+ return binding;
+ });
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_COORDINATION_HOME: homeB }, async () => {
+ expect((await claimWorktree(engine, sourceId, root)).coordination_path).toBe(claimed.coordination_path);
+ const status = await writerOnboardingPreflight(engine, sourceId) as { sources: Array<{ coordination_lock?: Record<string, unknown> }> };
+ const lock = status.sources[0]!.coordination_lock!;
+ expect(lock).toMatchObject({ path: claimed.coordination_path, rule: 'reservation' });
+ expect(lock.coordination_home_ignored).toMatchObject({ configured_directory: expect.stringContaining(join(homeB, 'locks')), recorded_path: claimed.coordination_path });
+ expect(String((lock.coordination_home_ignored as { move_step: string }).move_step)).toContain('No gbrain command relocates a recorded lock');
+ const doctor = await checkCoordinationLockLocation(engine);
+ expect(doctor.status).toBe('warn');
+ expect(doctor.message).toContain(`records its lock at ${claimed.coordination_path}`);
+ expect(doctor.message).toContain('the recorded lock wins');
+ expect(doctor.message).toContain(`Make ${dirname(claimed.coordination_path!)} survive container recreation`);
+ });
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_COORDINATION_HOME: homeA }, async () => {
+ const status = await writerOnboardingPreflight(engine, sourceId) as { sources: Array<{ coordination_lock?: Record<string, unknown> }> };
+ expect(status.sources[0]!.coordination_lock!.coordination_home_ignored).toBeUndefined();
+ });
+}, 30_000);
+
test('an ordinary root keeps its lock under persistenceHome() and never reads GBRAIN_COORDINATION_HOME', async () => {
const home = join(base, 'ordinary-home'), root = join(base, 'ordinary-root');
const sourceId = await source(root);