Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): deliberate exits for a recreated or symlinked canonical root (#5914)

garrytan0bcb9e7727cf
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index cf40cdac99..3a5aac5740 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -10,11 +10,11 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast
- `src/core/persistence/authority.ts` — durable write authority. `submissionAuthority` records the caller's grant ceiling on every write request (scopes, operations, slug prefixes, delegated namespace and, for a delegated job, its native `subagentId` when a positive safe integer); `authorizeWrite` re-checks it against the CURRENT principal at publication and replay. For a delegated OAuth client the current namespace is the stored `delegated_slug_prefixes` in `prefixes` mode, or only `wiki/agents/<retained subagentId>/*` for the native `job` form (prefixes NULL); anything else allows nothing, and it always intersects the original accepted prefixes, bound tools, scope and source, so a revoked, narrowed or switched grant or a foreign or invalid job id denies (`test/persistence-page-authority.test.ts`, Postgres: `test/e2e/minions-authority-parity.test.ts`). #5994: a context carrying `replayAuthority` (set only by `gbrain repair failed-writes`) gets that stored authority back from `submissionAuthority` (`replayedAuthority`): same source incarnation or refused, `databaseOnlyReason`/`takeHoldersUsed` dropped for admission to recompute, then `authorizeWrite` and page visibility against the live grant.
- `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`. See [persistence stalls](persistence-stalls.md).
+- `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; `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--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`. See [persistence stalls](persistence-stalls.md).
- `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`.
-- `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. `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/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/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. A failed atom batch's resume refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify.
- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.
@@ -58,4 +58,4 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast
- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot; exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.
-- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keep `digest`, `file_count`, `canonical_stamp` and `self_transfer` but no per-file map (#5790), so their size is independent of the worktree; `compactStoredManifest` drops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. Large-repo tests: `test/persistence-large-manifest.test.ts` (12k files, both engines via `test/e2e/persistence-large-manifest-postgres.test.ts`) and `test/e2e/persistence-large-manifest-50k.test.ts`. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres. #6099: manifests are Git-scoped for Git checkouts; see `worktree-manifest.ts` in [managed sync and persistence stalls](persistence-stalls.md).
+- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; `withTopologyLocks(..., { relocation: true })` (rebind only, #5914 P1.3c) verifies a recorded root that now resolves through a symlink to the rebind target with `inspectRelocatedPhysicalRoot` instead of the realpath check, and the rebind transaction then calls `relocatePhysicalRoot` and moves `local_path`, the host binding and `relative_path` in place of a new worktree; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keep `digest`, `file_count`, `canonical_stamp` and `self_transfer` but no per-file map (#5790), so their size is independent of the worktree; `compactStoredManifest` drops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. Large-repo tests: `test/persistence-large-manifest.test.ts` (12k files, both engines via `test/e2e/persistence-large-manifest-postgres.test.ts`) and `test/e2e/persistence-large-manifest-50k.test.ts`. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres. #6099: manifests are Git-scoped for Git checkouts; see `worktree-manifest.ts` in [managed sync and persistence stalls](persistence-stalls.md).
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index e51dc3f108..ff40e9e9ed 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -35,7 +35,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/journal.ts` — the request journal SQL: admission, claims, renewals, releases and completion. #6278: the claim statements stamp a `preparing` phase of their own token at claim time and return the previous claim's stamp with the row (`previous_claim_phase`), so a stalled receipt names the last recorded step; a group follower carries no stamp until its wave dispatches it (`markDispatched`), so a kill charges exactly the members that were preparing; `renewGroupClaims` stamps each member's own phase; `releaseUnpublishedClaim` charges one `preparation_attempts` only for `preparation_deadline` (`claim_lost`, `consumer_stopping` and `group_member_waiting` never do); `chargePreparationAttempt` charges a claim this owner still holds before it is finished `preparation_stalled`; `floorPreparationAttempts` pins the counter at the limit after a ceiling overrun; completing a request as committed resets the counter (`completeWrite`, `completeGroup`). An older owner ignores the counter and its renewals overwrite the stamp with the old shape (writer status shows each owner's version); every statement keeps `PERSISTENCE_PROTOCOL_PREDICATE`. Tests: `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.
- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths. Writer status's blockers also carry each request's `operation`, `intent_kind` and `preparation_attempts`; a running blocker's `claim` adds the preparation `step`, `step_age_ms`, `waiting_on`, the owner process (kind, pid, gbrain build, from the live claim's stamp), `budget_ms` and, past the budget, `stall: { reason: 'preparation_overdue', step, step_age_ms, waiting_on, budget_ms }` (`claimStall`; `WRITE_HEALTH_REASONS`, the wire enum, is unchanged). `WRITER_NEXT_ACTIONS` has entries for `preparation_deadline` (keep the request id: the owner will claim it again) and `preparation_stalled` (do not resubmit under the same id; retry-held after the fix), and the result carries `preparation_policy` (the budgets, ceiling, attempt limit and switch in effect). Doctor `persistence_write_stall` prints the same fields. Tests: `test/persistence-writer-status-stall.test.ts`.
- `src/core/schema-migrations/v220-persistence-request-preparation-attempts.ts` — #6278: `persistence_requests.preparation_attempts integer NOT NULL DEFAULT 0 CHECK (preparation_attempts >= 0)`, the count of cut-offs of a request's preparation. Existing rows start at 0; a commit resets it. It is a migration-created column (also in the `persistence_requests` CREATE TABLE of `src/schema.sql`, with no index) so a fresh install and an upgraded brain keep the same column order. Tests: `test/persistence-preparation-attempts-migration.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.
-- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks, then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.
+- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks with `identity: 'reservation'` (#5914: it publishes nothing, so a recreated directory whose reservation names the worktree and whose stamp carries the same token releases; a token mismatch refuses), then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.
- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.
- `src/core/persistence/sync-page-fault.ts` — #6340: a page that moved under a managed catch-up holds the page, not the run. `headCommittedBytes` returns the working-tree bytes of a path when their blob id equals `HEAD:<path>` (sha1 or sha256 by HEAD's id length), so `freezeEntry` imports bytes committed past the pinned target as HEAD has them (the later pin..HEAD diff re-imports them as a no-op; idea and first test from PR #6323, which this supersedes) and `prepareManagedSyncMutation`'s `newerWorkingTree` screen never sees them. `pageChangeProof` is #6194's revision-linked proof usable at freeze time; `pageChangedHold` builds the `concurrent_write` hold for a database page that was edited, deleted or re-bound after enumeration (with the competing request when proven, else `page_revision` + `expected_revision`), `worktreeDirtyHold` the new `worktree_dirty` hold (pinned `blob_oid`, `working_hash`) for uncommitted bytes that match neither the pin nor the page, `pinnedWorktreeConflict` recognizes that receipt and `pageMovedSinceAdmission` a `revision_conflict` receipt whose page really moved (a run-level conflict with the page where it was still blocks). In `sync-run.ts`: `freezeEntry` resolves the three freeze-time throws (`page_identity_changed`, `revision_conflict`, the renamed-source conflict) into holds when holds are on (a page that still holds exactly what the import carries is re-bound to its new revision and passed by the waiver screen; `sync.holds=fail` and company-brain cursors keep the refusals), `holdFailedFenceRequest` converts the two receipts (imports and deletes) through `receiptPageFaultHold`, re-freezes an entry once under a fresh request when its file changed between admission and publication (`fileChangedAfterAdmission`, the `raw_file_changed` receipt: committed bytes then import as HEAD has them, a second change under the re-frozen request is held `worktree_dirty`; `holdUnderGate` takes `refrozen` in place of `hold` and records the conversion as `refrozen`), `convertBlockedCursor` converts a cursor an older release left blocked (re-freezing a dirty file that is committed now), `originFaultHold` holds an entry whose recorded origin no longer identifies the enumerated page (`assertSyncPageOrigin` at freeze), every page-fault hold marks the cursor `overtaken` (#5522: another cursor may have checkpointed this target), and the `--retry-failed` start tries that conversion before rediscovering, so the frozen manifest survives. `writeGitHold` counts `meta.attempts` per re-hold with the same code; `HOLD_ATTEMPTS_NEEDS_HUMAN` (3) turns a page hold into `needs_human`. The run's catch skips the failure ledger for `isRetryableConnError` / statement timeouts. Tests: `test/managed-sync-page-fault-holds.test.ts` (freeze-time DB edit → hold, same content → re-bind, dirty → `worktree_dirty` → commit → import, committed past pin → HEAD bytes, old blocked cursor → in-place conversion with attempts, connection death → no ledger row, same run on relaunch, one extra pass), the updated expectations in `test/persistence-managed-sync.test.ts` and `test/managed-sync-concurrent-write-hold.test.ts`.
- `src/core/persistence/sync-write-diagnostic.ts` — `managedSyncWriteDiagnostic`, the `managedWrite` block of a managed sync result (terminal receipt reason, suggestion with the retry command, the CRLF-only note), moved unchanged out of `sync-run.ts` by #6340.
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index e813dedb8d..bb8302276c 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -499,6 +499,40 @@ gbrain sources writer transfer accept default --brain host --self-transfer \
# After separate approval, rerun accept without --dry-run.
```
+<a id="recreated-root"></a>**Recreated or moved canonical root (#5914).** A
+directory deleted and recreated at its recorded path (a restore from backup, a
+container rebuilt without its volume, a Migration Assistant copy) keeps its
+path but not its inode and birth time, so every verb refused
+`recovery_required`, self-transfer included. Two deliberate exits exist, and
+neither relaxes anything else:
+
+- *Same path, new directory:* add `--confirm-relocated-root` to both
+ self-transfer phases. It waives only the inode and birth-time comparison, and
+ only when the token, brain id, worktree id, root and coordination path of the
+ stamp and the **outside-root reservation** all agree; a copied in-root stamp
+ without the reservation beside the root is never authority. Prepare records
+ `relocated: true` on the durable manifest, accept must repeat the flag (in
+ either direction it refuses `writer_transfer_conflict`), and the reservation
+ is rewritten through a compare-and-swap: a reservation someone else changed
+ between prepare and accept refuses with detail `stale_record`, so prepare
+ again from a fresh status. The flag without `--self-transfer` is a usage
+ error.
+- *Recorded path now a symlink to the moved checkout:* run
+ `gbrain sources set-path <source> <recorded-or-real-path>` on the owner host.
+ When the recorded path resolves to the target and the reservation under the
+ recorded name and the stamp inside the real directory agree on token, brain
+ id and worktree id, the worktree keeps its id: `local_path` and the host
+ binding move to the real directory, the reservation is written under the new
+ `sha256(root)` name, the old one is removed and the stamp names the new root.
+ A token or worktree mismatch keeps the refusal and moves nothing.
+
+`gbrain sources writer deactivate --dry-run` lists a `physical_root` blocker
+exactly when its real run would refuse: the managed run takes the strict
+worktree lock, so a recreated root blocks it until one of the exits above ran;
+the classic (pre-activation) release publishes nothing and needs only the
+native lock plus a reservation naming the worktree whose stamp carries the same
+token, so a recreated root does not block it but a token mismatch does.
+
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
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index a59a1fc1a7..089392bfeb 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -40,6 +40,7 @@ of making a duplicate.
| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. Never force-write, edit SQL or disable the guard. |
| `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 --retry-failed`. |
| `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. |
+| <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="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` | An unfinished sync's processing options (`--no-embed`, `--no-extract`, `--no-schema-pack`) conflict with this run, or the cursor predates saved options and has none. When options are saved, a run that omits those flags, including autopilot and `sync` jobs, adopts them. | When the message prints a resume command (`gbrain sync --source <source> --no-pull` plus the saved flags), run it or drop the conflicting flag. When it reports no saved options, resolve pending requests first, then rediscover with `gbrain sync --source <source> --no-pull --retry-failed` and the processing flags you want. |
diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.ts
index 8d799988c2..2feee63f01 100644
--- a/src/commands/persistence-admin.ts
+++ b/src/commands/persistence-admin.ts
@@ -21,8 +21,8 @@ export const WRITER_HELP = `Usage:
gbrain sources writer claim <source> --path <directory> [administration options] [--dry-run] [--json]
gbrain sources writer activate --confirm-quiesced [--cleanup-dead-local-locks] [--shared-skills] [administration options] [--dry-run] [--json]
gbrain sources writer deactivate [--admin-intent writer_deactivate --expected-state <admin_state>] [--dry-run] [--json]
- gbrain sources writer transfer prepare <source> [--self-transfer] [administration options] [--dry-run] [--json]
- gbrain sources writer transfer accept <source> --path <worktree-root> --expected-epoch <n> --manifest <sha256> [--self-transfer] [administration options] [--dry-run] [--json]
+ gbrain sources writer transfer prepare <source> [--self-transfer [--confirm-relocated-root]] [administration options] [--dry-run] [--json]
+ gbrain sources writer transfer accept <source> --path <worktree-root> --expected-epoch <n> --manifest <sha256> [--self-transfer [--confirm-relocated-root]] [administration options] [--dry-run] [--json]
gbrain sources writer lock [--json]
gbrain sources writer unlock [--json]
@@ -110,7 +110,7 @@ export function adminHostConfig<T extends GBrainConfig>(config: T | null | undef
type Group = 'writer' | 'local-writer';
const GROUP_ARGV: Record<Group, string[]> = { writer: ['gbrain', 'sources', 'writer'], 'local-writer': ['gbrain', 'auth', 'local-writer'] };
-const BARE_FLAGS = ['--json', '--dry-run', '--replace', '--probe', '--confirm-quiesced', '--self-transfer', '--cleanup-dead-local-locks', '--shared-skills'];
+const BARE_FLAGS = ['--json', '--dry-run', '--replace', '--probe', '--confirm-quiesced', '--self-transfer', '--confirm-relocated-root', '--cleanup-dead-local-locks', '--shared-skills'];
/** A CLI usage refusal: the exact usage in the suggestion, the group's help as the read-only fix. */
function invalid(group: Group, message: string, suggestion: string) {
return opError('invalid_params', message, suggestion, {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 0a72c1934b..c2b748539f 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -373,6 +373,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.147.0', text: 'In a brain folder with the Git durability hook, a write that arrives while the effect worker commits a backlog of Git effects now publishes after the group in flight, inside its 5 s wait, instead of returning pending after the whole backlog; Git effects still commit in order. A write waiting on a busy worktree is reported as `writer_busy` without a stale preparing phase.' },
// `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.151.0', text: '`delta` and `context_pack` called without `include_private`, and the per-turn context block that harness hooks inject, now apply to their facts the same page-visibility rule they already apply to their pages. With `include_private` from the local CLI, `delta` and `context_pack` output is unchanged.' },
+ // W14 PR1 P1.3 (#5914). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.156.0', text: 'A managed checkout deleted and recreated at its recorded path (restore from backup, rebuilt container, Migration Assistant copy) has two deliberate exits instead of `recovery_required` from every verb: `gbrain sources writer transfer prepare/accept <source> --self-transfer --confirm-relocated-root` waives only the directory identity comparison when the stamp and the reservation beside the root agree on everything else, and `gbrain sources set-path <source> <path>` converges a checkout moved behind a symlink at its recorded path, keeping the worktree. `gbrain sources writer deactivate --dry-run` now lists a `physical_root` blocker exactly when its real run would refuse, and the classic (pre-activation) release no longer refuses on a recreated directory whose reservation and stamp still agree.' },
// W14 PR1 P1.2 (#6432). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.156.0', text: 'Schema-pack YAML now decodes quoted scalars: a double-quoted value carries the JSON escape subset and a single-quoted value is literal text with `\'\'` for one quote, so a link-type regex written as `"\\\\b"` loads as `\\b` and a `gbrain schema` mutation writes it back unchanged (before, every mutation doubled the backslashes of every quoted scalar). A hand-written double-quoted value that meant two backslashes now means one. A mutation whose emitted YAML does not read back as the manifest refuses with `schema_pack_emit_mismatch` and leaves the file unchanged; a pack file above 8 MiB refuses to load with `schema_pack_too_large` instead of being read, and `gbrain doctor` warns on a mutable pack above 1 MiB with the hand-repair runbook.' },
];
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 094c7830eb..5776ccaba4 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -18,7 +18,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],
'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],
'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--prefer-postgres', '--probe', '--require-db', '--skip-verify', '--source', '--uninstall', '--url', '--yes'],
- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],
+ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],
'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--probe', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -58,8 +58,8 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'errors': ['--brain', '--changed', '--help', '--json', '--source'],
'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
- 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
- 'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
+ 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
+ 'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--slug', '--source'],
'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
'feedback': ['--brain', '--help', '--json', '--page', '--source'],
@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--allow-create-db', '--allow-docker', '--apply', '--auto', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--show-toplevel', '--skip-embed-check', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--allow-create-db', '--allow-docker', '--apply', '--auto', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
@@ -90,16 +90,16 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--older-than', '--source', '--yes'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],
- 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],
+ 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],
'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
- 'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--brain', '--break-lock', '--client', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
+ 'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'recall': ['--accept-pending', '--access', '--add', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--progress-interval', '--progress-json', '--purge', '--query', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--apply', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--include-ambiguous', '--json', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--path', '--plan', '--progress-interval', '--progress-json', '--quiet', '--repo', '--self-transfer', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
+ 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--apply', '--background', '--brain', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--include-ambiguous', '--json', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--path', '--plan', '--progress-interval', '--progress-json', '--quiet', '--repo', '--self-transfer', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],
'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],
@@ -108,7 +108,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--no-llm', '--only', '--probe', '--remediate', '--remediation-plan', '--scopes', '--skip', '--slug', '--slugs', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait', '--wait-drain', '--warn-only', '--yes'],
+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait', '--wait-drain', '--warn-only', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
@@ -122,7 +122,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait', '--wait-drain', '--warn-only', '--yes'],
+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait', '--wait-drain', '--warn-only', '--yes'],
'status': ['--abbrev-ref', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
@@ -131,7 +131,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
'trust': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--since', '--source', '--source-id', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
- 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],
+ 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
'whoknows': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index a025140530..ce5ca398f8 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -49,6 +49,13 @@ function bool(params: Record<string, unknown>, key: string): void {
if (params[key] !== undefined && typeof params[key] !== 'boolean') throw invalid(`${key} must be a boolean.`,
`Send ${key} as a JSON boolean (true or false); on the CLI it is the bare flag ${cliFlag(key)}, which takes no value.`);
}
+/** #5914: `--confirm-relocated-root` only qualifies a self-transfer; alone it is a usage error, never a silent no-op. */
+function transferOptions(params: Record<string, unknown>): { selfTransfer: boolean; relocated: boolean } {
+ bool(params, 'confirm_relocated_root');
+ if (params.confirm_relocated_root === true && params.self_transfer !== true) throw invalid('confirm_relocated_root requires self_transfer.',
+ 'Pass --confirm-relocated-root together with --self-transfer: it waives only the directory identity comparison of a self-transfer that repairs a checkout recreated at its recorded path.');
+ return { selfTransfer: params.self_transfer === true, relocated: params.confirm_relocated_root === true };
+}
function keys(params: Record<string, unknown>, allowed: string[]) {
const unknown = Object.keys(params).filter(key => !allowed.includes(key));
if (unknown.length) throw invalid(`Unsupported administration parameters: ${unknown.join(', ')}.`,
@@ -289,9 +296,10 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
: uuid(params.request_id, 'A valid deactivation request UUID is required.', 'Pass --request-id as a UUID, or omit it and gbrain generates one.') }) };
}
if (operation === 'writer_transfer_prepare') {
- keys(params, ['source_id', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer']);
+ keys(params, ['source_id', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer', 'confirm_relocated_root']);
const sourceId = source(params.source_id);
bool(params, 'self_transfer');
+ const transfer = transferOptions(params);
if (params.dry_run) {
const binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
if (!binding || binding.owner_host_id !== existingLocalHostId() || !binding.local_path) {
@@ -299,11 +307,11 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
`This host is not source ${sourceId}'s current owner. Run the transfer prepare on the owner host that writer status names; a transfer is a deliberate topology change the operator reviews.`,
{ fix: readFix(`Shows which host owns source ${sourceId}, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });
}
- const { manifest } = await prepareWriterTransfer(engine, sourceId, existingLocalHostId()!, undefined, { selfTransfer: params.self_transfer === true, dryRun: true });
- return { dry_run: true, action: operation, binding, manifest: { digest: manifest.digest, file_count: manifest.file_count } };
+ const { manifest } = await prepareWriterTransfer(engine, sourceId, existingLocalHostId()!, undefined, { ...transfer, dryRun: true });
+ return { dry_run: true, action: operation, binding, manifest: { digest: manifest.digest, file_count: manifest.file_count }, ...(transfer.relocated ? { relocated: true } : {}) };
}
const expectedState = await requireWriterAdminIntent(engine, operation, params);
- const prepared = await prepareWriterTransfer(engine, sourceId, undefined, expectedState, { selfTransfer: params.self_transfer === true });
+ const prepared = await prepareWriterTransfer(engine, sourceId, undefined, expectedState, transfer);
// #6099: a Git-scoped manifest covers tracked files only; untracked files Git does not ignore are reported as a count.
const untracked = prepared.manifest.untracked_count ?? 0;
return { prepared: true, source_id: sourceId, worktree_id: prepared.worktree_id, owner_epoch: prepared.owner_epoch,
@@ -311,15 +319,16 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
...(untracked ? { untracked_files: untracked, warning: `${untracked} untracked file(s) in the checkout that Git does not ignore are not part of the transfer manifest and are not carried to the successor; commit them, or add them to .gitignore, before the successor clones.` } : {}) };
}
if (operation === 'writer_transfer_accept') {
- keys(params, ['source_id', 'path', 'expected_epoch', 'manifest', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer']);
+ keys(params, ['source_id', 'path', 'expected_epoch', 'manifest', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer', 'confirm_relocated_root']);
bool(params, 'self_transfer');
+ const transfer = transferOptions(params);
const sourceId = source(params.source_id), root = path(params.path);
if (typeof params.expected_epoch !== 'string' || !/^[1-9]\d{0,18}$/.test(params.expected_epoch)
|| BigInt(params.expected_epoch) > 9_223_372_036_854_775_807n) throw invalid('expected_epoch must be the prepared positive owner epoch.',
`Pass --expected-epoch with the owner_epoch that gbrain sources writer transfer prepare ${sourceId} printed (a positive integer).`, transferStatusFix(sourceId));
if (typeof params.manifest !== 'string' || !/^[a-f0-9]{64}$/.test(params.manifest)) throw invalid('manifest must be the prepared SHA-256 manifest digest.',
`Pass --manifest with the 64-character manifest digest that gbrain sources writer transfer prepare ${sourceId} printed.`, transferStatusFix(sourceId));
- if (params.dry_run && params.self_transfer === true) await acceptWriterTransfer(engine, sourceId, root, params.expected_epoch, params.manifest, existingLocalHostId()!, undefined, { selfTransfer: true, dryRun: true });
+ if (params.dry_run && params.self_transfer === true) await acceptWriterTransfer(engine, sourceId, root, params.expected_epoch, params.manifest, existingLocalHostId()!, undefined, { ...transfer, dryRun: true });
if (params.dry_run) {
const current = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
const [prepared] = current ? await engine.executeRaw<{ manifest: StoredWorktreeManifest | null }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [current.worktree_id]) : [];
@@ -328,7 +337,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
...(candidate.scope ? { manifest_scope: candidate.scope } : {}), ...(candidate.untracked_count ? { untracked_files: candidate.untracked_count } : {}) };
}
const expectedState = await requireWriterAdminIntent(engine, operation, params);
- await acceptWriterTransfer(engine, sourceId, root, params.expected_epoch, params.manifest, undefined, expectedState, { selfTransfer: params.self_transfer === true });
+ await acceptWriterTransfer(engine, sourceId, root, params.expected_epoch, params.manifest, undefined, expectedState, transfer);
return { transferred: true, binding: await getWorktreeBinding(engine, sourceId) };
}
if (operation === 'local_writer_list') {
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index 397e0e8bb5..5aeabb242b 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -39,13 +39,13 @@ import { recordTopologyChange } from './topology-receipts.ts';
import { lockTopologyPrincipal, topologyPrincipal } from './topology-locks.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { carryHoldsToClassicState, holdCarryBlocked, planHoldCarry, type HoldCarry } from '../connectors/item-holds-store.ts';
-import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath } from './physical-root-record.ts';
+import { assertPhysicalRoot, assertPhysicalRootReservation, PHYSICAL_ROOT_MARKER, physicalRootReservationPath } from './physical-root-record.ts';
import { preActivationClaims, releasePreActivationClaims, type PreActivationClaim } from './pre-activation-release.ts';
export const DEACTIVATE_DOCS = 'docs/architecture/topologies.md#deactivate-runbook';
export interface DeactivationBlocker {
- kind: 'writer_admin_lock' | 'request' | 'topology_recovery' | 'effect' | 'lease' | 'connector_holds';
+ kind: 'writer_admin_lock' | 'request' | 'topology_recovery' | 'effect' | 'lease' | 'connector_holds' | 'physical_root';
id: string;
source_id?: string;
detail: string;
@@ -145,6 +145,39 @@ export async function deactivationBlockers(engine: BrainEngine): Promise<Deactiv
return blockers;
}
+/**
+ * #5914 [R9a]: the `physical_root` blockers of this host's owned checkouts, probed
+ * exactly as the real operation of each mode will: the managed run takes the
+ * strict worktree lock (inode and birth time compared), the classic release
+ * publishes nothing and checks only the reservation's worktree id and token.
+ * Each preview therefore lists what its own real run would refuse on.
+ */
+export async function physicalRootBlockers(engine: BrainEngine, mode: 'managed' | 'classic'): Promise<DeactivationBlocker[]> {
+ const hostId = existingLocalHostId();
+ const sources = mode === 'managed'
+ ? await engine.executeRaw<{ id: string }>('SELECT source_id AS id FROM persistence_source_bindings ORDER BY source_id')
+ : (await preActivationClaims(engine)).map(claim => ({ id: claim.source_id }));
+ const blockers: DeactivationBlocker[] = [];
+ const seen = new Set<string>();
+ for (const { id } of sources) {
+ const binding = await getWorktreeBinding(engine, id, hostId);
+ if (!binding || binding.owner_host_id !== hostId || !binding.local_path || !binding.coordination_path || seen.has(binding.worktree_id)) continue;
+ seen.add(binding.worktree_id);
+ const identity = { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path };
+ try { if (mode === 'managed') assertPhysicalRoot(binding.local_path, identity); else assertPhysicalRootReservation(binding.local_path, identity); }
+ catch (error) {
+ const detail = error instanceof OperationError ? error.message : String(error);
+ blockers.push({ kind: 'physical_root', id: binding.worktree_id, source_id: id, detail: `${binding.local_path}: ${detail}`,
+ exit: mode === 'managed'
+ ? `gbrain sources writer status ${id} --json, then (same path, directory recreated) gbrain sources writer transfer prepare ${id} --self-transfer --confirm-relocated-root --admin-intent writer_transfer_prepare --expected-state <admin_state> `
+ + `and gbrain sources writer transfer accept ${id} --path ${binding.local_path} --expected-epoch <owner_epoch> --manifest <digest> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_accept --expected-state <admin_state>; `
+ + 'a checkout moved behind a symlink converges with gbrain sources set-path instead'
+ : `gbrain sources writer status ${id} --json; the reservation beside ${binding.local_path} must name this worktree and its stamp must carry the same token (docs/architecture/topologies.md#recreated-root)` });
+ }
+ }
+ return blockers;
+}
+
function blockedError(blockers: DeactivationBlocker[]): OperationError {
const locked = blockers.find(b => b.kind === 'writer_admin_lock');
if (locked) return new OperationError('writer_admin_locked', 'Writer administration is locked; deactivation was not applied.',
@@ -183,7 +216,7 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
const claims = await preActivationClaims(engine);
const classic = { ...base, mode: 'classic' as const, deactivated: false, mode_epoch: Number(brain.mode_epoch) };
if (!claims.length) return { ...classic, retired_worktrees: [], blockers: [], ...(opts.dryRun ? {} : { local_markers: await cleanupRetiredManagedMarkers(engine) }) };
- const blockers = await deactivationBlockers(engine);
+ const blockers = [...await deactivationBlockers(engine), ...await physicalRootBlockers(engine, 'classic')];
if (opts.dryRun) return { ...classic, retired_worktrees: [], blockers, pre_activation_claims: claims };
if (blockers.length) throw blockedError(blockers);
const released = await releasePreActivationClaims(engine, { expectedState: opts.expectedState, requestId: opts.requestId,
@@ -192,7 +225,7 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
return { ...classic, retired_worktrees: worktrees.map(id => ({ id, roots: [...new Set(released.filter(c => c.worktree_id === id).flatMap(c => c.roots))] })),
blockers: [], pre_activation_claims: released, local_markers: await cleanupRetiredManagedMarkers(engine) };
}
- const blockers = await deactivationBlockers(engine);
+ const blockers = [...await deactivationBlockers(engine), ...await physicalRootBlockers(engine, 'managed')];
if (opts.dryRun) {
const carried_holds = (await planHoldCarry(engine, existingLocalHostId())).filter(c => c.items > 0 && !holdCarryBlocked(c));
return { ...base, mode: 'managed', deactivated: false, mode_epoch: Number(brain.mode_epoch), blockers, carried_holds };
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index ef90fbf429..a30edd7dae 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -16,7 +16,7 @@ import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from '
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 { readPhysicalRootStamp } from './physical-root-record.ts';
+import { assertPhysicalRootReservation, readPhysicalRootStamp } from './physical-root-record.ts';
import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.ts';
import { assertWriterAdminState } from './admin-intent.ts';
import { assertWriterAdminUnlocked } from './admin-lock.ts';
@@ -137,11 +137,11 @@ export async function claimWorktree(engine: BrainEngine, sourceId: string, path:
* reports busy while lanes hold the lease, and the lease drains for it after `DEFER_WAIT_MS`.
*/
export async function acquireWorktree(binding: WorktreeBinding, waitMs = 0, signal?: AbortSignal, engine?: BrainEngine,
- opts: { yieldLanes?: boolean } = {}): Promise<NativeLockHandle | null> {
+ opts: { yieldLanes?: boolean; identity?: 'strict' | 'reservation' } = {}): Promise<NativeLockHandle | null> {
if (!binding.local_path || !binding.coordination_path) return null;
// #5984 lanes: an exclusive writer drains this process's lane lease first; while lanes still hold it the worktree is busy.
if (waitMs <= 0 && !opts.yieldLanes ? !deferToLease(binding.coordination_path) : !await yieldLease(binding.coordination_path, waitMs, signal)) return null;
- const lock = await lockWorktree(binding, waitMs, signal, engine);
+ const lock = await lockWorktree(binding, waitMs, signal, engine, opts.identity);
if (lock) exclusiveAcquired(binding.coordination_path);
return lock;
}
@@ -154,12 +154,22 @@ export async function acquireWorktreeShared(binding: WorktreeBinding, engine: Br
export function joinWorktreeLease(binding: WorktreeBinding): NativeLockHandle | null {
return binding.local_path && binding.coordination_path ? joinLease(binding.coordination_path) : null;
}
-async function lockWorktree(binding: WorktreeBinding, waitMs: number, signal: AbortSignal | undefined, engine: BrainEngine | undefined): Promise<NativeLockHandle | null> {
+/**
+ * `identity: 'reservation'` (#5914) is for a caller that publishes nothing (the
+ * pre-activation release): the native lock plus the reservation's worktree id
+ * and token, without the inode/birth comparison a recreated directory fails.
+ */
+async function lockWorktree(binding: WorktreeBinding, waitMs: number, signal: AbortSignal | undefined, engine: BrainEngine | undefined,
+ identityCheck: 'strict' | 'reservation' = 'strict'): Promise<NativeLockHandle | null> {
if (!binding.coordination_path || !binding.local_path) return null;
const lock = await (waitMs > 0 ? acquireNativeLock(binding.coordination_path, { timeoutMs: waitMs, signal })
: tryAcquireNativeLock(binding.coordination_path));
if (!lock) return null;
const identity = { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path };
+ if (identityCheck === 'reservation') {
+ try { assertPhysicalRootReservation(binding.local_path, identity); return lock; }
+ catch (error) { await lock.release(); throw error; }
+ }
try { assertPhysicalRoot(binding.local_path, identity); return lock; }
catch (error) {
try {
@@ -245,8 +255,14 @@ export function humanManifestProgress(): ProgressOptions | undefined {
return options.mode === 'auto' ? options : undefined;
}
+export interface WriterTransferOptions {
+ selfTransfer?: boolean;
+ dryRun?: boolean;
+ /** #5914: `--confirm-relocated-root`, a self-transfer of a directory recreated at the same path (inode/birth waived; everything else must agree). */
+ relocated?: boolean;
+}
export async function prepareWriterTransfer(engine: BrainEngine, sourceId: string, hostId = localHostId(), expectedAdminState?: string,
- opts: { selfTransfer?: boolean; dryRun?: boolean } = {}): Promise<{ worktree_id: string; owner_epoch: string; manifest: StoredWorktreeManifest }> {
+ opts: WriterTransferOptions = {}): Promise<{ worktree_id: string; owner_epoch: string; manifest: StoredWorktreeManifest }> {
const binding = await getWorktreeBinding(engine, sourceId, hostId);
if (!binding || binding.owner_host_id !== hostId || !binding.local_path) throw opError('permission_denied', 'Only the current owner can prepare this transfer.',
`This host does not own source ${sourceId}'s checkout, so nothing was prepared. Check which host owns it; transfer preparation runs in a terminal on that host.`,
@@ -282,7 +298,7 @@ export async function prepareWriterTransfer(engine: BrainEngine, sourceId: strin
{ fix: writerStatusFix(sourceId) });
const [brain] = await tx.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
const recovery = opts.selfTransfer ? inspectPhysicalRootRecovery(binding.local_path!, { brainId: brain.brain_id,
- worktreeId: binding.worktree_id, hostId, coordinationPath: binding.coordination_path! }) : undefined;
+ worktreeId: binding.worktree_id, hostId, coordinationPath: binding.coordination_path! }, { relocated: opts.relocated === true }) : undefined;
if (!opts.selfTransfer) assertPhysicalRoot(binding.local_path!, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path });
if (hashed instanceof Error) throw hashed;
const manifest: StoredWorktreeManifest = { ...hashed, ...(recovery ? { self_transfer: recovery } : {}) };
@@ -292,7 +308,7 @@ export async function prepareWriterTransfer(engine: BrainEngine, sourceId: strin
} finally { await lock.release(); }
}
export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string, path: string, expectedEpoch: string, expectedManifest: string, hostId = localHostId(), expectedAdminState?: string,
- opts: { selfTransfer?: boolean; dryRun?: boolean } = {}): Promise<void> {
+ opts: WriterTransferOptions = {}): Promise<void> {
const root = realpathSync(resolve(path));
const binding = await getWorktreeBinding(engine, sourceId, hostId);
if (!binding) throw opError('not_found', 'Source has no worktree owner.',
@@ -328,6 +344,10 @@ export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string
if (!!owner.manifest.self_transfer !== !!opts.selfTransfer || JSON.stringify(await getWorktreeBinding(tx, sourceId, hostId)) !== JSON.stringify(binding)) throw opError('writer_transfer_conflict', 'The prepared transfer mode or binding changed.',
`Source ${sourceId} was prepared ${owner.manifest.self_transfer ? 'as' : 'without'} a self-transfer, or its binding changed since then, so nothing was accepted. Accept with the same --self-transfer choice used at prepare, after re-reading writer status.`,
{ fix: writerStatusFix(sourceId) });
+ // #5914: the relocation waiver is persisted on the prepared record and must be repeated at accept, in both directions.
+ if (opts.selfTransfer && (owner.manifest.self_transfer?.relocated === true) !== (opts.relocated === true)) throw opError('writer_transfer_conflict', 'The prepared self-transfer differs on --confirm-relocated-root.',
+ `Source ${sourceId} was prepared ${owner.manifest.self_transfer?.relocated ? 'with' : 'without'} --confirm-relocated-root, so nothing was accepted. Accept with the same flag, or have the owner prepare again.`,
+ { fix: writerStatusFix(sourceId) });
const pending = await tx.executeRaw(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND (state IN ('running','recovering') OR recovery IS NOT NULL) LIMIT 1`, [binding.worktree_id]);
const mirrors = await tx.executeRaw('SELECT id FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1', [binding.worktree_id]);
if (pending.length || mirrors.length) throw opError('recovery_required', 'Transfer state changed; prepare again.',
diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.ts
index 3a51135ea0..975a2722f9 100644
--- a/src/core/persistence/physical-root-record.ts
+++ b/src/core/persistence/physical-root-record.ts
@@ -79,7 +79,13 @@ function createPrivate(path: string, value: unknown): boolean {
return true;
}
export function readPhysicalRootReservation(path: string): PhysicalRootReservation | null {
- const root = canonicalFilesystemPath(path);
+ return readReservationRecord(canonicalFilesystemPath(path));
+}
+/** #5914: the reservation written for `recorded` as it was recorded, even when that path now resolves elsewhere through a symlink. */
+export function readRecordedPhysicalRootReservation(recorded: string): PhysicalRootReservation | null {
+ return readReservationRecord(recorded);
+}
+function readReservationRecord(root: string): 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)
@@ -180,6 +186,25 @@ function replacePrivate(path: string, value: unknown): void {
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; } }
}
+/**
+ * #5914: compare-and-swap of the outside-root reservation for a deliberate
+ * relocation (recreated directory, moved checkout). The caller holds the
+ * outside-root native lock and verified database ownership. A reservation
+ * already equal to `next` is a no-op; one that matches neither `expected` nor
+ * `next` was changed by someone else and refuses with detail `stale_record`.
+ */
+export function replacePhysicalRootReservation(root: string, expected: PhysicalRootReservation, next: PhysicalRootReservation): void {
+ if (next.root !== root || expected.root !== root || next.token !== expected.token || next.worktreeId !== expected.worktreeId || next.brainId !== expected.brainId) throw physicalRootError();
+ const current = readPhysicalRootReservation(root);
+ if (current && digest(current) === digest(next)) return;
+ if (!current || digest(current) !== digest(expected)) {
+ const error = physicalRootError('The ownership reservation changed since this relocation was prepared; prepare it again from a fresh writer status.');
+ error.detail = 'stale_record';
+ throw error;
+ }
+ replacePrivate(physicalRootReservationPath(root), next);
+ if (digest(readPhysicalRootReservation(root)) !== digest(next)) throw physicalRootError('The re-stamped ownership reservation contains unexpected bytes.');
+}
/** Caller holds the outside-root native lock and verified database ownership; only the device fields change. */
export function restampPhysicalRootDevice(root: string, reservation: PhysicalRootReservation, stamp: PhysicalRootStamp, change: { from: string; to: string }): void {
if (reservation.initialDevice === change.from) replacePrivate(physicalRootReservationPath(root), { ...reservation, initialDevice: change.to });
@@ -207,6 +232,58 @@ export function adoptTransferredRootStamp(directory: string, reservation: Physic
assertPhysicalRootStamp(directory, reservation);
excludeOwnershipMarkers([directory, reservation.root, dirname(reservation.root)]);
}
+/**
+ * #5914: the identity check a release that publishes nothing needs. The
+ * outside-root reservation must name this worktree (and coordination path),
+ * and a stamp, when one is readable, must carry the reservation's token; the
+ * inode and birth time of a recreated directory are not compared. Callers
+ * hold the native lock.
+ */
+export function assertPhysicalRootReservation(path: string, identity: { worktreeId: string; coordinationPath?: string | null }): void {
+ try {
+ const reservation = readPhysicalRootReservation(path);
+ if (!reservation || reservation.worktreeId !== identity.worktreeId || identity.coordinationPath && reservation.coordinationPath !== identity.coordinationPath) throw physicalRootError();
+ const stamp = existsSync(path) ? readPhysicalRootStamp(path) : null;
+ if (stamp && (stamp.token !== reservation.token || stamp.worktreeId !== reservation.worktreeId || stamp.brainId !== reservation.brainId)) throw physicalRootError();
+ } catch (error) { if (error instanceof OperationError) throw error; throw physicalRootError(); }
+}
+/**
+ * #5914 (P1.3c): the recorded root now resolves through a symlink to `target`.
+ * Verifies the moved checkout is this same worktree (reservation under the old
+ * name and stamp inside the real directory agree on token, brainId and
+ * worktreeId; the stamp names the old root) and returns both records.
+ */
+export function inspectRelocatedPhysicalRoot(recorded: string, target: string, identity: { worktreeId: string; coordinationPath?: string | null }):
+ { reservation: PhysicalRootReservation; stamp: PhysicalRootStamp } {
+ try {
+ if (recorded === target || realpathSync(recorded) !== target || realpathSync(target) !== target) throw physicalRootError();
+ const reservation = readRecordedPhysicalRootReservation(recorded), stamp = readPhysicalRootStamp(target);
+ if (!reservation || !stamp || reservation.worktreeId !== identity.worktreeId || identity.coordinationPath && reservation.coordinationPath !== identity.coordinationPath
+ || stamp.token !== reservation.token || stamp.worktreeId !== reservation.worktreeId || stamp.brainId !== reservation.brainId || stamp.root !== recorded) throw physicalRootError();
+ return { reservation, stamp };
+ } catch (error) { if (error instanceof OperationError) throw error; throw physicalRootError(); }
+}
+/**
+ * #5914 (P1.3c): moves the ownership records of a verified relocation to the
+ * real directory: the reservation is written under the new `sha256(root)`
+ * name, the stamp is rewritten to name the new root from the live directory,
+ * then the old reservation is removed. Caller holds the native lock and the
+ * topology transaction; `inspectRelocatedPhysicalRoot` ran first.
+ */
+export function relocatePhysicalRoot(recorded: string, target: string, records: { reservation: PhysicalRootReservation; stamp: PhysicalRootStamp }): PhysicalRootReservation {
+ const info = statSync(target, { bigint: true });
+ const reservation: PhysicalRootReservation = { ...records.reservation, root: target,
+ initialDevice: info.dev.toString(), initialInode: info.ino.toString(), initialBirth: info.birthtimeNs.toString() };
+ const existing = readPhysicalRootReservation(target);
+ if (existing && digest(existing) !== digest(reservation)) throw physicalRootError('Another reservation already names the relocated directory.');
+ if (!existing && !createPrivate(physicalRootReservationPath(target), reservation)) throw physicalRootError();
+ replacePrivate(join(target, PHYSICAL_ROOT_MARKER), { ...records.stamp, root: target, device: info.dev.toString(), inode: info.ino.toString(), birth: info.birthtimeNs.toString() });
+ assertPhysicalRootStamp(target, reservation);
+ try { unlinkSync(physicalRootReservationPath(recorded)); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
+ flushDirectory(dirname(physicalRootReservationPath(recorded)));
+ excludeOwnershipMarkers([target, dirname(target)]);
+ return reservation;
+}
export function assertPhysicalRoot(path: string, identity: { worktreeId: string; coordinationPath?: string | null }): void {
try {
const root = realpathSync(path);
diff --git a/src/core/persistence/physical-root-recovery.ts b/src/core/persistence/physical-root-recovery.ts
index 2d018108da..8331608ba7 100644
--- a/src/core/persistence/physical-root-recovery.ts
+++ b/src/core/persistence/physical-root-recovery.ts
@@ -4,7 +4,7 @@ import { isAbsolute, relative, sep } from 'node:path';
import { digest } from './digest.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { adoptTransferredRootStamp, assertNoPhysicalRootOverlap, assertPhysicalRoot, physicalRootError,
- readPhysicalRootReservation, readPhysicalRootStamp, restorePhysicalRootReservation,
+ readPhysicalRootReservation, readPhysicalRootStamp, replacePhysicalRootReservation, restorePhysicalRootReservation,
type PhysicalRootReservation, type PhysicalRootStamp } from './physical-root-record.ts';
type Identity = Pick<PhysicalRootReservation, 'brainId' | 'worktreeId' | 'hostId' | 'coordinationPath'>;
@@ -13,25 +13,38 @@ export interface PhysicalRootRecovery {
before: { reservation: PhysicalRootReservation | null; stamp: PhysicalRootStamp | null };
reservation: PhysicalRootReservation;
stamp: PhysicalRootStamp;
+ /** #5914: prepared with `--confirm-relocated-root`; the inode and birth comparisons were waived and accept must repeat the flag. */
+ relocated?: true;
}
-export function inspectPhysicalRootRecovery(root: string, identity: Identity & { token?: string }): PhysicalRootRecovery {
+/**
+ * `relocated` (#5914, `--confirm-relocated-root`) waives only the inode and
+ * birth-time comparisons of a directory recreated at the same path. It needs
+ * the outside-root reservation (a copied in-root stamp alone is never
+ * authority) and every other field to agree; the returned reservation carries
+ * the live directory identity so the repair re-stamps from it.
+ */
+export function inspectPhysicalRootRecovery(root: string, identity: Identity & { token?: string }, opts: { relocated?: boolean } = {}): PhysicalRootRecovery {
if (realpathSync(root) !== root || lstatSync(root).isSymbolicLink()) throw physicalRootError();
const rel = relative(root, identity.coordinationPath);
if (canonicalFilesystemPath(identity.coordinationPath) !== identity.coordinationPath
|| !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`)) throw physicalRootError();
const reservation = readPhysicalRootReservation(root), stamp = readPhysicalRootStamp(root), info = statSync(root, { bigint: true });
if (!info.isDirectory()) throw physicalRootError();
+ if (opts.relocated && !reservation) throw physicalRootError('No ownership reservation exists beside this checkout, so the relocation cannot be confirmed; a copied stamp alone is not authority.');
if (reservation && (reservation.brainId !== identity.brainId || reservation.worktreeId !== identity.worktreeId
|| reservation.coordinationPath !== identity.coordinationPath)) throw physicalRootError();
+ const sameDirectory = (inode: string, birth: string) => opts.relocated || inode === info.ino.toString() && birth === info.birthtimeNs.toString();
if (stamp && (stamp.brainId !== identity.brainId || stamp.worktreeId !== identity.worktreeId || stamp.root !== root
- || reservation && stamp.token !== reservation.token || stamp.inode !== info.ino.toString() || stamp.birth !== info.birthtimeNs.toString())) throw physicalRootError();
- if (!stamp && reservation && (reservation.initialInode !== info.ino.toString() || reservation.initialBirth !== info.birthtimeNs.toString())) throw physicalRootError();
+ || reservation && stamp.token !== reservation.token || !sameDirectory(stamp.inode, stamp.birth))) throw physicalRootError();
+ if (!stamp && reservation && !sameDirectory(reservation.initialInode ?? '', reservation.initialBirth ?? '')) throw physicalRootError();
assertNoPhysicalRootOverlap(root);
- const target: PhysicalRootReservation = reservation ?? { version: 1, ...identity, root, token: stamp?.token ?? identity.token ?? randomUUID(),
- initialDevice: info.dev.toString(), initialInode: info.ino.toString(), initialBirth: info.birthtimeNs.toString() };
+ const live = { initialDevice: info.dev.toString(), initialInode: info.ino.toString(), initialBirth: info.birthtimeNs.toString() };
+ const target: PhysicalRootReservation = reservation ? opts.relocated ? { ...reservation, ...live } : reservation
+ : { version: 1, ...identity, root, token: stamp?.token ?? identity.token ?? randomUUID(), ...live };
return { hostId: identity.hostId, before: { reservation, stamp }, reservation: target, stamp: { version: 1, token: target.token,
- brainId: target.brainId, worktreeId: target.worktreeId, root, device: info.dev.toString(), inode: info.ino.toString(), birth: info.birthtimeNs.toString() } };
+ brainId: target.brainId, worktreeId: target.worktreeId, root, device: info.dev.toString(), inode: info.ino.toString(), birth: info.birthtimeNs.toString() },
+ ...(opts.relocated ? { relocated: true as const } : {}) };
}
export function repairPhysicalRoot(root: string, recovery: PhysicalRootRecovery,
@@ -39,13 +52,14 @@ export function repairPhysicalRoot(root: string, recovery: PhysicalRootRecovery,
const target = recovery.reservation;
if (target.root !== root || target.worktreeId !== identity.worktreeId || recovery.hostId !== identity.hostId
|| target.coordinationPath !== identity.coordinationPath) throw physicalRootError();
- const current = inspectPhysicalRootRecovery(root, { ...target, hostId: identity.hostId });
+ const current = inspectPhysicalRootRecovery(root, { ...target, hostId: identity.hostId }, { relocated: recovery.relocated === true });
const same = (a: unknown, b: unknown) => digest(a) === digest(b);
if (!same(current.stamp, recovery.stamp)
|| !same(current.before.reservation, recovery.before.reservation) && !same(current.before.reservation, target)
|| !same(current.before.stamp, recovery.before.stamp) && !same(current.before.stamp, recovery.stamp)) throw physicalRootError('Physical identity changed after transfer preparation; inspect the retained recovery state.');
if (dryRun) return;
- restorePhysicalRootReservation(target);
+ if (recovery.relocated && recovery.before.reservation) replacePhysicalRootReservation(root, recovery.before.reservation, target);
+ else restorePhysicalRootReservation(target);
if (!same(readPhysicalRootReservation(root), target)) throw physicalRootError();
adoptTransferredRootStamp(root, target, target.token);
assertPhysicalRoot(root, identity);
diff --git a/src/core/persistence/pre-activation-release.ts b/src/core/persistence/pre-activation-release.ts
index dd7951e699..d365085148 100644
--- a/src/core/persistence/pre-activation-release.ts
+++ b/src/core/persistence/pre-activation-release.ts
@@ -62,7 +62,8 @@ export async function releasePreActivationClaims(engine: BrainEngine, opts: { ex
const binding = await getWorktreeBinding(engine, claim.source_id, hostId);
if (!binding || binding.owner_host_id !== hostId || !binding.local_path || locked.has(binding.worktree_id)) continue;
locked.add(binding.worktree_id);
- const lock = await acquireWorktree(binding, 0, undefined, undefined, { yieldLanes: true });
+ // #5914: the release publishes nothing, so it needs the native lock and the reservation's worktree id and token, not the inode of a recreated directory.
+ const lock = await acquireWorktree(binding, 0, undefined, undefined, { yieldLanes: true, identity: 'reservation' });
if (!lock) throw new OperationError('writer_lock_unavailable', `A local process holds the worktree lock of claimed source '${claim.source_id}'.`,
'Stop the gbrain process on this host that holds it (gbrain serve or autopilot), then rerun deactivate.');
locks.push(lock);
diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.ts
index 158871fccf..e827a0a537 100644
--- a/src/core/persistence/source-lifecycle.ts
+++ b/src/core/persistence/source-lifecycle.ts
@@ -25,6 +25,7 @@ import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from '.
import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.ts';
import { flushTopologyDirectory } from './topology-filesystem.ts';
import { claimPhysicalRoot } from './physical-root.ts';
+import { inspectRelocatedPhysicalRoot, relocatePhysicalRoot } from './physical-root-record.ts';
import { assertWriterAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';
import { assertWriterAdminUnlocked } from './admin-lock.ts';
@@ -212,6 +213,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
const invalidated=await settleTopologyRequests(tx,sources,worktrees,principal);
// All pending mirrors must settle before these manifests are read. A pure
// path rebind may never substitute stale or incomplete canonical bytes.
+ let relocated:ReturnType<typeof inspectRelocatedPhysicalRoot>|undefined;
if(input.operation==='rebind'){
const binding=bindings.find(value=>value.source_id===input.sourceId);
if(!binding&&source?.local_path===null)throw new OperationError('writer_registration_required','This source has no canonical filesystem binding.',
@@ -221,6 +223,8 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
{fix:ownerStatusFix(input.sourceId)});
if(manifests.get(binding.local_path)!.digest!==manifests.get(root!.worktree)!.digest) throw rebindManifestMismatch(input.sourceId,binding.local_path,root!.worktree,
storedManifestScope(manifests.get(binding.local_path)));
+ if(binding.local_path!==root!.worktree&&realpathSync(binding.local_path)===root!.worktree)
+ relocated=inspectRelocatedPhysicalRoot(binding.local_path,root!.worktree,{worktreeId:binding.worktree_id,coordinationPath:binding.coordination_path});
}
const ownedSourcePath=currentBinding?.local_path?join(currentBinding.local_path,currentBinding.relative_path):source?.local_path;
if(input.operation==='restore'&&ownedSourcePath&&!existsSync(ownedSourcePath)) throw opError('recovery_required','Restore requires the verified canonical checkout. Reclone it before restoring the source.',
@@ -242,7 +246,16 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
archive_expires_at=COALESCE(archive_expires_at,now()+interval '72 hours'),config=$2::text::jsonb WHERE id=$1`,[input.sourceId,JSON.stringify({...source?.config,federated:false})]);
else if(input.operation==='restore') await tx.executeRaw(`UPDATE sources SET archived=false,archived_at=NULL,archive_expires_at=NULL,
config=$2::text::jsonb WHERE id=$1`,[input.sourceId,JSON.stringify({...source?.config,federated:input.refederate!==false})]);
- else if(input.operation==='rebind'){
+ else if(input.operation==='rebind'&&relocated){
+ // #5914 (P1.3c): the recorded root now resolves through a symlink to the new directory; the worktree keeps its id
+ // and its ownership records move to the real path (reservation under the new sha256(root) name, stamp naming it).
+ const moved=relocatePhysicalRoot(currentBinding!.local_path!,root!.worktree,relocated);
+ await tx.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1',[input.sourceId,root!.source]);
+ await tx.executeRaw('UPDATE persistence_host_bindings SET local_path=$3 WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[currentBinding!.worktree_id,localHostId(),moved.root]);
+ const rel=relative(nativeFilesystemPath(moved.root),nativeFilesystemPath(root!.source)).split(sep).join('/');
+ await tx.executeRaw('UPDATE persistence_source_bindings SET relative_path=$2 WHERE source_id=$1',[input.sourceId,rel]);
+ manifests.set(moved.root,manifests.get(root!.worktree)!);
+ }else if(input.operation==='rebind'){
await tx.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1',[input.sourceId,root!.source]);
const id=await installTopologyBinding(tx,input.sourceId,incarnation,root!,bindings);if(!worktrees.includes(id))worktrees.push(id);
}else{
@@ -272,7 +285,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
const row=await recordTopologyChange(tx,{principal,requestId,intent,operation:input.operation,sourceId:input.sourceId,incarnation:source?.incarnation??String(result.source_incarnation),worktrees},result);
return topologyReceipt(row);
});
- },root?.worktree);
+ },root?.worktree,5000,{relocation:input.operation==='rebind'});
}
/** #6099: a rebind's new directory does not match the current checkout; names the first differing paths (Git-tracked paths in git scope). */
diff --git a/src/core/persistence/topology-locks.ts b/src/core/persistence/topology-locks.ts
index 06d550fada..7447c4f738 100644
--- a/src/core/persistence/topology-locks.ts
+++ b/src/core/persistence/topology-locks.ts
@@ -1,6 +1,7 @@
import { join } from 'node:path';
-import { existsSync } from 'node:fs';
+import { existsSync, realpathSync } from 'node:fs';
import { assertPhysicalRoot } from './physical-root.ts';
+import { inspectRelocatedPhysicalRoot } from './physical-root-record.ts';
import type { BrainEngine } from '../engine.ts';
import { opError } from '../ops/contract.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
@@ -32,8 +33,14 @@ export async function lockTopologyPrincipal(engine: BrainEngine, id: string): Pr
}
/** Native locks precede every topology/source/grant/receipt transaction. */
+/**
+ * `relocation` (#5914, P1.3c): a `set-path` whose target is where the recorded
+ * root now resolves through a symlink. The recorded binding then verifies as a
+ * relocated root (reservation and stamp agree on token, brainId and worktreeId)
+ * instead of failing the realpath check; the transaction moves its records.
+ */
export async function withTopologyLocks<T>(engine: BrainEngine, sourceId: string,
- run: (bindings: TopologyBinding[]) => Promise<T>, additionalRoot?: string, waitMs=5000): Promise<T> {
+ run: (bindings: TopologyBinding[]) => Promise<T>, additionalRoot?: string, waitMs=5000, opts: { relocation?: boolean } = {}): Promise<T> {
const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
const handles: NativeLockHandle[] = [];
const take = async (path: string) => {
@@ -63,7 +70,10 @@ 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))assertPhysicalRoot(item.local_path,{worktreeId:item.worktree_id,coordinationPath: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);
}
return await run(bindings);
} finally { for (const handle of handles.reverse()) await handle.release(); }
diff --git a/test/deactivate-preview-parity.test.ts b/test/deactivate-preview-parity.test.ts
new file mode 100644
index 0000000000..72ff3bc8d5
--- /dev/null
+++ b/test/deactivate-preview-parity.test.ts
@@ -0,0 +1,87 @@
+/**
+ * #5914 (W14 P1.3 [R9a]): each `deactivate --dry-run` runs the probe of its own
+ * real operation on a recreated canonical root. The classic (pre-activation)
+ * release publishes nothing, so it holds the native lock and checks only the
+ * reservation's worktree id and token: its preview lists no `physical_root`
+ * blocker and the real release succeeds; a token mismatch still refuses both.
+ * The managed real run takes the strict worktree lock, so its preview lists
+ * `physical_root` and the real run refuses with the same blocker.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, 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 { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
+import { writerAdminState } from '../src/core/persistence/admin-intent.ts';
+import { getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { PHYSICAL_ROOT_MARKER } from '../src/core/persistence/physical-root-record.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { recreateRoot } from './helpers/recreate-root.ts';
+
+const admin = (engine: BrainEngine, operation: string, params: Record<string, unknown> = {}) =>
+ runPersistenceAdministration(engine, operation as never, params) as Promise<Record<string, any>>;
+const deactivate = async (engine: BrainEngine, extra: Record<string, unknown> = {}) =>
+ admin(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: await writerAdminState(engine), ...extra });
+function corruptToken(root: string) {
+ const path = join(root, PHYSICAL_ROOT_MARKER), stamp = JSON.parse(readFileSync(path, 'utf8'));
+ writeFileSync(path, JSON.stringify({ ...stamp, token: randomUUID() }), { mode: 0o600 });
+}
+
+describe('classic release (pre-activation claim) on a recreated root', () => {
+ const directory = mkdtempSync(join(tmpdir(), 'gbrain-preview-parity-'));
+ let engine: BrainEngine;
+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });
+ afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(directory, { recursive: true, force: true }); });
+
+ async function claimed(run: (f: { root: string; source: string }) => Promise<void>) {
+ const home = join(directory, randomUUID()), root = join(home, 'root'); mkdirSync(root, { recursive: true });
+ const source = `classic-${randomUUID().slice(0, 8)}`;
+ writeFileSync(join(root, 'note.md'), 'Canonical example');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, root]);
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined }, async () => {
+ await runPersistenceAdministration(engine, 'writer_claim', { source_id: source, path: root, ...await reviewedWriterIntent(engine, 'writer_claim') });
+ await run({ root, source });
+ });
+ }
+
+ test('preview lists no physical_root blocker and the real release succeeds', () => claimed(async f => {
+ recreateRoot(f.root, { keepStamp: true });
+ const dry = await admin(engine, 'writer_deactivate', { dry_run: true });
+ expect(dry.mode).toBe('classic');
+ expect(dry.pre_activation_claims.map((c: { source_id: string }) => c.source_id)).toEqual([f.source]);
+ expect(dry.blockers).toEqual([]);
+ const released = await deactivate(engine);
+ expect(released.pre_activation_claims.map((c: { source_id: string }) => c.source_id)).toEqual([f.source]);
+ expect(await getWorktreeBinding(engine, f.source)).toBeNull();
+ }));
+
+ test('a token mismatch: the preview lists physical_root and the real release refuses on the same blocker', () => claimed(async f => {
+ recreateRoot(f.root, { keepStamp: true });
+ corruptToken(f.root);
+ const dry = await admin(engine, 'writer_deactivate', { dry_run: true });
+ expect(dry.blockers.map((b: { kind: string; source_id?: string }) => [b.kind, b.source_id])).toEqual([['physical_root', f.source]]);
+ await expect(deactivate(engine)).rejects.toMatchObject({ code: 'writer_not_quiesced', suggestion: expect.stringContaining(`physical_root ${dry.blockers[0].id}`) });
+ expect(await getWorktreeBinding(engine, f.source)).not.toBeNull();
+ await engine.executeRaw('DELETE FROM persistence_source_bindings WHERE source_id=$1', [f.source]);
+ }));
+});
+
+describe('managed deactivation on a recreated root', () => {
+ test('preview lists physical_root and the real run refuses with the same blocker', () => managedBrain(async ({ engine, root }) => {
+ recreateRoot(root, { keepStamp: true });
+ const dry = await admin(engine, 'writer_deactivate', { dry_run: true });
+ expect(dry.mode).toBe('managed');
+ const blocker = dry.blockers.find((b: { kind: string }) => b.kind === 'physical_root');
+ expect(blocker).toMatchObject({ source_id: 'default' });
+ expect(blocker.exit).toContain('--self-transfer');
+ expect(blocker.exit).toContain('--confirm-relocated-root');
+ await expect(deactivate(engine)).rejects.toMatchObject({ code: 'writer_not_quiesced', suggestion: expect.stringContaining('physical_root') });
+ expect((await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1'))[0].enabled).toBe(true);
+ }));
+});
diff --git a/test/e2e/physical-root-relocation.test.ts b/test/e2e/physical-root-relocation.test.ts
new file mode 100644
index 0000000000..ca6ae6b8e2
--- /dev/null
+++ b/test/e2e/physical-root-relocation.test.ts
@@ -0,0 +1,7 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+// #5914 (W14 P1.3 / P1.3c): the recreated-root waiver and the symlink rebind on Postgres.
+await registerPostgresTests(
+ () => import('../physical-root-relocated.test.ts'),
+ () => import('../physical-root-symlink.test.ts'),
+);
diff --git a/test/helpers/recreate-root.ts b/test/helpers/recreate-root.ts
new file mode 100644
index 0000000000..a26ca1f2de
--- /dev/null
+++ b/test/helpers/recreate-root.ts
@@ -0,0 +1,18 @@
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { PHYSICAL_ROOT_MARKER } from '../../src/core/persistence/physical-root-record.ts';
+
+/** Deletes and recreates the directory at the same path: a new inode and birth time, the same bytes. */
+export function recreateRoot(root: string, opts: { keepStamp: boolean }): void {
+ const stamp = readFileSync(join(root, PHYSICAL_ROOT_MARKER));
+ const before = statSync(root, { bigint: true });
+ rmSync(root, { recursive: true });
+ mkdirSync(join(root, '..', `decoy-${randomUUID().slice(0, 8)}`));
+ mkdirSync(root);
+ writeFileSync(join(root, 'note.md'), 'Canonical example');
+ if (opts.keepStamp) writeFileSync(join(root, PHYSICAL_ROOT_MARKER), stamp, { mode: 0o600 });
+ const after = statSync(root, { bigint: true });
+ if (after.ino === before.ino && after.birthtimeNs === before.birthtimeNs) throw new Error('fixture: the recreated directory kept its identity');
+}
+
diff --git a/test/physical-root-relocated.test.ts b/test/physical-root-relocated.test.ts
new file mode 100644
index 0000000000..51e2edcfa7
--- /dev/null
+++ b/test/physical-root-relocated.test.ts
@@ -0,0 +1,132 @@
+/**
+ * #5914 (W14 P1.3): a canonical root recreated at the same path (new inode and
+ * birth time) refused `recovery_required` from every verb, self-transfer
+ * included. `--confirm-relocated-root` on `transfer prepare/accept
+ * --self-transfer` waives only the inode/birth comparisons, and only when
+ * token, brainId, worktreeId, root and coordination path all agree and the
+ * outside-root reservation exists (a copied in-root stamp alone is never
+ * authority). The waiver is persisted on the prepared record and required at
+ * accept; the re-stamp goes through a compare-and-swap on the reservation.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, 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 { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
+import { acquireWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath, readPhysicalRootReservation, readPhysicalRootStamp,
+ replacePhysicalRootReservation } from '../src/core/persistence/physical-root-record.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { recreateRoot } from './helpers/recreate-root.ts';
+
+const backends = testBackends();
+for (const kind of backends) describe(`relocated canonical root (${kind})`, () => {
+ const directory = mkdtempSync(join(tmpdir(), 'gbrain-relocated-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 disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); rmSync(directory, { recursive: true, force: true }); });
+
+ async function fixture(run: (f: { root: string; home: string; source: string; binding: NonNullable<Awaited<ReturnType<typeof getWorktreeBinding>>> }) => Promise<void>) {
+ const home = join(directory, randomUUID()), root = join(home, 'root'); mkdirSync(root, { recursive: true });
+ const source = `relocated-${randomUUID().slice(0, 8)}`;
+ writeFileSync(join(root, 'note.md'), 'Canonical example');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, root]);
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined }, async () => {
+ await runPersistenceAdministration(engine, 'writer_claim', { source_id: source, path: root, ...await reviewedWriterIntent(engine, 'writer_claim') });
+ await run({ root, home, source, binding: (await getWorktreeBinding(engine, source))! });
+ });
+ }
+ const administer = async (operation: 'writer_transfer_prepare' | 'writer_transfer_accept', params: Record<string, unknown>) =>
+ runPersistenceAdministration(engine, operation, { ...params, ...await reviewedWriterIntent(engine, operation) }) as Promise<any>;
+ const storedSelfTransfer = async (worktreeId: string) => (await engine.executeRaw<{ manifest: { self_transfer?: { relocated?: boolean } } }>(
+ 'SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [worktreeId]))[0].manifest?.self_transfer;
+
+ for (const keepStamp of [true, false]) test(`recreated root (${keepStamp ? 'stamp restored from backup' : 'no stamp'}): refused without the waiver, repaired with it, waiver required at accept`, () => fixture(async f => {
+ recreateRoot(f.root, { keepStamp });
+ const live = statSync(f.root, { bigint: true });
+ await expect(acquireWorktree(f.binding)).rejects.toMatchObject({ code: 'recovery_required' });
+ await expect(administer('writer_transfer_prepare', { source_id: f.source, self_transfer: true })).rejects.toMatchObject({ code: 'recovery_required' });
+ await expect(administer('writer_transfer_prepare', { source_id: f.source, confirm_relocated_root: true })).rejects.toMatchObject({ code: 'invalid_params' });
+
+ const prepared = await administer('writer_transfer_prepare', { source_id: f.source, self_transfer: true, confirm_relocated_root: true });
+ expect((await storedSelfTransfer(f.binding.worktree_id))?.relocated).toBe(true);
+ const accept = { source_id: f.source, path: f.root, expected_epoch: prepared.owner_epoch, manifest: prepared.manifest.digest, self_transfer: true };
+ await expect(administer('writer_transfer_accept', accept)).rejects.toMatchObject({ code: 'writer_transfer_conflict' });
+ expect(readPhysicalRootReservation(f.root)!.initialInode).not.toBe(live.ino.toString());
+ await administer('writer_transfer_accept', { ...accept, confirm_relocated_root: true });
+
+ const binding = (await getWorktreeBinding(engine, f.source))!;
+ expect(binding.owner_epoch).toBe('2'); expect(binding.state).toBe('active');
+ const reservation = readPhysicalRootReservation(f.root)!, stamp = readPhysicalRootStamp(f.root)!;
+ expect(reservation.initialInode).toBe(live.ino.toString()); expect(reservation.initialBirth).toBe(live.birthtimeNs.toString());
+ expect(stamp.inode).toBe(live.ino.toString()); expect(stamp.token).toBe(reservation.token);
+ const lock = await acquireWorktree(binding); expect(lock).not.toBeNull(); await lock?.release();
+ }));
+
+ test('the waiver is denied when the reservation is missing or any identity field disagrees; nothing is re-stamped', () => fixture(async f => {
+ recreateRoot(f.root, { keepStamp: true });
+ const reservationPath = physicalRootReservationPath(f.root), stampPath = join(f.root, PHYSICAL_ROOT_MARKER);
+ const reservation = readFileSync(reservationPath, 'utf8'), stamp = readFileSync(stampPath, 'utf8');
+ const waived = () => administer('writer_transfer_prepare', { source_id: f.source, self_transfer: true, confirm_relocated_root: true });
+ const unchanged = () => { expect(readFileSync(stampPath, 'utf8')).toBe(stamp); expect(existsSync(reservationPath) ? readFileSync(reservationPath, 'utf8') : null).toBeOneOf([reservation, null]); };
+
+ rmSync(reservationPath);
+ await expect(waived()).rejects.toMatchObject({ code: 'recovery_required' });
+ unchanged();
+ writeFileSync(reservationPath, reservation, { mode: 0o600 });
+
+ for (const [field, value] of [['token', randomUUID()], ['worktreeId', randomUUID()], ['brainId', randomUUID()], ['root', join(f.home, 'elsewhere')]] as const) {
+ const damaged = { ...JSON.parse(stamp), [field]: value };
+ writeFileSync(stampPath, JSON.stringify(damaged), { mode: 0o600 });
+ await expect(waived()).rejects.toMatchObject({ code: 'recovery_required' });
+ expect(readFileSync(reservationPath, 'utf8')).toBe(reservation);
+ writeFileSync(stampPath, stamp, { mode: 0o600 });
+ }
+ writeFileSync(reservationPath, JSON.stringify({ ...JSON.parse(reservation), coordinationPath: join(f.home, 'other.lock') }), { mode: 0o600 });
+ await expect(waived()).rejects.toMatchObject({ code: 'recovery_required' });
+ writeFileSync(reservationPath, reservation, { mode: 0o600 });
+ unchanged();
+ expect(await storedSelfTransfer(f.binding.worktree_id)).toBeUndefined();
+ }));
+
+ test('the re-stamp is a compare-and-swap: a second identical swap is a no-op, a stale expectation refuses, and an accept after a foreign re-stamp refuses', () => fixture(async f => {
+ recreateRoot(f.root, { keepStamp: true });
+ const before = readPhysicalRootReservation(f.root)!;
+ const live = statSync(f.root, { bigint: true });
+ const next = { ...before, initialDevice: live.dev.toString(), initialInode: live.ino.toString(), initialBirth: live.birthtimeNs.toString() };
+ replacePhysicalRootReservation(f.root, before, next);
+ expect(readPhysicalRootReservation(f.root)).toEqual(next);
+ replacePhysicalRootReservation(f.root, before, next);
+ expect(readPhysicalRootReservation(f.root)).toEqual(next);
+ expect(() => replacePhysicalRootReservation(f.root, before, { ...next, initialInode: '1' })).toThrow(expect.objectContaining({ code: 'recovery_required', detail: 'stale_record' }));
+ expect(readPhysicalRootReservation(f.root)).toEqual(next);
+
+ expect(() => replacePhysicalRootReservation(f.root, next, { ...next, token: randomUUID() })).toThrow(expect.objectContaining({ code: 'recovery_required' }));
+
+ replacePhysicalRootReservation(f.root, next, before);
+ const prepared = await administer('writer_transfer_prepare', { source_id: f.source, self_transfer: true, confirm_relocated_root: true });
+ writeFileSync(physicalRootReservationPath(f.root), JSON.stringify({ ...before, initialInode: '1' }), { mode: 0o600 });
+ await expect(administer('writer_transfer_accept', { source_id: f.source, path: f.root, expected_epoch: prepared.owner_epoch, manifest: prepared.manifest.digest,
+ self_transfer: true, confirm_relocated_root: true })).rejects.toMatchObject({ code: 'recovery_required' });
+ }));
+
+ test('the waiver on an intact root is a plain self-transfer: the reservation is left as it is', () => fixture(async f => {
+ const reservation = readFileSync(physicalRootReservationPath(f.root), 'utf8');
+ const prepared = await administer('writer_transfer_prepare', { source_id: f.source, self_transfer: true, confirm_relocated_root: true });
+ expect((await storedSelfTransfer(f.binding.worktree_id))?.relocated).toBe(true);
+ await administer('writer_transfer_accept', { source_id: f.source, path: f.root, expected_epoch: prepared.owner_epoch, manifest: prepared.manifest.digest,
+ self_transfer: true, confirm_relocated_root: true });
+ expect(readFileSync(physicalRootReservationPath(f.root), 'utf8')).toBe(reservation);
+ expect((await getWorktreeBinding(engine, f.source))!.owner_epoch).toBe('2');
+ }));
+});
diff --git a/test/physical-root-symlink.test.ts b/test/physical-root-symlink.test.ts
new file mode 100644
index 0000000000..274990039d
--- /dev/null
+++ b/test/physical-root-symlink.test.ts
@@ -0,0 +1,88 @@
+/**
+ * #5914 (W14 P1.3c [R9b]): the recorded canonical path now traverses a
+ * symlink (the checkout was moved and a link left at the old path). Every
+ * verb refused `recovery_required` before any inode comparison, with no exit.
+ * `gbrain sources set-path <id> <old-or-new-path>` now converges when
+ * `realpathSync(old) === new` and the reservation and stamp agree on token,
+ * brainId and worktreeId: the host binding and `local_path` move to the real
+ * directory, the reservation is rewritten under the new `sha256(root)` name,
+ * the old one is removed and the stamp names the new root. The worktree keeps
+ * its id; nothing else about the identity check is relaxed.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, symlinkSync, 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 { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath, readPhysicalRootReservation, readPhysicalRootStamp } 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 { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+for (const kind of backends) describe(`canonical path through a symlink (${kind})`, () => {
+ const directory = mkdtempSync(join(tmpdir(), 'gbrain-symlink-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 disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); rmSync(directory, { recursive: true, force: true }); });
+
+ async function fixture(run: (f: { root: string; real: string; home: string; source: string; binding: NonNullable<Awaited<ReturnType<typeof getWorktreeBinding>>> }) => Promise<void>) {
+ const home = mkdtempSync(join(directory, 'home-')), root = join(home, 'root'), real = join(home, 'moved', 'root'); mkdirSync(root, { recursive: true });
+ const source = `symlink-${randomUUID().slice(0, 8)}`;
+ writeFileSync(join(root, 'note.md'), 'Canonical example');
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ await resetPgliteState(engine as PGLiteEngine);
+ await registerLocalWriter(engine, 'cli');
+ 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');
+ const binding = (await getWorktreeBinding(engine, source))!;
+ mkdirSync(join(home, 'moved'));
+ renameSync(root, real);
+ symlinkSync(real, root);
+ await run({ root, real, home, source, binding });
+ });
+ }
+ const setPath = (source: string, path: string) => runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: source, path });
+
+ test('set-path to the recorded (now symlinked) path or its real target converges and keeps the worktree', () => fixture(async f => {
+ await expect(acquireWorktree(f.binding)).rejects.toMatchObject({ code: 'recovery_required' });
+ const oldReservation = physicalRootReservationPath(f.root);
+ expect(existsSync(oldReservation)).toBe(true);
+ const token = JSON.parse(readFileSync(join(f.real, PHYSICAL_ROOT_MARKER), 'utf8')).token;
+
+ const receipt = await setPath(f.source, f.root) as Record<string, any>;
+ expect(receipt.noop).not.toBe(true);
+ const binding = (await getWorktreeBinding(engine, f.source))!;
+ expect(binding.worktree_id).toBe(f.binding.worktree_id);
+ expect(binding.local_path).toBe(f.real);
+ expect((await engine.executeRaw<{ local_path: string }>('SELECT local_path FROM sources WHERE id=$1', [f.source]))[0].local_path).toBe(f.real);
+ expect(existsSync(oldReservation)).toBe(false);
+ const reservation = readPhysicalRootReservation(f.real)!, stamp = readPhysicalRootStamp(f.real)!;
+ expect(reservation.root).toBe(f.real); expect(reservation.token).toBe(token);
+ expect(stamp.root).toBe(f.real); expect(stamp.token).toBe(token);
+ const lock = await acquireWorktree(binding); expect(lock).not.toBeNull(); await lock?.release();
+
+ const again = await setPath(f.source, f.real) as Record<string, any>;
+ expect(again.noop).toBe(true);
+ }));
+
+ test('a token or worktree mismatch keeps the refusal; no reservation moves', () => fixture(async f => {
+ const stampPath = join(f.real, PHYSICAL_ROOT_MARKER), stamp = JSON.parse(readFileSync(stampPath, 'utf8'));
+ writeFileSync(stampPath, JSON.stringify({ ...stamp, token: randomUUID() }), { mode: 0o600 });
+ await expect(setPath(f.source, f.root)).rejects.toMatchObject({ code: 'recovery_required' });
+ expect(existsSync(physicalRootReservationPath(f.root))).toBe(true);
+ expect(existsSync(physicalRootReservationPath(f.real))).toBe(false);
+ expect((await getWorktreeBinding(engine, f.source))!.local_path).toBe(f.root);
+ }));
+});