Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sources): name a moved managed checkout and its exit (physical_root_moved)

garrytand504915d0d29
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8cadb056cf..19ddab5240 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,44 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**Moved your brain folder? gbrain now tells you how to bring it back.** When a managed checkout was moved to a new path, or a folder above it was renamed, `gbrain sources set-path` and `gbrain sources add` used to refuse with a generic "identity changed" or "checkout missing" error that offered no way out, and their `--dry-run` said everything was fine. Now the preview and the real command refuse the same way, name where gbrain recorded the folder and where it is now, and give the exact commands that get you back without losing the folder's ownership or Git history. Nothing new can rebind ownership: the commands are the ones that already worked, and gbrain still checks everything they do.
+
+### How to use it
+
+Run the command you were going to run, with `--dry-run`:
+
+```bash
+gbrain sources set-path notes /Users/alice-example/Brain --dry-run
+```
+
+The refusal (`recovery_required`, detail `physical_root_moved`) carries its exit as a `fix` the agent asks you about first, because it moves your folders:
+
+| What happened | The exit it names |
+|---|---|
+| Folder moved, its source still registered | `ln -s <new> <old>`, `gbrain sources set-path <source> <new>`, `rm <old>` |
+| Folder moved after `gbrain sources remove` | `mv <new> <old>`, then `gbrain sources add <id> --path <old>`, which reattaches the folder's history |
+| A parent folder renamed | the same, on the parent folder |
+| Copied to another disk and the original deleted | restore the original, or switch to classic mode (`gbrain sources writer deactivate --dry-run`); a copy cannot be reattached |
+
+### Things to watch
+
+- `gbrain sources add --dry-run` and `gbrain sources writer claim --dry-run` now refuse a folder that holds a copied ownership stamp, and `gbrain sources set-path --dry-run` refuses a missing checkout, as their real runs always did. They still write nothing.
+- A remote agent whose page write reaches such a folder sees only the detail, never a path.
+- A brain without a Git repository is unaffected: the default keyless brain's `gbrain sources set-path` stays a plain path update.
+
+Proposed and first implemented by @Kkkkkuro (#8625).
+
+### Itemized changes
+
+- `src/core/persistence/physical-root-record.ts`: `describeMovedPhysicalRoot` (read-only file evidence: the stamp's recorded root is gone, and the reservation of that root, beside it or beside the new root after a parent rename, carries the stamp's token, brain and worktree; `sameDirectory` from device, inode and birth time), `physicalRootMovedError` (path-free) and `physicalRootMovedRefusal` (the local CLI refusal with an `ask_user` fix chain in argv form, paths shell-quoted in the prose). An ownership stamp other users can read at the new path now refuses `ownership_record_not_private` instead of the generic error.
+- `src/core/persistence/physical-root.ts`: `movedPhysicalRoot` accepts the evidence only for this brain, a worktree this host owns and a host binding still at the recorded root; `reservePhysicalRoot` raises the path-free refusal on its copied-marker branch.
+- `src/core/persistence/source-lifecycle.ts`, `topology-locks.ts`, `administration.ts`: `add`, `claim`, `rebind` and `writer claim` build the full refusal (never for the automatic first-write claim); their dry runs predict it, and a rebind dry run of a missing checkout refuses `source_checkout_missing` like the real run.
+- `src/core/persistence/verb-errors.ts`, `src/core/error-registry.ts`: the `physical_root_moved` reason and its explanation; `docs/guides/error-codes.md` regenerated.
+- Docs: `docs/architecture/topologies.md#moved-root`, `docs/guides/write-refusals.md#moved-root`.
+- Tests: `test/physical-root-moved-8625.test.ts` (PGLite and Postgres: leaf and parent moves, bound and removed sources, Git and plain directories, a copy on a new inode, two sources in one worktree, `writer claim --dry-run`, five lookalikes that keep the generic refusal, a readable stamp, the classic keyless set-path, and a remote `put_page` whose refusal carries no path or worktree id).
+
## [0.60.620.0] - 2026-11-09
**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.
diff --git a/docs/architecture/key-files/page-identity-and-administration.md b/docs/architecture/key-files/page-identity-and-administration.md
index c69fcbc2b1..42701c3ce4 100644
--- a/docs/architecture/key-files/page-identity-and-administration.md
+++ b/docs/architecture/key-files/page-identity-and-administration.md
@@ -28,7 +28,7 @@ records refuse without deleting uncertain state. Regression coverage:
are not substitutes. This protects routine repair from accidental topology
changes, not against a malicious trusted local administrator. Read the
[operator procedure](../topologies.md) before changing its preconditions.
-- `src/core/persistence/onboarding.ts` + `legacy-locks.ts` + `physical-root-recovery.ts` — read-only source onboarding states; exact same-host dead-lock cleanup under explicit activation opt-in; and state-bound same-owner root repair using a durable manifest and token-verified temporary stamp. #5914: `inspectPhysicalRootRecovery(root, identity, { relocated })` (`--confirm-relocated-root`) waives only the inode/birth comparison, requires the outside-root reservation and every other field to agree, returns the reservation with the live directory identity and marks the recovery `relocated: true`; `repairPhysicalRoot` then rewrites the reservation through `physical-root-record.ts` `replacePhysicalRootReservation` (compare-and-swap: already-equal is a no-op, anything else refuses with detail `stale_record`) before adopting the stamp. `physical-root-record.ts` also holds `assertPhysicalRootReservation` (native-lock callers that publish nothing: reservation worktree id plus stamp token, no inode), `readRecordedPhysicalRootReservation`, `inspectRelocatedPhysicalRoot` and `relocatePhysicalRoot` (P1.3c: a recorded path that now resolves through a symlink keeps its worktree; the reservation moves under the new `sha256(root)` name and the stamp names the new root). `physical-root.ts` `restampPhysicalRoot` handles a filesystem device id that changed while the owner token, brain, worktree, root, inode and a non-zero birth time still match (macOS can renumber `st_dev` across reboots): under the caller's outside-root native lock, one transaction verifies owner host, brain and host binding and rewrites the recorded self-transfer copies and retained topology staging identities (each only while it still names the old device); after commit the stamp and the reservation's initial device are rewritten and the event is logged, so an interruption between the two leaves a device-only change the next locked acquisition finishes. Ownership markers inside a retained topology clone stage are not re-stamped; an interrupted clone recovery that spans a device renumbering still needs source recovery. `assertPhysicalRoot` stays read-only; zero birth time or any other difference keeps the refusal. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.
+- `src/core/persistence/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). #8625: `describeMovedPhysicalRoot(root)` reads only files: a stamp whose recorded root is gone, with the reservation of that root beside it (the checkout moved) or beside `root` (a renamed parent carried it; the moved pair is cut by common path suffix), token, brain and worktree agreeing, and `sameDirectory` from device, inode and birth; never ownership authority and never the token. `physicalRootMovedError` is the path-free refusal (`PHYSICAL_ROOT_MOVED_MESSAGE`, detail `physical_root_moved`); `physicalRootMovedRefusal` is the local CLI one naming the recorded path, worktree, sources and an `ask_user` fix chain (symlink, `set-path` for the first source, `rm`, then `set-path` for the rest; or `mv` back and `add`/`writer claim`; or, for a copy whose source was removed, `writer deactivate --dry-run`). `physical-root.ts` `movedPhysicalRoot` adds the database side (this brain, worktree owned by the host, host binding at the recorded root, members) and `reservePhysicalRoot` throws the path-free refusal on its copied-marker branch, which remote page writes reach through the automatic claim; `movedPhysicalRootRefusal` builds the full one, which `source-lifecycle.ts` raises for a rebind whose missing recorded checkout is stamped at the new path and in place of the claim's path-free refusal (caught around `withTopologyLocks`, except for the automatic first-write claim), and `writer claim` raises the same way. The dry runs predict both: `inspectTopologyPhysicalRoot` takes the operation, and add, claim and `writer claim --dry-run` run `topology-locks.ts` `inspectClaimedPhysicalRoot` (the copied-marker probe of a root no local binding encloses, at `claimedWorktreeRoot`); a rebind dry run of a missing recorded checkout refuses as the real run does. Tests: `test/physical-root-moved-8625.test.ts`. `physical-root.ts` `restampPhysicalRoot` handles a filesystem device id that changed while the owner token, brain, worktree, root, inode and a non-zero birth time still match (macOS can renumber `st_dev` across reboots): under the caller's outside-root native lock, one transaction verifies owner host, brain and host binding and rewrites the recorded self-transfer copies and retained topology staging identities (each only while it still names the old device); after commit the stamp and the reservation's initial device are rewritten and the event is logged, so an interruption between the two leaves a device-only change the next locked acquisition finishes. Ownership markers inside a retained topology clone stage are not re-stamped; an interrupted clone recovery that spans a device renumbering still needs source recovery. `assertPhysicalRoot` stays read-only; zero birth time or any other difference keeps the refusal. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.
- `src/core/persistence/coordination-lock.ts` — the one resolver of a worktree's native coordination lock path, used by `claimWorktree`, `reservePhysicalRoot` (managed claim and clone), `runManagedSourceClone` and `acceptWriterTransfer`. `resolveCoordinationLock(root, worktreeId, { reservation, binding }, hostId)` returns `{ path, rule }`: the recorded reservation path (always wins over env), then a transfer's recorded binding path when absolute, canonical and outside the root, then `coordinationLockDirectory`: `persistenceHome()/locks` when outside the canonical root (`persistence_home`), else `$GBRAIN_COORDINATION_HOME/locks/<sha256(root\0host)[:32]>` (`coordination_home`, absolute and no `..`, else `invalid_params`) or `~/.gbrain/persistence/locks/<namespace>` (`home_default`); a result still inside the root refuses `storage_error` before any reservation is written. `GBRAIN_COORDINATION_HOME` is on the cwd `.env` quarantine list. `repairWedgedReservation(engine, root, hostId)` (called before `claimWorktree`'s transaction and at the top of `reservePhysicalRoot`) returns at once for a missing or healthy reservation; for one whose recorded lock is inside the root (`physical-root-record.ts` `readWedgedPhysicalRootReservation`) it takes the env-independent guard `reservationRepairGuardPath` (beside the reservation, 2 s wait, else `writer_lock_unavailable`), re-checks, requires the brain id, the claiming host id and no `persistence_worktrees` row, and `repairReservationCoordinationPath` rewrites only `coordinationPath` (digest re-read before the atomic rename, `stale_record` otherwise). `onboarding.ts` reports each source's `coordination_lock` (`path`, `rule`, `old_path_wedge`, or the `directory` an unclaimed root would use; never mints a host id) and uses it for the storage preflight's `coordination_directory`. Tests: `test/coordination-lock.serial.test.ts`. `coordinationHomeIgnored(root, recorded)` reports a set `GBRAIN_COORDINATION_HOME` that applies to the root (rule 4) but names another directory than the recorded lock (`configured_directory`, `recorded_path`, `move_step`); writer status adds it as `coordination_lock.coordination_home_ignored`.
- `src/commands/doctor/checks/coordination-lock.ts` — doctor `coordination_lock_location` (read-only): warns, per source checkout or host binding of this host, when `coordinationHomeIgnored` reports the recorded lock wins over `GBRAIN_COORDINATION_HOME`, naming the recorded path and the move step. Test: `test/coordination-lock.serial.test.ts`.
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index 3bbf18fbad..51dbd6d260 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -566,6 +566,34 @@ neither relaxes anything else:
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.
+- <a id="moved-root"></a>*Moved to a new path, no symlink (#8625):* `gbrain sources
+ set-path <source> <new>`, `gbrain sources add <id> --path <new>` and
+ `gbrain sources writer claim <id> --path <new>`, dry runs included, refuse
+ `recovery_required` with detail `physical_root_moved` when the folder's stamp
+ names this brain, a worktree this host owns and a recorded root that no longer
+ exists, and the reservation under the recorded name carries the stamp's token.
+ That reservation sits beside the old root when the checkout itself moved, or
+ beside the new root when a parent folder was renamed and carried it along; the
+ refusal then names that parent. The refusal names the recorded path, the
+ worktree and its sources, and the exit (its `fix` is `ask_user`, since it
+ moves the user's folders):
+ - *The worktree still has sources:* `ln -s <new> <old>` (the moved folder or
+ parent), `gbrain sources set-path <source> <new>` (the symlinked relocation
+ above), `rm <old>`, then `set-path` for each further source of the worktree.
+ - *Its source was removed* (`remove` keeps the worktree and its history):
+ `mv <new> <old>`, then `gbrain sources add <id> --path <old>` (add `--force`
+ for a plain directory), which reattaches the worktree; move it again with the
+ steps above.
+ - *The folder is a copy* (another filesystem, a copy and delete: its device,
+ inode or birth time differs from the stamp) *and its source was removed:*
+ moving it back would not reattach the worktree, so restore the original from a
+ backup or switch the brain to classic mode with `gbrain sources writer
+ deactivate --dry-run`.
+
+ A lookalike (another brain's stamp, a token the reservation does not carry, a
+ recorded root that still exists, a worktree another host owns, no reservation)
+ keeps the generic refusal. A remote page write that reaches the automatic claim
+ of such a folder gets the detail only, with no path or worktree id.
`gbrain sources writer deactivate --dry-run` lists a `physical_root` blocker
exactly when its real run would refuse: the managed run takes the strict
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 917a8556ba..43292309ad 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3924,7 +3924,7 @@ More: [docs/guides/repair.md#recovery-prior-stage-unavailable](../../docs/guides
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| An earlier write left state that must be inspected and recovered before new writes. | Details name the exit when there is one: physical_root_device_changed (the checkout's filesystem device number changed; re-stamped by itself when ownership verifies) and physical_root_directory_changed (the directory at the recorded path was recreated, or its birth time drifted beyond 1 µs; the relocated-root self-transfer, `transfer prepare/accept <source> --self-transfer --confirm-relocated-root`, re-stamps it). Both are explained in docs/guides/write-refusals.md. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |
+| An earlier write left state that must be inspected and recovered before new writes. | Details name the exit when there is one: physical_root_device_changed (the checkout's filesystem device number changed; re-stamped by itself when ownership verifies) and physical_root_directory_changed (the directory at the recorded path was recreated, or its birth time drifted beyond 1 µs; the relocated-root self-transfer, `transfer prepare/accept <source> --self-transfer --confirm-relocated-root`, re-stamps it) and physical_root_moved (the checkout was moved to a new path or its parent folder renamed; `sources add`, `set-path` and `writer claim`, dry runs included, name the recorded path and the symlink-then-set-path or move-back exit, and a remote caller sees no path). All three are explained in docs/guides/write-refusals.md. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |
### recovery_version_unsupported
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index cc48ea8298..536eba10d9 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -64,7 +64,8 @@ of making a duplicate.
| `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. |
| `physical_root_directory_changed` | `recovery_required` | The directory at the checkout's recorded path is not the one the owner stamped: its inode changed, or its birth time differs from the stamp by more than 1 µs, while the owner token, brain, worktree, root and device all still match. A checkout deleted and recreated at the same path (restore from backup, rebuilt container, Migration Assistant copy) looks like this. A birth time within 1 µs of the stamp is accepted (#6501: APFS reports a new directory's birth time tens of nanoseconds apart across processes); a stamp of `0` against a filesystem that now reports a birth time, or a damaged stamp, still refuses. | A refused page write carries `detail: physical_root_directory_changed` and this self-transfer as its `fix` (`next: tell_user_to_run`, both phases): an agent relays it and never runs it. If the checkout was recreated at its recorded path, do a deliberate relocated-root self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. `writer status --json` prints the commands filled in. Retry the original write with the **same** request ID. Never delete ownership marker files. |
| <a id="ownership_record_not_private"></a>`ownership_record_not_private` | `recovery_required` | A private ownership record of the checkout (`.gbrain-owner.json` inside it, or `.gbrain-owner-<hash>.json` beside it) is readable by other users, typically after a recursive `chmod` of a copied brain, so it no longer proves who owns the checkout. Nothing was written; the message names no path. | The refusal's `fix` is `gbrain doctor --only foreign_ownership_marker` on the brain host, which names each such record and the exact `chmod 600 '<path>'`. Run it, then submit the write again with a new request_id. Never remove the record. |
-| <a id="recreated-root"></a>recreated or moved canonical root | `recovery_required` | The checkout at the recorded path is a different directory (new inode and birth time after a restore, a rebuilt container or a Migration Assistant copy) or the recorded path now resolves through a symlink; without this release every verb, self-transfer included, refused with no exit (#5914). | Same path, directory recreated: the self-transfer above with `--confirm-relocated-root` on **both** phases; it waives only the directory identity comparison and needs the reservation beside the root (`.gbrain-owner-<hash>.json`) and the stamp to agree on token, brain, worktree, root and coordination path. Recorded path now a symlink to the moved checkout: `gbrain sources set-path <source> <path>` on the owner host keeps the worktree and moves its records. `gbrain sources writer deactivate --dry-run` lists `physical_root` when its real run would refuse, and the dry runs of `gbrain sources remove` and `gbrain sources set-path` refuse with the same `recovery_required` their real runs would (#6849). Runbook: [recreated root](../architecture/topologies.md#recreated-root). Never delete ownership marker files. |
+| <a id="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. Moved with no symlink: the refusal names it, see [moved root](#moved-root). `gbrain sources writer deactivate --dry-run` lists `physical_root` when its real run would refuse, and the dry runs of `gbrain sources remove`, `gbrain sources set-path`, `gbrain sources add` and `gbrain sources writer claim` refuse with the same `recovery_required` their real runs would (#6849, #8625). Runbook: [recreated root](../architecture/topologies.md#recreated-root). Never delete ownership marker files. |
+| <a id="moved-root"></a>`physical_root_moved` | `recovery_required` | The checkout was moved to a new path, or a parent folder of it was renamed, with no symlink left at the recorded path (#8625). The folder's ownership stamp names this brain, a worktree this host owns and a recorded root that no longer exists, and the reservation under the recorded name carries the stamp's token. `gbrain sources add`, `gbrain sources set-path` and `gbrain sources writer claim`, their `--dry-run` included, refuse with the recorded path, the worktree and its sources; nothing changed. A remote page write that reaches the automatic claim of such a folder carries only the detail, never a path or worktree id. | The refusal's `fix` is `ask_user` (it moves the user's folders) and its `verify` is the same command with `--dry-run`. Worktree with sources: `ln -s <new> <old>`, `gbrain sources set-path <source> <new>`, `rm <old>`, then `set-path` for each further source. Source removed: `mv <new> <old>`, then `gbrain sources add <id> --path <old>` (`--force` for a plain directory), which reattaches the worktree; move it again with the first exit. A copy that is not the stamped directory (another filesystem, or copied and deleted) with its source removed cannot be moved back: restore the original from a backup, or switch to classic mode with `gbrain sources writer deactivate --dry-run`. A renamed parent folder is named and moved or symlinked instead of the checkout. Runbook: [moved root](../architecture/topologies.md#moved-root). Never delete ownership marker files. |
| <a id="embedding_budget_below_worst_case"></a>`embedding_budget_below_worst_case` | `embedding_budget_below_worst_case` | `gbrain migrate embeddings` (or the local `migrate_embeddings` operation) was given a `--max-cost-usd` cap below the migration's worst-case authorization: every planned provider request at its maximum input size, plus any debits a resumed run already holds. The run stopped before any provider request, re-chunk or vector invalidation, so nothing changed. The message and JSON carry `cap_usd`, `worst_case_usd`, `debited_usd` and `required_cap_usd`. | Re-run with the value the `suggestion` names, for example `gbrain migrate embeddings --to <provider:model> --dim <N> --max-cost-usd <required_cap_usd> --yes` (operation: `max_cost_usd`). Preview first with `--dry-run`, which prints the worst-case authorization beside the estimate. Requests settle to reported usage, so actual spend is usually far below the cap. See [embedding migration](embedding-migration.md). |
| frontmatter slug conflict | `frontmatter_slug_conflict` (`invalid_params` on a gbrain older than v0.60.47.0) | A file's frontmatter `slug:` names a different page than its path. On a write nothing is written; during sync the file is held and the rest of the source imports. | Remove the `slug:` line or make it match the path, commit, then sync. See [`frontmatter_slug_conflict`](#frontmatter_slug_conflict). |
| `cursor_processing_options_conflict` | `invalid_params` | Retired in 0.60.255.0 (#6712): no longer returned. An unfinished sync's processing opt-outs (`--no-embed`, `--no-extract`, `--no-schema-pack`) are inherited by every run that resumes it, and the result names them in `inherited_options`. An older gbrain still returns it when a run's processing flags conflict with the cursor's. | On an older gbrain, run the printed resume command (`gbrain sync --source <source> --no-pull` plus the saved flags) or drop the conflicting flag. After upgrading, rerun the sync: it finishes the cursor with its stored opt-outs. |
@@ -86,7 +87,7 @@ of making a duplicate.
| <a id="writer_admin_locked"></a>`writer_admin_locked` | `writer_admin_locked` | The operator set the brain's writer admin lock (`gbrain sources writer lock`), so writer claim, activate, transfer prepare and transfer accept refuse for every caller. Ordinary writes are not affected. | Agents: stop and ask the operator; do not unlock it yourself. The operator runs, on the brain host, `gbrain sources writer unlock`, re-reads `gbrain sources writer status <source> --json`, administers, then `gbrain sources writer lock` again. See the [writer admin lock](../architecture/topologies.md#writer-admin-lock). |
| <a id="writer_not_quiesced"></a>`writer_not_quiesced` | `writer_not_quiesced` | Activation found an older writer, a legacy lock, or queued, running or recovering work. When work blocks it, the message names the blocking effect id, kind, source, page and request id. | Stop the writers named in the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook), inspect the named work with `gbrain sources writer status <source> --json`, let it finish, then retry. A committed write whose embedding effect is stuck queued or failed is settled by `gbrain repair embedding-effects --source <source>` (preview), then the same command with `--apply`; see [stale queued embedding effects](repair.md#stale-queued-embedding-effects). |
| <a id="activation_source_path_missing"></a>`source_path_missing` | `source_changed` | `gbrain sources writer activate` (with or without `--dry-run`) found a source whose recorded `local_path` no longer exists on this host, for example a checkout that lived in a temporary directory. Activation cannot verify that source's canonical directory, so nothing changed. The message names the source and the missing path. Claiming the source at another directory does not help while the stale path stays recorded. | Run the command the suggestion prints: `gbrain sources set-path <source> <directory>` to point the source at its checkout (the suggestion fills in the claimed directory when the source is claimed), or `gbrain sources remove <source> --confirm-destructive` when the source is no longer needed (`gbrain sources archive <source>` keeps a 72-hour grace period). Then `gbrain sources writer activate --confirm-quiesced --dry-run` and activate. |
-| <a id="source_checkout_missing"></a>canonical checkout missing | `recovery_required` | A page write (`put_page`, `capture`, `add_timeline_entry`, `edit_page` and the other page writers; `detail: source_checkout_missing`) found that the source's canonical checkout directory does not exist on this host, for example a brain copied to another machine or container without its source directories; nothing was written, and the message names the source but not the path. A source directory missing inside a checkout that exists (Git keeps no empty directory, so a fresh clone lacks an empty member folder) is not this refusal: the write creates it. A managed source lifecycle command (`gbrain sources archive`, `remove`, `purge`, `restore`, `rebind`) found that the source's canonical checkout directory was deleted out of band. A source with **no pages** that is the **only** source on that checkout is retired anyway: archive, remove and purge succeed and the receipt records `retired_without_checkout` with the missing path. Otherwise nothing changed; the message names the path, the page count and how many other sources share the checkout. Recreating an empty directory at the same path does not help (its physical identity differs). | Restore the checkout (for example from a backup) and retry; `gbrain sources writer status --source <source> --json` shows the registered path. If it is gone for good, switch the brain to classic mode with `gbrain sources writer deactivate --dry-run`, then the printed `apply_command` (see the [deactivate runbook](../architecture/topologies.md#deactivate-runbook)), and retire the source there with `gbrain sources archive <source>`. |
+| <a id="source_checkout_missing"></a>canonical checkout missing | `recovery_required` | A page write (`put_page`, `capture`, `add_timeline_entry`, `edit_page` and the other page writers; `detail: source_checkout_missing`) found that the source's canonical checkout directory does not exist on this host, for example a brain copied to another machine or container without its source directories; nothing was written, and the message names the source but not the path. A source directory missing inside a checkout that exists (Git keeps no empty directory, so a fresh clone lacks an empty member folder) is not this refusal: the write creates it. A managed source lifecycle command (`gbrain sources archive`, `remove`, `purge`, `restore`, `rebind`) found that the source's canonical checkout directory was deleted out of band. When the directory a `rebind` names holds that checkout's ownership stamp (it was moved, not deleted), the refusal is [`physical_root_moved`](#moved-root) instead, and `gbrain sources set-path --dry-run` refuses the same way as the real run. A source with **no pages** that is the **only** source on that checkout is retired anyway: archive, remove and purge succeed and the receipt records `retired_without_checkout` with the missing path. Otherwise nothing changed; the message names the path, the page count and how many other sources share the checkout. Recreating an empty directory at the same path does not help (its physical identity differs). | Restore the checkout (for example from a backup) and retry; `gbrain sources writer status --source <source> --json` shows the registered path. If it is gone for good, switch the brain to classic mode with `gbrain sources writer deactivate --dry-run`, then the printed `apply_command` (see the [deactivate runbook](../architecture/topologies.md#deactivate-runbook)), and retire the source there with `gbrain sources archive <source>`. |
| <a id="migrations_running"></a>`migrations_running` | `migrations_running` (exit 75) | `gbrain apply-migrations` (or the post-upgrade step of `gbrain upgrade`) found another runner holding the brain's orchestration lock and stopped before touching the migration ledger, so migrations never run twice in parallel. The message names the holder's host and pid. A holder that died is taken over automatically on the next run. `gbrain upgrade` reports this as `Migrations: running`, not as a failed upgrade. | Wait for the other run to finish; `gbrain doctor` shows migration progress. Then `gbrain apply-migrations --yes` confirms everything is applied. |
| <a id="schema_behind"></a>`schema_behind` | `migrations_pending` (reason `schema_behind`) | A managed write (`put_page` and every write admitted the same way) was refused before admission because the brain schema is at a lower version than this gbrain build needs: an upgrade installed the new binary but `gbrain apply-migrations` did not finish, often because the database role gbrain connects as does not own the tables. The write path reads tables or columns only the pending migrations add, so publishing now would fail. It is not retryable as is (class `caller`): the same write refuses until the schema is migrated. Nothing was admitted and the request id was not used. A replay of a request id accepted earlier still reconciles, and the `apply-migrations` orchestrators are not refused while they hold the migration lock. | Run `gbrain apply-migrations --yes` on the brain host as the database role that owns the gbrain tables (the fix renders `tell_user_to_run` when this connection's role does not own them), confirm with `gbrain doctor --json` (`schema_version` at head), then resubmit the same write: the same request id commits. A write that already failed on a missing column or table is classified `schema_missing` by `gbrain write-request <request_id> --json`. |
| <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 91c4fa72d0..008bc5ea48 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
-src/core/behavior-change-notice.ts 1687 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row
+src/core/behavior-change-notice.ts 1688 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 #8625: physical_root_moved_8625 row (since TBD until the merge slot; rows are data and cannot move)
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 2e82668a4c..aa2306b538 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1489,6 +1489,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.618.0', id: 'refresh_replan_own_commits_8828', text: 'A `gbrain sources refresh` whose checkout HEAD moved while it waited for writes admitted before its fence no longer refuses `refresh_source_changed` when every commit since its start is one of gbrain\'s own (in the commit ledger) and the upstream branch holds them: it takes HEAD as its start and fast-forwards to the upstream. A HEAD move that includes a commit gbrain did not make, or gbrain\'s commits the upstream does not hold yet, still refuses as before.' },
{ since: '0.60.619.0', id: 'managed_commit_push_unpublished_gst1923', text: 'On a managed checkout, `gbrain git commit-push -m <msg> -- <paths>` now reports how many commits the upstream lacks as last fetched (`unpublished` in `--json`, `null` when there is no upstream) and says nothing was pushed, instead of answering `nothing to commit; <remote>/<branch> at -` and logging `[push] ok-already-on-remote` for a commit that already existed. It writes no push-log line on a managed checkout. It still never pushes there; `gbrain git commit-push --push-only --keep-checkout --path <checkout>` publishes.' },
{ since: '0.60.620.0', id: 'refresh_publish_diverged_default_gbra386', text: 'A diverged managed checkout now publishes its local commits on `gbrain sources refresh` by default when the worktree\'s Git durability is on: `sources.refresh_publish_diverged` unset now means on there (it used to mean off), merged with the upstream in memory, never rebased or forced. The refresh publish first scans what the local commits add (messages, added lines, merge resolutions) and refuses the new `publish_secret_found` naming the file, line and rule, never the value, when one looks like a secret; `gbrain git commit-push --push-only --scan-secrets` runs the same gate. Unset with durability not on still refuses, naming `gbrain sources writer git-durability <source> --enable`; `false` turns it off.' },
+ { since: 'TBD', id: 'physical_root_moved_8625', text: 'On a managed brain, a checkout moved to a new path (or whose parent folder was renamed) is now named: `gbrain sources add`, `gbrain sources set-path` and `gbrain sources writer claim` refuse with `recovery_required`, detail `physical_root_moved`, naming the recorded path, the worktree and the commands that bring it back, instead of a generic identity error (add, claim) or detail-less `source_checkout_missing` (set-path). Their `--dry-run` now refuses as the real run does: before, the add, claim and set-path dry runs of a moved checkout, the add and claim dry runs of a folder holding a copied ownership stamp, and the set-path dry run of a missing checkout exited 0. Nothing about ownership changed; the dry runs still write nothing.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index af6d21fed8..471fdf3692 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -657,7 +657,7 @@ export const CODES = {
fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--detail', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-reads the convergence shadow; writes nothing.' } },
recovery_prior_stage_unavailable: { class: 'consent', actor: 'user', summary: "gbrain repair stuck-recovery cannot apply that --keep choice to a page recovery over the single-string ceiling, because the staged copy of its prior file is missing, does not match its recorded SHA-256, or is not a regular file; nothing was changed.", why: "A prior file over 24 MiB is not embedded in its recovery record: the record names a staged copy beside the file by path and SHA-256, and only that copy can put the prior bytes back. Without it --keep prior has nothing safe to restore, so the remaining exit is --keep disk, which the user must agree to.", docs: 'docs/guides/repair.md#recovery-prior-stage-unavailable' },
recovery_version_unsupported: { class: 'host_only', actor: 'host_admin', summary: "A newer gbrain wrote this recovery record (its version is unknown here), so this gbrain left the record, its staged files and the canonical file untouched; writes on that worktree wait for it.", why: "A recovery record says how to finish an interrupted publication; reading a newer layout as an older one can publish wrong bytes, delete a staged file or clear the record. Only a gbrain that knows the version may recover it, so the fix is upgrading gbrain on the canonical owner host and restarting its writer processes.", docs: 'docs/guides/write-refusals.md#recovery_version_unsupported' },
- recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes.", why: "Details name the exit when there is one: physical_root_device_changed (the checkout's filesystem device number changed; re-stamped by itself when ownership verifies) and physical_root_directory_changed (the directory at the recorded path was recreated, or its birth time drifted beyond 1 µs; the relocated-root self-transfer, `transfer prepare/accept <source> --self-transfer --confirm-relocated-root`, re-stamps it). Both are explained in docs/guides/write-refusals.md." },
+ recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes.", why: "Details name the exit when there is one: physical_root_device_changed (the checkout's filesystem device number changed; re-stamped by itself when ownership verifies) and physical_root_directory_changed (the directory at the recorded path was recreated, or its birth time drifted beyond 1 µs; the relocated-root self-transfer, `transfer prepare/accept <source> --self-transfer --confirm-relocated-root`, re-stamps it) and physical_root_moved (the checkout was moved to a new path or its parent folder renamed; `sources add`, `set-path` and `writer claim`, dry runs included, name the recorded path and the symlink-then-set-path or move-back exit, and a remote caller sees no path). All three are explained in docs/guides/write-refusals.md." },
redirect_uri_mismatch: { class: 'caller', summary: "Google connect credential error: redirect uri mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },
ref_not_in_answer: { class: 'caller', summary: "The rated page is not one of the pages the answer used.", docs: 'docs/guides/retrieval-feedback.md#ref_not_in_answer' },
refresh_dirty: { class: 'caller', summary: "The worktree has uncommitted changes." },
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index 5c219fad52..dacf896a25 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -1,5 +1,7 @@
/** Trusted local administration, shared by direct CLI and its authenticated resident proxy. */
import { isAbsolute, join } from 'node:path';
+import { claimedWorktreeRoot, inspectClaimedPhysicalRoot } from './topology-locks.ts';
+import { movedPhysicalRootRefusal } from './physical-root.ts';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { UNSUPPORTED_MANAGED_BULK_WRITERS } from './maintenance.ts';
@@ -327,9 +329,18 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
const sourceId = source(params.source_id), root = path(params.path);
// #5198: say at claim time what the claim retires, before and after the fact.
const notice = await readManagedMode(engine) ? {} : { activation_required: CLAIM_BEFORE_ACTIVATION_NOTICE };
- if (params.dry_run) return { dry_run: true, action: operation, source_id: sourceId, path: root, current: await getWorktreeBinding(engine, sourceId, existingHostIdFor(engine)), ...notice };
+ // #8625: a moved checkout at the root the claim reserves is named with its exit.
+ const worktree = claimedWorktreeRoot(root);
+ if (params.dry_run) {
+ if (worktree) await inspectClaimedPhysicalRoot(engine, sourceId, worktree, 'claim', existingHostIdFor(engine));
+ return { dry_run: true, action: operation, source_id: sourceId, path: root, current: await getWorktreeBinding(engine, sourceId, existingHostIdFor(engine)), ...notice };
+ }
const expectedState = await requireWriterAdminIntent(engine, operation, params);
- return { claimed: true, binding: await claimWorktree(engine, sourceId, root, undefined, expectedState), ...notice };
+ try { return { claimed: true, binding: await claimWorktree(engine, sourceId, root, undefined, expectedState), ...notice }; }
+ catch (error) {
+ if (!(error instanceof OperationError) || error.detail !== 'physical_root_moved' || !worktree) throw error;
+ throw await movedPhysicalRootRefusal(engine, worktree, { sourceId, operation: 'claim' }, existingHostIdFor(engine)) ?? error;
+ }
}
if (operation === 'writer_activate') {
keys(params, ['confirm_quiesced', 'dry_run', 'shared_skills', 'admin_intent', 'expected_state', 'cleanup_dead_local_locks']);
diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.ts
index 2fa65a99d7..6f27f08531 100644
--- a/src/core/persistence/physical-root-record.ts
+++ b/src/core/persistence/physical-root-record.ts
@@ -9,6 +9,7 @@ import { digest, sha256 } from './digest.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { OWNERSHIP_MARKER_GLOBS, PHYSICAL_ROOT_MARKER } from './root-metadata.ts';
import { ownerMarkerMissingError } from './owner-marker.ts';
+import type { Action } from '../agent-output.ts';
export { OWNERSHIP_MARKER_GLOBS, PHYSICAL_ROOT_MARKER, isPhysicalRootMetadata } from './root-metadata.ts';
const RESERVATION_PREFIX = '.gbrain-owner-';
@@ -115,8 +116,9 @@ export function coordinationPathInsideRoot(root: string, path: string): boolean
const rel = relative(root, path);
return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
}
-function readReservationRecord(root: string, allowInsideLock = false): PhysicalRootReservation | null {
- const value = readPrivate(physicalRootReservationPath(root)) as PhysicalRootReservation | null;
+/** `directory`: where to look for the reservation named for `root`; beside `root` unless a renamed parent carried it (#8625). */
+function readReservationRecord(root: string, allowInsideLock = false, directory = dirname(root)): PhysicalRootReservation | null {
+ const value = readPrivate(join(directory, `${RESERVATION_PREFIX}${sha256(root)}.json`)) as PhysicalRootReservation | null;
if (value === null) return null;
if (value.version !== 1 || ![value.token,value.brainId,value.worktreeId,value.hostId].every(uuid)
|| value.root !== root || typeof value.coordinationPath !== 'string' || !isAbsolute(value.coordinationPath) || value.coordinationPath.includes('\0')
@@ -239,6 +241,108 @@ export function samePhysicalBirth(stored: string | null | undefined, live: bigin
if (value === 0n || live === 0n) return false;
return (value > live ? value - live : live - value) <= PHYSICAL_BIRTH_TOLERANCE_NS;
}
+/** #8625: a checkout found at `root` whose stamp records a root that no longer exists, and the move that explains it. Refusal evidence, never ownership authority. */
+export interface MovedPhysicalRoot {
+ recorded: string; root: string; brainId: string; worktreeId: string;
+ /** The folder that moved: the checkout itself, or the renamed parent that carried it (`ancestor`). */
+ from: string; to: string; ancestor: boolean;
+ /** The live directory is the stamped one (device, inode and birth time), so moving it back reattaches the worktree. */
+ sameDirectory: boolean;
+}
+/**
+ * #8625: reads only the stamp in `root` and the reservation of the root it records: beside that old root when the checkout
+ * itself moved, or beside `root` (still named for the old root) when a parent folder was renamed and carried both along.
+ * A recorded root that still exists (a copy), a stamp and reservation that disagree on token, brain or worktree, or a
+ * parent rename that also renamed the checkout is no move (null). An ownership record other users can read keeps its own refusal.
+ */
+export function describeMovedPhysicalRoot(root: string): MovedPhysicalRoot | null {
+ try {
+ const stamp = readPhysicalRootStamp(root);
+ if (!stamp || stamp.root === root || existsSync(stamp.root)) return null;
+ let reservation = readReservationRecord(stamp.root), from = stamp.root, to = root;
+ if (!reservation) {
+ const recorded = stamp.root.split(sep), current = root.split(sep);
+ let shared = 0;
+ while (shared < Math.min(recorded.length, current.length) - 2 && recorded[recorded.length - 1 - shared] === current[current.length - 1 - shared]) shared++;
+ if (!shared) return null;
+ reservation = readReservationRecord(stamp.root, false, dirname(root));
+ from = recorded.slice(0, -shared).join(sep); to = current.slice(0, -shared).join(sep);
+ }
+ if (!reservation || reservation.token !== stamp.token || reservation.brainId !== stamp.brainId || reservation.worktreeId !== stamp.worktreeId) return null;
+ const info = statSync(root, { bigint: true });
+ return { recorded: stamp.root, root, brainId: stamp.brainId, worktreeId: stamp.worktreeId, from, to, ancestor: from !== stamp.root,
+ sameDirectory: stamp.device === info.dev.toString() && stamp.inode === info.ino.toString() && samePhysicalBirth(stamp.birth, info.birthtimeNs) };
+ } catch (error) {
+ if (error instanceof OperationError && error.detail === 'ownership_record_not_private') throw error;
+ return null;
+ }
+}
+export const PHYSICAL_ROOT_MOVED_MESSAGE = 'This folder holds the ownership stamp of a canonical checkout that was moved here from the path it is recorded at.';
+/** #8625: the path-free refusal of `reservePhysicalRoot`, which remote page writes reach through the automatic claim. */
+export function physicalRootMovedError(): OperationError {
+ const error = physicalRootError(PHYSICAL_ROOT_MOVED_MESSAGE);
+ error.detail = 'physical_root_moved';
+ error.suggestion = 'Nothing changed. On the brain host, run the same gbrain sources add, set-path or writer claim with --dry-run in a terminal: it names the recorded path and the commands that bring the checkout back. Moving folders is the user\'s decision. Never remove the ownership markers.';
+ error.docs = 'docs/guides/write-refusals.md#moved-root';
+ return error;
+}
+const shellQuote = (path: string) => `'${path.replaceAll("'", "'\\''")}'`;
+/**
+ * #8625: the local CLI refusal for a moved checkout, with the exit built from existing verbs. A worktree that still has
+ * sources: a symlink at the old path, `set-path` for each source (the #5914 relocation), then the symlink removed. One
+ * whose source was removed: move it back and re-add (or claim) at the recorded path, which reattaches the worktree. A
+ * folder that is not the stamped directory any more cannot be reattached by moving it, so the exit is restore or deactivate.
+ */
+export function physicalRootMovedRefusal(moved: MovedPhysicalRoot, exit: { sourceId: string; operation: 'add' | 'claim' | 'rebind'; members: Array<{ sourceId: string; relativePath: string }> }): OperationError {
+ const { recorded, root, from, to, worktreeId } = moved, q = shellQuote;
+ const where = `The checkout at ${q(root)} is worktree ${worktreeId}, recorded at ${q(recorded)}${moved.ancestor ? `; its folder ${q(from)} was moved to ${q(to)}` : ''}.`;
+ const user = (why: string, argv: string[], user_message: string, extra: Partial<Action> = {}): Action =>
+ ({ ask_user: true, argv, consent: [], actor: 'user', requires_exclusive: false, why, user_message, docs: 'docs/guides/write-refusals.md#moved-root', ...extra });
+ const error = physicalRootError(where);
+ error.detail = 'physical_root_moved';
+ error.docs = 'docs/guides/write-refusals.md#moved-root';
+ if (exit.members.length) {
+ const steps = exit.members.map(member => ['gbrain', 'sources', 'set-path', member.sourceId, member.relativePath ? join(root, member.relativePath) : root]);
+ error.message = `${where} It holds source${steps.length > 1 ? 's' : ''} ${exit.members.map(member => member.sourceId).join(', ')}.`;
+ // The first set-path moves the worktree; each further source of it is pointed at the new path once the symlink is gone.
+ const [first, ...rest] = steps, setPathText = (step: string[]) => `gbrain sources set-path ${step[3]} ${q(step[4])}`;
+ error.suggestion = `Nothing changed. Ask the user before touching their folders. Then leave a symlink at the old path with ln -s ${q(to)} ${q(from)}, run ${setPathText(first)} `
+ + `(it keeps worktree ${worktreeId} and its history and moves the ownership records to the new path), then remove the symlink with rm ${q(from)}`
+ + `${rest.length ? `, then run ${rest.map(setPathText).join(', then ')}` : ''}. Never remove the ownership markers.`;
+ const pointAt = (step: string[], then?: Action) => user(`Moves source ${step[3]}'s canonical path to the checkout's new place, keeping its worktree and history.`, step,
+ `May I update source ${step[3]} to point at ${step[4]}?`, then ? { then } : {});
+ let after: Action | undefined;
+ for (const step of [...rest].reverse()) after = pointAt(step, after);
+ const then = pointAt(first, user('Removes the symlink left at the old path; the checkout stays where it is now.', ['rm', from], 'The symlink at the old path is no longer needed. May I remove it?',
+ after ? { then: after } : {}));
+ error.fix = user(`Leaves a symlink at the old path so gbrain can verify the moved checkout is the same worktree before it moves its records.`, ['ln', '-s', to, from],
+ `Your brain folder moved from ${from} to ${to}. I can leave a symlink at the old path, update gbrain's record of it, then remove the symlink; your files and Git history stay as they are. Shall I go ahead?`,
+ { then, verify: { argv: [...steps[0], '--dry-run'] } });
+ return error;
+ }
+ const label = exit.operation === 'claim' ? 'gbrain sources writer claim' : 'gbrain sources add';
+ if (!moved.sameDirectory) {
+ error.message = `${where} It has no source since its source was removed, and this folder is a copy, not the stamped directory (its device, inode or birth time differs).`;
+ error.suggestion = `Nothing changed. Moving this copy back to ${q(recorded)} would not reattach worktree ${worktreeId}. Restore the original folder at ${q(recorded)} from a backup, then rerun ${label} ${exit.sourceId} --path ${q(recorded)}; `
+ + 'or, if it is gone for good, switch the brain to classic mode with gbrain sources writer deactivate --dry-run (then the printed apply_command) and add the folder there. Never remove the ownership markers.';
+ error.fix = user('Read-only preview of switching the brain to classic mode, where the copied folder can be added without the old ownership records.',
+ ['gbrain', 'sources', 'writer', 'deactivate', '--dry-run'],
+ `Your brain folder was copied to ${root} and the original at ${recorded} is gone. gbrain cannot reattach a copy. Do you want to restore the original from a backup, or switch the brain to classic mode?`);
+ return error;
+ }
+ const command = exit.operation === 'claim' ? ['gbrain', 'sources', 'writer', 'claim', exit.sourceId, '--path', recorded]
+ : ['gbrain', 'sources', 'add', exit.sourceId, '--path', recorded, ...(existsSync(join(root, '.git')) ? [] : ['--force'])];
+ const readd = exit.operation === 'claim' ? [...command, '--admin-intent', 'writer_claim', '--expected-state', '<admin_state>'] : command;
+ error.message = `${where} It has no source since its source was removed; the worktree and its history are kept.`;
+ error.suggestion = `Nothing changed. Ask the user before touching their folders. Then move it back with mv ${q(to)} ${q(from)} and run ${label} ${exit.sourceId} --path ${q(recorded)}${exit.operation === 'claim' ? ' (with the admin intent writer status prints)' : ''}, `
+ + `which reattaches worktree ${worktreeId} and its history. To keep the folder at its new place afterwards, move it again and run gbrain sources set-path ${exit.sourceId} --dry-run: it names the symlink steps. Never remove the ownership markers.`;
+ error.fix = user('Moves the folder back to where gbrain recorded it, so the worktree and its history can be reattached.', ['mv', to, from],
+ `Your brain folder moved from ${from} to ${to}, and gbrain only recognizes it at the old path. May I move it back and re-add it there? You can move it again afterwards with gbrain's help.`,
+ { verify: { argv: [...command, '--dry-run'] },
+ then: user(`Re-registers source ${exit.sourceId} at the recorded path, which reattaches worktree ${worktreeId}.`, readd, `May I register source ${exit.sourceId} at ${recorded}?`,
+ exit.operation === 'claim' ? { inputs: [{ name: 'admin_state', how: 'admin_state from gbrain sources writer status --json on the brain host' }] } : {}) });
+ return error;
+}
/** The #5914 exit for a directory recreated at its recorded path; filled with the source and root by lockWorktree (ownership.ts). */
export function physicalRootDirectoryChangedError(): OperationError {
const error = physicalRootError('The checkout directory at the recorded root is not the one this owner stamped (its inode or birth time changed) while the owner token, brain, worktree, root and device still match. '
diff --git a/src/core/persistence/physical-root.ts b/src/core/persistence/physical-root.ts
index 4c56bdcb1c..c1a4477fc9 100644
--- a/src/core/persistence/physical-root.ts
+++ b/src/core/persistence/physical-root.ts
@@ -5,8 +5,10 @@ import type { BrainEngine } from '../engine.ts';
import type { SqlEngine } from './model.ts';
import { repairWedgedReservation, resolveCoordinationLock } from './coordination-lock.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
-import { adoptTransferredRootStamp, assertNoPhysicalRootOverlap, assertPhysicalRoot, assertPhysicalRootStamp, PHYSICAL_ROOT_MARKER, physicalRootDeviceChange, physicalRootError,
- readPhysicalRootReservation, readPhysicalRootStamp, reservePhysicalRootRecord, restampPhysicalRootDevice, samePhysicalBirth, writePhysicalRootStamp, type PhysicalRootReservation } from './physical-root-record.ts';
+import type { OperationError } from '../ops/contract.ts';
+import { adoptTransferredRootStamp, assertNoPhysicalRootOverlap, assertPhysicalRoot, assertPhysicalRootStamp, describeMovedPhysicalRoot, PHYSICAL_ROOT_MARKER, physicalRootDeviceChange, physicalRootError,
+ physicalRootMovedError, physicalRootMovedRefusal, readPhysicalRootReservation, readPhysicalRootStamp, reservePhysicalRootRecord, restampPhysicalRootDevice, samePhysicalBirth, writePhysicalRootStamp,
+ type MovedPhysicalRoot, type PhysicalRootReservation } from './physical-root-record.ts';
export { assertPhysicalRoot, isPhysicalRootMetadata, readPhysicalRootReservation } from './physical-root-record.ts';
export interface PhysicalRootClaim { hostId: string; worktreeId?: string; coordinationPath?: string; }
@@ -26,8 +28,8 @@ export async function reservePhysicalRoot(tx: SqlEngine, path: string, opts: Phy
const previous = readPhysicalRootReservation(root);
const worktreeId = opts.worktreeId ?? previous?.worktreeId ?? randomUUID();
const coordinationPath = opts.coordinationPath ?? resolveCoordinationLock(root, worktreeId, { reservation: previous?.coordinationPath }, opts.hostId).path;
- // A copied marker without its original sibling reservation is not a new root.
- if (!previous && existsSync(join(root, PHYSICAL_ROOT_MARKER))) throw physicalRootError();
+ // A copied marker without its original sibling reservation is not a new root; a moved checkout is named, path-free (#8625).
+ if (!previous && existsSync(join(root, PHYSICAL_ROOT_MARKER))) throw await movedPhysicalRoot(tx, root, opts.hostId) ? physicalRootMovedError() : physicalRootError();
const reservation = previous ?? reservePhysicalRootRecord(root, { brainId, worktreeId, hostId: opts.hostId, coordinationPath });
if (reservation.brainId !== brainId || reservation.worktreeId !== worktreeId || reservation.coordinationPath !== coordinationPath) throw physicalRootError();
const [owner] = await tx.executeRaw<{ owner_host_id: string | null }>('SELECT owner_host_id FROM persistence_worktrees WHERE id=$1::uuid', [worktreeId]);
@@ -35,6 +37,30 @@ export async function reservePhysicalRoot(tx: SqlEngine, path: string, opts: Phy
assertNoPhysicalRootOverlap(root);
return reservation;
}
+/**
+ * #8625: the file evidence of a moved checkout at `path`, accepted only when this brain recorded it: the stamp's brain,
+ * its worktree owned by `hostId`, and that worktree's host binding still at the recorded root. Read-only.
+ */
+export async function movedPhysicalRoot(tx: SqlEngine, path: string, hostId: string | null):
+ Promise<(MovedPhysicalRoot & { members: Array<{ sourceId: string; relativePath: string }> }) | null> {
+ const moved = describeMovedPhysicalRoot(canonicalFilesystemPath(path));
+ if (!moved || !hostId) return null;
+ const [row] = await tx.executeRaw<{ brain_id: string; owner_host_id: string | null; local_path: string | null }>(`SELECT brain_id::text AS brain_id,
+ (SELECT owner_host_id::text FROM persistence_worktrees WHERE id=$1::uuid) AS owner_host_id,
+ (SELECT local_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid) AS local_path
+ FROM persistence_brain WHERE singleton=1`, [moved.worktreeId, hostId]);
+ if (row?.brain_id !== moved.brainId || row.owner_host_id !== hostId || row.local_path !== moved.recorded) return null;
+ const members = await tx.executeRaw<{ source_id: string; relative_path: string }>(
+ 'SELECT source_id,relative_path FROM persistence_source_bindings WHERE worktree_id=$1::uuid ORDER BY source_id', [moved.worktreeId]);
+ return { ...moved, members: members.map(member => ({ sourceId: member.source_id, relativePath: member.relative_path })) };
+}
+/** #8625: the full moved-checkout refusal for a trusted local caller (paths, worktree, exit); null when `root` is no moved checkout of this host, or not of `recorded`. */
+export async function movedPhysicalRootRefusal(tx: SqlEngine, root: string, exit: { sourceId: string; operation: 'add' | 'claim' | 'rebind' }, hostId: string | null,
+ recorded?: string): Promise<OperationError | null> {
+ const moved = await movedPhysicalRoot(tx, root, hostId);
+ if (!moved || recorded !== undefined && moved.recorded !== recorded) return null;
+ return physicalRootMovedRefusal(moved, { ...exit, members: moved.members });
+}
/** Existing bindings require their stamp; only a never-committed original claim may finish creating it. */
export async function claimPhysicalRoot(tx: SqlEngine, path: string, opts: PhysicalRootClaim): Promise<PhysicalRootReservation> {
const reservation = await reservePhysicalRoot(tx, path, opts);
diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.ts
index e8ccb10596..0e42e264d1 100644
--- a/src/core/persistence/source-lifecycle.ts
+++ b/src/core/persistence/source-lifecycle.ts
@@ -24,7 +24,7 @@ import { principalAttribution } from './attribution.ts';
import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';
import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.ts';
import { flushTopologyDirectory } from './topology-filesystem.ts';
-import { claimPhysicalRoot } from './physical-root.ts';
+import { claimPhysicalRoot, movedPhysicalRootRefusal } 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';
@@ -158,7 +158,15 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
const retire=['archive','remove','purge'].includes(input.operation);
const manifestRequired=!retire||(await engine.executeRaw<{digest:string|null}>(
`SELECT w.manifest->>'digest' AS digest FROM persistence_source_bindings b JOIN persistence_worktrees w ON w.id=b.worktree_id WHERE b.source_id=$1`,[input.sourceId])).some(row=>!row.digest);
- if(input.dryRun) await inspectTopologyPhysicalRoot(engine,input.sourceId,root?.worktree,{relocation:input.operation==='rebind'});
+ // #8625: the operation a moved checkout's exit names; restore, archive and the others pass no path.
+ const exit={sourceId:input.sourceId,operation:input.operation as 'add'|'claim'|'rebind'};
+ if(input.dryRun&&input.operation==='rebind'&&root){
+ // #8625: the real rebind hashes the recorded checkout first, so a missing one refuses before anything else.
+ const own=await getWorktreeBinding(engine,input.sourceId);
+ if(own?.local_path&&own.owner_host_id===hostIdFor(engine)&&own.coordination_path&&!existsSync(own.local_path))
+ throw await movedPhysicalRootRefusal(engine,root.worktree,exit,hostIdFor(engine),own.local_path)??missingCheckoutError(input.sourceId,own.local_path);
+ }
+ if(input.dryRun) await inspectTopologyPhysicalRoot(engine,input.sourceId,root?.worktree,{relocation:input.operation==='rebind',operation:input.operation});
if(input.dryRun) return {dry_run:true,operation:input.operation,source_id:input.sourceId,source_incarnation:before?.incarnation??null,path:root?.source??before?.local_path??null,manifest_required:manifestRequired};
return withTopologyLocks(engine,input.sourceId,async bindings=>{
// Hash canonical bytes while holding native exclusion, without a database
@@ -170,7 +178,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
if(input.operation==='add'&&input.createDirectory&&path===root?.worktree)continue;
// #5219: retiring may skip a vanished checkout; the transaction proves the source is empty and its sole member.
if(retire&&!root){missingCheckout=path;continue;}
- throw missingCheckoutError(input.sourceId,path);
+ throw (root&&await movedPhysicalRootRefusal(engine,root.worktree,exit,hostIdFor(engine),path))||missingCheckoutError(input.sourceId,path);
}
if(!manifestRequired)continue;
const manifest=worktreeManifest(path,{progress:humanManifestProgress()});
@@ -301,7 +309,13 @@ 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,5000,{relocation:input.operation==='rebind'});
+ },root?.worktree,5000,{relocation:input.operation==='rebind'}).catch(async(error:unknown)=>{
+ // #8625: the claim's own refusal is path-free; a trusted local lifecycle names the move and its exit. The automatic
+ // first-write claim keeps it path-free, since a remote page write can reach it.
+ if(error instanceof OperationError&&error.detail==='physical_root_moved'&&root&&!input.automaticClaim)
+ throw await movedPhysicalRootRefusal(engine,root.worktree,exit,hostIdFor(engine))??error;
+ throw error;
+ });
}
/** #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 f8c61799dc..81ce48b2be 100644
--- a/src/core/persistence/topology-locks.ts
+++ b/src/core/persistence/topology-locks.ts
@@ -1,7 +1,7 @@
import { join } from 'node:path';
import { existsSync, realpathSync } from 'node:fs';
-import { assertPhysicalRoot } from './physical-root.ts';
-import { inspectRelocatedPhysicalRoot } from './physical-root-record.ts';
+import { assertPhysicalRoot, movedPhysicalRootRefusal } from './physical-root.ts';
+import { inspectRelocatedPhysicalRoot, PHYSICAL_ROOT_MARKER, physicalRootError, readPhysicalRootReservation } 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';
@@ -12,6 +12,7 @@ import { containsPath, getWorktreeBinding, type WorktreeBinding } from './owners
import { completeWrite, lockCounters } from './journal.ts';
import { principalKey, requestPrincipal, type WriteRequest } from './model.ts';
import { catalogueError } from '../error-catalogue.ts';
+import { discoverGitRoot } from '../sync-git.ts';
import { ACTIVE_REFRESH_STATES_SQL } from './worktree-refresh-schema.ts';
export type TopologyBinding=WorktreeBinding & { unbound?:boolean };
@@ -85,12 +86,33 @@ function assertBindingPhysicalRoot(item: TopologyBinding, sourceId: string, addi
/**
* #6849: a lifecycle dry run predicts the physical-root refusal the real run hits in withTopologyLocks for the
- * source's own binding on this host. Read-only: it takes no lock and writes no stamp, reservation or row.
+ * source's own binding on this host, and (#8625) for an add or claim the refusal `reservePhysicalRoot` raises at the
+ * new root. Read-only: it takes no lock and writes no stamp, reservation or row.
*/
-export async function inspectTopologyPhysicalRoot(engine: BrainEngine, sourceId: string, additionalRoot?: string, opts: { relocation?: boolean } = {}): Promise<void> {
+export async function inspectTopologyPhysicalRoot(engine: BrainEngine, sourceId: string, additionalRoot?: string,
+ opts: { relocation?: boolean; operation?: string } = {}): Promise<void> {
const binding = await getWorktreeBinding(engine, sourceId);
- if (!binding || binding.owner_host_id !== hostIdFor(engine) || !binding.coordination_path) return;
- assertBindingPhysicalRoot(binding, sourceId, additionalRoot, opts);
+ if (binding && binding.owner_host_id === hostIdFor(engine) && binding.coordination_path) assertBindingPhysicalRoot(binding, sourceId, additionalRoot, opts);
+ if (additionalRoot && (opts.operation === 'add' || opts.operation === 'claim')) await inspectClaimedPhysicalRoot(engine, sourceId, additionalRoot, opts.operation, hostIdFor(engine));
+}
+
+/** #8625: the checkout root a claim of `path` reserves (its Git top, as claimWorktree resolves it), or null for a missing path. */
+export function claimedWorktreeRoot(path: string): string | null {
+ let root: string;
+ try { root = realpathSync(path); } catch { return null; }
+ try { return realpathSync(discoverGitRoot(root)); } catch { return root; }
+}
+
+/**
+ * #8625: a stamp with no reservation beside it refuses the claim of `root` as a copied marker, named
+ * `physical_root_moved` when it is a checkout of this host that moved. The claim reserves `root` itself only when no
+ * local binding encloses it (otherwise it reuses that worktree's root), so only then does this predict the refusal.
+ */
+export async function inspectClaimedPhysicalRoot(engine: BrainEngine, sourceId: string, root: string, operation: 'add' | 'claim', hostId: string | null): Promise<void> {
+ if (!existsSync(join(root, PHYSICAL_ROOT_MARKER)) || readPhysicalRootReservation(root)) return;
+ const local = hostId ? await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM persistence_host_bindings WHERE host_id=$1::uuid', [hostId]) : [];
+ if (local.some(row => row.local_path && containsPath(row.local_path, root))) return;
+ throw await movedPhysicalRootRefusal(engine, root, { sourceId, operation }, hostId) ?? physicalRootError();
}
/**
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 16a6ba7782..00d00953af 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -11,7 +11,7 @@ import { PAGE_CHANGED_AFTER_READ_MESSAGE } from '../page-state/types.ts';
import { readFix } from '../ops/op-fix.ts';
import { ERROR_CATALOGUE } from '../error-catalogue.ts';
import { SOURCE_CHECKOUT_MISSING, type CheckoutRefusalOrigin } from './publication-failure.ts';
-import { ownershipRecordNotPrivateError, physicalRootDirectoryChangedError } from './physical-root-record.ts';
+import { ownershipRecordNotPrivateError, physicalRootDirectoryChangedError, PHYSICAL_ROOT_MOVED_MESSAGE } from './physical-root-record.ts';
/** GST-465: a page write to a source whose canonical checkout is missing on this host. The path is left to the read-only fix, which a remote caller cannot run. */
export function sourceCheckoutMissingRefusal(sourceId: string, slug: string | null): OperationError {
@@ -168,6 +168,9 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {
// #6501: a checkout recreated (or drifted beyond the birth tolerance) at its recorded path; the #5914 relocated-root self-transfer is the exit.
if (code === 'recovery_required' && message?.startsWith('The checkout directory at the recorded root is not the one this owner stamped')) return { reason: 'physical_root_directory_changed', message,
suggestion: 'On the brain host, gbrain sources writer status <source> --json shows the filled commands: gbrain sources writer transfer prepare <source> --self-transfer --confirm-relocated-root, then transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --confirm-relocated-root (each with its admin intent). Retry the original write with the same request_id afterwards; never remove the ownership markers.' };
+ // #8625: the source's folder holds the stamp of a checkout moved from its recorded path; the path-free refusal of the automatic claim.
+ if (code === 'recovery_required' && message === PHYSICAL_ROOT_MOVED_MESSAGE) return { reason: 'physical_root_moved', message,
+ suggestion: 'Nothing was written. On the brain host, the owner runs the same gbrain sources add, set-path or writer claim with --dry-run in a terminal: it names the recorded path and the commands that bring the checkout back (a symlink and set-path, or moving the folder back). Moving folders is the user\'s decision; never remove the ownership markers.' };
if (code === 'owner_unavailable' && message === UNBOUND_PUBLICATION_MESSAGE) return { reason: 'unbound_source', message,
suggestion: 'Read the page again and submit the write with a new request_id; a bound source publishes it to its canonical file.' };
if (code === 'owner_unavailable') return { reason: code, message: 'The accepted source owner is unavailable or changed.',
diff --git a/test/physical-root-moved-8625.test.ts b/test/physical-root-moved-8625.test.ts
new file mode 100644
index 0000000000..c9843be0d0
--- /dev/null
+++ b/test/physical-root-moved-8625.test.ts
@@ -0,0 +1,293 @@
+/**
+ * #8625: a managed checkout moved to a new path. Before, the `add` and `set-path` dry runs said OK while the real
+ * runs refused with a generic identity error (`add`) or `source_checkout_missing` (`set-path`), and neither named the
+ * exit that already works. Now both refuse with detail `physical_root_moved`, naming the recorded path, the worktree
+ * and the exact commands (symlink then `set-path` for a bound worktree; move back then `add` for one whose source was
+ * removed; restore or deactivate when the folder is not the same directory any more). Nothing changes ownership:
+ * the existing verbs still verify everything, and a remote caller sees no path.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { Action } from '../src/core/agent-output.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath } from '../src/core/persistence/physical-root-record.ts';
+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';
+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runSetPath } from '../src/commands/sources-set-path.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+type Refusal = { code?: string; detail?: string; message?: string; suggestion?: string; docs?: string; fix?: Action };
+const refusal = (promise: Promise<unknown>): Promise<Refusal | null> => promise.then(() => null, (error: Refusal) => error);
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'] }).toString().trim();
+
+for (const kind of testBackends()) describe(`#8625 a moved managed checkout names its way back (${kind})`, () => {
+ const directory = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-moved-root-')));
+ let engine: BrainEngine, close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 120_000);
+ afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: directory }, () => disposePersistenceConsumer(engine));
+ if (close) await close(); else await engine.disconnect();
+ rmSync(directory, { recursive: true, force: true });
+ });
+
+ interface Fixture { home: string; base: string; root: string; source: string; worktreeId: string; members: string[] }
+ /** Sources claimed before activation in one checkout at `<base>/<parent>/root` (a Git checkout unless `git: false`), then the brain activated. */
+ async function fixture(opts: { git?: boolean; parent?: string; members?: string[] }, run: (f: Fixture) => Promise<void>): Promise<void> {
+ const home = join(directory, randomUUID()), base = join(home, 'brains'), root = join(base, opts.parent ?? 'old', 'root');
+ const tag = randomUUID().slice(0, 8), subs = opts.members ?? [''];
+ for (const sub of subs) { mkdirSync(join(root, sub), { recursive: true }); writeFileSync(join(root, sub, 'alice-example.md'), '# Alice Example\n\nA note.\n'); }
+ if (opts.git !== false) {
+ git(root, 'init', '-q', '-b', 'main'); git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ git(root, 'config', 'commit.gpgsign', 'false'); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'init');
+ }
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const ids = subs.map((_, i) => `moved-${tag}-${i}`);
+ for (const [i, sub] of subs.entries()) {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [ids[i], join(root, sub)]);
+ await claimWorktree(engine, ids[i], join(root, sub));
+ }
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await registerLocalWriter(engine, 'cli');
+ const worktreeId = (await getWorktreeBinding(engine, ids[0]))!.worktree_id;
+ try { await run({ home, base, root, source: ids[0], worktreeId, members: ids }); }
+ finally { await disposePersistenceConsumer(engine); }
+ });
+ }
+ const add = (sourceId: string, path: string, dryRun = false) => runManagedSourceLifecycle(engine, { operation: 'add', sourceId, path, dryRun });
+ const setPath = (sourceId: string, path: string, dryRun = false) => runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId, path, dryRun });
+ const remove = (sourceId: string) => runManagedSourceLifecycle(engine, { operation: 'remove', sourceId, confirmDestructive: true });
+ const generation = async (id: string) => Number((await engine.executeRaw<{ g: string }>('SELECT topology_generation::text AS g FROM persistence_worktrees WHERE id=$1::uuid', [id]))[0].g);
+ const hostPath = async (id: string) => (await engine.executeRaw<{ local_path: string }>('SELECT local_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid', [id]))[0]?.local_path;
+ const state = async () => ({
+ changes: (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_topology_changes'))[0].n,
+ bindings: await engine.executeRaw('SELECT * FROM persistence_source_bindings ORDER BY source_id'),
+ hosts: await engine.executeRaw('SELECT worktree_id,local_path,coordination_path FROM persistence_host_bindings ORDER BY worktree_id'),
+ sources: await engine.executeRaw('SELECT id,local_path FROM sources ORDER BY id'),
+ });
+ /** Runs a refusal's fix chain as an operator would once the user agreed: plain commands as argv, gbrain steps through the lifecycle. */
+ async function runFix(fix: Action | undefined): Promise<void> {
+ for (let step = fix; step; step = step.then) {
+ const argv = step.argv!;
+ if (argv[0] !== 'gbrain') { execFileSync(argv[0], argv.slice(1)); continue; }
+ const path = argv.includes('--path') ? argv[argv.indexOf('--path') + 1] : argv[4];
+ if (argv[2] === 'add') await add(argv[3], path);
+ else if (argv[2] === 'set-path') await setPath(argv[3], path);
+ else throw new Error(`unexpected fix step: ${argv.join(' ')}`);
+ }
+ }
+ const expectMoved = (error: Refusal | null, recorded: string, worktreeId: string) => {
+ expect(error).toMatchObject({ code: 'recovery_required', detail: 'physical_root_moved' });
+ expect(error!.message).toContain(recorded);
+ expect(error!.message).toContain(worktreeId);
+ expect(error!.suggestion).toContain('Never remove the ownership markers');
+ expect(error!.fix).toMatchObject({ ask_user: true, actor: 'user' });
+ expect(typeof error!.fix!.user_message).toBe('string');
+ expect(error!.fix!.verify?.argv).toContain('--dry-run');
+ };
+ const expectGeneric = (error: Refusal | null) => {
+ expect(error).toMatchObject({ code: 'recovery_required' });
+ expect(error!.detail).toBeUndefined();
+ };
+
+ test('pin: remove then add at the same root keeps the worktree id, advances its topology and keeps Git history', () => fixture({}, async f => {
+ const head = git(f.root, 'rev-parse', 'HEAD'), before = await generation(f.worktreeId);
+ await remove(f.source);
+ await add(`${f.source}-b`, f.root);
+ expect((await getWorktreeBinding(engine, `${f.source}-b`))!.worktree_id).toBe(f.worktreeId);
+ expect(await generation(f.worktreeId)).toBe(before + 2);
+ expect(git(f.root, 'rev-parse', 'HEAD')).toBe(head);
+ }), 120_000);
+
+ for (const repo of [true, false]) test(`removed source, folder moved (${repo ? 'Git checkout' : 'repo-less directory'}): add and its dry run refuse physical_root_moved, write nothing, and the exit converges`, () => fixture({ git: repo }, async f => {
+ const head = repo ? git(f.root, 'rev-parse', 'HEAD') : null, bytes = readFileSync(join(f.root, 'alice-example.md'), 'utf8');
+ await remove(f.source);
+ const moved = join(f.base, 'moved-root'), next = `${f.source}-b`;
+ renameSync(f.root, moved);
+ const stampBytes = readFileSync(join(moved, PHYSICAL_ROOT_MARKER), 'utf8'), reservationBytes = readFileSync(physicalRootReservationPath(f.root), 'utf8');
+ const before = await state();
+ const preview = await refusal(add(next, moved, true));
+ expectMoved(preview, f.root, f.worktreeId);
+ expect(preview!.suggestion).toContain(`mv '${moved}' '${f.root}'`);
+ const real = await refusal(add(next, moved));
+ expectMoved(real, f.root, f.worktreeId);
+ expect(real!.fix).toEqual(preview!.fix);
+ expect(readFileSync(join(moved, PHYSICAL_ROOT_MARKER), 'utf8')).toBe(stampBytes);
+ expect(readFileSync(physicalRootReservationPath(f.root), 'utf8')).toBe(reservationBytes);
+ expect(existsSync(physicalRootReservationPath(moved))).toBe(false);
+ expect(await state()).toEqual(before);
+
+ // The printed exit: move back and re-add at the recorded path, which reattaches the worktree; its verify then passes.
+ await runFix(real!.fix);
+ expect((await getWorktreeBinding(engine, next))!.worktree_id).toBe(f.worktreeId);
+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: next, path: f.root, dryRun: true });
+ // Moving it to the new place again names the bound (symlink) exit, which keeps it too.
+ renameSync(f.root, moved);
+ const bound = await refusal(setPath(next, moved, true));
+ expectMoved(bound, f.root, f.worktreeId);
+ await runFix(bound!.fix);
+ expect(existsSync(f.root)).toBe(false);
+ expect(await getWorktreeBinding(engine, next)).toMatchObject({ worktree_id: f.worktreeId, local_path: moved });
+ expect(readFileSync(join(moved, 'alice-example.md'), 'utf8')).toBe(bytes);
+ if (head) expect(git(moved, 'rev-parse', 'HEAD')).toBe(head);
+ }), 120_000);
+
+ test('bound source, folder moved: set-path and its dry run refuse physical_root_moved; the symlink exit keeps the worktree', () => fixture({}, async f => {
+ const moved = join(f.base, 'renamed');
+ renameSync(f.root, moved);
+ const reservationBytes = readFileSync(physicalRootReservationPath(f.root), 'utf8'), before = await state();
+ const preview = await refusal(setPath(f.source, moved, true));
+ expectMoved(preview, f.root, f.worktreeId);
+ expect(preview!.suggestion).toContain(`ln -s '${moved}' '${f.root}'`);
+ const real = await refusal(setPath(f.source, moved));
+ expectMoved(real, f.root, f.worktreeId);
+ expect(readFileSync(physicalRootReservationPath(f.root), 'utf8')).toBe(reservationBytes);
+ expect(await state()).toEqual(before);
+ await runFix(real!.fix);
+ expect(existsSync(f.root)).toBe(false);
+ expect(await getWorktreeBinding(engine, f.source)).toMatchObject({ worktree_id: f.worktreeId, local_path: moved });
+ expect(existsSync(physicalRootReservationPath(f.root))).toBe(false);
+ expect(existsSync(physicalRootReservationPath(moved))).toBe(true);
+ await setPath(f.source, moved, true);
+ }), 120_000);
+
+ test('a bound checkout that is missing but not moved still refuses source_checkout_missing, in the dry run too', () => fixture({}, async f => {
+ rmSync(f.root, { recursive: true, force: true });
+ const other = join(f.base, 'elsewhere'); mkdirSync(other);
+ for (const dryRun of [true, false]) {
+ const error = await refusal(setPath(f.source, other, dryRun));
+ expect(error).toMatchObject({ code: 'recovery_required', docs: 'docs/guides/write-refusals.md#source_checkout_missing' });
+ expect(error!.message).toContain(`The canonical checkout ${f.root} of source '${f.source}' is missing`);
+ }
+ }), 120_000);
+
+ for (const bound of [true, false]) test(`a renamed parent folder (${bound ? 'bound' : 'removed source'}) names the parent, and its exit converges`, () => fixture({ parent: 'parent-old' }, async f => {
+ if (!bound) await remove(f.source);
+ const from = join(f.base, 'parent-old'), to = join(f.base, 'parent-new'), moved = join(to, 'root'), sourceId = bound ? f.source : `${f.source}-b`;
+ renameSync(from, to);
+ const error = await refusal(bound ? setPath(sourceId, moved, true) : add(sourceId, moved, true));
+ expectMoved(error, f.root, f.worktreeId);
+ expect(error!.message).toContain(`'${from}'`);
+ expect(error!.fix!.argv).toEqual(bound ? ['ln', '-s', to, from] : ['mv', to, from]);
+ await runFix(error!.fix);
+ expect(await getWorktreeBinding(engine, sourceId)).toMatchObject({ worktree_id: f.worktreeId, local_path: bound ? moved : f.root });
+ expect(existsSync(from)).toBe(!bound);
+ }), 120_000);
+
+ test('a copy with a new inode whose original was deleted names restore or deactivate, never a move back', () => fixture({}, async f => {
+ await remove(f.source);
+ const copy = join(f.base, 'copied-root');
+ cpSync(f.root, copy, { recursive: true, preserveTimestamps: true });
+ rmSync(f.root, { recursive: true, force: true });
+ for (const dryRun of [true, false]) {
+ const error = await refusal(add(`${f.source}-b`, copy, dryRun));
+ expect(error).toMatchObject({ code: 'recovery_required', detail: 'physical_root_moved' });
+ expect(error!.message).toContain(f.root);
+ expect(error!.suggestion).toContain('gbrain sources writer deactivate --dry-run');
+ expect(error!.suggestion).not.toContain('mv ');
+ expect(error!.fix!.argv).toEqual(['gbrain', 'sources', 'writer', 'deactivate', '--dry-run']);
+ }
+ }), 120_000);
+
+ test('a worktree with two sources names a set-path for each, and both land at the new path', () => fixture({ members: ['notes', 'people'] }, async f => {
+ const moved = join(f.base, 'renamed');
+ renameSync(f.root, moved);
+ const error = await refusal(setPath(f.source, join(moved, 'notes')));
+ expectMoved(error, f.root, f.worktreeId);
+ for (const id of f.members) expect(error!.message).toContain(id);
+ await runFix(error!.fix);
+ const paths = await engine.executeRaw<{ id: string; local_path: string }>('SELECT id,local_path FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [f.members]);
+ expect(paths).toEqual([{ id: f.members[0], local_path: join(moved, 'notes') }, { id: f.members[1], local_path: join(moved, 'people') }]);
+ expect(await hostPath(f.worktreeId)).toBe(moved);
+ }), 120_000);
+
+ test('writer claim --dry-run refuses a moved checkout like the add does', () => fixture({}, async f => {
+ await remove(f.source);
+ const moved = join(f.base, 'moved-root'), id = `${f.source}-c`;
+ renameSync(f.root, moved);
+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: id });
+ expectMoved(await refusal(runPersistenceAdministration(engine, 'writer_claim', { source_id: id, path: moved, dry_run: true })), f.root, f.worktreeId);
+ }), 120_000);
+
+ test('lookalikes keep the generic refusal: another brain, another token, a copy, another host, no reservation', () => fixture({}, async f => {
+ await remove(f.source);
+ const moved = join(f.base, 'moved-root'), stamp = join(moved, PHYSICAL_ROOT_MARKER), reservation = physicalRootReservationPath(f.root);
+ renameSync(f.root, moved);
+ const original = { stamp: readFileSync(stamp, 'utf8'), reservation: readFileSync(reservation, 'utf8') };
+ const put = (path: string, bytes: string) => { rmSync(path, { force: true }); writeFileSync(path, bytes, { mode: 0o600 }); };
+ const patch = (path: string, fields: Record<string, unknown>) => put(path, JSON.stringify({ ...JSON.parse(readFileSync(path, 'utf8')), ...fields }));
+ const restore = () => { put(stamp, original.stamp); put(reservation, original.reservation); };
+ const check = async () => { for (const dryRun of [true, false]) expectGeneric(await refusal(add(`${f.source}-b`, moved, dryRun))); };
+ const brainId = randomUUID();
+ patch(stamp, { brainId }); patch(reservation, { brainId }); await check(); restore();
+ patch(stamp, { token: randomUUID() }); await check(); restore();
+ mkdirSync(f.root); await check(); rmSync(f.root, { recursive: true });
+ const [{ owner }] = await engine.executeRaw<{ owner: string }>('SELECT owner_host_id::text AS owner FROM persistence_worktrees WHERE id=$1::uuid', [f.worktreeId]);
+ await engine.executeRaw('UPDATE persistence_worktrees SET owner_host_id=$2::uuid WHERE id=$1::uuid', [f.worktreeId, randomUUID()]); await check();
+ await engine.executeRaw('UPDATE persistence_worktrees SET owner_host_id=$2::uuid WHERE id=$1::uuid', [f.worktreeId, owner]);
+ unlinkSync(reservation); await check();
+ }), 120_000);
+
+ test('a stamp other users can read after the move refuses ownership_record_not_private', () => fixture({}, async f => {
+ await remove(f.source);
+ const moved = join(f.base, 'moved-root');
+ renameSync(f.root, moved);
+ chmodSync(join(moved, PHYSICAL_ROOT_MARKER), 0o644);
+ for (const dryRun of [true, false]) expect(await refusal(add(`${f.source}-b`, moved, dryRun))).toMatchObject({ code: 'recovery_required', detail: 'ownership_record_not_private' });
+ }), 120_000);
+
+ test('repo-less classic brain: a moved folder is a plain set-path, unchanged', async () => {
+ const home = join(directory, randomUUID()), root = join(home, 'notes'), moved = join(home, 'notes-moved'); mkdirSync(root, { recursive: true });
+ const source = `classic-${randomUUID().slice(0, 8)}`;
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: undefined }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, root]);
+ renameSync(root, moved);
+ await runSetPath(engine, [source, moved]);
+ expect((await engine.executeRaw<{ local_path: string }>('SELECT local_path FROM sources WHERE id=$1', [source]))[0].local_path).toBe(moved);
+ });
+ }, 60_000);
+});
+
+if (testBackends().includes('pglite')) describe('#8625 a remote page write never sees the moved checkout\'s paths (pglite, pre-activation)', () => {
+ const directory = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-moved-remote-')));
+ let engine: PGLiteEngine;
+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+ afterAll(async () => { await withEnv({ GBRAIN_HOME: directory }, () => disposePersistenceConsumer(engine)); await engine.disconnect(); rmSync(directory, { recursive: true, force: true }); });
+
+ test('remote put_page to a source whose folder holds a moved stamp refuses without a path or worktree id', async () => {
+ const home = join(directory, 'home'), root = join(directory, 'brains', 'old-root'), moved = join(directory, 'brains', 'new-root');
+ mkdirSync(root, { recursive: true });
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: undefined }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.setConfig('sync.write_through', 'true');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['source-a', root]);
+ const worktreeId = (await claimWorktree(engine, 'source-a', root)).worktree_id;
+ await engine.executeRaw("DELETE FROM persistence_source_bindings WHERE source_id='source-a'");
+ await engine.executeRaw("DELETE FROM sources WHERE id='source-a'");
+ renameSync(root, moved);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['source-b', moved]);
+ const result = await dispatchToolCall(engine, 'put_page', { slug: 'notes/alice-example', content: '---\ntype: note\ntitle: Alice Example\n---\n# Alice Example\n' },
+ { remote: true, transport: 'stdio', sourceId: 'source-b', admissionOrigin: 'interactive' });
+ expect(result.isError).toBe(true);
+ const text = result.content[0]!.text;
+ expect(JSON.parse(text)).toMatchObject({ code: 'recovery_required', detail: 'physical_root_moved' });
+ for (const secret of [directory, root, moved, worktreeId]) expect(text).not.toContain(secret);
+ expect(existsSync(join(moved, 'notes'))).toBe(false);
+ });
+ }, 120_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 72ad5657dd..73391f9e00 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -447,6 +447,7 @@ test/persistence-write-interrupted.test.ts
test/persistence-write-stall.test.ts
test/persistence-writer-fences.test.ts
test/physical-root-birth-tolerance-6501.test.ts
+test/physical-root-moved-8625.test.ts
test/provenance-drift-7891.test.ts
test/provenance-stamps-7873.test.ts
test/purge-fact.test.ts