Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts, persistence): keep timeline facts fences in place and replay remembers refused while their file awaits import (#6686, #6693)
time-attack72c261649d24
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 477ccaf0e6..0bcf4d7097 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3016,7 +3016,7 @@ More: [docs/guides/write-refusals.md#slug_page_mismatch](../../docs/guides/write| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| The source changed during the operation; nothing was committed. | Covers a replaced, archived or re-bound source and a canonical file that differs from the page's database copy (detail file_database_drift). A page that records no file of its own reconciles against the file at its slug path only with gbrain sources reconcile <source> <slug> --preview --adopt-slug-path. A canonical file that is gone while its page is live (reason canonical_file_missing, a ghost page) never clears by retrying or syncing: a person restores the file and syncs, or removes the page (docs/guides/write-refusals.md#canonical_file_missing). | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+| The source changed during the operation; nothing was committed. | Covers a replaced, archived or re-bound source and a canonical file that differs from the page's database copy (detail file_database_drift). When that file is a committed Git change sync has not imported yet, the reason is pending_import: a refused remember is replayed once by the sync that imports it, any other write is resubmitted after that sync (docs/guides/write-refusals.md#pending_import). A page that records no file of its own reconciles against the file at its slug path only with gbrain sources reconcile <source> <slug> --preview --adopt-slug-path. A canonical file that is gone while its page is live (reason canonical_file_missing, a ghost page) never clears by retrying or syncing: a person restores the file and syncs, or removes the page (docs/guides/write-refusals.md#canonical_file_missing). | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |### source_id_takendiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 679655b5ad..7c5cb308c0 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1039,6 +1039,47 @@ request). Attribution names the original writer. A replay thebrain refuses reports `refused` with the code. The failed receipts stay ashistory.+Since #6693 a `remember` refused because its page's file held a committed Git+change sync had not imported (`pending_import`) or was held by sync+(`sync_held`) is not left for this preview alone: after every managed sync the+same replay runs by itself for those remembers whose page now matches its file+(at most 50 per sync and 30 s; the sync result's `replayedRemembers` and one+stderr line count them). A replay keeps the fact's original `valid_from` and+expiry. `put_page` and `add_timeline_entry` refusals are only replayed here,+after you preview them. Receipts refused before this release are not replayed+automatically; this preview lists them.++<a id="split-facts"></a>+### Split facts++A page whose `## Facts` fence lived below the timeline sentinel got a second+fence above the sentinel from managed `remember` and `extract_facts` writes+before this release (#6686). Writers now edit a lone timeline fence where it+is, and `extract_facts` reconciles it there, but a page that is already split+keeps two fences: `extract_facts` leaves its index as it is and warns+`FACTS_FENCE_BELOW_SENTINEL` naming this repair. `gbrain repair split-facts`+merges them. It is explicit-only and preview-bound and never runs from+`--all`, doctor's remediation plan, the maintenance cycle or an upgrade.++**Say to your agent:** *"Preview which pages have split facts fences, show me+the list, then merge them after I agree."*++```bash+gbrain repair split-facts --source <id> # preview: merge / row_collision / unparsed / not_conserved+gbrain repair split-facts --source <id> --apply --expect <hash> # merges exactly the previewed pages+```++The merged fence stays below the sentinel and holds every row of both fences+under its own row number, so each fact keeps its id; the body fence goes, with+the `## Facts` heading above it when that heading holds nothing else. A page is+kept and listed when a fence does not parse cleanly (`unparsed`: preview+`gbrain repair fences`), when a row number appears in both fences+(`row_collision`: edit the page so each number appears once, then preview+again), or when the merged page would not read back exactly+(`not_conserved`: merge by hand). Each merge is a revision-bound `put_page`;+a page changed since the preview reports `changed_since_preview` and is kept.+Undo a merge on a managed source with `git revert` of its commit.+<a id="file-drift"></a>### File driftdiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 1c2648e82b..81bb3c5ad3 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -54,6 +54,7 @@ of making a duplicate.| <a id="file_database_drift"></a>`file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). Many pages at once: `gbrain sources reconcile <source> --brain host --audit --conflicts` lists them and `gbrain repair file-drift` resolves them, preferring the file or the database copy ([file drift](repair.md#file-drift)). || <a id="canonical_file_missing"></a>`canonical_file_missing` | `source_changed` (a caller write; maintenance refuses before admission) | The page's recorded canonical file is gone while its database page is still live (a ghost page: the file was moved or deleted outside gbrain). A caller write refuses with "The canonical file was removed outside coordinated publication." and nothing is written; retrying it refuses the same way. A maintenance write (fact-fence adoption, enrichment, `dream`) is refused before admission: no request id, no receipt (before #6696 each cycle settled a `conflict` receipt). `gbrain sources writer failures <source>` reports such receipts as category `canonical_file_missing`. Neither copy was changed. | Decide which copy is right. If the file should exist, restore it at its recorded path and preview the page with `gbrain sources reconcile <source> <slug> --brain host --preview`, or sync. If the page should go, preview the ghost-page repair with `gbrain repair ghost-pages --source <source>` (read-only; it prints the apply command with its hash) and apply it with `--apply --expect <hash> --yes` only after the user agrees; a soft-deleted page can be restored with `gbrain restore <slug> --force` until the autopilot purge 72 h later. `gbrain pages ghosts --source <source>` and doctor `ghost_pages` list them, doctor `maintenance_write_drift` lists held-back maintenance writes. See [ghost pages](repair.md#ghost-pages). || <a id="refusal_breaker"></a>`refusal_breaker` | the code of the earlier refusals | The same maintenance write (same source, slug, page revision, planner and intent) was refused `persistence.maintenance.refusal_breaker_threshold` times (default 3; `0` turns it off) in the last 24 hours, so maintenance submits nothing for it instead of adding another receipt (#6696). It is tried again once the page, the planner or the write changes, or when the oldest refusal is 24 hours old. | Read the last refusal with `gbrain write-request -- <request_id>` (named in the message) and fix what it names. Doctor `maintenance_write_drift` lists every held-back write with its exit. |+| <a id="pending_import"></a>`pending_import` | `source_changed` (detail `file_database_drift`, reason `pending_import`) | The page's canonical file holds a change committed through Git (another agent's commit, a pull) that managed sync has not imported yet: the file on disk is exactly the blob `HEAD` holds for its path and not the one the source's last imported commit holds. The message is "The canonical file holds a committed Git change that sync has not imported yet." Nothing was overwritten. Since #6693 the receipt records origin `pending_import`; a write refused because sync holds the file records origin `sync_held` (see [held files](#held-files-and-content-refusals)). | A `remember` needs nothing from the caller: its `fix.next` is `wait`, the fact is kept in the receipt, and the first managed sync that imports the file (any outcome, a partial run included) makes one replay attempt on the original caller's lane with the fact's original `valid_from` and expiry (the sync result's `replayedRemembers` counts examined, replayed, waiting, skipped, remaining; at most 50 per run and 30 s). Do not save the fact again. A remember refused while sync held its file is replayed the same way once the repaired file is imported. A replay that is refused (authority revoked, page rewritten) stays listed by `gbrain repair failed-writes --source <source>` for a person. Any other write (`put_page`, `add_timeline_entry`) is never replayed automatically, because its body would replace the imported change: run `gbrain sync --source <source> --no-pull` on the brain host (the refusal's fix), read the page again and resubmit with a new request ID. An uncommitted hand edit still refuses `file_database_drift` and needs reconcile. || <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. A purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then `gbrain sync --source <id> --no-pull --full` (or the next sync that imports the file) imports its current content into the surviving page. For a purge, soft-delete instead. After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. || <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. Never force-write, edit SQL or disable the guard. || `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull --retry-failed`. |diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 3b9a844083..71ad0e194b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -12,7 +12,7 @@ src/commands/extract.ts 2637 ratchet grown v0.46.26.0 megawave: FS-walk stamp snsrc/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 codessrc/commands/serve-http.ts 931 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)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 527 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+src/commands/sync.ts 529 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)src/core/cycle.ts 3314 ratchet +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 fieldsrc/core/cycle/synthesize.ts 3228 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)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 countdiff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex b62bee1d4d..b867e08d50 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -248,6 +248,7 @@ test/loops-close-fact.serial.test.ts global-state global-state: process-wide testest/loops-extract-run.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the processtest/managed-connector-routing.serial.test.ts global-state global-state: spyOn globalThis.fetchtest/managed-push-remedy.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)+test/managed-timeline-facts.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway; persistence consumer registrytest/managed-unsupported-preflight.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the processtest/mcp-admin-cli.serial.test.ts global-state global-state: spyOn console.log, globalThis.fetchtest/mcp-backup-nag.serial.test.ts R2 R2: mock.module(../src/core/search/hybrid.ts, ../src/core/search/projection-readiness.ts) replaces modules for every file in the processdiff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 5ed2c7030f..a33e82590d 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -22,6 +22,8 @@ export interface SyncResult {/** #6643: the request a `--retry-failed` rediscovery waits for (its producer and slug), instead of a silent no-op. */retryWait?: import('../core/persistence/sync-run.ts').RetryWait;/** #6643: knock-on pages this run re-froze automatically, and the limits that bound it. */+ /** #6693: caller remembers refused while their page's file awaited import (or was held), replayed after this sync imported it. */+ replayedRemembers?: import('../core/repair/failed-writes.ts').ImportReplayReport;knockOns?: { refrozen: number }; /** #6722: pages this run left large or embed_skip (chunked, keyword-searchable) and their embedding state. */ size_states?: import('../core/page-embedding-budget.ts').SyncSizeStates;status: 'up_to_date' | 'synced' | 'first_sync' | 'dry_run' | 'blocked_by_failures' | 'partial';fromCommit: string | null;diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex d373df18ff..8409ef63e0 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -13,6 +13,7 @@ import {import { currentJobSignal } from '../../core/minions/submission-authority.ts';import { currentCompanyBrainSync, getCompanyBrainProfile } from '../../core/company-brain/profile.ts';import type { BrainEngine } from '../../core/engine.ts';+import type { OperationContext } from '../../core/ops/contract.ts';import { refreshProjectionStatistics } from '../../core/search/projection-statistics.ts';import { withRefreshingLock, LockUnavailableError, LockStolenError, syncLockId } from '../../core/db-lock.ts';import { readSyncAnchor } from '../../core/sync-anchor.ts';@@ -80,6 +81,10 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<}if (!opts.dryRun) await recordUpstreamObservation(engine, opts.sourceId ?? 'default', opts.repoPath);if (!opts.dryRun && ['synced', 'first_sync', 'up_to_date'].includes(result.status)) await clearSettledFailures(engine, opts.sourceId ?? 'default');+ if (!opts.dryRun) {+ const replayed = await replayImportedRemembers(engine, opts.sourceId ?? 'default');+ if (replayed) result = { ...result, replayedRemembers: replayed };+ }return result;}const filesystemRoot = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');@@ -124,6 +129,28 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<}}+/**+ * #6693: after a managed sync (any outcome: a partial run can still import the file), replay the caller remembers refused while+ * their page's file awaited import or was held, whose page this run brought back in line with its file. Best effort: a failure+ * is one stderr line and never fails the sync. Returns null when nothing was examined.+ */+async function replayImportedRemembers(engine: BrainEngine, sourceId: string): Promise<SyncResult['replayedRemembers'] | null> {+ try {+ const { loadConfig } = await import('../../core/config.ts');+ const { replayImportedRemembers: replay } = await import('../../core/repair/failed-writes.ts');+ const logger = { info: () => {}, warn: (m: string) => serr(m), error: (m: string) => serr(m) };+ const report = await replay({ engine, config: loadConfig() ?? { engine: engine.kind }, logger, remote: false, dryRun: false, sourceId } as OperationContext, sourceId);+ if (!report.examined) return null;+ serr(`[sync] replayed ${report.replayed} of ${report.examined} remember(s) refused while their page's file awaited import`+ + `${report.waiting ? `; ${report.waiting} still waiting` : ''}${report.skipped ? `; ${report.skipped} not replayable (gbrain repair failed-writes --source ${sourceId} lists them)` : ''}`+ + `${report.remaining ? `; ${report.remaining} left for the next sync` : ''}.`);+ return report;+ } catch (error) {+ serr(`[sync] could not replay remembers refused while their page's file awaited import: ${error instanceof Error ? error.message : String(error)} (gbrain repair failed-writes --source ${sourceId} replays them).`);+ return null;+ }+}+/** #6288: a successful managed sync clears this source's recorded failures its imported commit already settles (#6543 D5: legacy ledger rows too); best effort. */async function clearSettledFailures(engine: BrainEngine, sourceId: string): Promise<void> {try {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 5b52a20d76..ce3b34c701 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -627,6 +627,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Large pages A3/T44, A4/T32 (Lane 3a).{ since: '0.60.242.0', text: 'Replacing a page\'s chunks now writes them in bounded batches (at most 500 rows and 16 MiB of encoded rows per statement) after one prune, all in the same transaction, instead of one statement carrying every chunk. A page with thousands of chunks no longer builds one giant statement, and a failure in any batch still rolls the whole replacement back.' },{ since: '0.60.242.0', text: 'A chunk vector is now tied to the chunk\'s text and its full embedding input rather than its position. When an edit inserts or removes chunks above it, a projection rebuild moves the unchanged chunk to its new index with its vector instead of dropping it, so only new or changed chunks wait for embedding. An embed that finishes after the page changed now commits the vectors of the chunks that are still the same (same text, source and embedding input) and leaves the rest for the next run, instead of discarding the whole run; the page\'s embedding signature is stamped only when every chunk got its vector. A vector built under an old title or synopsis is still dropped.' },+ // #6693 (D7): writes refused while their page's file awaits import.+ { since: '0.60.243.0', text: 'A write refused because its page\'s canonical file holds a committed Git change that managed sync has not imported yet now says so (`source_changed`, reason `pending_import`, "The canonical file holds a committed Git change that sync has not imported yet.") instead of "an uncoordinated local edit". A `remember` refused that way, or refused because sync held the file, is kept: after each managed sync, gbrain replays those remembers whose page now matches its file, once, with the fact\'s original date and the caller\'s original authority (at most 50 per sync; the sync result\'s `replayedRemembers` counts them), so the agent should not save the fact again. `put_page` and other writes are not replayed: resubmit after the next sync. Remembers refused before this release are listed by `gbrain repair failed-writes --source <id>`.' },+ // #6686 (D8): a facts fence below the timeline sentinel.+ { since: '0.60.243.0', text: 'A page whose only `## Facts` fence sits below the timeline sentinel keeps it there: `remember` and `extract_facts` now add their rows to that fence (and strike a replaced row where it lives) instead of adding a second fence above the sentinel, and `extract_facts` reconciles such a fence instead of warning `FACTS_FENCE_BELOW_SENTINEL` and freezing its facts. A page that already has a fence on each side of the sentinel still warns, now naming `gbrain repair split-facts --source <id>`, an explicit preview-then-apply repair that merges the two fences under their own row numbers and refuses a page whose fences share a row number.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex e32e7532be..306637d3bf 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -76,7 +76,7 @@ import {import { writeReceipt } from '../extract/receipt-writer.ts';import { fenceUnfencedFacts, planUnfencedFacts } from '../facts/unfenced-facts.ts';import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';-import { parseFactsFence, FACTS_FENCE_BEGIN } from '../facts-fence.ts';+import { factsFenceSection, factsFenceSections, parseFactsFence, FACTS_FENCE_BEGIN } from '../facts-fence.ts';import {duplicateActiveFenceRows,extractFactsFromFenceText,@@ -371,11 +371,15 @@ interface FenceReconcilePlan {/*** One page's reconcile plan against its stored rows. Null when the fence is* not authoritative (warnings are appended): a warning-bearing parse or a- * fence below the timeline sentinel preserves the page's existing index.+ * fence in each section of the page (#6686: a split fence) preserves the page's existing index.*/async function planFenceReconcile(db: BrainEngine, page: { compiled_truth: string | null; timeline: string | null; effective_date?: Date | string | null },slug: string, sourceId: string, warnings: string[]): Promise<FenceReconcilePlan | null> {- const parsed = parseFactsFence(page.compiled_truth ?? '');+ // #6686: a lone fence below the timeline sentinel that parses cleanly is the page's fence, read where the writers+ // edit it; one that does not parse keeps the #3625 guard below.+ const below = factsFenceSection(page) === 'timeline' ? parseFactsFence(page.timeline ?? '') : null;+ const lone = below !== null && below.warnings.length === 0;+ const parsed = lone ? below : parseFactsFence(page.compiled_truth ?? '');if (parsed.warnings.length > 0) {// The parser deliberately skips malformed rows and returns any rows it// could still recover. That partial result is not authoritative: using@@ -386,7 +390,14 @@ async function planFenceReconcile(db: BrainEngine, page: { compiled_truth: strin// #3625: a fence below the timeline sentinel lands in page.timeline, where// parseFactsFence cannot see it; reading compiled_truth alone would treat// its rows as deleted. timelineHasGenuineFactsFenceMarker explains the scan.- if (timelineHasGenuineFactsFenceMarker(page.timeline ?? '')) {+ if (!lone && timelineHasGenuineFactsFenceMarker(page.timeline ?? '')) {+ // #6686: a fence in each section (a writer added one above the sentinel) is merged by an explicit repair.+ if (factsFenceSections(page).body) {+ warnings.push(`${slug}: FACTS_FENCE_BELOW_SENTINEL: the page holds a ## Facts fence above the <!-- timeline --> sentinel and another below it `+ + `(a split fence), so extract_facts leaves its indexed facts as they are. Preview merging them into one with gbrain repair split-facts --source ${sourceId}, `+ + 'then apply the hash it prints.');+ return null;+ }warnings.push(`${slug}: FACTS_FENCE_BELOW_SENTINEL: a ## Facts fence was found below ` +`the <!-- timeline --> sentinel, where extract_facts cannot see it. ` +diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 0a1b4b4541..b888ad8ba6 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -461,7 +461,7 @@ export const CODES = {why: 'Read-only: lists the held file with the slug sync files it as and its fix, which names the exact edit and the content-repair preview; nothing is written.',verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },source_binding_required: { class: 'caller', summary: "A write needs an explicit source binding on this MCP server (--source-guard)." },- source_changed: { class: 'caller', summary: "The source changed during the operation; nothing was committed.", why: "Covers a replaced, archived or re-bound source and a canonical file that differs from the page's database copy (detail file_database_drift). A page that records no file of its own reconciles against the file at its slug path only with gbrain sources reconcile <source> <slug> --preview --adopt-slug-path. A canonical file that is gone while its page is live (reason canonical_file_missing, a ghost page) never clears by retrying or syncing: a person restores the file and syncs, or removes the page (docs/guides/write-refusals.md#canonical_file_missing)." },+ source_changed: { class: 'caller', summary: "The source changed during the operation; nothing was committed.", why: "Covers a replaced, archived or re-bound source and a canonical file that differs from the page's database copy (detail file_database_drift). When that file is a committed Git change sync has not imported yet, the reason is pending_import: a refused remember is replayed once by the sync that imports it, any other write is resubmitted after that sync (docs/guides/write-refusals.md#pending_import). A page that records no file of its own reconciles against the file at its slug path only with gbrain sources reconcile <source> <slug> --preview --adopt-slug-path. A canonical file that is gone while its page is live (reason canonical_file_missing, a ghost page) never clears by retrying or syncing: a person restores the file and syncs, or removes the page (docs/guides/write-refusals.md#canonical_file_missing)." },source_id_taken: { class: 'caller', summary: "This source already exists and does not match this exact admitted request." },source_mismatch: { class: 'caller', summary: "The request names a different source than the one this serve is bound to; it is refused, never rerouted." },source_not_ready: { class: 'caller', summary: "A committed source and approved schema are required." },diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.tsindex aa2f6a7998..8466d9de75 100644--- a/src/core/facts-fence.ts+++ b/src/core/facts-fence.ts@@ -659,6 +659,38 @@ export function upsertFactRow(* An unclosed code block before that point would swallow the fence (it would* render as code), so the fence goes above the block's opener instead.*/+/** #6686: which sections of a page hold a facts fence outside markdown code (the reader `replaceOrInsertFactsFence` uses). */+export function factsFenceSections(page: { compiled_truth: string | null; timeline?: string | null }): { body: boolean; timeline: boolean } {+ const holds = (text: string | null | undefined) => locateOutsideCode(text ?? '', FACTS_FENCE_BEGIN, FACTS_FENCE_END).beginIdx !== -1;+ return { body: holds(page.compiled_truth), timeline: holds(page.timeline) };+}++/**+ * #6686: the section a writer edits a page's facts fence in. A fence that lives+ * below the timeline sentinel (in `timeline`) is edited there when the body has+ * none, so the writer neither adds a second fence above the sentinel nor+ * rewrites the page's layout; every other page (no fence, a body fence, or+ * fences in both sections) is edited in the body, as before.+ */+export function factsFenceSection(page: { compiled_truth: string | null; timeline?: string | null }): 'compiled_truth' | 'timeline' {+ const held = factsFenceSections(page);+ return !held.body && held.timeline ? 'timeline' : 'compiled_truth';+}++/**+ * #6686: strike fence row `rowNum` as superseded by row `by` in whichever section's fence holds it (a split page can+ * hold the old row in the other section than the one the new row went to); a page without the row is returned as is.+ */+export function strikeFactRowInPage<T extends { compiled_truth: string; timeline: string }>(page: T, rowNum: number, by: number): T {+ for (const key of ['compiled_truth', 'timeline'] as const) {+ const rows = parseFactsFence(page[key]).facts;+ if (!rows.some(f => f.rowNum === rowNum)) continue;+ return { ...page, [key]: replaceOrInsertFactsFence(page[key], renderFactsTable(rows.map(f => f.rowNum === rowNum+ ? { ...f, active: false, supersededBy: by, context: `superseded by #${by}` } : f))) };+ }+ return page;+}+export function replaceOrInsertFactsFence(body: string, fenceBlock: string): string {const { beginIdx, endIdx } = locateOutsideCode(body, FACTS_FENCE_BEGIN, FACTS_FENCE_END);if (beginIdx !== -1 && endIdx !== -1) {diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 76389a8806..e4e6e559f4 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -36,6 +36,7 @@ import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePerimport { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';+import { PENDING_IMPORT, SYNC_HELD } from './pending-import.ts';import { CANONICAL_FILE_MISSING, databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';import { SYNC_CURSOR_REPLACED } from './sync-checkpoint-replaced.ts';import { fenceFailureDetail } from '../fence-repair/refusal.ts';@@ -131,7 +132,9 @@ function requestError(error: unknown): PublicationFailure {if (error instanceof OperationError) {// #6188: a typed fence refusal keeps its location in the bounded detail, which outlives receipt compaction.const detail = fenceFailureDetail(error) ?? withdrawalFailureDetail(error) ?? (error.syncRefusal as PublicationFailure['detail'] | undefined)- ?? (error.detail === CANONICAL_FILE_MISSING ? { origin: CANONICAL_FILE_MISSING } : undefined);+ ?? (error.detail === CANONICAL_FILE_MISSING ? { origin: CANONICAL_FILE_MISSING } : undefined)+ // #6693: a refusal on a page whose file awaits import or is held by sync; the replay after import selects on it.+ ?? (error.code === 'source_changed' && (error.reason === PENDING_IMPORT || error.reason === SYNC_HELD) ? { origin: error.reason } : undefined);return { code: error.code, message: error.message, ...(detail ? { detail } : {}) };}const refusal = databaseRefusal(error);diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex 236f743121..4ef8f42dd3 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -5,7 +5,7 @@ import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';import type { RegistryCode } from '../error-registry.ts';-import { parseFactsFence, upsertFactRow, formatFenceDate, renderFactsTable, replaceOrInsertFactsFence } from '../facts-fence.ts';+import { factsFenceSection, parseFactsFence, strikeFactRowInPage, upsertFactRow, formatFenceDate } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';import { assertFactNotWithdrawn, decideSingleFact, factWithdrawnRefusal, type FactCandidate } from '../facts/single-prepare.ts';import { assertFactNotPurged, isFactWithdrawn } from '../facts/withdrawal.ts';@@ -147,10 +147,12 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ}// #6188 (D20): the entity's stored fence is normalized in this same write; a residual refuses typed `target_fence_malformed`.const target = snapshot ? await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: snapshot.page }) : null;- let body = target?.page.compiled_truth ?? '';- const parsed = parseFactsFence(body);+ // #6686: the fence is edited in the section it lives in (a lone timeline fence stays below the sentinel); the other section is kept byte for byte.+ const fenced = { compiled_truth: target?.page.compiled_truth ?? '', timeline: target?.page.timeline ?? '' };+ const section = factsFenceSection(fenced);+ let next = { ...fenced };const [maximum] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);- let nextRow = Math.max(maximum?.n ?? 0, ...parsed.facts.map(fact => fact.rowNum)) + 1;+ let nextRow = Math.max(maximum?.n ?? 0, ...[fenced.compiled_truth, fenced.timeline].flatMap(text => parseFactsFence(text).facts.map(fact => fact.rowNum))) + 1;const entries: Array<{ fact: typeof facts[number]; duplicateId: number | null; rowNum?: number; duplicateOf?: number; supersedes?: FactCandidate; gate?: GatedRowDecision }> = [];const seen = new Map<string, number[]>();// #5575 B3: a new row passes the write gate at the extraction's declared tier (ENG-18) before it reaches the fence;@@ -183,21 +185,20 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writif (gate && gate.action !== 'insert') { blocked.push(gate); continue; }const rowNum = fact.entity_slug !== null && !fallback(fact) ? nextRow++ : undefined;// #6385 R12: an entity fence that does not parse cleanly refuses typed instead of losing the rows it skipped.- if (rowNum !== undefined) body = refuseUnparsedRewrite({ compiled_truth: body, timeline: target!.page.timeline }, row.slug, row.source_id, () => upsertFactRow(body, {+ if (rowNum !== undefined) next = { ...next, [section]: refuseUnparsedRewrite(next, row.slug, row.source_id, () => upsertFactRow(next[section], {rowNum, claim: fact.fact, kind: fact.kind, visibility: fact.visibility,confidence: fact.confidence ?? 1, notability: fact.notability ?? 'medium', source: fact.source, context: fact.context ?? undefined,validFrom: formatFenceDate(fact.valid_from!), validUntil: fact.valid_until ? formatFenceDate(fact.valid_until) : undefined,claimMetric: fact.claim_metric ?? undefined, claimValue: fact.claim_value ?? undefined,claimUnit: fact.claim_unit ?? undefined, claimPeriod: fact.claim_period ?? undefined,- ...(fact.attributed_to ? { attributedTo: fact.attributed_to } : {}) }).body);- // Strike the superseded row in this page's fence, as the remember mutation does.+ ...(fact.attributed_to ? { attributedTo: fact.attributed_to } : {}) }).body) };+ // Strike the superseded row in this page's fence, as the remember mutation does (#6686: in the section that holds it).if (supersedes && rowNum !== undefined && supersedes.source_markdown_slug === row.slug && supersedes.row_num != null) {- body = replaceOrInsertFactsFence(body, renderFactsTable(parseFactsFence(body).facts.map(f => f.rowNum === Number(supersedes.row_num)- ? { ...f, active: false, supersededBy: rowNum, context: `superseded by #${rowNum}` } : f)));+ next = strikeFactRowInPage(next, Number(supersedes.row_num), rowNum);}entries.push({ fact, duplicateId: null, rowNum, supersedes, gate });}- const canonicalFacts = extractFactsFromFenceText(parseFactsFence(body).facts, row.slug, row.source_id);+ const canonicalFacts = extractFactsFromFenceText(parseFactsFence(next[section]).facts, row.slug, row.source_id);for (const entry of entries) {if (entry.rowNum === undefined) continue;const canonical = canonicalFacts.find(fact => fact.row_num === entry.rowNum);@@ -213,7 +214,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writconst rowNums = entries.flatMap(entry => entry.rowNum === undefined ? [] : [entry.rowNum]);page = await withPendingFenceRows({ sourceId: row.source_id, slug: row.slug, rowNums, tier: fenceAppendPendingTier(taint?.trust.tier) },() => preparePageMutation(engine, { ...row, intent: { ...p,- content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body, timeline: target!.page.timeline }, snapshot.tags) } }, config));+ content: serializePageToMarkdown({ ...snapshot.page, ...next }, snapshot.tags) } }, config));if (page.observedRevision !== snapshot.revision) throw factsRefusal('revision_conflict', 'The fact entity changed during preparation.', row,`Entity page ${row.slug} changed while its ## Facts table was being prepared, so none of these facts were published.`);}diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 0609734916..15d0bee640 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -5,7 +5,7 @@ import { opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import { pageIdentityError } from './page-identity.ts';import { assertPageRevision } from '../page-state/types.ts';-import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, upsertFactRow, formatFenceDate } from '../facts-fence.ts';+import { factsFenceSection, parseFactsFence, strikeFactRowInPage, upsertFactRow, formatFenceDate } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';import { assertFactNotWithdrawn, decideReplacement, decideSingleFact, prepareFactEmbedding, type SingleFactIntent } from '../facts/single-prepare.ts';import { factEmbeddingDisabled } from '../embedding-disabled.ts';@@ -150,20 +150,19 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequewriter: row.principal_kind, path: snapshot.page.source_path ?? null, remote: row.authority.remote }) };// #6696 C9: a facts row the fence does not hold (extraction, a hand edit) still owns its row_num, so the new row numbers past both.const [indexed] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);+ // #6686: the fence is edited in the section it lives in (a lone timeline fence stays below the sentinel); the other section is kept byte for byte.+ const section = factsFenceSection(target.page);+ const fenced = { compiled_truth: target.page.compiled_truth, timeline: target.page.timeline ?? '' };// #6385 R12: an entity fence that does not parse cleanly refuses typed instead of losing the rows it skipped.- const appended = refuseUnparsedRewrite(target.page, row.slug, row.source_id, () => upsertFactRow(target.page.compiled_truth, {+ const appended = refuseUnparsedRewrite(target.page, row.slug, row.source_id, () => upsertFactRow(fenced[section], {claim: input.fact, kind: input.kind, visibility: input.visibility, confidence: 1, notability: 'medium', validFrom: formatFenceDate(validFrom),validUntil: validUntil ? formatFenceDate(validUntil) : undefined, source: fact.source, context,- rowNum: Math.max(indexed?.n ?? 0, ...parseFactsFence(target.page.compiled_truth).facts.map(f => f.rowNum)) + 1 }));+ rowNum: Math.max(indexed?.n ?? 0, ...[fenced.compiled_truth, fenced.timeline].flatMap(text => parseFactsFence(text).facts.map(f => f.rowNum))) + 1 }));rowNum = appended.rowNum;- let body = appended.body;+ let next = { ...fenced, [section]: appended.body };const old = decision.candidate;- if (status === 'superseded' && old?.source_markdown_slug === row.slug && old.row_num != null) {- const rows = parseFactsFence(body).facts.map(f => f.rowNum === old.row_num- ? { ...f, active: false, supersededBy: rowNum, context: `superseded by #${rowNum}` } : f);- body = replaceOrInsertFactsFence(body, renderFactsTable(rows));- }- const content = serializePageToMarkdown({ ...snapshot.page, compiled_truth: body, timeline: target.page.timeline }, snapshot.tags);+ if (status === 'superseded' && old?.source_markdown_slug === row.slug && old.row_num != null) next = strikeFactRowInPage(next, Number(old.row_num), rowNum);+ const content = serializePageToMarkdown({ ...snapshot.page, ...next }, snapshot.tags);// Reuse the canonical parser/chunker and durable filesystem publication.// The original caller revision was checked above; this CAS binds this render.// #5575 ENG-1: the new row has no facts row yet; its chunks are cut at the append's tier.diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 717e365be7..f3965af282 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -15,6 +15,7 @@ import { comparableFrontmatter, frontmatterHoldMessageWithoutKeys, parseMarkdownimport { assertLargePageReplacement } from './large-page-guard.ts';import { OperationError, opError } from '../ops/contract.ts';import { CANONICAL_FILE_MISSING } from './publication-failure.ts';+import { committedPendingImport, pendingImportRefusal, SYNC_HELD } from './pending-import.ts';import { readFix } from '../ops/op-fix.ts';import { isOpPageSlug } from '../ops/context.ts';import { shellQuote, type Action } from '../agent-output.ts';@@ -158,7 +159,7 @@ export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, bytparsed.compiled_truth, parsed.timeline ?? '', snapshot.withdrawals, { sourceId: snapshot.page.source_id, marker: snapshot.globalPurges }) }, parsed.tags);return digest(actual) === digest(canonical(snapshot.page, snapshot.tags));}-export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, snapshot: PageSnapshot | null,+export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'> & { operation?: string }, snapshot: PageSnapshot | null,content: string | null, hostId?: string, options: { allowMissing?: boolean; deleting?: boolean; capture?: { path: string; hash: string }; activePack?: ParseOpts['activePack']; remote?: boolean;/** #6368: a tombstone purge whose file matches these sync.exclude globs (relative to the source root) owns no file. */excludeTombstone?: { patterns: string[]; onExcluded: (path: string) => void };@@ -229,6 +230,8 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequif (held) throw held;// #6394: a page that never recorded its file reconciles against the file at its slug path only when adopted explicitly.const adopt = !snapshot.page.source_path && !snapshot.page.source_uri ? ['--adopt-slug-path'] : [];+ // #6693: a committed Git change sync has not imported yet (another agent's commit), on a page that records its file.+ if (!adopt.length && await committedPendingImport(engine, row.source_id, root, path)) throw pendingImportRefusal(row, options.remote === true);throw opError('source_changed', 'The canonical file contains an uncoordinated local edit.',`On the brain host, run gbrain sources reconcile ${row.source_id} ${row.slug} --brain <brain id, host by default> --preview${adopt.length ? ' --adopt-slug-path (the page records no file of its own, so the preview adopts the file at its slug path)' : ''}, review and apply the resolved preview, then retry this write with a new request_id. Neither copy was overwritten.`,{ detail: 'file_database_drift', fix: readFix(`Previews how page ${row.slug}'s canonical file and database copy reconcile; a preview never changes canonical content.`,@@ -260,6 +263,7 @@ async function heldFileRefusal(engine: BrainEngine, row: Pick<WriteRequest, 'sou+ `so ${effect} is read-only for put_page until the brain host operator repairs the file; retrying this write refuses the same way. Relay the fix to the user, then submit the intended write with a new request_id. Neither copy was overwritten.`,{ fix: hostOperatorFix([{ source_id: row.source_id, route: recordRoute(hold) }], `The canonical file of page ${row.slug} is held (${hold.code}): only the brain host operator can inspect and repair it.`) });if (kind === 'drift') error.detail = 'file_database_drift';+ error.reason = SYNC_HELD;return error;}const fix = gitHoldFix(hold);@@ -269,6 +273,7 @@ async function heldFileRefusal(engine: BrainEngine, row: Pick<WriteRequest, 'sou+ `so ${effect} is read-only for put_page until the file is repaired; retrying this write refuses the same way. `+ `Repair the file first (${shellQuote(fix.argv ?? [])}: ${fix.why}), then submit the intended write with a new request_id. Neither copy was overwritten.`, { fix });if (kind === 'drift') error.detail = 'file_database_drift';+ error.reason = SYNC_HELD;return error;}diff --git a/src/core/persistence/pending-import.ts b/src/core/persistence/pending-import.tsnew file mode 100644index 0000000000..debfa6fbaa--- /dev/null+++ b/src/core/persistence/pending-import.ts@@ -0,0 +1,63 @@+/**+ * #6693: a page write refused because its canonical file differs from the+ * database is usually another agent's committed Git change that managed sync+ * has not imported yet, not a hand edit. That case is told apart here, from+ * Git alone and read-only: the file on disk is exactly the blob `HEAD` holds+ * for its path (nothing uncommitted), and that blob is not the one the+ * source's last imported commit (`sources.last_commit`) holds, or no import+ * is recorded yet. Any Git failure (no repository, a commit that no longer+ * exists, a path Git cannot resolve) answers false, so the write keeps the+ * ordinary drift refusal.+ *+ * The refusal stays `source_changed` / `file_database_drift` (every reader of+ * drift keeps working) and carries reason `pending_import`, which the+ * coordinator records as the receipt's `error_detail.origin`. A refused+ * `remember` gets one replay attempt from the first managed sync that+ * imports the file (`replayImportedRemembers`, repair/failed-writes.ts); any other write+ * is resubmitted by its caller after that sync.+ */+import { relative, sep } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import type { Action } from '../agent-output.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { syncGit } from './sync-discovery.ts';+import { PENDING_IMPORT_MESSAGE } from './verb-errors.ts';++export const PENDING_IMPORT = 'pending_import';+/** #6693: the receipt origin of a write refused because sync holds the page's file (heldFileRefusal). */+export const SYNC_HELD = 'sync_held';++/** Whether the file at `path` (inside the source checkout `root`) is a committed change the source has not imported yet. */+export async function committedPendingImport(engine: BrainEngine, sourceId: string, root: string, path: string): Promise<boolean> {+ const [source] = await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]);+ const rel = `./${relative(root, path).split(sep).join('/')}`;+ try {+ const head = syncGit(root, ['rev-parse', '--verify', '--quiet', `HEAD:${rel}`]).trim();+ if (!head || syncGit(root, ['hash-object', '--', rel]).trim() !== head) return false;+ if (!source?.last_commit) return true;+ syncGit(root, ['cat-file', '-e', `${source.last_commit}^{commit}`]);+ let imported = '';+ try { imported = syncGit(root, ['rev-parse', '--verify', '--quiet', `${source.last_commit}:${rel}`]).trim(); } catch { imported = ''; }+ return imported !== head;+ } catch {+ return false;+ }+}++/** The refusal: nothing was overwritten; a remember waits for its replay, any other write is resubmitted after the next sync. */+export function pendingImportRefusal(row: { source_id: string; slug: string; operation?: string }, remote: boolean): OperationError {+ const status = ['gbrain', 'sync', 'status', '--source', row.source_id, '--json'];+ const remember = row.operation === 'remember';+ const fix: Action = remember+ ? { argv: status, consent: [], actor: 'provider', requires_exclusive: false, verify: { argv: status }, docs: 'docs/guides/write-refusals.md#pending_import',+ why: `The fact is kept in this request's receipt and queued for one automatic replay attempt by the first managed sync that imports the file; do not save it again. `+ + `This read-only status shows when the source has synced; until the replay commits, gbrain repair failed-writes --source ${row.source_id} lists the fact (a replay that is refused stays there for a person to replay).` }+ : { argv: ['gbrain', 'sync', '--source', row.source_id, '--no-pull', '--json'], consent: [], actor: remote ? 'host_admin' : 'agent', requires_exclusive: false,+ verify: { argv: status }, docs: 'docs/guides/write-refusals.md#pending_import',+ why: 'Imports the committed change on the brain host; then read the page again and resubmit the intended write with a new request_id.' };+ return opError('source_changed', PENDING_IMPORT_MESSAGE,+ `Nothing was overwritten. The canonical file of ${row.slug} in source ${row.source_id} holds a change committed through Git that managed sync has not imported yet, `+ + (remember ? 'so this remember was refused and kept: the first sync that imports the file makes one replay attempt, with its original date and authority.'+ : 'so this write was refused rather than replacing those bytes: after the next sync imports them, read the page again and resubmit with a new request_id.'),+ { detail: 'file_database_drift', reason: PENDING_IMPORT, fix });+}diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 8365fe5b4a..fbcf07b4fd 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex 8e66cb9286..573dc47e7d 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -50,7 +50,9 @@ export type WithdrawalRefusalDetail = WithdrawalFailureDetail & Pick<Publication/** #6696 (A12): the page's recorded canonical file is gone (`prepareFileTarget`); a producer refuses the same write before admission. */export const CANONICAL_FILE_MISSING = 'canonical_file_missing';export interface CanonicalFileDetail { origin: typeof CANONICAL_FILE_MISSING; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }-export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | WithdrawalRefusalDetail | OwnerExceptionDetail | CanonicalFileDetail }+/** #6693: a page write refused because its file holds a committed change sync has not imported (`pending_import`) or sync holds the file (`sync_held`). */+export interface PendingImportDetail { origin: 'pending_import' | 'sync_held'; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }+export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | WithdrawalRefusalDetail | OwnerExceptionDetail | CanonicalFileDetail | PendingImportDetail }const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 02039ad968..2f4ad55a24 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -1,3 +1,4 @@+import { PENDING_IMPORT, pendingImportRefusal } from './pending-import.ts';import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { OperationError } from '../ops/contract.ts';@@ -335,6 +336,11 @@ export function writeResponse(row: WriteRequest, hints: { retryAfterMs?: number? pendingWriteHint(receipt, row.operation): delivered?.suggestion ?? content?.suggestion ?? held?.suggestion ?? terminalReceiptHint(row, reason), delivered?.docs);if (delivered?.detail ?? held?.reason) error.detail = delivered?.detail ?? held?.reason;+ // #6693: a write refused while its page's file awaited import says so, with the wait (remember) or the sync to run first.+ if (isTerminal(row) && reason === 'source_changed' && (row.error_detail as { origin?: unknown } | null | undefined)?.origin === PENDING_IMPORT) {+ const pending = pendingImportRefusal(row, row.authority?.remote === true);+ Object.assign(error, { suggestion: pending.suggestion, fix: pending.fix, reason: pending.reason, detail: pending.detail, docs: pending.docs ?? error.docs });+ }// #6317 (B1b): a waiter-only process names the owner that publishes for it, so the caller is told who holds the write instead of polling blind.if (!isTerminal(row) && hints.waiterOnlyOwner) {const owner = hints.waiterOnlyOwner;diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex 4a59b857d0..998c80926e 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -16,6 +16,9 @@ export function frontmatterSlugConflictMessage(path: string, found: string, expe/** #5988: the page's canonical file is held by sync; the code says why gbrain cannot import it. Location-free, so receipts may keep it. */const HELD_FILE = /^(?:The canonical file is held by sync|A file held by sync) \(([a-z_]+)\) (and differs from the page|occupies the canonical page path); the page is read-only for put_page until the file is repaired\.$/;+/** #6693: the refusal of a page write whose file holds a committed Git change sync has not imported yet (pending-import.ts). */+export const PENDING_IMPORT_MESSAGE = 'The canonical file holds a committed Git change that sync has not imported yet.';+export function heldFileMessage(kind: 'drift' | 'occupied', code: string): string {return kind === 'drift'? `The canonical file is held by sync (${code}) and differs from the page; the page is read-only for put_page until the file is repaired.`@@ -48,6 +51,10 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {reason: 'file_database_drift', message: 'The canonical file and database disagree. Neither copy was overwritten.',suggestion: 'On the source host, run gbrain sources reconcile <source> <slug> --brain <brain> --preview. Review and apply the resolved preview before retrying the original write with a new request_id. This is data repair, not an ownership or permission change.',};+ if (message === PENDING_IMPORT_MESSAGE) return {+ reason: 'pending_import', message: 'A committed Git change to the page\'s file has not been imported yet; neither copy was overwritten.',+ suggestion: 'A refused remember is replayed once by the first managed sync that imports the file; do not save it again. Any other write: after the next gbrain sync --source <source> --no-pull, read the page again and resubmit with a new request_id.',+ };if (['Newer working-tree bytes and the current page disagree with this pinned Git import.','Newer code file bytes disagree with the pinned import.', 'Canonical sanitization cannot overwrite newer working-tree bytes.'].includes(message ?? '')) return {reason: 'pinned_git_worktree_conflict', message: 'The pinned Git content conflicts with working-tree bytes; sync did not overwrite them.',diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 79403eedf0..7aba41fc72 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -37,7 +37,7 @@ import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsindex 41789d4cc9..4bd44ae600 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -53,6 +53,7 @@ import { initializeLocalPersistence, requestPrincipalForContext, submitPageMutatimport { submitRememberMutation } from '../persistence/memory-mutations.ts';import { getWorktreeBinding } from '../persistence/ownership.ts';import { prepareFileTarget } from '../persistence/page-prepare.ts';+import { PENDING_IMPORT, SYNC_HELD } from '../persistence/pending-import.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import { resolveEntitySlugWithSource } from '../entities/resolve.ts';import { dispositionOf, PAGE_REMOVAL_OPERATIONS, supersessionOrderSql, supersessionSql } from '../persistence/terminal-classify.ts';@@ -70,6 +71,8 @@ const DRIFT_REFUSAL = `(r.state='conflict' AND r.error_code='source_changed')`;interface FailedWrite {id: string; request_id: string; sequence: string; operation: string; source_id: string; slug: string; digest: string; state: string;intent: Record<string, unknown>; authority: WriteAuthority; created_at: string; producer: string | null;+ /** #6693: the refusal's recorded origin (`pending_import`, `sync_held`), when the receipt carries one. */+ origin?: string | null;}type Disposition = 'replay' | 'already_written' | 'duplicate' | 'superseded' | 'unpinned_target' | 'file_database_drift';/** A replay bound to the page revision the preview saw (null: no live page). */@@ -93,7 +96,7 @@ function producerCommand(producer: string, sourceId: string): string {async function failedWrites(engine: BrainEngine, sourceIds: string[], id?: string): Promise<FailedWrite[]> {const rows = await engine.executeRaw<FailedWrite>(`SELECT r.id::text, r.request_id::text, r.sequence::text, r.operation, r.source_id, r.slug, r.digest, r.state, r.intent, r.authority,- to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS created_at,+ to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS created_at, r.error_detail->>'origin' AS origin,CASE WHEN r.operation = ANY($2::text[]) AND NOT (r.operation='put_page' AND r.intent ? 'kind') THEN NULLELSE r.operation || COALESCE(':' || (r.intent->>'kind'), '') END AS producerFROM persistence_requests r@@ -363,6 +366,10 @@ async function replayParams(ctx: OperationContext, write: ApprovedWrite, requestreturn { refused: { applied: false, outcome: 'changed_since_preview', reason: `the fact's subject ${target} no longer resolves to itself` } };}params.entity = target;+ // #6693: the fact keeps the dates its first admission gave it (valid_from defaults to the admission time, a ttl to an absolute expiry).+ if (typeof write.intent.valid_from === 'string') params.valid_from = write.intent.valid_from;+ if (typeof write.intent.valid_until === 'string') params.ttl = write.intent.valid_until;+ else delete params.ttl;return { params };}if (write.operation === 'put_page') {@@ -414,3 +421,55 @@ async function replay(ctx: OperationContext, failed: ApprovedWrite): Promise<Rep}return { applied: true, outcome: 'replayed' };}++/** #6693: the most caller remembers one sync run replays, and the time it may spend on them. */+export const IMPORT_REPLAY_LIMIT = 50;+export const IMPORT_REPLAY_BUDGET_MS = 30_000;++/** #6693: what one post-sync replay pass did; counts only, never a slug or claim. */+export interface ImportReplayReport {+ /** Refused remembers of the source whose page awaited import or was held by sync, not yet written. */+ examined: number;+ replayed: number;+ /** Their page still differs from its file (not imported yet, or still held): kept for a later sync. */+ waiting: number;+ /** Not replayed: written or superseded since, unpinned, or the replay was refused (authority, conflict); `gbrain repair failed-writes` lists each. */+ skipped: number;+ /** Left for the next sync by the per-run limit or time budget. */+ remaining: number;+}++/**+ * #6693 (D7): after a managed sync, replay once each caller `remember` that was+ * refused because its page's file held a committed change sync had not imported+ * (`pending_import`) or was held by sync (`sync_held`), now that the page matches+ * its file again. Same path as `gbrain repair failed-writes --apply`: the+ * disposition rules, the original trust lane, a live authority re-check and a+ * request id derived from the refused request, so two passes (or a pass and a+ * manual apply) admit one request. A page still drifted is skipped before any+ * admission, so a pass adds no receipt for it. `put_page` is never replayed here:+ * its full body would replace the change the sync just imported.+ */+export async function replayImportedRemembers(ctx: OperationContext, sourceId: string,+ opts: { limit?: number; budgetMs?: number; now?: () => number } = {}): Promise<ImportReplayReport> {+ const now = opts.now ?? Date.now;+ const deadline = now() + (opts.budgetMs ?? IMPORT_REPLAY_BUDGET_MS);+ const limit = opts.limit ?? IMPORT_REPLAY_LIMIT;+ const candidates = (await failedWrites(ctx.engine, [sourceId])).filter(write => write.operation === 'remember' && write.producer === null+ && (write.origin === PENDING_IMPORT || write.origin === SYNC_HELD));+ const report: ImportReplayReport = { examined: 0, replayed: 0, waiting: 0, skipped: 0, remaining: 0 };+ for (const [index, write] of candidates.entries()) {+ if (report.replayed >= limit || now() >= deadline) { report.remaining = candidates.length - index; break; }+ const verdict = await disposition(ctx.engine, write);+ // A replay that committed (or a later write of the same fact) settles the receipt; it stays as history only.+ if (verdict.class === 'already_written') continue;+ report.examined++;+ if (verdict.class !== 'replay') { report.skipped++; continue; }+ if (await stillDrifted(ctx.engine, write)) { report.waiting++; continue; }+ const outcome = await replay(ctx, { ...write, revision: await pageRevision(ctx.engine, write.source_id, write.slug), selection: [sourceId] });+ if (outcome.applied) report.replayed++;+ else if (outcome.outcome === 'file_database_drift') report.waiting++;+ else report.skipped++;+ }+ return report;+}diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 2bd846b94b..3ad0ce4d56 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -59,6 +59,7 @@ import { frontmatterRepair } from './frontmatter.ts';import { attributionBackfillRepair } from './attribution-backfill.ts';import { plannerStatsRepair } from './planner-stats.ts';import { fencesRepair } from './fences.ts';+import { splitFactsRepair } from './split-facts.ts';import { slugConflictsRepair } from './slug-conflicts.ts';import { frontmatterKeysRepair } from './frontmatter-keys.ts';import { fileDriftRepair } from './file-drift.ts';@@ -219,6 +220,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'reconcile, relink, maintenance) are counted with the command that produces them again. Preview-bound: --apply --expect <hash> replays exactly '+ 'the previewed set under new request ids, after re-checking each write\'s original authority; the failed receipts stay as history.',},+ 'split-facts': {+ handler: splitFactsRepair, embeds: 'effect', checks: [], explicit_only: true,+ summary: 'Merge the two ## Facts fences of a page whose fence lived below the timeline sentinel and to which a managed writer before this release '+ + 'added a second fence above it (#6686). The merged fence stays below the sentinel and keeps every row of both fences under its own row number; '+ + 'the body fence goes, with its ## Facts heading when that holds nothing else. A page is kept when a fence does not parse (unparsed), a row '+ + 'number is in both fences (row_collision: a person chooses), or the merged page would not read back exactly (not_conserved). Preview-bound: '+ + '--apply --expect <hash> merges exactly the previewed pages through revision-bound put_page (changed_since_preview when a page moved). Runs only when named.',+ },frontmatter: {handler: frontmatterRepair, embeds: 'effect', checks: ['git_held_files', 'frontmatter_repairable'], explicit_only: true, consent: 'destructive',summary: 'Fix files whose YAML frontmatter gbrain holds or reads only by guessing (#5988), and pages an older import stored wrong: per file the minimal 'diff --git a/src/core/repair/split-facts.ts b/src/core/repair/split-facts.tsnew file mode 100644index 0000000000..97e620aee8--- /dev/null+++ b/src/core/repair/split-facts.ts@@ -0,0 +1,142 @@+/**+ * `gbrain repair split-facts` (#6686, D8): merge the two `## Facts` fences of a+ * page whose fence lived below the timeline sentinel and to which a managed+ * writer before this release added a second fence above it. The merged fence+ * stays where the original one is (the timeline section), holding every row of+ * both fences under its own row number; the body fence goes, with the+ * `## Facts` heading the writer added when that heading holds nothing else.+ *+ * A page is kept, never guessed at, when a fence does not parse cleanly+ * (`unparsed`), when a row number appears in both fences (`row_collision`: a+ * person chooses which row keeps it), or when the merged page would not read+ * back exactly (`not_conserved`: the serialized page must split into the+ * intended body and timeline, carry no fence defect, and hold every before row+ * cell for cell). Explicit-only and preview-bound: the preview lists each page+ * with its revision under a hash; `--apply --expect <hash>` publishes exactly+ * that set through revision-bound `put_page`s (`changed_since_preview` when a+ * page moved). It never runs from `--all`, the remediation plan, the+ * maintenance cycle or an upgrade.+ */+import type { BrainEngine } from '../engine.ts';+import type { Page } from '../types.ts';+import { OperationError } from '../ops/contract.ts';+import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';+import { locateOutsideCode } from '../fence-scan.ts';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, factsFenceSections, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, type ParsedFact } from '../facts-fence.ts';+import { scanCanonicalFences } from '../fence-repair/refusal.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';++type Residual = 'unparsed' | 'row_collision' | 'not_conserved';++const rowKey = (row: ParsedFact) => JSON.stringify(row);+const byRow = (a: ParsedFact, b: ParsedFact) => a.rowNum - b.rowNum;++/** The page body without its facts fence, and without the `## Facts` heading above it when that heading holds only the fence. */+function withoutBodyFence(body: string): string {+ const { beginIdx, endIdx } = locateOutsideCode(body, FACTS_FENCE_BEGIN, FACTS_FENCE_END);+ let before = body.slice(0, beginIdx);+ const after = body.slice(endIdx + FACTS_FENCE_END.length);+ if (/^\s*(#|$)/.test(after)) before = before.replace(/(^|\n)## Facts[ \t]*\n\s*$/, '$1');+ const head = before.trimEnd();+ const tail = after.trim() ? after.replace(/^\s+/, '') : '';+ return head && tail ? `${head}\n\n${tail}` : head || tail;+}++/** The merged page, or why it is kept; null when the page is not split. */+export function mergeSplitFacts(page: Page, tags: string[]): { compiled_truth: string; timeline: string } | { residual: Residual; rows?: number[] } | null {+ const held = factsFenceSections(page);+ if (!held.body || !held.timeline) return null;+ const body = parseFactsFence(page.compiled_truth), timeline = parseFactsFence(page.timeline ?? '');+ if (body.warnings.length || timeline.warnings.length) return { residual: 'unparsed' };+ const numbers = new Set(timeline.facts.map(row => row.rowNum));+ const collisions = [...new Set(body.facts.map(row => row.rowNum).filter(n => numbers.has(n)))].sort((a, b) => a - b);+ if (collisions.length) return { residual: 'row_collision', rows: collisions };+ const merged = [...timeline.facts, ...body.facts].sort(byRow);+ const next = { compiled_truth: withoutBodyFence(page.compiled_truth), timeline: replaceOrInsertFactsFence(page.timeline ?? '', renderFactsTable(merged)) };+ // The published bytes must read back as exactly this page: the same two sections, no fence defect, every before row.+ const reread = parseMarkdown(serializePageToMarkdown({ ...page, ...next }, tags), `${page.slug}.md`);+ const scan = scanCanonicalFences({ compiled_truth: reread.compiled_truth, timeline: reread.timeline });+ const conserved = reread.compiled_truth.trim() === next.compiled_truth.trim() && (reread.timeline ?? '').trim() === next.timeline.trim() && !scan.defects.length+ && JSON.stringify([...scan.facts].sort(byRow).map(rowKey)) === JSON.stringify(merged.map(rowKey))+ && !factsFenceSections(next).body;+ return conserved ? next : { residual: 'not_conserved' };+}++interface ApprovedPage { source_id: string; slug: string; id: number; revision: string }+interface SplitItem extends RepairItem { approved: ApprovedPage; hash: string; last: boolean }++function previewCommand(scope: RepairScope): string {+ return `gbrain repair split-facts${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;+}++async function sourcesOf(engine: BrainEngine, scope: RepairScope) {+ return engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);+}++const hashOf = async (engine: BrainEngine, scope: RepairScope, pages: ApprovedPage[]) =>+ previewHash({ kind: 'split-facts-v1', brain_id: scope.brain_id, sources: await sourcesOf(engine, scope), selection: { source_ids: scope.source_ids }, pages });++function item(page: ApprovedPage, hash: string, last: boolean): SplitItem {+ return { cursor: { phase: 0, id: page.id }, source_id: page.source_id, slug: page.slug, chars: 0, action: 'merge the split ## Facts fences', approved: page, hash, last };+}++export const splitFactsRepair: RepairHandler = {+ kind: 'split-facts',+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const command = previewCommand(scope);+ if (opts?.apply) {+ if (!opts.expect) throw new OperationError('invalid_params', 'gbrain repair split-facts --apply merges only the set a preview printed.',+ `Preview first: ${command} — show the user the listing, then run the apply command it prints: ${command} --apply --expect <preview-hash>`, 'docs/guides/repair.md#split-facts');+ const approved = await loadApprovedSet<ApprovedPage>(engine, { command: 'split-facts', hash: opts.expect, previewCommand: command,+ emptyHash: () => hashOf(engine, scope, []) });+ if (approved.items.some(page => !scope.source_ids.includes(page.source_id))) throw previewChangedError(opts.expect, command);+ return { items: approved.items.map((page, index) => item(page, opts.expect!, index === approved.items.length - 1)).filter(entry => afterCursor(entry.cursor, after)),+ preview_hash: opts.expect, residuals: {} };+ }+ const pages = await engine.executeRaw<{ id: number; source_id: string; slug: string }>(+ `SELECT id, source_id, slug FROM pages+ WHERE source_id=ANY($1::text[]) AND deleted_at IS NULL AND compiled_truth LIKE '%gbrain:facts:begin%' AND timeline LIKE '%gbrain:facts:begin%' ORDER BY id`,+ [scope.source_ids]);+ const residuals: Record<string, number> = {};+ const listing: NonNullable<RepairPlan['listing']> = [];+ const merge: ApprovedPage[] = [];+ for (const page of pages) {+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });+ if (!snapshot) continue;+ const verdict = mergeSplitFacts(snapshot.page, snapshot.tags);+ if (!verdict) continue;+ const label = `${page.source_id}:${page.slug} (revision ${snapshot.revision})`;+ if ('residual' in verdict) {+ residuals[verdict.residual] = (residuals[verdict.residual] ?? 0) + 1;+ listing.push({ item: label, class: verdict.residual, detail: verdict.residual === 'row_collision'+ ? `rows ${verdict.rows!.join(', ')} are numbered in both fences; edit the page so each number appears once, then preview again`+ : verdict.residual === 'unparsed' ? 'a fence does not parse cleanly; gbrain repair fences previews its repair' : 'the merged page would not read back exactly; merge the fences by hand' });+ continue;+ }+ merge.push({ source_id: page.source_id, slug: page.slug, id: page.id, revision: snapshot.revision });+ listing.push({ item: label, class: 'merge', detail: 'the body fence\'s rows move into the fence below the timeline sentinel' });+ }+ const hash = await hashOf(engine, scope, merge);+ if (merge.length) await saveApprovedSet<ApprovedPage>(engine, { command: 'split-facts', hash }, merge);+ return { items: merge.map((page, index) => item(page, hash, index === merge.length - 1)), preview_hash: hash, residuals, listing };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { approved, hash, last } = entry as SplitItem;+ const outcome = await mergeOne(ctx, entry, approved);+ if (last) await clearApprovedSet(ctx.engine, { command: 'split-facts', hash });+ return outcome;+ },+};++async function mergeOne(ctx: Parameters<RepairHandler['apply']>[0], entry: RepairItem, approved: ApprovedPage): Promise<RepairItemOutcome> {+ const snapshot = await ctx.engine.readPageSnapshot(approved.slug, { sourceId: approved.source_id });+ if (!snapshot || snapshot.revision !== approved.revision) return { applied: false, outcome: 'changed_since_preview', reason: 'the page changed since the preview' };+ const next = mergeSplitFacts(snapshot.page, snapshot.tags);+ if (!next || 'residual' in next) return { applied: false, outcome: 'changed_since_preview', reason: next ? next.residual : 'the page is no longer split' };+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: approved.slug, source_id: approved.source_id,+ content: serializePageToMarkdown({ ...snapshot.page, ...next }, snapshot.tags), expected_revision: snapshot.revision,+ request_id: await repairRequestId(ctx, 'split-facts', entry, snapshot.revision) } });+ return { applied: true, outcome: 'merged' };+}diff --git a/test/e2e/managed-timeline-facts-postgres.test.ts b/test/e2e/managed-timeline-facts-postgres.test.tsnew file mode 100644index 0000000000..52bbdcbc3d--- /dev/null+++ b/test/e2e/managed-timeline-facts-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../managed-timeline-facts.serial.test.ts'));diff --git a/test/e2e/system-of-record-invariant.test.ts b/test/e2e/system-of-record-invariant.test.tsindex 98ee30ad39..a9af3c5d52 100644--- a/test/e2e/system-of-record-invariant.test.ts+++ b/test/e2e/system-of-record-invariant.test.ts@@ -389,7 +389,7 @@ ${remoteBody}`, { noEmbed: true, sourceId: 'default', remote: true });// page authored with the `## Facts` fence below `<!-- timeline -->` — the// LLM-composed shape the issue describes — imported through the actual// production write path (importFromContent → parseMarkdown → splitBody).- test('a fence written below the sentinel really does land in page.timeline via splitBody, and extract_facts preserves the existing index instead of wiping it', async () => {+ test('a fence written below the sentinel really does land in page.timeline via splitBody, and extract_facts reads it there instead of wiping the index (#6686)', async () => {const slug = 'people/real-split-fence';const fenceRows = `| 1 | REAL_SPLIT_FACT | fact | 1.0 | world | high | 2026-01-01 | | s | |`;@@ -448,8 +448,9 @@ ${fenceRows}expect(moved?.compiled_truth ?? '').not.toContain('gbrain:facts:begin');expect(moved?.timeline ?? '').toContain('gbrain:facts:begin');+ // #6686 (D8): a lone timeline fence is the page's fence, so the reconcile reads it in place and keeps the row.const r = await runExtractFacts(engine, { slugs: [slug] });- expect(r.warnings.some(w => w.includes('FACTS_FENCE_BELOW_SENTINEL'))).toBe(true);+ expect(r.warnings).toEqual([]);expect(r.factsDeleted).toBe(0);// eslint-disable-next-line @typescript-eslint/no-explicit-anydiff --git a/test/extract-facts-phase.test.ts b/test/extract-facts-phase.test.tsindex d803e736e2..2391d3a410 100644--- a/test/extract-facts-phase.test.ts+++ b/test/extract-facts-phase.test.ts@@ -658,7 +658,7 @@ describe('runExtractFacts — happy path', () => {expect(cleanRows.rows.map((row: { fact: string }) => row.fact)).toEqual(['Clean']);});- test('#3625: a Facts fence below the timeline sentinel is loud-skipped, never treated as absence', async () => {+ test('#3625 / #6686: a lone Facts fence below the timeline sentinel is read as the page fence, never treated as absence', async () => {await putPage('people/carol', FACT_FENCE(`| 1 | Seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,));@@ -680,7 +680,8 @@ describe('runExtractFacts — happy path', () => {const r = await runExtractFacts(engine, { slugs: ['people/carol'] });- expect(r.warnings.some(w => w.includes('FACTS_FENCE_BELOW_SENTINEL'))).toBe(true);+ // #6686 (D8): the managed writers keep and edit a lone timeline fence in place, so reconcile reads it there.+ expect(r.warnings).toEqual([]);expect(r.factsDeleted).toBe(0);expect(r.factsInserted).toBe(0);@@ -713,7 +714,7 @@ describe('runExtractFacts — happy path', () => {expect(Number(rows.rows[0].n)).toBe(0);});- test('#3625: a Facts fence below the timeline sentinel is preserved, not deleted, and warns loudly', async () => {+ test('#3625 / #6686: a lone Facts fence below the timeline sentinel reconciles from where it lives, not as a deleted fence', async () => {// Seed the page with the fence in its normal place (above the sentinel)// and let it index normally.await putPage('people/alice', FACT_FENCE(@@ -743,16 +744,17 @@ describe('runExtractFacts — happy path', () => {const r = await runExtractFacts(engine, { slugs: ['people/alice'] });- // The fix: this must NOT read as "fence removed" and must NOT delete- // the previously-indexed rows.+ // This must NOT read as "fence removed": #6686 (D8) reads the lone timeline fence as the page's fence, so the+ // two rows the page write already projected from it stay indexed and the reconcile finds them in sync.+ expect(r.warnings).toEqual([]);expect(r.factsDeleted).toBe(0);- expect(r.warnings.some(w => w.includes('FACTS_FENCE_BELOW_SENTINEL'))).toBe(true);+ expect(r.factsInserted).toBe(0);// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst rows = await (engine as any).db.query(- `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice' ORDER BY row_num`,+ `SELECT fact, row_num FROM facts WHERE source_markdown_slug = 'people/alice' AND expired_at IS NULL ORDER BY row_num`,);- expect(rows.rows.map((row: { fact: string }) => row.fact)).toEqual(['Founded Acme', 'Prefers async']);+ expect(rows.rows.map((row: { fact: string; row_num: number }) => [row.fact, Number(row.row_num)])).toEqual([['Founded Acme', 1], ['Prefers async', 2]]);});test('#3625 control: a genuinely fence-less page (no fence anywhere in the body) still wipes as before', async () => {diff --git a/test/managed-timeline-facts.serial.test.ts b/test/managed-timeline-facts.serial.test.tsnew file mode 100644index 0000000000..81ecddfb43--- /dev/null+++ b/test/managed-timeline-facts.serial.test.ts@@ -0,0 +1,187 @@+/** #6686: managed fact appends must see a legacy fence below the timeline sentinel.+ * Real journal/coordinator publication on PGLite and optional Postgres, no providers.+ * The remember/extract_facts × body/timeline/quoted cases and the replacement case are from PR #6689 (Contributed by @javieraldape).+ * Serial: configures the process-global gateway and persistence consumer registry.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { parseFactsFence, upsertFactRow, FACTS_FENCE_BEGIN } from '../src/core/facts-fence.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';+import { prepareManagedFactsMutation } from '../src/core/persistence/facts-prepare.ts';+import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const config = { embedding_disabled: true };+const claim = 'Private historical preference';+const fresh = 'Prefers asynchronous weekly reports';+const biography = 'Synthetic biography with preserved prose.';+const history = '## Timeline\n\n- 2026-10-01: Preserved historical event.';+const oldFence = upsertFactRow('', { rowNum: 7, claim, kind: 'preference', visibility: 'private', confidence: 1, notability: 'medium', source: 'fixture' }).body;++beforeAll(async () => {+ configureGateway({ ...config, env: {} });+ for (const backend of testBackends()) {+ if (backend === 'pglite') {+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine);+ } else {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close;+ }+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); resetGateway();+});++async function fixture(engine: BrainEngine, section: 'body' | 'timeline' | 'quoted') {+ const sourceId = `timeline-facts-${randomUUID()}`;+ const slug = 'people/example';+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ const quoted = `\n\n\`\`\`markdown\n${oldFence}\n\`\`\``;+ await engine.putPage(slug, { type: 'person', title: 'Example', compiled_truth: biography + (section === 'body' ? `\n\n${oldFence}` : ''),+ timeline: history + (section === 'timeline' ? `\n\n${oldFence}` : section === 'quoted' ? quoted : ''),+ frontmatter: { private_metadata: 'preserved fixture' } }, { sourceId });+ await engine.addTag(slug, 'preserved-tag', { sourceId });+ let oldId: number | undefined;+ if (section !== 'quoted') {+ oldId = (await engine.insertFacts([{ fact: claim, entity_slug: slug, source_markdown_slug: slug, row_num: 7,+ kind: 'preference', visibility: 'private', source: 'fixture', confidence: 1 }], { source_id: sourceId })).ids[0];+ }+ await registerLocalWriter(engine, 'cli');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx: OperationContext = { engine, sourceId, config: { ...config, engine: engine.kind }, remote: false,+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ return { sourceId, slug, ctx, oldId };+}++async function extract(engine: BrainEngine, f: Awaited<ReturnType<typeof fixture>>) {+ await disposePersistenceConsumer(engine);+ const snapshot = (await engine.readPageSnapshot(f.slug, { sourceId: f.sourceId }))!;+ const authority = await submissionAuthority(f.ctx, 'extract_facts', f.sourceId, snapshot.sourceIncarnation, f.slug);+ const intent = { kind: 'managed_facts_entity', batchKey: randomUUID(), inputDigest: randomUUID(), expected_revision: snapshot.revision,+ facts: [{ fact: fresh, entity_slug: f.slug, source: 'fixture extraction', kind: 'preference', visibility: 'world', confidence: 1,+ valid_from: '2026-10-14T00:00:00.000Z', valid_until: null, embedding: null }] };+ const row = await admitWrite(engine, { principal: authority.principal, operation: 'extract_facts', sourceId: f.sourceId,+ sourceIncarnation: snapshot.sourceIncarnation, slug: f.slug, pageId: snapshot.page.id, callerIntent: intent, intent, authority, requestId: randomUUID() });+ const claimed = (await claimNextWrite(engine, localHostId()))!;+ expect(claimed.id).toBe(row.id);+ const result = await publishMutation(engine, claimed, await prepareManagedFactsMutation(engine, claimed, f.ctx.config), localHostId());+ expect(result.state).toBe('committed');+ expect((await getWriteRequestById(engine, row.id))?.outcome).toMatchObject({ inserted: 1, fenced: true });+}++async function assertPage(engine: BrainEngine, f: Awaited<ReturnType<typeof fixture>>, section: 'body' | 'timeline' | 'quoted', supersedes = false) {+ const snapshot = (await engine.readPageSnapshot(f.slug, { sourceId: f.sourceId }))!;+ const page = snapshot.page;+ expect(page.compiled_truth).toContain(biography);+ expect(page.timeline).toContain(history);+ expect(page.frontmatter.private_metadata).toBe('preserved fixture');+ expect(snapshot.tags).toEqual(['preserved-tag']);+ const content = serializePageToMarkdown(page, snapshot.tags);+ const facts = parseFactsFence(content);+ expect(facts.warnings).toEqual([]);+ expect(facts.facts.map(row => row.claim)).toEqual(section === 'quoted' ? [fresh] : [claim, fresh]);+ const selected = section === 'timeline' ? page.timeline : page.compiled_truth;+ expect(parseFactsFence(selected).facts).toHaveLength(section === 'quoted' ? 1 : 2);+ if (section === 'timeline') expect(page.compiled_truth).toBe(biography);+ if (section === 'quoted') expect(page.timeline).toContain(oldFence);+ else expect(content.split(FACTS_FENCE_BEGIN)).toHaveLength(2);+ const rows = await engine.executeRaw<{ fact: string; row_num: number; expired: boolean }>(+ 'SELECT fact,row_num,expired_at IS NOT NULL AS expired FROM facts WHERE source_id=$1 ORDER BY row_num', [f.sourceId]);+ expect(rows.map(row => row.fact)).toEqual(section === 'quoted' ? [fresh] : [claim, fresh]);+ if (section !== 'quoted') {+ expect(rows.map(row => Number(row.row_num))).toEqual([7, 8]);+ expect(facts.facts[0].active).toBe(!supersedes);+ expect(rows[0].expired).toBe(supersedes);+ }+ expect((await engine.getChunks(f.slug, { sourceId: f.sourceId })).map(c => c.chunk_text).join('\n')).not.toContain(claim);+}++for (const writer of ['remember', 'extract_facts'] as const) {+ describe(`${writer} preserves canonical timeline facts`, () => {+ for (const section of ['timeline', 'body', 'quoted'] as const) {+ test(`appends without splitting the ${section} fence or losing private history`, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, section);+ try {+ if (writer === 'remember') {+ const params = { fact: fresh, provenance: 'fixture', entity: f.slug, request_id: randomUUID() };+ const receipt = await submitRememberMutation(f.ctx, params, 30_000);+ expect(receipt.state).toBe('committed');+ await disposePersistenceConsumer(engine);+ expect(await submitRememberMutation(f.ctx, params)).toEqual(receipt);+ } else await extract(engine, f);+ await assertPage(engine, f, section);+ } finally { await disposePersistenceConsumer(engine); }+ }+ }, 120_000);+ }+ });+}+test('caller replacement strikes the old timeline row and preserves row identity', async () => {+ for (const engine of engines) {+ const f = await fixture(engine, 'timeline');+ try {+ const receipt = await submitRememberMutation(f.ctx, { fact: fresh, provenance: 'fixture', entity: f.slug,+ visibility: 'private', replaces: String(f.oldId), request_id: randomUUID() }, 30_000);+ expect(receipt.state).toBe('committed');+ await assertPage(engine, f, 'timeline', true);+ } finally { await disposePersistenceConsumer(engine); }+ }+}, 120_000);++test('a timeline-only page whose index holds rows beyond its fence numbers the new row past both (#6541 shape)', async () => {+ for (const engine of engines) {+ const f = await fixture(engine, 'timeline');+ try {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.insertFacts([{ fact: 'Indexed outside the fence', entity_slug: f.slug, source_markdown_slug: f.slug, row_num: 9,+ kind: 'fact', visibility: 'world', source: 'fixture', confidence: 1 }], { source_id: f.sourceId });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const before = (await engine.readPageSnapshot(f.slug, { sourceId: f.sourceId }))!.page;+ const receipt = await submitRememberMutation(f.ctx, { fact: fresh, provenance: 'fixture', entity: f.slug, request_id: randomUUID() }, 30_000);+ expect(receipt.state).toBe('committed');+ const page = (await engine.readPageSnapshot(f.slug, { sourceId: f.sourceId }))!.page;+ expect(page.compiled_truth).toBe(before.compiled_truth);+ expect(parseFactsFence(page.compiled_truth).facts).toEqual([]);+ expect(parseFactsFence(page.timeline).facts.map(row => [row.rowNum, row.claim])).toEqual([[7, claim], [10, fresh]]);+ expect(page.timeline.startsWith(history)).toBe(true);+ } finally { await disposePersistenceConsumer(engine); }+ }+}, 120_000);++test('on a split page, a replacement strikes the old row in the timeline fence that holds it', async () => {+ for (const engine of engines) {+ const f = await fixture(engine, 'timeline');+ try {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const above = upsertFactRow('', { rowNum: 8, claim: 'Added above by an older writer', kind: 'fact', visibility: 'world', confidence: 1, notability: 'medium', source: 'fixture' }).body;+ const snapshot = (await engine.readPageSnapshot(f.slug, { sourceId: f.sourceId }))!;+ await engine.putPage(f.slug, { type: 'person', title: 'Example', compiled_truth: `${biography}\n\n${above}`, timeline: snapshot.page.timeline,+ frontmatter: snapshot.page.frontmatter }, { sourceId: f.sourceId });+ await engine.insertFacts([{ fact: 'Added above by an older writer', entity_slug: f.slug, source_markdown_slug: f.slug, row_num: 8,+ kind: 'fact', visibility: 'world', source: 'fixture', confidence: 1 }], { source_id: f.sourceId });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const receipt = await submitRememberMutation(f.ctx, { fact: fresh, provenance: 'fixture', entity: f.slug,+ visibility: 'private', replaces: String(f.oldId), request_id: randomUUID() }, 30_000);+ expect(receipt.state).toBe('committed');+ const page = (await engine.readPageSnapshot(f.slug, { sourceId: f.sourceId }))!.page;+ const struck = parseFactsFence(page.timeline).facts.find(row => row.rowNum === 7)!;+ expect([struck.active, struck.supersededBy]).toEqual([false, 9]);+ expect(parseFactsFence(page.compiled_truth).facts.map(row => [row.rowNum, row.claim])).toEqual([[8, 'Added above by an older writer'], [9, fresh]]);+ } finally { await disposePersistenceConsumer(engine); }+ }+}, 120_000);diff --git a/test/remember-pending-import.test.ts b/test/remember-pending-import.test.tsnew file mode 100644index 0000000000..b87ca7f779--- /dev/null+++ b/test/remember-pending-import.test.ts@@ -0,0 +1,130 @@+/**+ * #6693 (D7): a remember onto a page whose canonical file holds a committed Git change managed sync has not imported+ * yet (another agent's commit) is refused `pending_import`, kept, and replayed once by the sync that imports the file.+ * Managed PGLite brain with a durable Git repo, no providers.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { performSync } from '../src/commands/sync.ts';+import { parseFactsFence } from '../src/core/facts-fence.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';+import { lostCallerWrites, replayImportedRemembers } from '../src/core/repair/failed-writes.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { durableGitRepo, git } from './helpers/git-publication.ts';++const slug = 'people/owner-example';+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };+const file = (root: string) => join(root, `${slug}.md`);+const edit = (root: string, line: string) => writeFileSync(file(root), readFileSync(file(root), 'utf8').replace('Body.', `Body.\n\n${line}`));++async function seed(ctx: OperationContext) {+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(),+ content: '---\ntype: person\ntitle: Owner\n---\n\nBody.\n' } });+}+async function refused(run: () => Promise<unknown>) {+ try { await run(); } catch (error) { return error as { code?: string; reason?: string; message?: string; fix?: { actor?: string; argv?: string[] } }; }+ throw new Error('the write was expected to be refused');+}+const lastReceipt = async (engine: BrainEngine, operation: string) => (await engine.executeRaw<{ state: string; error_code: string; error_detail: { origin?: string } | null }>(+ 'SELECT state,error_code,error_detail FROM persistence_requests WHERE operation=$1 ORDER BY sequence DESC LIMIT 1', [operation]))[0];+const sync = (engine: BrainEngine, root: string) => performSync(engine, { repoPath: root, sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, concurrency: 1 });+const claims = async (engine: BrainEngine) => (await engine.executeRaw<{ fact: string; row_num: number | null }>(+ "SELECT fact,row_num FROM facts WHERE source_id='default' AND entity_slug=$1 AND expired_at IS NULL ORDER BY id", [slug]));++describe('#6693 remember onto a page whose file awaits import', () => {+ test('is refused pending_import, kept, and replayed once by the sync that imports the file', () => managedBrain(async ({ engine, ctx, root }) => {+ await seed(ctx);+ edit(root, 'Another agent added this line through Git.');+ git(root, 'add', '--', `${slug}.md`); git(root, 'commit', '-q', '-m', 'agent commit not yet imported');++ const error = await refused(() => submitRememberMutation(ctx, { fact: 'Owner prefers async updates', entity: slug, provenance: 'test', visibility: 'world',+ valid_from: '2026-09-01T00:00:00.000Z' }));+ expect(error.code).toBe('source_changed');+ expect(error.reason).toBe('pending_import');+ expect(error.message).toBe('The canonical file holds a committed Git change that sync has not imported yet.');+ // A remember waits for its replay: a status read under a provider actor renders `next: wait`.+ expect(error.fix?.actor).toBe('provider');+ expect(error.fix?.argv).toEqual(['gbrain', 'sync', 'status', '--source', 'default', '--json']);+ const receipt = await lastReceipt(engine, 'remember');+ expect(receipt.state).toBe('conflict');+ expect(receipt.error_detail?.origin).toBe('pending_import');+ // Before the import, a direct pass replays nothing and admits nothing.+ expect(await replayImportedRemembers(ctx, 'default')).toMatchObject({ examined: 1, replayed: 0, waiting: 1 });+ expect((await engine.executeRaw('SELECT 1 FROM persistence_requests WHERE operation=$1', ['remember'])).length).toBe(1);++ const result = await sync(engine, root);+ expect(result.replayedRemembers).toMatchObject({ examined: 1, replayed: 1, waiting: 0 });+ const content = readFileSync(file(root), 'utf8');+ expect(content).toContain('Another agent added this line through Git.');+ expect(parseFactsFence(content).facts.map(f => [f.claim, f.validFrom])).toEqual([['Owner prefers async updates', '2026-09-01']]);+ expect((await claims(engine)).map(row => [row.fact, Number(row.row_num)])).toEqual([['Owner prefers async updates', 1]]);+ expect((await lostCallerWrites(engine, ['default'])).lost).toEqual([]);++ // The next sync finds the receipt settled and replays nothing again.+ expect((await sync(engine, root)).replayedRemembers).toBeUndefined();+ expect(await claims(engine)).toHaveLength(1);+ }, { setup }), 120_000);++ test('two concurrent passes admit one replay', () => managedBrain(async ({ engine, ctx, root }) => {+ await seed(ctx);+ const original = readFileSync(file(root), 'utf8');+ edit(root, 'Committed elsewhere.');+ git(root, 'add', '--', `${slug}.md`); git(root, 'commit', '-q', '-m', 'agent commit');+ await refused(() => submitRememberMutation(ctx, { fact: 'Owner reads email at noon', entity: slug, provenance: 'test', visibility: 'world' }));+ // The other agent takes its change back: the file matches the page again without a sync, so both passes see a replayable write.+ writeFileSync(file(root), original);+ git(root, 'add', '--', `${slug}.md`); git(root, 'commit', '-q', '-m', 'agent takes it back');+ const reports = await Promise.all([replayImportedRemembers(ctx, 'default'), replayImportedRemembers(ctx, 'default')]);+ expect(reports.reduce((sum, r) => sum + r.replayed, 0)).toBeGreaterThanOrEqual(1);+ expect((await claims(engine)).map(row => row.fact)).toEqual(['Owner reads email at noon']);+ expect((await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE operation='remember' AND state='committed'")).length).toBe(1);+ }, { setup }), 120_000);++ test('a remember refused by a sync-held file is replayed after the repaired file is imported', () => managedBrain(async ({ engine, ctx, root }) => {+ await seed(ctx);+ writeFileSync(file(root), '---\ntype: person\ntitle: [unclosed\n---\n\nBody.\n');+ git(root, 'add', '--', `${slug}.md`); git(root, 'commit', '-q', '-m', 'broken frontmatter');+ await sync(engine, root);+ const error = await refused(() => submitRememberMutation(ctx, { fact: 'Owner prefers mornings', entity: slug, provenance: 'test', visibility: 'world' }));+ expect(error.code).toBe('source_changed');+ expect((await lastReceipt(engine, 'remember')).error_detail?.origin).toBe('sync_held');+ writeFileSync(file(root), '---\ntype: person\ntitle: Owner\n---\n\nBody.\n\nRepaired.\n');+ git(root, 'add', '--', `${slug}.md`); git(root, 'commit', '-q', '-m', 'repair frontmatter');+ expect((await sync(engine, root)).replayedRemembers).toMatchObject({ replayed: 1 });+ expect((await claims(engine)).map(row => row.fact)).toEqual(['Owner prefers mornings']);+ expect(readFileSync(file(root), 'utf8')).toContain('Repaired.');+ }, { setup }), 120_000);++ test('an uncommitted hand edit keeps the reconcile refusal and is never replayed', () => managedBrain(async ({ engine, ctx, root }) => {+ await seed(ctx);+ edit(root, 'A hand edit nobody committed.');+ const error = await refused(() => submitRememberMutation(ctx, { fact: 'Owner likes tea', entity: slug, provenance: 'test', visibility: 'world' }));+ expect(error.code).toBe('source_changed');+ expect(error.reason).toBeUndefined();+ expect(error.message).toBe('The canonical file contains an uncoordinated local edit.');+ expect((await lastReceipt(engine, 'remember')).error_detail).toBeNull();+ git(root, 'add', '--', `${slug}.md`); git(root, 'commit', '-q', '-m', 'commit the hand edit later');+ expect((await sync(engine, root)).replayedRemembers).toBeUndefined();+ expect(await claims(engine)).toEqual([]);+ }, { setup }), 120_000);++ test('a put_page refused the same way is classified but not replayed', () => managedBrain(async ({ engine, ctx, root }) => {+ await seed(ctx);+ edit(root, 'Committed by another agent.');+ git(root, 'add', '--', `${slug}.md`); git(root, 'commit', '-q', '-m', 'agent commit');+ const revision = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision;+ const error = await refused(() => submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), expected_revision: revision,+ content: '---\ntype: person\ntitle: Owner\n---\n\nReplaced body.\n' } }));+ expect(error.reason).toBe('pending_import');+ expect(error.fix?.argv).toEqual(['gbrain', 'sync', '--source', 'default', '--no-pull', '--json']);+ expect((await lastReceipt(engine, 'put_page')).error_detail?.origin).toBe('pending_import');+ expect((await sync(engine, root)).replayedRemembers).toBeUndefined();+ expect(readFileSync(file(root), 'utf8')).toContain('Committed by another agent.');+ expect(readFileSync(file(root), 'utf8')).not.toContain('Replaced body.');+ }, { setup }), 120_000);+});diff --git a/test/repair-split-facts.test.ts b/test/repair-split-facts.test.tsnew file mode 100644index 0000000000..88030f0d41--- /dev/null+++ b/test/repair-split-facts.test.ts@@ -0,0 +1,114 @@+/**+ * #6686 (D8): `gbrain repair split-facts` merges a page's two ## Facts fences (one below the timeline sentinel, one a+ * managed writer added above it) into the fence below the sentinel, keeping every row number and fact id; a row number+ * in both fences is listed for a person and never merged. Real journal publication on PGLite, no providers.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { FACTS_FENCE_BEGIN, parseFactsFence, upsertFactRow } from '../src/core/facts-fence.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { AUTO_REPAIR_REGISTRY, repairRunner } from '../src/core/repair/registry.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { mergeSplitFacts } from '../src/core/repair/split-facts.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-split-facts-'));+const logger = { info() {}, warn() {}, error() {} };+const biography = 'Synthetic biography with preserved prose.';+const history = '## Timeline\n\n- 2026-10-01: Preserved historical event.';+let engine: PGLiteEngine;+const config = { embedding_disabled: true };++const fence = (rows: Array<[number, string, 'world' | 'private']>) => rows.reduce((body, [rowNum, claim, visibility]) =>+ upsertFactRow(body, { rowNum, claim, kind: 'fact', visibility, confidence: 1, notability: 'medium', source: 'fixture' }).body, '');++beforeAll(async () => {+ configureGateway({ ...config, env: {} });+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+}, 120_000);+afterAll(async () => {+ await disposePersistenceConsumer(engine); await engine.disconnect(); resetGateway(); rmSync(home, { recursive: true, force: true });+});++/** A page split the way a writer before this release left it: the original fence below the sentinel, a second one added above it. */+async function splitPage(sourceId: string, slug: string, below: Array<[number, string, 'world' | 'private']>, above: Array<[number, string, 'world' | 'private']>) {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [sourceId]);+ await engine.putPage(slug, { type: 'person', title: 'Example', compiled_truth: `${biography}\n\n${fence(above)}`,+ timeline: `${history}\n\n${fence(below)}`, frontmatter: { private_metadata: 'kept' } }, { sourceId });+ const ids = (await engine.insertFacts([...below, ...above].map(([row_num, fact, visibility]) => ({ fact, entity_slug: slug, source_markdown_slug: slug, row_num,+ kind: 'fact' as const, visibility, source: 'fixture', confidence: 1 })), { source_id: sourceId })).ids;+ await registerLocalWriter(engine, 'cli');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return ids;+}+const facts = (sourceId: string, slug: string) => engine.executeRaw<{ id: number; fact: string; row_num: number; expired: boolean }>(+ 'SELECT id,fact,row_num,expired_at IS NOT NULL AS expired FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY row_num', [sourceId, slug]);++describe('gbrain repair split-facts', () => {+ test('merges the split fences below the sentinel, keeping row numbers and fact ids; a collision page is listed and kept', () => withEnv({ GBRAIN_HOME: home }, async () => {+ const sourceId = `split-${randomUUID().slice(0, 8)}`;+ const slug = 'people/split-example', clash = 'people/clash-example';+ const ids = await splitPage(sourceId, slug, [[7, 'Private historical preference', 'private']], [[8, 'Prefers asynchronous weekly reports', 'world']]);+ await splitPage(sourceId, clash, [[1, 'Original row one', 'world']], [[1, 'Colliding row one', 'world']]);+ const clashBefore = (await engine.readPageSnapshot(clash, { sourceId }))!;++ // Detection: extract_facts names the repair instead of reconciling a split page.+ const extracted = await runExtractFacts(engine, { slugs: [slug], sourceId });+ expect(extracted.warnings.join('\n')).toContain(`gbrain repair split-facts --source ${sourceId}`);++ // Explicit-only: never in --all, the remediation plan or the maintenance cycle.+ expect(AUTO_REPAIR_REGISTRY.map(spec => spec.kind)).not.toContain('split-facts');+ const scope = await resolveRepairScope(engine, sourceId);+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('split-facts', scope, { explicit: true, sourceFlag: sourceId });+ expect(preview.affected).toBe(1);+ expect(preview.residuals).toEqual({ row_collision: 1 });+ expect(preview.listing?.find(entry => entry.item.includes(clash))?.detail).toContain('rows 1 are numbered in both fences');+ // A preview writes nothing.+ expect((await engine.readPageSnapshot(slug, { sourceId }))!.page.compiled_truth).toContain(FACTS_FENCE_BEGIN);++ const expect_ = preview.apply_command.split('--expect ')[1];+ const applied = await (await repairRunner(engine, { apply: true, logger })).run('split-facts', scope, { explicit: true, sourceFlag: sourceId, expect: expect_ });+ expect(applied.applied).toBe(1);+ const after = (await engine.readPageSnapshot(slug, { sourceId }))!;+ expect(after.page.compiled_truth).toBe(biography);+ expect(after.page.timeline).toContain(history);+ expect(parseFactsFence(after.page.timeline ?? '').facts.map(row => [row.rowNum, row.claim, row.visibility])).toEqual([+ [7, 'Private historical preference', 'private'], [8, 'Prefers asynchronous weekly reports', 'world']]);+ expect(after.page.frontmatter.private_metadata).toBe('kept');+ expect((await facts(sourceId, slug)).map(row => [Number(row.id), Number(row.row_num), row.expired])).toEqual([[ids[0], 7, false], [ids[1], 8, false]]);+ // The merged page is a lone timeline fence, which extract_facts now reconciles in place.+ expect((await runExtractFacts(engine, { slugs: [slug], sourceId })).warnings).toEqual([]);+ expect((await facts(sourceId, slug)).map(row => Number(row.id))).toEqual(ids);++ // The collision page is untouched.+ expect((await engine.readPageSnapshot(clash, { sourceId }))!.revision).toBe(clashBefore.revision);++ // The hash approved one set: applying it again merges nothing, and a stale hash refuses.+ const fresh = await (await repairRunner(engine, { apply: false, logger })).run('split-facts', scope, { explicit: true, sourceFlag: sourceId });+ expect(fresh.affected).toBe(0);+ await expect((await repairRunner(engine, { apply: true, logger })).run('split-facts', scope, { explicit: true, sourceFlag: sourceId, expect: expect_ }))+ .rejects.toMatchObject({ code: 'preview_changed' });+ }), 120_000);+});++describe('mergeSplitFacts', () => {+ const page = (compiled_truth: string, timeline: string) => ({ slug: 'people/x', type: 'person', title: 'X', frontmatter: {}, compiled_truth, timeline }) as never;+ test('keeps a ## Facts heading that holds more than the fence, and the prose under it', () => {+ const body = `Bio.\n\n## Facts\n\nA note people wrote.\n\n${fence([[2, 'Above', 'world']]).replace('## Facts\n\n', '')}\n\n## Later\n\nMore prose.`;+ const merged = mergeSplitFacts(page(body, `${history}\n\n${fence([[1, 'Below', 'world']])}`), []) as { compiled_truth: string; timeline: string };+ expect(merged.compiled_truth).toBe('Bio.\n\n## Facts\n\nA note people wrote.\n\n## Later\n\nMore prose.');+ expect(parseFactsFence(merged.timeline).facts.map(row => row.claim)).toEqual(['Below', 'Above']);+ });+ test('a page with one fence is not split', () => {+ expect(mergeSplitFacts(page('Bio.', `${history}\n\n${fence([[1, 'Below', 'world']])}`), [])).toBeNull();+ expect(mergeSplitFacts(page(`Bio.\n\n${fence([[1, 'Above', 'world']])}`, history), [])).toBeNull();+ });+});