Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

persistence: adopt a one-sided local edit before remember, capture and add_timeline_entry (GST-1601 part 2)

garrytan8b3cdd6ff4f6
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index afda8884ba..4fc08ee8f3 100644
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -17,3 +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`.
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index 7e42f441dd..3afe88c9e0 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -262,7 +262,7 @@ own `fix` and a link to this section:
| `reason` | Cause | Next step |
| --- | --- | --- |
-| `file_database_drift` | The file was edited outside a coordinated write, or it is older than the database copy. | Run the `fix` (a reconcile preview), then resolve and apply it as described in [Repair a file/database disagreement](#repair-a-filedatabase-disagreement). |
+| `file_database_drift` | The file was edited outside a coordinated write, or it is older than the database copy. | Run the `fix` (a reconcile preview), then resolve and apply it as described in [Repair a file/database disagreement](#repair-a-filedatabase-disagreement). A source with `persistence.adopt_local_edits.source.<id>` on adopts a one-sided edit for `remember`, `capture` and `add_timeline_entry` instead ([file_database_drift](write-refusals.md#file_database_drift)). |
| `held_file` | Sync holds the file because it cannot import it. | Run the hold repair in `fix` (for example `gbrain repair frontmatter --source workspace`), as in [held files](repair.md#held-files). |
| `canonical_file_missing` | The file was removed while lint ran. | Recover the file or import the deletion; reconciliation does not restore missing files. |
| `revision_changed` | Another write published the page while lint ran. | Nothing; the next cycle lints the current revision. `fix` reads the page as it is now. |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 69960289e6..fcbb7576ff 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). | 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 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/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjs
index 6a27549637..18bdb75d43 100644
--- a/scripts/check-core-guard-coverage.mjs
+++ b/scripts/check-core-guard-coverage.mjs
@@ -38,6 +38,7 @@ const EXEMPT = {
'src/core/persistence/change-reason.ts': 'wraps the PreparedMutation preparePageMutation returned (service.ts) in place: the core guard, exclusiveSources and every other field are the guarded object\'s own',
'src/core/persistence/import-deferral.ts': 'withSupersedes wraps the PreparedMutation preparePageMutation returned (service.ts) in place: it only adds the supersedes trailer and the outcome field to a held blind put_page; the core guard, exclusiveSources and every other field are the guarded object\'s own',
'src/core/persistence/valid-time-advisory.ts': 'wraps the PreparedMutation withChangeReason returned (service.ts) in place: its apply only adds the read-only valid_time advisory to the outcome after the guarded apply; the core guard, exclusiveSources and every other field are the guarded object\'s own',
+ 'src/core/persistence/local-edit-adoption.ts': 'withAdoptedLocalEdit wraps the PreparedMutation preparePersistedMutation returned (service.ts) in place: its apply only adds the adopted field to the outcome after the guarded apply; the adoption it publishes is a managed_file_repair (file-repair.ts) of the bytes already in the owner checkout',
'src/core/persistence/noop-kernel.ts': 'decides that nothing would change; publishes nothing',
'src/core/generations/repair.ts': 'the managed restore of a database-only generation (chronicle event pages, never core pages) revives and retires derived items through the adapter inside the coordinated request',
'src/core/generations/managed.ts': 'the generation activation flips the derived ledger; it writes no page text (its member page writes go through preparePageMutation)',
diff --git a/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsv
index dbc628c90f..10886feebb 100644
--- a/scripts/core-world-reads-baseline.tsv
+++ b/scripts/core-world-reads-baseline.tsv
@@ -687,6 +687,7 @@ src/core/persistence/journal.ts process_env 1 W6: settings plane out of the core
src/core/persistence/large-file.ts fs_import 1 W5: repo-less persistence for hosts
src/core/persistence/links-preparation.ts module_collection 1 W6: per-engine state, or mark as a constant table
src/core/persistence/local-client.ts fs_import 1 W5: repo-less persistence for hosts
+src/core/persistence/local-edit-adoption.ts fs_import 1 W5: repo-less persistence for hosts (reads the drifted canonical file it adopts)
src/core/persistence/maintenance.ts fs_import 1 W5: repo-less persistence for hosts
src/core/persistence/native-file-target.ts fs_import 1 W5: repo-less persistence for hosts
src/core/persistence/native-lock.ts fs_import 2 W5: repo-less persistence for hosts
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index da911f5ef9..bbc9745ca6 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 1660 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); +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-1601 source_changed_origin_gst1601 row (since TBD until the merge slot; rows are data and cannot move)
+src/core/behavior-change-notice.ts 1661 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); +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-1601 source_changed_origin_gst1601 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-1601 part 2: the adopt_local_edits_gst1601 row
diff --git a/src/commands/doctor/checks/local-edit-adoptions.ts b/src/commands/doctor/checks/local-edit-adoptions.ts
new file mode 100644
index 0000000000..7a4196b60c
--- /dev/null
+++ b/src/commands/doctor/checks/local-edit-adoptions.ts
@@ -0,0 +1,40 @@
+/**
+ * `local_edit_adoptions` (GST-1601 part 2, persistence/local-edit-adoption.ts): per source, the one-sided local edits the
+ * 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.
+ */
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+
+const DOCS = 'docs/guides/write-refusals.md#file_database_drift';
+const MAX_PATHS = 20;
+
+interface SourceAdoptions { source_id: string; adoptions: number; paths: string[] }
+
+async function runLocalEditAdoptions(ctx: DoctorContext): Promise<Check[]> {
+ const engine = connectedEngine(ctx);
+ ctx.progress.heartbeat('local_edit_adoptions');
+ 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'
+ 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) {
+ checks.push({ name: 'local_edit_adoptions', status: 'ok', details: { sources, docs: DOCS }, message: 'No local edit was adopted in the last 24 h.' });
+ return checks;
+ }
+ checks.push({ name: 'local_edit_adoptions', status: 'ok', details: { sources, docs: DOCS },
+ message: `Local edits adopted in the last 24 h: ${sources.map(source => `${source.source_id}: ${source.adoptions} (${source.paths.join(', ')})`).join('; ')}. `
+ + 'Each was committed on its own before the write that met it; someone or something is editing these files outside gbrain.' });
+ } catch (error) {
+ checks.push({ name: 'local_edit_adoptions', status: 'ok', details: { health: 'unknown', docs: DOCS },
+ message: `Could not read local edit adoptions (${error instanceof Error ? error.message : String(error)}).` });
+ }
+ return checks;
+}
+
+export const localEditAdoptionsEntry: DoctorEntry = { name: 'local_edit_adoptions', emits: ['local_edit_adoptions'], run: runLocalEditAdoptions };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index b3da83367b..a7568e7ec2 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -132,6 +132,7 @@ import { fenceIntegrityEntry } from './checks/fence-integrity.ts';
import { outsideContentFencesEntry } from './checks/outside-content-fences.ts';
import { dbAheadOfGitEntry } from './checks/db-ahead-of-git.ts';
import { gitIndexLagEntry } from './checks/git-index-lag.ts';
+import { localEditAdoptionsEntry } from './checks/local-edit-adoptions.ts';
import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';
import { ghostPagesEntry } from './checks/ghost-pages.ts';
import { memberAccessEntry } from './checks/member-access.ts';
@@ -316,6 +317,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
dbAheadOfGitEntry,
// Git-canonical G3: how far each strict source's index trails the commit at HEAD.
gitIndexLagEntry,
+ // GST-1601: the one-sided local edits adopted in the last 24 h per source (informational, always ok).
+ localEditAdoptionsEntry,
// GBRA-221: live fence rows on imported pages whose body is outside-authored text (review only).
outsideContentFencesEntry,
// GBRA-248 W0: writes waiting on a long-quiet owner host, and a file plane that disables embeddings over a database with vectors.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index df1f4699d3..e65125a160 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1458,6 +1458,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', id: 'refresh_barrier_prb', text: 'New setting `persistence.refresh_barrier` (off by default): with it on, a single page write (`put_page`, `remember` and the other single-page verbs) that reaches a checkout while `gbrain sources refresh` drains or merges it is journaled and answered `pending` at once (MCP `isError: false`, CLI exit 10) instead of refused `worktree_refreshing`. It commits after the refresh, or ends `revision_conflict` when the refresh changed its file, or `refresh_barrier_expired` after `persistence.refresh_barrier_max_wait_ms` (15 minutes). Syncs, jobs and batches keep the refusal. `gbrain upgrade --check-downgrade` exits 3 `downgrade_blocked_deferred_writes` while such writes wait.' },
{ since: 'TBD', id: 'refresh_barrier_import_gst1582', text: 'With `persistence.refresh_barrier` on, no page write bounces because a sync is running: a `put_page`, `capture`, `remember` or `add_timeline_entry` whose page file holds a committed change managed sync has not imported yet is answered `pending` (receipt `deferred: { pending_import: true }`) instead of refused `pending_import`, and is prepared again once the import lands (a `put_page` with `expected_revision` then ends `revision_conflict` if the import moved the page; a blind one lands and names the revision and commit it replaced in `supersedes`, a `gbrain-supersedes:` commit trailer and the commit ledger), or ends `pending_import_expired` after the wait limit. A write during a refresh in `recovery_required` waits too, and `persistence.refresh_barrier_max_deferred` is no longer read: no write past it is refused. With the barrier off those refusals are unchanged. Wherever `worktree_refreshing` still refuses, `retry_after_ms` is estimated from the refresh (its typical duration minus how long it has run, at least 15 s while syncing and 2 s otherwise) instead of a fixed 1000, the message says the write was not saved and when to retry, and the CLI\'s human output ends with one line saying the same.' },
{ since: 'TBD', id: 'source_changed_origin_gst1601', text: 'A page write refused `source_changed` now records its cause in the receipt\'s `error_detail.origin` (`file_database_drift` for an uncoordinated local edit, `canonical_path_occupied`, `raw_file_changed`, `pinned_git_worktree_conflict`, `unsafe_file_target`, `source_binding_changed` or `unbound_source`), not only for `pending_import`, `sync_held` and `canonical_file_missing`, so `gbrain write-request`, doctor and receipt queries name it. Nothing else about the refusal changed, and none of these is replayed.' },
+ { since: 'TBD', id: 'adopt_local_edits_gst1601', text: 'New per-source opt-in `persistence.adopt_local_edits.source.<id>` (off by default): a `remember`, `capture` or `add_timeline_entry` whose page file holds a local edit nobody committed, while Git `HEAD` still holds the database\'s copy (on a repo-less brain, any such edit), is no longer refused `file_database_drift`. Once the file has been unchanged for `persistence.adopt_quiet_ms` (default 5000), the owner commits the edit on its own (only that file, subject `gbrain: adopt local edit to <path>`, trailers `gbrain-adopted:` and `gbrain-author: unknown`, a commit-ledger line; repo-less brains record it in the database only), keeps the replaced revision in page history with reason `adopted_local_edit`, then applies the write on top; its receipt names `adopted: { path, blob, replaced_revision }` and doctor `local_edit_adoptions` lists the last 24 h. An edit to the title, the type or a protected frontmatter key, a file that does not import, an edit on both sides, `put_page` and every other verb keep the refusal; a file changed again during the adoption ends `raw_file_changed` with nothing written.' },
{ since: 'TBD', id: 'commit_push_base_prb', text: '`gbrain git commit-push` takes `--base <path>=<blob>|absent` (repeatable, each path one the command commits): it refuses `commit_base_moved`, committing nothing, when the file at HEAD is no longer the blob the caller read. Without `--base` nothing changes.' },
{ since: 'TBD', id: 'file_drift_held_needs_prefer_8615', text: '`gbrain repair file-drift` with `--held`, `--side`, `--state`, `--cursor` or `--provenance` and no `--prefer` now refuses with the usage line (`invalid_params`, and `file_drift_state_required` for a deleted side without `--state`) instead of silently running the all-drifted survey, which counted a different set of pages (#8615).' },
{ since: 'TBD', id: 'refresh_source_changed_retry_8617', text: 'A `gbrain sources refresh` run refused `refresh_source_changed` because the checkout HEAD moved (a writer committing) or work reached the checkout after the drain check now retries once from a fresh precheck in the same run, so the tick is not lost (#8617). When the retry is refused too, the run returns the first `refresh_source_changed` refusal with the retry\'s cause appended; ownership or source-membership changes are not retried.' },
diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.ts
index e7500c5893..284bebaf08 100644
--- a/src/core/config-runtime-keys.ts
+++ b/src/core/config-runtime-keys.ts
@@ -23,5 +23,6 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = [
'sources.refresh_publish_diverged', // persistence/worktree-refresh.ts (#7686): refresh publishes a diverged checkout's local commits merged with the upstream before fast-forwarding, default off
'serve.vector_prewarm', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve prewarms the HNSW indexes into shared_buffers at start when they fit, default off
'mcp.stdio_member', // access/caller.ts (GBRA-218): binds a local stdio MCP server to one member; unbound, stdio reads no page that names readers
+ 'persistence.adopt_quiet_ms', // persistence/local-edit-adoption.ts (GST-1601): how long a local edit must be quiet before it is adopted, default 5000
'mcp.stdio_may_act_for', // access/audience.ts (GBRA-231): whom a local stdio server may act for (_meta.on_behalf_of); unset, stdio refuses every audience
];
diff --git a/src/core/config.ts b/src/core/config.ts
index 1c7c25b903..6ca37197ad 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1858,7 +1858,7 @@ export const KNOWN_CONFIG_KEY_PREFIXES: readonly string[] = [
'minions.',
'pace.', // pace.mode + PACE_MODE_CONFIG_KEYS (src/core/pace-mode.ts)
'decide.', // System One decide.* (validated by src/core/ai/decide/config.ts DECIDE_CONFIG_KEYS)
- 'sync.max_deletes.source.', 'sync.max_delete_ratio.source.', 'sync.apply_held_deletions.source.', // #7130 per-source delete caps, GBRA-133 per-source held-deletion switch
+ 'sync.max_deletes.source.', 'sync.max_delete_ratio.source.', 'sync.apply_held_deletions.source.', 'persistence.adopt_local_edits.source.', // #7130 per-source delete caps, GBRA-133 per-source held-deletion switch, GST-1601 per-source local-edit adoption
'connectors.', // chat-connectors: source_id, sync_floor_min, embed_kickoff_min_pages, doctor_stale_hours, <provider>.{auto_sync,last_sync_at,auth_error_at,watermark_iso} (no secrets — creds are file-plane)
];
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index c27cb81a94..d795485a06 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -241,6 +241,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'db_ahead_of_git',
// Git-canonical G3: how far each strict source's index trails HEAD (doctor/checks/git-index-lag.ts).
'git_index_lag',
+ // GST-1601: local edits adopted in the last 24 h per source (doctor/checks/local-edit-adoptions.ts).
+ 'local_edit_adoptions',
'edge_validity',
'text_projection_readiness',
'timeline_coverage',
diff --git a/src/core/git/commit-ledger.ts b/src/core/git/commit-ledger.ts
index 03112617d6..845314c9e3 100644
--- a/src/core/git/commit-ledger.ts
+++ b/src/core/git/commit-ledger.ts
@@ -32,12 +32,12 @@ export const LEDGER_ROTATE_BYTES = 4 * 1024 * 1024;
const LINE_MAX_BYTES = 1023;
const LOCK_WAIT_MS = 2_000;
-export interface LedgerCommit { sha: string; writer: LedgerWriter; ref?: string | null; request_id?: string | null; worktree_id?: string | null; supersedes?: string[] }
+export interface LedgerCommit { sha: string; writer: LedgerWriter; ref?: string | null; request_id?: string | null; worktree_id?: string | null; supersedes?: string[]; adopted?: string[] }
export interface LedgerIntent { writer: LedgerWriter; head_before: string | null; message: string }
export type LedgerRecord =
| { v: 1; e: 'start'; t: string }
- | { v: 1; e: 'commit'; t: string; sha: string; writer: LedgerWriter; request_id: string | null; worktree: string | null; worktree_id: string | null; ref: string | null; pid: number; host: string | null; supersedes?: string[] }
+ | { v: 1; e: 'commit'; t: string; sha: string; writer: LedgerWriter; request_id: string | null; worktree: string | null; worktree_id: string | null; ref: string | null; pid: number; host: string | null; supersedes?: string[]; adopted?: string[] }
| { v: 1; e: 'intent'; t: string; writer: LedgerWriter; head_before: string | null; msg_sha256: string; worktree: string | null; pid: number; host: string | null };
interface Location { common: string; gitDir: string; worktree: string | null }
@@ -110,7 +110,7 @@ function line(record: LedgerRecord): string {
function commitRecord(loc: Location, entry: LedgerCommit): LedgerRecord {
return { v: 1, e: 'commit', t: new Date().toISOString(), sha: entry.sha, writer: entry.writer, request_id: entry.request_id ?? null,
worktree: loc.worktree, worktree_id: entry.worktree_id ?? null, ref: entry.ref === undefined ? headRef(loc.gitDir) : entry.ref, pid: process.pid, host: hostId(),
- ...(entry.supersedes?.length ? { supersedes: entry.supersedes } : {}) };
+ ...(entry.supersedes?.length ? { supersedes: entry.supersedes } : {}), ...(entry.adopted?.length ? { adopted: entry.adopted } : {}) };
}
function intentRecord(loc: Location, intent: LedgerIntent): LedgerRecord {
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 5b17b26532..ce1a6b6086 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -31,6 +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 { timePublicationStep } from './publication-timing.ts';
import type { AppendedRange, GitCommitNote } from './effect-model.ts';
import { authorizePageVisibility } from './page-visibility.ts';
@@ -393,7 +394,10 @@ export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteRe
stage: PublicationStage = 'publication'): Promise<WriteRequest> {
const charged = await releaseChargedInterruption(engine, row, error, stage);
if (charged) return charged;
- const failure = withAttempt(requestError(error), stage, engine);
+ // 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;
+ 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;
if (held) return held;
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index a6e41c23cf..1d7fa8146d 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -5,7 +5,7 @@ import { gitDurabilityPolicy } from './git-durability-policy.ts';
import type { WorktreeBinding } from './ownership.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import type { GitCommitNote } from './effect-model.ts';
+import { adoptedBy, type GitCommitNote } from './effect-model.ts';
import { persistenceHome } from './identity.ts';
import { nativeFileTarget } from './native-file-target.ts';
import { gitChildEnv, literalPathspecs } from '../git-env.ts';
@@ -378,8 +378,9 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
} finally { if (messageDir) rmSync(messageDir, { recursive: true, force: true }); }
if (result.code === 0) {
const head = await git(session, ['rev-parse', 'HEAD']);
- const supersedes = supersededBy([...noted.values()].flatMap(note => note.trailers ?? []));
- if (head.code === 0) await recordCommitAsync(root, { sha: head.stdout.trim(), writer: 'effect', ...(supersedes.length ? { supersedes } : {}) });
+ const trailers = [...noted.values()].flatMap(note => note.trailers ?? []);
+ const supersedes = supersededBy(trailers), adopted = adoptedBy(trailers);
+ if (head.code === 0) await recordCommitAsync(root, { sha: head.stdout.trim(), writer: 'effect', ...(supersedes.length ? { supersedes } : {}), ...(adopted.length ? { adopted } : {}) });
}
const outcome = result.code === 0 ? { git: 'committed' } : gitFailure('Cannot commit the canonical Git target.',
`git commit failed for ${commitPaths.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);
diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.ts
index d93cb9c1e6..323b1bcc6e 100644
--- a/src/core/persistence/effect-model.ts
+++ b/src/core/persistence/effect-model.ts
@@ -33,6 +33,21 @@ export function fenceRepairCommit(path: string, classes: readonly string[], tier
export function contentRepairCommit(path: string, receipt: Pick<ContentRepairReceipt, 'tier' | 'confidence'>): GitCommitNote {
return { subject: contentRepairCommitSubject(path), line: `${safe(path)} (frontmatter_slug_conflict)`, trailers: [contentRepairTrailer(receipt)] };
}
+/** GST-1601: the trailer key of an adopted local edit's commit; its values ride the commit-ledger line (`adopted`). */
+export const ADOPTED_TRAILER_KEY = 'gbrain-adopted';
+/**
+ * GST-1601 an adopted local edit's note: subject `gbrain: adopt local edit to <path>`, trailers
+ * `gbrain-adopted: <path>: worktree blob <blob> over revision <revision>` and `gbrain-author: unknown` (nobody coordinated the edit).
+ */
+export function localEditAdoptionCommit(path: string, blob: string, revision: string): GitCommitNote {
+ return { subject: `gbrain: adopt local edit to ${safe(path)}`, line: `${safe(path)} (adopted local edit)`,
+ trailers: [`${ADOPTED_TRAILER_KEY}: ${safe(path)}: worktree blob ${blob} over revision ${revision}`, 'gbrain-author: unknown'] };
+}
+/** The `gbrain-adopted:` values among a commit's notes, for its ledger line. */
+export function adoptedBy(trailers: Iterable<string>): string[] {
+ const key = `${ADOPTED_TRAILER_KEY}: `;
+ return [...trailers].filter(trailer => trailer.startsWith(key)).map(trailer => trailer.slice(key.length));
+}
/** `rule`: for `git_target_ignored`, the .gitignore rule that excludes the file (`<file>:<line>: <pattern>`). */
export interface ParkedTarget { slug?: string; error_code: string; rule?: string }
/** #7423 / #7378: a settled target: under a declared db_only dir (`declared`), or its current bytes proved on the fetched remote (effect-settle.ts). */
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index d5bd2bab51..9d3686b7c4 100644
--- a/src/core/persistence/file-repair.ts
+++ b/src/core/persistence/file-repair.ts
@@ -74,7 +74,8 @@ import { screenSyncImport } from './sync-prepare.ts';
import type { SyncRename } from './sync-discovery.ts';
import type { PreparedContentImport } from './prepared-import.ts';
import type { PreparedMutation } from './coordinator.ts';
-import { contentRepairCommit, fenceRepairCommit } from './effect-model.ts';
+import { contentRepairCommit, fenceRepairCommit, localEditAdoptionCommit } from './effect-model.ts';
+import { ADOPTED_CHANGE_REASON, 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';
@@ -103,6 +104,8 @@ export interface ManagedFileRepairIntent extends Record<string, unknown> {
contentRepair?: ContentRepairReceipt;
/** #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 };
}
/** The repair command a refusal names (D6 router): a fence repair's, the content repair's, or the frontmatter repair's. */
@@ -327,11 +330,16 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
}
const fenceRepair = checkedFenceRepair(p, row.source_id);
const contentRepair = checkedContentRepair(p, row.source_id);
+ const adopted = p.adoptLocalEdit;
+ if (adopted !== undefined && (typeof adopted?.blob !== 'string' || typeof adopted.replaced_revision !== 'string' || 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.`);
+ }
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.`,
{ fix: ownerStatusFix(row.source_id) });
const root = join(binding.local_path, binding.relative_path);
+ const adoptNote = adopted ? localEditAdoptionCommit(p.path, adopted.blob, adopted.replaced_revision) : undefined;
const bytes = Buffer.from(p.content, 'utf8');
const fileChanges = sha256(bytes) !== p.beforeHash;
const checkFile = () => {
@@ -374,8 +382,10 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
return { observedRevision: snapshot?.revision ?? null, noop: ready.noop && !fileChanges && !moved, contentUnchanged: ready.noop && !fileChanges && !moved,
trust: await ownerImportTrust(engine, row, ready.parsedPage.frontmatter, p.sourcePath), deferEmbedding: p.noEmbed, ...(moved ? { additionalPageKeys: [{ sourceId: row.source_id, slug: moved.slug }] } : {}),
...(ready.afterCommit || moved ? { afterCommit: async (target: BrainEngine) => { await published.afterCommit?.(target); } } : {}),
- ...(fileChanges ? { file: { root, path: target, content: bytes, expectedBeforeHash: p.beforeHash,
- ...(fenceRepair ? { commit: fenceRepairCommit(p.path, fenceRepair.classes, fenceRepair.tier) } : contentRepair ? { commit: contentRepairCommit(p.path, contentRepair) } : {}) } } : {}),
+ ...(fileChanges || adopted ? { file: { root, path: target, content: bytes, expectedBeforeHash: p.beforeHash,
+ ...(adoptNote ? { commit: adoptNote }
+ : fenceRepair ? { commit: fenceRepairCommit(p.path, fenceRepair.classes, fenceRepair.tier) } : contentRepair ? { commit: contentRepairCommit(p.path, contentRepair) } : {}) } } : {}),
+ ...(adoptNote ? { afterEffects: (tx: BrainEngine, outcome: Record<string, unknown>) => commitAdoptedLocalEdit(tx, row.source_id, binding, target, adoptNote, outcome) } : {}),
validate: async tx => {
const current = await getWorktreeBinding(tx, row.source_id);
if (!current || current.worktree_id !== row.worktree_id || String(current.owner_epoch) !== p.ownerEpoch) throw opError('owner_unavailable', 'The repair owner changed.',
@@ -398,7 +408,9 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
applied = movedImport;
}
published = applied;
+ const [last] = adopted && snapshot ? await tx.executeRaw<{ id: number | string | null }>('SELECT max(id) AS id FROM page_versions WHERE page_id=$1', [snapshot.page.id]) : [];
const installed = await applied.apply(tx);
+ if (adopted && snapshot) await tx.executeRaw('UPDATE page_versions SET change_reason=$2 WHERE page_id=$1 AND id>$3', [snapshot.page.id, ADOPTED_CHANGE_REASON, Number(last?.id ?? 0)]);
await bindOrigin(tx, { sourceId: row.source_id, slug: row.slug, sourcePath: p.sourcePath });
// A body stored in segments was sealed by its import's apply when complete (sealSegmentedPage); the inline text seal reads the whole timeline.
if (!applied.noop) { await project(tx); if (!installed?.segmented) await sealPageTextProjection(tx, row.slug, row.source_id); }
@@ -410,6 +422,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
raw_sha256: sha256(importContent), gbrain_version: VERSION, revision: page.revision, parser: syncImportParserFor(p.sourcePath, screenConfig.packIdentity), ...syncDiskProvenance(bytes, null) });
return { status: moved ? 'renamed' : applied.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,
chunks: applied.result.chunks, imported_file: true, file_repaired: fileChanges, hold_cleared: holdCleared, ...(moved ? { renamed_from: moved.slug } : {}),
- ...(fenceRepair ? { fence_repair: fenceRepair } : {}), ...(contentRepair ? { content_repair: contentRepair } : {}) };
+ ...(fenceRepair ? { fence_repair: fenceRepair } : {}), ...(contentRepair ? { content_repair: contentRepair } : {}),
+ ...(adopted ? { adopted_local_edit: { path: p.path, blob: adopted.blob, replaced_revision: adopted.replaced_revision } } : {}) };
} };
}
diff --git a/src/core/persistence/git-door.ts b/src/core/persistence/git-door.ts
index f074e9d642..eaaf69ff09 100644
--- a/src/core/persistence/git-door.ts
+++ b/src/core/persistence/git-door.ts
@@ -45,7 +45,7 @@ import type { Notice } from '../agent-output.ts';
import { literalPathspecs } from '../git-env.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { commitMessage, commitMessageArgs, git, gitBytes, gitFailure, gitStepTimeoutMs, ignoredTargetError, reclaimAbandonedIndexLock, withSession, type GitSession } from './effect-git.ts';
-import type { GitCommitNote } from './effect-model.ts';
+import { adoptedBy, type GitCommitNote } from './effect-model.ts';
import { persistenceHome } from './identity.ts';
import { ignoreCandidates } from './ignore-rules.ts';
import { hashFile } from './large-file.ts';
@@ -329,8 +329,9 @@ async function doorCommit(session: GitSession, root: string, files: DoorFile[],
if (commit.code !== 0) throw gitFailure('Cannot commit the canonical Git target.',
`git commit-tree failed for ${changed.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);
const created = commit.stdout.trim();
- const supersedes = supersededBy([...noted.values()].flatMap(note => note.trailers ?? []));
- await recordCommitAsync(root, { sha: created, writer: 'door', ref: branch, ...(supersedes.length ? { supersedes } : {}) });
+ const trailers = [...noted.values()].flatMap(note => note.trailers ?? []);
+ const supersedes = supersededBy(trailers), adopted = adoptedBy(trailers);
+ await recordCommitAsync(root, { sha: created, writer: 'door', ref: branch, ...(supersedes.length ? { supersedes } : {}), ...(adopted.length ? { adopted } : {}) });
await doorSeams.beforeUpdateRef?.(root, attempt);
const moved = await git(session, ['update-ref', '-m', `commit: ${message[0]!.split('\n')[0]}`, branch, created, head]);
if (moved.code === 0) {
diff --git a/src/core/persistence/local-edit-adoption.ts b/src/core/persistence/local-edit-adoption.ts
new file mode 100644
index 0000000000..fa4c5ced66
--- /dev/null
+++ b/src/core/persistence/local-edit-adoption.ts
@@ -0,0 +1,197 @@
+/**
+ * GST-1601 part 2: a remember, capture or add_timeline_entry refused `source_changed` / `file_database_drift` because its
+ * page's canonical file holds a one-sided local edit (git HEAD still holds the database's copy, only the worktree file
+ * moved) adopts that edit, then applies on top. Per source and off by default: `persistence.adopt_local_edits.source.<id>`.
+ *
+ * The owner publishes the edit first as its own write: a `managed_file_repair` (file-repair.ts) carrying `adoptLocalEdit`,
+ * admitted under this installation's CLI writer (never the caller's principal) with a request id derived from the
+ * caller's, so a write adopts at most once. It imports the file's exact bytes under the hash it read (an edit landing
+ * before publication ends `raw_file_changed` and nothing is written), archives the replaced revision with change_reason
+ * `adopted_local_edit`, and, on a Git-durable checkout, commits only that file before its row commits: subject
+ * `gbrain: adopt local edit to <path>`, trailers `gbrain-adopted:` and `gbrain-author: unknown`, a commit-ledger line
+ * (`adopted`). A repo-less brain records the adoption in the database alone. The caller's claim is then released and its
+ * write prepared again from scratch; its receipt names `adopted: { path, blob, replaced_revision }`.
+ *
+ * Everything else keeps the refusal: another operation, a batch, the flag off, a held file, a two-sided edit (HEAD holds
+ * 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.
+ */
+import { randomUUID } from 'node:crypto';
+import { readFileSync, statSync } from 'node:fs';
+import { relative, 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 { gitBlobOid, sha256 } from './digest.ts';
+import { commitGitTargets } from './effect-git.ts';
+import { sourceCanonicalGit } from './git-door.ts';
+import { gitDurabilityPolicy } from './git-durability-policy.ts';
+import { withRegisteredLocalWriter } from './identity.ts';
+import { admitWrite, getWriteRequest, getWriteRequestById, publicationGroupKey, releaseUnpublishedClaim } from './journal.ts';
+import { isTerminal, type WriteRequest } from './model.ts';
+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 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';
+const ADOPT_QUIET_DEFAULT_MS = 5_000;
+/** A file is waited on for at most this many quiet windows. */
+const QUIET_WINDOWS = 3;
+/** How long the adoption retries a worktree lock another owner task holds. */
+const LOCK_RETRY_MS = 10_000;
+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 } = {};
+
+/** The drifted file a `file_database_drift` refusal carries (page-prepare.ts compareFileTarget). */
+interface LocalEditTarget { root: string; path: string }
+export interface AdoptedLocalEdit { path: string; blob: string; replaced_revision: string }
+
+export async function adoptLocalEditsOn(engine: BrainEngine, sourceId: string): Promise<boolean> {
+ const value = await engine.getConfig(`persistence.adopt_local_edits.source.${sourceId}`).catch(() => null);
+ 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);
+ return Number.isFinite(value) && value >= 0 ? Math.min(value, 60_000) : ADOPT_QUIET_DEFAULT_MS;
+}
+/** 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. */
+async function settled(path: string, quiet: number): Promise<boolean> {
+ const deadline = Date.now() + quiet * QUIET_WINDOWS;
+ for (;;) {
+ const age = Date.now() - statSync(path).mtimeMs;
+ if (age >= quiet) return true;
+ if (Date.now() + quiet - age > deadline) return false;
+ await new Promise(resolve => setTimeout(resolve, quiet - age));
+ }
+}
+
+/** 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;
+ const bytes = readFileSync(target.path);
+ const text = bytes.toString('utf8');
+ const head = await headCommit(target.root) ? 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;
+ const { prepareRepairPublication, repairScreenConfig } = await import('./file-repair.ts');
+ const screen = await repairScreenConfig(engine, row.source_id);
+ if (await protectedLocalEdit(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 });
+ if (publication.status !== 'ready') return null;
+ const 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 }, source_id: row.source_id, request_id: adoptionRequestId(row) } };
+}
+
+/** Claims, prepares and publishes the admitted adoption, retrying while another owner task holds the worktree lock. */
+async function publishAdoption(engine: BrainEngine, admitted: WriteRequest, path: string): Promise<WriteRequest> {
+ const { finishUnpublishedFailure, publishMutation } = await import('./coordinator.ts');
+ const { prepareManagedFileRepairMutation } = await import('./file-repair.ts');
+ const deadline = Date.now() + LOCK_RETRY_MS;
+ let row = admitted;
+ for (;;) {
+ const [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()]);
+ });
+ if (!claimed) return (await getWriteRequestById(engine, row.id))!;
+ try {
+ const prepared = await prepareManagedFileRepairMutation(engine, claimed, { engine: engine.kind } as GBrainConfig);
+ localEditAdoptionSeams.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;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+}
+
+/**
+ * The owner's answer to a drift refusal of `row` (coordinator.ts finishUnpublishedFailure): `released` once the local edit
+ * 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> {
+ 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
+ || publicationGroupKey(row) !== null || !await adoptLocalEditsOn(engine, row.source_id)) return null;
+ const binding = await getWorktreeBinding(engine, row.source_id);
+ if (!binding?.local_path) return null;
+ let admission: Awaited<ReturnType<typeof adoptionIntent>>;
+ let admitted: WriteRequest | null;
+ try {
+ if (!await settled(target.path, await quietMs(engine))) return null;
+ admission = await adoptionIntent(engine, row, target, binding);
+ if (!admission) return null;
+ const params = admission.params;
+ const ctx = { engine, sourceId: row.source_id, remote: false, dryRun: false, config: { engine: engine.kind } as GBrainConfig,
+ logger: { info() {}, warn() {}, error() {} } } as OperationContext;
+ admitted = await withRegisteredLocalWriter(engine, 'cli', async writer => {
+ if (await getWriteRequest(engine, writer.principal, params.request_id)) return null;
+ const { preparePageAdmission } = await import('./page-mutations.ts');
+ const prepared = await preparePageAdmission(ctx, { operation: 'put_page', params, managedFileImport: true });
+ return prepared.prior ? null : admitWrite(engine, prepared.admission);
+ });
+ } catch { return null; }
+ if (!admitted) return null;
+ const done = await publishAdoption(engine, admitted, target.path);
+ if (done.state === 'committed') {
+ 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'`,
+ [row.id, row.execution_token, JSON.stringify({ adopted_local_edit: admission.adopted })]);
+ await releaseUnpublishedClaim(tx, row, 'local_edit_adopted');
+ });
+ return { released: (await getWriteRequestById(engine, row.id))! };
+ }
+ 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.',
+ `The canonical file of ${row.slug} in source ${row.source_id} changed again while gbrain adopted its local edit, so nothing was written. Read the file, then submit the write again with a new request_id.`) };
+ }
+ return null;
+}
+
+/**
+ * The adoption's Git commit, made in its publication transaction before the row commits (file-repair.ts afterEffects):
+ * only the adopted file, with the adoption's note, on a Git-durable checkout. A strict source's door already committed
+ * it; a repo-less brain has nothing to commit. A commit that fails rolls the adoption back.
+ */
+export async function commitAdoptedLocalEdit(tx: BrainEngine, sourceId: string, binding: WorktreeBinding, path: string, note: GitCommitNote, outcome: Record<string, unknown>): Promise<void> {
+ const root = binding.local_path!;
+ if (await sourceCanonicalGit(tx, sourceId) || !await headCommit(root) || !(await gitDurabilityPolicy(binding, root)).durable) return;
+ const rel = relative(root, path).split(sep).join('/');
+ 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) });
+}
+
+/** A write prepared again after its local edit was adopted names the adoption on its receipt (`adopted`). */
+export function withAdoptedLocalEdit(row: WriteRequest, prepared: PreparedMutation): PreparedMutation {
+ const adopted = row.intent?.adopted_local_edit as AdoptedLocalEdit | undefined;
+ if (!adopted) return prepared;
+ const apply = prepared.apply.bind(prepared);
+ prepared.apply = async (tx, preimage) => ({ ...await apply(tx, preimage) as Record<string, unknown>, adopted });
+ return prepared;
+}
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 64122a7171..4c0a7678c7 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -267,6 +267,19 @@ async function frontmatterDriftWrite(engine: BrainEngine, slug: string, fileText
return digest(check.frontmatter) === digest(file.frontmatter) && check.title === file.title && check.type === incoming.type && digest(check.tags) === digest(file.tags)
&& check.compiled_truth === incoming.compiled_truth && (check.timeline ?? '') === (incoming.timeline ?? '') ? spliced : null;
}
+/**
+ * GST-1601: whether a local edit changes what an adoption must never take without a person: the title, the type, or a
+ * policy, protected, access, lineage or trust-lowering frontmatter key (the keys frontmatterDriftWrite never splices).
+ */
+export async function protectedLocalEdit(engine: BrainEngine, slug: string, fileText: string, snapshot: PageSnapshot, activePack?: ParseOpts['activePack']): Promise<boolean> {
+ snapshot = (await materializedSnapshot(engine, snapshot))!;
+ const file = parseMarkdown(fileText, slug, { activePack });
+ if (file.title !== snapshot.page.title || importedFileType(file, snapshot.page, false) !== snapshot.page.type) return true;
+ const fileFrontmatter = comparableFrontmatter(withoutSafetyAssessments(file.frontmatter));
+ const stored = comparableFrontmatter(withoutSafetyAssessments(snapshot.page.frontmatter ?? {}));
+ return [...new Set([...Object.keys(fileFrontmatter), ...Object.keys(stored)])].some(key => digest(fileFrontmatter[key] ?? null) !== digest(stored[key] ?? null)
+ && (POLICY_KEYS.has(key) || protectedReconcileKey(key) || SPLICE_REFUSED_KEYS.has(key) || key === 'slug'));
+}
/** The type a file's parse compares with (`fileMatchesSnapshot`), after aligning the parse with what its import over `page` stores. */
function importedFileType(parsed: ParsedMarkdown, page: Pick<Page, 'type' | 'frontmatter'>, inferred: boolean): Page['type'] {
// #5521 parity for subtype (#5928): a pack rule is not part of the file's bytes, so a file
@@ -467,10 +480,12 @@ async function compareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 's
const spliced = !adopt.length && options.deleting !== true && typeof content === 'string' && before instanceof Buffer && !bodyUnread(snapshot.page) && before.length <= PUSH_SCAN_MAX_FILE_BYTES
? await frontmatterDriftWrite(engine, row.slug, before.toString('utf8'), snapshot, content, options.activePack) : null;
if (spliced !== null) return { path, root, content: spliced, expectedBeforeHash: beforeHash() };
- throw opError('source_changed', 'The canonical file contains an uncoordinated local edit.',
+ // GST-1601: the drifted file rides the refusal, so the owner can adopt a one-sided local edit (local-edit-adoption.ts).
+ throw Object.assign(opError('source_changed', 'The canonical file contains an uncoordinated local edit.',
`On the brain host, run gbrain sources reconcile ${row.source_id} ${row.slug} --brain <brain id, host by default> --preview${adopt.length ? ' --adopt-slug-path (the page records no file of its own, so the preview adopts the file at its slug path)' : ''}, review and apply the resolved preview, then retry this write with a new request_id. Neither copy was overwritten.`,
{ detail: 'file_database_drift', fix: readFix(`Previews how page ${row.slug}'s canonical file and database copy reconcile; a preview never changes canonical content.`,
- { argv: ['gbrain', 'sources', 'reconcile', row.source_id, row.slug, '--brain', 'host', '--preview', ...adopt] }) });
+ { argv: ['gbrain', 'sources', 'reconcile', row.source_id, row.slug, '--brain', 'host', '--preview', ...adopt] }) }),
+ adopt.length || options.deleting === true ? {} : { localEdit: { root, path } });
}
} else if (before && !snapshot && content !== null && beforeHash() !== fileContentHash(content)
&& !(options.capture && beforeHash() === options.capture.hash)) {
diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.ts
index 183c6d94d0..947d75ddb2 100644
--- a/src/core/persistence/pending-import.ts
+++ b/src/core/persistence/pending-import.ts
@@ -97,6 +97,11 @@ export async function headBlob(root: string, path: string, signal?: AbortSignal)
return quiet(gitRead(root, ['rev-parse', '--verify', '--quiet', `HEAD:./${relative(root, path).split(sep).join('/')}`], signal), signal);
}
+/** The bytes of blob `blob` in `root`'s repository as text, or null when Git cannot read it. */
+export async function blobText(root: string, blob: string, signal?: AbortSignal): Promise<string | null> {
+ return gitRead(root, ['cat-file', 'blob', blob], signal).then(out => out, error => { if (signal?.aborted) throw error; return null; });
+}
+
/**
* The blob id HEAD holds at `path` when the working-tree file there is exactly that blob (`hash-object` applies the
* path's clean filters, as `git add` would); null when the file differs, is absent, or HEAD has no entry there.
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index c2a787f905..47c067bd3d 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -1,6 +1,7 @@
import { PENDING_IMPORT, pendingImportRefusal } from './pending-import.ts';
import { deferredWaiting } from './refresh-barrier.ts';
import { withSupersedes } from './import-deferral.ts';
+import { withAdoptedLocalEdit } from './local-edit-adoption.ts';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { OperationError } from '../ops/contract.ts';
@@ -81,6 +82,10 @@ export function registerMutationPreparer(operation: string, prepare: PrepareMuta
* phase clock, which carries the preparation's cancellation to every preparer's `enterClaimStep` boundaries.
*/
export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest, cfg: GBrainConfig, signal?: AbortSignal, clock?: ClaimPhaseClock) {
+ // GST-1601: a write prepared again after its page's local edit was adopted names the adoption on its receipt.
+ return withAdoptedLocalEdit(row, await prepareByOperation(e, row, cfg, signal, clock));
+}
+async function prepareByOperation(e: BrainEngine, row: WriteRequest, cfg: GBrainConfig, signal?: AbortSignal, clock?: ClaimPhaseClock) {
assertMutationProtocol(row);
enterClaimStep(clock, 'dispatch');
const registered = preparers.get(row.operation);
diff --git a/test/adopt-local-edit.test.ts b/test/adopt-local-edit.test.ts
new file mode 100644
index 0000000000..d921d90771
--- /dev/null
+++ b/test/adopt-local-edit.test.ts
@@ -0,0 +1,314 @@
+/**
+ * GST-1601 part 2: a remember, capture or add_timeline_entry onto a page whose canonical file holds a one-sided local
+ * edit (git HEAD and the database agree, only the worktree file moved) adopts that edit, then applies on top.
+ *
+ * Protects: with `persistence.adopt_local_edits` on for the page's source, the edit is published first as its own
+ * owner-internal write (`managed_file_repair` carrying `adoptLocalEdit`): one commit of only that file, subject
+ * `gbrain: adopt local edit to <path>`, trailers `gbrain-adopted:` and `gbrain-author: unknown`, a commit-ledger line,
+ * page_versions keeping the replaced revision with change_reason `adopted_local_edit`; then the caller's write is
+ * prepared again and lands as its own commit, its receipt naming `adopted`. Everything else keeps today's
+ * `source_changed` / `file_database_drift` refusal and writes nothing: protected frontmatter drift, a file that does not
+ * parse, a two-sided edit (HEAD differs from the database), put_page, the flag off, the flag on for another source. A
+ * file still changing waits out `persistence.adopt_quiet_ms` (bounded), a file changed between the adoption's
+ * preparation and publication ends `raw_file_changed` with nothing written, a repo-less brain adopts into the database
+ * alone, and doctor `local_edit_adoptions` reports the adoption.
+ * Seams: the refresh fixture (one clone, sources alpha and beta), managedBrain for the repo-less case, the effect
+ * worker run in-process, `localEditAdoptionSeams.beforePublish`.
+ */
+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { disposePersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';
+import { getWriteRequestById } from '../src/core/persistence/journal.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readLedger } from '../src/core/git/commit-ledger.ts';
+import { isTerminal, type WriteRequest } from '../src/core/persistence/model.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { commitFile, git, page, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }
+ await closePostgres?.();
+});
+afterEach(async () => {
+ const adoption = await import('../src/core/persistence/local-edit-adoption.ts').catch(() => null);
+ if (adoption) adoption.localEditAdoptionSeams.beforePublish = undefined;
+});
+
+const setConfig = (engine: BrainEngine, key: string, value: string) => engine.executeRaw(
+ 'INSERT INTO config(key,value) VALUES($1,$2) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value', [key, value]);
+const clearConfig = (engine: BrainEngine) => engine.executeRaw("DELETE FROM config WHERE key LIKE 'persistence.adopt%'");
+
+/** The fixture with Git durability on, a Git identity, and adoption on for `on` (alpha by default) with no quiet window. */
+const each = (fn: (f: RefreshFixture) => Promise<void>, opts: { on?: 'alpha' | 'beta' | 'none'; quietMs?: number } = {}) => (async () => {
+ for (const engine of engines) await withRefreshFixture(engine, async f => {
+ git(f.root, 'config', 'user.name', 'Example'); git(f.root, 'config', 'user.email', '[email protected]'); git(f.root, 'config', 'commit.gpgsign', 'false');
+ await f.engine.executeRaw("UPDATE persistence_host_bindings SET git_durability='enabled'");
+ await clearConfig(f.engine);
+ const on = opts.on ?? 'alpha';
+ if (on !== 'none') await setConfig(f.engine, `persistence.adopt_local_edits.source.${on === 'alpha' ? f.alpha : f.beta}`, 'true');
+ await setConfig(f.engine, 'persistence.adopt_quiet_ms', String(opts.quietMs ?? 0));
+ try { await fn(f); } finally { await clearConfig(f.engine); }
+ });
+})();
+
+async function call(f: RefreshFixture, name: string, params: Record<string, unknown>) {
+ const result = await dispatchToolCall(f.engine, name, params, { remote: true, transport: 'stdio', sourceId: f.alpha, admissionOrigin: 'interactive' });
+ return { isError: result.isError === true, body: JSON.parse(result.content[0]!.text) as Record<string, any> };
+}
+/** A local CLI write; its receipt whether it settled or was left pending. */
+async function local(f: RefreshFixture, operation: 'put_page' | 'capture', params: Record<string, unknown>): Promise<Record<string, any>> {
+ try { return await submitPageMutation(f.ctx(f.alpha), { operation, params: { request_id: randomUUID(), ...params } }) as Record<string, any>; }
+ catch (error) {
+ const e = error as { code?: string; writeError?: string; writeRequest?: Record<string, any> };
+ if ((e.code === 'write_pending' || e.writeError === 'write_pending') && e.writeRequest) return e.writeRequest;
+ throw error;
+ }
+}
+/** The engine is shared across tests: rows are scoped to the fixture's sources (or the repo-less brain's `default`). */
+type Scope = { engine: BrainEngine; alpha?: string; beta?: string };
+const sources = (s: Scope) => s.alpha ? [s.alpha, s.beta!] : ['default'];
+const lastRow = async (s: Scope, operation: string) => (await s.engine.executeRaw<WriteRequest>(
+ "SELECT * FROM persistence_requests WHERE operation=$1 AND source_id=ANY($2::text[]) AND COALESCE(intent->>'kind','')<>'managed_file_repair' ORDER BY sequence DESC LIMIT 1", [operation, sources(s)]))[0]!;
+const adoptionRows = (s: Scope) => s.engine.executeRaw<WriteRequest>(
+ "SELECT * FROM persistence_requests WHERE source_id=ANY($1::text[]) AND intent->>'kind'='managed_file_repair' AND intent ? 'adoptLocalEdit' ORDER BY sequence", [sources(s)]);
+/** The request's final row: waits for it while the resident consumer works. */
+async function settled(engine: BrainEngine, row: WriteRequest): Promise<WriteRequest> {
+ const current = (await getWriteRequestById(engine, row.id))!;
+ return isTerminal(current) ? current : waitForWrite(engine, current, { engine: engine.kind } as never, 30_000);
+}
+const file = (f: RefreshFixture, rel: string) => readFileSync(join(f.root, 'alpha', rel), 'utf8');
+const LOCAL = 'A local edit nobody committed.';
+const EDITED = page('Alpha one', `The first alpha observation.\n\n${LOCAL}`);
+const blobOf = (f: RefreshFixture, rel: string) => git(f.root, 'hash-object', '--', `alpha/${rel}`);
+const revision = async (f: RefreshFixture, slug: string) => (await f.engine.readPageSnapshot(slug, { sourceId: f.alpha }))!.revision;
+const head = (f: RefreshFixture) => git(f.root, 'rev-parse', 'HEAD');
+
+/** Runs the effect worker until request `id`'s Git effect has committed. */
+async function gitEffectDone(f: RefreshFixture, id: string): Promise<void> {
+ for (let i = 0; i < 100; i++) {
+ await runPersistenceEffects(f.engine, { engine: f.engine.kind } as never, { hostId: localHostId() });
+ const [effect] = await f.engine.executeRaw<{ state: string }>("SELECT state FROM persistence_effects WHERE request_id=$1::uuid AND kind='git'", [id]);
+ if (effect?.state === 'committed') return;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ throw new Error(`the Git effect of request ${id} did not commit`);
+}
+
+/** Every observable of one adoption followed by the caller's write. */
+/** `replaces`: the caller's write replaces the page body (a capture), so the edit survives in the adopt commit and history only. */
+async function expectAdopted(f: RefreshFixture, done: WriteRequest, rel: string, slug: string, blob: string, replaced: string, callerText: string, replaces = false) {
+ expect(done).toMatchObject({ state: 'committed' });
+ expect((done.outcome as { adopted?: unknown }).adopted).toEqual({ path: rel, blob, replaced_revision: replaced });
+ const content = file(f, rel);
+ if (!replaces) expect(content).toContain(LOCAL);
+ expect(content).toContain(callerText);
+ await gitEffectDone(f, done.id);
+ const [caller, adopt] = git(f.root, 'log', '-2', '--format=%H', '--', `alpha/${rel}`).split('\n');
+ const message = git(f.root, 'log', '-1', '--format=%B', adopt!);
+ expect(message.split('\n')[0]).toBe(`gbrain: adopt local edit to ${rel}`);
+ const note = `${rel}: worktree blob ${blob} over revision ${replaced}`;
+ expect(message).toContain(`gbrain-adopted: ${note}`);
+ expect(message).toContain('gbrain-author: unknown');
+ expect(message).not.toContain(done.principal_id);
+ expect(git(f.root, 'show', '--name-only', '--format=', adopt!).split('\n').filter(Boolean)).toEqual([`alpha/${rel}`]);
+ expect(git(f.root, 'show', `${adopt}:alpha/${rel}`)).toContain(LOCAL);
+ expect(git(f.root, 'show', `${adopt}:alpha/${rel}`)).not.toContain(callerText);
+ expect(git(f.root, 'log', '-1', '--format=%s', caller!)).not.toContain('adopt local edit');
+ expect(git(f.root, 'show', `${caller}:alpha/${rel}`)).toContain(callerText);
+ const line = readLedger(join(f.root, '.git')).find(r => r.e === 'commit' && r.sha === adopt) as { adopted?: string[] } | undefined;
+ expect(line?.adopted).toEqual([note]);
+ const [adoption] = await adoptionRows(f);
+ expect(adoption).toMatchObject({ state: 'committed', principal_kind: 'local_cli' });
+ expect(adoption!.id).not.toBe(done.id);
+ const versions = await f.engine.executeRaw<{ compiled_truth: string; change_reason: string | null }>(
+ 'SELECT v.compiled_truth, v.change_reason FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY v.id', [f.alpha, slug]);
+ const replacedVersion = versions.find(v => v.change_reason === 'adopted_local_edit');
+ expect(replacedVersion).toBeDefined();
+ expect(replacedVersion!.compiled_truth).not.toContain(LOCAL);
+}
+
+test('an add_timeline_entry onto an uncommitted body edit adopts the edit in its own commit, then lands on top', () => each(async f => {
+ 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 added onto the local edit.' });
+ expect(out.isError).toBe(false);
+ const done = await settled(f.engine, await lastRow(f, 'add_timeline_entry'));
+ expect(done.principal_kind).toBe('local_stdio');
+ await expectAdopted(f, done, 'one.md', 'one', blob, replaced, 'Entry added onto the local edit.');
+}), 180_000);
+
+test('a capture onto an uncommitted body edit adopts the edit, then lands on top', () => each(async f => {
+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);
+ const blob = blobOf(f, 'one.md'), replaced = await revision(f, 'one');
+ await local(f, 'capture', { slug: 'one', content: 'Captured onto the local edit.', force: true });
+ const done = await settled(f.engine, await lastRow(f, 'capture'));
+ await expectAdopted(f, done, 'one.md', 'one', blob, replaced, 'Captured onto the local edit.', true);
+}), 180_000);
+
+const PERSON = '---\ntitle: Alice Example\ntype: person\n---\nAlice is a person.\n';
+
+test('a remember onto an uncommitted body edit adopts the edit, then lands on top', () => each(async f => {
+ commitFile(f.root, 'alpha/people/alice-example.md', PERSON, 'person page');
+ await performManagedSync(f.engine, { sourceId: f.alpha, noPull: true, noEmbed: true });
+ writeFileSync(join(f.root, 'alpha', 'people', 'alice-example.md'), PERSON.replace('Alice is a person.', `Alice is a person.\n\n${LOCAL}`));
+ const blob = blobOf(f, 'people/alice-example.md'), replaced = await revision(f, 'people/alice-example');
+ const out = await call(f, 'remember', { fact: 'alice-example likes tea', entity: 'people/alice-example', provenance: 'test' });
+ expect(out.isError).toBe(false);
+ const done = await settled(f.engine, await lastRow(f, 'remember'));
+ await expectAdopted(f, done, 'people/alice-example.md', 'people/alice-example', blob, replaced, 'alice-example likes tea');
+}), 180_000);
+
+/** A write onto `content` that must keep today's refusal and write nothing. */
+async function expectRefused(f: RefreshFixture, content: string, run: () => Promise<unknown>, operation: string) {
+ writeFileSync(join(f.root, 'alpha', 'one.md'), content);
+ const before = { head: head(f), revision: await revision(f, 'one') };
+ await run().catch(() => undefined);
+ const row = await settled(f.engine, await lastRow(f, operation));
+ expect(row).toMatchObject({ state: 'conflict', error_code: 'source_changed' });
+ expect((row.error_detail as { origin?: string } | null)?.origin).toBe('file_database_drift');
+ expect(file(f, 'one.md')).toBe(content);
+ expect(head(f)).toBe(before.head);
+ expect(await revision(f, 'one')).toBe(before.revision);
+ expect(await adoptionRows(f)).toEqual([]);
+}
+const timeline = (f: RefreshFixture) => () => call(f, 'add_timeline_entry', { slug: 'one', date: '2026-11-06', summary: 'Must not land.' });
+
+test('protected frontmatter drift keeps the refusal', () => each(async f => {
+ await expectRefused(f, page('Alpha renamed', `The first alpha observation.\n\n${LOCAL}`), timeline(f), 'add_timeline_entry');
+ await expectRefused(f, EDITED.replace('type: note\n', 'type: note\nreadable_by: [alice-example]\n'), timeline(f), 'add_timeline_entry');
+}), 180_000);
+
+test('a file that does not parse keeps the refusal', () => each(async f => {
+ await expectRefused(f, `---\ntitle: Alpha one\ntype: note\nbroken: [unclosed\n---\nThe first alpha observation.\n\n${LOCAL}\n`, timeline(f), 'add_timeline_entry');
+}), 180_000);
+
+test('a two-sided edit (HEAD moved past the database) keeps the refusal', () => each(async f => {
+ commitFile(f.root, 'alpha/one.md', page('Alpha one', 'The first alpha observation.\n\nCommitted but not imported.'), 'another writer');
+ await expectRefused(f, page('Alpha one', `The first alpha observation.\n\nCommitted but not imported.\n\n${LOCAL}`), timeline(f), 'add_timeline_entry');
+}), 180_000);
+
+test('put_page keeps the refusal, blind and with expected_revision', () => each(async f => {
+ await expectRefused(f, EDITED, () => local(f, 'put_page', { slug: 'one', content: page('Alpha one', 'Replaced.'), force: true }), 'put_page');
+ const seen = await revision(f, 'one');
+ await expectRefused(f, EDITED, () => call(f, 'put_page', { slug: 'one', content: page('Alpha one', 'Replaced.'), expected_revision: seen }), 'put_page');
+}), 180_000);
+
+test('with the flag off the refusal is unchanged', () => each(async f => {
+ await expectRefused(f, EDITED, timeline(f), 'add_timeline_entry');
+}, { on: 'none' }), 180_000);
+
+test('with the flag on for another source only the refusal is unchanged', () => each(async f => {
+ await expectRefused(f, EDITED, timeline(f), 'add_timeline_entry');
+}, { on: 'beta' }), 180_000);
+
+test('a file still changing is not adopted until it settles, then lands', () => each(async f => {
+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);
+ const pending = call(f, 'add_timeline_entry', { slug: 'one', date: '2026-11-06', summary: 'Entry after the edits settled.' });
+ await new Promise(resolve => setTimeout(resolve, 400));
+ expect(await adoptionRows(f)).toEqual([]);
+ writeFileSync(join(f.root, 'alpha', 'one.md'), page('Alpha one', `The first alpha observation.\n\n${LOCAL}\n\nA second local edit.`));
+ const blob = blobOf(f, 'one.md');
+ await new Promise(resolve => setTimeout(resolve, 600));
+ expect(await adoptionRows(f)).toEqual([]);
+ await pending;
+ const done = await settled(f.engine, await lastRow(f, 'add_timeline_entry'));
+ expect(done.state).toBe('committed');
+ expect((done.outcome as { adopted?: { blob?: string } }).adopted?.blob).toBe(blob);
+ expect(file(f, 'one.md')).toContain('A second local edit.');
+ expect(file(f, 'one.md')).toContain('Entry after the edits settled.');
+}, { quietMs: 1500 }), 180_000);
+
+test('a file that never settles within the bound keeps the refusal', () => each(async f => {
+ 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 {
+ await call(f, 'add_timeline_entry', { slug: 'one', date: '2026-11-06', summary: 'Must not land.' });
+ const row = await settled(f.engine, await lastRow(f, 'add_timeline_entry'));
+ expect(row).toMatchObject({ state: 'conflict', error_code: 'source_changed' });
+ expect((row.error_detail as { origin?: string } | null)?.origin).toBe('file_database_drift');
+ } finally { clearInterval(timer); }
+ expect(await adoptionRows(f)).toEqual([]);
+}, { quietMs: 300 }), 180_000);
+
+test('a file changed between the adoption\'s preparation and publication ends raw_file_changed with nothing written', () => each(async f => {
+ const { localEditAdoptionSeams } = await import('../src/core/persistence/local-edit-adoption.ts');
+ writeFileSync(join(f.root, 'alpha', 'one.md'), EDITED);
+ const before = { head: head(f), revision: await revision(f, 'one') };
+ const RACED = page('Alpha one', 'The first alpha observation.\n\nA third writer raced the adoption.');
+ localEditAdoptionSeams.beforePublish = path => { writeFileSync(path, RACED); };
+ await call(f, 'add_timeline_entry', { slug: 'one', date: '2026-11-06', summary: 'Must not land.' });
+ const row = await settled(f.engine, await lastRow(f, 'add_timeline_entry'));
+ expect(row).toMatchObject({ state: 'conflict', error_code: 'source_changed' });
+ expect((row.error_detail as { origin?: string } | null)?.origin).toBe('raw_file_changed');
+ const [adoption] = await adoptionRows(f);
+ expect(adoption).toMatchObject({ state: 'conflict', error_code: 'source_changed' });
+ expect((adoption!.error_detail as { origin?: string } | null)?.origin).toBe('raw_file_changed');
+ expect(file(f, 'one.md')).toBe(RACED);
+ expect(head(f)).toBe(before.head);
+ expect(await revision(f, 'one')).toBe(before.revision);
+}), 180_000);
+
+test('doctor local_edit_adoptions reports the adoptions of the last 24 h per source', () => each(async f => {
+ const { localEditAdoptionsEntry } = await import('../src/commands/doctor/checks/local-edit-adoptions.ts');
+ const run = async () => (await localEditAdoptionsEntry.run({ engine: f.engine, progress: { heartbeat() {} } } as never) as Array<{ name: string; status: string; message: string; details?: any }>)[0]!;
+ expect(await run()).toMatchObject({ name: 'local_edit_adoptions', status: 'ok' });
+ 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 check = await run();
+ expect(check).toMatchObject({ name: 'local_edit_adoptions', status: 'ok' });
+ expect(check.details.sources.filter((s: { source_id: string }) => s.source_id === f.alpha || s.source_id === f.beta)).toEqual([{ source_id: f.alpha, adoptions: 1, paths: ['one.md'] }]);
+ expect(check.message).toContain(f.alpha);
+}), 180_000);
+
+const SLUG = 'people/owner-example';
+test('a repo-less brain adopts the edit into the database alone', 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}`);
+ writeFileSync(path, edited);
+ const replaced = (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).toBe('committed');
+ const bytes = Buffer.from(edited);
+ const blob = createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
+ expect((done.outcome as { adopted?: unknown }).adopted).toEqual({ path: `${SLUG}.md`, blob, replaced_revision: replaced });
+ const content = readFileSync(path, 'utf8');
+ expect(content).toContain(LOCAL);
+ expect(content).toContain('Owner prefers async updates');
+ const versions = await engine.executeRaw<{ change_reason: string | null }>(
+ "SELECT v.change_reason FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id='default' AND p.slug=$1", [SLUG]);
+ expect(versions.some(v => v.change_reason === 'adopted_local_edit')).toBe(true);
+ }, backend === 'postgres' ? { databaseUrl: process.env.DATABASE_URL } : {});
+}, 180_000);
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index 4d352920c9..a4f2bbe052 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -249,6 +249,7 @@
" [OK] person_title_duplicates: No title-prefixed person page pairs with an unprefixed page (0 titled page(s) examined).",
" [OK] db_ahead_of_git: Informational, nothing to do: the database compared with the commit at HEAD, per source with a Git checkout. notes: 5 equal. Page detail: gbrain sources git-gap <source-id>.",
" [OK] git_index_lag: No source is strict (git-canonical), so no index trails a commit.",
+ " [OK] local_edit_adoptions: No local edit was adopted in the last 24 h.",
" [OK] outside_content_fences: No fact, take or link is indexed from a fence on an imported email, calendar, GitHub or transcript page.",
" [OK] owner_host_stale: No managed write is waiting on an owner host.",
" [OK] embedding_plane_disagreement: The config file disables embeddings and the database holds no vectors.",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 54908d7284..deaba2923f 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -3803,6 +3803,17 @@
"name": "git_index_lag",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/write-refusals.md#file_database_drift",
+ "sources": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No local edit was adopted in the last 24 h.",
+ "name": "local_edit_adoptions",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index acaa292ff5..4a90131159 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -4070,6 +4070,17 @@
"name": "git_index_lag",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/write-refusals.md#file_database_drift",
+ "sources": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No local edit was adopted in the last 24 h.",
+ "name": "local_edit_adoptions",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -9119,6 +9130,17 @@
"name": "git_index_lag",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/write-refusals.md#file_database_drift",
+ "sources": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No local edit was adopted in the last 24 h.",
+ "name": "local_edit_adoptions",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index d880b34555..4a0a4c7c1b 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -3432,6 +3432,17 @@
"name": "git_index_lag",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/write-refusals.md#file_database_drift",
+ "sources": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No local edit was adopted in the last 24 h.",
+ "name": "local_edit_adoptions",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 5414b1e932..e6a6616d99 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -3475,6 +3475,17 @@
"name": "git_index_lag",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/write-refusals.md#file_database_drift",
+ "sources": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No local edit was adopted in the last 24 h.",
+ "name": "local_edit_adoptions",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 85da325630..d0d169f31b 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -3478,6 +3478,17 @@
"name": "git_index_lag",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/write-refusals.md#file_database_drift",
+ "sources": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No local edit was adopted in the last 24 h.",
+ "name": "local_edit_adoptions",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index d54baa8dfe..c861fffdf3 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -1065,6 +1065,10 @@
"category": "brain",
"name": "git_index_lag"
},
+ {
+ "category": "brain",
+ "name": "local_edit_adoptions"
+ },
{
"category": "brain",
"name": "outside_content_fences"
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 0b9929ccc7..6ed4751961 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -25,6 +25,7 @@ test/access-page-indexes-online.test.ts
test/access-qm-actor.test.ts
test/access-writes.test.ts
test/activation-unbound-rooted-6449.test.ts
+test/adopt-local-edit.test.ts
test/alias-source-cascade-5094.test.ts
test/attribution-backfill-history.test.ts
test/backstop-same-page-shadow-managed-6333.test.ts