Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(activation): a vanished source directory is a named source_changed blocker, dry run included (#5206)

garrytanfda58615260d
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 77e36089e9..1ab02a5b2e 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -6,7 +6,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](
- `src/core/persistence/connector-google-receipts.ts` — the managed Google attachment-repair preparer checks account/thread/message ownership from the current canonical snapshot, changes only the owned receipt frontmatter field, and installs provider-free text projections under the existing source-before-page publication locks. Page identity/revision, current authorization, source incarnation and file recovery guards remain mandatory; body, unrelated frontmatter, tags and the withdrawal ledger are preserved. It schedules no embeddings, loop detection or fact extraction. `connector-sync.ts` admits this narrow mutation and banks its committed receipts through the existing managed connector checkpoints.
-- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and active filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards before enabling managed writes. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders, under the lease transaction lock. Dry-run reports candidates without deletion. Registration never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still require canonical physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes.
+- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and active filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards before enabling managed writes. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders, under the lease transaction lock. Dry-run reports candidates without deletion. Registration never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still require canonical physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes. A non-connector source whose recorded `local_path` no longer exists (unclaimed, or claimed by this host) refuses `source_changed` with detail `source_path_missing`, naming the source, the path and the `sources set-path` / `sources remove` exits (the claimed checkout filled in), in `--dry-run` too (#5206, `test/activation-missing-source-path.test.ts`).
- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`.
- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index ed8d00f686..03481d732e 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -57,6 +57,7 @@ of making a duplicate.
| `targets_parked` (doctor: `parked_effects`) | effect `error_code` | A Git backup or withdrawal target failed five times in a row and was set aside so the other pages keep committing. An effect `error_code` of `git_index_stale` means an index lock older than 10 minutes blocks the checkout: `.git/index.lock` in it (`git -C <checkout> rev-parse --git-path index.lock` for a linked worktree). Remove it only if no git command is running there, then run the `retry-effects` command. A fresher lock (`git_index_locked`) is retried as contention and never parks. The page write itself committed; its Git backup or withdrawal is incomplete. Contention, dependency waits, shutdown and transient database errors never count toward the five. | `gbrain sources writer status <source>`, fix the cause it names, preview with `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, then run it without `--dry-run`. Each run grants one more attempt per parked target; a target that fails again parks again. |
| <a id="writer_admin_locked"></a>`writer_admin_locked` | `writer_admin_locked` | The operator set the brain's writer admin lock (`gbrain sources writer lock`), so writer claim, activate, transfer prepare and transfer accept refuse for every caller. Ordinary writes are not affected. | Agents: stop and ask the operator; do not unlock it yourself. The operator runs, on the brain host, `gbrain sources writer unlock`, re-reads `gbrain sources writer status <source> --json`, administers, then `gbrain sources writer lock` again. See the [writer admin lock](../architecture/topologies.md#writer-admin-lock). |
| <a id="writer_not_quiesced"></a>`writer_not_quiesced` | `writer_not_quiesced` | Activation found an older writer, a legacy lock, or queued, running or recovering work. When work blocks it, the message names the blocking effect id, kind, source, page and request id. | Stop the writers named in the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook), inspect the named work with `gbrain sources writer status <source> --json`, let it finish, then retry. A committed write whose embedding effect is stuck queued or failed is settled by `gbrain repair embedding-effects --source <source>` (preview), then the same command with `--apply`; see [stale queued embedding effects](repair.md#stale-queued-embedding-effects). |
+| <a id="activation_source_path_missing"></a>`source_path_missing` | `source_changed` | `gbrain sources writer activate` (with or without `--dry-run`) found a source whose recorded `local_path` no longer exists on this host, for example a checkout that lived in a temporary directory. Activation cannot verify that source's canonical directory, so nothing changed. The message names the source and the missing path. Claiming the source at another directory does not help while the stale path stays recorded. | Run the command the suggestion prints: `gbrain sources set-path <source> <directory>` to point the source at its checkout (the suggestion fills in the claimed directory when the source is claimed), or `gbrain sources remove <source> --confirm-destructive` when the source is no longer needed (`gbrain sources archive <source>` keeps a 72-hour grace period). Then `gbrain sources writer activate --confirm-quiesced --dry-run` and activate. |
| <a id="migrations_running"></a>`migrations_running` | `migrations_running` (exit 75) | `gbrain apply-migrations` (or the post-upgrade step of `gbrain upgrade`) found another runner holding the brain's orchestration lock and stopped before touching the migration ledger, so migrations never run twice in parallel. The message names the holder's host and pid. A holder that died is taken over automatically on the next run. `gbrain upgrade` reports this as `Migrations: running`, not as a failed upgrade. | Wait for the other run to finish; `gbrain doctor` shows migration progress. Then `gbrain apply-migrations --yes` confirms everything is applied. |
| <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull --retry-failed`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). |
| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. |
diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.ts
index 85cd9384bb..778934120c 100644
--- a/src/core/error-catalogue.ts
+++ b/src/core/error-catalogue.ts
@@ -37,6 +37,7 @@ export const ERROR_CATALOGUE = {
repair_kind_unavailable: { code: 'unavailable', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' },
colon_slug_windows_write_through: { code: 'colon_slug_windows_write_through', docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through' },
embedding_auth_failed: { code: 'embedding_auth_failed', docs: 'docs/guides/write-refusals.md#embedding_auth_failed' },
+ activation_source_path_missing: { code: 'source_changed', docs: 'docs/guides/write-refusals.md#activation_source_path_missing' },
managed_pull_skipped: { code: 'managed_pull_skipped', docs: 'docs/guides/write-refusals.md#managed_pull_skipped' },
} as const satisfies Record<string, CatalogueEntry>;
diff --git a/src/core/persistence/activation.ts b/src/core/persistence/activation.ts
index a137d77348..d7b9d3f7bd 100644
--- a/src/core/persistence/activation.ts
+++ b/src/core/persistence/activation.ts
@@ -1,4 +1,4 @@
-import { realpathSync } from 'node:fs';
+import { existsSync, realpathSync } from 'node:fs';
import { join, resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
@@ -11,6 +11,7 @@ import { assertWriterAdminUnlocked } from './admin-lock.ts';
import { notQuiescedError } from './blocking-effects.ts';
import { inspectLegacyWriterLocks } from './legacy-locks.ts';
import { deleteLockRowExact } from '../db-lock.ts';
+import { catalogueError } from '../error-catalogue.ts';
export interface ActivationReport {
enabled: boolean;
@@ -31,11 +32,20 @@ async function configuredSources(engine: BrainEngine, lock = false): Promise<Sou
return sources.map(source => ({ id: source.id, incarnation: source.incarnation, connector: source.kind === 'google' || source.kind === 'github',
root: source.local_path || (source.id === 'default' ? fallback : null) }));
}
+/** #5206: a recorded source directory that vanished is a named blocker with its exits, never a bare ENOENT. */
+function sourcePathMissing(source: SourceRoot, claimedRoot: string | null): OperationError {
+ const error = catalogueError('activation_source_path_missing',
+ `Source '${source.id}' records the local path ${source.root}, which does not exist on this host, so activation cannot verify its canonical directory.`,
+ `Point it at its checkout with gbrain sources set-path ${source.id} ${claimedRoot ? JSON.stringify(claimedRoot) : '<directory>'}, or remove it with gbrain sources remove ${source.id} --confirm-destructive; then rerun gbrain sources writer activate --confirm-quiesced --dry-run.`);
+ error.detail = 'source_path_missing';
+ return error;
+}
async function validatedBindings(engine: BrainEngine, sources: SourceRoot[], hostId: string | null, lock = false): Promise<WorktreeBinding[]> {
const bindings: WorktreeBinding[] = [];
for (const source of sources) {
let binding = await getWorktreeBinding(engine, source.id, hostId);
if ((!source.root || source.connector) && !binding) continue;
+ if (!binding && !source.connector && !existsSync(resolve(source.root!))) throw sourcePathMissing(source, null);
if (binding && lock) {
await engine.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [binding.worktree_id]);
binding = await getWorktreeBinding(engine, source.id, hostId);
@@ -48,6 +58,7 @@ async function validatedBindings(engine: BrainEngine, sources: SourceRoot[], hos
'SELECT local_path,coordination_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid', [binding.worktree_id, binding.owner_host_id]);
if (!owner?.local_path || !owner.coordination_path) throw new OperationError('writer_registration_required', 'The canonical owner registration is incomplete.');
if (binding.owner_host_id === hostId) {
+ if (source.root && !existsSync(resolve(source.root))) throw sourcePathMissing(source, binding.local_path && join(binding.local_path, binding.relative_path));
if (!binding.local_path || !binding.coordination_path
|| source.root && realpathSync(resolve(source.root)) !== realpathSync(join(binding.local_path, binding.relative_path))) {
throw new OperationError('source_changed', `Source '${source.id}' no longer matches its registered canonical directory.`);
diff --git a/test/activation-missing-source-path.test.ts b/test/activation-missing-source-path.test.ts
new file mode 100644
index 0000000000..0c0b0b5795
--- /dev/null
+++ b/test/activation-missing-source-path.test.ts
@@ -0,0 +1,83 @@
+/**
+ * #5206: writer activation with a source whose recorded local_path vanished is
+ * a named `source_changed` blocker (detail `source_path_missing`) naming the
+ * source, the missing path and the exits (`sources set-path`, `sources
+ * remove`), in --dry-run too, instead of a bare ENOENT from lstat.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { activatePersistence } from '../src/core/persistence/activation.ts';
+import { claimWorktree, managedPersistenceEnabled } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runSetPath } from '../src/commands/sources-set-path.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { flagRejection, gbrainInvocations, liveCliVerbs } from './helpers/cli-command-surface.ts';
+
+let engine: PGLiteEngine;
+let schemaVersion: string;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema();
+ schemaVersion = (await engine.getConfig('version'))!;
+}, 120_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+
+/** O-DX-2: each `gbrain …` command the prose hint names resolves and parses with the real CLI's flags. */
+function expectRunnableFix(fix: string) {
+ const invocations = [...fix.matchAll(/gbrain [^,;]+/g)].flatMap(m => gbrainInvocations(m[0].replace(/\.$/, '')));
+ expect(invocations.length).toBeGreaterThan(1);
+ for (const inv of invocations) {
+ expect(liveCliVerbs().has(inv.verb)).toBe(true);
+ expect(flagRejection(inv)).toBeNull();
+ }
+}
+
+async function fixture(run: (home: string, live: string) => Promise<void>) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-activation-missing-'));
+ const live = join(home, 'live'); mkdirSync(live);
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ await disposePersistenceConsumer(engine); await resetPgliteState(engine); await engine.setConfig('version', schemaVersion);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['live-example', live]);
+ await claimWorktree(engine, 'live-example', live);
+ await run(home, live);
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+test('an unclaimed source whose recorded directory vanished blocks activation by name, dry run included', () => fixture(async home => {
+ const gone = join(home, 'vanished-temp');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['stale-example', gone]);
+ for (const dryRun of [true, false]) {
+ const error = await activatePersistence(engine, { confirmQuiesced: true, dryRun }).catch(e => e);
+ expect(error).toMatchObject({ code: 'source_changed', detail: 'source_path_missing', docs: 'docs/guides/write-refusals.md#activation_source_path_missing' });
+ expect(error.message).toContain(`Source 'stale-example' records the local path ${gone}`);
+ expect(error.message).not.toContain('ENOENT');
+ expect(error.suggestion).toContain('gbrain sources set-path stale-example <directory>');
+ expect(error.suggestion).toContain('gbrain sources remove stale-example --confirm-destructive');
+ expectRunnableFix(error.suggestion);
+ }
+ expect(await managedPersistenceEnabled(engine)).toBe(false);
+}), 60_000);
+
+test('a claimed source whose recorded local_path vanished names its claimed checkout, and the printed set-path clears the blocker', () => fixture(async home => {
+ const claimed = join(home, 'claimed'); mkdirSync(claimed);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['default-example', claimed]);
+ await claimWorktree(engine, 'default-example', claimed);
+ const gone = join(home, 'tmp-vanished');
+ await engine.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1', ['default-example', gone]);
+ for (const dryRun of [true, false]) {
+ const error = await activatePersistence(engine, { confirmQuiesced: true, dryRun }).catch(e => e);
+ expect(error).toMatchObject({ code: 'source_changed', detail: 'source_path_missing' });
+ expect(error.message).toContain(`Source 'default-example' records the local path ${gone}`);
+ expect(error.suggestion).toContain(`gbrain sources set-path default-example ${JSON.stringify(claimed)}`);
+ expectRunnableFix(error.suggestion);
+ }
+ const log = console.log; console.log = () => {};
+ try { await runSetPath(engine, ['default-example', claimed]); } finally { console.log = log; }
+ expect(await activatePersistence(engine, { confirmQuiesced: true, dryRun: true })).toMatchObject({ enabled: false, activated: false, filesystem_sources: 2 });
+}), 60_000);