Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(6948): guard bookkeeping, legacy-twin fixtures, e2e index restore

garrytan12e7d468f8cc
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index a0a0d8fa6b..04f05dc02f 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -19,6 +19,8 @@ src/commands/migrations/v0_32_2.ts 2 coordinator On a managed brain each entity
src/commands/pages.ts 2 engine_guard Both engine references are dry-run previews (the --dry-run listing and the D6 consent count before a hard purge, #6114); the purge runs purgeDeletedPagesCoordinated, which is coordinated on managed brains.
src/commands/reconcile-links.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
src/commands/reindex-aliases.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
+src/core/persistence/twin-merge.ts 10 coordinator The #6948 twin merge (links in every role, link transitions, timeline, raw data, files, user tags, aliases and facts move onto the canonical page; the twin is marked origin_twin and soft-deleted) runs only inside the managed_maintenance_resolve_origin_twin preparer's coordinated transaction on managed brains, or one maintenanceTransaction on unmanaged brains, after the group verdict is rechecked under both page locks; it writes no file, so there is no filesystem ordering to keep.
+src/core/repair/origin-twins.ts 1 coordinator gbrain repair origin-twins and the post-sync heal resolve each verified twin as a receipted managed_maintenance_resolve_origin_twin request (submitDatabaseMaintenanceIntent, owner host only) on managed brains and in one maintenanceTransaction on unmanaged brains; the verdict is recomputed inside the write and any drift holds the file instead of merging.
src/core/search-vector-backfill.ts 2 projection backfillPageVectors (reindex-search-vector, the fts_cjk_boundary migration) rewrites only pages.search_vector, through the seal's pageSearchVectorSql over the sanitized timeline and guarded by the knowledge revision it read (its read is an UPDATE-to-self of id); canonical fields are untouched and the managed writer guard passes search_vector-only updates.
src/commands/sources-set-path.ts 1 coordinator Managed rebind uses native exclusion, exact manifest verification and a retained source-incarnation receipt; unmanaged pointer repair remains explicit.
src/commands/sources.ts 10 coordinator Managed add/archive/restore/remove/purge/reclone route through source lifecycle; remaining legacy canonical SQL stays fenced.
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 60850de65a..5a6914eb68 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -256,6 +256,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/facts/relink-publish.ts` (2): `relink_facts` request preparer.
- `src/core/facts/unfenced-facts.ts` (2): the cycle and v0.32.2 fence of `row_num`-NULL facts: a maintenance request on managed brains; the unmanaged body mirror and row-number stamp run in `maintenanceTransaction`.
- `src/core/facts/withdrawal.ts` (1): runs inside the `forget` request's coordinated write.
+- `src/core/persistence/twin-merge.ts` (5): the #6948 twin merge runs in the `managed_maintenance_resolve_origin_twin` preparer's coordinated transaction on managed brains and in one `maintenanceTransaction` on unmanaged brains (`gbrain repair origin-twins` and the post-sync heal).
- `src/core/trust/timeline-projection.ts` (2): `gbrain extract` timeline walks (file, incremental, stale) and the per-entry fallback write through it: one `maintenanceTransaction` per page tier.
- `src/core/facts/write-single.ts` (2): the legacy single-fact insert and its supersession link each run in `maintenanceTransaction`; managed brains publish through the fact request.
- `src/core/import-file.ts` (12): direct markdown, code and image imports, the moved-file rename (`updateSlug`) and the #3694 legacy-hash re-stamp run in `maintenanceTransaction`; managed imports go through the page request preparer.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 7406200baa..511d2cee9b 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -1007,6 +1007,50 @@ that page. Any other error, such as a storage fault, an unavailable owner or
contention, still stops the apply; rerun the same apply command once it clears.
<a id="rename-identity"></a>
+<a id="origin-twins"></a>
+### Origin twins
+
+`gbrain repair origin-twins --source <id>` (#6948) resolves duplicate-origin twins: several live pages of one source
+recording the same file as their origin, which managed sync holds [`origin_conflict`](write-refusals.md#origin_conflict)
+while the rest of the source syncs. It is explicit-only, preview-bound and destructive, runs only on the source's
+canonical owner host (`not_owner_host` elsewhere), and refuses a remote caller.
+
+The preview lists each group with its pages, ids, revisions and verdict, using the same rule as sync:
+
+- **Verified duplicates** (no reason): exactly one page is the page the path names, every page holds the same inline
+ body, the file is readable, no two explicit frontmatter `id`s differ, the pages share one visibility and one trust
+ tier, no other page has slug-keyed fact withdrawals or purges or a file at its own slug path, and no other page holds a
+ manual link, relationship date, timeline entry or raw payload that differs from the canonical page's. The apply
+ merges each other page into the canonical one. Links in every role, link transitions, timeline rows, raw data,
+ attachments, user-added tags, free-text aliases and facts other pages assert move to it; an exact duplicate, or a link
+ re-derived from the shared body, is dropped. The twin's slug becomes an alias. The twin forgets the file, is marked
+ `origin_twin` and is soft-deleted (the file is untouched), and the 72 h retention purge removes it database-only.
+ Its receipt (`origin_twin_resolved`) lists every frontmatter key of the twin the canonical page lacks or holds
+ differently, with the twin's value, plus the restore command. The canonical page's frontmatter comes from the file,
+ so add any key you want to keep to the file.
+- **A decision** (a reason): listed with the commands to decide it, never resolved by a plain apply. With
+ `--slug <kept-slug>` the preview offers only to *detach* the other pages: they forget the file, are marked
+ `origin_twin` and stay live as database-only pages. Nothing is deleted.
+
+A page marked `origin_twin` never writes or removes a file again: `gbrain restore` brings back its own text as a
+database-only page, an edit publishes database-only, and an owner `--purge` is refused because its content is the
+canonical page's (the retention purge still removes it). A later file at its own slug path, imported by sync, clears the
+marker.
+
+The apply refuses [`origin_twin_mass_merge_refused`](error-codes.md#origin_twin_mass_merge_refused) when its merges
+would soft-delete more than half of the source's file-backed pages, unless `GBRAIN_ALLOW_MASS_RECONCILE=1`.
+
+**Sync-time heal.** After each successful managed sync, held files whose pages are still verified duplicates are merged
+the same way, at most 200 files per run and 1,000 twin pages per source per 24 h, and never on a dry run, under a remote
+job, with an unfinished sync cursor, or above the mass valve. `gbrain sync --json` reports it as
+`origin_twins_resolved`. Opt out with `gbrain config set sync.origin_twins.auto_resolve false` (default on, like
+`sync.slug_conflicts.auto_remove`).
+
+**The index.** Migration v257 builds the partial unique index `pages_live_origin_key` (one live page per recorded
+origin; `CREATE UNIQUE INDEX CONCURRENTLY` on Postgres) only when the brain has no twins. With twins the migration
+changes nothing and succeeds, and doctor's `origin_twins` check reports "Index pending". Once the last group is
+resolved, the repair's apply builds the index.
+
### Rename identity
When sync cannot confirm an inexact Git rename (#6729), it imports the pair as a
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index a20d536fb5..cb0c23e581 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -123,6 +123,7 @@ Every hold and error has three fields, from one table
| `write_gate_rejected` | page | none | yes | always: write_gate.external_mode=reject is the user's setting |
| `legacy_slug_conflict` | page | none | yes | always: only a person decides which legacy page the file takes over |
| `origin_conflict` | page | repair | no | the hold carries a reason (the pages differ, ids conflict or none is the page the path names), or the heal is off |
+| `origin_conflict_decision` | page | none | yes | always: the pages differ, their ids conflict or none is the page the path names |
| `revision_conflict` | page | retry | no | the same path fails again after a rerun |
| `page_identity_changed` | page | retry | no | the same path fails again after a rerun |
| `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun |
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index e75e70a6cd..a193600daf 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -202,6 +202,7 @@ with each file and fix the ones that need no guessing."*
| <a id="purged_content"></a>`purged_content` | The file (or written content) has the content hash of a page the owner purged with `gbrain delete <slug> --purge`, under any slug, or carries a purged claim the database refuses. Purge leaves a text-free tombstone so a stale file, re-sync or revert cannot bring the content back. | Delete or edit the file and commit; an edited file imports normally. Only if the purge was a mistake, the owner lists tombstones with `gbrain pages purges list` and clears one with `gbrain pages unpurge <slug>` on the brain host; a managed-sync hold re-screens on every sync, so the next one imports it. A Google or GitHub connector item refused this way is skipped and the sync continues; `gbrain sources status` lists it ("skipped as purged content"). See [expire versus purge](memory-boundaries.md#purge). |
| <a id="write_gate_rejected"></a>`write_gate_rejected` | The source is untrusted, the file reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request), and the operator set `write_gate.external_mode` to `reject`, so the file is never imported and always visible. Managed sync holds it when it freezes the file (#6712 PR 2; before, the refusal came at preparation and blocked the rest of the source); an owner allow rule (`gbrain trust allow`) covering the source and the file's path admits it at freeze exactly as at preparation. The hold is `needs_human`, and every sync re-screens it, so the setting switched or an allow rule added clears it on the next sync. | Tell the user; whether to edit the file or switch `write_gate.external_mode` back to `quarantine` is their decision. |
| <a id="legacy_slug_conflict"></a><a id="legacy_slug_conflict-explicit_id_conflict"></a>`legacy_slug_conflict` (`explicit_id_conflict`) | The file has no page at its slug, and several live pages an older gbrain imported before the current slug fold (a space, an emoji, an accent or a trailing dash in the slug; no recorded file) fold to that slug (#6727). Exactly one such page is taken over by the file: the next sync imports into it (same page id, links, timeline and aliases) and records the file as its origin, instead of creating a second page. With several, sync cannot tell which page is the file's, so it holds the file and the rest of the source syncs. It holds the file the same way when the one match has a slug sync cannot write as it stands (capital letters, from a gbrain that predates lowercase slugs; the importer lowercases), rather than creating a second page beside it. With reason `explicit_id_conflict` (#6729), the one match carries an explicit frontmatter `id` that differs from the file's, so it is a different document and is not taken over. With `sync.holds=fail` the run stops with `page_identity_changed`. Twins an older sync already created are not merged by this. | Ask the user which page is the file's (`gbrain sync status --source <source> --json` names every candidate slug). Remove each other one with `gbrain delete --source <source> -- '<slug>'` (soft delete, recoverable for 72 h), or rename the file if none of them is its page; with one match under a slug with capitals, which no command can address yet, keep the file held or rename it to a name that folds to another slug (it then imports as a new page beside the old one, which keeps its links). For `explicit_id_conflict`: give the file the page's `id` if it is the same document; otherwise rename the file or delete the old page. Then `gbrain sync --source <source> --no-pull`. The hold re-screens on every sync. |
+| <a id="origin_conflict"></a><a id="origin_conflict-no_canonical_claimant"></a><a id="origin_conflict-content_differs"></a><a id="origin_conflict-file_unreadable"></a><a id="origin_conflict-explicit_id_conflict"></a><a id="origin_conflict-visibility_differs"></a><a id="origin_conflict-trust_tier_differs"></a><a id="origin_conflict-twin_has_withdrawals"></a><a id="origin_conflict-twin_slug_path_occupied"></a><a id="origin_conflict-twin_evidence_conflicts"></a>`origin_conflict` (`no_canonical_claimant`, `content_differs`, `file_unreadable`, `explicit_id_conflict`, `visibility_differs`, `trust_tier_differs`, `twin_has_withdrawals`, `twin_slug_path_occupied`, `twin_evidence_conflicts`) | Several live pages of the source record this file as their origin (duplicate-origin twins, #6948). Sync used to stop the whole source with `page_identity_changed`; now only this file is held and the rest of the source syncs. With no reason the pages are verified duplicates: the page the path names (`meta.canonical_slug`), one inline body, a readable file, no conflicting frontmatter ids, one visibility and trust tier, no slug-keyed fact withdrawals or purges, no file at a twin's own slug path and no link, relationship date, timeline entry or raw payload the merge would lose. Right after that managed sync, the heal merges each other page into the canonical one (links, relationship dates, timeline, raw data, user tags, aliases and facts move; its slug becomes an alias; it is soft-deleted without touching the file, restorable for 72 h) and the next sync imports the file. A reason means a person decides: `no_canonical_claimant` (no page, or not exactly one, is the page the path names), `content_differs` (the bodies differ, or one cannot be read), `file_unreadable`, `explicit_id_conflict` (different frontmatter `id`s), `visibility_differs`, `trust_tier_differs` (a merge never raises or lowers a tier), `twin_has_withdrawals`, `twin_slug_path_occupied`, `twin_evidence_conflicts`. With `sync.holds=fail` the run stops with `page_identity_changed`. | `gbrain repair origin-twins --source <source>` (read-only) lists every group with its pages, revisions and verdict. Verified groups: let the next sync heal them, or apply the preview now. A decision: read each page (`gbrain get --source <source> -- '<slug>'`), then either `gbrain repair origin-twins --source <source> --slug '<kept-slug>'` (the others forget the file and stay live; nothing is deleted) or soft-delete the others with `gbrain delete`. Then `gbrain sync --source <source> --no-pull`. The heal's kill switch is `gbrain config set sync.origin_twins.auto_resolve false`. The hold re-screens on every sync. Guide: [origin twins](repair.md#origin-twins). |
| <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. |
| <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. |
| <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one. Pages under `storage.keep_db` prefixes are never held: the entry is skipped and the keep_db worker reconciles the page from the database. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. A changed file or page revision re-screens the hold by itself. |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 07f8b9a094..56937e8a21 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -12,7 +12,7 @@ src/commands/extract.ts 2635 ratchet grown v0.46.26.0 megawave: FS-walk stamp sn
src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes
src/commands/serve-http.ts 937 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts)
src/core/ai/gateway.ts 4523 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text
-src/commands/sync.ts 546 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone)
+src/commands/sync.ts 548 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts)
src/core/cycle.ts 3322 ratchet +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts)
src/core/cycle/synthesize.ts 3224 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts
src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count
@@ -36,8 +36,8 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
-src/core/config.ts 1985 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys)
-src/core/persistence/sync-run.ts 1778 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured
+src/core/config.ts 1986 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts)
+src/core/persistence/sync-run.ts 1782 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts)
src/core/bootstrap/harness.ts 2584 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 716 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts)
@@ -45,5 +45,5 @@ src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker
src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
src/commands/doctor/checks/extraction-sync.ts 1492 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge)
src/core/search/evidence-delivery.ts 1712 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
-src/commands/config.ts 1511 ratchet 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)
+src/commands/config.ts 1512 ratchet 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)
src/commands/mcp-expose.ts 1512 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)
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index c8e80478ff..79c501e37e 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -396,6 +396,7 @@ src/core/persistence/memory-mutations.ts planRememberTarget call:serializePageTo
src/core/persistence/memory-mutations.ts planRememberTarget field STREAM
src/core/persistence/memory-prepare.ts prepareMemoryMutation call:serializePageToMarkdown SEGW assertInlineBody first
src/core/persistence/memory-prepare.ts prepareMemoryMutation field SEGW assertInlineBody before the fence write
+src/core/persistence/origin-twins.ts readOriginClaimants sql STREAM #6948 twin verdict: md5 of an inline body; a segmented page (compiled_truth NULL) reads NULL and holds content_differs, so missing evidence never matches
src/core/persistence/overwritten-edits.ts CONTENT_COLUMNS sql STREAM selects body_storage beside the inline body columns; a segmented version or page has NULL bodies and its overwrite is reported unknown (reason segmented), never compared or restored
src/core/persistence/overwritten-edits.ts overwriteContent field STREAM returns null for a segmented row (body_storage segmented or NULL compiled_truth); the scan reports that overwrite unknown (reason segmented)
src/core/persistence/overwritten-edits.ts overwriteDigest field STREAM inline content only: called on overwriteContent results, which are null for a segmented row
diff --git a/src/commands/doctor/checks/origin-twins.ts b/src/commands/doctor/checks/origin-twins.ts
index 655920ead4..b9bbf91fe7 100644
--- a/src/commands/doctor/checks/origin-twins.ts
+++ b/src/commands/doctor/checks/origin-twins.ts
@@ -13,28 +13,35 @@ import { originIndexState, originTwinCounts, originTwinsRepairCommand, ORIGIN_IN
const DOCS = 'docs/guides/repair.md#origin-twins';
async function runOriginTwins(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
try {
const engine = connectedEngine(ctx);
const index = await originIndexState(engine);
- if (index === 'present') return [{ name: 'origin_twins', status: 'ok', details: { index, docs: DOCS }, message: `${ORIGIN_INDEX.name} is present: no two live pages can record one file.` }];
+ if (index === 'present') {
+ checks.push({ name: 'origin_twins', status: 'ok', details: { index, docs: DOCS }, message: `${ORIGIN_INDEX.name} is present: no two live pages can record one file.` });
+ return checks;
+ }
const sources = await originTwinCounts(engine);
if (sources.length) {
const first = sources[0]!.source_id;
- return [{ name: 'origin_twins', status: 'warn', details: { index, sources, docs: DOCS },
+ checks.push({ name: 'origin_twins', status: 'warn', details: { index, sources, docs: DOCS },
message: `Index pending: ${sources.map(s => `source ${s.source_id} has ${s.groups} file(s) recorded by several live pages (${s.twins} extra page(s))`).join('; ')}. `
+ `Sync holds each such file origin_conflict and imports the rest. Preview the fix with ${originTwinsRepairCommand(first)} (writes nothing); its apply builds ${ORIGIN_INDEX.name} once no source has a group.`,
fix: agentFix(['gbrain', 'repair', 'origin-twins', '--source', first, '--json'],
'Read-only preview: lists each duplicate-origin group with its pages, revisions and verdict, and prints the apply command with its hash. Apply only after the user agrees (merged twins are soft-deleted; their file stays).',
- 'origin_twins', { docs: DOCS }) }];
+ 'origin_twins', { docs: DOCS }) });
+ return checks;
}
const [source] = await engine.executeRaw<{ id: string }>("SELECT id FROM sources ORDER BY (id = 'default') DESC, id LIMIT 1");
- return [{ name: 'origin_twins', status: 'warn', details: { index, sources: [], docs: DOCS },
- message: `Index pending: no duplicate-origin twins remain, but ${ORIGIN_INDEX.name} is ${index}. Build it with ${originTwinsRepairCommand(source?.id ?? 'default')} --apply --expect <hash from its preview> --yes (online; writes no page).`,
- fix: agentFix(['gbrain', 'repair', 'origin-twins', '--source', source?.id ?? 'default', '--json'],
- 'Read-only preview of an empty set; its printed apply command builds the index online and changes no page.', 'origin_twins', { docs: DOCS }) }];
+ const id = source?.id ?? 'default';
+ checks.push({ name: 'origin_twins', status: 'warn', details: { index, sources: [], docs: DOCS },
+ message: `Index pending: no duplicate-origin twins remain, but ${ORIGIN_INDEX.name} is ${index}. Build it with ${originTwinsRepairCommand(id)} --apply --expect <hash from its preview> --yes (online; writes no page).`,
+ fix: agentFix(['gbrain', 'repair', 'origin-twins', '--source', id, '--json'],
+ 'Read-only preview of an empty set; its printed apply command builds the index online and changes no page.', 'origin_twins', { docs: DOCS }) });
} catch (error) {
- return [checkError('origin_twins', 'check for duplicate-origin twins and the origin index', error, { details: { index: 'unknown', docs: DOCS } })];
+ checks.push(checkError('origin_twins', 'check for duplicate-origin twins and the origin index', error, { details: { index: 'unknown', docs: DOCS } }));
}
+ return checks;
}
export const originTwinsEntry: DoctorEntry = { name: 'origin_twins', emits: ['origin_twins'], run: runOriginTwins };
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 501751e313..05269fb6ea 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -892,6 +892,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// #6932 hotfix (abandoned index-lock reclaim, scaled Git step deadlines) and #6936 (advisor collector failures).
{ since: '0.60.295.0', text: 'On a managed brain the canonical writer now removes a Git index lock (`.git/index.lock`) in its checkout by itself when it can prove the lock is abandoned (Linux with every process visible, a local filesystem, no process holding the lock open, no git running in or pointed at the checkout, and the lock empty and at least 5 s old or older than 10 minutes), then retries the Git effects that lock had parked. Each removal leaves a receipt in GBRAIN_HOME/persistence/index-lock-reclaims.jsonl, and doctor `parked_effects` reports them. A lock it cannot prove abandoned is kept, as before. Each Git effect step now gets 20 s plus 2 s per MiB of index (at most 120 s) and 10 s to exit after SIGTERM, and `git status` there no longer takes the index lock.' },
{ since: '0.60.295.0', text: '`gbrain advisor` reports a check that failed to run as a warn finding `collector_failed:<check>` and exits 1, instead of leaving it out and possibly reporting a healthy brain with exit 0.' },
+ { since: '0.60.296.0', text: 'Managed sync no longer stops a whole source when several live pages record one file as their origin (duplicate-origin twins, #6948): only that file is held `origin_conflict` and the rest syncs. When the pages are verified duplicates (the page the path names, one body, a readable file, compatible ids, one visibility and trust tier, nothing the merge would lose), the sync merges the others into it right after the run: their links, relationship dates, timeline, raw data, user tags, aliases and facts move, their slugs become aliases, and they are soft-deleted without touching the file (restorable for 72 h; the receipt lists any frontmatter they carried that the file lacks). Opt out with `gbrain config set sync.origin_twins.auto_resolve false`. Any other group stays held for a person: `gbrain repair origin-twins --source <id>` previews every group, and `--slug <kept-slug>` detaches the others without deleting them. New index `pages_live_origin_key` makes a new twin unwritable; it is built only on a brain with no twins, so with twins the upgrade changes nothing and doctor `origin_twins` reports "Index pending" until the repair resolves them.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index ce35407e29..3545ca7209 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -203,7 +203,7 @@ export function maintenanceDriftRefusal(sourceId: string, slug: string): Operati
* retirement, which exists to soft-delete pages whose canonical file is gone): a missing canonical file publishes, so it is no ghost.
*/
export const PUBLISHES_WITHOUT_FILE: ReadonlySet<string> = new Set(['managed_maintenance_chronicle_event', 'managed_maintenance_chronicle_retire', 'managed_maintenance_retire_stale_atoms',
- 'managed_maintenance_retire_ghost_page', 'managed_maintenance_resolve_origin_twin']);
+ 'managed_maintenance_retire_ghost_page']);
/** #6696 (A12): `source_changed` / `canonical_file_missing` before admission: the page's recorded file is gone; never a new request. */
export function maintenanceGhostRefusal(sourceId: string, slug: string): OperationError {
diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.ts
index 29857301ee..98f9ea14ea 100644
--- a/src/core/persistence/public-category.ts
+++ b/src/core/persistence/public-category.ts
@@ -34,7 +34,7 @@ export const PUBLIC_BY_TERMINAL: Readonly<Record<TerminalCategory, PublicCategor
/** Fault codes (holds, run stops, receipts) by name; a test pins that every `SYNC_FAULT_TABLE` code is here. */
export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {
worktree_dirty: 'drift', file_drift: 'drift', source_changed: 'drift', pinned_git_worktree_conflict: 'drift',
- concurrent_write: 'conflict', revision_conflict: 'conflict', page_identity_changed: 'conflict', legacy_slug_conflict: 'conflict', origin_conflict: 'conflict',
+ concurrent_write: 'conflict', revision_conflict: 'conflict', page_identity_changed: 'conflict', legacy_slug_conflict: 'conflict', origin_conflict: 'conflict', origin_conflict_decision: 'conflict',
invalid_fence: 'content_refused', invalid_frontmatter: 'content_refused', frontmatter_slug_conflict: 'content_refused', rename_held: 'content_refused',
file_too_large: 'content_refused', content_rejected: 'content_refused', managed_image_sync_unsupported: 'content_refused',
purged_content: 'content_refused', write_gate_rejected: 'content_refused',
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index bae5942e23..57293455e8 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -721,7 +721,7 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
}
const keep = claimants.find(page => page.slug === canonical);
const soft = claimants.filter(page => page !== keep).map(page => `gbrain delete --source-id ${source} --expected-revision ${page.revision} -- '${page.slug}'`);
- return { argv: ['gbrain', 'get', '--source', source, '--', claimants[0]?.slug ?? canonical], consent: [], actor: 'user', requires_exclusive: false, docs: `docs/guides/write-refusals.md#origin_conflict-${record.meta.reason}`,
+ return { argv: ['gbrain', 'get', '--source', source, '--', claimants[0]?.slug ?? canonical], consent: [], actor: 'user', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#origin_conflict',
user_message: `Pages ${named} all record ${record.path} as their origin, and sync cannot prove they are one document (${record.meta.reason}), so it held only this file; the rest of the source keeps syncing. `
+ `Read each page (gbrain get --source ${source} -- '<slug>'), pick the one that is this file's page and soft-delete each other one (the file stays, restorable for 72 h)`
+ (soft.length ? `, for example: ${soft.join('; ')}` : '') + `; then run gbrain sync --source ${source} --no-pull. gbrain repair origin-twins --source ${source} lists the group and its commands.`,
diff --git a/src/core/repair/origin-twins.ts b/src/core/repair/origin-twins.ts
index 926e22ee8c..e310aca2e3 100644
--- a/src/core/repair/origin-twins.ts
+++ b/src/core/repair/origin-twins.ts
@@ -213,6 +213,17 @@ export const originTwinsRepair: RepairHandler = {
const command = originTwinsRepairCommand(sourceId);
const keep = opts?.slugs?.length ? opts.slugs : undefined;
if (keep && keep.length !== 1) throw opError('invalid_params', 'gbrain repair origin-twins --slug names the one page that keeps a file.', `Name one slug per run: ${command} --slug '<kept-slug>'.`, { fix: previewFix(sourceId), docs: DOCS });
+ const context = await originOwnerContext(engine, sourceId);
+ if (!context.ok) {
+ // Off the owner host (or with no checkout bound) a source that holds no twin has nothing to resolve; the index needs no checkout.
+ const stored = await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL GROUP BY source_path HAVING count(*) > 1 LIMIT 1', [sourceId]);
+ if (stored.length) throw ownerRefusal(sourceId, context.reason);
+ const hash = previewHash({ kind: 'origin-twins-v1', brain_id: scope.brain_id, selection: { source_ids: scope.source_ids }, empty: true });
+ if (!opts?.apply) return { items: [], preview_hash: hash, residuals: { groups: 0 }, warnings: [`Source ${sourceId} has no duplicate-origin group; --apply builds the pages_live_origin_key index once no source has one.`] };
+ const built = await buildOriginIndexIfClean(engine, ORIGIN_INDEX_MIGRATION);
+ return { items: [], preview_hash: opts.expect ?? hash, residuals: { index_present: built.state === 'present' ? 1 : 0 }, warnings: [built.state === 'pending'
+ ? `pages_live_origin_key stays pending: ${built.sources.map(s => `source ${s.source_id} still has ${s.groups} group(s)`).join(', ')}.` : `pages_live_origin_key: ${built.state}.`] };
+ }
const scan = await scanOriginTwins(engine, sourceId);
const chosen = keep ? scan.groups.filter(group => group.claimants.some(page => page.slug === keep[0])) : scan.groups;
const pairs = chosen.flatMap(group => groupPairs(group, keep?.[0]));
diff --git a/test/e2e/helpers.ts b/test/e2e/helpers.ts
index 98a3ef15db..a969828992 100644
--- a/test/e2e/helpers.ts
+++ b/test/e2e/helpers.ts
@@ -10,6 +10,7 @@
import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
import { join, resolve, relative, dirname, basename, extname } from 'path';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { ORIGIN_INDEX } from '../../src/core/persistence/origin-index.ts';
import * as db from '../../src/core/db.ts';
import { importFromContent } from '../../src/core/import-file.ts';
import { parseMarkdown } from '../../src/core/markdown.ts';
@@ -173,6 +174,9 @@ export async function setupDB(options: { replayMigrations?: boolean } = {}): Pro
// MIGRATIONS array and only run when engine.initSchema() executes them.
// Idempotent: re-running migrations on an already-migrated DB is a no-op.
await engine.initSchema();
+ // #6948: a test that seeds legacy origin twins drops pages_live_origin_key, which the migrations do not rebuild on
+ // an already-migrated database; the emptied tables hold no twin, so every file starts with the index a fresh brain has.
+ await engine.executeRaw(ORIGIN_INDEX.sql);
return engine;
}
diff --git a/test/e2e/managed-sync-shared-origin-6517.test.ts b/test/e2e/managed-sync-shared-origin-6517.test.ts
index 5325d4eadc..b7723eae7a 100644
--- a/test/e2e/managed-sync-shared-origin-6517.test.ts
+++ b/test/e2e/managed-sync-shared-origin-6517.test.ts
@@ -1,7 +1,8 @@
/**
* #6517 (GBRA-79 wave 16, G3.3 [R7]): the managed sync path end to end with a
* duplicate-origin twin. Two live pages of the source record one file: the
- * run refuses `page_identity_changed` and names the soft-delete exit. After
+ * run holds that file `origin_conflict` (#6948; it used to refuse the whole
+ * source with `page_identity_changed`). After
* the loser is soft-deleted (the shared-origin delete keeps the file), the run
* imports the file into the survivor through both origin guards (discovery
* census, `assertSyncPageOrigin` at preparation and publication), then edits
@@ -25,6 +26,7 @@ import { operations, type OperationContext } from '../../src/core/operations.ts'
import { claimWorktree } from '../../src/core/persistence/ownership.ts';
import { performManagedSync } from '../../src/core/persistence/sync-run.ts';
import { readManagedSyncFailures } from '../../src/core/persistence/sync-failures.ts';
+import { readGitSourceHolds } from '../../src/core/persistence/sync-holds.ts';
import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
@@ -32,6 +34,7 @@ import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { testBackends } from '../helpers/test-backends.ts';
import { withEnv } from '../helpers/with-env.ts';
+import { dropOriginIndex } from '../helpers/origin-index.ts';
const op = (name: string) => operations.find(o => o.name === name)!;
const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
@@ -73,6 +76,7 @@ for (const backend of testBackends()) describe(`[${backend}] #6517 managed sync
beforeAll(async () => {
if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }
+ await dropOriginIndex(engine);
}, 120_000);
afterAll(async () => {
installFaultHook(undefined);
@@ -81,13 +85,14 @@ for (const backend of testBackends()) describe(`[${backend}] #6517 managed sync
rmSync(home, { recursive: true, force: true });
}, 60_000);
- test('two live claimants refuse the run and name the exit; after the loser is soft-deleted the file imports, edits and deletes through both guards; a single tombstone resurrects', async () => {
+ test('two live claimants hold their file (the rest syncs); after the loser is soft-deleted the file imports, edits and deletes through both guards; a single tombstone resurrects', async () => {
const f = await twins();
writeFileSync(f.file, note('Alpha, version two.')); commit(f.root, 'version two');
- const refused = await sync(f.opts).then(() => null, error => error as Error & { code?: string; suggestion?: string });
- expect(refused?.code).toBe('page_identity_changed');
- expect(refused?.message).toContain('Several pages claim the same imported origin');
- expect(refused?.suggestion).toContain('Soft-delete the page that should not own the file');
+ // #6948: the twin no longer refuses the source; only its file is held origin_conflict (the bodies differ: a person decides).
+ const held = await sync(f.opts);
+ expect(held.status).toBe('synced');
+ const [hold] = (await readGitSourceHolds(engine, { sourceIds: [f.id] }))[0]?.holds ?? [];
+ expect(hold).toMatchObject({ path: 'alpha.md', code: 'origin_conflict', meta: { reason: 'content_differs', canonical_slug: 'alpha' } });
expect((await page(f.id, 'alpha'))!.compiled_truth).toContain('version one');
// The exit: the twin is hidden, the file stays.
expect(await softDelete(f.id, 'alpha-twin')).toMatchObject({ state: 'committed', write_through: { skipped: 'shared_origin' } });
diff --git a/test/e2e/origin-twins-6948.test.ts b/test/e2e/origin-twins-6948.test.ts
index cbfd29d9d4..c85e49d278 100644
--- a/test/e2e/origin-twins-6948.test.ts
+++ b/test/e2e/origin-twins-6948.test.ts
@@ -33,6 +33,7 @@ import { _resetCliExitVerdictForTests } from '../../src/core/cli-force-exit.ts';
import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { testBackends } from '../helpers/test-backends.ts';
+import { dropOriginIndex } from '../helpers/origin-index.ts';
import { withEnv } from '../helpers/with-env.ts';
const op = (name: string) => operations.find(o => o.name === name)!;
@@ -93,7 +94,7 @@ for (const backend of testBackends()) describe(`[${backend}] #6948 duplicate-ori
if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }
// Twins exist only on brains written before this release, whose index is pending.
- await engine.executeRaw('DROP INDEX IF EXISTS pages_live_origin_key');
+ await dropOriginIndex(engine);
}, 120_000);
afterAll(async () => {
await withEnv(env, async () => { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); });
@@ -240,7 +241,7 @@ for (const backend of testBackends()) describe(`[${backend}] #6948 duplicate-ori
await v257.handler!(engine);
expect(await originIndexState(engine)).toBe('missing');
expect(await pages()).toBe(before);
- const pending = (await originTwinsEntry.run({ engine } as never))[0]!;
+ const pending = ((await originTwinsEntry.run({ engine } as never)) as Array<{ name: string; status: string; message: string }>)[0]!;
expect(pending).toMatchObject({ name: 'origin_twins', status: 'warn' });
expect(pending.message).toContain('Index pending');
expect(pending.message).toContain(`source ${f.id} has 1 file(s) recorded by several live pages`);
@@ -256,7 +257,7 @@ for (const backend of testBackends()) describe(`[${backend}] #6948 duplicate-ori
}
}
expect(await originIndexState(engine)).toBe('present');
- expect((await originTwinsEntry.run({ engine } as never))[0]).toMatchObject({ status: 'ok' });
+ expect(((await originTwinsEntry.run({ engine } as never)) as Array<{ status: string }>)[0]).toMatchObject({ status: 'ok' });
// With the index present, a second live claim on an origin is refused by the database.
const refused = await write(f.id, tx => tx.putPage('alpha-third', { type: 'note', title: 'x', compiled_truth: 'x', timeline: '', frontmatter: {}, content_hash: 'x', source_path: 'alpha.md' }, { sourceId: f.id }))
.then(() => 'written', () => 'refused');
diff --git a/test/e2e/sync-reconcile-postgres.test.ts b/test/e2e/sync-reconcile-postgres.test.ts
index 45df5381a4..d35ffb238b 100644
--- a/test/e2e/sync-reconcile-postgres.test.ts
+++ b/test/e2e/sync-reconcile-postgres.test.ts
@@ -15,6 +15,7 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { setupDB, teardownDB, hasDatabase } from './helpers.ts';
+import { dropOriginIndex } from '../helpers/origin-index.ts';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { execSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
@@ -99,6 +100,13 @@ describeIfDB('#3583: rename reconcile on PostgreSQL', () => {
await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
expect(await engine.getPage('people/beta')).not.toBeNull();
+ // A NEW unrelated file at the old path. It imports before the legacy
+ // bookkeeping below names that path again: no writer records a held
+ // origin on a second page any more (#6948).
+ writeFileSync(join(repo, 'people/alpha.md'), personMd('Alpha Two', 'A different Alpha.'));
+ execSync('git add -A && git commit -m "new alpha"', { cwd: repo, stdio: 'pipe' });
+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
+
// Put the row into the stale-bookkeeping state deliberately. The cheap
// rename above repairs source_path, so this shape is not what a rename
// leaves behind TODAY — it is what a row renamed before that repair
@@ -107,6 +115,8 @@ describeIfDB('#3583: rename reconcile on PostgreSQL', () => {
// produce it: without this the row is not even a candidate, and the
// live-row assertion below passes with liveness protection disabled
// (adversarial review).
+ // Only a brain whose pages_live_origin_key index is pending can hold this shape (#6948).
+ await dropOriginIndex(engine);
await engine.executeRaw(
`UPDATE pages SET source_path = 'people/alpha.md'
WHERE source_id = 'default' AND slug = 'people/beta'`,
@@ -117,11 +127,6 @@ describeIfDB('#3583: rename reconcile on PostgreSQL', () => {
expect(betaRows).toHaveLength(1);
expect(betaRows[0].source_path).toBe('people/alpha.md');
- // A NEW unrelated file at the old path…
- writeFileSync(join(repo, 'people/alpha.md'), personMd('Alpha Two', 'A different Alpha.'));
- execSync('git add -A && git commit -m "new alpha"', { cwd: repo, stdio: 'pipe' });
- await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
-
// …renamed into an OCCUPIED destination (gamma pre-exists), forcing the
// fallback-to-add + reconcile path.
await engine.putPage('people/gamma', {
diff --git a/test/file-claims-win32-6659.serial.test.ts b/test/file-claims-win32-6659.serial.test.ts
index b59d2381de..b339e53830 100644
--- a/test/file-claims-win32-6659.serial.test.ts
+++ b/test/file-claims-win32-6659.serial.test.ts
@@ -13,6 +13,7 @@ import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { importFromContent } from '../src/core/import-file.ts';
import { findLiveFileClaimants } from '../src/core/persistence/file-claims.ts';
+import { dropOriginIndex } from './helpers/origin-index.ts';
let engine: PGLiteEngine;
let root: string;
@@ -27,8 +28,12 @@ beforeAll(async () => {
await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('win-6659','win-6659',$1,'{}')", [root]);
for (const slug of ['notes/shared', 'notes/shared-twin']) {
await importFromContent(engine, slug, '---\ntype: note\ntitle: Shared\n---\nShared body.\n',
- { sourceId: 'win-6659', sourcePath: 'notes/shared.md', noEmbed: true });
+ { sourceId: 'win-6659', sourcePath: slug === 'notes/shared' ? 'notes/shared.md' : undefined, noEmbed: true });
}
+ // No writer records a held origin on a second page any more (#6948): the twin's origin is set as a brain written
+ // before that guard, whose pages_live_origin_key index is pending, holds it.
+ await dropOriginIndex(engine);
+ await engine.executeRaw("UPDATE pages SET source_path='notes/shared.md' WHERE source_id='win-6659' AND slug='notes/shared-twin'");
}, 120_000);
afterAll(async () => {
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index cdf6030c35..271531e763 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -196,7 +196,7 @@ for (const backend of testBackends()) {
const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts',
'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',
frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',
- 'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',
+ 'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'origin-twins': 'gbrain repair origin-twins', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',
'overwritten-edits': 'gbrain repair overwritten-edits', 'missing-tables': 'gbrain repair missing-tables' };
// The post-upgrade banner names both findings with the kind's read-only preview.
diff --git a/test/helpers/origin-index.ts b/test/helpers/origin-index.ts
new file mode 100644
index 0000000000..d1ee3f16ca
--- /dev/null
+++ b/test/helpers/origin-index.ts
@@ -0,0 +1,9 @@
+import type { BrainEngine } from '../../src/core/engine.ts';
+
+/**
+ * #6948: duplicate-origin twins exist only on brains written before `pages_live_origin_key` (the index stays pending
+ * while they do), so a fixture that seeds twins drops it first, as such a brain is.
+ */
+export async function dropOriginIndex(engine: Pick<BrainEngine, 'executeRaw'>): Promise<void> {
+ await engine.executeRaw('DROP INDEX IF EXISTS pages_live_origin_key');
+}
diff --git a/test/import-publication-guards.test.ts b/test/import-publication-guards.test.ts
index 9aad9e09a5..8c66b11281 100644
--- a/test/import-publication-guards.test.ts
+++ b/test/import-publication-guards.test.ts
@@ -66,23 +66,23 @@ for (const legacy of [false, true]) {
for (const engine of engines) {
const slug = `merge-import/path-${legacy}`;
const body = content('Unchanged content.');
- await importFromContent(engine, slug, body, { noEmbed: true, sourceId, sourcePath: 'old.md' });
+ await importFromContent(engine, slug, body, { noEmbed: true, sourceId, sourcePath: `old-${legacy}.md` });
if (legacy) {
const page = (await engine.getPage(slug, { sourceId }))!;
await engine.executeRaw('UPDATE pages SET content_hash=$1 WHERE id=$2', [contentHashLegacy(page), page.id]);
}
const before = await state(engine, slug);
await expect(importFromContent(engine, slug, body, {
- noEmbed: true, sourceId, sourcePath: 'current.md',
+ noEmbed: true, sourceId, sourcePath: `current-${legacy}.md`,
beforeCommit: async tx => {
- expect((await tx.getPage(slug, { sourceId }))!.source_path).toBe('current.md');
+ expect((await tx.getPage(slug, { sourceId }))!.source_path).toBe(`current-${legacy}.md`);
throw new Error('fixture path publication rejected');
},
})).rejects.toThrow('fixture path publication rejected');
expect(await state(engine, slug)).toEqual(before);
- expect((await importFromContent(engine, slug, body, { noEmbed: true, sourceId, sourcePath: 'current.md' })).status).toBe('skipped');
+ expect((await importFromContent(engine, slug, body, { noEmbed: true, sourceId, sourcePath: `current-${legacy}.md` })).status).toBe('skipped');
const after = await state(engine, slug);
- expect(after.snapshot!.page.source_path).toBe('current.md');
+ expect(after.snapshot!.page.source_path).toBe(`current-${legacy}.md`);
expect(after.snapshot!.revision).toBe(before.snapshot!.revision);
expect(after.chunks).toEqual(before.chunks);
expect(after.versions).toEqual(before.versions);
diff --git a/test/origin-twins-6948.test.ts b/test/origin-twins-6948.test.ts
index 1cee4d4d59..b3717da629 100644
--- a/test/origin-twins-6948.test.ts
+++ b/test/origin-twins-6948.test.ts
@@ -17,6 +17,7 @@ import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
+import { dropOriginIndex } from './helpers/origin-index.ts';
const page = (id: number, slug: string, over: Partial<OriginClaimant> = {}): OriginClaimant =>
({ id, slug, revision: '1', body_hash: 'same', fm_id: null, private: false, restricted: false, trust_tier: 'owner', ...over });
@@ -105,7 +106,7 @@ for (const backend of testBackends()) describe(`[${backend}] #6948 mergeTwinInto
if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }
// A brain that already holds twins (written before this release): the index is pending, so twins can be seeded.
- await engine.executeRaw('DROP INDEX IF EXISTS pages_live_origin_key');
+ await dropOriginIndex(engine);
}, 120_000);
afterAll(async () => { await engine.disconnect(); await closePostgres?.(); }, 60_000);
diff --git a/test/persistence-git-subdir-origin.test.ts b/test/persistence-git-subdir-origin.test.ts
index b4afe1b73c..4983ff6016 100644
--- a/test/persistence-git-subdir-origin.test.ts
+++ b/test/persistence-git-subdir-origin.test.ts
@@ -105,8 +105,8 @@ test('legacy git-root origins sync, are repaired in place on import, survive ful
test('a legacy origin that could name two files refuses with a reason id instead of guessing', async () => isolated(async engine => {
const f = await fixture(engine, { 'a.md': '---\ntitle: A\n---\nRoot body.\n', 'sub/a.md': '---\ntitle: Nested\n---\nNested body.\n' }, { scope: 'sub' });
expect((await sync(engine, f)).status).toBe('first_sync');
- await engine.executeRaw("UPDATE pages SET source_path='sub/a.md' WHERE source_id=$1 AND slug='a'", [f.id]);
await engine.executeRaw("UPDATE pages SET source_path=NULL WHERE source_id=$1 AND slug='sub/a'", [f.id]);
+ await engine.executeRaw("UPDATE pages SET source_path='sub/a.md' WHERE source_id=$1 AND slug='a'", [f.id]);
writeFileSync(join(f.root, 'a.md'), '---\ntitle: A\n---\nChanged root body.\n');
commit(f.repo, 'change root file');
const refused = await sync(engine, f).then(() => null, (error: unknown) => error as { code?: string; detail?: string });
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 12e8291655..48b964e4e7 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -208,6 +208,7 @@ test/managed-sync-stale-group-head.test.ts
test/migration-persistence-request-id-index.test.ts
test/migration-persistence-request-slug-index.test.ts
test/on-commit-embedding.serial.test.ts
+test/origin-twins-6948.test.ts
test/overwritten-edits-6712.test.ts
test/owner-refusal.test.ts
test/pack-relation-direction-engine.test.ts
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 9e94276321..670bb8a620 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'];
+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));
diff --git a/test/sync-origin-live-wins-6517.test.ts b/test/sync-origin-live-wins-6517.test.ts
index a6f620992e..6efba5d15a 100644
--- a/test/sync-origin-live-wins-6517.test.ts
+++ b/test/sync-origin-live-wins-6517.test.ts
@@ -20,6 +20,7 @@ import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
+import { dropOriginIndex } from './helpers/origin-index.ts';
describe('#6517 selectOriginClaimant, the one origin rule', () => {
const live = (id: number) => ({ id, deleted_at: null });
@@ -67,6 +68,7 @@ for (const backend of testBackends()) describe(`[${backend}] #6517 assertSyncPag
beforeAll(async () => {
if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }
+ await dropOriginIndex(engine);
}, 120_000);
afterAll(async () => { await engine.disconnect(); await closePostgres?.(); }, 60_000);
diff --git a/test/sync-rename-reconcile.serial.test.ts b/test/sync-rename-reconcile.serial.test.ts
index f72c48001a..3b90bc2405 100644
--- a/test/sync-rename-reconcile.serial.test.ts
+++ b/test/sync-rename-reconcile.serial.test.ts
@@ -30,6 +30,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { dropOriginIndex } from './helpers/origin-index.ts';
import { PAGE_MAX_BYTES } from '../src/core/page-size-policy.ts';
let engine: PGLiteEngine;
@@ -45,6 +46,9 @@ beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
+ // These tests recreate legacy bookkeeping (several live rows naming one source_path), which only a brain whose
+ // pages_live_origin_key index is pending can hold (#6948).
+ await dropOriginIndex(engine);
});
afterAll(async () => {
@@ -605,6 +609,15 @@ describe('#3583 review: a live page sharing the stale source_path survives the r
execSync('git mv people/alpha.md people/beta.md', { cwd: repo, stdio: 'pipe' });
execSync('git commit -m "cheap rename alpha to beta"', { cwd: repo, stdio: 'pipe' });
await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
+
+ // An unrelated NEW file appears at the old path, and the live beta row
+ // names that path again (the legacy bookkeeping): two active rows now
+ // share source_path=people/alpha.md. No writer records a held origin on
+ // a second page any more (#6948), so the legacy row is set last, as a
+ // brain written before that guard holds it.
+ writeFileSync(join(repo, 'people/alpha.md'), personMd('Alpha II', 'A fresh, unrelated alpha.'));
+ execSync('git add -A && git commit -m "new unrelated alpha"', { cwd: repo, stdio: 'pipe' });
+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
await engine.executeRaw(
`UPDATE pages SET source_path = 'people/alpha.md'
WHERE source_id = 'default' AND slug = 'people/beta'`,
@@ -615,12 +628,6 @@ describe('#3583 review: a live page sharing the stale source_path survives the r
);
expect(betaRows).toHaveLength(1);
expect(betaRows[0].source_path).toBe('people/alpha.md');
-
- // An unrelated NEW file appears at the old path — two active rows now
- // share source_path=people/alpha.md.
- writeFileSync(join(repo, 'people/alpha.md'), personMd('Alpha II', 'A fresh, unrelated alpha.'));
- execSync('git add -A && git commit -m "new unrelated alpha"', { cwd: repo, stdio: 'pipe' });
- await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
expect(await engine.getPage('people/alpha')).not.toBeNull();
expect(await engine.getPage('people/beta')).not.toBeNull();
diff --git a/test/unbound-source-6536.test.ts b/test/unbound-source-6536.test.ts
index b9804db788..4cfc7c242c 100644
--- a/test/unbound-source-6536.test.ts
+++ b/test/unbound-source-6536.test.ts
@@ -21,6 +21,7 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
+import { dropOriginIndex } from './helpers/origin-index.ts';
const backends = testBackends();
const engines: BrainEngine[] = [];
@@ -29,6 +30,8 @@ const dirs: string[] = [];
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; }
+ // The parity fixture gives two live pages one origin, which only a brain whose pages_live_origin_key is pending holds (#6948).
+ for (const engine of engines) await dropOriginIndex(engine);
}, 120_000);
afterAll(async () => {
for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }