Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: foreign_writers partial scans, fail-closed owner guard, adopt_local_edits hardening (GST-1623 items 4, 6-9; #8755)
garrytandd92331bde65
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e31625b727..2c4cc8fb3e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,19 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Doctor `foreign_writers` no longer reads an unreadable ledger or a skipped repository as clean, the owner-path commit guard fails closed, and the opt-in local-edit adoption (`persistence.adopt_local_edits`, off by default) gets the hardening it needed before any source turns it on.** `foreign_writers` now marks a scan partial when a root's Git probe fails, when roots pass the 50-root cap, or when the commit ledger exists but cannot be read. It names a foreign commit that carries a `gbrain-` trailer as possibly an older gbrain without the ledger, and still fails it. `gbrain git commit-push` refuses a repository that only encloses a registered checkout. Adoption keeps its refusal for a conflicted path or a merge in progress, a stale editor save, a segmented or oversized page, and a caller whose claim is gone. Its quiet wait is capped at the foreground budget, and an adoption whose publication failed after its commit is retried instead of left orphaned.++### Itemized changes++- `src/commands/doctor/checks/foreign-writers.ts`, `src/core/git/commit-ledger.ts`: `partial_reasons` lists skipped roots. A probe that fails inside a checkout, or roots past `MAX_ROOTS`, mark the scan partial, and a scan that read no repository but skipped one warns instead of reporting not_applicable. `readLedger` treats only ENOENT as empty. A failed or timed-out `git status` names its checkout, and its timeout follows doctor's per-entry deadline (5 to 30 s). Commits with a `gbrain-` trailer carry `gbrain_trailer`.+- `src/commands/git.ts`, `src/core/persistence/root-registry.ts`: `checkout_not_a_source` requires a registered root to contain the checkout, or to be a directory of it that its HEAD tracks. A registry directory that cannot be listed refuses with a typed error.+- `src/core/git/commit-guard.ts`: the owner-path hook exits 1 when `git rev-parse --absolute-git-dir` fails.+- `src/core/persistence/local-edit-adoption.ts`, `file-repair.ts`, `coordinator.ts`, `pending-import.ts`: adoption refuses unmerged paths and in-progress merges, cherry-picks and rebases. It also refuses a file whose body equals one of the last 50 revisions or that drops rows the current revision added, and it stats the file before reading it. It caps the quiet wait at 30 s and records the caller's claim, so an orphaned adoption publishes nothing. It waits on an adoption another task is already publishing, retries a requeued publication against a HEAD that already holds the adopted blob, and never reports `released` for a lost claim. An empty `persistence.adopt_quiet_ms` reads as the 5000 default, and an admission failure logs a `phase=adoption` line.+- `src/commands/doctor/checks/local-edit-adoptions.ts`: counts adoptions from `outcome.adopted_local_edit`, which receipt compaction keeps.+- Tests: `test/doctor-foreign-writers.test.ts`, `test/commit-ledger.test.ts`, `test/sources-guard.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`, and `test/adopt-local-edit.test.ts` on PGLite and Postgres (GST-1623 items 4 and 6–9, #8755).+## [0.60.600.0] - 2026-11-07**With the refresh write barrier on, writes waiting behind an import no longer use up the capacity the import itself needs, so a full cap no longer stalls managed sync until the waits expire.** The barrier is still off by default (`persistence.refresh_barrier`), and with it off nothing changes. Before, every held write kept its outstanding-request slot and intent bytes, so enough of them could leave a managed sync job, or a bulk import group, refused `queue_capacity`, and the writes it would have released waited out the limit and expired. A held `capture` that replaces an imported page now names what it replaced, as a blind `put_page` does, and the expiry pass no longer expires a hold that an import and a new deferral replaced while it ran.diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.mdindex 77c4230657..079234a828 100644--- a/docs/architecture/key-files/core-persistence-request-indexes.md+++ b/docs/architecture/key-files/core-persistence-request-indexes.md@@ -17,4 +17,4 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa- `src/core/persistence/hosted-repo.ts` with `src/commands/sources-host-repo.ts` — G7b-2, `gbrain sources host-repo <id> --dir <path> [--push-remote <url>] [--dry-run | --expect <plan_hash>]`: a hosted brain gives an empty, unbound source a bare repository (`<dir>/repo.git`, branch `main`, one commit holding an empty `.gitignore`, repository-local identity `gbrain`) and checks it out as a linked worktree (`<dir>/worktree`) claimed through `runManagedSourceLifecycle` (`add` or `claim`, every physical-root and manifest check), with `config.canonical = "git"` and `config.hosted_repo` set in the claim's own transaction. The door then commits there unchanged. A pre-receive hook (`core.hooksPath` pinned to the repository's `hooks/`) refuses every push, since Git's checked-out-branch refusal ends once the worktree is pruned. The preview (the default without `--expect`) prints the plan in words and a `plan_hash` over the source incarnation, canonical setting, directory state, push remote and hook; the apply refuses `preview_changed` when it moved. Refuses `strict_requires_managed` on an unmanaged brain, `hosted_repo_refused` (`source_bound`, `source_has_path`, `source_has_pages`, `source_archived`, `dir_not_empty`) and `overlapping_path` (a directory in a checkout or a source's directory). On a hosted source the preview reports the hook (`ok`/`missing`/`changed`) and the worktree link, and the apply reinstalls the hook. Trusted local CLI only; no operation. Tests: `test/hosted-repo-g7b2.test.ts` (both engines).- `src/core/persistence/worktree-link.ts` `linkedWorktreeProblem` / `assertLinkedWorktreeIntact` — a claim (`localRoot` in `source-lifecycle.ts`) refuses `git_worktree_link_broken` for a linked worktree whose `.git` file names a repository entry that is gone (pruned) or whose entry names another path (the checkout moved); a submodule's `.git` file is checked for existence only. Tests: `test/hosted-repo-g7b2.test.ts`.- `src/core/persistence/sync-receipt-wait.ts` — how long a managed sync pass waits on its own admitted write, in one place: `syncReceiptWait()` returns `pass` (5 s), `checkpoint` (8 s), `held` (30 s, while this process's consumer still holds the write) and `drain` (30 s, a drain's re-entry). `sync-run.ts` reads every wait from it. `__setSyncReceiptWaitForTests(partial | null)` is the test seam (returns a restore function), so a test outlasts a wait in milliseconds instead of sleeping past 30 s.-- **`src/core/persistence/local-edit-adoption.ts`** — GST-1601 part 2: with `persistence.adopt_local_edits.source.<id>` on, `finishUnpublishedFailure` (`coordinator.ts`) hands a `remember` / `capture` / `add_timeline_entry` refused `file_database_drift` to `adoptLocalEdit`, which reads the drifted file the refusal carries (`localEdit`, set in `page-prepare.ts` compareFileTarget), waits until it is quiet (`persistence.adopt_quiet_ms`, at most three windows), and adopts only a one-sided, safe edit: HEAD's blob matches the database copy (`fileMatchesSnapshot`; a repo-less brain skips this), `protectedLocalEdit` finds no title, type or protected-key change, and `prepareRepairPublication` is `ready`. The adoption is a `managed_file_repair` (`file-repair.ts`) carrying `adoptLocalEdit` (`{ blob, replaced_revision }`), admitted under the CLI writer with a request id derived from the caller's (one adoption per write), claimed and published inline (`publishMutation`, retrying a busy worktree lock for 10 s) so it lands before the caller: it publishes the file's unchanged bytes with the `localEditAdoptionCommit` note, stamps the archived replaced revision `change_reason = 'adopted_local_edit'`, and commits that one file inside its publication transaction (`afterEffects` → `commitAdoptedLocalEdit`; a strict source's door commits it instead). The caller is then released with `intent.adopted_local_edit` and prepared again; `withAdoptedLocalEdit` (`service.ts` preparePersistedMutation) puts `adopted` on its receipt. A file changed under the adoption ends both `raw_file_changed`. Commit-ledger lines carry `adopted` (`adoptedBy`, `effect-model.ts`). Doctor `local_edit_adoptions` (`src/commands/doctor/checks/local-edit-adoptions.ts`) lists adoptions of the last 24 h per source, always ok. Test: `test/adopt-local-edit.test.ts`.+- **`src/core/persistence/local-edit-adoption.ts`** — GST-1601 part 2: with `persistence.adopt_local_edits.source.<id>` on, `finishUnpublishedFailure` (`coordinator.ts`) hands a `remember` / `capture` / `add_timeline_entry` refused `file_database_drift` to `adoptLocalEdit`, which reads the drifted file the refusal carries (`localEdit`, set in `page-prepare.ts` compareFileTarget), waits until it is quiet (`persistence.adopt_quiet_ms`, empty reads as the 5000 default, at most three windows and never past 30 s: the caller's claim holds its worktree queue meanwhile), and adopts only a one-sided, safe edit (#8755: a file over `PAGE_MAX_BYTES`, checked by stat before reading, a segmented page, an unmerged path or an operation in progress (`pending-import.ts` `unmergedPath` / `mergeInProgress`), and a stale editor save (`staleEditorSave`: the file equals an earlier `page_versions` body, or lacks a list or table row the current revision has and its newest archived version had not) keep the refusal; the repo-less test walks up for `.git`): HEAD's blob matches the database copy (`fileMatchesSnapshot`; a repo-less brain skips this), `protectedLocalEdit` finds no title, type or protected-key change, and `prepareRepairPublication` is `ready`. The adoption is a `managed_file_repair` (`file-repair.ts`) carrying `adoptLocalEdit` (`{ blob, replaced_revision }`), admitted under the CLI writer with a request id derived from the caller's (one adoption per write), claimed and published inline (`publishMutation`, retrying a busy worktree lock for 10 s) so it lands before the caller: it publishes the file's unchanged bytes with the `localEditAdoptionCommit` note, stamps the archived replaced revision `change_reason = 'adopted_local_edit'`, and commits that one file inside its publication transaction (`afterEffects` → `commitAdoptedLocalEdit`; a strict source's door commits it instead). #8755: a publication that fails after that commit is requeued by recovery and `publishAdoption` publishes it again (it retries any release within its 10 s): `adoptedHeadHolds` accepts HEAD holding the adopted blob and the replay names the landed commit (`landed_before_row`). The intent names the caller's claim (`adoptLocalEdit.caller`); `assertAdoptionCaller` (`file-repair.ts` preparation) refuses `write_claim_lost` once that claim is gone, so an adoption orphaned by a crash publishes nothing; its own claim carries the owner stamp. `settleAdoption` waits up to 120 s more on an adoption whose publication already started; a caller whose claim was lost is returned as `claimLost`, never `released`; an admission failure logs `[persistence] phase=adoption`. The caller is then released with `intent.adopted_local_edit` and prepared again; `withAdoptedLocalEdit` (`service.ts` preparePersistedMutation) puts `adopted` on its receipt. A file changed under the adoption ends both `raw_file_changed`. Commit-ledger lines carry `adopted` (`adoptedBy`, `effect-model.ts`). Doctor `local_edit_adoptions` (`src/commands/doctor/checks/local-edit-adoptions.ts`) lists adoptions of the last 24 h per source from `outcome.adopted_local_edit` (kept by compaction), always ok. Test: `test/adopt-local-edit.test.ts`.diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.mdindex 2f65edba1c..60dfdaea7a 100644--- a/docs/architecture/key-files/workspace-push-and-backup.md+++ b/docs/architecture/key-files/workspace-push-and-backup.md@@ -12,8 +12,8 @@ Key files:## Shared-checkout git writer-- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --literal-pathspecs`, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (`git_unavailable`, paths unstaged). `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. `notePending` is exported: the derived and dream write-through (`cycle/derived-write-through.ts`, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`. The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.sourceRoot` (#8662). Tests: `test/git-writer-safety-7381.serial.test.ts`, `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`.+- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --literal-pathspecs`, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (`git_unavailable`, paths unstaged). `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. `notePending` is exported: the derived and dream write-through (`cycle/derived-write-through.ts`, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`. The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.sourceRoot` (#8662); a registered checkout must contain the resolved one, or be a subdirectory its HEAD tracks, so a repository that only encloses one is refused, and a registry that cannot be listed refuses `writer_coordinator_required` (GST-1623). Tests: `test/git-writer-safety-7381.serial.test.ts`, `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`.- `src/commands/doctor/checks/git-writer.ts` — `checkout_lagging`, `dirty_age`, `commits_outside_source_root`, `quarantined_changes` (#7381, brain category, after `git_convergence`): over the unmanaged source checkouts with an upstream (`sourceRoots` from git-convergence, grouped by toplevel with each source's toplevel-relative root), never fetching, every git call bounded at 5 s. Lagging warns when `HEAD..@{u}` holds a commit over an hour old (fix: `gbrain git commit-push --pull --path <top>`, agent). Dirty age warns on pending write-through files older than 30 minutes (`pendingWriteThroughStillDirty`; fix: `commit-push --pending`, agent) and on files staged that long (ask_user: unstage or commit by name). Outside-root warns on unpushed non-merge commits that change files outside the DB source roots plus `gbrain.sourceRoot` (`localCommitsOutsideRoots`; ask_user fix with `--allow-outside-source-root`), and says when the checkout has no root recorded. Test: `test/doctor-git-writer-7381.test.ts`.-- `src/core/git/commit-ledger.ts` — the commit ledger (PR B, docs/designs/REFRESH_WRITE_BARRIER.md part 3): `<git common dir>/gbrain/commit-ledger.jsonl`, one O_APPEND JSON line under 1 KiB per record, under its own flock `commit-ledger.lock` (start line, append, 4 MiB rotation to `commit-ledger.1.jsonl`). `recordCommit`/`recordCommitAsync` take the sha and writer kind (`commit_push`, `door`, `merge`, `replay`, `effect`, `sync_init`, `workspace_push`, `bootstrap`, `hosted_repo`); porcelain sites call `recordIntent` (head_before, `messageDigest` of the message) before `git commit`, plumbing sites record the `commit-tree` sha before the ref moves. A failed append never fails the commit (logged once); a directory outside git records nothing. `readLedger` reads both files. Tests: `test/commit-ledger.test.ts`.-- `src/commands/doctor/checks/foreign-writers.ts` — `foreign_writers` (PR B part 4): every registered source checkout on this host, managed worktrees included, deduplicated by git common dir. Reflogs (`logs/HEAD`, `logs/refs/heads/*`, `worktrees/*/logs/HEAD`, newest 5,000 entries each) are classified by `classifyReflogMessage`: porcelain creations by new sha, other ref moves by the `old..new` range within 10 minutes of the entry, merges/fast-forwards/resets/checkouts/branch/clone excluded. Unledgered commits fail (`plain`, `amend`, `rewrite`, `plumbing`; `guard_bypassed` when the enforce guard predates the commit); intent matches are `unconfirmed` (warn, never written back); entries before the ledger start are uncovered. Dirty page files come from `status --porcelain=v2` under the source roots minus queued/running git effects and the write-through pending ledger. Repo-less: `not_applicable`. Tests: `test/doctor-foreign-writers.test.ts`.-- `src/commands/sources-guard.ts` — `gbrain sources guard <source> --install|--uninstall|--status [--mode enforce]` (PR B part 5): owner host only (`permission_denied` elsewhere), install/uninstall under the worktree's native writer lock (`acquireWorktree`). `commit-guard.ts` `installOwnerGuard` writes the hook to `<worktree git dir>/gbrain-hooks` and sets `git config --worktree core.hooksPath` (enabling `extensions.worktreeConfig`, moving `core.bare`/`core.worktree` to `config.worktree`, only when linked worktrees exist), refusing when another tool's hook lives at the effective hooks path and copying gbrain's own hooks there (the brain-durability post-commit hook, so an unrecorded binding stays durable); both owner-path modes exit 0 outside the owner worktree (a worktree added after the install inherits its hooks path through `config.worktree`), `renderGuardHook('enforce')` keeps only the merge exemption, and `renderGuardHook()` with no mode stays byte-identical to the opt-in `gbrain git guard` hook. Tests: `test/sources-guard.test.ts`.+- `src/core/git/commit-ledger.ts` — the commit ledger (PR B, docs/designs/REFRESH_WRITE_BARRIER.md part 3): `<git common dir>/gbrain/commit-ledger.jsonl`, one O_APPEND JSON line under 1 KiB per record, under its own flock `commit-ledger.lock` (start line, append, 4 MiB rotation to `commit-ledger.1.jsonl`). `recordCommit`/`recordCommitAsync` take the sha and writer kind (`commit_push`, `door`, `merge`, `replay`, `effect`, `sync_init`, `workspace_push`, `bootstrap`, `hosted_repo`); porcelain sites call `recordIntent` (head_before, `messageDigest` of the message) before `git commit`, plumbing sites record the `commit-tree` sha before the ref moves. A failed append never fails the commit (logged once); a directory outside git records nothing. `readLedger` reads both files; only a missing file reads as empty, any other read error throws (GST-1623). Tests: `test/commit-ledger.test.ts`.+- `src/commands/doctor/checks/foreign-writers.ts` — `foreign_writers` (PR B part 4): every registered source checkout on this host, managed worktrees included, deduplicated by git common dir. Reflogs (`logs/HEAD`, `logs/refs/heads/*`, `worktrees/*/logs/HEAD`, newest 5,000 entries each) are classified by `classifyReflogMessage`: porcelain creations by new sha, other ref moves by the `old..new` range within 10 minutes of the entry, merges/fast-forwards/resets/checkouts/branch/clone excluded. Unledgered commits fail (`plain`, `amend`, `rewrite`, `plumbing`; `guard_bypassed` when the enforce guard predates the commit); intent matches are `unconfirmed` (warn, never written back); entries before the ledger start are uncovered. Dirty page files come from `status --porcelain=v2` under the source roots minus queued/running git effects and the write-through pending ledger. GST-1623: a foreign commit carries `gbrain_trailer` when its trailer paragraph has a `gbrain-*:` line (named as possibly an older gbrain without the ledger; still fails); `partial_reasons` names what the scan skipped (a root inside a checkout whose `rev-parse` fails, roots past `MAX_ROOTS` 50, an unreadable ledger, a failed or timed-out status, given up to 30 s within doctor's budget, the budget itself), and a scan that read no repository but skipped one warns. Repo-less: `not_applicable`. Tests: `test/doctor-foreign-writers.test.ts`.+- `src/commands/sources-guard.ts` — `gbrain sources guard <source> --install|--uninstall|--status [--mode enforce]` (PR B part 5): owner host only (`permission_denied` elsewhere), install/uninstall under the worktree's native writer lock (`acquireWorktree`). `commit-guard.ts` `installOwnerGuard` writes the hook to `<worktree git dir>/gbrain-hooks` and sets `git config --worktree core.hooksPath` (enabling `extensions.worktreeConfig`, moving `core.bare`/`core.worktree` to `config.worktree`, only when linked worktrees exist), refusing when another tool's hook lives at the effective hooks path and copying gbrain's own hooks there (the brain-durability post-commit hook, so an unrecorded binding stays durable); both owner-path modes exit 0 outside the owner worktree (a worktree added after the install inherits its hooks path through `config.worktree`) and exit 1 when `git rev-parse --absolute-git-dir` fails (GST-1623, fail closed), `renderGuardHook('enforce')` keeps only the merge exemption, and `renderGuardHook()` with no mode stays byte-identical to the opt-in `gbrain git guard` hook. Tests: `test/sources-guard.test.ts`.diff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.mdindex ce913ee7b7..6f3eef4ec4 100644--- a/docs/guides/shared-checkout-git.md+++ b/docs/guides/shared-checkout-git.md@@ -173,7 +173,7 @@ Follow the error's `fix.next` as the| `committed_local` | 0 | A managed canonical worktree, or a checkout with no Git remote (`no_remote: true`): the paths were committed locally and nothing was pushed. Report the commit; it reaches a remote on the owner's next publish, or after a remote is added and `--push-only` runs. || `pushed_checkout_lagging` | 0 | The push landed but this checkout was not advanced; a `[gbrain notice]` names the files that blocked it. Change nothing: the next commit-push or `--pull` catches the checkout up. Never stash or reset to "fix" it. || `commit_lock_busy` | 1 | Another writer held the lock for the whole wait; nothing was committed. Retry once. If it is still busy, tell the user which checkout and lock path the message names and stop. |-| <a id="checkout_not_a_source"></a>`checkout_not_a_source` | 1 | The checkout commit-push resolved from the working directory (no `--path`) is not one of the brain's source checkouts on this host, typically a wrapper that changed into another repository; nothing was staged. The message lists the brain's checkouts. Tell the user to make the script pass `--path` with the absolute brain checkout. A host whose brain records no source checkout, or a checkout with `gbrain.sourceRoot` set, is never refused this way. |+| <a id="checkout_not_a_source"></a>`checkout_not_a_source` | 1 | The checkout commit-push resolved from the working directory (no `--path`) is not one of the brain's source checkouts on this host, typically a wrapper that changed into another repository; nothing was staged. The message lists the brain's checkouts. Tell the user to make the script pass `--path` with the absolute brain checkout. A repository that only encloses a source checkout (a brain cloned inside another repository) is not one; a source registered at a subdirectory its checkout tracks is. A host whose brain records no source checkout, or a checkout with `gbrain.sourceRoot` set, is never refused this way. || `commit_paths_invalid` | 1 | No paths, a path outside the checkout, the checkout root itself, or a path git would not stage. Name the explicit files you wrote and rerun. || `commit_prestaged_paths` | 1 | Another writer staged files under a directory you named; nothing was staged or committed. Name your own files explicitly. Unstage the others (`git restore --staged -- <file>`, which keeps their bytes) only after the user agrees. || `commit_outside_source_root` | 1 | The commit, or a local commit about to be published, changes files outside the brain's [source root](#source-roots); nothing was pushed. Show the user `git show --stat <sha>`; rerun with `--allow-outside-source-root` only if they want it published. |@@ -632,6 +632,10 @@ on this host, managed worktrees included, once per repository. It is read-only.commit fails the check, naming the newest one:`Commit <sha12> (<kind>, "<subject>", <time>) in <checkout> was not made bygbrain; route that writer through gbrain git commit-push or a page write`.+ An older gbrain co-installed on the host (one without the commit ledger)+ also reads as a foreign writer; a foreign commit whose message carries a+ `gbrain-*:` trailer is flagged `gbrain_trailer` and named as possibly that,+ but still fails, since a trailer alone proves nothing.Ask the user which job makes such commits before changing anything.- **Covered window.** Reflog entries older than the ledger's start (or itsoldest retained line after rotation) are reported as uncovered, never@@ -646,8 +650,13 @@ on this host, managed worktrees included, once per repository. It is read-only.The JSON (`details`) carries the window per repository, every foreign commit(sha, kind, ref, time, subject, committer), the unconfirmed ones, ref moves it-could not read, and at most 20 dirty files with the total count. A brain with-no Git checkout reports `not_applicable`.+could not read, and at most 20 dirty files with the total count. Whatever the+scan could not read leaves it partial (a warning) with the reasons in+`partial_reasons`: a root inside a Git checkout that git cannot read, source+roots past the 50-root cap, an unreadable ledger, a `git status` that failed+or timed out (it gets up to 30 s within doctor's budget), or doctor's budget+running out. A brain with no Git checkout reports `not_applicable`; a scan+that skipped a root never does.## Limitsdiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 3180a72de2..e9b875011e 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -51,7 +51,7 @@ of making a duplicate.| Reason | Error code | What it means | Recovery || --- | --- | --- | --- |-| <a id="file_database_drift"></a>`file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. The receipt records the cause as `error_detail.origin: file_database_drift` (GST-1601). A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. Drift only in ordinary frontmatter keys (not a policy, privacy, lineage or trust key such as `readable_by`, `derived_from` or `trust_tier`, nor title, type or tags) does not refuse a write that leaves the frontmatter unchanged, such as `remember`: the write lands and the file keeps its own frontmatter, so that drift is left for reconcile (#8109). With `gbrain config set persistence.adopt_local_edits.source.<source> true` (off by default), a `remember`, `capture` or `add_timeline_entry` that meets a one-sided local edit (Git `HEAD` still holds the database copy; on a repo-less brain, any edit) is not refused: once the file has been unchanged for `persistence.adopt_quiet_ms` (default 5000), the owner commits that file on its own (`gbrain: adopt local edit to <path>`, trailers `gbrain-adopted:` and `gbrain-author: unknown`; page history reason `adopted_local_edit`), then applies the write on top, and the receipt names `adopted`. A two-sided edit, a file that does not import, an edit to the title, type or a protected key, `put_page` and every other verb still refuse; doctor `local_edit_adoptions` lists adoptions of the last 24 h (GST-1601). | The receipt's fix (`gbrain sources writer failures <source>`, `gbrain write-request <request_id> --json`) previews keeping the database copy for that one page with `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (`--prefer file` previews importing the file instead); a person picks the side, then the agent runs the apply command the preview prints. A group of such receipts gets `--all-drifted --since <instant>` with the oldest receipt's time, so only pages that drifted since then are selected. For a hand merge: `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). Many pages at once: `gbrain sources reconcile <source> --brain host --audit --conflicts` lists them and `gbrain repair file-drift` resolves them, preferring the file or the database copy ([file drift](repair.md#file-drift)). |+| <a id="file_database_drift"></a>`file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. The receipt records the cause as `error_detail.origin: file_database_drift` (GST-1601). A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. Drift only in ordinary frontmatter keys (not a policy, privacy, lineage or trust key such as `readable_by`, `derived_from` or `trust_tier`, nor title, type or tags) does not refuse a write that leaves the frontmatter unchanged, such as `remember`: the write lands and the file keeps its own frontmatter, so that drift is left for reconcile (#8109). With `gbrain config set persistence.adopt_local_edits.source.<source> true` (off by default), a `remember`, `capture` or `add_timeline_entry` that meets a one-sided local edit (Git `HEAD` still holds the database copy; on a repo-less brain, any edit) is not refused: once the file has been unchanged for `persistence.adopt_quiet_ms` (default 5000), the owner commits that file on its own (`gbrain: adopt local edit to <path>`, trailers `gbrain-adopted:` and `gbrain-author: unknown`; page history reason `adopted_local_edit`), then applies the write on top, and the receipt names `adopted`. A two-sided edit, a file that does not import, an edit to the title, type or a protected key, `put_page` and every other verb still refuse; doctor `local_edit_adoptions` lists adoptions of the last 24 h (GST-1601). The refusal also stays for a file over the page size limit or a page stored in segments, an unmerged path or a merge, cherry-pick, revert or rebase in progress, and a stale editor save (a file equal to an earlier stored revision, or missing a Facts or timeline row the last write added); the quiet wait never passes 30 s, since writes behind it on the same checkout wait meanwhile (#8755). | The receipt's fix (`gbrain sources writer failures <source>`, `gbrain write-request <request_id> --json`) previews keeping the database copy for that one page with `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (`--prefer file` previews importing the file instead); a person picks the side, then the agent runs the apply command the preview prints. A group of such receipts gets `--all-drifted --since <instant>` with the oldest receipt's time, so only pages that drifted since then are selected. For a hand merge: `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). Many pages at once: `gbrain sources reconcile <source> --brain host --audit --conflicts` lists them and `gbrain repair file-drift` resolves them, preferring the file or the database copy ([file drift](repair.md#file-drift)). || <a id="canonical_file_missing"></a>`canonical_file_missing` | `source_changed` (a caller write; maintenance refuses before admission) | The page's recorded canonical file is gone while its database page is still live (a ghost page: the file was moved or deleted outside gbrain). A caller write refuses with "The canonical file was removed outside coordinated publication." and nothing is written; retrying it refuses the same way. A maintenance write (fact-fence adoption, enrichment, `dream`) is refused before admission: no request id, no receipt (before #6696 each cycle settled a `conflict` receipt). `gbrain sources writer failures <source>` reports such receipts as category `canonical_file_missing`. Neither copy was changed. | Decide which copy is right. If the file should exist, restore it at its recorded path and preview the page with `gbrain sources reconcile <source> <slug> --brain host --preview`, or sync. If the page should go, preview the ghost-page repair with `gbrain repair ghost-pages --source <source>` (read-only; it prints the apply command with its hash) and apply it with `--apply --expect <hash> --yes` only after the user agrees; a soft-deleted page can be restored with `gbrain restore <slug> --force` until the autopilot purge 72 h later. `gbrain pages ghosts --source <source>` and doctor `ghost_pages` list them, doctor `maintenance_write_drift` lists held-back maintenance writes. See [ghost pages](repair.md#ghost-pages). || <a id="refusal_breaker"></a>`refusal_breaker` | the code of the earlier refusals | The same maintenance write (same source, slug, page revision, planner and intent) was refused `persistence.maintenance.refusal_breaker_threshold` times (default 3; `0` turns it off) in the last 24 hours, so maintenance submits nothing for it instead of adding another receipt (#6696). It is tried again once the page, the planner or the write changes, or when the oldest refusal is 24 hours old. | Read the last refusal with `gbrain write-request -- <request_id>` (named in the message) and fix what it names. Doctor `maintenance_write_drift` lists every held-back write with its exit. || <a id="canonical_file_absent"></a>`canonical_file_absent` | `source_changed` (`restore_page` / `gbrain restore`) | On a brain without managed persistence, a restore that writes no file (`sync.write_through` off, a sandbox, a database-only source) of a soft-deleted page whose recorded file is no longer among the files sync imports (#6609). A plain restore would be undone by the next `gbrain sync --full`, so nothing was restored. Not retryable; the fix asks the user. | Ask the user. To keep the page with its file: put the file back at its recorded path, commit it and `gbrain sync --source <source>`. To keep it database-only: `gbrain restore <slug> --source-id <source> --detach` (MCP `restore_page` with `detach: true`), which forgets the recorded file and stamps `database_only_reason='detached'`. See [restoring a page whose file is gone](../storage-tiering.md#restoring-a-page-whose-file-is-gone). |diff --git a/src/commands/doctor/checks/foreign-writers.ts b/src/commands/doctor/checks/foreign-writers.tsindex a1b6114044..dc398c42c1 100644--- a/src/commands/doctor/checks/foreign-writers.ts+++ b/src/commands/doctor/checks/foreign-writers.ts@@ -15,13 +15,18 @@* warn, never written back.* - Dirty page files: untracked and unstaged files under the source roots, leaving out paths with a queued or running* git effect and paths in the write-through pending ledger; age is the file's mtime.+ * - GST-1623: whatever the scan could not read leaves it partial, with the reason (`partial_reasons`): a root inside a Git+ * checkout whose probe fails, roots past the scan cap, an unreadable ledger, a git status that failed or timed out+ * (given up to 30 s within doctor's budget), doctor's budget itself. A scan that read no repository but skipped one is+ * a warn, never not_applicable. A foreign commit whose message carries a `gbrain-*:` trailer is still foreign (a+ * trailer is forgeable) but is named as possibly an older gbrain without the commit ledger.*/import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';-import { join, relative, resolve, sep } from 'node:path';+import { dirname, join, relative, resolve, sep } from 'node:path';import { execFileSync } from '../../../core/spawn.ts';import { GIT_READ_ENV, gitChildEnv } from '../../../core/git-env.ts';import type { Check } from '../../doctor.ts';-import { readLedger, messageDigest } from '../../../core/git/commit-ledger.ts';+import { ledgerFiles, readLedger, messageDigest } from '../../../core/git/commit-ledger.ts';import { readPendingWriteThrough } from '../../../core/git/commit-push.ts';import { GUARD_ENFORCE_MARKER, GUARD_HOOK, OWNER_HOOKS_DIR } from '../../../core/git/commit-guard.ts';import { existingHostIdFor } from '../../../core/persistence/identity.ts';@@ -37,22 +42,34 @@ export const FOREIGN_DIRTY_WARN_MS = 30 * 60_000;const MAX_REFLOG_ENTRIES = 5_000;const MAX_RANGE_COMMITS = 500;const GIT_TIMEOUT_MS = 5_000;+const STATUS_TIMEOUT_MAX_MS = 30_000;const MAX_ROOTS = 50;const MAX_LISTED = 20;const ZERO = /^0+$/;+const BUDGET_REASON = 'doctor\'s time budget ran out';export type ForeignKind = 'plain' | 'amend' | 'rewrite' | 'plumbing';-export interface ForeignCommit { sha: string; kind: ForeignKind; guard_bypassed: boolean; ref: string; time: string; subject: string; committer: string; checkout: string }+export interface ForeignCommit { sha: string; kind: ForeignKind; guard_bypassed: boolean; gbrain_trailer: boolean; ref: string; time: string; subject: string; committer: string; checkout: string }interface Candidate { sha: string; kind: ForeignKind; ref: string; time: number; gitDir: string | null; checkout: string }interface Checkout { top: string; gitDir: string; source_ids: string[]; roots: string[] }interface Repo { common: string; checkouts: Map<string, Checkout> }interface Reflog { file: string; ref: string; gitDir: string | null }interface Entry { old: string; next: string; time: number; message: string }-function git(root: string, args: string[], input?: string): string | null {- try { return execFileSync('git', ['-C', root, ...args], { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'], input, timeout: GIT_TIMEOUT_MS, maxBuffer: 32 * 1024 * 1024, env: gitChildEnv(GIT_READ_ENV) }).toString(); }- catch { return null; }+function gitRun(root: string, args: string[], input?: string, timeout = GIT_TIMEOUT_MS): { out: string | null; timedOut: boolean } {+ try { return { out: execFileSync('git', ['-C', root, ...args], { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'], input, timeout, maxBuffer: 32 * 1024 * 1024, env: gitChildEnv(GIT_READ_ENV) }).toString(), timedOut: false }; }+ catch (error) { const e = error as { code?: string; signal?: string }; return { out: null, timedOut: e.code === 'ETIMEDOUT' || e.signal === 'SIGTERM' }; }}+const git = (root: string, args: string[], input?: string): string | null => gitRun(root, args, input).out;+/** Whether `root` or an ancestor holds a `.git` entry: a checkout git should have answered for (reconcile-state.ts insideGitCheckout). */+function insideGitCheckout(root: string): boolean {+ for (let dir = resolve(root); ; dir = dirname(dir)) {+ if (existsSync(join(dir, '.git'))) return true;+ if (dirname(dir) === dir) return false;+ }+}+/** A commit message whose trailer paragraph (its last) carries a `gbrain-*:` trailer gbrain writes (repair, supersedes, adopted). */+const gbrainTrailer = (message: string) => /^gbrain-[a-z][a-z-]*:\s/m.test(message.trim().split(/\n[ \t]*\n/).at(-1) ?? '');const canonical = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } };/** Porcelain creation kind of a reflog message; 'excluded' for moves that create nothing locally; 'other' for the rest. */@@ -109,7 +126,7 @@ function checkoutOf(repo: Repo, gitDir: string | null): string {return [...repo.checkouts.values()][0]!.top;}-async function repositories(engine: BrainEngine): Promise<Repo[]> {+async function repositories(engine: BrainEngine): Promise<{ repos: Repo[]; skipped: string[] }> {const roots = new Map<string, string[]>(await sourceRoots(engine));try {const hostId = existingHostIdFor(engine);@@ -124,10 +141,16 @@ async function repositories(engine: BrainEngine): Promise<Repo[]> {}} catch { /* an embedded engine without a host id, or a brain without the managed tables */ }const repos = new Map<string, Repo>();+ const skipped: string[] = [];+ if (roots.size > MAX_ROOTS) skipped.push(`${roots.size - MAX_ROOTS} source root(s) past the ${MAX_ROOTS}-root scan cap were not scanned`);for (const [root, ids] of [...roots].slice(0, MAX_ROOTS)) {if (!existsSync(root)) continue;- const out = git(root, ['rev-parse', '--show-toplevel', '--absolute-git-dir'])?.split('\n');- if (!out?.[0] || !out[1]) continue;+ const probe = gitRun(root, ['rev-parse', '--show-toplevel', '--absolute-git-dir']);+ const out = probe.out?.split('\n');+ if (!out?.[0] || !out[1]) {+ if (probe.timedOut || insideGitCheckout(root)) skipped.push(`${root} could not be read as a Git checkout (git rev-parse ${probe.timedOut ? `timed out after ${GIT_TIMEOUT_MS / 1000} s` : 'failed'})`);+ continue;+ }const [top, gitDir] = [out[0], out[1]];let common = gitDir;try { common = resolve(gitDir, readFileSync(join(gitDir, 'commondir'), 'utf8').trim()); } catch { /* the main git dir */ }@@ -140,7 +163,7 @@ async function repositories(engine: BrainEngine): Promise<Repo[]> {repo.checkouts.set(top, entry);repos.set(key, repo);}- return [...repos.values()];+ return { repos: [...repos.values()], skipped };}/** Paths gbrain is about to commit: queued or running git effects, absolute. */@@ -161,10 +184,12 @@ async function pendingEffectPaths(engine: BrainEngine): Promise<Set<string>> {interface Dirty { path: string; checkout: string; state: 'untracked' | 'modified' | 'deleted' | 'unmerged'; age_ms: number }-function dirtyFiles(c: Checkout, skip: Set<string>, now: number): Dirty[] | null {+/** The dirty page files of one checkout, or why git status could not list them. `timeout` is the caller's share of doctor's budget. */+function dirtyFiles(c: Checkout, skip: Set<string>, now: number, timeout: number): Dirty[] | { failed: string } {const specs = c.roots.includes('') ? ['.'] : c.roots.map(r => `:(literal)${r}`);- const raw = git(c.top, ['status', '--porcelain=v2', '-z', '--untracked-files=all', '--', ...specs]);- if (raw === null) return null;+ const status = gitRun(c.top, ['status', '--porcelain=v2', '-z', '--untracked-files=all', '--', ...specs], undefined, timeout);+ const raw = status.out;+ if (raw === null) return { failed: status.timedOut ? `git status timed out after ${Math.round(timeout / 1000)} s in ${c.top} (a large checkout: run git status there to list its files)` : `git status failed in ${c.top}` };const pending = new Set(readPendingWriteThrough(c.top).map(e => canonical(join(c.top, e.path))));const fields = raw.split('\0');const out: Dirty[] = [];@@ -203,8 +228,13 @@ interface RepoReport {uncovered: number; foreign: ForeignCommit[]; unconfirmed: ForeignCommit[]; unknown: { ref: string; old: string; new: string; time: string }[];}-function scanRepo(repo: Repo, deadline: number): { report: RepoReport; partial: boolean } {- const ledger = readLedger(repo.common);+function scanRepo(repo: Repo, deadline: number): { report: RepoReport; partial: boolean; reason?: string } {+ let ledger: ReturnType<typeof readLedger>;+ try { ledger = readLedger(repo.common); }+ catch (error) {+ const report: RepoReport = { common: repo.common, checkouts: [...repo.checkouts.keys()], ledger: false, window_from: null, ledger_start: null, oldest_reflog: null, uncovered: 0, foreign: [], unconfirmed: [], unknown: [] };+ return { report, partial: true, reason: `the commit ledger in ${ledgerFiles(repo.common).dir} could not be read (${(error as NodeJS.ErrnoException).code ?? (error as Error).message}), so no commit there was attributed` };+ }const ledgered = new Set<string>();const intents: { head_before: string | null; msg: string; t: number; who: string; resolved: boolean }[] = [];let start: number | null = null;@@ -278,7 +308,7 @@ function scanRepo(repo: Repo, deadline: number): { report: RepoReport; partial:if (parents.length > 1) continue;const ct = Number(f[2]);const guard = c.kind === 'plain' ? enforceGuardSince(c.gitDir) : null;- const commit: ForeignCommit = { sha: c.sha, kind: c.kind, guard_bypassed: guard !== null && guard <= ct * 1000, ref: c.ref, time: new Date(ct * 1000).toISOString(), subject: f[4]!, committer: f[3]!, checkout: c.checkout };+ const commit: ForeignCommit = { sha: c.sha, kind: c.kind, guard_bypassed: guard !== null && guard <= ct * 1000, gbrain_trailer: gbrainTrailer(f[5]!), ref: c.ref, time: new Date(ct * 1000).toISOString(), subject: f[4]!, committer: f[3]!, checkout: c.checkout };const digest = messageDigest(f[5]!);const matched = intents.some(t => !t.resolved && t.head_before === (parents[0] ?? null) && t.msg === digest && ct * 1000 >= t.t - 1000 && ct * 1000 - t.t <= UNCONFIRMED_WINDOW_MS);(matched ? report.unconfirmed : report.foreign).push(commit);@@ -295,8 +325,8 @@ async function runForeignWriters(ctx: DoctorContext): Promise<Check[]> {const checks: Check[] = [];ctx.progress.heartbeat('foreign_writers');const engine = connectedEngine(ctx);- const repos = await repositories(engine);- if (!repos.length) {+ const { repos, skipped } = await repositories(engine);+ if (!repos.length && !skipped.length) {checks.push(infoCheck('foreign_writers', 'Not applicable: no registered source on this host is a Git checkout, so there are no commits to attribute (the database is the record on a repo-less brain).', 'not_applicable'));return checks;}@@ -305,18 +335,22 @@ async function runForeignWriters(ctx: DoctorContext): Promise<Check[]> {const skip = await pendingEffectPaths(engine);const reports: RepoReport[] = [];const dirty: Dirty[] = [];- let partial = false;+ const reasons = [...skipped];+ const budget = () => { if (Date.now() <= deadline) return false; if (!reasons.includes(BUDGET_REASON)) reasons.push(BUDGET_REASON); return true; };for (const repo of repos) {- if (Date.now() > deadline) { partial = true; break; }+ if (budget()) break;const scanned = scanRepo(repo, deadline);reports.push(scanned.report);- partial ||= scanned.partial;+ if (scanned.reason) reasons.push(scanned.reason);+ else if (scanned.partial && !reasons.includes(BUDGET_REASON)) reasons.push(BUDGET_REASON);for (const c of repo.checkouts.values()) {- if (Date.now() > deadline) { partial = true; break; }- const found = dirtyFiles(c, skip, now);- if (found === null) partial = true; else dirty.push(...found);+ if (budget()) break;+ const timeout = Number.isFinite(deadline) ? Math.max(GIT_TIMEOUT_MS, Math.min(STATUS_TIMEOUT_MAX_MS, deadline - Date.now())) : GIT_TIMEOUT_MS;+ const found = dirtyFiles(c, skip, now, timeout);+ if (Array.isArray(found)) dirty.push(...found); else reasons.push(found.failed);}}+ const partial = reasons.length > 0;const isOld = (d: Dirty) => d.age_ms > FOREIGN_DIRTY_WARN_MS;dirty.sort((a, b) => Number(isOld(b)) - Number(isOld(a)) || a.checkout.localeCompare(b.checkout) || a.path.localeCompare(b.path));const foreign = reports.flatMap(r => r.foreign).sort((a, b) => b.time.localeCompare(a.time) || a.sha.localeCompare(b.sha));@@ -325,23 +359,25 @@ async function runForeignWriters(ctx: DoctorContext): Promise<Check[]> {const old = dirty.filter(isOld).sort((a, b) => b.age_ms - a.age_ms);const details = {window: reports.map(r => ({ common: r.common, from: r.window_from, to: new Date(now).toISOString(), ledger_start: r.ledger_start, oldest_reflog: r.oldest_reflog, uncovered: r.uncovered, ledger: r.ledger })),- foreign, unconfirmed, unknown, dirty: dirty.slice(0, MAX_LISTED), dirty_count: dirty.length, dirty_warn_after_minutes: FOREIGN_DIRTY_WARN_MS / 60_000, partial,+ foreign, unconfirmed, unknown, dirty: dirty.slice(0, MAX_LISTED), dirty_count: dirty.length, dirty_warn_after_minutes: FOREIGN_DIRTY_WARN_MS / 60_000, partial, partial_reasons: reasons,};const scope = `${repos.length} repositor${repos.length === 1 ? 'y' : 'ies'}${partial ? ' (partial)' : ''}`;if (foreign.length) {const newest = foreign[0]!;const line = `Commit ${newest.sha.slice(0, 12)} (${label(newest)}, "${newest.subject}", ${newest.time}) in ${newest.checkout} was not made by gbrain; route that writer through gbrain git commit-push or a page write`;+ const trailed = foreign.filter(c => c.gbrain_trailer);+ const older = trailed.length ? ` ${trailed.length} of them carry a gbrain- commit trailer (${trailed.slice(0, 3).map(c => c.sha.slice(0, 12)).join(', ')}): possibly an older gbrain without the commit ledger, co-installed on this host; upgrade every gbrain that writes to this checkout (a trailer alone does not prove gbrain made the commit).` : '';checks.push({ name: 'foreign_writers', status: 'fail', details,- message: `${foreign.length} commit(s) in ${scope} were made by a writer outside gbrain: ${foreign.slice(0, 5).map(c => `${c.sha.slice(0, 12)} ${label(c)} by ${c.committer}`).join(', ')}${foreign.length > 5 ? ', ...' : ''}. ${line}.`,+ message: `${foreign.length} commit(s) in ${scope} were made by a writer outside gbrain: ${foreign.slice(0, 5).map(c => `${c.sha.slice(0, 12)} ${label(c)} by ${c.committer}`).join(', ')}${foreign.length > 5 ? ', ...' : ''}. ${line}.${older}`,fix: { ask_user: true, argv: ['git', '-C', newest.checkout, 'show', '--stat', newest.sha], consent: [], actor: 'user', requires_exclusive: false,- why: `${line}. A commit made around gbrain skips its writer lock and leaves files no import recorded; finding and rerouting the writer (a cron, a script, an agent running plain git) is the user's call.`,+ why: `${line}. A commit made around gbrain skips its writer lock and leaves files no import recorded; finding and rerouting the writer (a cron, a script, an agent running plain git, or an older gbrain without the commit ledger) is the user's call.`,user_message: `A writer outside gbrain committed ${newest.sha.slice(0, 12)} ("${newest.subject}") in ${newest.checkout} at ${newest.time}. Which job or agent makes these commits, so it can be switched to gbrain git commit-push or a page write?`,verify: doctorVerify('foreign_writers') } });return checks;}if (unconfirmed.length || unknown.length || old.length || partial) {const parts = [- partial ? 'the scan did not finish (doctor\'s time budget, or a git status that failed), so part of the window is unchecked' : '',+ partial ? `the scan did not finish (${reasons.join('; ')}), so part of the window is unchecked` : '',unconfirmed.length ? `${unconfirmed.length} commit(s) match a gbrain intent whose commit line is missing (a crash between git commit and the ledger append): ${unconfirmed.slice(0, 5).map(c => c.sha.slice(0, 12)).join(', ')}; they are not written back to the ledger` : '',unknown.length ? `${unknown.length} ref move(s) whose commits could not be read: ${unknown.slice(0, 5).map(u => `${u.ref} -> ${u.new.slice(0, 12)}`).join(', ')}` : '',old.length ? `${old.length} page file(s) have been untracked or modified for more than ${FOREIGN_DIRTY_WARN_MS / 60_000} minutes with no gbrain commit pending: ${old.slice(0, 5).map(d => `${d.path} (${d.state}, ${ago(d.age_ms)})`).join(', ')}${old.length > 5 ? ', ...' : ''}` : '',diff --git a/src/commands/doctor/checks/local-edit-adoptions.ts b/src/commands/doctor/checks/local-edit-adoptions.tsindex 7a4196b60c..fe7bf87805 100644--- a/src/commands/doctor/checks/local-edit-adoptions.ts+++ b/src/commands/doctor/checks/local-edit-adoptions.ts@@ -3,7 +3,8 @@* owner adopted in the last 24 hours (a remember, capture or add_timeline_entry whose page file someone edited outside* gbrain, adopted in its own commit before the write applied). Informational and always ok: adoption is opt-in per* source (`persistence.adopt_local_edits.source.<id>`), and an edit someone keeps making by hand is worth knowing about.- * Paths are source-relative; no page text.+ * Paths are source-relative; no page text. #8755: read from the receipt's `outcome.adopted_local_edit`, which compaction+ * keeps (it drops the intent), so a compacted adoption is still counted.*/import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';@@ -19,8 +20,8 @@ async function runLocalEditAdoptions(ctx: DoctorContext): Promise<Check[]> {const checks: Check[] = [];try {const rows = await engine.executeRaw<{ source_id: string; adoptions: number | string; paths: string[] }>(- `SELECT source_id, count(*)::int AS adoptions, array_agg(DISTINCT intent->>'path' ORDER BY intent->>'path') AS paths FROM persistence_requests- WHERE state='committed' AND operation='put_page' AND intent->>'kind'='managed_file_repair' AND intent ? 'adoptLocalEdit'+ `SELECT source_id, count(*)::int AS adoptions, array_agg(DISTINCT outcome->'adopted_local_edit'->>'path' ORDER BY outcome->'adopted_local_edit'->>'path') AS paths+ FROM persistence_requests WHERE state='committed' AND operation='put_page' AND outcome ? 'adopted_local_edit'AND completed_at > now() - interval '24 hours' GROUP BY source_id ORDER BY source_id`);const sources: SourceAdoptions[] = rows.map(row => ({ source_id: row.source_id, adoptions: Number(row.adoptions), paths: row.paths.slice(0, MAX_PATHS) }));if (!sources.length) {diff --git a/src/commands/git.ts b/src/commands/git.tsindex 51702ed3d6..1ec2af5d9e 100644--- a/src/commands/git.ts+++ b/src/commands/git.ts@@ -12,7 +12,7 @@* gbrain git guard [--install | --uninstall] [--path <dir>] [--json]*/import { existsSync, realpathSync } from 'node:fs';-import { join } from 'node:path';+import { isAbsolute, join, relative, sep } from 'node:path';import { commitAndPush, checkoutRoot, pullShared, scopePaths, COMMIT_LOCK_NAME, SOURCE_ROOT_CONFIG, type Resolution } from '../core/git/commit-push.ts';import { guardStatus, installGuard, uninstallGuard } from '../core/git/commit-guard.ts';import { appendPushLog } from '../core/brain-repo-durability.ts';@@ -22,8 +22,7 @@ import { writeStdoutFinal } from '../core/cli-force-exit.ts';import { execFileSync } from '../core/spawn.ts';import { gitChildEnv } from '../core/git-env.ts';import { GIT_ENV } from '../core/git-transport.ts';-import { managedFilesystemRootFor } from '../core/persistence/filesystem-guard.ts';-import { registeredManagedRootRecords } from '../core/persistence/root-registry.ts';+import { canonicalFilesystemPath, checkoutGitMetadata, managedRootMarkerFor, registeredManagedRootRecords } from '../core/persistence/root-registry.ts';const HELP = `Usage: gbrain git commit-push [--path <dir>] -m <msg> [--json] [--] <paths...>gbrain git commit-push --push-only [--path <dir>] [--branch <b>]@@ -142,11 +141,17 @@ function parseResolutions(specs: string[]): Map<string, Resolution> {* them and carries no mark of a gbrain brain checkout is refused before anything is staged (a wrapper that changed into* another repository). A legacy source is not in that record, so `gbrain sources harden`'s marks admit it: a* gbrain.sourceRoot or gbrain.cliPath entry, or the committed scripts/brain-commit-push.sh (whose own calls pass no --path).- * An explicit --path names its checkout and is not checked here.+ * An explicit --path names its checkout and is not checked here. GST-1623: a registered checkout must contain the resolved+ * one, or be a directory of it that its HEAD tracks; a repository that only encloses a registered checkout (a nested clone)+ * is not a source checkout.*/function assertSourceCheckout(repo: string): void {const registered = registeredManagedRootRecords();- if (!registered.length || managedFilesystemRootFor(repo)) return;+ if (!registered.length || managedRootMarkerFor(repo)) return;+ const top = canonicalFilesystemPath(repo);+ const within = (root: string, path: string) => { const rel = relative(root, path); return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`); };+ const metadata = checkoutGitMetadata(top);+ if (registered.some(record => within(record.root, top) || (within(top, record.root) && metadata !== null && existsSync(record.root) && checkoutGitMetadata(record.root) === metadata))) return;if (existsSync(join(repo, 'scripts', 'brain-commit-push.sh'))) return;try {execFileSync('git', ['-C', repo, 'config', '--local', '--get-regexp', `^(${SOURCE_ROOT_CONFIG}|gbrain.clipath)$`.replace(/\./g, '\\.').toLowerCase()], { env: gitChildEnv({ ...GIT_ENV }), stdio: ['ignore', 'pipe', 'ignore'] });diff --git a/src/core/git/commit-guard.ts b/src/core/git/commit-guard.tsindex fb3415422e..6a86d8c132 100644--- a/src/core/git/commit-guard.ts+++ b/src/core/git/commit-guard.ts@@ -44,7 +44,9 @@ ${enforce ? `${GUARD_ENFORCE_MARKER}[ "\${${GUARD_BYPASS_ENV}:-}" = off ] && exit 0[ "\${2:-}" = merge ] && exit 0${owner ? `# git worktree add copies config.worktree, so a worktree added after the install inherits this hooks path: only the owner worktree is guarded.-[ "$(cd "$(git rev-parse --absolute-git-dir)" && pwd -P)" = "$(cd "$(dirname "$0")/.." && pwd -P)" ] || exit 0+# GST-1623: a git dir git cannot name fails closed; only a hook that belongs to another git dir passes.+_gd="$(git rev-parse --absolute-git-dir 2>/dev/null)" && [ -n "$_gd" ] && _gd="$(cd "$_gd" && pwd -P)" || { echo "gbrain commit guard: could not resolve this checkout's git dir, so the commit was refused; nothing changed." >&2; exit 1; }+[ "$_gd" = "$(cd "$(dirname "$0")/.." && pwd -P)" ] || exit 0` : ''}for _op in ${enforce ? 'MERGE_HEAD' : 'MERGE_HEAD CHERRY_PICK_HEAD REVERT_HEAD rebase-merge rebase-apply sequencer'}; do[ -e "$(git rev-parse --git-path "$_op")" ] && exit 0donediff --git a/src/core/git/commit-ledger.ts b/src/core/git/commit-ledger.tsindex 845314c9e3..51a3c630af 100644--- a/src/core/git/commit-ledger.ts+++ b/src/core/git/commit-ledger.ts@@ -168,13 +168,18 @@ export async function recordIntentAsync(root: string, intent: LedgerIntent): Proawait writeLockedAsync(root, loc => intentRecord(loc, intent));}-/** The retained ledger lines, oldest first (the rotated file, then the current one); unparseable lines are skipped. */+/**+ * The retained ledger lines, oldest first (the rotated file, then the current one); unparseable lines are skipped. Only a+ * missing file reads as empty: any other read error throws (GST-1623), so doctor never reads an unreadable ledger as+ * "nothing ledgered".+ */export function readLedger(common: string): LedgerRecord[] {const files = ledgerFiles(common);const out: LedgerRecord[] = [];for (const file of [files.rotated, files.current]) {let text: string;- try { text = readFileSync(file, 'utf8'); } catch { continue; }+ try { text = readFileSync(file, 'utf8'); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; throw error; }for (const raw of text.split('\n')) {if (!raw) continue;try {diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex bc9c92d8c1..3daf1acb81 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -398,6 +398,7 @@ export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteRe// GST-1601: with persistence.adopt_local_edits on for the source, a one-sided local edit is adopted and the write prepared again.const adoption = await adoptLocalEdit(engine, row, error);if (adoption && 'released' in adoption) return adoption.released;+ if (adoption && 'claimLost' in adoption) return adoption.claimLost;const failure = withAttempt(requestError(adoption?.error ?? error), stage, engine);// GST-1582: with the refresh barrier on, a write refused because its file awaits an import waits for that import instead.const held = failure.code === 'source_changed' ? await holdForImport(engine, row, error) : null;diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.tsindex 9cf2017fb3..8aeae54a79 100644--- a/src/core/persistence/file-repair.ts+++ b/src/core/persistence/file-repair.ts@@ -75,7 +75,7 @@ import type { SyncRename } from './sync-discovery.ts';import type { PreparedContentImport } from './prepared-import.ts';import type { PreparedMutation } from './coordinator.ts';import { contentRepairCommit, fenceRepairCommit, localEditAdoptionCommit } from './effect-model.ts';-import { ADOPTED_CHANGE_REASON, adoptedHeadHolds, commitAdoptedLocalEdit } from './local-edit-adoption.ts';+import { ADOPTED_CHANGE_REASON, adoptedHeadHolds, assertAdoptionCaller, commitAdoptedLocalEdit } from './local-edit-adoption.ts';import { recordSlugLineAlias } from '../page-state/rename-alias.ts';import type { WriteRequest } from './model.ts';import { bindOrigin } from './origin-guard.ts';@@ -105,7 +105,7 @@ export interface ManagedFileRepairIntent extends Record<string, unknown> {/** #6696 C8: the hold observation the repair read; the publication clears the path's hold only while it is that observation (a newer hold stays). */holdObservedAt?: string;/** GST-1601: an adopted one-sided local edit (local-edit-adoption.ts): the worktree blob and the revision it replaces. */- adoptLocalEdit?: { blob: string; replaced_revision: string; head: string | null };+ adoptLocalEdit?: { blob: string; replaced_revision: string; head: string | null; caller?: { id: string; token: string | null } };}/** The repair command a refusal names (D6 router): a fence repair's, the content repair's, or the frontmatter repair's. */@@ -334,6 +334,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:if (adopted !== undefined && (typeof adopted?.blob !== 'string' || typeof adopted.replaced_revision !== 'string' || (typeof adopted.head !== 'string' && adopted.head !== null) || p.expected_revision !== adopted.replaced_revision)) {throw opError('invalid_params', 'The local edit adoption intent is incomplete.', `Adoption request ${row.request_id} in source ${row.source_id} names no worktree blob or replaced revision, so it published nothing.`);}+ if (adopted) await assertAdoptionCaller(engine, row, adopted.caller);const binding = await getWorktreeBinding(engine, row.source_id);if (!row.worktree_id || !binding?.local_path || String(binding.owner_epoch) !== p.ownerEpoch) throw opError('owner_unavailable', 'A managed file repair requires its accepted canonical owner.',`Source ${row.source_id}'s canonical owner changed or went away after repair request ${row.request_id} was accepted, so it published nothing. Check the owner, then preview the repair again on the host that owns the source.`,@@ -394,7 +395,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:`Source ${row.source_id}'s canonical owner changed while repair request ${row.request_id} was prepared, so it published nothing. Check the owner, then preview the repair again.`,{ fix: ownerStatusFix(row.source_id) });checkFile();- if (adopted && !await adoptedHeadHolds(binding, root, target, adopted.head)) throw changedSincePreview(row.source_id, p.path, 'git HEAD moved after its local edit was read', kind);+ if (adopted && !await adoptedHeadHolds(binding, root, target, adopted.head, adopted.blob)) throw changedSincePreview(row.source_id, p.path, 'git HEAD moved after its local edit was read', kind);if (contentRepair?.declared_alias) await assertDeclaredSlugAbsent(tx, row.source_id, root, p, contentRepair.declared_alias, row.slug, kind);await assertRenameSource(tx);await ready.validate(tx);diff --git a/src/core/persistence/local-edit-adoption.ts b/src/core/persistence/local-edit-adoption.tsindex eb8d13b4e7..4e896fd88a 100644--- a/src/core/persistence/local-edit-adoption.ts+++ b/src/core/persistence/local-edit-adoption.ts@@ -17,13 +17,28 @@* neither the database's copy nor any entry), a file that does not import cleanly, and an edit to the title, the type or* a protected frontmatter key (page-prepare.ts protectedLocalEdit). A file still changing is adopted only once it has* been quiet for `persistence.adopt_quiet_ms` (default 5000); one that is not quiet within three windows keeps the refusal.+ *+ * #8755 hardening: the quiet wait is capped at the foreground preparation budget (30 s), since the caller's running claim+ * holds its worktree's queue meanwhile; a file over PAGE_MAX_BYTES (checked before it is read) or a page stored in+ * segments keeps the refusal; so do an unmerged path or a merge, cherry-pick, revert or rebase in progress, a file equal to+ * an earlier stored revision, and one missing a Facts or timeline row the last revision added (a stale editor buffer+ * saved over gbrain's write). The repo-less test walks up for `.git` (a source in a subdirectory of its repository). A+ * publication that failed after the adoption's commit landed is requeued by recovery and published again (its validate+ * accepts HEAD holding the adopted blob; the commit is then named, not repeated). An adoption another task is+ * publishing is waited on, never left to commit after its caller was refused. The adoption names its caller's claim and+ * publishes nothing once that claim is gone (a crash between admission and settling); its own claim carries the owner+ * stamp like any other. A caller whose claim was lost meanwhile is reported as such, never as released.*/import { randomUUID } from 'node:crypto';import { existsSync, readFileSync, statSync } from 'node:fs';-import { join, relative, sep } from 'node:path';+import { dirname, join, relative, resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';-import { OperationError, type OperationContext } from '../ops/contract.ts';+import { OperationError, opError, type OperationContext } from '../ops/contract.ts';+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';+import { parseMarkdown } from '../markdown.ts';+import type { PageSnapshot } from '../page-state/types.ts';import { gitBlobOid, sha256 } from './digest.ts';import { commitGitTargets } from './effect-git.ts';import { sourceCanonicalGit } from './git-door.ts';@@ -35,7 +50,8 @@ import { declarePersistenceProtocol } from './protocol.ts';import type { WorktreeBinding } from './ownership.ts';import { getWorktreeBinding } from './ownership.ts';import { fileMatchesSnapshot, protectedLocalEdit } from './page-prepare.ts';-import { blobText, headBlob, headCommit } from './pending-import.ts';+import { blobText, headBlob, headCommit, landedCommit, mergeInProgress, unmergedPath } from './pending-import.ts';+import { claimOwner } from './claim-phase.ts';import type { PreparedMutation } from './coordinator.ts';import type { GitCommitNote } from './effect-model.ts';@@ -44,12 +60,18 @@ export const ADOPT_QUIET_KEY = 'persistence.adopt_quiet_ms';const ADOPT_QUIET_DEFAULT_MS = 5_000;/** A file is waited on for at most this many quiet windows. */const QUIET_WINDOWS = 3;+/** #8755: the inline quiet wait never passes the foreground preparation budget: the caller's claim holds its worktree queue. */+const ADOPT_WAIT_MAX_MS = 30_000;/** How long the adoption retries a worktree lock another owner task holds. */const LOCK_RETRY_MS = 10_000;+/** #8755: how long an adoption another task is publishing is waited on past LOCK_RETRY_MS before the caller keeps its refusal. */+const PUBLISHING_WAIT_MS = 120_000;+/** Earlier stored revisions a stale editor save is compared with. */+const STALE_REVISIONS = 50;const ADOPTING_OPERATIONS: readonly string[] = ['remember', 'capture', 'add_timeline_entry'];-/** Test seam: runs between the adoption's preparation and its publication, with the file's path. */-export const localEditAdoptionSeams: { beforePublish?: (path: string) => void } = {};+/** Test seams: `beforePublish` runs between the adoption's preparation and its publication, with the file's path; `maxWaitMs` lowers the quiet-wait cap. */+export const localEditAdoptionSeams: { beforePublish?: (path: string) => void; maxWaitMs?: number } = {};/** The drifted file a `file_database_drift` refusal carries (page-prepare.ts compareFileTarget). */interface LocalEditTarget { root: string; path: string }@@ -60,18 +82,28 @@ export async function adoptLocalEditsOn(engine: BrainEngine, sourceId: string):return ['1', 'true', 'yes', 'on'].includes(String(value ?? '').trim().toLowerCase());}async function quietMs(engine: BrainEngine): Promise<number> {- const value = Number(await engine.getConfig(ADOPT_QUIET_KEY).catch(() => null) ?? ADOPT_QUIET_DEFAULT_MS);+ const raw = String(await engine.getConfig(ADOPT_QUIET_KEY).catch(() => null) ?? '').trim();+ const value = raw ? Number(raw) : ADOPT_QUIET_DEFAULT_MS;return Number.isFinite(value) && value >= 0 ? Math.min(value, 60_000) : ADOPT_QUIET_DEFAULT_MS;}+/** #8755: whether a `.git` entry sits at `root` or above it (reconcile-state.ts insideGitCheckout): only a brain with none is repo-less. */+function insideGitCheckout(root: string): boolean {+ for (let dir = resolve(root); ; dir = dirname(dir)) {+ if (existsSync(join(dir, '.git'))) return true;+ if (dirname(dir) === dir) return false;+ }+}+const logAdoption = (row: WriteRequest, reason: string, error: unknown) => process.stderr.write(`[persistence] phase=adoption reason=${reason} source=${row.source_id} request=${row.request_id} `+ + `message="${String(error instanceof Error ? error.message : error).replace(/\s+/g, ' ').slice(0, 300)}"; the write keeps its file_database_drift refusal\n`);/** The adoption's request id, derived from the caller's write so a write adopts at most once. */function adoptionRequestId(row: Pick<WriteRequest, 'id'>): string {const h = sha256(`gbrain:adopt-local-edit:${row.id}`);return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${(8 + (parseInt(h[16]!, 16) & 3)).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}`;}-/** Waits until `path` has not changed for the quiet window; false when it is still changing after QUIET_WINDOWS windows. */+/** Waits until `path` has not changed for the quiet window; false when it is still changing after QUIET_WINDOWS windows or the cap. */async function settled(path: string, quiet: number): Promise<boolean> {- const deadline = Date.now() + quiet * QUIET_WINDOWS;+ const deadline = Date.now() + Math.min(quiet * QUIET_WINDOWS, localEditAdoptionSeams.maxWaitMs ?? ADOPT_WAIT_MAX_MS);for (;;) {const age = Date.now() - statSync(path).mtimeMs;if (age >= quiet) return true;@@ -80,26 +112,52 @@ async function settled(path: string, quiet: number): Promise<boolean> {}}+/** Body lines that are Facts or timeline fence rows (list items and table rows, not a table's separator line). */+function fenceRows(...texts: Array<string | null | undefined>): Set<string> {+ return new Set(texts.flatMap(text => (text ?? '').split('\n')).map(line => line.trim()).filter(line => /^(- |\|)/.test(line) && !/^\|[\s:|-]*\|?$/.test(line)));+}+/**+ * #8755: a stale editor save: the file equals an earlier stored revision's body, or lacks a Facts or timeline row the last+ * revision added (rows the page holds that its newest archived version, the revision before, did not).+ */+async function staleEditorSave(engine: BrainEngine, slug: string, text: string, snapshot: PageSnapshot, activePack: unknown): Promise<boolean> {+ const file = parseMarkdown(text, slug, { activePack } as never);+ const body = (compiled: string | null | undefined, timeline: string | null | undefined) => `${(compiled ?? '').trim()}\0${(timeline ?? '').trim()}`;+ const versions = await engine.executeRaw<{ compiled_truth: string | null; timeline: string | null }>(+ 'SELECT compiled_truth, timeline FROM page_versions WHERE page_id=$1 AND compiled_truth IS NOT NULL ORDER BY id DESC LIMIT $2', [snapshot.page.id, STALE_REVISIONS]);+ const current = body(snapshot.page.compiled_truth, snapshot.page.timeline);+ const mine = body(file.compiled_truth, file.timeline);+ if (mine !== current && versions.some(version => body(version.compiled_truth, version.timeline) === mine)) return true;+ if (!versions.length) return false;+ const before = fenceRows(versions[0]!.compiled_truth, versions[0]!.timeline);+ const kept = fenceRows(file.compiled_truth, file.timeline);+ return [...fenceRows(snapshot.page.compiled_truth, snapshot.page.timeline)].some(line => !before.has(line) && !kept.has(line));+}+/** What adopting the edit to `target` admits, or null when the edit is not one-sided and safe. */async function adoptionIntent(engine: BrainEngine, row: WriteRequest, target: LocalEditTarget, binding: WorktreeBinding) {const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });const sourcePath = snapshot?.page.source_path;- if (!snapshot || !sourcePath || snapshot.page.deleted_at) return null;+ if (!snapshot || !sourcePath || snapshot.page.deleted_at || isSegmentedPage(snapshot.page)) return null;+ if (statSync(target.path).size > PAGE_MAX_BYTES) return null;const bytes = readFileSync(target.path);const text = bytes.toString('utf8');// An edit whose bytes do not decode losslessly would be rewritten by its own adoption, so it keeps the refusal.if (!Buffer.from(text, 'utf8').equals(bytes)) return null;const commit = await headCommit(target.root);// A checkout whose HEAD git cannot read keeps the refusal; only a brain with no repository has no HEAD to ask.- if (!commit && existsSync(join(binding.local_path!, '.git'))) return null;+ if (!commit && insideGitCheckout(binding.local_path!)) return null;const head = commit ? await headBlob(target.root, target.path) : undefined;if (head === null) return null;- // A checkout whose HEAD holds the database's copy: only the worktree file moved. A repo-less brain has no HEAD to ask.- const committed = head ? await blobText(target.root, head) : null;- if (head && (committed === null || !await fileMatchesSnapshot(engine, row.slug, committed, snapshot, sourcePath))) return null;+ // Conflict markers from a merge, stash pop, cherry-pick or rebase are never adopted (`git add` would mark them resolved).+ if (commit && (await unmergedPath(target.root, target.path) !== false || await mergeInProgress(target.root) !== false)) return null;const { prepareRepairPublication, repairScreenConfig } = await import('./file-repair.ts');const screen = await repairScreenConfig(engine, row.source_id);+ // A checkout whose HEAD holds the database's copy: only the worktree file moved. A repo-less brain has no HEAD to ask.+ const committed = head ? await blobText(target.root, head) : null;+ if (head && (committed === null || !await fileMatchesSnapshot(engine, row.slug, committed, snapshot, sourcePath, screen.activePack))) return null;if (await protectedLocalEdit(engine, row.slug, text, snapshot, screen.activePack)) return null;+ if (await staleEditorSave(engine, row.slug, text, snapshot, screen.activePack)) return null;const path = relative(target.root, target.path).split(sep).join('/');const publication = await prepareRepairPublication(engine, { sourceId: row.source_id, slug: row.slug, sourcePath, path, root: target.root,content: text, snapshot, base: snapshot, ...screen });@@ -107,7 +165,8 @@ async function adoptionIntent(engine: BrainEngine, row: WriteRequest, target: Loconst adopted: AdoptedLocalEdit = { path, blob: gitBlobOid(bytes, head?.length === 64 ? 'sha256' : 'sha1'), replaced_revision: snapshot.revision };return { adopted, params: { kind: 'managed_file_repair', slug: row.slug, path, sourcePath, content: text, beforeHash: sha256(bytes),resultDigest: publication.digest, ownerEpoch: String(binding.owner_epoch), expected_revision: snapshot.revision, noEmbed: true,- adoptLocalEdit: { blob: adopted.blob, replaced_revision: adopted.replaced_revision, head: head ?? null }, source_id: row.source_id, request_id: adoptionRequestId(row) } };+ adoptLocalEdit: { blob: adopted.blob, replaced_revision: adopted.replaced_revision, head: head ?? null, caller: { id: row.id, token: row.execution_token } },+ source_id: row.source_id, request_id: adoptionRequestId(row) } };}/** Whether the caller still holds the claim its refusal is being answered under (a cancelled caller adopts nothing). */@@ -116,9 +175,28 @@ async function callerHolds(engine: BrainEngine, caller: WriteRequest): Promise<b[caller.id, caller.execution_token])).length > 0;}-/** Publication's recheck (file-repair.ts validate): HEAD still holds the blob the adoption read, so no newer commit is overwritten. */-export async function adoptedHeadHolds(binding: WorktreeBinding, root: string, path: string, head: string | null): Promise<boolean> {- return head === null ? !existsSync(join(binding.local_path!, '.git')) : await headBlob(root, path) === head;+/**+ * Publication's recheck (file-repair.ts validate): HEAD still holds the blob the adoption read, so no newer commit is+ * overwritten; or the adopted blob itself (#8755: this adoption's own commit landed before a publication that failed+ * after it, and recovery requeued it).+ */+export async function adoptedHeadHolds(binding: WorktreeBinding, root: string, path: string, head: string | null, blob?: string): Promise<boolean> {+ if (head === null) return !insideGitCheckout(binding.local_path!);+ const current = await headBlob(root, path);+ return current === head || (blob !== undefined && current === blob);+}++/**+ * #8755: the claim an adoption is made under (`adoptLocalEdit.caller`) still holds, checked as the adoption prepares: an+ * adoption whose caller is gone (cancelled, finished, or reclaimed after a crash between admission and settling)+ * publishes nothing.+ */+export async function assertAdoptionCaller(engine: BrainEngine, row: WriteRequest, caller: { id?: unknown; token?: unknown } | undefined): Promise<void> {+ if (!caller) return;+ const [held] = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE id=$1::uuid AND state='running' AND execution_token=$2::uuid`, [String(caller.id), String(caller.token)]);+ if (held) return;+ throw opError('write_claim_lost', 'The write this local edit adoption was made for no longer waits on it.',+ `Adoption request ${row.request_id} in source ${row.source_id} belongs to a write whose claim ended (it was cancelled, finished, or reclaimed after its process stopped), so the local edit was not adopted and nothing was written.`);}/** Claims, prepares and publishes the admitted adoption, retrying while another owner task holds the worktree lock. */@@ -132,7 +210,8 @@ async function publishAdoption(engine: BrainEngine, caller: WriteRequest, admittconst [claimed] = await engine.transaction(async tx => {await declarePersistenceProtocol(tx);return tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,- claim_expires_at=now()+interval '60 seconds',updated_at=now(),blocked_reason=NULL WHERE id=$1::uuid AND state='queued' RETURNING *`, [row.id, randomUUID()]);+ claim_expires_at=now()+interval '60 seconds',updated_at=now(),blocked_reason=NULL,+ claim_phase=jsonb_build_object('token',$2::text,'owner',$3::text::jsonb,'claimed_at',to_jsonb(now())) WHERE id=$1::uuid AND state='queued' RETURNING *`, [row.id, randomUUID(), JSON.stringify(claimOwner())]);});if (!claimed) return (await getWriteRequestById(engine, row.id))!;try {@@ -140,7 +219,8 @@ async function publishAdoption(engine: BrainEngine, caller: WriteRequest, admittlocalEditAdoptionSeams.beforePublish?.(path);row = await publishMutation(engine, claimed, prepared);} catch (error) { row = await finishUnpublishedFailure(engine, claimed, error, 'preparation'); }- if (isTerminal(row) || Date.now() > deadline || !['writer_busy', 'writer_pool_capacity'].includes(row.blocked_reason ?? '')) return row;+ // #8755: any release is retried, a publication recovery requeued after the adoption's commit landed included.+ if (isTerminal(row) || Date.now() > deadline || row.state !== 'queued') return row;await new Promise(resolve => setTimeout(resolve, 100));}}@@ -148,6 +228,8 @@ async function publishAdoption(engine: BrainEngine, caller: WriteRequest, admitt/*** An adoption `publishAdoption` left unfinished (still blocked on the worktree lock, or claimed by the resident consumer* before its publication started) is cancelled, so a caller that keeps its refusal never has its local edit adopted later.+ * #8755: one whose publication another task already started (or a recovery record holds) cannot be cancelled; it is+ * waited on for PUBLISHING_WAIT_MS more, so it does not commit after its caller was refused.*/async function settleAdoption(engine: BrainEngine, row: WriteRequest): Promise<WriteRequest> {if (isTerminal(row)) return row;@@ -155,7 +237,9 @@ async function settleAdoption(engine: BrainEngine, row: WriteRequest): Promise<Wconst deadline = Date.now() + LOCK_RETRY_MS;for (;;) {const current = await cancelWriteRequest(engine, requestPrincipal(row), row.request_id) ?? row;- if (isTerminal(current) || Date.now() > deadline) return current;+ if (isTerminal(current)) return current;+ const publishing = current.publication_started || current.recovery != null;+ if (Date.now() > deadline + (publishing ? PUBLISHING_WAIT_MS : 0)) return current;await new Promise(resolve => setTimeout(resolve, 100));}}@@ -165,7 +249,7 @@ async function settleAdoption(engine: BrainEngine, row: WriteRequest): Promise<W* is adopted and the write queued to prepare again, `error` when the adoption found the file changed under it (the* write ends with that refusal), null when the write keeps its own refusal.*/-export async function adoptLocalEdit(engine: BrainEngine, row: WriteRequest, error: unknown): Promise<{ released: WriteRequest } | { error: OperationError } | null> {+export async function adoptLocalEdit(engine: BrainEngine, row: WriteRequest, error: unknown): Promise<{ released: WriteRequest } | { claimLost: WriteRequest } | { error: OperationError } | null> {const target = (error as { localEdit?: LocalEditTarget } | null)?.localEdit;if (!target || !(error instanceof OperationError) || error.code !== 'source_changed' || error.detail !== 'file_database_drift' || error.reason|| !ADOPTING_OPERATIONS.includes(row.operation) || (row.target_kind ?? 'page') !== 'page' || !row.worktree_id || row.intent?.adopted_local_edit@@ -187,17 +271,20 @@ export async function adoptLocalEdit(engine: BrainEngine, row: WriteRequest, errconst prepared = await preparePageAdmission(ctx, { operation: 'put_page', params, managedFileImport: true });return prepared.prior ? null : admitWrite(engine, prepared.admission);});- } catch { return null; }+ } catch (failure) { logAdoption(row, 'admission_failed', failure); return null; }if (!admitted) return null;const done = await settleAdoption(engine, await publishAdoption(engine, row, admitted, target.path));if (done.state === 'committed') {- await engine.transaction(async tx => {+ // #8755: the release is fenced on the caller's token; a claim lost meanwhile is reported as lost, never as released.+ const kept = await engine.transaction(async tx => {await declarePersistenceProtocol(tx);- await tx.executeRaw(`UPDATE persistence_requests SET intent=intent||$3::text::jsonb WHERE id=$1::uuid AND execution_token=$2::uuid AND state='running'`,+ const [held] = await tx.executeRaw(`UPDATE persistence_requests SET intent=intent||$3::text::jsonb WHERE id=$1::uuid AND execution_token=$2::uuid AND state='running' RETURNING id`,[row.id, row.execution_token, JSON.stringify({ adopted_local_edit: admission.adopted })]);- await releaseUnpublishedClaim(tx, row, 'local_edit_adopted');+ if (held) await releaseUnpublishedClaim(tx, row, 'local_edit_adopted');+ return !!held;});- return { released: (await getWriteRequestById(engine, row.id))! };+ const current = (await getWriteRequestById(engine, row.id))!;+ return kept ? { released: current } : { claimLost: current };}if (done.error_code === 'source_changed' && (done.error_detail as { origin?: string } | null)?.origin === 'raw_file_changed') {return { error: new OperationError('source_changed', done.error_message ?? 'The canonical file changed after preparation.',@@ -218,6 +305,11 @@ export async function commitAdoptedLocalEdit(tx: BrainEngine, sourceId: string,const result = (await commitGitTargets(root, [rel], undefined, new Map([[rel, note]]))).get(rel);if (result instanceof OperationError) throw result;if (result?.git === 'committed') Object.assign(outcome.persistence as object, { git_state: 'committed', git_commit: await headCommit(root) });+ // #8755: a replay after the commit landed (validate accepted HEAD holding the adopted blob) names that commit.+ else if (result?.git === 'unchanged') {+ const landed = await landedCommit(root, null, path);+ if (landed) Object.assign(outcome.persistence as object, { git_state: 'committed', git_commit: landed, landed_before_row: true });+ }}/** A write prepared again after its local edit was adopted names the adoption on its receipt (`adopted`). */diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.tsindex 947d75ddb2..841c548c93 100644--- a/src/core/persistence/pending-import.ts+++ b/src/core/persistence/pending-import.ts@@ -17,6 +17,7 @@* is resubmitted by its caller after that sync.*/import { spawn } from '../spawn.ts';+import { existsSync } from 'node:fs';import { relative, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';@@ -120,6 +121,20 @@ export async function landedCommit(root: string, from: string | null, path: strireturn quiet(gitRead(root, ['rev-list', '-1', from ? `${from}..HEAD` : 'HEAD', '--', `:(literal)${relative(root, path).split(sep).join('/')}`]));}+/** #8755: whether the index holds unmerged stages for `path` (a conflict); null when Git cannot read it. */+export async function unmergedPath(root: string, path: string, signal?: AbortSignal): Promise<boolean | null> {+ return gitRead(root, ['ls-files', '-u', '-z', '--', `:(literal)${relative(root, path).split(sep).join('/')}`], signal)+ .then(out => out.length > 0, error => { if (signal?.aborted) throw error; return null; });+}++/** #8755: whether a merge, cherry-pick, revert or rebase is in progress in `root`'s checkout; null when Git cannot say. */+export async function mergeInProgress(root: string, signal?: AbortSignal): Promise<boolean | null> {+ const markers = ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'rebase-merge', 'rebase-apply'];+ return gitRead(root, ['rev-parse', '--path-format=absolute', ...markers.flatMap(marker => ['--git-path', marker])], signal)+ .then(out => { const paths = out.split('\n').filter(Boolean); return paths.length === markers.length ? paths.some(path => existsSync(path)) : null; },+ error => { if (signal?.aborted) throw error; return null; });+}+/** The commit HEAD names in `root`, or null on an unborn branch or when Git cannot read it. */export async function headCommit(root: string, signal?: AbortSignal): Promise<string | null> {return quiet(gitRead(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], signal), signal);diff --git a/src/core/persistence/root-registry.ts b/src/core/persistence/root-registry.tsindex 3f89699e8f..24498076e4 100644--- a/src/core/persistence/root-registry.ts+++ b/src/core/persistence/root-registry.ts@@ -180,7 +180,13 @@ export function registeredManagedRootRecords(): Array<{ root: string; source_id?const directory = registryDirectory();let files: string[];try { files = readdirSync(directory); }- catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; }+ catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code === 'ENOENT') return [];+ // GST-1623: an unlistable registry is a typed refusal, never a raw error.+ throw opError('writer_coordinator_required', 'Managed-root ownership records cannot be listed.',+ `gbrain could not read ${directory} (${code ?? 'unknown error'}), so it cannot tell which checkouts this brain manages and refuses the command. Fix the path's permissions for this user (or move aside a file standing where that directory belongs), then run the command again.`);+ }const records: Array<{ root: string; source_id?: string }> = [];for (const file of files.filter(file => file.endsWith('.json'))) {try {diff --git a/test/adopt-local-edit.test.ts b/test/adopt-local-edit.test.tsindex 527aa6b7eb..f89d85affc 100644--- a/test/adopt-local-edit.test.ts+++ b/test/adopt-local-edit.test.ts@@ -16,8 +16,9 @@* worker run in-process, `localEditAdoptionSeams.beforePublish`.*/import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';import { createHash, randomUUID } from 'node:crypto';-import { readFileSync, writeFileSync } from 'node:fs';+import { readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { acquireWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';import type { BrainEngine } from '../src/core/engine.ts';@@ -399,3 +400,139 @@ test('a repo-less brain adopts the edit into the database alone', async () => {expect(versions.some(v => v.change_reason === 'adopted_local_edit')).toBe(true);}, backend === 'postgres' ? { databaseUrl: process.env.DATABASE_URL } : {});}, 180_000);++// ── #8755 hardening ─────────────────────────────────────────────────────────++test('#8755 a: a write to another page on the same worktree is not held for the full quiet bound behind an adoption whose file never settles', () => each(async f => {+ const { localEditAdoptionSeams } = await import('../src/core/persistence/local-edit-adoption.ts');+ localEditAdoptionSeams.maxWaitMs = 1500;+ let n = 0;+ const touch = () => writeFileSync(join(f.root, 'alpha', 'one.md'), page('Alpha one', `The first alpha observation.\n\n${LOCAL} ${n++}`));+ touch();+ const timer = setInterval(touch, 100);+ try {+ const pending = timeline(f)().catch(() => undefined);+ for (let i = 0; i < 100 && !(await f.engine.executeRaw("SELECT 1 FROM persistence_requests WHERE operation='add_timeline_entry' AND source_id=$1 AND state='running'", [f.alpha])).length; i++) await new Promise(resolve => setTimeout(resolve, 50));+ const started = Date.now();+ const other = await local(f, 'put_page', { slug: 'two', content: page('Alpha two', 'Another page on the same worktree.') });+ let row: WriteRequest | undefined;+ for (let i = 0; i < 150; i++) {+ [row] = await f.engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE request_id=$1::uuid", [other.request_id]);+ if (row && isTerminal(row)) break;+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ expect(row?.state).toBe('committed');+ expect(Date.now() - started).toBeLessThan(15_000);+ await pending;+ } finally { clearInterval(timer); localEditAdoptionSeams.maxWaitMs = undefined; }+ expect((await adoptionRows(f)).filter(r => r.state === 'committed')).toEqual([]);+}, { quietMs: 60_000 }), 180_000);++test('#8755 b: a publication that fails after the adoption\'s commit is recovered: the adoption commits once and the caller lands', () => each(async f => {+ const { installFaultHook } = await import('../src/core/persistence/fault-points.ts');+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);+ const blob = blobOf(f, 'one.md'), replaced = await revision(f, 'one');+ let fired = 0;+ installFaultHook((point, detail) => {+ if (point === 'publication:before_commit' && detail.operation === 'put_page' && detail.sourceId === f.alpha && fired++ === 0) {+ throw Object.assign(new Error('could not serialize access due to concurrent update'), { code: '40001' });+ }+ });+ try { await timeline(f)().catch(() => undefined); } finally { installFaultHook(undefined); }+ expect(fired).toBeGreaterThan(0);+ const done = await settled(f.engine, await lastRow(f, 'add_timeline_entry'));+ await expectAdopted(f, done, 'one.md', 'one', blob, replaced, 'Must not land.');+ expect(git(f.root, 'log', '--format=%s', '--', 'alpha/one.md').split('\n').filter(s => s.includes('adopt local edit'))).toHaveLength(1);+ const [adoption] = await adoptionRows(f);+ expect((adoption!.outcome as { persistence?: { git_commit?: string } }).persistence?.git_commit).toBeTruthy();+}), 180_000);++test('#8755 c: conflict markers keep the refusal: an unmerged path, and a merge in progress', () => each(async f => {+ const MARKERS = page('Alpha one', `The first alpha observation.\n\n<<<<<<< HEAD\nours\n=======\n${LOCAL}\n>>>>>>> side`);+ const base = git(f.root, 'rev-parse', 'HEAD:alpha/one.md');+ writeFileSync(join(f.root, 'theirs.tmp'), page('Alpha one', `The first alpha observation.\n\n${LOCAL}`));+ const theirs = git(f.root, 'hash-object', '-w', 'theirs.tmp');+ git(f.root, 'update-index', '--force-remove', 'alpha/one.md');+ execFileSync('git', ['-C', f.root, 'update-index', '--index-info'], { input: `100644 ${base} 1\talpha/one.md\n100644 ${base} 2\talpha/one.md\n100644 ${theirs} 3\talpha/one.md\n` });+ await expectRefused(f, MARKERS, timeline(f), 'add_timeline_entry');+ git(f.root, 'update-index', '--add', '--cacheinfo', `100644,${base},alpha/one.md`);+ writeFileSync(join(f.root, '.git', 'MERGE_HEAD'), `${head(f)}\n`);+ try { await expectRefused(f, EDITED, timeline(f), 'add_timeline_entry'); } finally { rmSync(join(f.root, '.git', 'MERGE_HEAD'), { force: true }); }+}), 180_000);++test('#8755 d: a stale editor save keeps the refusal: the earlier revision as it was, and one missing the row gbrain added', () => each(async f => {+ const before = file(f, 'one.md');+ const out = await call(f, 'add_timeline_entry', { slug: 'one', date: '2026-11-06', summary: 'Entry gbrain added.' });+ expect(out.isError).toBe(false);+ const added = await settled(f.engine, await lastRow(f, 'add_timeline_entry'));+ expect(added.state).toBe('committed');+ await gitEffectDone(f, added.id);+ expect(git(f.root, 'show', 'HEAD:alpha/one.md')).toContain('Entry gbrain added.');+ await expectRefused(f, before, timeline(f), 'add_timeline_entry');+ await expectRefused(f, before.replace('The first alpha observation.', `The first alpha observation.\n\n${LOCAL}`), timeline(f), 'add_timeline_entry');+}), 180_000);++test('#8755 e: a file over the page size limit keeps the refusal', () => each(async f => {+ const { PAGE_MAX_BYTES } = await import('../src/core/page-size-policy.ts');+ await expectRefused(f, page('Alpha one', `The first alpha observation.\n\n${'x'.repeat(PAGE_MAX_BYTES + 1)}`), timeline(f), 'add_timeline_entry');+}), 180_000);++test('#8755 j: an empty persistence.adopt_quiet_ms reads as the default window, not as no wait', () => each(async f => {+ await setConfig(f.engine, 'persistence.adopt_quiet_ms', '');+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);+ const written = Date.now();+ await call(f, 'add_timeline_entry', { slug: 'one', date: '2026-11-06', summary: 'Entry after the default window.' });+ const done = await settled(f.engine, await lastRow(f, 'add_timeline_entry'));+ expect(done.state).toBe('committed');+ const [adoption] = await adoptionRows(f);+ expect(new Date(adoption!.created_at as unknown as string).getTime() - written).toBeGreaterThanOrEqual(4_000);+}), 180_000);++test('#8755 l: doctor local_edit_adoptions still counts an adoption whose receipt was compacted', () => each(async f => {+ const { localEditAdoptionsEntry } = await import('../src/commands/doctor/checks/local-edit-adoptions.ts');+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);+ await call(f, 'add_timeline_entry', { slug: 'one', date: '2026-11-06', summary: 'Entry for the doctor.' });+ expect((await settled(f.engine, await lastRow(f, 'add_timeline_entry'))).state).toBe('committed');+ const [adoption] = await adoptionRows(f);+ await f.engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");+ await tx.executeRaw('UPDATE persistence_requests SET intent=NULL,compacted=true WHERE id=$1::uuid', [adoption!.id]);+ });+ const check = (await localEditAdoptionsEntry.run({ engine: f.engine, progress: { heartbeat() {} } } as never) as Array<{ details?: any }>)[0]!;+ expect(check.details.sources.filter((s: { source_id: string }) => s.source_id === f.alpha)).toEqual([{ source_id: f.alpha, adoptions: 1, paths: ['one.md'] }]);+}), 180_000);++test('#8755 k: a repo-less-looking source inside an enclosing repository whose HEAD git cannot read keeps the refusal', async () => {+ for (const backend of backends) await managedBrain(async ({ engine, ctx, root }) => {+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: SLUG, request_id: randomUUID(), content: '---\ntype: person\ntitle: Owner\n---\n\nBody.\n' } });+ await setConfig(engine, 'persistence.adopt_local_edits.source.default', 'true');+ await setConfig(engine, 'persistence.adopt_quiet_ms', '0');+ const path = join(root, `${SLUG}.md`);+ const edited = readFileSync(path, 'utf8').replace('Body.', `Body.\n\n${LOCAL}`);+ execFileSync('git', ['init', '-q', '-b', 'main', join(root, '..')]);+ writeFileSync(path, edited);+ const before = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!.revision;+ await submitRememberMutation(ctx, { fact: 'Owner prefers async updates', entity: SLUG, provenance: 'test', visibility: 'world' }).catch(() => undefined);+ const done = await settled(engine, await lastRow({ engine }, 'remember'));+ expect(done.state).not.toBe('committed');+ expect(readFileSync(path, 'utf8')).toBe(edited);+ expect((await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!.revision).toBe(before);+ expect((await adoptionRows({ engine })).filter(r => r.state === 'committed')).toEqual([]);+ }, backend === 'postgres' ? { databaseUrl: process.env.DATABASE_URL } : {});+}, 180_000);+++test('#8755 h: an adoption names its caller\'s claim, and one whose caller no longer holds it publishes nothing', () => each(async f => {+ const { assertAdoptionCaller } = await import('../src/core/persistence/local-edit-adoption.ts');+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);+ await timeline(f)().catch(() => undefined);+ const done = await settled(f.engine, await lastRow(f, 'add_timeline_entry'));+ expect(done.state).toBe('committed');+ const [adoption] = await adoptionRows(f);+ const caller = (adoption!.intent as { adoptLocalEdit?: { caller?: { id: string; token: string } } }).adoptLocalEdit?.caller;+ expect(caller?.id).toBe(done.id);+ expect(caller?.token).toBeTruthy();+ const refused = await assertAdoptionCaller(f.engine, adoption!, caller).then(() => null, (e: { code?: string }) => e);+ expect(refused?.code).toBe('write_claim_lost');+}), 180_000);+diff --git a/test/commit-ledger.test.ts b/test/commit-ledger.test.tsindex 686678445b..502cd17090 100644--- a/test/commit-ledger.test.ts+++ b/test/commit-ledger.test.ts@@ -96,3 +96,12 @@ test('messageDigest applies git whitespace cleanup', () => {expect(messageDigest('subject \n\n\n\nbody\n\n')).toBe(messageDigest('subject\n\nbody'));expect(messageDigest('a')).not.toBe(messageDigest('b'));});++test('GST-1623: a ledger that exists but cannot be read throws instead of reading as empty; a missing one is empty', () => {+ const root = repo();+ expect(readLedger(join(root, '.git'))).toEqual([]);+ const files = ledgerFiles(join(root, '.git'));+ mkdirSync(files.current, { recursive: true });+ expect(() => readLedger(join(root, '.git'))).toThrow();+});+diff --git a/test/doctor-foreign-writers.test.ts b/test/doctor-foreign-writers.test.tsindex 98b6c28cc9..797c1d8f89 100644--- a/test/doctor-foreign-writers.test.ts+++ b/test/doctor-foreign-writers.test.ts@@ -248,6 +248,7 @@ test('a git status that fails leaves the scan partial, which warns instead of reexpect(check.details!.partial).toBe(true);expect(check.status).toBe('warn');expect(check.message).toContain('the scan did not finish');+ expect(check.message).toContain(`git status failed in ${work}`);}, 60_000);test('after rotation the ledgered commits in commit-ledger.1.jsonl still count', async () => {@@ -327,3 +328,57 @@ test('the scan reads git without optional locks: a stat-dirty index is left as iexpect(readFileSync(join(work, '.git/index')).equals(before)).toBe(true);});++test('GST-1623: a foreign commit carrying a gbrain- trailer is named as possibly an older gbrain without the commit ledger, and still fails', async () => {+ const { work } = checkout();+ await register('older', join(work, 'notes'));+ write(work, 'notes/a.md', 'a\n');+ commitPathsLocked(work, ['notes/a.md'], 'start the ledger', { lockWaitMs: 1000 });+ write(work, 'notes/b.md', 'b\n');+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'gbrain: repair a page', '-m', 'gbrain-repair: frontmatter_slug_conflict deterministic high']);+ const trailed = head(work);+ write(work, 'notes/c.md', 'c\n');+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'plain commit']);+ const check = await run();+ expect(check.status).toBe('fail');+ const bySha = Object.fromEntries((check.details!.foreign as ForeignCommit[]).map(c => [c.sha, c]));+ expect(bySha[trailed]).toMatchObject({ gbrain_trailer: true });+ expect(bySha[head(work)]).toMatchObject({ gbrain_trailer: false });+ expect(check.message).toContain('an older gbrain without the commit ledger');+}, 60_000);++test('GST-1623: a root whose git probe fails, and a scan where every root fails, warn as partial instead of not_applicable', async () => {+ const { work } = checkout();+ await register('broken', join(work, 'notes'));+ writeFileSync(join(work, '.git', 'HEAD'), 'not a ref\n');+ const check = await run();+ expect(check.status).toBe('warn');+ expect(check.readiness_state).not.toBe('not_applicable');+ expect(check.details!.partial).toBe(true);+ expect((check.details!.partial_reasons as string[]).join(' ')).toContain(join(work, 'notes'));+ expect(check.message).toContain('could not be read as a Git checkout');+}, 60_000);++test('GST-1623: roots past the scan cap leave the scan partial, never not_applicable', async () => {+ const plain = mkdtempSync(join(dir, 'capped-'));+ for (let i = 0; i < 51; i++) { mkdirSync(join(plain, `r${String(i).padStart(2, '0')}`)); await register(`capped-${String(i).padStart(2, '0')}`, join(plain, `r${String(i).padStart(2, '0')}`)); }+ const check = await run();+ expect(check.status).toBe('warn');+ expect(check.details!.partial).toBe(true);+ expect(check.message).toContain('past the 50-root scan cap');+}, 60_000);++test('GST-1623: an unreadable commit ledger warns as partial instead of reading as an empty ledger', async () => {+ const { work } = checkout();+ await register('ledger', join(work, 'notes'));+ write(work, 'notes/a.md', 'a\n');+ commitPathsLocked(work, ['notes/a.md'], 'start the ledger', { lockWaitMs: 1000 });+ const files = ledgerFiles(join(work, '.git'));+ rmSync(files.current); mkdirSync(files.current);+ const check = await run();+ expect(check.status).toBe('warn');+ expect(check.details!.partial).toBe(true);+ expect(check.message).toContain('commit ledger');+ expect(check.message).toContain('could not be read');+}, 60_000);+diff --git a/test/git-commit-push-not-a-source-8662.test.ts b/test/git-commit-push-not-a-source-8662.test.tsindex db19c973e5..f0aae25190 100644--- a/test/git-commit-push-not-a-source-8662.test.ts+++ b/test/git-commit-push-not-a-source-8662.test.ts@@ -103,3 +103,41 @@ test('a host whose brain records no source checkout commits in any checkout as bexpect(result.exitCode).toBe(0);expect(JSON.parse(result.stdout)).toMatchObject({ outcome: 'pushed', paths: ['notes/a.md'] });}, 60_000);++test('GST-1623: a repository that only encloses a registered checkout is refused; a registered subdirectory of the checkout admits it', async () => {+ const outer = otherRepo('enclosing-code');+ const home = join(dir, 'enclosing-home'), brain = join(outer, 'brain');+ mkdirSync(join(brain, 'people'), { recursive: true });+ execFileSync('git', ['init', '-q', '-b', 'main', brain]);+ writeFileSync(join(brain, 'README.md'), 'brain\n');+ git(brain, 'add', 'README.md'); git(brain, 'commit', '-qm', 'init');+ withEnv({ GBRAIN_HOME: home }, () => { recordManagedRoots('00000000-0000-4000-8000-000000001623', [{ local_path: brain, source_id: 'source-a' }]); });+ const before = git(outer, 'rev-parse', 'HEAD');+ const refused = await commitPush(outer, home, '--', 'notes/a.md');+ expect(refused.exitCode).toBe(1);+ expect((JSON.parse(refused.stdout) as { code: string }).code).toBe('checkout_not_a_source');+ expect(git(outer, 'rev-parse', 'HEAD')).toBe(before);+ const tracked = otherRepo('subdir-source');+ const subHome = join(dir, 'subdir-home');+ withEnv({ GBRAIN_HOME: subHome }, () => { recordManagedRoots('00000000-0000-4000-8000-000000001624', [{ local_path: join(tracked, 'notes'), source_id: 'source-a' }]); });+ git(tracked, 'add', 'notes/a.md'); git(tracked, 'commit', '-qm', 'track notes');+ writeFileSync(join(tracked, 'notes', 'a.md'), 'an edited page\n');+ const admitted = await commitPush(tracked, subHome, '--', 'notes/a.md');+ expect(admitted.exitCode).toBe(0);+ expect(JSON.parse(admitted.stdout)).toMatchObject({ outcome: 'committed_local', paths: ['notes/a.md'] });+}, 60_000);++test('GST-1623: a managed-root registry that cannot be listed is refused with a typed error, not a raw one', async () => {+ const other = otherRepo('registry-unreadable');+ const home = join(dir, 'registry-unreadable-home');+ mkdirSync(join(home, '.gbrain', 'persistence'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'persistence', 'managed-roots'), 'not a directory\n');+ const before = git(other, 'rev-parse', 'HEAD');+ const result = await commitPush(other, home, '--', 'notes/a.md');+ expect(result.exitCode).toBe(1);+ const envelope = JSON.parse(result.stdout) as { code: string; message: string; suggestion?: string };+ expect(envelope.code).toBe('writer_coordinator_required');+ expect(envelope.message).toContain('cannot be listed');+ expect(git(other, 'rev-parse', 'HEAD')).toBe(before);+}, 60_000);+diff --git a/test/sources-guard.test.ts b/test/sources-guard.test.tsindex c47e8a43b1..a46b6278ff 100644--- a/test/sources-guard.test.ts+++ b/test/sources-guard.test.ts@@ -4,6 +4,7 @@* linked sibling worktree of the same repository keeps its own hooks. In-memory PGLite and real git repositories.*/import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync, spawnSync } from 'node:child_process';import { createHash } from 'node:crypto';import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';@@ -170,3 +171,34 @@ test('the install is worktree-local: a linked sibling keeps its hooks and commitexpect(error?.code).toBe('git_unavailable');expect((await sourcesGuard(f.engine, { sourceId: f.alpha, action: 'status', mode: 'default' })).installed).toBe(false);}), 120_000);++test('GST-1623: the owner-path hook fails closed when git cannot name the git dir, and still passes a foreign git dir', () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-guard-closed-'));+ try {+ const repo = join(root, 'repo');+ mkdirSync(repo);+ git(repo, 'init', '-q', '-b', 'main');+ const hooks = join(repo, '.git', 'gbrain-hooks');+ mkdirSync(hooks, { recursive: true });+ const real = execFileSync('sh', ['-c', 'command -v git']).toString().trim();+ const bin = join(root, 'bin');+ mkdirSync(bin);+ writeFileSync(join(bin, 'git'), `#!/bin/sh\nfor a in "$@"; do [ "$a" = --absolute-git-dir ] && exit 128; done\nexec ${real} "$@"\n`, { mode: 0o755 });+ const msg = join(root, 'msg');+ writeFileSync(msg, 'subject\n');+ for (const mode of ['default', 'enforce'] as const) {+ const hook = join(hooks, `prepare-commit-msg-${mode}`);+ writeFileSync(hook, renderGuardHook(mode), { mode: 0o755 });+ const run = (path: string, cwd: string) => spawnSync('bash', [hook, msg], { cwd, env: { ...process.env, PATH: path, GBRAIN_COMMIT_GUARD: '' }, encoding: 'utf8' });+ const failed = run(`${bin}:${process.env.PATH}`, repo);+ expect(failed.status).toBe(1);+ expect(failed.stderr).toContain('could not resolve');+ const other = join(root, `other-${mode}`);+ mkdirSync(other);+ git(other, 'init', '-q', '-b', 'main');+ expect(run(process.env.PATH!, other).status).toBe(0);+ expect(run(process.env.PATH!, repo).status).toBe(1);+ }+ } finally { rmSync(root, { recursive: true, force: true }); }+});+