Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): adoption replay publishes a landed commit, receipt names it, bisect/squash refused (#8824, #8767, #8826)

garrytand0dc7e264add
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0011813b94..d3c1d3b8dc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**Opt-in local-edit adoption (`persistence.adopt_local_edits`, off by default) no longer leaves an adoption commit unrecorded when the write it was made for ends early, names that commit on a failed adoption's receipt, and refuses during a bisect or an uncommitted squash merge.** An adoption whose `gbrain: adopt local edit` commit landed before its publication failed used to end `write_claim_lost` (or be cancelled) once its caller's claim ended, so the commit was never recorded and later writes to the page refused `file_database_drift` until a sync. It is now published on its replay with its receipt naming the landed commit. An adoption that ends without committing after its commit landed names that commit too (`outcome.persistence.git_commit`, `landed_before_row: true`), so `gbrain write-request` and `gbrain sources writer failures` tie the commit to the adoption. Adoption now also keeps its refusal while a `git bisect` or an uncommitted `git merge --squash` is in progress, and when Git names the checkout's git dir with anything but one absolute, existing directory in valid UTF-8.
+
+### Itemized changes
+
+- `src/core/persistence/local-edit-adoption.ts`, `file-repair.ts`: `landedAdoptionCommit` finds this adoption's commit at HEAD (subject, `gbrain-adopted:` trailer, commit-ledger line, the pre-adoption blob in its parent and the adopted blob at HEAD). Preparation and the publication's recheck run the caller check only until that commit lands, and `settleAdoption` leaves a requeued adoption whose commit landed to the consumer instead of cancelling it. Fixes #8824.
+- `src/core/persistence/coordinator.ts`: `recoverPublication` stamps a landed adoption commit as `outcome.persistence = {git_state: committed, git_commit, landed_before_row: true}` on the requeued or failed receipt, the shape a strict source's landed door commit already uses; `completeWrite` keeps it on any later end without committing. Fixes #8767.
+- `src/core/persistence/pending-import.ts`: `operationMarkerPaths` adds `BISECT_LOG` and `SQUASH_MSG`, reads `git rev-parse --absolute-git-dir` as bytes and answers null on invalid UTF-8, or unless the one line (only its trailing newline stripped) is an absolute path that exists as a directory. `GIT_OPERATION_MARKERS` and `assertNoOperationInProgress` (`src/core/git/commit-push.ts`) are unchanged. A `git cherry-pick -n` leaves no marker; the adoption and its caller commit only their own path (`git commit --only`), so the picked path stays staged. Fixes #8826.
+- Tests: `test/adopt-local-edit.test.ts` on PGLite and Postgres (a replay after the caller was cancelled before recovery requeued it; a terminal failure right after the adoption commit; a real `cherry-pick -n` of another path; a real bisect and a squash merge stopped on a conflict in another path), and `test/operation-marker-paths.test.ts` (a non-UTF-8 git dir reached through a clean symlink mid-cherry-pick, real squash merge and bisect, and a shim git answering with CRLF, a trailing space, a relative path, a missing directory, a file or no newline).
+
## [0.60.611.0] - 2026-11-08
**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, even when an older gbrain left a stale marker in it. 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, and checks the claim, the conflict and the merge again in the transaction that publishes its commit. Its quiet wait is capped at the foreground budget, and an adoption whose publication failed after its commit is retried instead of left orphaned.
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index a397ffac65..c5ea58bcf8 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`, 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` / `operationMarkerPaths`), 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`.
+- **`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` / `operationMarkerPaths`; #8826 adds `BISECT_LOG` and `SQUASH_MSG` and reads `--absolute-git-dir` as bytes, answering null unless it is one absolute, existing directory in valid UTF-8), 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. #8824: the check runs only until the adoption's commit lands: once HEAD holds it (`landedAdoptionCommit`: the newest commit on the path has the adoption's subject, trailer and commit-ledger line, its parent holds the pre-adoption blob and HEAD the adopted one), a replay publishes it whatever became of its caller, and `settleAdoption` leaves such a requeued adoption to the consumer instead of cancelling it. #8767: `recoverPublication` (`coordinator.ts`) stamps that commit (`adoptionCommitLanded`) as `outcome.persistence = {git_state: committed, git_commit, landed_before_row: true}` on the requeued or failed receipt, which `completeWrite` keeps on any later end without committing. `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. Tests: `test/adopt-local-edit.test.ts`, `test/operation-marker-paths.test.ts`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 1a0f1d073d..6ab24ef381 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 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="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). It also stays while a `git bisect` (`BISECT_LOG`) or an uncommitted `git merge --squash` (`SQUASH_MSG`) is in progress, and when `git rev-parse --absolute-git-dir` answers with anything but one absolute, existing directory in valid UTF-8; a `git cherry-pick -n` leaves no marker, and its staged paths stay out of the adoption's commit (#8826). An adoption whose commit landed before its publication failed is published on its replay even after the write it was made for ended, and one that ends without committing after that commit names it on its receipt (`outcome.persistence.git_commit`, `landed_before_row: true`; #8824, #8767). | 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/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsv
index 82c75a2265..fa92d9a42d 100644
--- a/scripts/core-world-reads-baseline.tsv
+++ b/scripts/core-world-reads-baseline.tsv
@@ -700,6 +700,7 @@ src/core/persistence/ownership.ts process_env 2 W6: settings plane out of the co
src/core/persistence/page-mutations.ts fs_import 1 W5: repo-less persistence for hosts
src/core/persistence/page-prepare.ts fs_import 1 W5: repo-less persistence for hosts
src/core/persistence/page-purge.ts module_collection 3 W6: per-engine state, or mark as a constant table
+src/core/persistence/pending-import.ts fs_import 1 W5: repo-less persistence for hosts (#8826: operationMarkerPaths stats the git dir Git names before it trusts the marker paths)
src/core/persistence/pending-import.ts spawn_import 1 W7: process-wide effects move to src/cli
src/core/persistence/physical-root-record.ts fs_import 1 W5: repo-less persistence for hosts
src/core/persistence/physical-root-record.ts spawn_import 1 W7: process-wide effects move to src/cli
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 753b73979d..0eac06ecde 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
-src/core/behavior-change-notice.ts 1680 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6
+src/core/behavior-change-notice.ts 1681 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move)
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d4fc1e147c..803c79e6c3 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1479,6 +1479,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.611.0', id: 'doctor_foreign_writers_partial_gst1623', text: 'Doctor `foreign_writers` no longer reads what it could not scan as clean. A source root inside a Git checkout whose `git rev-parse` fails or times out, roots past the 50-root scan cap, a commit ledger that exists but cannot be read, and a `git status` that failed or timed out now mark the scan partial, each listed in the new `partial_reasons` and named in the message. A scan that read no repository but skipped one warns instead of reporting not_applicable. `git status` now gets up to 30 s within doctor\'s budget instead of the fixed git timeout. A foreign commit whose trailers include a `gbrain-` trailer still fails the check, and the message names it as possibly an older gbrain without the commit ledger (`gbrain_trailer: true`).' },
{ since: '0.60.611.0', id: 'commit_push_enclosing_repo_gst1623', text: 'On a brain home that records its source checkouts, `gbrain git commit-push` without `--path` now also refuses `checkout_not_a_source` in a repository that only encloses a registered checkout (a clone above it): a registered checkout must contain the resolved one, or be a directory of it that its HEAD tracks. A checkout registry that cannot be listed now refuses `writer_coordinator_required` instead of an internal error.' },
{ since: '0.60.611.0', id: 'owner_guard_fail_closed_gst1623', text: 'The owner-path commit guard of `gbrain sources guard` now refuses the commit (exit 1, with a message) when `git rev-parse --absolute-git-dir` fails, instead of letting it through; a hook that belongs to another git dir still passes. A guard installed by an earlier version keeps its old script until `gbrain sources guard <source> --install` runs again.' },
+ { since: 'TBD', id: 'adopt_local_edits_replay_markers_8824', text: 'With `persistence.adopt_local_edits` on for a source (off by default), an adoption whose `gbrain: adopt local edit` commit already landed in Git is now published, and its receipt names that commit (`outcome.persistence.git_commit`, `landed_before_row: true`), even when the write it was made for was cancelled or its claim ended before the replay; before, it ended `failed` / `write_claim_lost` (or was cancelled) and left the commit unrecorded, so later writes to the page refused `file_database_drift` until a sync. An adoption that ends without committing after that commit landed now names the commit on its receipt too, so `gbrain write-request` and `gbrain sources writer failures` tie it to the adoption. Adoption also keeps the `file_database_drift` refusal while a `git bisect` (`BISECT_LOG`) or an uncommitted `git merge --squash` (`SQUASH_MSG`) is in progress, and when `git rev-parse --absolute-git-dir` answers with anything but one absolute, existing directory in valid UTF-8.' },
{ since: '0.60.611.0', id: 'adopt_local_edits_hardening_8755', text: 'With `persistence.adopt_local_edits` on for a source (off by default), a local edit is no longer adopted, and the write keeps its `file_database_drift` refusal, when its path has merge conflicts, while a merge, cherry-pick, revert or rebase is in progress, when the file equals one of the page\'s last 50 revisions or drops rows the current revision added (a stale editor save), when the page is segmented, or when the write\'s claim ended meanwhile. The quiet wait is capped at 30 s (it was up to three `persistence.adopt_quiet_ms` windows, 180 s at that key\'s cap), and an empty `persistence.adopt_quiet_ms` reads as the 5000 default instead of no wait. Doctor `local_edit_adoptions` still counts an adoption after its receipt is compacted.' },
{ since: '0.60.611.0', id: 'managed_sync_kind_reserved_8765', text: 'A page write that passes a `kind` starting with `managed_sync_` (for example `capture` with `kind: managed_sync_import`) is now refused `invalid_params` and writes nothing: that prefix is reserved for managed sync, and with `persistence.refresh_barrier` on a waiting write now tells sync\'s own imports apart from later writes by the operation that wrote them, not by the kind. Use another kind, or drop `kind`.' },
{ since: '0.60.608.0', id: 'refresh_barrier_later_write_gst1623', text: 'With `persistence.refresh_barrier` on, a write that waited behind a refresh or an import (other than a `remember` or `add_timeline_entry`, which still applies on top) now ends `revision_conflict` instead of applying when a later write to the same page committed first, which a consumer from an older release can cause; read the page again and resubmit with a new `request_id`. A write held again and again behind imports now expires once it has waited four wait limits (at least 4 hours) since its admission, even when each hold is shorter than one wait limit. With the barrier on or off, a plain-git commit that lands on the start commit right before a refresh merges makes git refuse the fast-forward, and the refresh now ends `refresh_source_changed` with the fence lifted and the commit kept, instead of leaving the checkout `recovery_required`; one that lands right after the merge is recorded and synced.' },
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 3daf1acb81..cef9d0a01c 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -31,7 +31,7 @@ import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
import { queuePublicationEffects } from './effect-journal.ts';
import { deferredReplayRefusal } from './refresh-barrier.ts';
import { holdForImport } from './import-deferral.ts';
-import { adoptLocalEdit } from './local-edit-adoption.ts';
+import { adoptionCommitLanded, adoptLocalEdit } from './local-edit-adoption.ts';
import { timePublicationStep } from './publication-timing.ts';
import type { AppendedRange, GitCommitNote } from './effect-model.ts';
import { authorizePageVisibility } from './page-visibility.ts';
@@ -869,6 +869,8 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId
// Withdrawal is authoritative DB state and is never rolled back here.
const failure: PublicationFailure | undefined = terminalError ?? (current.error_code ? {code:current.error_code,message:current.error_message ?? 'Publication failed before database completion.',
...(current.error_detail ? { detail: current.error_detail as unknown as PublicationFailureDetail } : {})} : undefined);
+ // #8767: so is a local edit adoption's own commit (local-edit-adoption.ts), on a failure and on the requeued replay.
+ landed ??= await adoptionCommitLanded(tx, current, binding);
// G7b: a door commit that landed before its row is named on the receipt, whatever the replay's outcome.
const kept = landed ? { persistence: { git_state: 'committed', git_commit: landed, landed_before_row: true } } : null;
if (failure) return completeWrite(tx, current, failureState(failure.code), kept ?? {}, failure);
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index 16ee15f1c0..f57b105e81 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, assertAdoptionCaller, commitAdoptedLocalEdit, conflictOrOperation } from './local-edit-adoption.ts';
+import { ADOPTED_CHANGE_REASON, adoptedHeadHolds, assertAdoptionCaller, commitAdoptedLocalEdit, conflictOrOperation, landedAdoptionCommit } 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';
@@ -334,7 +334,6 @@ 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.`,
@@ -351,6 +350,9 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
return target;
};
const target = checkFile();
+ // #8824: the caller's claim is checked only before the adoption's commit lands; a replay after it publishes that commit.
+ const adoptionLanded = () => adopted ? landedAdoptionCommit(root, target, { path: p.path, ...adopted }) : Promise.resolve(null);
+ if (adopted && !await adoptionLanded()) await assertAdoptionCaller(engine, row, adopted.caller);
const source = { sourceId: row.source_id };
const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });
assertPageRevision(snapshot, { expectedRevision: p.expected_revision ?? null }); // null: admitted against an absent page; still a revision_conflict if one appeared (#5385)
@@ -397,7 +399,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
checkFile();
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);
// #8755: the caller's claim and the index are read again here, where the adoption commits: a cancel or a conflict may come after preparation.
- if (adopted) await assertAdoptionCaller(tx, row, adopted.caller, true);
+ if (adopted && !await adoptionLanded()) await assertAdoptionCaller(tx, row, adopted.caller, true);
if (adopted && adopted.head !== null && await conflictOrOperation(root, target)) throw changedSincePreview(row.source_id, p.path, 'a merge, rebase or conflicted path appeared 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);
diff --git a/src/core/persistence/local-edit-adoption.ts b/src/core/persistence/local-edit-adoption.ts
index 9e9ca65f51..bf7ff167c2 100644
--- a/src/core/persistence/local-edit-adoption.ts
+++ b/src/core/persistence/local-edit-adoption.ts
@@ -28,6 +28,11 @@
* 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.
+ *
+ * #8824/#8767: the caller check runs only until the adoption's own commit lands. A replay that finds HEAD holding it
+ * (`landedAdoptionCommit`) publishes it whatever became of the caller, a requeued one is never cancelled, and recovery
+ * names the commit on the receipt (`landed_before_row`) whether the adoption then commits or ends without committing.
+ * #8826: a bisect or an uncommitted squash merge also keeps the refusal (`operationMarkerPaths`).
*/
import { randomUUID } from 'node:crypto';
import { existsSync, readFileSync, statSync } from 'node:fs';
@@ -50,10 +55,11 @@ 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, landedCommit, operationMarkerPaths, unmergedPath } from './pending-import.ts';
+import { blobAt, blobText, commitMessage, headBlob, headCommit, landedCommit, operationMarkerPaths, unmergedPath } from './pending-import.ts';
+import { ledgerLocation, readLedger } from '../git/commit-ledger.ts';
+import { adoptedBy, localEditAdoptionCommit, type GitCommitNote } from './effect-model.ts';
import { claimOwner } from './claim-phase.ts';
import type { PreparedMutation } from './coordinator.ts';
-import type { GitCommitNote } from './effect-model.ts';
export const ADOPTED_CHANGE_REASON = 'adopted_local_edit';
export const ADOPT_QUIET_KEY = 'persistence.adopt_quiet_ms';
@@ -217,6 +223,38 @@ export async function assertAdoptionCaller(engine: BrainEngine, row: WriteReques
`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.`);
}
+/**
+ * #8824: the commit of this adoption when HEAD already holds it: the newest commit on the path is `gbrain: adopt local edit
+ * to <path>` carrying this adoption's `gbrain-adopted:` trailer and commit-ledger line, its parent held the pre-adoption
+ * blob, and HEAD holds the adopted blob. Null otherwise, on a repo-less brain, or when Git or the ledger cannot be read.
+ * A replay that finds it publishes whatever became of its caller (the commit is durable), and its receipt names it.
+ */
+export async function landedAdoptionCommit(root: string, target: string, adopted: { path: string; blob: string; replaced_revision: string; head: string | null }): Promise<string | null> {
+ if (adopted.head === null || await headBlob(root, target) !== adopted.blob) return null;
+ const commit = await landedCommit(root, null, target);
+ if (!commit || await blobAt(root, `${commit}^`, target) !== adopted.head) return null;
+ const note = localEditAdoptionCommit(adopted.path, adopted.blob, adopted.replaced_revision);
+ const lines = (await commitMessage(root, commit))?.split('\n') ?? [];
+ if (lines[0] !== note.subject || !note.trailers?.every(trailer => lines.includes(trailer))) return null;
+ const [trailer] = adoptedBy(note.trailers);
+ const location = ledgerLocation(root);
+ try {
+ return location && readLedger(location.common).some(record => record.e === 'commit' && record.sha === commit && record.adopted?.includes(trailer!)) ? commit : null;
+ } catch { return null; }
+}
+
+/** #8824/#8767: `landedAdoptionCommit` for an adoption request `row` (any other request answers null), read on `binding`'s checkout. */
+export async function adoptionCommitLanded(engine: BrainEngine, row: WriteRequest, binding?: WorktreeBinding | null): Promise<string | null> {
+ const intent = row.intent as { kind?: unknown; path?: unknown; adoptLocalEdit?: { blob?: unknown; replaced_revision?: unknown; head?: unknown } } | null;
+ const adopted = intent?.adoptLocalEdit;
+ if (intent?.kind !== 'managed_file_repair' || typeof intent.path !== 'string' || typeof adopted?.blob !== 'string'
+ || typeof adopted.replaced_revision !== 'string' || typeof adopted.head !== 'string') return null;
+ const bound = binding === undefined ? await getWorktreeBinding(engine, row.source_id) : binding;
+ if (!bound?.local_path) return null;
+ const root = join(bound.local_path, bound.relative_path);
+ return landedAdoptionCommit(root, join(root, intent.path), { path: intent.path, blob: adopted.blob, replaced_revision: adopted.replaced_revision, head: adopted.head });
+}
+
/** Claims, prepares and publishes the admitted adoption, retrying while another owner task holds the worktree lock. */
async function publishAdoption(engine: BrainEngine, caller: WriteRequest, admitted: WriteRequest, path: string): Promise<WriteRequest> {
const { finishUnpublishedFailure, publishMutation } = await import('./coordinator.ts');
@@ -254,6 +292,10 @@ async function settleAdoption(engine: BrainEngine, row: WriteRequest): Promise<W
const { cancelWriteRequest } = await import('./control.ts');
const deadline = Date.now() + LOCK_RETRY_MS;
for (;;) {
+ // #8824: a requeued adoption whose commit already landed is left for the consumer, which publishes it naming that
+ // commit; cancelling it would orphan the commit.
+ const latest = (await getWriteRequestById(engine, row.id)) ?? row;
+ if (latest.state === 'queued' && await adoptionCommitLanded(engine, latest)) return latest;
const current = await cancelWriteRequest(engine, requestPrincipal(row), row.request_id) ?? row;
if (isTerminal(current)) return current;
const publishing = current.publication_started || current.recovery != null;
diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.ts
index 1aedb85243..6d9aed1dfe 100644
--- a/src/core/persistence/pending-import.ts
+++ b/src/core/persistence/pending-import.ts
@@ -17,7 +17,8 @@
* is resubmitted by its caller after that sync.
*/
import { spawn } from '../spawn.ts';
-import { join, relative, sep } from 'node:path';
+import { statSync } from 'node:fs';
+import { isAbsolute, join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import { gitChildEnv } from '../git-env.ts';
@@ -39,13 +40,19 @@ export const GIT_KILL_GRACE_MS = 2_000;
* GIT_KILL_GRACE_MS, so no Git process outlives the request that started it.
*/
function gitRead(root: string, args: string[], signal?: AbortSignal): Promise<string> {
+ return gitBytes(root, args, signal).then(out => out.toString('utf8'));
+}
+
+/** #8826: gitRead's stdout as bytes, for an answer that must not be decoded lossily. */
+function gitBytes(root: string, args: string[], signal?: AbortSignal): Promise<Buffer> {
return new Promise((resolve, reject) => {
if (signal?.aborted) { reject(signal.reason); return; }
const group = process.platform !== 'win32';
const child = spawn('git', ['-c', 'core.quotepath=false', '-C', root, ...args], { env: gitChildEnv(), stdio: ['ignore', 'pipe', 'ignore'], detached: group });
const kill = (name: NodeJS.Signals) => { try { if (group && child.pid) process.kill(-child.pid, name); else child.kill(name); } catch { /* already gone */ } };
- let stdout = '', settled = false;
- const settle = (error: unknown, value = '') => {
+ const stdout: Buffer[] = [];
+ let settled = false;
+ const settle = (error: unknown, value = Buffer.alloc(0)) => {
if (settled) return;
settled = true;
clearTimeout(timer);
@@ -60,10 +67,9 @@ function gitRead(root: string, args: string[], signal?: AbortSignal): Promise<st
const onAbort = () => settle(signal!.reason);
const timer = setTimeout(() => settle(new Error(`git ${args[0]} did not finish within ${GIT_TIMEOUT_MS} ms`)), GIT_TIMEOUT_MS);
signal?.addEventListener('abort', onAbort, { once: true });
- child.stdout.setEncoding('utf8');
- child.stdout.on('data', (chunk: string) => { stdout += chunk; });
+ child.stdout.on('data', (chunk: Buffer) => { stdout.push(chunk); });
child.on('error', error => settle(error));
- child.on('close', code => settle(code === 0 ? undefined : new Error(`git ${args[0]} exited ${code}`), stdout));
+ child.on('close', code => settle(code === 0 ? undefined : new Error(`git ${args[0]} exited ${code}`), Buffer.concat(stdout)));
});
}
@@ -128,15 +134,32 @@ export async function unmergedPath(root: string, path: string, signal?: AbortSig
/**
* #8755: the absolute paths of the markers a merge, cherry-pick, revert or rebase in progress leaves in `root`'s git dir
- * (MERGE_HEAD, CHERRY_PICK_HEAD, REVERT_HEAD, sequencer, rebase-merge, rebase-apply); null when Git cannot name them. The
- * caller checks which exist. All of them live in the per-worktree git dir, which Git prints absolute and symlink-resolved,
- * so a root reached through a symlink still names the real markers. Output that is not exactly one line answers null.
+ * (MERGE_HEAD, CHERRY_PICK_HEAD, REVERT_HEAD, sequencer, rebase-merge, rebase-apply), and #8826 a bisect (BISECT_LOG) or a
+ * squash merge not yet committed (SQUASH_MSG, the only marker it leaves); null when Git cannot name them. The caller checks
+ * which exist. All of them live in the per-worktree git dir, which Git prints absolute and symlink-resolved, so a root
+ * reached through a symlink still names the real markers. #8826: the answer is read as bytes; one that is not valid UTF-8,
+ * or is not exactly one line (only its trailing newline is stripped) naming an absolute path that exists as a directory,
+ * answers null. A `cherry-pick -n` leaves no marker; adoption commits only its own path (`git commit --only`).
*/
export async function operationMarkerPaths(root: string, signal?: AbortSignal): Promise<string[] | null> {
- const markers = ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'sequencer', 'rebase-merge', 'rebase-apply'];
- return gitRead(root, ['rev-parse', '--absolute-git-dir'], signal)
- .then(out => { const lines = out.split('\n'); return lines.length === 2 && lines[0] && !lines[1] ? markers.map(marker => join(lines[0], marker)) : null; },
- error => { if (signal?.aborted) throw error; return null; });
+ const markers = ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'sequencer', 'rebase-merge', 'rebase-apply', 'BISECT_LOG', 'SQUASH_MSG'];
+ let out: string;
+ try { out = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(await gitBytes(root, ['rev-parse', '--absolute-git-dir'], signal)); }
+ catch (error) { if (signal?.aborted) throw error; return null; }
+ const dir = out.endsWith('\n') ? out.slice(0, -1) : '';
+ if (!dir || dir.includes('\n') || !isAbsolute(dir)) return null;
+ try { if (!statSync(dir).isDirectory()) return null; } catch { return null; }
+ return markers.map(marker => join(dir, marker));
+}
+
+/** #8824: the full message of `commit` in `root`'s repository, or null when Git cannot read it. */
+export async function commitMessage(root: string, commit: string): Promise<string | null> {
+ return gitRead(root, ['log', '-1', '--format=%B', commit]).catch(() => null);
+}
+
+/** #8824: the blob id `rev` holds at `path` (inside `root`), or null when it has no entry there or Git cannot read it. */
+export async function blobAt(root: string, rev: string, path: string): Promise<string | null> {
+ return quiet(gitRead(root, ['rev-parse', '--verify', '--quiet', `${rev}:./${relative(root, path).split(sep).join('/')}`]));
}
/** #8759: the text of `path` as `commit` holds it, or null when Git cannot read it there. */
diff --git a/test/adopt-local-edit.test.ts b/test/adopt-local-edit.test.ts
index 9812a46104..b12ab9b4f2 100644
--- a/test/adopt-local-edit.test.ts
+++ b/test/adopt-local-edit.test.ts
@@ -623,3 +623,110 @@ test('#8755 p: a stale editor save matches an earlier revision whose edges hold
await expectRefused(f, page('Alpha one', EARLIER), timeline(f), 'add_timeline_entry');
expect(published).toBe(0);
}), 180_000);
+
+
+// ── #8824 / #8767 / #8826 ───────────────────────────────────────────────────
+
+/** The adoption commit of `rel`: the newest commit on its path whose subject is the adoption's. */
+const adoptCommit = (f: RefreshFixture, rel: string) => git(f.root, 'log', '--format=%H %s', '--', `alpha/${rel}`).split('\n')
+ .filter(line => line.includes(`gbrain: adopt local edit to ${rel}`)).map(line => line.split(' ')[0]!);
+const statementCancel = () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });
+
+test('#8824: an adoption whose commit landed before its caller\'s claim ended is published by the consumer, naming that commit', () => each(async f => {
+ const { installFaultHook } = await import('../src/core/persistence/fault-points.ts');
+ const rel = 'people/alice-example.md', slug = 'people/alice-example';
+ commitFile(f.root, `alpha/${rel}`, PERSON, 'person page');
+ await performManagedSync(f.engine, { sourceId: f.alpha, noPull: true, noEmbed: true });
+ writeFileSync(join(f.root, 'alpha', rel), PERSON.replace('Alice is a person.', `Alice is a person.\n\n${LOCAL}`));
+ const blob = blobOf(f, rel), replaced = await revision(f, slug);
+ let fired = 0, cancelled: string | undefined;
+ installFaultHook(async (point, detail) => {
+ if (detail.operation !== 'put_page' || detail.sourceId !== f.alpha) return;
+ if (point === 'publication:before_commit' && fired++ === 0) throw statementCancel();
+ // The publication failed after the adoption's commit landed; the caller's claim ends before recovery requeues it.
+ if (point === 'persistence:recovery_interruption_charged' && cancelled === undefined) {
+ const [caller] = await f.engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE operation='add_timeline_entry' AND source_id=$1 AND state='running' ORDER BY sequence DESC LIMIT 1", [f.alpha]);
+ cancelled = (await cancelWriteRequest(f.engine, requestPrincipal(caller!), caller!.request_id))?.state;
+ }
+ });
+ try { await call(f, 'add_timeline_entry', { slug, date: '2026-11-06', summary: 'Entry whose claim ends.' }).catch(() => undefined); } finally { installFaultHook(undefined); }
+ expect(fired).toBeGreaterThan(0);
+ expect(cancelled).toBe('cancelled');
+ const landed = adoptCommit(f, rel);
+ expect(landed).toHaveLength(1);
+ const [adoption] = await adoptionRows(f);
+ const done = await settled(f.engine, adoption!);
+ expect(done).toMatchObject({ state: 'committed' });
+ expect(done.error_code).not.toBe('write_claim_lost');
+ expect((done.outcome as { persistence?: unknown }).persistence).toMatchObject({ git_state: 'committed', git_commit: landed[0], landed_before_row: true });
+ expect((done.outcome as { adopted_local_edit?: unknown }).adopted_local_edit).toEqual({ path: rel, blob, replaced_revision: replaced });
+ expect(adoptCommit(f, rel)).toEqual(landed);
+ expect((await f.engine.readPageSnapshot(slug, { sourceId: f.alpha }))!.page.compiled_truth).toContain(LOCAL);
+ const out = await call(f, 'remember', { fact: 'alice-example follows the adopted edit', entity: slug, provenance: 'test' });
+ expect(out.isError).toBe(false);
+ const remembered = await settled(f.engine, await lastRow(f, 'remember'));
+ expect(remembered.state).toBe('committed');
+ expect(file(f, rel)).toContain(LOCAL);
+ expect(file(f, rel)).toContain('alice-example follows the adopted edit');
+}), 180_000);
+
+test('#8767: a terminal failure after the adoption\'s commit leaves a receipt naming that commit', () => each(async f => {
+ const { installFaultHook } = await import('../src/core/persistence/fault-points.ts');
+ const { readTerminalFailures } = await import('../src/core/persistence/terminal-failures.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 new Error('example terminal failure after the adoption commit');
+ });
+ try { await timeline(f)().catch(() => undefined); } finally { installFaultHook(undefined); }
+ expect(fired).toBe(1);
+ const landed = adoptCommit(f, 'one.md');
+ expect(landed).toHaveLength(1);
+ const note = `one.md: worktree blob ${blob} over revision ${replaced}`;
+ expect(git(f.root, 'log', '-1', '--format=%B', landed[0]!)).toContain(`gbrain-adopted: ${note}`);
+ const line = readLedger(join(f.root, '.git')).find(r => r.e === 'commit' && r.sha === landed[0]) as { adopted?: string[] } | undefined;
+ expect(line?.adopted).toEqual([note]);
+ const [adoption] = await adoptionRows(f);
+ const done = await settled(f.engine, adoption!);
+ expect(done.state).toBe('failed');
+ expect((done.outcome as { persistence?: unknown }).persistence).toEqual({ git_state: 'committed', git_commit: landed[0], landed_before_row: true });
+ const listing = await readTerminalFailures(f.engine, { sourceId: f.alpha, state: 'all' });
+ expect(listing.status).toBe('ok');
+ expect((listing as { rows?: Array<{ request_id: string }> }).rows?.map(row => row.request_id)).toContain(done.request_id);
+}), 180_000);
+
+test('#8826: a cherry-pick -n of another path leaves no marker, and neither the adoption nor its caller commits the picked path', () => each(async f => {
+ const branch = git(f.root, 'symbolic-ref', '--short', 'HEAD');
+ git(f.root, 'checkout', '-q', '-b', 'side-example');
+ const picked = commitFile(f.root, 'notes-example.md', 'Picked onto the index.\n', 'side example');
+ git(f.root, 'checkout', '-q', branch);
+ git(f.root, 'cherry-pick', '-n', picked);
+ expect(['CHERRY_PICK_HEAD', 'MERGE_HEAD', 'sequencer'].filter(marker => fs.existsSync(join(f.root, '.git', marker)))).toEqual([]);
+ expect(git(f.root, 'diff', '--cached', '--name-only')).toBe('notes-example.md');
+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);
+ const blob = blobOf(f, 'one.md'), replaced = await revision(f, 'one');
+ const out = await call(f, 'add_timeline_entry', { slug: 'one', date: '2026-11-06', summary: 'Entry beside a cherry-pick -n.' });
+ expect(out.isError).toBe(false);
+ const done = await settled(f.engine, await lastRow(f, 'add_timeline_entry'));
+ await expectAdopted(f, done, 'one.md', 'one', blob, replaced, 'Entry beside a cherry-pick -n.');
+ const [caller] = git(f.root, 'log', '-1', '--format=%H', '--', 'alpha/one.md').split('\n');
+ expect(git(f.root, 'show', '--name-only', '--format=', caller!).split('\n').filter(Boolean)).toEqual(['alpha/one.md']);
+ expect(git(f.root, 'diff', '--cached', '--name-only')).toBe('notes-example.md');
+ expect(git(f.root, 'log', '--format=%H', '--', 'notes-example.md')).toBe('');
+}), 180_000);
+
+test('#8826: a bisect, or a squash merge stopped on a conflict in another path, keeps the refusal', () => each(async f => {
+ git(f.root, 'bisect', 'start');
+ try { await expectRefused(f, EDITED, timeline(f), 'add_timeline_entry'); } finally { git(f.root, 'bisect', 'reset'); }
+ const branch = git(f.root, 'symbolic-ref', '--short', 'HEAD');
+ git(f.root, 'checkout', '-q', '-b', 'squash-example');
+ commitFile(f.root, 'beta/one.md', page('Beta one', 'A side edit.'), 'side');
+ git(f.root, 'checkout', '-q', branch);
+ commitFile(f.root, 'beta/one.md', page('Beta one', 'A main edit.'), 'main');
+ expect(() => git(f.root, 'merge', '--squash', 'squash-example')).toThrow();
+ expect(fs.existsSync(join(f.root, '.git', 'MERGE_HEAD'))).toBe(false);
+ expect(git(f.root, 'ls-files', '-u', '--', 'alpha/one.md')).toBe('');
+ try { await expectRefused(f, EDITED, timeline(f), 'add_timeline_entry'); } finally { git(f.root, 'reset', '-q', '--hard'); }
+}), 180_000);
+
diff --git a/test/operation-marker-paths.test.ts b/test/operation-marker-paths.test.ts
index 40dc80702d..7809d8e44c 100644
--- a/test/operation-marker-paths.test.ts
+++ b/test/operation-marker-paths.test.ts
@@ -9,6 +9,7 @@ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync,
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { operationMarkerPaths } from '../src/core/persistence/pending-import.ts';
+import { withEnv } from './helpers/with-env.ts';
const base = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-op-markers-')));
afterAll(() => rmSync(base, { recursive: true, force: true }));
@@ -124,3 +125,79 @@ test('a cherry-pick range stopped between picks, after the first conflict was co
git(root, 'cherry-pick', '--quit');
expect(await present(root)).toEqual([]);
});
+
+
+// ── #8826 ───────────────────────────────────────────────────────────────────
+
+/** A repository at `root` (reached by whatever path) whose page has diverging commits on main and side. */
+function diverged(root: string): void {
+ git(root, 'init', '-q');
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, 'notes', 'page.md'), 'one\n');
+ writeFileSync(join(root, 'notes', 'other.md'), 'other\n');
+ git(root, 'add', '.');
+ git(root, 'commit', '-qm', 'one');
+ git(root, 'checkout', '-qb', 'side');
+ writeFileSync(join(root, 'notes', 'page.md'), 'side\n');
+ git(root, 'commit', '-qam', 'side');
+ git(root, 'checkout', '-q', 'main');
+ writeFileSync(join(root, 'notes', 'page.md'), 'main\n');
+ git(root, 'commit', '-qam', 'main');
+}
+
+test('a git dir whose path is not valid UTF-8, reached through a clean symlink, never reads as clean mid-cherry-pick', async () => {
+ const real = Buffer.concat([Buffer.from(join(base, 'bytes-')), Buffer.from([0xff, 0xfe])]);
+ mkdirSync(real);
+ const link = join(base, 'bytes-link');
+ symlinkSync(real, link);
+ diverged(link);
+ expect(() => git(link, 'cherry-pick', 'side')).toThrow();
+ expect(existsSync(join(link, '.git', 'CHERRY_PICK_HEAD'))).toBe(true);
+ expect(await readsClean(link)).toBe(false);
+ expect(await operationMarkerPaths(link)).toBeNull();
+});
+
+test('a squash merge stopped on a conflict leaves no MERGE_HEAD but SQUASH_MSG, which is in progress until reset', async () => {
+ const root = join(base, 'squash');
+ mkdirSync(root);
+ diverged(root);
+ expect(() => git(root, 'merge', '--squash', 'side')).toThrow();
+ expect(existsSync(join(root, '.git', 'MERGE_HEAD'))).toBe(false);
+ expect(await present(join(root, 'notes'))).toEqual([join(root, '.git', 'SQUASH_MSG')]);
+ git(root, 'reset', '-q', '--hard');
+ expect(await present(root)).toEqual([]);
+});
+
+test('a bisect in progress sees BISECT_LOG until it is reset', async () => {
+ const root = repo('bisecting');
+ for (const n of ['two', 'three']) {
+ writeFileSync(join(root, 'notes', 'deep', 'page.md'), `${n}\n`);
+ git(root, 'commit', '-qam', n);
+ }
+ git(root, 'bisect', 'start');
+ git(root, 'bisect', 'bad');
+ git(root, 'bisect', 'good', 'HEAD~2');
+ expect(await present(root)).toEqual([join(root, '.git', 'BISECT_LOG')]);
+ git(root, 'bisect', 'reset');
+ expect(await present(root)).toEqual([]);
+});
+
+/** Runs `operationMarkerPaths` against a shim git whose `rev-parse --absolute-git-dir` prints `output`; every other command is real git. */
+async function withShimGitDir(root: string, output: string): Promise<string[] | null> {
+ const shim = mkdtempSync(join(base, 'shim-'));
+ const realGit = execFileSync('sh', ['-c', 'command -v git'], { env }).toString().trim();
+ writeFileSync(join(shim, 'out'), output);
+ writeFileSync(join(shim, 'git'), `#!/bin/sh\nfor a in "$@"; do [ "$a" = --absolute-git-dir ] && { cat "${shim}/out"; exit 0; }; done\nexec "${realGit}" "$@"\n`, { mode: 0o755 });
+ return withEnv({ PATH: `${shim}:${process.env.PATH}` }, () => operationMarkerPaths(root));
+}
+
+test('a git dir answer that is not one absolute, existing directory line reads as unknown (CRLF, trailing space, relative, missing, a file)', async () => {
+ const root = repo('shimmed');
+ const gitDir = join(root, '.git');
+ writeFileSync(join(gitDir, 'MERGE_HEAD'), `${git(root, 'rev-parse', 'HEAD').trim()}\n`);
+ expect(await withShimGitDir(root, `${gitDir}\n`)).toContain(join(gitDir, 'MERGE_HEAD'));
+ for (const output of [`${gitDir}\r\n`, `${gitDir} \n`, '.git\n', `${join(base, 'missing-dir')}\n`, `${join(gitDir, 'MERGE_HEAD')}\n`, `${gitDir}`]) {
+ expect(await withShimGitDir(root, output)).toBeNull();
+ }
+});
+