Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(repair): pull_blocked_local_changes and gbrain repair url-clone-fences (GBRA-130 C-2, #6946)

garrytan257144735ece
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 60850de65a..0037695aee 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -296,6 +296,7 @@ or a physical projection that leaves attribution untouched):
- `src/core/repair/stale-atoms.ts` (3): a request on managed brains; the unmanaged retirement runs in `maintenanceTransaction`.
- `src/core/repair/take-supersession.ts` (1): `gbrain repair take-supersession` reprojection: a receipted `managed_maintenance_take_reproject` request on managed brains, `maintenanceTransaction` on unmanaged ones; fence edits go through a revision-bound `put_page`.
- `src/core/repair/timeline-comments.ts` (1): `gbrain repair timeline-comments` row cleanup: `withCoordinatedWrite` under the page key on managed brains, `maintenanceTransaction` otherwise.
+- `src/core/repair/url-clone-fences.ts` (2): `gbrain repair url-clone-fences` (#6946), unmanaged brains only (a managed brain previews nothing); keeping the appended fence rows database-only (clearing `row_num`, inserting a row the database lost) runs in one `maintenanceTransaction` under the page lock after the preview recheck; HEAD's bytes then import through `importFromContent`.
- `src/core/schema-pack/page-to-alias.ts` (1): the page-to-alias conversion soft-deletes each converted page in `maintenanceTransaction`.
- `src/core/schema-pack/page-to-link.ts` (1): the page-to-link conversion soft-deletes each converted page in `maintenanceTransaction`.
- `src/core/schema-pack/retype.ts` (1): each bounded retype batch runs in `maintenanceTransaction`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 4505c2e33a..65dc1ed80e 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2748,6 +2748,16 @@ More: [docs/guides/repair.md#projection-owner-resident](../../docs/guides/repair
|---|---|---|---|---|---|---|
| The catalog adoption is accepted but not fully committed. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |
+### pull_blocked_local_changes
+
+<a id="pull_blocked_local_changes"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A clone gbrain owns (sources add --url) has local changes in its checkout, so git pull --ff-only cannot fast-forward it and every sync of the source stops at the pull. | Older gbrain releases appended ## Facts fence rows to clone files on unmanaged brains (#6946); a local change to a file the upstream also changed blocks every fast-forward. Current releases keep facts about a clone database-only. | Ask the user, then preview the repair: gbrain repair url-clone-fences --source <id>. It proves which files differ from HEAD only by gbrain fence rows and restores those after keeping their facts database-only; a file with any other edit is named and left for the user. | user | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/repair.md#url-clone-fences](../../docs/guides/repair.md#url-clone-fences)
+
### purge_blocked_pending_recovery
<a id="purge_blocked_pending_recovery"></a>
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 7406200baa..35a56699ac 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -150,6 +150,7 @@ work behind exits 0, so scripts should also check `results[].complete`.
| `rename-identity` | `rename_identity_downgrades` | Explicit-only, preview-bound, destructive consent. For an inexact Git rename that sync split into a delete plus an add (#6729): carries the old page's identity (id, version history, timeline, links, facts, aliases) onto the new slug, imports the new file onto it as an edit and retires the provisional page; or, with `--close`, settles the pair and moves nothing. `--slug <new-slug>` (and `--from <old-slug>`) names one pair; `--apply --expect <hash> --yes`. See [rename identity](#rename-identity). | `fact_rows_collide` (a fence row of the old page the new file does not keep with the same claim); `managed_remedy_unavailable` (a carry on a managed source; `--close` is the remedy there); pages changed after the preview (`changed_since_preview`). |
| `overwritten-edits` | `sync_overwritten_db_edits` | Explicit-only, preview-bound. Restores database edits that an incremental managed sync replaced with a committed file edit and no `file_drift` hold (#6712, fixed by #6887). It restores only what the records prove: a database-only revision (its receipt published no file) archived by a managed-sync import that wrote different content, with no later revision holding the edit again. The preview diffs the live page against the edit; `--apply --expect <hash>` reverts each page to that version through a revision-bound, database-only `revert_version` and holds the committed file `file_drift` when it differs. See [overwritten edits](#overwritten-edits). | `unknown_*` findings (no persistence outcome on the writer's receipt, the import's content no longer readable, a segmented version), listed but not restored; pages that moved after the preview (`changed_since_preview`). |
| `missing-tables` | `schema_missing_tables` | Explicit-only, preview-bound. Recreates, empty, a rebuildable cache table (`query_cache`, `code_traversal_cache`) that the applied migrations created but the brain no longer has, on a brain whose schema version already covers its creating migration, so `apply-migrations` never recreates it (#6911). DDL only (`IF NOT EXISTS`), no journal admission, brain-wide. See [missing tables](#missing-tables). | `user_data_tables`: a missing table that holds user data; this repair never recreates it, so restore its rows from a backup first. `other_tables`: a missing table that holds no user data; `gbrain init --migrate-only` recreates it if the base schema defines it. |
+| `url-clone-fences` | none (`gbrain sync --source <id>` stops at the pull with `pull_blocked_local_changes`) | Explicit-only, preview-bound, destructive consent. Clears the `## Facts` fence rows an older gbrain appended to files of a clone it owns (`gbrain sources add --url`), which block every `git pull --ff-only` that touches those files (#6946). The preview proves each changed file differs from HEAD only by appended fence rows; `--apply --expect <hash> --yes` backs each file up, keeps its rows database-only and restores the file from HEAD. Unmanaged brains only. See [URL clone fences](#url-clone-fences). | `non_fence_edit`, `unparsed_fence`, `staged_change`, `deleted`, `not_in_head`, `unreadable_checkout`: a file with any other difference from HEAD, named with why; files that changed after the preview (`changed_since_preview`). |
Timeline rows that an earlier version of a page produced and its current text
no longer has are removals, not history, so `timeline` neither counts nor
@@ -1448,6 +1449,49 @@ again), or when the merged page would not read back exactly
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="url-clone-fences"></a>
+### URL clone fences
+
+A source added with `gbrain sources add <id> --url <git-url>` is a clone gbrain
+owns and updates with `git pull --ff-only`. Before this release, `remember`,
+`extract_facts` and page writes on an unmanaged brain wrote `## Facts` fence
+rows and page files into that clone (#6946). The local change blocks every pull
+that touches the same file, so the clone stops following upstream. Current
+releases keep those writes database-only: a fact about a clone page is stored
+and recalled from the database with no fence row (`row_num` empty), and page
+write-through reports `skipped: "url_clone"`. A managed brain does the same
+with `gbrain sources mirror-readonly <id>`.
+
+A clone an older release already dirtied still blocks its pulls. `gbrain sync
+--source <id>` then prints `pull_blocked_local_changes` with the changed files
+and an `ask_user` fix naming this repair (the sync JSON `reason` stays
+`pull_failed`; the cycle's sync phase carries the code in `pull_blocked`).
+
+**Say to your agent:** *"Preview which files of the clone gbrain changed, show
+me the list, then restore them after I agree."*
+
+```bash
+gbrain repair url-clone-fences --source <id> # preview: fence_rows_only / refused classes
+gbrain repair url-clone-fences --source <id> --apply --expect <hash> --yes # restores exactly the previewed files
+gbrain sync --source <id> # pulls again
+```
+
+The preview lists every tracked file that differs from HEAD and proves the
+difference is only fence rows gbrain appended: both fences parse, HEAD's rows
+are an unchanged prefix of the working copy's, and re-rendering HEAD with the
+working fence reproduces the file byte for byte. Any other difference is
+named with its class (`non_fence_edit`, `unparsed_fence`, `staged_change`,
+`deleted`, `not_in_head`, `unreadable_checkout`) and the file is left alone; resolve it in the clone (keep
+the edit upstream, or discard it with `git checkout -- <path>`), then preview
+again. Each restored file is first backed up under
+`~/.gbrain/backups/url-clone-fences/`. Its rows stay active and recallable as
+database-only facts, HEAD's bytes are imported as the page (as sync would
+import them), and only then is the file restored; each step is idempotent, so
+a stopped run previews the same file again. A file that changed since the preview
+reports `changed_since_preview` and is kept. Undo by copying the backup over
+the file. It is explicit-only and never runs from `--all`, doctor's
+remediation plan, the maintenance cycle or an upgrade.
+
<a id="file-drift"></a>
### File drift
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index ebfcfd6f82..a660ccec2a 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -13,7 +13,7 @@ src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line
src/commands/serve-http.ts 937 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts)
src/core/ai/gateway.ts 4523 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text
src/commands/sync.ts 546 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone)
-src/core/cycle.ts 3328 ratchet +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts)
+src/core/cycle.ts 3330 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts)
src/core/cycle/synthesize.ts 3230 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites)
src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count
src/core/engine.ts 2832 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 9a8b4639f4..fade9b254a 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -74,6 +74,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i
gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]
[--keep prior|disk --apply --expect <preview-hash> --yes] [--json]
gbrain repair ghost-pages --source <id> [--apply --expect <preview-hash> --yes] [--json]
+ gbrain repair url-clone-fences [--source <id>] [--apply --expect <preview-hash> --yes] [--json]
gbrain repair rename-identity --source <id> [--slug <new-slug> [--from <old-slug>] [--close]
[--apply --expect <preview-hash> --yes]] [--json]
${REPAIR_CONTENT_HELP}
@@ -123,7 +124,7 @@ Options:
stuck-recovery --apply: the version of each blocked file to keep (the user's choice from the preview).
--request-id <uuid>
stuck-recovery: resolve only this request's recovery (default: every blocked record of the source).
- --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, rename-identity --apply: the user agreed to the previewed changes (destructive
+ --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, rename-identity, url-clone-fences --apply: the user agreed to the previewed changes (destructive
consent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).
--json Machine-readable output with a stable shape (frontmatter: every per-file diff).
@@ -135,13 +136,14 @@ Held files (the content lane, then the two-pass frontmatter repair): docs/guides
Malformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fences.
A write recovery blocked on unexpected_file_bytes: docs/guides/repair.md#stuck-recovery.
Live pages whose canonical file is missing (ghost pages): docs/guides/repair.md#ghost-pages.
+A sources add --url clone whose pull stops at pull_blocked_local_changes: docs/guides/repair.md#url-clone-fences.
Renames whose identity sync did not keep (rename-identity): docs/guides/live-sync.md#renaming-a-page.`;
const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force', '--close']);
const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from']);
/** Flags only some kinds accept, with the kinds that do. */
const KIND_FLAGS: Record<string, readonly string[]> = {
- '--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'rename-identity'],
+ '--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'rename-identity', 'url-clone-fences'],
'--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],
'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],
diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.ts
index ac4864f927..7a52cafe58 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -52,6 +52,7 @@ import { performFullSync } from './full.ts';
import { applyHoldsToManifest, planHoldRescreen, wouldHoldFields, type LegacyHolds } from './holds.ts';
import { sweepOrphanedRenameSentinels } from './rename-reconcile.ts';
import type { SyncPlan, SyncActivePack } from './sync-run.ts';
+import { formatUrlClonePullBlock, urlClonePullBlock } from '../../core/url-clone.ts';
export type PreflightOutcome = { readonly done: SyncResult } | { readonly plan: SyncPlan };
@@ -636,6 +637,9 @@ async function pullAndResolveHead(
} else {
serr(`Warning: git pull failed: ${msg.slice(0, 200)}`); // #1315 stderr-first
}
+ // #6946: an owned clone's own checkout blocks it; name the files and the preview-first repair.
+ const block = opts.sourceId ? await urlClonePullBlock(engine, opts.sourceId) : null;
+ if (block) serr(formatUrlClonePullBlock(block));
} finally {
shutdown.release();
}
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 30a99ef137..ace88d5cd6 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -59,7 +59,7 @@ import { assertValidSourceId } from './source-id.ts';
import { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';
import { acquireLeaseSet, maintenanceLockBusySkip, MAINTENANCE_LEASE_ID } from './cycle/lock-set.ts';
import { assertEmbedNotStalled } from './embed-stall.ts'; import { embedBackfillFix } from './embed-consent.ts';
-import { anyAbortSignal } from './abort-signals.ts';
+import { anyAbortSignal } from './abort-signals.ts'; import { urlClonePullBlock, urlClonePullBlockSummary } from './url-clone.ts';
import { maybeRefreshPlannerStats } from './planner-stats.ts'; import { listSourceChangedPages, sourceCycleWindowStamp, unionSlugSets, type SourceCycleWindow } from './cycle/source-window.ts';
export { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';
@@ -1303,6 +1303,7 @@ async function runPhaseSync(
// doesn't report a clean run over a wedged source. Timeout-class partials
// keep the pre-existing 'ok' mapping (they converge on retry by design).
const pullFailedPartial = result.status === 'partial' && result.reason === 'pull_failed';
+ const pullBlock = pullFailedPartial && sourceId ? await urlClonePullBlock(engine, sourceId) : null;
// Untracked-gap fix: uncommitted working-tree drift (files invisible to
// commit-driven sync) surfaces as 'warn', not a clean 'ok +0' — a nightly
// cycle over a dirty vault otherwise reports convergence it never achieved.
@@ -1321,7 +1322,7 @@ async function runPhaseSync(
duration_ms: 0,
summary: dryRun
? `${syncedCount} page(s) would sync, ${result.deleted} would delete`
- : pullFailedPartial
+ : pullBlock ? urlClonePullBlockSummary(pullBlock) : pullFailedPartial
? `git pull failed, nothing imported — source may be behind its remote (sync anchor unchanged)`
: `+${result.added} added, ~${result.modified} modified, -${result.deleted} deleted${uncommittedNote}${upstreamNote}`,
details: {
@@ -1335,6 +1336,7 @@ async function runPhaseSync(
syncStatus: result.status,
...(result.reason ? { syncReason: result.reason } : {}),
...(result.uncommitted ? { uncommitted: result.uncommitted } : {}),
+ ...(pullBlock ? { pull_blocked: { code: pullBlock.code, paths: pullBlock.paths, fix: pullBlock.fix } } : {}),
dryRun,
},
pagesAffected: result.pagesAffected,
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 56524e685b..971eac1cf9 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -475,6 +475,11 @@ export const CODES = {
projection_pending: { class: 'retryable', summary: "The current text projection is not ready." },
provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },
publication_pending: { class: 'retryable', summary: "The catalog adoption is accepted but not fully committed." },
+ pull_blocked_local_changes: { class: 'caller', retryable: false, actor: 'user',
+ summary: "A clone gbrain owns (sources add --url) has local changes in its checkout, so git pull --ff-only cannot fast-forward it and every sync of the source stops at the pull.",
+ why: 'Older gbrain releases appended ## Facts fence rows to clone files on unmanaged brains (#6946); a local change to a file the upstream also changed blocks every fast-forward. Current releases keep facts about a clone database-only.',
+ suggestion: 'Ask the user, then preview the repair: gbrain repair url-clone-fences --source <id>. It proves which files differ from HEAD only by gbrain fence rows and restores those after keeping their facts database-only; a file with any other edit is named and left for the user.',
+ docs: 'docs/guides/repair.md#url-clone-fences' },
purge_blocked_pending_recovery: { class: 'retryable', summary: "A purge was refused because a pending, running or recovering write still needs the content it would remove; nothing was purged.", why: "Purge redacts stored write intents and rewrites pages; doing that under an unfinished publication or recovery would lose or resurrect content.", suggestion: 'Wait for the named write to finish or recover (gbrain write-request <id>), then retry the purge with the same request id.', docs: 'docs/guides/memory-boundaries.md#purge' },
purge_lookup_timeout: { class: 'caller', retryable: false, actor: 'host_admin',
summary: "A page purge's in-transaction journal lookup hit the publication transaction's statement budget, so the purge failed terminally; nothing was removed, tombstoned or redacted, and later writes to the source move again.",
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 39825a76cf..0d1b32cd76 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -49,7 +49,7 @@ import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';
import { readFix } from '../ops/op-fix.ts';
import { ItemRun, type ItemFailure } from '../item-failure.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', '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', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', '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', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 62c7e76789..d360088397 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -71,6 +71,7 @@ import { aliasesRepair } from './aliases.ts';
import { renameIdentityRepair, RENAME_IDENTITY_CONSENT_TEXT } from './rename-identity.ts';
import { overwrittenEditsRepair } from './overwritten-edits.ts';
import { missingTablesRepair } from './missing-tables.ts';
+import { urlCloneFencesRepair } from './url-clone-fences.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
import type { OperationError } from '../ops/contract.ts';
@@ -382,6 +383,20 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'recreated. DDL only (IF NOT EXISTS), no journal admission. The preview prints a hash; --apply --expect <hash> recreates exactly that set. '
+ 'Runs only when named; never on upgrade. Brain-wide.',
},
+ 'url-clone-fences': {
+ handler: urlCloneFencesRepair, embeds: 'none', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',
+ consentText: {
+ what: 'Restore the previewed files of a clone gbrain owns from HEAD after keeping their gbrain fence rows database-only',
+ why: 'An older gbrain appended ## Facts fence rows to these clone files, and the local change blocks every git pull --ff-only that touches them; the preview proved each file differs from HEAD by those rows alone.',
+ risk: 'Each file is backed up under ~/.gbrain/backups/url-clone-fences/ before it changes, and its fact rows stay active and recallable in the database. A file that changed since the preview is skipped. Copy the backup back to undo.',
+ user_message: 'Restore the previewed clone files from the last pulled commit? Their facts stay in the database and each file is backed up first',
+ },
+ summary: 'Clear the local changes an older gbrain left in a clone it owns (sources add --url), which make every sync stop at the pull with '
+ + 'pull_blocked_local_changes (#6946). The preview lists each tracked file that differs from HEAD and proves the difference is only ## Facts fence '
+ + 'rows gbrain appended; any other difference (a user edit, a staged change, a deleted file) is named and left untouched. --apply --expect <hash> --yes, '
+ + 'per previewed file: back it up, keep its appended rows database-only in one transaction, import HEAD\'s bytes as the page, then restore the file '
+ + 'from HEAD. Unmanaged brains only (a managed brain uses gbrain sources mirror-readonly). Runs only when named.',
+ },
};
export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));
diff --git a/src/core/repair/url-clone-fences.ts b/src/core/repair/url-clone-fences.ts
new file mode 100644
index 0000000000..0c3dbe3c85
--- /dev/null
+++ b/src/core/repair/url-clone-fences.ts
@@ -0,0 +1,204 @@
+/**
+ * `gbrain repair url-clone-fences` (#6946, GBRA-130 C-2): clear the local changes an
+ * older gbrain left in a clone it owns (`sources add --url`), which block every
+ * `git pull --ff-only` that touches the same file (`pull_blocked_local_changes`,
+ * url-clone.ts). Current releases never write into such a clone on an unmanaged
+ * brain; this kind exits the state the older fence writer left behind.
+ *
+ * The preview lists every tracked file of each owned clone in scope that differs
+ * from HEAD and proves, per file, that the difference is only `## Facts` fence
+ * rows gbrain appended: both sides' fences parse, HEAD's rows are an unchanged
+ * prefix of the working copy's, and re-rendering HEAD's bytes with the working
+ * fence reproduces the working copy byte for byte. Any other difference (a user
+ * edit, a struck or changed row, a staged change, a deleted file) refuses that
+ * file, names it in the preview with why, and leaves it untouched.
+ *
+ * Explicit-only, preview-bound and destructive: `--apply --expect <hash> --yes`
+ * applies exactly the previewed files. Per file, under the source filesystem
+ * lock and the page lock, the apply rechecks the file and HEAD against the
+ * preview (`changed_since_preview` otherwise), backs the working copy up under
+ * ~/.gbrain/backups/url-clone-fences/, keeps the appended rows database-only in
+ * one transaction (`row_num` and `source_markdown_slug` cleared, the shape every
+ * database-only fact has; a fence row the database lost is inserted
+ * database-only), imports HEAD's bytes as the page (the canonical import, as
+ * sync would), and only then restores the file from HEAD. Each step is
+ * idempotent, so a run stopped between them previews the same file again. Facts stay active and recallable. To
+ * undo, copy the backup over the file. Unmanaged brains only.
+ */
+import { createHash } from 'node:crypto';
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { execFileSync } from '../spawn.ts';
+import { gitChildEnv } from '../git-env.ts';
+import { gbrainPath } from '../config.ts';
+import { atomicWriteFileSync } from '../atomic-write.ts';
+import { createFrontmatterBackup, makeFrontmatterBackupRunId } from '../brain-writer.ts';
+import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, type ParsedFact } from '../facts-fence.ts';
+import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';
+import { importFromContent } from '../import-file.ts';
+import { assertSourceFilesystemActive, withSourceFilesystemLock } from '../minions/source-filesystem.ts';
+import { OperationError } from '../ops/contract.ts';
+import { withPageLock } from '../page-lock.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { clearApprovedSet, loadApprovedSet, previewHash, saveApprovedSet, type ApprovedSetKey } from '../persistence/preview-approval.ts';
+import { resolveSlugForPath } from '../sync.ts';
+import { isOwnedClone, trackedChanges, urlCloneReadOnly, urlCloneRepairPreviewArgv } from '../url-clone.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan } from './core.ts';
+
+const DOCS = 'docs/guides/repair.md#url-clone-fences';
+/** preview-approval's command union predates this kind; the store keys on the string alone. */
+const APPROVAL = { command: 'url-clone-fences' as ApprovedSetKey['command'] };
+
+/** One previewed file whose difference from HEAD is only appended fence rows. */
+interface ClonedFile { source_id: string; root: string; path: string; slug: string; head_sha256: string; work_sha256: string; rows: number[] }
+type FileItem = RepairItem & { file: ClonedFile; hash?: string; last?: boolean };
+
+const sha256 = (text: string) => createHash('sha256').update(text).digest('hex');
+const preview = (sourceId: string | undefined) => sourceId ? urlCloneRepairPreviewArgv(sourceId).join(' ') : 'gbrain repair url-clone-fences';
+
+function git(root: string, args: string[]): string {
+ return execFileSync('git', ['-C', root, ...args], { env: gitChildEnv(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 }) as string;
+}
+
+/** HEAD's bytes of a root-relative path; null when HEAD has no such file. */
+function headBytes(root: string, path: string): string | null {
+ try { return git(root, ['show', `HEAD:${path}`]); } catch { return null; }
+}
+
+type Proof = { ok: true; added: ParsedFact[] } | { ok: false; class: string; reason: string };
+
+/** Whether `work` is `head` with fence rows appended and nothing else (see the module header). */
+export function proveFenceRowsOnly(head: string | null, work: string | null): Proof {
+ if (work === null) return { ok: false, class: 'deleted', reason: 'the file is deleted in the checkout' };
+ if (head === null) return { ok: false, class: 'not_in_head', reason: 'HEAD has no such file' };
+ const before = parseFactsFence(head);
+ const after = parseFactsFence(work);
+ if (before.warnings.length || after.warnings.length) return { ok: false, class: 'unparsed_fence', reason: 'a facts fence does not parse cleanly' };
+ const prefix = before.facts.length < after.facts.length && before.facts.every((row, i) => JSON.stringify(row) === JSON.stringify(after.facts[i]));
+ if (!prefix || replaceOrInsertFactsFence(head, renderFactsTable(after.facts)) !== work) {
+ return { ok: false, class: 'non_fence_edit', reason: 'the file differs from HEAD by more than appended fence rows' };
+ }
+ return { ok: true, added: after.facts.slice(before.facts.length) };
+}
+
+async function pageSlug(engine: BrainEngine, sourceId: string, path: string): Promise<string> {
+ const [row] = await engine.executeRaw<{ slug: string }>(
+ 'SELECT slug FROM pages WHERE source_id = $1 AND source_path = $2 AND deleted_at IS NULL ORDER BY id LIMIT 1', [sourceId, path]);
+ return row?.slug ?? resolveSlugForPath(path);
+}
+
+/** Every changed file of every owned clone in scope, proven or refused. */
+async function survey(engine: BrainEngine, sourceIds: string[]): Promise<{ files: ClonedFile[]; listing: RepairListing[] }> {
+ const files: ClonedFile[] = [];
+ const listing: RepairListing[] = [];
+ const sources = await engine.executeRaw<{ id: string; local_path: string | null; config: unknown }>(
+ 'SELECT id, local_path, config FROM sources WHERE id = ANY($1::text[]) ORDER BY id', [sourceIds]);
+ for (const source of sources) {
+ if (!source.local_path || !isOwnedClone(source) || !existsSync(source.local_path)) continue;
+ const root = source.local_path;
+ let paths: string[];
+ let staged: Set<string>;
+ try {
+ paths = trackedChanges(root);
+ staged = new Set(git(root, ['diff', '--cached', '--name-only', '-z', 'HEAD', '--']).split('\0').filter(Boolean));
+ } catch (error) {
+ listing.push({ item: `${source.id}:.`, class: 'unreadable_checkout', detail: `git cannot read the checkout (${(error as Error).message.split('\n')[0]}); fix the checkout, then preview again: ${preview(source.id)}` });
+ continue;
+ }
+ for (const path of paths) {
+ const item = `${source.id}:${path}`;
+ const work = existsSync(join(root, path)) ? readFileSync(join(root, path), 'utf8') : null;
+ const head = headBytes(root, path);
+ const proof: Proof = staged.has(path) ? { ok: false, class: 'staged_change', reason: 'the file has a staged change, which gbrain never makes' } : proveFenceRowsOnly(head, work);
+ if (!proof.ok) {
+ listing.push({ item, class: proof.class, detail: `${proof.reason}, so it is left as it is. Keep or remove that change yourself (git -C ${root} diff HEAD -- ${path} shows it), then preview again: ${preview(source.id)}` });
+ continue;
+ }
+ const slug = await pageSlug(engine, source.id, path);
+ files.push({ source_id: source.id, root, path, slug, head_sha256: sha256(head!), work_sha256: sha256(work!), rows: proof.added.map(row => row.rowNum) });
+ listing.push({ item, class: 'fence_rows_only', detail: `${proof.added.length} fence row(s) gbrain appended to ${slug}: kept database-only, then the file is restored from HEAD` });
+ }
+ }
+ return { files, listing };
+}
+
+const toItem = (file: ClonedFile, index: number, hash?: string, last?: boolean): FileItem => ({ cursor: { phase: 0, id: index + 1 }, source_id: file.source_id,
+ slug: file.slug, chars: 0, action: 'restore_from_head', file, ...(hash ? { hash, last } : {}) });
+
+/** One transaction: the appended rows become database-only rows (a row the database lost is inserted database-only). */
+async function keepRowsDatabaseOnly(engine: BrainEngine, file: ClonedFile, added: ParsedFact[]): Promise<{ moved: number; inserted: number }> {
+ return maintenanceTransaction(engine, async tx => {
+ let moved = 0;
+ let inserted = 0;
+ for (const row of added) {
+ const updated = await tx.executeRaw<{ id: number }>(
+ 'UPDATE facts SET row_num = NULL, source_markdown_slug = NULL WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num = $3 RETURNING id',
+ [file.source_id, file.slug, row.rowNum]);
+ moved += updated.length;
+ if (updated.length) continue;
+ const kept = await tx.executeRaw<{ id: number }>(
+ 'SELECT id FROM facts WHERE source_id = $1 AND entity_slug = $2 AND row_num IS NULL AND fact = $3 LIMIT 1', [file.source_id, file.slug, row.claim]);
+ if (kept.length) continue;
+ const { row_num: _row, source_markdown_slug: _slug, superseded_by_row: _superseded, ...fact } = extractFactsFromFenceText([row], file.slug, file.source_id)[0]!;
+ await tx.insertFact(fact, { source_id: file.source_id }); // gbrain-allow-direct-insert: url-clone-fences keeps a fence row the database lost as a database-only row before its file is restored
+ inserted++;
+ }
+ return { moved, inserted };
+ });
+}
+
+async function restoreFile(engine: BrainEngine, file: ClonedFile, runId: string): Promise<RepairItemOutcome> {
+ if (!await urlCloneReadOnly(engine, file.source_id)) return { applied: false, outcome: 'refused', reason: 'not_url_clone', detail: { path: file.path } };
+ const abs = join(file.root, file.path);
+ const head = headBytes(file.root, file.path);
+ const work = existsSync(abs) ? readFileSync(abs, 'utf8') : null;
+ const proof = proveFenceRowsOnly(head, work);
+ if (!proof.ok || sha256(head!) !== file.head_sha256 || sha256(work!) !== file.work_sha256) {
+ return { applied: false, outcome: 'changed_since_preview', detail: { path: file.path } };
+ }
+ const backup = createFrontmatterBackup(abs, { sourcePath: file.root, backupRoot: gbrainPath('backups', 'url-clone-fences', runId) });
+ const { moved, inserted } = await keepRowsDatabaseOnly(engine, file, proof.added);
+ await importFromContent(engine, file.slug, head!, { sourceId: file.source_id, sourcePath: file.path, sourceRoot: file.root, noEmbed: true });
+ assertSourceFilesystemActive();
+ atomicWriteFileSync(abs, head!);
+ return { applied: true, outcome: 'restored', detail: { path: file.path, slug: file.slug, backup, rows_moved: moved, rows_inserted: inserted } };
+}
+
+export const urlCloneFencesRepair: RepairHandler = {
+ kind: 'url-clone-fences',
+ publication: 'projection',
+ embeds: false,
+ async plan(engine, scope, after, opts = { apply: false }): Promise<RepairPlan> {
+ const source = scope.source_ids.length === 1 ? scope.source_ids[0] : undefined;
+ if (await managedPersistenceEnabled(engine)) {
+ return { items: [], residuals: {}, warnings: ['This brain is managed: gbrain repair url-clone-fences applies to unmanaged brains. On a managed brain, gbrain sources mirror-readonly <id> keeps a clone\'s checkout unwritten.'] };
+ }
+ if (opts.apply) {
+ if (!opts.expect) throw new OperationError('invalid_params', 'gbrain repair url-clone-fences --apply needs the preview hash.',
+ `Preview first: ${preview(source)} — then run the apply command it prints (--apply --expect <preview-hash> --yes).`, DOCS);
+ const { items: files } = await loadApprovedSet<ClonedFile>(engine, { ...APPROVAL, hash: opts.expect, previewCommand: preview(source) });
+ const items = files.map((file, index) => toItem(file, index, opts.expect, index === files.length - 1)).filter(item => afterCursor(item.cursor, after));
+ if (!items.length) await clearApprovedSet(engine, { ...APPROVAL, hash: opts.expect });
+ return { items, preview_hash: opts.expect, residuals: {} };
+ }
+ const { files, listing } = await survey(engine, scope.source_ids);
+ const residuals: Record<string, number> = {};
+ for (const entry of listing) if (entry.class !== 'fence_rows_only') residuals[entry.class] = (residuals[entry.class] ?? 0) + 1;
+ const hash = previewHash({ kind: 'url-clone-fences-v1', brain_id: scope.brain_id, files: files.map(f => [f.source_id, f.path, f.head_sha256, f.work_sha256, f.rows]) });
+ if (files.length) await saveApprovedSet<ClonedFile>(engine, { ...APPROVAL, hash }, files);
+ return { items: files.map((file, index) => toItem(file, index)), residuals, listing, ...(files.length ? { preview_hash: hash } : {}), details: { listing } };
+ },
+ async apply(ctx, entry, opts) {
+ const item = entry as FileItem;
+ const { file } = item;
+ const outcome = await withSourceFilesystemLock(ctx.engine, file.root,
+ () => withPageLock(file.slug, () => restoreFile(ctx.engine, file, opts?.runId ?? makeFrontmatterBackupRunId()), { timeoutMs: 5_000 }));
+ if (item.last && item.hash) await clearApprovedSet(ctx.engine, { ...APPROVAL, hash: item.hash });
+ return outcome;
+ },
+ render(details) {
+ return ((details as { listing?: RepairListing[] }).listing ?? []).map(entry => ` ${entry.class}: ${entry.item}: ${entry.detail ?? ''}`);
+ },
+};
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index cdf6030c35..d797b227c0 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -197,7 +197,8 @@ for (const backend of testBackends()) {
'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',
frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',
'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',
- 'overwritten-edits': 'gbrain repair overwritten-edits', 'missing-tables': 'gbrain repair missing-tables' };
+ 'overwritten-edits': 'gbrain repair overwritten-edits', 'missing-tables': 'gbrain repair missing-tables',
+ 'url-clone-fences': 'gbrain repair url-clone-fences' };
// The post-upgrade banner names both findings with the kind's read-only preview.
const banner = await postUpgradeRecoveryBanner(engine, 'host');
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index 9e94276321..95f7c72ef8 100644
--- a/test/repair-explicit-only.test.ts
+++ b/test/repair-explicit-only.test.ts
@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { withEnv } from './helpers/with-env.ts';
-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'];
+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables', 'url-clone-fences'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));