Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): keep writer coordination locks outside the checkout (#6765)

garrytan22965a869605
diff --git a/docs/architecture/key-files/page-identity-and-administration.md b/docs/architecture/key-files/page-identity-and-administration.md
index dbfbb92c32..61a46d56d4 100644
--- a/docs/architecture/key-files/page-identity-and-administration.md
+++ b/docs/architecture/key-files/page-identity-and-administration.md
@@ -29,6 +29,7 @@ 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`.
`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 bd8c1f037b..2d22739611 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -552,6 +552,54 @@ For containers, persist the canonical source root, its sibling-reservation
parent, persistence home and stable lock/coordination directory together across
recreation. Storage preflight reports each location and can identify Linux
overlay/tmpfs backing, but a mount shown as present is **not** attested durable.
+When `GBRAIN_HOME` lies inside the checkout, the lock directory is not the persistence
+home (see [where the coordination lock lives](#coordination-lock)): set
+`GBRAIN_COORDINATION_HOME` to a mounted directory outside the checkout so the lock
+survives recreation, because the default `~/.gbrain/persistence` usually sits on the
+container's ephemeral filesystem.
+
+<a id="coordination-lock"></a>**Where the coordination lock lives.** Every
+canonical checkout has one native lock file that all of its writers share, and
+it never lives inside the checkout it protects (a copied checkout must not copy
+its lock). Claim, reservation, reclone and transfer choose it with one rule;
+the first match wins:
+
+1. `reservation`: the path the outside-root reservation
+ (`.gbrain-owner-<sha256(root)>.json` beside the root) already records. A
+ recorded path always wins over the environment, so two processes with
+ different settings still lock the same file.
+2. `binding`: on a transfer, the accepting host binding's recorded path, when it
+ is absolute, canonical and outside the successor checkout.
+3. `persistence_home`: `<persistence home>/locks/<worktree id>.lock`
+ (`$GBRAIN_HOME/.gbrain/persistence`, else `~/.gbrain/persistence`) when that
+ is outside the checkout. This is every ordinary layout.
+4. `coordination_home` / `home_default`: when the persistence home is inside the
+ checkout (`GBRAIN_HOME` is the checkout or lies inside it),
+ `$GBRAIN_COORDINATION_HOME/locks/<namespace>/<worktree id>.lock`, or the same
+ under `~/.gbrain/persistence` when the variable is unset. The namespace is a
+ hash of the canonical checkout path and the host id, so one shared fallback
+ directory can serve several checkouts and hosts.
+5. A result still inside the checkout (for example `GBRAIN_COORDINATION_HOME`
+ pointing into it through a symlink) refuses with `storage_error` before
+ anything is written.
+
+`GBRAIN_COORDINATION_HOME` must be an absolute path without `..` segments and is
+read only when rule 4 applies. It comes from the process environment only: a
+`.env` file in the working directory cannot set it (it is on the cwd `.env`
+quarantine list). `gbrain sources writer status --json` prints
+`onboarding.sources[].coordination_lock` with the resolved `path` and the `rule`
+that chose it; an unclaimed checkout without a reservation reports the
+`directory` a claim would use, and an unreadable setting reports `error`.
+
+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
+marks it `old_path_wedge: true`. Upgrade, then run the claim again on the host
+that reserved it: the claim rewrites only the reservation's lock path (same
+token, brain, host and worktree), under a guard file beside the reservation. A
+reservation that names another brain or host, or a worktree the database
+already records, is left unchanged and keeps the refusal; that case needs
+verified writer recovery. Never delete the reservation to get past it.
### Claim and activate runbook
diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.md
index 5a30203230..ae78e812fb 100644
--- a/docs/mcp/DEPLOY.md
+++ b/docs/mcp/DEPLOY.md
@@ -750,6 +750,20 @@ Operator checklist:
Optional defense-in-depth: a dedicated Postgres role (or RLS) limited to the
allowed `source_id`s, so even a leaked connection string can't read everything.
+### Writer coordination lock in containers
+
+A managed checkout's writers share one native lock file outside the checkout.
+It lives in `$GBRAIN_HOME/.gbrain/persistence/locks` unless `GBRAIN_HOME` is the
+checkout or lies inside it; then it goes under `GBRAIN_COORDINATION_HOME` (else
+`~/.gbrain/persistence`). For the lock to survive container recreation, mount the
+directory that holds it together with the checkout and its parent: mount
+`GBRAIN_HOME`, or, when `GBRAIN_HOME` is inside the checkout, set
+`GBRAIN_COORDINATION_HOME` to a mounted absolute path outside the checkout in the
+container's environment (a `.env` file in the working directory cannot set it).
+`gbrain sources writer status --json` shows the resolved path and the rule that
+chose it under `onboarding.sources[].coordination_lock`; the full rule is in
+[topologies](../architecture/topologies.md#coordination-lock).
+
### Run gbrain under a real init (tini / `--init`)
If `gbrain serve` is your container's entrypoint, it runs as PID 1 and
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index f8c5ed279f..a76d163363 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -423,3 +423,4 @@ test/writeback-review-fixes.serial.test.ts global-state global-state: process-wi
test/resolve-ipc-rebind.serial.test.ts global-state global-state: binds real Unix sockets and spawns a child serve that is SIGKILLed; withEnv scopes GBRAIN_HOME
test/backup-preflight-6649.serial.test.ts global-state global-state: R3: constructs PGLiteEngine inside the restore-drill and fixture-brain steps (each disconnected in finally); creates symlinked homes and 8 GiB sparse files
test/windows-ipc-long-path-6573.serial.test.ts R1 R1: mutates process.env (USERPROFILE) to place the per-user run dir under a non-ASCII profile path; native windows-latest only
+test/coordination-lock.serial.test.ts global-state global-state: withEnv holds GBRAIN_HOME and GBRAIN_COORDINATION_HOME across awaited PGLite claims and transfers, and real native lock files are held across them
diff --git a/src/core/env-trust.ts b/src/core/env-trust.ts
index 967e71000b..f01e7f8c59 100644
--- a/src/core/env-trust.ts
+++ b/src/core/env-trust.ts
@@ -177,6 +177,7 @@ export const CWD_DOTENV_PROTECTED_KEYS: readonly string[] = [
'GBRAIN_BIN_OVERRIDE', // gbrain binary used by claw-test
// --- root / registry redirect ------------------------------------------
'GBRAIN_HOME', // relocates ~/.gbrain (config, .env, keys, registry)
+ 'GBRAIN_COORDINATION_HOME', // #6765: where a checkout's writer coordination lock goes when GBRAIN_HOME is inside it; a planted value moves the lock two writers must share
'GBRAIN_MOUNTS_PATH', // brain mounts registry file
'GBRAIN_WORKER_STATUS_PATH',
'GBRAIN_WORKER_STATUS_TOKEN',
diff --git a/src/core/persistence/coordination-lock.ts b/src/core/persistence/coordination-lock.ts
new file mode 100644
index 0000000000..3110e65850
--- /dev/null
+++ b/src/core/persistence/coordination-lock.ts
@@ -0,0 +1,93 @@
+import { homedir } from 'node:os';
+import { isAbsolute, join } from 'node:path';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { sha256 } from './digest.ts';
+import { localHostId, persistenceHome } from './identity.ts';
+import type { SqlEngine } from './model.ts';
+import { acquireNativeLock } from './native-lock.ts';
+import { coordinationPathInsideRoot, physicalRootError, readWedgedPhysicalRootReservation, repairReservationCoordinationPath,
+ reservationRepairGuardPath } from './physical-root-record.ts';
+import { canonicalFilesystemPath } from './root-registry.ts';
+
+/**
+ * #6765: where a worktree's native coordination lock lives. One resolver serves claim, physical-root reservation,
+ * topology clone, writer transfer and writer status:
+ * reservation the path the outside-root reservation already records (always wins over any env)
+ * binding the host binding's recorded path, when it is absolute, canonical and outside the root (transfer)
+ * persistence_home persistenceHome()/locks, when that is outside the canonical root (every ordinary layout)
+ * coordination_home $GBRAIN_COORDINATION_HOME/locks/<namespace>, when persistenceHome() is inside the root
+ * home_default ~/.gbrain/persistence/locks/<namespace>, the same case without GBRAIN_COORDINATION_HOME
+ * The namespace is sha256(canonical root, host id): a shared fallback home can span roots and hosts, and restored
+ * database clones can share a worktree id. A result still inside the root refuses.
+ */
+export type CoordinationLockRule = 'reservation' | 'binding' | 'persistence_home' | 'coordination_home' | 'home_default';
+export interface CoordinationLock { path: string; rule: CoordinationLockRule }
+export interface RecordedCoordinationLock { reservation?: string | null; binding?: string | null }
+
+const statusFix = () => readFix('Shows each source\'s coordination lock path and the rule that chose it, read-only.',
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--json'] });
+
+function insideRootRefusal(root: string, path: string) {
+ return opError('storage_error', `No coordination lock directory outside the canonical checkout ${root} is available.`,
+ `The writer lock for ${root} would land at ${path}, inside the files it protects, so nothing was claimed or reserved. `
+ + 'Export GBRAIN_COORDINATION_HOME as an absolute directory outside the checkout (in the process environment, not a .env file in the checkout) and run the command again.',
+ { fix: statusFix() });
+}
+
+/** The directory a new lock of `root` goes in, and the rule that chose it. A null host (read-only status before any claim) leaves the namespace off. */
+export function coordinationLockDirectory(path: string, hostId: string | null): { directory: string; rule: Exclude<CoordinationLockRule, 'reservation' | 'binding'> } {
+ const root = canonicalFilesystemPath(path);
+ const preferred = canonicalFilesystemPath(join(persistenceHome(), 'locks'));
+ if (!coordinationPathInsideRoot(root, preferred)) return { directory: preferred, rule: 'persistence_home' };
+ const override = process.env.GBRAIN_COORDINATION_HOME?.trim();
+ if (override && (!isAbsolute(override) || override.includes('\0') || override.split(/[\\/]/).includes('..'))) throw opError('invalid_params',
+ 'GBRAIN_COORDINATION_HOME must be an absolute path without ".." segments.',
+ `GBRAIN_COORDINATION_HOME is set to ${JSON.stringify(override)}, so no coordination lock was placed and nothing changed. Set it to an absolute directory outside ${root}, or unset it to use ~/.gbrain/persistence.`);
+ const locks = join(override || join(homedir(), '.gbrain', 'persistence'), 'locks');
+ const directory = canonicalFilesystemPath(hostId === null ? locks : join(locks, sha256(`${root}\0${hostId}`).slice(0, 32)));
+ if (coordinationPathInsideRoot(root, directory)) throw insideRootRefusal(root, directory);
+ return { directory, rule: override ? 'coordination_home' : 'home_default' };
+}
+
+export function resolveCoordinationLock(path: string, worktreeId: string, recorded: RecordedCoordinationLock = {}, hostId?: string): CoordinationLock {
+ if (recorded.reservation) return { path: recorded.reservation, rule: 'reservation' };
+ const root = canonicalFilesystemPath(path), binding = recorded.binding;
+ if (binding && isAbsolute(binding) && !binding.includes('\0') && canonicalFilesystemPath(binding) === binding && !coordinationPathInsideRoot(root, binding)) {
+ return { path: binding, rule: 'binding' };
+ }
+ const { directory, rule } = coordinationLockDirectory(root, hostId ?? localHostId());
+ const lock = canonicalFilesystemPath(join(directory, `${worktreeId}.lock`));
+ if (coordinationPathInsideRoot(root, lock)) throw insideRootRefusal(root, lock);
+ return { path: lock, rule };
+}
+
+/** How long a repair waits for another repairer of the same root before refusing. */
+const REPAIR_GUARD_WAIT_MS = 2000;
+
+/**
+ * #6766: a release before #6765 placed the lock of a checkout that contains GBRAIN_HOME inside that checkout, wrote the
+ * reservation and then refused it, so every later claim failed closed. A first claim on the reserving host rewrites only
+ * the reservation's coordinationPath, under a guard beside the reservation (independent of any env), when the brain and
+ * host match and no worktree row exists for it. A missing or healthy reservation returns before taking the guard, so a
+ * caller inside a database transaction never waits on it for a healthy root.
+ */
+export async function repairWedgedReservation(engine: SqlEngine, root: string, hostId: string): Promise<void> {
+ if (!readWedgedPhysicalRootReservation(root)) return;
+ const guard = await acquireNativeLock(reservationRepairGuardPath(root), { timeoutMs: REPAIR_GUARD_WAIT_MS });
+ if (!guard) throw opError('writer_lock_unavailable', 'Another process is repairing this checkout\'s reservation.',
+ `Another gbrain process is moving the coordination lock recorded for ${root} out of the checkout, so nothing was claimed. Run the claim again once that process has finished.`,
+ { fix: statusFix() });
+ try {
+ const wedged = readWedgedPhysicalRootReservation(root);
+ if (!wedged) return;
+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
+ if (wedged.brainId !== brain?.brain_id) throw physicalRootError('This checkout\'s reservation (its lock inside the checkout) belongs to another brain, so it was left unchanged.');
+ if (wedged.hostId !== hostId) throw physicalRootError('Another host reserved this physical checkout with its lock inside the checkout; only a claim on that host repairs it.');
+ const owned = await engine.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid', [wedged.worktreeId]);
+ if (owned.length) throw physicalRootError('An owned checkout requires verified writer recovery; its recorded coordination lock is never moved by a claim.');
+ const lock = resolveCoordinationLock(root, wedged.worktreeId, {}, hostId).path;
+ repairReservationCoordinationPath(root, wedged, lock);
+ process.stderr.write(`[persistence] reservation of ${root} recorded its coordination lock inside the checkout (${wedged.coordinationPath}); moved it to ${lock}, identity unchanged.\n`);
+ } finally { await guard.release(); }
+}
diff --git a/src/core/persistence/onboarding.ts b/src/core/persistence/onboarding.ts
index 18553280fd..97159d2093 100644
--- a/src/core/persistence/onboarding.ts
+++ b/src/core/persistence/onboarding.ts
@@ -2,8 +2,10 @@ import { existsSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { existingLocalHostId, persistenceHome } from './identity.ts';
-import { containsPath, getWorktreeBinding, readManagedMode } from './ownership.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 { inspectLegacyWriterLocks } from './legacy-locks.ts';
import { UNSUPPORTED_MANAGED_BULK_WRITERS } from './maintenance.ts';
import { isConnectorSourceKind } from './connector-identity.ts';
@@ -23,7 +25,27 @@ export function containerPathPreflight(paths: Record<string, string>, mountinfo?
const mount = mounts.find(entry => containsPath(entry.path, path));
const ephemeral = !!mount && (['tmpfs', 'ramfs'].includes(mount.type) || container && ['overlay', 'aufs'].includes(mount.type));
return { role, path, backing: ephemeral ? 'ephemeral' : mount ? 'mounted_unverified' : 'unknown', mount_path: mount?.path ?? null, filesystem: mount?.type ?? null };
- }), next_action: 'Verify that the canonical checkout, its parent (which holds the sibling reservation), and the persistence home/coordination lock survive container recreation together. A mounted path is not proof of durability. Do not delete ownership or lock files.' };
+ }), next_action: 'Verify that the canonical checkout, its parent (which holds the sibling reservation), and the persistence home/coordination lock survive container recreation together. A mounted path is not proof of durability. '
+ + 'When GBRAIN_HOME lies inside the checkout, the lock is placed under GBRAIN_COORDINATION_HOME (else ~/.gbrain/persistence) instead, so set GBRAIN_COORDINATION_HOME to a mounted directory outside the checkout. '
+ + 'A reservation an older release wrote with its lock inside the checkout (coordination_lock.old_path_wedge, "must live outside the canonical checkout") is repaired by the next claim on the host that reserved it. Do not delete ownership or lock files.' };
+}
+
+/**
+ * #6765: the coordination lock path of `root` and the rule that chose it, as a claim or transfer resolves it
+ * (coordination-lock.ts); an unclaimed root without a reservation reports the directory a claim would use.
+ * Read-only: never mints a host identity, so before the first claim the fallback namespace is left off.
+ */
+function coordinationLockStatus(root: string, binding: WorktreeBinding | null, host: string | null): Record<string, unknown> {
+ try {
+ 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' };
+ return { path: null, ...coordinationLockDirectory(root, host) };
+ } catch (error) {
+ return { path: binding?.coordination_path ?? null, rule: null, error: error instanceof Error ? error.message : String(error) };
+ }
}
export async function writerOnboardingPreflight(engine: BrainEngine, sourceId?: string) {
@@ -46,9 +68,12 @@ export async function writerOnboardingPreflight(engine: BrainEngine, sourceId?:
catch (error) { state = 'recovery_required'; physicalError = error instanceof Error ? error.message : String(error); }
}
const root = binding?.local_path ?? (connector ? null : configured);
+ const lock = root ? coordinationLockStatus(root, binding, host) : undefined;
+ const lockDirectory = typeof lock?.path === 'string' ? dirname(lock.path) : typeof lock?.directory === 'string' ? lock.directory : join(persistenceHome(), 'locks');
const paths = root ? containerPathPreflight({ canonical_root: root, reservation_parent: dirname(root), persistence_home: persistenceHome(),
- coordination_directory: binding?.coordination_path ? dirname(binding.coordination_path) : join(persistenceHome(), 'locks') }) : undefined;
- sources.push({ source_id: row.id, state, write_through: writeThrough, ...(physicalError ? { physical_error: physicalError } : {}), ...(paths ? { storage: paths } : {}) });
+ coordination_directory: lockDirectory }) : undefined;
+ sources.push({ source_id: row.id, state, write_through: writeThrough, ...(physicalError ? { physical_error: physicalError } : {}),
+ ...(lock ? { coordination_lock: lock } : {}), ...(paths ? { storage: paths } : {}) });
}
return { sources, legacy_locks: await inspectLegacyWriterLocks(engine), unsupported_maintenance: [...UNSUPPORTED_MANAGED_BULK_WRITERS],
procedure: 'For deliberate onboarding, stop and upgrade older writers on every host, review all sources and durable paths, explicitly claim each filesystem source using its fresh admin_state, inspect status again, then explicitly activate with --confirm-quiesced and a fresh admin_state. A claim alone fences legacy sync; finish activation before ordinary writes or sync. This inspection never claims, activates, repairs or switches to database-only storage.' };
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index 09706aef77..f7b8faf5e1 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
import { realpathSync, statSync } from 'node:fs';
-import { isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { isAbsolute, relative, resolve, sep } from 'node:path';
import { pipelined } from '../page-state/transactions.ts';
import type { BrainEngine } from '../engine.ts';
import { OperationError, opError } from '../ops/contract.ts';
@@ -11,14 +11,15 @@ import { discoverGitRoot } from '../sync-git.ts';
import { cliOptsToProgressOptions, getCliOptions } from '../cli-options.ts';
import type { ProgressOptions } from '../progress.ts';
import { detectManifestScope, storedManifestScope, worktreeManifest, type StoredWorktreeManifest, type WorktreeManifest } from './worktree-manifest.ts';
-import { localHostId, persistenceHome } from './identity.ts';
+import { localHostId } from './identity.ts';
+import { repairWedgedReservation, resolveCoordinationLock } from './coordination-lock.ts';
import type { SqlEngine, WriteRequest } from './model.ts';
import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';
import { acquireShared, deferToLease, exclusiveAcquired, joinLease, yieldLease } from './worktree-lease.ts';
import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';
import { assertPhysicalRoot, claimPhysicalRoot, preparePhysicalRootTransfer, readPhysicalRootReservation, restampPhysicalRoot } from './physical-root.ts';
import { assertPhysicalRootReservation, readPhysicalRootStamp } from './physical-root-record.ts';
-import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.ts';
+import { nativeFilesystemPath } from './root-registry.ts';
import { assertWriterAdminState } from './admin-intent.ts';
import { readGraduationRow } from './graduation-schema.ts';
import { assertWriterAdminUnlocked } from './admin-lock.ts';
@@ -99,9 +100,10 @@ export async function claimWorktree(engine: BrainEngine, sourceId: string, path:
try { root = realpathSync(discoverGitRoot(root)); } catch { /* ordinary directory source */ }
// Probe the native capability before recording ownership. Stable lock lives
// outside any source directory, so reclone cannot produce a second inode.
+ await repairWedgedReservation(engine, root, hostId);
const existingPhysical = readPhysicalRootReservation(root);
const candidateId = existingPhysical?.worktreeId ?? randomUUID();
- const lockPath = existingPhysical?.coordinationPath ?? canonicalFilesystemPath(join(persistenceHome(), 'locks', `${candidateId}.lock`));
+ const lockPath = resolveCoordinationLock(root, candidateId, { reservation: existingPhysical?.coordinationPath }, hostId).path;
const probe = await tryAcquireNativeLock(lockPath);
if (!probe) throw opError('writer_lock_unavailable', 'Cannot acquire the new worktree coordination lock.',
`Another gbrain process holds the coordination lock for this checkout, so source ${sourceId} was not claimed. Check writer status and run the claim again once that process has finished.`,
@@ -350,7 +352,8 @@ export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string
if (opts.selfTransfer && root !== binding.local_path) throw opError('source_changed', 'Self-transfer must target the recorded canonical path.',
`A self-transfer of source ${sourceId} only repairs its recorded checkout, so nothing was accepted. Pass --path ${binding.local_path ?? 'with the recorded canonical path from writer status'} instead.`,
{ fix: writerStatusFix(sourceId) });
- const coordination = opts.selfTransfer ? binding.coordination_path : readPhysicalRootReservation(root)?.coordinationPath ?? join(persistenceHome(), 'locks', `${binding.worktree_id}.lock`);
+ const coordination = opts.selfTransfer ? binding.coordination_path : resolveCoordinationLock(root, binding.worktree_id,
+ { reservation: readPhysicalRootReservation(root)?.coordinationPath, binding: binding.coordination_path }, hostId).path;
if (!coordination) throw opError('recovery_required', 'The recorded coordination path is missing.',
`Source ${sourceId}'s host binding has no coordination lock path, so no transfer was accepted. Inspect writer status and show it to the user; repairing the binding is a deliberate topology change (docs/architecture/topologies.md).`,
{ fix: writerStatusFix(sourceId) });
diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.ts
index 02d90061e1..2e84dd90dc 100644
--- a/src/core/persistence/physical-root-record.ts
+++ b/src/core/persistence/physical-root-record.ts
@@ -86,17 +86,51 @@ export function readPhysicalRootReservation(path: string): PhysicalRootReservati
export function readRecordedPhysicalRootReservation(recorded: string): PhysicalRootReservation | null {
return readReservationRecord(recorded);
}
-function readReservationRecord(root: string): PhysicalRootReservation | null {
+/** Whether `path` is `root` or lies under it (both canonical). */
+export function coordinationPathInsideRoot(root: string, path: string): boolean {
+ const rel = relative(root, path);
+ return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
+}
+function readReservationRecord(root: string, allowInsideLock = false): PhysicalRootReservation | null {
const value = readPrivate(physicalRootReservationPath(root)) as PhysicalRootReservation | null;
if (value === null) return null;
if (value.version !== 1 || ![value.token,value.brainId,value.worktreeId,value.hostId].every(uuid)
|| value.root !== root || typeof value.coordinationPath !== 'string' || !isAbsolute(value.coordinationPath) || value.coordinationPath.includes('\0')
|| ![value.initialDevice,value.initialInode,value.initialBirth].every(part => part === null || typeof part === 'string' && /^\d+$/.test(part))) throw physicalRootError();
- const lockRelative = relative(root, value.coordinationPath);
- if (canonicalFilesystemPath(value.coordinationPath) !== value.coordinationPath
- || !isAbsolute(lockRelative) && lockRelative !== '..' && !lockRelative.startsWith(`..${sep}`)) throw physicalRootError('The stable coordination lock must live outside the canonical checkout.');
+ if (canonicalFilesystemPath(value.coordinationPath) !== value.coordinationPath) throw physicalRootError();
+ if (!allowInsideLock && coordinationPathInsideRoot(root, value.coordinationPath)) throw physicalRootError('The stable coordination lock must live outside the canonical checkout. '
+ + 'A reservation an older release wrote with its lock inside the checkout (GBRAIN_HOME inside the source root) is repaired by the next claim of this checkout on the host that reserved it; do not delete it.');
return value;
}
+/** #6766: the reservation an older release wedged with its lock inside the checkout (every other field valid), or null. */
+export function readWedgedPhysicalRootReservation(path: string): PhysicalRootReservation | null {
+ const root = canonicalFilesystemPath(path);
+ const value = readReservationRecord(root, true);
+ return value && coordinationPathInsideRoot(root, value.coordinationPath) ? value : null;
+}
+/** The guard every wedged-reservation repairer of `root` takes: beside the reservation, so it never depends on the coordination env. */
+export function reservationRepairGuardPath(root: string): string {
+ return `${physicalRootReservationPath(canonicalFilesystemPath(root))}.repair.lock`;
+}
+/**
+ * #6766: rewrite only the coordinationPath of a wedged reservation. The caller holds the repair guard and verified the
+ * brain, host and absence of a worktree row; the record is re-read and compared by digest before the atomic rename.
+ */
+export function repairReservationCoordinationPath(path: string, expected: PhysicalRootReservation, coordinationPath: string): void {
+ const root = canonicalFilesystemPath(path);
+ if (expected.root !== root || canonicalFilesystemPath(coordinationPath) !== coordinationPath || coordinationPathInsideRoot(root, coordinationPath)) {
+ throw physicalRootError('The repaired coordination lock must be a canonical path outside the canonical checkout.');
+ }
+ replacePrivate(physicalRootReservationPath(root), { ...expected, coordinationPath }, () => {
+ const current = readReservationRecord(root, true);
+ if (!current || digest(current) !== digest(expected)) {
+ const error = physicalRootError('The ownership reservation changed while its coordination lock was being repaired; run the claim again.');
+ error.detail = 'stale_record';
+ throw error;
+ }
+ });
+ if (readPhysicalRootReservation(root)?.coordinationPath !== coordinationPath) throw physicalRootError('The repaired ownership reservation contains unexpected bytes.');
+}
export function readPhysicalRootStamp(root: string): PhysicalRootStamp | null {
const value = readPrivate(join(root, PHYSICAL_ROOT_MARKER)) as PhysicalRootStamp | null;
if (value && (value.version !== 1 || ![value.token,value.brainId,value.worktreeId].every(uuid)
@@ -225,12 +259,13 @@ export function physicalRootDeviceChange(stamp: PhysicalRootStamp, reservation:
|| info.birthtimeNs === 0n || stamp.device === info.dev.toString()) return null;
return { from: stamp.device, to: info.dev.toString() };
}
-function replacePrivate(path: string, value: unknown): void {
+function replacePrivate(path: string, value: unknown, beforeRename?: () => void): void {
const temporary = `${path}.${randomUUID()}.tmp`;
let created = false;
try {
created = createPrivate(temporary, value);
if (!created || digest(readPrivate(temporary)) !== digest(value)) throw physicalRootError('The re-stamped ownership record contains unexpected bytes.');
+ beforeRename?.();
renameSync(temporary, path); created = false; flushDirectory(dirname(path));
} finally { if (created) try { unlinkSync(temporary); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } }
}
diff --git a/src/core/persistence/physical-root.ts b/src/core/persistence/physical-root.ts
index fb45aa773b..4c56bdcb1c 100644
--- a/src/core/persistence/physical-root.ts
+++ b/src/core/persistence/physical-root.ts
@@ -3,7 +3,7 @@ import { existsSync, lstatSync, realpathSync, statSync } from 'node:fs';
import { join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { SqlEngine } from './model.ts';
-import { persistenceHome } from './identity.ts';
+import { repairWedgedReservation, resolveCoordinationLock } from './coordination-lock.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { adoptTransferredRootStamp, assertNoPhysicalRootOverlap, assertPhysicalRoot, assertPhysicalRootStamp, PHYSICAL_ROOT_MARKER, physicalRootDeviceChange, physicalRootError,
readPhysicalRootReservation, readPhysicalRootStamp, reservePhysicalRootRecord, restampPhysicalRootDevice, samePhysicalBirth, writePhysicalRootStamp, type PhysicalRootReservation } from './physical-root-record.ts';
@@ -22,9 +22,10 @@ async function brainIdentity(tx: SqlEngine): Promise<string> {
*/
export async function reservePhysicalRoot(tx: SqlEngine, path: string, opts: PhysicalRootClaim): Promise<PhysicalRootReservation> {
const root = canonicalFilesystemPath(path), brainId = await brainIdentity(tx);
+ await repairWedgedReservation(tx, root, opts.hostId);
const previous = readPhysicalRootReservation(root);
const worktreeId = opts.worktreeId ?? previous?.worktreeId ?? randomUUID();
- const coordinationPath = opts.coordinationPath ?? previous?.coordinationPath ?? canonicalFilesystemPath(join(persistenceHome(), 'locks', `${worktreeId}.lock`));
+ const coordinationPath = opts.coordinationPath ?? resolveCoordinationLock(root, worktreeId, { reservation: previous?.coordinationPath }, opts.hostId).path;
// A copied marker without its original sibling reservation is not a new root.
if (!previous && existsSync(join(root, PHYSICAL_ROOT_MARKER))) throw physicalRootError();
const reservation = previous ?? reservePhysicalRootRecord(root, { brainId, worktreeId, hostId: opts.hostId, coordinationPath });
diff --git a/src/core/persistence/topology-clone.ts b/src/core/persistence/topology-clone.ts
index 4f02041caf..a4c898a240 100644
--- a/src/core/persistence/topology-clone.ts
+++ b/src/core/persistence/topology-clone.ts
@@ -12,7 +12,8 @@ import { parseSourceConfig } from '../sources-load.ts';
import type { SourceLifecycleInput } from './source-lifecycle.ts';
import type { TopologyCloneRecovery } from './topology-clone-model.ts';
import { compactStoredManifest, getWorktreeBinding, humanManifestProgress, storedManifestScope, worktreeManifest } from './ownership.ts';
-import { localHostId, persistenceHome } from './identity.ts';
+import { localHostId } from './identity.ts';
+import { resolveCoordinationLock } from './coordination-lock.ts';
import { acquireNativeLock, type NativeLockHandle } from './native-lock.ts';
import { canonicalFilesystemPath, recordManagedRoots } from './root-registry.ts';
import { withFilesystemPublication } from './filesystem-guard.ts';
@@ -85,7 +86,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
{fix:writerStatusFix(input.sourceId)});
const reservedIdentity=readPhysicalRootReservation(target);
const worktreeId=currentBinding?.worktree_id??reservedIdentity?.worktreeId??randomUUID();
- const coordination=currentBinding?.coordination_path??reservedIdentity?.coordinationPath??join(persistenceHome(),'locks',`${worktreeId}.lock`);
+ const coordination=resolveCoordinationLock(target,worktreeId,{reservation:reservedIdentity?.coordinationPath,binding:currentBinding?.coordination_path}).path;
let newLock:NativeLockHandle|null=null;
if(!bindings.some(binding=>binding.worktree_id===worktreeId)){newLock=await acquireNativeLock(coordination!,{timeoutMs:5000});if(!newLock)throw opError('writer_lock_unavailable','The new clone coordination lock is busy.',
`Another gbrain process holds the coordination lock for ${target}, so source ${input.sourceId} was not cloned. Run the command again once that process has finished.`,
diff --git a/test/coordination-lock.serial.test.ts b/test/coordination-lock.serial.test.ts
new file mode 100644
index 0000000000..792311937b
--- /dev/null
+++ b/test/coordination-lock.serial.test.ts
@@ -0,0 +1,266 @@
+/**
+ * #6765/#6766/#6767: the writer coordination lock never lives inside the checkout it coordinates.
+ *
+ * 1. Protects: a claim, reservation, transfer and writer status resolve the worktree's native lock through
+ * one rule (recorded reservation, then the binding's outside-root path, then persistenceHome()/locks when
+ * it is outside the root, then GBRAIN_COORDINATION_HOME or ~/.gbrain/persistence namespaced by root and
+ * host, else refuse), and a reservation an older release wedged with an inside-root lock is repaired by
+ * the next first claim.
+ * 2. Fails when: the claim defaults the lock to persistenceHome() again (GBRAIN_HOME inside the root wedges
+ * the reservation), a transfer recomputes the lock from the accepting process's home, a second process
+ * resolves its own GBRAIN_COORDINATION_HOME instead of the recorded path, the repair rewrites another
+ * brain's/host's/owned reservation, or takes its guard for a healthy root.
+ * 3. Existing onboarding and transfer suites keep GBRAIN_HOME outside the checkout, so none reach this path.
+ * 4. No seam: real PGLite, real native locks, real reservation files.
+ * Serial: withEnv holds GBRAIN_HOME / GBRAIN_COORDINATION_HOME across awaited claims and transfers.
+ */
+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 { 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';
+import { reservePhysicalRoot } from '../src/core/persistence/physical-root.ts';
+import { assertPhysicalRoot, physicalRootReservationPath, readPhysicalRootReservation, reservePhysicalRootRecord } from '../src/core/persistence/physical-root-record.ts';
+import { acquireNativeLock } from '../src/core/persistence/native-lock.ts';
+import { writerOnboardingPreflight } from '../src/core/persistence/onboarding.ts';
+import { quarantineCwdDotenv } from '../src/core/env-trust.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const base = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-coordination-lock-')));
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(base, { recursive: true, force: true });
+});
+
+const outside = (root: string, path: string) => { const rel = relative(root, path); return isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`); };
+const codeOf = (error: unknown) => (error as { code?: string })?.code;
+async function rejection(promise: Promise<unknown>): Promise<Error & { code?: string }> {
+ try { await promise; } catch (error) { return error as Error & { code?: string }; }
+ throw new Error('expected a refusal');
+}
+async function source(root: string): Promise<string> {
+ const id = `lock-${randomUUID()}`;
+ mkdirSync(root, { recursive: true });
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, root]);
+ return id;
+}
+async function brainId(): Promise<string> {
+ const [row] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
+ return row.brain_id;
+}
+
+test('a checkout that is also GBRAIN_HOME claims with its lock under GBRAIN_COORDINATION_HOME, outside the checkout', async () => {
+ const root = join(base, 'home-is-root'), coordination = join(base, 'coordination');
+ const sourceId = await source(root);
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_COORDINATION_HOME: coordination }, async () => {
+ const binding = await claimWorktree(engine, sourceId, root);
+ const reservation = readPhysicalRootReservation(root)!;
+ expect(binding.coordination_path).toBe(reservation.coordinationPath);
+ expect(outside(root, binding.coordination_path!)).toBe(true);
+ expect(binding.coordination_path!.startsWith(join(coordination, 'locks') + sep)).toBe(true);
+ assertPhysicalRoot(root, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path });
+ expect((await claimWorktree(engine, sourceId, root)).worktree_id).toBe(binding.worktree_id);
+ });
+}, 30_000);
+
+test('a fallback that still resolves inside the checkout refuses before any reservation is written', async () => {
+ const root = join(base, 'symlinked-fallback'), alias = join(base, 'alias-into-root');
+ const sourceId = await source(root);
+ symlinkSync(root, alias, 'dir');
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_COORDINATION_HOME: alias }, async () => {
+ const error = await rejection(claimWorktree(engine, sourceId, root)) as Error & { code?: string; suggestion?: string };
+ expect(error.code).toBe('storage_error');
+ expect(error.suggestion).toContain('GBRAIN_COORDINATION_HOME');
+ expect(existsSync(physicalRootReservationPath(root))).toBe(false);
+ });
+});
+
+test('two processes with different GBRAIN_COORDINATION_HOME values on one root lock the same recorded file', async () => {
+ const root = join(base, 'two-homes');
+ const first = await source(root), second = await source(root);
+ const homeA = join(base, 'coordination-a'), homeB = join(base, 'coordination-b');
+ const claimed = await withEnv({ GBRAIN_HOME: root, GBRAIN_COORDINATION_HOME: homeA }, () => claimWorktree(engine, first, root));
+ expect(claimed.coordination_path!.startsWith(homeA + sep)).toBe(true);
+ const held = await acquireNativeLock(claimed.coordination_path!, { timeoutMs: 1000 });
+ expect(held).not.toBeNull();
+ try {
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_COORDINATION_HOME: homeB }, async () => {
+ expect(codeOf(await rejection(claimWorktree(engine, second, root)))).toBe('writer_lock_unavailable');
+ });
+ } finally { await held!.release(); }
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_COORDINATION_HOME: homeB }, async () => {
+ const reserved = await reservePhysicalRoot(engine, root, { hostId: localHostId() });
+ expect(reserved.coordinationPath).toBe(claimed.coordination_path!);
+ const joined = await claimWorktree(engine, second, root);
+ expect(joined.worktree_id).toBe(claimed.worktree_id);
+ expect(joined.coordination_path).toBe(claimed.coordination_path);
+ });
+ expect(existsSync(join(homeB, 'locks'))).toBe(false);
+}, 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);
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_COORDINATION_HOME: 'relative/not-used' }, async () => {
+ const binding = await claimWorktree(engine, sourceId, root);
+ expect(binding.coordination_path).toBe(join(persistenceHome(), 'locks', `${binding.worktree_id}.lock`));
+ });
+});
+
+test('the resolver namespaces the fallback by canonical root and host, defaults to ~/.gbrain/persistence and validates the override', async () => {
+ const { resolveCoordinationLock } = await import('../src/core/persistence/coordination-lock.ts');
+ const root = join(base, 'resolver-root'), nested = join(root, 'nested');
+ mkdirSync(nested, { recursive: true });
+ const hostA = randomUUID(), hostB = randomUUID();
+ await withEnv({ GBRAIN_HOME: nested, GBRAIN_COORDINATION_HOME: join(base, 'shared') }, () => {
+ const first = resolveCoordinationLock(root, 'worktree', {}, hostA);
+ expect(first.rule).toBe('coordination_home');
+ expect(resolveCoordinationLock(root, 'worktree', {}, hostA).path).toBe(first.path);
+ expect(resolveCoordinationLock(root, 'worktree', {}, hostB).path).not.toBe(first.path);
+ expect(resolveCoordinationLock(nested, 'worktree', {}, hostA).path).not.toBe(first.path);
+ expect(resolveCoordinationLock(root, 'worktree', { reservation: '/recorded/reservation.lock', binding: '/recorded/binding.lock' }, hostA))
+ .toEqual({ path: '/recorded/reservation.lock', rule: 'reservation' });
+ expect(resolveCoordinationLock(root, 'worktree', { binding: '/recorded/binding.lock' }, hostA)).toEqual({ path: '/recorded/binding.lock', rule: 'binding' });
+ expect(resolveCoordinationLock(root, 'worktree', { binding: join(root, 'inside.lock') }, hostA).rule).toBe('coordination_home');
+ });
+ await withEnv({ GBRAIN_HOME: nested, GBRAIN_COORDINATION_HOME: undefined }, () => {
+ const fallback = resolveCoordinationLock(root, 'worktree', {}, hostA);
+ expect(fallback.rule).toBe('home_default');
+ expect(fallback.path.startsWith(join(realpathSync(homedir()), '.gbrain', 'persistence', 'locks') + sep)).toBe(true);
+ });
+ for (const value of ['relative', `${join(base, 'shared')}/../elsewhere`]) {
+ await withEnv({ GBRAIN_HOME: nested, GBRAIN_COORDINATION_HOME: value }, () => {
+ expect(() => resolveCoordinationLock(root, 'worktree', {}, hostA)).toThrow('GBRAIN_COORDINATION_HOME');
+ });
+ }
+});
+
+for (const reserved of [false, true]) {
+ test(reserved ? 'a transfer takes the successor reservation\'s lock first' : 'a transfer accepted under another GBRAIN_HOME keeps the recorded lock', async () => {
+ const home = join(base, randomUUID()), root = join(home, 'checkout'), successor = join(home, 'successor');
+ const sourceId = await source(root);
+ writeFileSync(join(root, 'page.md'), 'Example content');
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const host = localHostId();
+ const original = await claimWorktree(engine, sourceId, root, host);
+ cpSync(root, successor, { recursive: true });
+ let expected = original.coordination_path!;
+ if (reserved) {
+ expected = join(home, 'successor.lock');
+ reservePhysicalRootRecord(successor, { brainId: await brainId(), worktreeId: original.worktree_id, hostId: host, coordinationPath: expected });
+ }
+ const prepared = await prepareWriterTransfer(engine, sourceId, host);
+ await withEnv({ GBRAIN_HOME: join(home, 'new-home') }, () =>
+ acceptWriterTransfer(engine, sourceId, successor, prepared.owner_epoch, prepared.manifest.digest, host));
+ const transferred = await getWorktreeBinding(engine, sourceId, host);
+ expect(transferred?.local_path).toBe(successor);
+ expect(transferred?.coordination_path).toBe(expected);
+ expect(readPhysicalRootReservation(successor)?.coordinationPath).toBe(expected);
+ });
+ }, 30_000);
+}
+
+/** The record a release before this fix left behind: valid in every field, its lock inside the checkout. */
+async function wedged(overrides: Record<string, string> = {}) {
+ const root = join(base, `wedged-${randomUUID()}`);
+ const sourceId = await source(root);
+ writeFileSync(join(root, 'page.md'), 'Canonical example');
+ const hostId = await withEnv({ GBRAIN_HOME: root }, () => localHostId());
+ const worktreeId = randomUUID(), info = statSync(root, { bigint: true });
+ const record = { version: 1, token: randomUUID(), brainId: await brainId(), worktreeId, hostId, root,
+ coordinationPath: join(root, '.gbrain', 'persistence', 'locks', `${worktreeId}.lock`),
+ initialDevice: info.dev.toString(), initialInode: info.ino.toString(), initialBirth: info.birthtimeNs.toString(), ...overrides };
+ const path = physicalRootReservationPath(root);
+ writeFileSync(path, JSON.stringify(record));
+ chmodSync(path, 0o600);
+ return { root, sourceId, hostId, record, path, env: { GBRAIN_HOME: root, GBRAIN_COORDINATION_HOME: join(base, 'repaired-locks') } };
+}
+
+test('a first claim repairs a reservation wedged by the old inside-root lock and keeps its identity', async () => {
+ const f = await wedged();
+ expect(() => readPhysicalRootReservation(f.root)).toThrow();
+ const binding = await withEnv(f.env, () => claimWorktree(engine, f.sourceId, f.root, f.hostId));
+ const reservation = readPhysicalRootReservation(f.root)!;
+ expect(binding.worktree_id).toBe(f.record.worktreeId);
+ expect({ ...reservation, coordinationPath: f.record.coordinationPath }).toEqual(f.record as typeof reservation);
+ expect(outside(f.root, reservation.coordinationPath)).toBe(true);
+ expect(binding.coordination_path).toBe(reservation.coordinationPath);
+}, 30_000);
+
+test('the managed reservation boundary repairs the same wedge', async () => {
+ const f = await wedged();
+ const reservation = await withEnv(f.env, () => reservePhysicalRoot(engine, f.root, { hostId: f.hostId }));
+ expect(reservation.worktreeId).toBe(f.record.worktreeId);
+ expect(reservation.token).toBe(f.record.token);
+ expect(outside(f.root, reservation.coordinationPath)).toBe(true);
+});
+
+test('a wedged reservation of another brain or host, or of a recorded worktree, is never rewritten', async () => {
+ for (const overrides of [{ brainId: randomUUID() }, { hostId: randomUUID() }] as Record<string, string>[]) {
+ const f = await wedged(overrides);
+ const before = readFileSync(f.path, 'utf8');
+ await withEnv(f.env, async () => { await rejection(claimWorktree(engine, f.sourceId, f.root, f.hostId)); });
+ expect(readFileSync(f.path, 'utf8')).toBe(before);
+ }
+ const f = await wedged();
+ await engine.executeRaw('INSERT INTO persistence_worktrees(id,owner_host_id,owner_epoch) VALUES($1::uuid,$2::uuid,1)', [f.record.worktreeId, f.hostId]);
+ const before = readFileSync(f.path, 'utf8');
+ await withEnv(f.env, async () => {
+ expect((await rejection(claimWorktree(engine, f.sourceId, f.root, f.hostId))).message).toContain('verified writer recovery');
+ });
+ expect(readFileSync(f.path, 'utf8')).toBe(before);
+}, 30_000);
+
+test('repairers serialize on a guard derived from the root, while a healthy root never takes it', async () => {
+ const f = await wedged();
+ const guard = await acquireNativeLock(`${physicalRootReservationPath(f.root)}.repair.lock`, { timeoutMs: 1000 });
+ expect(guard).not.toBeNull();
+ const fresh = join(base, `fresh-${randomUUID()}`);
+ const freshSource = await source(fresh);
+ const freshGuard = await acquireNativeLock(`${physicalRootReservationPath(fresh)}.repair.lock`, { timeoutMs: 1000 });
+ expect(freshGuard).not.toBeNull();
+ try {
+ await withEnv({ ...f.env, GBRAIN_COORDINATION_HOME: join(base, 'other-locks') }, async () => {
+ expect(codeOf(await rejection(claimWorktree(engine, f.sourceId, f.root, f.hostId)))).toBe('writer_lock_unavailable');
+ });
+ await withEnv({ GBRAIN_HOME: join(base, 'fresh-home') }, async () => {
+ expect((await claimWorktree(engine, freshSource, fresh)).local_path).toBe(fresh);
+ });
+ } finally { await guard!.release(); await freshGuard!.release(); }
+}, 30_000);
+
+test('a cwd .env cannot redirect the coordination lock', () => {
+ const dir = join(base, 'cwd-dotenv');
+ mkdirSync(dir);
+ writeFileSync(join(dir, '.env'), `GBRAIN_COORDINATION_HOME=${join(dir, 'planted')}\n`);
+ const env: Record<string, string | undefined> = { GBRAIN_COORDINATION_HOME: join(dir, 'planted') };
+ expect(quarantineCwdDotenv(env, dir, { warn: () => {} })).toEqual(['GBRAIN_COORDINATION_HOME']);
+ expect(env.GBRAIN_COORDINATION_HOME).toBeUndefined();
+});
+
+test('writer status prints the resolved lock path and the rule that chose it', async () => {
+ const root = join(base, 'status-root'), coordination = join(base, 'status-locks');
+ const bound = await source(root);
+ const pending = await source(join(base, 'status-unclaimed'));
+ await withEnv({ GBRAIN_HOME: root, GBRAIN_COORDINATION_HOME: coordination }, async () => {
+ const binding = await claimWorktree(engine, bound, root);
+ const [claimed] = (await writerOnboardingPreflight(engine, bound)).sources as Array<Record<string, any>>;
+ expect(claimed.coordination_lock).toEqual({ path: binding.coordination_path, rule: 'reservation' });
+ const [unclaimed] = (await writerOnboardingPreflight(engine, pending)).sources as Array<Record<string, any>>;
+ expect(unclaimed.coordination_lock).toMatchObject({ path: null, rule: 'persistence_home', directory: join(persistenceHome(), 'locks') });
+ });
+ const f = await wedged();
+ await withEnv(f.env, async () => {
+ const [stuck] = (await writerOnboardingPreflight(engine, f.sourceId)).sources as Array<Record<string, any>>;
+ expect(stuck.coordination_lock).toMatchObject({ path: f.record.coordinationPath, rule: 'reservation', old_path_wedge: true });
+ });
+}, 30_000);