Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sources): remove and set-path dry runs run the physical-root check their real runs make (#6849)
time-attack366e81d9074d
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 030dd7d05e..7a86e89b20 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -61,7 +61,7 @@ of making a duplicate.| `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull`. || `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. || `physical_root_directory_changed` | `recovery_required` | The directory at the checkout's recorded path is not the one the owner stamped: its inode changed, or its birth time differs from the stamp by more than 1 µs, while the owner token, brain, worktree, root and device all still match. A checkout deleted and recreated at the same path (restore from backup, rebuilt container, Migration Assistant copy) looks like this. A birth time within 1 µs of the stamp is accepted (#6501: APFS reports a new directory's birth time tens of nanoseconds apart across processes); a stamp of `0` against a filesystem that now reports a birth time, or a damaged stamp, still refuses. | If the checkout was recreated at its recorded path, do a deliberate relocated-root self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. `writer status --json` prints the commands filled in. Retry the original write with the **same** request ID. Never delete ownership marker files. |-| <a id="recreated-root"></a>recreated or moved canonical root | `recovery_required` | The checkout at the recorded path is a different directory (new inode and birth time after a restore, a rebuilt container or a Migration Assistant copy) or the recorded path now resolves through a symlink; without this release every verb, self-transfer included, refused with no exit (#5914). | Same path, directory recreated: the self-transfer above with `--confirm-relocated-root` on **both** phases; it waives only the directory identity comparison and needs the reservation beside the root (`.gbrain-owner-<hash>.json`) and the stamp to agree on token, brain, worktree, root and coordination path. Recorded path now a symlink to the moved checkout: `gbrain sources set-path <source> <path>` on the owner host keeps the worktree and moves its records. `gbrain sources writer deactivate --dry-run` lists `physical_root` when its real run would refuse. Runbook: [recreated root](../architecture/topologies.md#recreated-root). Never delete ownership marker files. |+| <a id="recreated-root"></a>recreated or moved canonical root | `recovery_required` | The checkout at the recorded path is a different directory (new inode and birth time after a restore, a rebuilt container or a Migration Assistant copy) or the recorded path now resolves through a symlink; without this release every verb, self-transfer included, refused with no exit (#5914). | Same path, directory recreated: the self-transfer above with `--confirm-relocated-root` on **both** phases; it waives only the directory identity comparison and needs the reservation beside the root (`.gbrain-owner-<hash>.json`) and the stamp to agree on token, brain, worktree, root and coordination path. Recorded path now a symlink to the moved checkout: `gbrain sources set-path <source> <path>` on the owner host keeps the worktree and moves its records. `gbrain sources writer deactivate --dry-run` lists `physical_root` when its real run would refuse, and the dry runs of `gbrain sources remove` and `gbrain sources set-path` refuse with the same `recovery_required` their real runs would (#6849). Runbook: [recreated root](../architecture/topologies.md#recreated-root). Never delete ownership marker files. || <a id="embedding_budget_below_worst_case"></a>`embedding_budget_below_worst_case` | `embedding_budget_below_worst_case` | `gbrain migrate embeddings` (or the local `migrate_embeddings` operation) was given a `--max-cost-usd` cap below the migration's worst-case authorization: every planned provider request at its maximum input size, plus any debits a resumed run already holds. The run stopped before any provider request, re-chunk or vector invalidation, so nothing changed. The message and JSON carry `cap_usd`, `worst_case_usd`, `debited_usd` and `required_cap_usd`. | Re-run with the value the `suggestion` names, for example `gbrain migrate embeddings --to <provider:model> --dim <N> --max-cost-usd <required_cap_usd> --yes` (operation: `max_cost_usd`). Preview first with `--dry-run`, which prints the worst-case authorization beside the estimate. Requests settle to reported usage, so actual spend is usually far below the cap. See [embedding migration](embedding-migration.md). || frontmatter slug conflict | `frontmatter_slug_conflict` (`invalid_params` on a gbrain older than v0.60.47.0) | A file's frontmatter `slug:` names a different page than its path. On a write nothing is written; during sync the file is held and the rest of the source imports. | Remove the `slug:` line or make it match the path, commit, then sync. See [`frontmatter_slug_conflict`](#frontmatter_slug_conflict). || `cursor_processing_options_conflict` | `invalid_params` | Retired in 0.60.255.0 (#6712): no longer returned. An unfinished sync's processing opt-outs (`--no-embed`, `--no-extract`, `--no-schema-pack`) are inherited by every run that resumes it, and the result names them in `inherited_options`. An older gbrain still returns it when a run's processing flags conflict with the cursor's. | On an older gbrain, run the printed resume command (`gbrain sync --source <source> --no-pull` plus the saved flags) or drop the conflicting flag. After upgrading, rerun the sync: it finishes the cursor with its stored opt-outs. |diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 6c5f8a4067..0bce6ff77f 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -910,6 +910,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.307.0', id: 'google_account_credential_refusal', text: 'A managed Google source whose account cannot be read because the Google API is disabled for the OAuth project (or the grant is missing, or Google answers 403) now fails the sync with that credential error (`api_not_enabled` with the console link to enable the API, `scope_missing`, or `upstream` naming the 403) instead of `connector_account_changed`. A credential that no service can name for another reason still refuses as before.' },{ since: '0.60.307.0', id: 'auth_rescope_client_print_only', text: '`gbrain auth rescope --client <id>` (and `gbrain auth rescope-client <id>`) with no grant flag and no `--profile` now prints the client\'s stored grants and writes nothing (`--json`: `changed: false`, `written: false`), as the help always said, instead of refusing with `invalid_grant`. An unknown client id refuses with `client_not_found`, whose fix is `gbrain auth clients --json`. `--repair` alone still refuses.' },{ since: '0.60.307.0', id: 'file_drift_unknown_listed', text: '`gbrain repair file-drift --all-drifted` previews and the bare `gbrain repair file-drift` survey now list a conflicted page the live check cannot classify (canonical file missing, page gone, not the owner host, a refused or failed check) as `unknown`, counted under `unknown_<reason>` with the next step for that reason. They used to drop it silently, so a preview could read as empty. Unknown pages are never repaired and get no `--class` preview command.' },+ { since: '0.60.307.0', id: 'source_lifecycle_dry_run_physical_root', text: 'On a managed brain, `gbrain sources remove --dry-run` and `gbrain sources set-path --dry-run` now run the read-only physical-root check their real runs make, so a checkout deleted and recreated at its recorded path refuses the dry run with `recovery_required` (detail `physical_root_directory_changed`, naming the relocated-root self-transfer) instead of exiting 0 and then refusing the real command. The dry run still writes nothing.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.tsindex 9b8cbb7a21..7ed5e926b6 100644--- a/src/core/persistence/source-lifecycle.ts+++ b/src/core/persistence/source-lifecycle.ts@@ -16,7 +16,7 @@ import { isInsideGitRepo, hasTrackedContent } from '../git-remote.ts';import { containsPath, getWorktreeBinding, humanManifestProgress, type WorktreeBinding, type WorktreeManifest, worktreeManifest } from './ownership.ts';import { manifestDifferences, storedManifestScope, type WorktreeManifestScope } from './worktree-manifest.ts';import { localHostId } from './identity.ts';-import { advanceTopology, lockTopologyPrincipal, lockTopologyRows, settleTopologyRequests, topologyCanonicalStamp, topologyPrincipal, withTopologyLocks } from './topology-locks.ts';+import { advanceTopology, inspectTopologyPhysicalRoot, lockTopologyPrincipal, lockTopologyRows, settleTopologyRequests, topologyCanonicalStamp, topologyPrincipal, withTopologyLocks } from './topology-locks.ts';import { priorTopologyChange, recordTopologyChange, topologyReceipt } from './topology-receipts.ts';import { isWriteRequestId } from './types.ts';import { withCoordinatedWrite } from './context.ts';@@ -156,6 +156,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLconst retire=['archive','remove','purge'].includes(input.operation);const manifestRequired=!retire||(await engine.executeRaw<{digest:string|null}>(`SELECT w.manifest->>'digest' AS digest FROM persistence_source_bindings b JOIN persistence_worktrees w ON w.id=b.worktree_id WHERE b.source_id=$1`,[input.sourceId])).some(row=>!row.digest);+ if(input.dryRun) await inspectTopologyPhysicalRoot(engine,input.sourceId,root?.worktree,{relocation:input.operation==='rebind'});if(input.dryRun) return {dry_run:true,operation:input.operation,source_id:input.sourceId,source_incarnation:before?.incarnation??null,path:root?.source??before?.local_path??null,manifest_required:manifestRequired};return withTopologyLocks(engine,input.sourceId,async bindings=>{// Hash canonical bytes while holding native exclusion, without a databasediff --git a/src/core/persistence/topology-locks.ts b/src/core/persistence/topology-locks.tsindex 5551b7197e..db1083cd6c 100644--- a/src/core/persistence/topology-locks.ts+++ b/src/core/persistence/topology-locks.ts@@ -70,15 +70,29 @@ export async function withTopologyLocks<T>(engine: BrainEngine, sourceId: string`The worktree holding source ${item.source_id || sourceId} is owned by host ${item.owner_host_id}, not this host (${localHostId()}), or has no coordination path here, so nothing changed. Run the lifecycle command on the owning host; moving ownership is a separate, deliberate writer transfer.`,{fix:ownerStatusFix(sourceId)});await take(item.coordination_path);- if(!item.local_path||!existsSync(item.local_path)) continue;- const identity={worktreeId:item.worktree_id,coordinationPath:item.coordination_path};- if(opts.relocation&&item.source_id===sourceId&&additionalRoot&&item.local_path!==additionalRoot&&realpathSync(item.local_path)===additionalRoot) inspectRelocatedPhysicalRoot(item.local_path,additionalRoot,identity);- else assertPhysicalRoot(item.local_path,identity);+ assertBindingPhysicalRoot(item,sourceId,additionalRoot,opts);}return await run(bindings);} finally { for (const handle of handles.reverse()) await handle.release(); }}+function assertBindingPhysicalRoot(item: TopologyBinding, sourceId: string, additionalRoot: string|undefined, opts: { relocation?: boolean }): void {+ if(!item.local_path||!existsSync(item.local_path)) return;+ const identity={worktreeId:item.worktree_id,coordinationPath:item.coordination_path};+ if(opts.relocation&&item.source_id===sourceId&&additionalRoot&&item.local_path!==additionalRoot&&realpathSync(item.local_path)===additionalRoot) inspectRelocatedPhysicalRoot(item.local_path,additionalRoot,identity);+ else assertPhysicalRoot(item.local_path,identity);+}++/**+ * #6849: a lifecycle dry run predicts the physical-root refusal the real run hits in withTopologyLocks for the+ * source's own binding on this host. Read-only: it takes no lock and writes no stamp, reservation or row.+ */+export async function inspectTopologyPhysicalRoot(engine: BrainEngine, sourceId: string, additionalRoot?: string, opts: { relocation?: boolean } = {}): Promise<void> {+ const binding = await getWorktreeBinding(engine, sourceId);+ if (!binding || binding.owner_host_id !== localHostId() || !binding.coordination_path) return;+ assertBindingPhysicalRoot(binding, sourceId, additionalRoot, opts);+}+/*** Keep the complete affected membership locked, including absent target keys.* An active `gbrain sources refresh` on an affected worktree refuses withdiff --git a/test/source-lifecycle-dry-run-physical-root-6849.test.ts b/test/source-lifecycle-dry-run-physical-root-6849.test.tsnew file mode 100644index 0000000000..c6a2e12dcf--- /dev/null+++ b/test/source-lifecycle-dry-run-physical-root-6849.test.ts@@ -0,0 +1,69 @@+/**+ * #6849: `sources remove --dry-run` and `sources set-path --dry-run` returned before the physical-root check the real+ * run makes in withTopologyLocks, so a recreated checkout passed the dry run and the real command refused+ * `recovery_required`. The dry run now runs the same check, read-only: no lock, stamp, reservation or row is written.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath } from '../src/core/persistence/physical-root-record.ts';+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++for (const kind of testBackends()) describe(`#6849 lifecycle dry runs check the physical root (${kind})`, () => {+ const directory = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-dry-root-')));+ let engine: BrainEngine, close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 120_000);+ afterAll(async () => {+ await withEnv({ GBRAIN_HOME: directory }, () => disposePersistenceConsumer(engine));+ if (close) await close(); else await engine.disconnect();+ rmSync(directory, { recursive: true, force: true });+ });++ test('a recreated checkout refuses the remove and set-path dry runs like the real run, and the dry runs write nothing', async () => {+ const home = join(directory, randomUUID()), root = join(home, 'root'); mkdirSync(root, { recursive: true });+ const source = `dry-${randomUUID().slice(0, 8)}`;+ await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, root]);+ await claimWorktree(engine, source, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await registerLocalWriter(engine, 'cli');+ const remove = () => runManagedSourceLifecycle(engine, { operation: 'remove', sourceId: source, dryRun: true });+ const setPath = () => runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: source, path: root, dryRun: true });+ expect(await remove()).toMatchObject({ dry_run: true, operation: 'remove', source_id: source });+ expect(await setPath()).toMatchObject({ dry_run: true, operation: 'rebind', source_id: source });++ const marker = join(root, PHYSICAL_ROOT_MARKER);+ const stamp = JSON.parse(readFileSync(marker, 'utf8'));+ writeFileSync(marker, JSON.stringify({ ...stamp, birth: (BigInt(stamp.birth) - 5_000_000_000n).toString() }), { mode: 0o600 });+ const markerBytes = readFileSync(marker, 'utf8');+ const reservationBytes = readFileSync(physicalRootReservationPath(root), 'utf8');+ const rows = async () => engine.executeRaw('SELECT b.*, w.state, w.owner_epoch FROM persistence_source_bindings b JOIN persistence_worktrees w ON w.id=b.worktree_id WHERE b.source_id=$1', [source]);+ const before = await rows();++ for (const run of [remove, setPath]) {+ const error = await run().then(() => null, (e: { code?: string; detail?: string; suggestion?: string }) => e);+ expect(error).toMatchObject({ code: 'recovery_required', detail: 'physical_root_directory_changed' });+ expect(error!.suggestion).toContain('--self-transfer --confirm-relocated-root');+ }+ expect(readFileSync(marker, 'utf8')).toBe(markerBytes);+ expect(readFileSync(physicalRootReservationPath(root), 'utf8')).toBe(reservationBytes);+ expect(await rows()).toEqual(before);+ expect(await getWorktreeBinding(engine, source)).toMatchObject({ local_path: root, state: 'active' });+ await disposePersistenceConsumer(engine);+ });+ }, 120_000);+});