Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
G8a git-canonical: gbrain sources canonical <id> --to git|mixed
garrytanff2799da461b
diff --git a/docs/designs/GIT_CANONICAL_MEMORY.md b/docs/designs/GIT_CANONICAL_MEMORY.mdindex 05cffa11a0..7a44c25b23 100644--- a/docs/designs/GIT_CANONICAL_MEMORY.md+++ b/docs/designs/GIT_CANONICAL_MEMORY.md@@ -72,7 +72,20 @@ A write from a remote MCP caller or a thin client becomes a journal request that## Conversion-A source changes mode only through a preview-bound verb. The preview is the [git-gap census](#the-git-gap-census): every page whose row differs from its committed blob, every page with no file that is not in a declared class, held items and parked effects, by category. The operator chooses per category to commit the database content through the door, declare it, or let git win. The preview lists any database content that git-wins would discard, and the apply binds to that preview. A source can return to its previous mode.+A source changes mode only through a preview-bound verb. The preview is the [git-gap census](#the-git-gap-census): every page whose row differs from its committed blob, every page with no file that is not in a declared class, held items and parked effects, by category. The preview lists any database content that git-wins would discard, and the apply binds to that preview. A source can return to its previous mode.++G8a ships it as `gbrain sources canonical <source-id> --to git|mixed [--dry-run | --apply --expect <hash>] [--json]`: trusted local CLI on a managed brain only, never an MCP operation. `--dry-run` (the default) writes nothing and puts every live page in one category, with counts, a capped path sample and the preview hash (HEAD, the source incarnation and every planned item with its revision):++| Category | What the apply does |+|---|---|+| adopt (`database_ahead`, `undeclared_database_only`, `worktree_only`) | Writes the page's export view to its file and commits it through the door, up to 200 pages per commit. The worktree writer lock is taken per group and dropped between groups. No row changes: the bytes read back `equal`, and the strict pass after them rewrites none of those rows. |+| declared | Nothing. A page under an ignored path is `git_ignored` and never gets a file or a Git effect. |+| git wins | The strict pass indexes the committed blob: Git moved and the database did not, Git deleted a page the database had not edited, a held deletion, or a held `file_drift` whose side is unknown. |+| holds | Cleared, so Git's verdict runs over them. |+| parked effects | Retried once, or, for targets Git ignores, the page is stamped `git_ignored` (declared) and the target stays parked as a record. |+| discard | Refused: `git_conversion_blocked` names each category (both sides moved, a both-sides drift hold, a database edit Git deleted, an uncommitted working-tree edit that differs from HEAD and the export, an ignored target, unparseable, unsafe path, segmented page, export mismatch, or a row a strict pass would overwrite unplanned). There is no override. |++`--apply --expect <hash>` re-plans and refuses `preview_changed` on any difference, adopts group by group (a crash leaves the source mixed and the rerun preview lists only what is left), clears the holds, settles the parked effects, runs the full strict-equivalent pass, then sets `canonical: git` in the transaction that records the conversion. Writes can land between that pass and the flag, so it runs one genuine strict pass and previews again: the conversion is complete only when nothing is left; otherwise it reports `git_conversion_incomplete` with what remains and the source stays strict, because Git wins. `--to mixed` removes the flag and changes nothing else; Git keeps every door commit.## The git-gap census@@ -104,6 +117,6 @@ The census also counts rows with no Git home, which G4 and G5 give a file form:| G5 | authored rows written by direct coordinated database writes get a file form || G6 | unmanaged writers routed through the door with batched commits || G7 | declared classes, large files, remote and hosted writes |-| G8 | conversion verb, retirement of the hold machinery for strict sources |+| G8 | conversion verb (G8a: `gbrain sources canonical`), retirement of the hold machinery for strict sources |Every wave is default-off and changes nothing for existing sources until a source is converted.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex af64295cb7..b87e94f2c7 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1669,6 +1669,28 @@ More: [docs/guides/repair.md#ghost-pages](../../docs/guides/repair.md#ghost-page|---|---|---|---|---|---|---|| The canonical root is not inside a Git checkout, so its Git effects have nothing to commit to. | Only the operator of the brain host can change what blocks this. | Initialize the root as a Git repository with a first commit and a remote on the brain host, then rerun; a database-only source needs no Git durability. | host_admin | `gbrain doctor --json` | 1 | no |+### git_conversion_blocked++<a id="git_conversion_blocked"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Converting a source to git-canonical would discard database content or cannot place it, so the apply wrote nothing. | gbrain sources canonical --to git applies only when every database row will be in Git or in a declared database-only class afterwards. The preview counts what would be lost or cannot be placed by category (detail lists them): both_moved and held_drift_both, a page Git and the database both changed; deleted_in_git, a page Git deleted that the database edited since; uncommitted_edit, a working-tree edit the adoption would overwrite; ignored_target, a page whose file Git ignores without a declared class; unparseable and unsafe_path, a committed file or path sync cannot read; segmented_page, a segmented page conversion does not adopt yet; export_mismatch, a page whose export does not read back equal; git_overwrites_database, a page version a strict pass would replace that nothing accepted. There is no override. | Relay the categories and their paths (the --dry-run preview lists them) and ask the user how each should be resolved; preview again afterwards. | user | `repeat the read that failed` | 1 | no |++Reasons: `both_moved`, `held_drift_both`, `deleted_in_git`, `uncommitted_edit`, `ignored_target`, `unparseable`, `unsafe_path`, `segmented_page`, `export_mismatch`, `git_overwrites_database`.++More: [docs/designs/GIT_CANONICAL_MEMORY.md#conversion](../../docs/designs/GIT_CANONICAL_MEMORY.md#conversion)++### git_conversion_incomplete++<a id="git_conversion_incomplete"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A git-canonical conversion stopped because its strict pass did not finish, or finished with work left after the flag was set. | The conversion runs a full strict-equivalent pass before it sets canonical: git, and one genuine strict pass after. A pass that ends partial, blocked or deferred stops the conversion where it is: before the flag the source stays as it was, after it the source stays strict (Git wins) and the plan lists what is left. | Wait until gbrain sync status --source <id> --json shows the source idle, then preview again with gbrain sources canonical <id> --to git --dry-run and apply the new hash. | agent | `repeat the read that failed` | 1 | yes |++More: [docs/designs/GIT_CANONICAL_MEMORY.md#conversion](../../docs/designs/GIT_CANONICAL_MEMORY.md#conversion)+### git_detached_head<a id="git_detached_head"></a>diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex db56f06c11..58782d4b8f 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -12,7 +12,7 @@ src/commands/extract.ts 2700 ratchet +8 GBRA-130 A-1: extract --stale --retry-hesrc/commands/jobs.ts 687 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes; +1 #7142: doctor-refresh handler registration (logic in doctor/last-known.ts); +20 #7242 jobs wait: subcommand row, import, usage lines and its --help text with the exit codes (logic in jobs/wait.ts)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 4533 ratchet +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +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; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts); +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved for-src/commands/sync.ts 550 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor engine; +2 #7167: SyncResult.writer interface field (a managed dry run reports the writer instead of waiting on it; the read lives in persistence/sync-dry-run-writer.ts)+src/commands/sync.ts 556 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor engine; +2 #7167: SyncResult.writer interface field (a managed dry run reports the writer instead of waiting on it; the read lives in persistence/sync-dry-run-writer.ts); +6 G8a git-canonical: SyncOpts.canonicalOverride interface field and its doc comment (internal: only the conversion apply in persistence/git-conversion.ts passes it; applied in persistence/sync-discovery.ts)src/core/cycle.ts 3338 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); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress; +1 GBRA-133: the extract phase passes the stale-drain budget to its targeted pass when sync gave no slug listsrc/core/cycle/synthesize.ts 3241 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); +2 GBRA-161 PR 4 (#7065): the synthesize phase activates each synthesized transcript's outputs as its generation (activateSynthesisGenerations import and call site; logic in cycle/synthesize-generations.ts); +8 GBRA-161 PR 5 (S-2): the dream summary publishes as a single-item dream_summary generation bound to its pre-run revision (publishSinglePage with a generation_fenced skip); +1 GBRA-60: a managed synthesis child carries dream_output (verify and stamp before put_page; cycle/synthesize-child-verify.ts)src/core/cycle/extract-atoms.ts 1658 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; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guard@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connesrc/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)-src/commands/sources.ts 2086 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured)+src/commands/sources.ts 2090 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts)src/core/link-extraction.ts 2424 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edgessrc/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshdiff --git a/src/commands/sources-canonical.ts b/src/commands/sources-canonical.tsnew file mode 100644index 0000000000..ecdbdc465e--- /dev/null+++ b/src/commands/sources-canonical.ts@@ -0,0 +1,93 @@+/**+ * `gbrain sources canonical <source-id> --to git|mixed` (git-canonical memory, G8a, docs/designs/GIT_CANONICAL_MEMORY.md#conversion):+ * the one verb that makes a source strict (`config.canonical = "git"`) or returns it to mixed. The default `--dry-run`+ * prints the plan, by category with counts and a capped sample of paths, and its hash; `--apply --expect <hash>` runs it+ * (persistence/git-conversion.ts). Trusted local CLI on a managed brain only; not an MCP operation, since it prints paths.+ */+import type { BrainEngine } from '../core/engine.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { OperationError, opError } from '../core/ops/contract.ts';+import { cliRenderContext, toAgentError } from '../core/agent-output.ts';+import { applyGitConversion, applyMixedConversion, assertConversionCaller, CONVERSION_GROUP_MAX, planGitConversion, planMixedConversion,+ type GitConversionPreview, type GitConversionResult, type MixedConversionPreview } from '../core/persistence/git-conversion.ts';++const USAGE = 'Usage: gbrain sources canonical <source-id> --to git|mixed [--dry-run | --apply --expect <hash> [--no-embed] [--no-extract]] [--json]';+const DOCS = 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion';++export function parseCanonicalArgs(args: string[]): { sourceId: string; to: 'git' | 'mixed'; apply: boolean; expect: string | null; json: boolean; noEmbed: boolean; noExtract: boolean } {+ const positional: string[] = [];+ let to: string | null = null, expect: string | null = null, apply = false;+ for (let i = 0; i < args.length; i++) {+ const arg = args[i]!;+ if (arg === '--to') { to = args[++i] ?? null; continue; }+ if (arg === '--expect') { expect = args[++i] ?? null; if (!expect) throw new OperationError('invalid_params', '--expect needs the preview hash.', USAGE); continue; }+ if (arg === '--apply') { apply = true; continue; }+ if (arg === '--dry-run' || arg === '--json' || arg === '--no-embed' || arg === '--no-extract') continue;+ if (arg.startsWith('-')) throw new OperationError('invalid_params', `Unknown sources canonical flag: ${arg}.`, USAGE);+ positional.push(arg);+ }+ if (positional.length !== 1) throw new OperationError('invalid_params', 'sources canonical needs exactly one source id.', USAGE);+ if (to !== 'git' && to !== 'mixed') throw new OperationError('invalid_params', `--to needs git or mixed; got ${to ?? 'nothing'}.`, USAGE);+ if (apply && args.includes('--dry-run')) throw new OperationError('invalid_params', '--apply and --dry-run exclude each other.', USAGE);+ if (apply && !expect) throw new OperationError('invalid_params', '--apply needs --expect <hash> from the --dry-run preview.', USAGE);+ return { sourceId: positional[0]!, to, apply, expect, json: args.includes('--json'), noEmbed: args.includes('--no-embed'), noExtract: args.includes('--no-extract') };+}++const counts = (record: Record<string, number>) => Object.entries(record).filter(([, n]) => n > 0).map(([k, n]) => `${k} ${n}`).join(', ') || 'none';+const sample = (paths: string[]) => paths.map(path => ` ${path}`);++export function describeGitPreview(p: GitConversionPreview): string {+ const lines = [`Source ${p.source_id}${p.strict ? ' (already git-canonical)' : ''} at ${p.head?.slice(0, 12) ?? 'no commit'}: ${p.pages} live page(s), ${p.equal} equal to HEAD.`,+ `Adopt (write the database's page to its file and commit it through the door, ${p.adopt.groups} commit(s) of up to ${CONVERSION_GROUP_MAX}): ${p.adopt.count} (${counts(p.adopt.by)}).`, ...sample(p.adopt.sample),+ `Declared database-only (nothing written, nothing deleted): ${p.declared.count} (${counts(p.declared.by)}).`,+ `Git wins (the strict pass indexes the committed file): ${p.git_wins.count} (${counts(p.git_wins.by)}).`, ...sample(p.git_wins.sample),+ `Holds cleared so Git's verdict runs: ${p.holds.count} (${counts(p.holds.by)}).`,+ `Parked effects: ${p.parked_effects.count} (retry ${p.parked_effects.retry}, reclassify as declared ${p.parked_effects.reclassify}; ${counts(p.parked_effects.by_code)}).`,+ `The strict pass also imports ${p.index.imports} and deletes ${p.index.deletes} page(s) where the database holds nothing Git lacks.`,+ `Database content that would be discarded: ${p.discard.count}${p.discard.count ? ` (${counts(p.discard.by)}); the apply refuses until it is 0` : ''}.`, ...sample(p.discard.sample)];+ lines.push(p.remaining === 0 && p.strict ? 'Nothing is left to convert.' : `Nothing changed. To apply: ${p.apply.join(' ')}`);+ return lines.join('\n');+}++function describeResult(r: GitConversionResult): string {+ const lines = [`Source ${r.source_id} ${r.status === 'converted' ? 'is git-canonical' : 'is git-canonical, with work left'}: ${r.committed.pages} page(s) committed in ${r.committed.groups} door commit(s), ${r.holds_cleared} hold(s) cleared, ${r.parked.retried} parked effect(s) retried and ${r.parked.reclassified} reclassified.`];+ if (r.status === 'incomplete') lines.push(describeGitPreview(r.after));+ return lines.join('\n');+}++function describeMixed(p: MixedConversionPreview): string {+ return p.strict ? `Source ${p.source_id} is git-canonical; --to mixed removes canonical: git and changes nothing else (Git keeps every door commit).\nNothing changed. To apply: ${p.apply.join(' ')}`+ : `Source ${p.source_id} is not git-canonical; there is nothing to change.`;+}++export async function runSourcesCanonical(engine: BrainEngine, args: string[]): Promise<void> {+ const json = args.includes('--json');+ if (args.includes('--help') || args.includes('-h')) { console.log(`${USAGE}\nPreview first: lists, by category, what converting the source to git-canonical (or back) does (${DOCS}).`); return; }+ const print = (value: unknown, text: string) => console.log(json ? JSON.stringify(value) : text);+ try {+ const parsed = parseCanonicalArgs(args);+ await assertConversionCaller(engine, parsed.sourceId);+ if (parsed.to === 'mixed') {+ if (!parsed.apply) { const { incarnation: _, ...preview } = await planMixedConversion(engine, parsed.sourceId); print(preview, describeMixed(preview)); return; }+ const done = await applyMixedConversion(engine, parsed.sourceId, parsed.expect!);+ print(done, done.status === 'mixed' ? `Source ${parsed.sourceId} is mixed: canonical: git removed.` : `Source ${parsed.sourceId} was not git-canonical; nothing changed.`);+ return;+ }+ if (!parsed.apply) { const { preview } = await planGitConversion(engine, parsed.sourceId); print(preview, describeGitPreview(preview)); return; }+ const result = await applyGitConversion(engine, parsed.sourceId, parsed.expect!, { noEmbed: parsed.noEmbed, noExtract: parsed.noExtract });+ if (result.status === 'incomplete') {+ const error = opError('git_conversion_incomplete', `Source ${parsed.sourceId} is git-canonical, and ${result.after.remaining} item(s) were still open after its strict pass.`,+ `Writes landed during the conversion. Git wins on the source now; preview again with gbrain sources canonical ${parsed.sourceId} --to git --dry-run and apply the new hash.`,+ { docs: DOCS, detail: 'work_left' });+ print({ status: 'incomplete', result, ...toAgentError(error, { transport: 'cli', command: 'sources canonical', render: cliRenderContext() }) }, describeResult(result));+ setCliExitVerdict(1);+ return;+ }+ print(result, describeResult(result));+ } catch (error) {+ if (!(error instanceof OperationError)) throw error;+ const env = toAgentError(error, { transport: 'cli', command: 'sources canonical', render: cliRenderContext() });+ console.log(json ? JSON.stringify({ status: 'refused', ...env }) : `Conversion refused (${error.code}): ${error.message}\nFix: ${error.suggestion ?? USAGE}`);+ setCliExitVerdict(1);+ }+}diff --git a/src/commands/sources-git-gap.ts b/src/commands/sources-git-gap.tsindex ef15748fdc..e6fdbb5980 100644--- a/src/commands/sources-git-gap.ts+++ b/src/commands/sources-git-gap.ts@@ -38,6 +38,10 @@ export type PageState = typeof PAGE_STATES[number];export const WORKTREE_STATES = ['clean', 'modified', 'deleted', 'untracked', 'absent'] as const;export type WorktreeState = typeof WORKTREE_STATES[number];+/** One page as the census classified it, handed to a caller that plans per page (G8 conversion, persistence/git-conversion.ts). */+export interface GitGapPage { id: string; slug: string; revision: string | null; path: string | null; state: PageState; segmented: boolean;+ declared?: DeclaredClass; worktree?: WorktreeState; headBlob?: string; databaseAlsoMoved?: boolean }+export interface GitGapSample { slug: string; path: string; state: PageState; fields?: string[]; declared?: DeclaredClass; basis?: 'import_record' | 'no_import_record'; worktree?: WorktreeState }export interface GitGapCensus {@@ -117,7 +121,7 @@ interface Checkout { root: string; head: HeadTree; mode: Awaited<ReturnType<typeconst refuse = (message: string, suggestion: string) => new OperationError('storage_error', message, suggestion, GIT_GAP_DOCS);-export async function censusGitGap(engine: BrainEngine, sourceId: string, opts: { sample: number; deadlineAt?: number }): Promise<GitGapCensus> {+export async function censusGitGap(engine: BrainEngine, sourceId: string, opts: { sample: number; deadlineAt?: number; collect?: (page: GitGapPage) => void }): Promise<GitGapCensus> {await resolveSourceId(engine, sourceId, undefined, { skipLocalSignals: true });const [source] = await engine.executeRaw<{ local_path: string | null; incarnation: string }>('SELECT local_path, incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);const root = source?.local_path && existsSync(source.local_path) ? source.local_path : null;@@ -142,7 +146,7 @@ export async function censusGitGap(engine: BrainEngine, sourceId: string, opts:const batch = await tx.executeRaw<Key>(`SELECT id::text, slug, source_id, source_path, octet_length(source_path) AS source_path_bytes, source_uri, withheld_source_path, type, frontmatter,database_only_reason, body_storage='segmented' AS segmented, knowledge_revision::text AS revision, NOT ${privatePagesFilterFragment('pages')} AS lineage_privateFROM pages WHERE source_id=$1 AND deleted_at IS NULL AND pages.id > $2::bigint ORDER BY pages.id LIMIT ${BATCH}`, [sourceId, cursor]);- if (batch.length) { await censusBatch(tx, batch, census, { checkout, policy, incarnation: source!.incarnation, sample: opts.sample }); cursor = batch[batch.length - 1]!.id; }+ if (batch.length) { await censusBatch(tx, batch, census, { checkout, policy, incarnation: source!.incarnation, sample: opts.sample, collect: opts.collect }); cursor = batch[batch.length - 1]!.id; }return batch.length < BATCH;});if (done) break;@@ -154,7 +158,11 @@ export async function censusGitGap(engine: BrainEngine, sourceId: string, opts:return census;}-interface BatchContext { checkout: Checkout | null; policy: { mirror: boolean; databaseOnlySource: boolean; dbOnly: (slug: string) => boolean; ignored: Set<string> }; incarnation: string; sample: number }+interface BatchContext { checkout: Checkout | null; policy: { mirror: boolean; databaseOnlySource: boolean; dbOnly: (slug: string) => boolean; ignored: Set<string> }; incarnation: string; sample: number;+ collect?: (page: GitGapPage) => void }++const collected = (key: Key, path: string | null, state: PageState, extra: Partial<GitGapPage> = {}): GitGapPage =>+ ({ id: key.id, slug: key.slug, revision: key.revision, path, state, segmented: key.segmented === true, ...extra });function note(census: GitGapCensus, limit: number, item: GitGapSample): void {if (census.sample.length < limit) census.sample.push(item);@@ -187,6 +195,7 @@ async function censusBatch(tx: BrainEngine, batch: Key[], census: GitGapCensus,if (declared) {census.declared[declared]++;census.states.declared_database_only++;+ ctx.collect?.(collected(key, rel, 'declared_database_only', { declared, ...(blob ? { headBlob: blob.oid } : {}) }));if (blob) { census.declared_with_head_blob++; note(census, ctx.sample, { slug: key.slug, path: rel!, state: 'declared_database_only', declared }); }else if (checkout) noFile.declared.push(key);continue;@@ -194,6 +203,7 @@ async function censusBatch(tx: BrainEngine, batch: Key[], census: GitGapCensus,if (!checkout) { census.not_compared++; continue; }if (!path || rel === null) {census.states.unsafe_path++;+ ctx.collect?.(collected(key, null, 'unsafe_path'));noFile.undeclared.push(key);note(census, ctx.sample, { slug: key.slug, path: key.source_path ?? '', state: 'unsafe_path' });continue;@@ -203,6 +213,7 @@ async function censusBatch(tx: BrainEngine, batch: Key[], census: GitGapCensus,const state: PageState = oid === null ? 'undeclared_database_only' : 'worktree_only';census.worktree![oid === null ? 'absent' : 'untracked']++;census.states[state]++;+ ctx.collect?.(collected(key, rel, state, { worktree: oid === null ? 'absent' : 'untracked' }));noFile.undeclared.push(key);note(census, ctx.sample, { slug: key.slug, path: rel, state, worktree: oid === null ? 'absent' : 'untracked' });continue;@@ -211,6 +222,7 @@ async function censusBatch(tx: BrainEngine, batch: Key[], census: GitGapCensus,census.worktree![worktree]++;if (blob.mode !== '100644' && blob.mode !== '100755') {census.states.unparseable++;+ ctx.collect?.(collected(key, rel, 'unparseable', { worktree, headBlob: blob.oid }));note(census, ctx.sample, { slug: key.slug, path: rel, state: 'unparseable', worktree });continue;}@@ -233,9 +245,10 @@ async function compareBatch(tx: BrainEngine, compare: Array<{ key: Key; path: stconst snapshot = await readExportPage(tx, item.key, withdrawals);const compared: ExportFileComparison = item.key.segmented ? await compareSegmentedExportBlob(tx, snapshot, withdrawals, item.blob, checkout.head.format): compareInlineExportFile(blobs.get(item.blob.oid)!, scannerSourcePath(checkout.root, item.path, checkout.mode), snapshot);- if (compared.state === 'equal') { census.states.equal++; continue; }+ if (compared.state === 'equal') { census.states.equal++; ctx.collect?.(collected(item.key, item.rel, 'equal', { worktree: item.worktree, headBlob: item.blob.oid })); continue; }if (compared.state === 'unparseable') {census.states.unparseable++;+ ctx.collect?.(collected(item.key, item.rel, 'unparseable', { worktree: item.worktree, headBlob: item.blob.oid }));note(census, ctx.sample, { slug: item.key.slug, path: item.rel, state: 'unparseable', worktree: item.worktree });continue;}@@ -250,7 +263,9 @@ async function compareBatch(tx: BrainEngine, compare: Array<{ key: Key; path: stconst state: PageState = gitMoved ? 'git_ahead' : 'database_ahead';census.states[state]++;if (!imported.length) census.database_ahead_without_import_record++;- if (gitMoved && record?.revision != null && String(record.revision) !== String(item.key.revision)) census.git_ahead_database_also_moved++;+ const databaseAlsoMoved = gitMoved && record?.revision != null && String(record.revision) !== String(item.key.revision);+ if (databaseAlsoMoved) census.git_ahead_database_also_moved++;+ ctx.collect?.(collected(item.key, item.rel, state, { worktree: item.worktree, headBlob: item.blob.oid, databaseAlsoMoved }));note(census, ctx.sample, { slug: item.key.slug, path: item.rel, state, fields: item.fields, basis: imported.length ? 'import_record' : 'no_import_record', worktree: item.worktree });}}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 8801cf3253..99c60b3f85 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -22,6 +22,7 @@* gbrain sources refresh <id> — drained worktree-wide ff-only refresh on a managed brain (F0)* gbrain sources git-gap <id> — read-only census of the database against the commit at HEAD (sources-git-gap.ts)* gbrain sources reindex <id> --from-git — a strict source's re-derive from Git, preview then apply (sources-reindex.ts)+ * gbrain sources canonical <id> --to git|mixed — convert a source to git-canonical or back, preview then apply (sources-canonical.ts)* gbrain sources push [<id>|--path <dir>] — scan-gated add→commit→pull→push* (agent-bootstrap; core in src/core/workspace-push.ts)*@@ -1912,6 +1913,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<vcase 'refresh': return (await import('./sources-refresh.ts')).runSourcesRefresh(engine, rest);case 'git-gap': return (await import('./sources-git-gap.ts')).runSourcesGitGap(engine, rest);case 'reindex': return (await import('./sources-reindex.ts')).runSourcesReindex(engine, rest);+ case 'canonical': return (await import('./sources-canonical.ts')).runSourcesCanonical(engine, rest);case 'archive': return runArchive(engine, rest);case 'restore': return runRestore(engine, rest);case 'purge': return runPurge(engine, rest);@@ -2020,6 +2022,8 @@ Subcommands:Read-only: how far the database is from the commit at HEAD, page by page.reindex <id> --from-git [--dry-run | --apply --expect <hash>] [--json]Strict source: preview, then apply, the full pass where Git wins.+ canonical <id> --to git|mixed [--dry-run | --apply --expect <hash>] [--json]+ Managed brains: convert the source to git-canonical (or back), preview first.set-cr-mode <id> <none|title|per_chunk_synopsis>Per-source contextual retrieval modeoverride (v0.40.3.0). Pass "unset" ordiff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 49313ebe2e..0e893801b6 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -201,6 +201,12 @@ export interface SyncOpts {capacityPreflight?: boolean;/** #6696: a runtime paid-work constraint (the cost gate deferred this run's embedding); never a processing option, never lifted by cursor adoption. */embedDeferred?: boolean;+ /**+ * G8 (persistence/git-conversion.ts): the conversion apply's strict-equivalent full pass, run before the source row says+ * `canonical: git`. Internal: no CLI flag or MCP parameter sets it, it refuses a remote caller, and it cannot reach+ * working-tree mode (resolveManagedSyncContext refuses `--working-tree` for a strict-classified pass).+ */+ canonicalOverride?: 'git';/*** v0.18.0 Step 5 — sync a specific named source. When set, sync reads* local_path + last_commit from the sources table (not the globaldiff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex b267d44c9d..a8982060cd 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -113,7 +113,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--run', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--timings', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -127,7 +127,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 24e4090ac1..9ec1d6fa80 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -329,6 +329,8 @@ export const CODES = {git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },git_unavailable: { class: 'retryable', summary: "A git command did not complete." },git_object_missing: { class: 'caller', summary: "A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone.", why: "An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#git_object_missing', suggestion: 'Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then sync again; every sync re-tests the hold.' },+ git_conversion_blocked: { class: 'consent', actor: 'user', summary: "Converting a source to git-canonical would discard database content or cannot place it, so the apply wrote nothing.", reasons: ['both_moved', 'held_drift_both', 'deleted_in_git', 'uncommitted_edit', 'ignored_target', 'unparseable', 'unsafe_path', 'segmented_page', 'export_mismatch', 'git_overwrites_database'], why: "gbrain sources canonical --to git applies only when every database row will be in Git or in a declared database-only class afterwards. The preview counts what would be lost or cannot be placed by category (detail lists them): both_moved and held_drift_both, a page Git and the database both changed; deleted_in_git, a page Git deleted that the database edited since; uncommitted_edit, a working-tree edit the adoption would overwrite; ignored_target, a page whose file Git ignores without a declared class; unparseable and unsafe_path, a committed file or path sync cannot read; segmented_page, a segmented page conversion does not adopt yet; export_mismatch, a page whose export does not read back equal; git_overwrites_database, a page version a strict pass would replace that nothing accepted. There is no override.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Relay the categories and their paths (the --dry-run preview lists them) and ask the user how each should be resolved; preview again afterwards.' },+ git_conversion_incomplete: { class: 'retryable', summary: "A git-canonical conversion stopped because its strict pass did not finish, or finished with work left after the flag was set.", why: "The conversion runs a full strict-equivalent pass before it sets canonical: git, and one genuine strict pass after. A pass that ends partial, blocked or deferred stops the conversion where it is: before the flag the source stays as it was, after it the source stays strict (Git wins) and the plan lists what is left.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Wait until gbrain sync status --source <id> --json shows the source idle, then preview again with gbrain sources canonical <id> --to git --dry-run and apply the new hash.' },git_home_required: { class: 'caller', summary: "A git-canonical source would store content in the database without a file in Git; nothing was written.", reasons: ['no_file_form', 'declared_target', 'facts_lane'], why: "On a source with canonical: git, page content reaches the database only after Git commits its file. The declared database-only classes (private, alias-private and lineage-private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores, detached pages and origin twins) are the only exceptions. no_file_form: the write has no file and is in no declared class; declared_target: a publication would commit a file for a declared page; facts_lane: a writer with no file form yet.", docs: 'docs/guides/write-refusals.md#git_home_required', suggestion: 'Ask the user which git home to configure (a path Git tracks, or a storage.db_only directory in gbrain.yml), then submit the write again with a new request_id.' },git_private_commit_refused: { class: 'caller', summary: "A git-canonical source refused to commit the file of a private, alias-private or lineage-private page; nothing was written and HEAD is unchanged.", reasons: ['private', 'alias_private', 'lineage_private'], why: "Private pages of a source with canonical: git are database-only: their bytes never enter Git history. A page turning private is published as the door commit that removes its file, never as a commit of its bytes.", docs: 'docs/guides/write-refusals.md#git_private_commit_refused', suggestion: 'The page stays database-only. Write it through put_page (which publishes a private page without a file), or remove visibility: private if it belongs in Git, then submit again with a new request_id.' },git_protocol_required: { class: 'host_only', summary: "A write reached a git-canonical source from a process that does not declare the git-canonical protocol (an older gbrain, or gbrain.write_sources set by hand); nothing was written.", docs: 'docs/guides/write-refusals.md#git_protocol_required', suggestion: 'Upgrade or stop the gbrain process that wrote it (gbrain upgrade on its host), then retry with a new request_id.' },diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex ec752cb100..0734ef1fde 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -103,7 +103,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect// and after the activation committed, before the producer acknowledges it.| 'generation:published' | 'generation:retired' | 'generation:activated'// GBRA-161 PR 1b: as a managed generation member (an overwrite or retirement after its activation committed) is prepared.- | 'generation:member';+ | 'generation:member'+ // G8a (git-conversion.ts): after a conversion group's door commit, and after the strict-equivalent pass, before the flag is set.+ | 'conversion:group_committed' | 'conversion:before_flip';/*** `signal` (#6278, `consumer:preparing` only): the preparation's abort signal, so* a stalling hook can model both the reporter's cases: a preparer that honoursdiff --git a/src/core/persistence/git-conversion.ts b/src/core/persistence/git-conversion.tsnew file mode 100644index 0000000000..5d283f32c3--- /dev/null+++ b/src/core/persistence/git-conversion.ts@@ -0,0 +1,423 @@+/**+ * G8a of git-canonical memory (docs/designs/GIT_CANONICAL_MEMORY.md, "Conversion"): the plan and apply behind+ * `gbrain sources canonical <id> --to git|mixed` (commands/sources-canonical.ts). Trusted local CLI only, managed+ * brains only, never an MCP operation.+ *+ * The preview (read-only) puts every live page of the source in one category, from the git-gap census (G1, the equality+ * contract against HEAD), the declared database-only classes (G7a), the open sync holds, the parked Git effects and the+ * level a strict pass would read (G3, sync-pass.ts readShadowLevel under a strict-classified context):+ * - adopt: the database holds content Git does not (database_ahead, undeclared_database_only, worktree_only). The apply+ * writes the page's export view (readExportPage, withdrawals overlaid: exactly what the census compares) to its file+ * and commits it with commitThroughDoor, one commit per group of CONVERSION_GROUP_MAX pages, under the worktree writer+ * lock, which is dropped between groups. No row changes: the database already holds those bytes.+ * - declared: database-only on purpose; nothing is written and nothing deleted.+ * - git_wins: Git's verdict replaces the row and loses nothing the operator has not accepted (Git moved and the+ * database did not; Git deleted a page sync had not indexed yet; a held deletion; a held file_drift whose side is+ * unknown). The strict-equivalent pass applies it.+ * - holds: cleared, so that pass runs Git's verdict over them (a hold at its level would settle the path).+ * - parked Git effects: retried (retry-effects' one authorized attempt), or reclassified when Git ignores the target+ * (the page is stamped git_ignored, G7a's declared class, and the target stays parked as a record).+ * - discard: database content that would be neither in Git after the apply nor declared, by category. The apply+ * refuses (git_conversion_blocked, naming the categories) unless it is zero; there is no override.+ * The preview hash binds HEAD, the source incarnation and every planned item with its revision.+ *+ * The apply re-plans and refuses preview_changed on a different hash, adopts group by group (a crash leaves the source+ * non-strict and the rerun preview lists only what is left), clears the holds, retries or reclassifies the parked+ * effects, checks the strict level once more (an overwrite nobody accepted stops it), runs the full strict-equivalent+ * pass (SyncOpts.canonicalOverride, internal) and sets `canonical: git` last, in the transaction that records the+ * conversion. Writes can land between that pass and the flag, so it then runs one genuine strict pass and plans again:+ * only a plan with no work left is a completed conversion; otherwise the source stays strict (Git wins) and the+ * remaining categories are reported. `--to mixed` removes the flag and changes nothing else.+ */+import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join, relative, sep } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { loadConfig } from '../config.ts';+import { resolveSourceId } from '../source-resolver.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';+import { currentSubmissionAuthority } from '../minions/submission-authority.ts';+import { inlineExportMarkdown, readExportPage, readExportWithdrawals } from '../export-snapshot.ts';+import { scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';+import { censusGitGap, type GitGapCensus, type GitGapPage } from '../../commands/sources-git-gap.ts';+import { compareInlineExportFile, ignoredPaths } from './git-gap.ts';+import { commitThroughDoor } from './git-door.ts';+import { currentVerifiedLocalWriter, localHostId } from './identity.ts';+import { acquireWorktree, readManagedMode } from './ownership.ts';+import { resolveManagedSyncContext, type ManagedSyncContext } from './sync-discovery.ts';+import { readShadowLevel } from './sync-pass.ts';+import { clearGitHold, fileDriftSide, readGitSourceHolds, readSyncImportProvenances, type GitHoldRecord } from './sync-holds.ts';+import { readDeletionProvenance } from './sync-origin-evidence.ts';+import { retryParkedEffects } from './effect-retry.ts';+import { runPersistenceEffects } from './effects.ts';+import { faultPoint } from './fault-points.ts';+import { previewChangedError, previewHash } from './preview-approval.ts';+import { sha256 } from './digest.ts';++export const CONVERSION_GROUP_MAX = 200;+export const CONVERSION_OP = 'git-canonical-conversion';+const DOCS = 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion';+const SAMPLE = 20;+const LOCK_WAIT_MS = 30_000;++export const ADOPT_STATES = ['database_ahead', 'undeclared_database_only', 'worktree_only'] as const;+export type AdoptState = typeof ADOPT_STATES[number];+export const GIT_WINS_REASONS = ['git_ahead', 'deleted_by_commit', 'held_deletion', 'held_drift_unknown'] as const;+export type GitWinsReason = typeof GIT_WINS_REASONS[number];+/** Database content the apply would discard or cannot place, by why: each must be zero before the apply runs. */+export const DISCARD_CATEGORIES = ['both_moved', 'held_drift_both', 'deleted_in_git', 'uncommitted_edit', 'ignored_target', 'unparseable', 'unsafe_path',+ 'segmented_page', 'export_mismatch', 'git_overwrites_database'] as const;+export type DiscardCategory = typeof DISCARD_CATEGORIES[number];++interface Counted<K extends string> { count: number; by: Record<K, number>; sample: string[] }+/** `disk`: sha256 of the working-tree bytes the preview saw (HEAD's or the export's), null when the file was absent. */+export interface AdoptItem { id: string; source_id: string; slug: string; revision: string | null; path: string; state: AdoptState; disk: string | null }+interface HoldItem { path: string; code: string; side: string | null; observed_at: string; action: 'git_wins' | 'rescreen' | 'blocked' }+interface ParkedItem { effect: string; request: string; kind: string; codes: string[]; slugs: string[]; action: 'retry' | 'reclassify' }++export interface GitConversionPreview {+ status: 'preview';+ source_id: string;+ to: 'git';+ /** Whether the source row already says canonical: git (a rerun after an incomplete conversion). */+ strict: boolean;+ head: string | null;+ pages: number;+ equal: number;+ adopt: Counted<AdoptState> & { action: 'commit_through_door'; groups: number };+ declared: Counted<string> & { action: 'none' };+ git_wins: Counted<GitWinsReason> & { action: 'index_committed_blob' };+ holds: Counted<string> & { action: 'clear' };+ parked_effects: { count: number; retry: number; reclassify: number; by_code: Record<string, number> };+ /** What a strict pass would import or delete that no page row loses (files with no row, removals Git committed). */+ index: { imports: number; deletes: number };+ discard: Counted<DiscardCategory>;+ /** Every item the apply still has to act on (adopt, git_wins, holds, parked retries, discard); 0 on a converted source. */+ remaining: number;+ preview_hash: string;+ apply: string[];+}++/** `settled`: paths whose Git import replaces nothing (the census reads them equal, or the plan adopts or accepts them). */+export interface GitConversionPlan { preview: GitConversionPreview; context: ManagedSyncContext; adopt: AdoptItem[]; holds: HoldItem[]; parked: ParkedItem[]; settled: Set<string>; incarnation: string }++const counted = <K extends string>(keys: readonly K[]): Counted<K> => ({ count: 0, by: Object.fromEntries(keys.map(key => [key, 0])) as Record<K, number>, sample: [] });+function tally<K extends string>(into: Counted<K>, key: K, path: string): void {+ into.count++;+ into.by[key] = (into.by[key] ?? 0) + 1;+ if (into.sample.length < SAMPLE) into.sample.push(path);+}++/** The refusals before anything is read: a remote caller, an unmanaged brain. */+export async function assertConversionCaller(engine: BrainEngine, sourceId: string): Promise<void> {+ if (currentSubmissionAuthority()?.kind === 'remote_generic' || currentVerifiedLocalWriter()?.remote) {+ throw trustedCliRequired('Converting a source to or from git-canonical runs only from the trusted local CLI on the brain host.');+ }+ if (await readManagedMode(engine)) return;+ const why = 'A git-canonical source is committed to Git before the database indexes it, and only managed persistence (the writer coordinator) does that.';+ throw opError('strict_requires_managed', `Source ${sourceId} cannot become git-canonical on an unmanaged brain; nothing was read or written.`,+ 'Ask the user whether to turn on managed persistence for this brain first; conversion runs only on a managed brain.',+ { why, docs: DOCS, fix: { consent: [], actor: 'user', requires_exclusive: false, why, verify: { argv: ['gbrain', 'doctor', '--json'] },+ user_message: `Source ${sourceId} can only become git-canonical on a brain with managed writes, and this brain is not managed. Should it move to managed writes first?` } });+}++/** The context a strict pass reads, for a source whose row does not say so yet. */+const strictContext = (context: ManagedSyncContext): ManagedSyncContext => ({ ...context, source: { ...context.source, config: { ...context.source.config, canonical: 'git' } } });++/** The read-only plan of `--to git`; its preview is what the CLI prints and the apply binds to. */+export async function planGitConversion(engine: BrainEngine, sourceId: string): Promise<GitConversionPlan> {+ const context = await resolveManagedSyncContext(engine, { sourceId, noPull: true, dryRun: true });+ const pages: GitGapPage[] = [];+ const equal = new Set<string>();+ const census = await censusGitGap(engine, sourceId, { sample: 0, collect: page => { if (page.state !== 'equal') pages.push(page); else if (page.path) equal.add(page.path); } });+ if (!census.checkout || realpathSync(census.checkout) !== context.root) {+ throw opError('source_changed', `Source ${sourceId}'s registered checkout is not its owner's root, so nothing was planned.`,+ `Check the owner with gbrain sources writer status --source ${sourceId} --json, then preview again.`);+ }+ const root = context.root;+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);+ const holdRecords = (await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? [];+ const held = new Map(holdRecords.map(hold => [hold.path, hold]));+ const preview = emptyPreview(sourceId, context, census);+ const adopt: AdoptItem[] = [], accepted = new Set<string>(), discarded = new Set<string>();+ const discard = (category: DiscardCategory, path: string) => { tally(preview.discard, category, path); discarded.add(path); };+ const gitWins = (reason: GitWinsReason, path: string) => { tally(preview.git_wins, reason, path); accepted.add(path); };+ const holds = holdRecords.map(hold => holdItem(hold));+ for (const hold of holds) {+ tally(preview.holds, hold.side ? `${hold.code}:${hold.side}` : hold.code, hold.path);+ if (hold.action === 'blocked') discard('held_drift_both', hold.path);+ }++ const noFile = pages.filter(page => page.state === 'undeclared_database_only' && page.path !== null);+ const provenance = noFile.length ? await readDeletionProvenance(root, noFile.map(page => page.path!)) : new Map();+ const records = noFile.length ? await readSyncImportProvenances(engine, sourceId, incarnation, noFile.map(page => Number(page.id))) : new Map();+ const candidates: Array<{ page: GitGapPage; state: AdoptState }> = [];+ for (const page of pages) {+ const path = page.path ?? page.slug;+ const hold = page.path ? held.get(page.path) : undefined;+ const side = hold?.code === 'file_drift' ? fileDriftSide(hold.meta) ?? null : null;+ switch (page.state) {+ case 'declared_database_only': tally(preview.declared, page.declared!, path); continue;+ case 'unparseable': discard('unparseable', path); continue;+ case 'unsafe_path': discard('unsafe_path', path); continue;+ case 'git_ahead':+ if (side === 'unknown') gitWins('held_drift_unknown', path);+ else if (page.databaseAlsoMoved && side !== 'both') discard('both_moved', path);+ else if (!page.databaseAlsoMoved) gitWins('git_ahead', path);+ continue;+ case 'database_ahead':+ if (side === 'unknown') { gitWins('held_drift_unknown', path); continue; }+ if (side === 'both') continue;+ candidates.push({ page, state: 'database_ahead' });+ continue;+ case 'worktree_only': candidates.push({ page, state: 'worktree_only' }); continue;+ case 'undeclared_database_only': {+ if (provenance.get(page.path!)?.kind !== 'deleted_by_commit') { candidates.push({ page, state: 'undeclared_database_only' }); continue; }+ const record = records.get(Number(page.id));+ if (side === 'deleted') gitWins('held_deletion', path);+ else if (record?.revision != null && String(record.revision) === String(page.revision)) gitWins('deleted_by_commit', path);+ else discard('deleted_in_git', path);+ continue;+ }+ default: continue;+ }+ }+ await planAdoption(engine, sourceId, root, candidates, preview, adopt, discard);+ const parked = await readParked(engine, sourceId);+ for (const item of parked) for (const code of item.codes) preview.parked_effects.by_code[`${item.kind}:${code}`] = (preview.parked_effects.by_code[`${item.kind}:${code}`] ?? 0) + 1;+ preview.parked_effects.count = parked.length;+ preview.parked_effects.retry = parked.filter(item => item.action === 'retry').length;+ preview.parked_effects.reclassify = parked.filter(item => item.action === 'reclassify').length;+ const settled = new Set([...equal, ...adopt.map(item => item.path), ...accepted]);+ await planIndex(engine, context, preview, new Set([...settled, ...held.keys(), ...discarded]), discard);+ preview.adopt.groups = Math.ceil(adopt.length / CONVERSION_GROUP_MAX);+ preview.remaining = preview.adopt.count + preview.git_wins.count + preview.holds.count + preview.parked_effects.retry + preview.discard.count;+ preview.preview_hash = previewHash({ source: sourceId, incarnation, to: 'git', strict: preview.strict, head: preview.head, states: census.states, declared: census.declared,+ adopt: adopt.map(item => [item.id, item.revision, item.path, item.state, item.disk]), git_wins: [...accepted].sort(), discard: preview.discard.by,+ holds: holds.map(hold => [hold.path, hold.code, hold.side, hold.observed_at]), parked: parked.map(item => [item.effect, item.action, item.codes]), index: preview.index });+ preview.apply = ['gbrain', 'sources', 'canonical', sourceId, '--to', 'git', '--apply', '--expect', preview.preview_hash];+ return { preview, context, adopt, holds, parked, settled, incarnation };+}++function emptyPreview(sourceId: string, context: ManagedSyncContext, census: GitGapCensus): GitConversionPreview {+ return { status: 'preview', source_id: sourceId, to: 'git', strict: context.source.config?.canonical === 'git', head: census.head, pages: census.pages, equal: census.states.equal,+ adopt: { ...counted(ADOPT_STATES), action: 'commit_through_door', groups: 0 }, declared: { ...counted<string>([]), action: 'none' },+ git_wins: { ...counted(GIT_WINS_REASONS), action: 'index_committed_blob' }, holds: { ...counted<string>([]), action: 'clear' },+ parked_effects: { count: 0, retry: 0, reclassify: 0, by_code: {} }, index: { imports: 0, deletes: 0 }, discard: counted(DISCARD_CATEGORIES), remaining: 0, preview_hash: '', apply: [] };+}++/** A hold's fate: a held deletion or an unknown-side drift goes to Git, a both-sides drift is database content Git would discard, the rest re-screen. */+function holdItem(hold: GitHoldRecord): HoldItem {+ const side = hold.code === 'file_drift' ? fileDriftSide(hold.meta) ?? null : null;+ const action = side === 'both' ? 'blocked' : side === 'unknown' || side === 'deleted' ? 'git_wins' : 'rescreen';+ return { path: hold.path, code: hold.code, side, observed_at: hold.observed_at, action };+}++/**+ * Each adoption candidate's export bytes must read back equal under the census contract, its target must not be ignored,+ * and the working tree must hold HEAD's bytes, the export's, or nothing: an uncommitted edit is never overwritten.+ */+async function planAdoption(engine: BrainEngine, sourceId: string, root: string, candidates: Array<{ page: GitGapPage; state: AdoptState }>, preview: GitConversionPreview,+ adopt: AdoptItem[], discard: (category: DiscardCategory, path: string) => void): Promise<void> {+ if (!candidates.length) return;+ const ignored = await ignoredPaths(root, candidates.map(({ page }) => page.path!));+ const mode = await scannerSlugRootMode(engine, sourceId, root);+ const withdrawals = await readExportWithdrawals(engine, sourceId);+ for (const { page, state } of candidates) {+ const path = page.path!;+ if (!ignored || ignored.has(path)) { discard('ignored_target', path); continue; }+ if (page.segmented) { discard('segmented_page', path); continue; }+ const snapshot = await readExportPage(engine, { ...page, source_id: sourceId }, withdrawals);+ const bytes = Buffer.from(inlineExportMarkdown(snapshot));+ if (compareInlineExportFile(bytes, scannerSourcePath(root, join(root, path), mode), snapshot).state !== 'equal') { discard('export_mismatch', path); continue; }+ const disk = diskBytes(join(root, path));+ if (page.worktree !== 'clean' && page.worktree !== 'absent' && !disk?.equals(bytes)) { discard('uncommitted_edit', path); continue; }+ adopt.push({ id: page.id, source_id: sourceId, slug: page.slug, revision: page.revision, path, state, disk: disk ? sha256(disk) : null });+ tally(preview.adopt, state, path);+ }+}++/** A level path (Git-root relative) as the census names it (source-root relative). */+const sourcePath = (scope: string, gitPath: string) => scope && gitPath.startsWith(`${scope}/`) ? gitPath.slice(scope.length + 1) : gitPath;++function diskBytes(path: string): Buffer | null {+ try { return lstatSync(path).isFile() ? readFileSync(path) : null; } catch { return null; }+}++/** Parked Git targets of the source (the census's parked list), each effect with its action. */+async function readParked(engine: BrainEngine, sourceId: string): Promise<ParkedItem[]> {+ const rows = await engine.executeRaw<{ effect: string; request: string; kind: string; parked: Array<{ slug?: string; error_code: string }> }>(+ `SELECT e.id::text AS effect, r.request_id::text AS request, e.kind, e.data->'parked' AS parked FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id+ WHERE e.source_id=$1 AND jsonb_typeof(e.data->'parked')='array' AND jsonb_array_length(e.data->'parked')>0 ORDER BY e.id`, [sourceId]);+ return rows.map(row => {+ const parked = typeof row.parked === 'string' ? JSON.parse(row.parked) as typeof row.parked : row.parked;+ const codes = parked.map(target => target.error_code);+ return { effect: row.effect, request: row.request, kind: row.kind, codes, slugs: parked.flatMap(target => target.slug ? [target.slug] : []),+ action: row.kind === 'git' && codes.every(code => code === 'git_target_ignored') ? 'reclassify' as const : 'retry' as const };+ });+}++/**+ * The level a strict pass reads (G3's reindex preview): what it imports or deletes, and every page version it would+ * replace that the plan has not placed (`git_overwrites_database`). `planned`: paths already placed (equal, adopted,+ * accepted, held or counted as discard).+ */+async function planIndex(engine: BrainEngine, context: ManagedSyncContext, preview: GitConversionPreview, planned: ReadonlySet<string>,+ discard: (category: DiscardCategory, path: string) => void): Promise<void> {+ const level = await readShadowLevel(engine, { sourceId: context.sourceId, full: true, context: strictContext(context) });+ if (!level) return;+ for (const entry of level.paths) {+ if (entry.result.settled || entry.result.inFlight || (entry.result.action !== 'import' && entry.result.action !== 'delete')) continue;+ const path = sourcePath(level.scope, entry.path);+ if (planned.has(path)) continue;+ if (entry.result.gitWins) discard('git_overwrites_database', path);+ else preview.index[entry.result.action === 'import' ? 'imports' : 'deletes']++;+ }+}++export interface GitConversionResult {+ status: 'converted' | 'incomplete';+ source_id: string;+ head: string | null;+ committed: { groups: number; pages: number; commits: string[] };+ holds_cleared: number;+ parked: { retried: number; reclassified: number };+ /** The plan after the flag was set and a strict pass ran: nothing left on a completed conversion. */+ after: GitConversionPreview;+}++const blockedError = (preview: GitConversionPreview): OperationError => {+ const categories = DISCARD_CATEGORIES.filter(category => preview.discard.by[category] > 0);+ return opError('git_conversion_blocked', `Converting source ${preview.source_id} would discard database content or cannot place it (${categories.map(category => `${category} ${preview.discard.by[category]}`).join(', ')}); nothing was written.`,+ `Resolve each listed path (gbrain sources canonical ${preview.source_id} --to git --dry-run lists them), then preview again. There is no override.`,+ { reason: categories[0], docs: DOCS, detail: categories.join(','), fix: { argv: ['gbrain', 'sources', 'canonical', preview.source_id, '--to', 'git', '--dry-run', '--json'], consent: [], actor: 'user',+ requires_exclusive: false, why: 'Lists every path of each blocking category; nothing changes.',+ user_message: `Converting ${preview.source_id} to git-canonical would lose database content in ${categories.join(', ')}. Each path needs a decision before conversion can run.` } });+};++/** The apply of `--to git` (see the header). Throws preview_changed or git_conversion_blocked before writing anything. */+export async function applyGitConversion(engine: BrainEngine, sourceId: string, expect: string, opts: { noEmbed?: boolean; noExtract?: boolean } = {}): Promise<GitConversionResult> {+ const previewCommand = `gbrain sources canonical ${sourceId} --to git --dry-run`;+ const plan = await planGitConversion(engine, sourceId);+ if (plan.preview.preview_hash !== expect) throw previewChangedError(expect, previewCommand);+ if (plan.preview.discard.count) throw blockedError(plan.preview);+ const committed = await adoptGroups(engine, plan, previewCommand);+ let holdsCleared = 0;+ for (const hold of plan.holds) {+ if (await engine.transaction(tx => clearGitHold(tx, { sourceId, incarnation: plan.incarnation, path: hold.path, observedAt: hold.observed_at }))) holdsCleared++;+ }+ const parked = await settleParked(engine, sourceId, plan.parked);+ const recheck = await readShadowLevel(engine, { sourceId, full: true, context: strictContext(plan.context) });+ const preview = { ...plan.preview, discard: counted(DISCARD_CATEGORIES) };+ for (const entry of recheck?.paths ?? []) {+ const path = sourcePath(recheck!.scope, entry.path);+ if (!entry.result.settled && !entry.result.inFlight && entry.result.gitWins && !plan.settled.has(path)) tally(preview.discard, 'git_overwrites_database', path);+ }+ if (preview.discard.count) throw blockedError(preview);+ const processing = { noEmbed: opts.noEmbed, noExtract: opts.noExtract };+ const { performManagedSync } = await import('./sync-run.ts');+ passOrThrow(sourceId, await performManagedSync(engine, { sourceId, noPull: true, full: true, ...processing, canonicalOverride: 'git' }));+ await faultPoint('conversion:before_flip', { sourceId });+ await recordConversion(engine, sourceId, plan.incarnation, 'git', expect, plan.preview.head);+ passOrThrow(sourceId, await performManagedSync(engine, { sourceId, noPull: true, full: true, ...processing }));+ const after = (await planGitConversion(engine, sourceId)).preview;+ return { status: after.remaining === 0 ? 'converted' : 'incomplete', source_id: sourceId, head: after.head, committed, holds_cleared: holdsCleared, parked, after };+}++const PASS_DONE = new Set(['first_sync', 'synced', 'up_to_date']);+function passOrThrow(sourceId: string, result: { status: string; reason?: string }): void {+ if (PASS_DONE.has(result.status)) return;+ throw opError('git_conversion_incomplete', `The strict pass of source ${sourceId} ended ${result.status}${result.reason ? ` (${result.reason})` : ''}, so the conversion stopped there.`,+ `Rerun gbrain sources canonical ${sourceId} --to git --dry-run once gbrain sync status --source ${sourceId} --json shows the source idle, then apply the new hash.`,+ { docs: DOCS, detail: result.status });+}++/**+ * Writes and commits the adopted pages group by group under the worktree writer lock. A page whose revision or working+ * tree moved since the preview stops the apply (preview_changed) before anything else changes: the groups already+ * committed hold the bytes the database has, so the rerun preview reads them equal.+ */+async function adoptGroups(engine: BrainEngine, plan: GitConversionPlan, previewCommand: string): Promise<GitConversionResult['committed']> {+ const { context, adopt } = plan;+ const root = context.root;+ const commits: string[] = [];+ const withdrawals = adopt.length ? await readExportWithdrawals(engine, context.sourceId) : [];+ for (let start = 0; start < adopt.length; start += CONVERSION_GROUP_MAX) {+ const group = adopt.slice(start, start + CONVERSION_GROUP_MAX);+ const lock = await acquireWorktree(context.binding, LOCK_WAIT_MS, undefined, engine, { yieldLanes: true });+ if (!lock) throw opError('writer_busy', `The writer lock of source ${context.sourceId}'s checkout stayed busy for ${LOCK_WAIT_MS / 1000}s, so group ${start / CONVERSION_GROUP_MAX + 1} was not committed.`,+ `Run ${previewCommand} again; the groups already committed read equal, so the new plan holds only what is left.`, { retryable: true });+ try {+ const files: Array<{ path: string; bytes: Buffer }> = [];+ for (const item of group) {+ const [live] = await engine.executeRaw<{ revision: string | null }>('SELECT knowledge_revision::text AS revision FROM pages WHERE id=$1::bigint AND deleted_at IS NULL', [item.id]);+ const target = join(root, item.path);+ const disk = diskBytes(target);+ if (!live || live.revision !== item.revision || (disk ? sha256(disk) : null) !== item.disk) throw previewChangedError(plan.preview.preview_hash, previewCommand);+ files.push({ path: target, bytes: Buffer.from(inlineExportMarkdown(await readExportPage(engine, item, withdrawals))) });+ }+ for (const file of files) writeAtomically(root, file.path, file.bytes);+ const commit = await commitThroughDoor(root, files.map(file => ({ path: file.path })), lock);+ if (commit) commits.push(commit);+ } finally { await lock.release(); }+ await faultPoint('conversion:group_committed', { sourceId: context.sourceId, round: start / CONVERSION_GROUP_MAX + 1 });+ }+ return { groups: commits.length, pages: adopt.length, commits };+}++function writeAtomically(root: string, target: string, bytes: Buffer): void {+ mkdirSync(dirname(target), { recursive: true });+ if (relative(realpathSync(root), realpathSync(dirname(target))).split(sep)[0] === '..') throw opError('git_target_unsafe', `${target} resolves outside the checkout, so it was not written.`, 'Reconcile the path first.');+ const temp = join(dirname(target), `.gbrain-convert-${process.pid}-${Date.now()}.tmp`);+ try { writeFileSync(temp, bytes); renameSync(temp, target); } finally { rmSync(temp, { force: true }); }+}++/** Retries each parked effect once (retry-effects' authorization) and stamps the pages of ignored targets git_ignored. */+async function settleParked(engine: BrainEngine, sourceId: string, parked: ParkedItem[]): Promise<GitConversionResult['parked']> {+ let retried = 0, reclassified = 0;+ for (const item of parked) {+ if (item.action === 'reclassify') {+ await engine.executeRaw(`UPDATE pages SET database_only_reason='git_ignored' WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL AND database_only_reason IS NULL`, [sourceId, item.slugs]);+ reclassified++;+ continue;+ }+ const result = await retryParkedEffects(engine, sourceId, item.request, false, { parkedOnly: true });+ if ((result?.effects as Array<{ action?: string }> | undefined)?.some(effect => effect.action === 'retry_queued')) retried++;+ }+ if (retried) await runPersistenceEffects(engine, loadConfig() ?? { engine: engine.kind }, { hostId: localHostId(), limit: 50 });+ return { retried, reclassified };+}++/** Sets or removes the flag in the transaction that records the conversion (op_checkpoints `git-canonical-conversion`, one row per source incarnation). */+export async function recordConversion(engine: BrainEngine, sourceId: string, incarnation: string, to: 'git' | 'mixed', hash: string, head: string | null): Promise<void> {+ await engine.transaction(async tx => {+ const [updated] = await tx.executeRaw<{ id: string }>(to === 'git'+ ? `UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id=$1 AND incarnation::text=$2 RETURNING id`+ : `UPDATE sources SET config = config - 'canonical' WHERE id=$1 AND incarnation::text=$2 RETURNING id`, [sourceId, incarnation]);+ if (!updated) throw opError('source_changed', `Source ${sourceId} was replaced during the conversion, so its mode was not changed.`, `Preview again with gbrain sources canonical ${sourceId} --to ${to} --dry-run.`);+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,+ [CONVERSION_OP, `${sourceId}:${incarnation}`, JSON.stringify([{ source_id: sourceId, incarnation, to, preview_hash: hash, head }])]);+ });+}++export interface MixedConversionPreview { status: 'preview'; source_id: string; to: 'mixed'; strict: boolean; preview_hash: string; apply: string[] }++/** `--to mixed`: the source stops being strict. Bound to the source incarnation and its current flag; nothing else is read. */+export async function planMixedConversion(engine: BrainEngine, sourceId: string): Promise<MixedConversionPreview & { incarnation: string }> {+ await resolveSourceId(engine, sourceId, undefined, { skipLocalSignals: true });+ const [source] = await engine.executeRaw<{ incarnation: string; strict: boolean }>(+ "SELECT incarnation::text AS incarnation, COALESCE(config->>'canonical','')='git' AS strict FROM sources WHERE id=$1", [sourceId]);+ const preview_hash = previewHash({ source: sourceId, incarnation: source.incarnation, to: 'mixed', strict: source.strict });+ return { status: 'preview', source_id: sourceId, to: 'mixed', strict: source.strict, preview_hash, incarnation: source.incarnation,+ apply: ['gbrain', 'sources', 'canonical', sourceId, '--to', 'mixed', '--apply', '--expect', preview_hash] };+}++/** Removes `canonical: git` in the transaction that records it; Git keeps every door commit and no row changes. */+export async function applyMixedConversion(engine: BrainEngine, sourceId: string, expect: string): Promise<{ status: 'mixed' | 'unchanged'; source_id: string }> {+ const plan = await planMixedConversion(engine, sourceId);+ if (plan.preview_hash !== expect) throw previewChangedError(expect, `gbrain sources canonical ${sourceId} --to mixed --dry-run`);+ if (!plan.strict) return { status: 'unchanged', source_id: sourceId };+ await recordConversion(engine, sourceId, plan.incarnation, 'mixed', expect, null);+ return { status: 'mixed', source_id: sourceId };+}diff --git a/src/core/persistence/sync-classify.ts b/src/core/persistence/sync-classify.tsindex b107b9af78..ee7157ad4d 100644--- a/src/core/persistence/sync-classify.ts+++ b/src/core/persistence/sync-classify.ts@@ -207,7 +207,8 @@ export function committedOnlyState(s: SyncPathState): SyncPathState {/*** G3: Git's verdict for a strict source, after its hold rows. Drift, a database version sync never saw (`db_ahead` that is- * not a pending door write), keep_db and an edited tombstone import the committed blob. A live page whose file is absent+ * not a pending door write, or a page no import record proves: `legacy_unverified`), keep_db and an edited tombstone import+ * the committed blob. A live page whose file is absent* from `T` waits for its origin evidence (sync-pass.ts reads it for every delete candidate), then is deleted when a commit* held the file and left as the database has it otherwise.*/@@ -221,7 +222,8 @@ function gitVerdict(state: SyncPathState): Matched {const rest = afterHold(state);const wins = (match: Matched): Matched => match;switch (rest.cls) {- case 'drift': case 'keep_db': case 'deleted_edited': return wins({ cls: 'import', settled: false, action: 'import' });+ // G8a: a page no import record proves (legacy_unverified, typically the unknown side of a held drift) takes the commit too.+ case 'drift': case 'keep_db': case 'deleted_edited': case 'legacy_unverified': return wins({ cls: 'import', settled: false, action: 'import' });case 'db_ahead': return rest.sub === 'pending' ? rest : wins({ cls: 'import', settled: false, action: 'import' });case 'delete': case 'delete_drift':if (state.originEvidence === undefined) return rest;diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex b68d141a82..112f66ad7e 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -19,7 +19,9 @@ import { resolveSlugRootMode } from '../sync-anchor.ts';import { isWriteTargetContained } from '../path-confine.ts';import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';import { unboundBindCommand } from './unbound-source.ts';-import { localHostId } from './identity.ts';+import { currentVerifiedLocalWriter, localHostId } from './identity.ts';+import { currentSubmissionAuthority } from '../minions/submission-authority.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';import { ownerUnavailableReason } from './owner-refusal.ts';import { sha256 } from './digest.ts';import { isWindowsColonTarget } from './native-file-target.ts';@@ -231,7 +233,11 @@ export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncO`Sync without pulling to import the checkout as it is (CLI: gbrain sync --no-pull --source ${sourceId}; MCP: sync_brain with no_pull: true), or fast-forward and sync the checkout with gbrain sources refresh ${sourceId}.`);const forbidden = managedForbiddenFlag(opts);if (forbidden) throw managedSyncFlagRefusal(forbidden, sourceId, ['--source', sourceId, '--no-pull']);- const [source, binding] = await (rows ?? readManagedSyncRows(engine, sourceId));+ const [read, binding] = await (rows ?? readManagedSyncRows(engine, sourceId));+ if (opts.canonicalOverride === 'git' && (currentSubmissionAuthority()?.kind === 'remote_generic' || currentVerifiedLocalWriter()?.remote)) {+ throw trustedCliRequired('The strict-equivalent pass of a git-canonical conversion runs only from the trusted local CLI.');+ }+ const source = read && opts.canonicalOverride === 'git' ? { ...read, config: { ...read.config, canonical: 'git' } } : read;if (source?.config?.canonical === 'git' && managedForbiddenFlag(opts, true)) throw managedSyncFlagRefusal('--working-tree', sourceId, ['--source', sourceId, '--no-pull', '--working-tree']);if (!source || source.archived || !binding || binding.source_incarnation !== source.incarnation ||binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path) {diff --git a/test/git-canonical-conversion-g8a.test.ts b/test/git-canonical-conversion-g8a.test.tsnew file mode 100644index 0000000000..902523ea27--- /dev/null+++ b/test/git-canonical-conversion-g8a.test.ts@@ -0,0 +1,305 @@+/**+ * G8a of git-canonical memory (docs/designs/GIT_CANONICAL_MEMORY.md#conversion): `gbrain sources canonical <id> --to git|mixed`.+ * A mixed source with every category present converts with the right action for each: database_ahead and undeclared+ * pages are written from the database and committed through the door (one commit per group), declared pages stay+ * database-only, a page Git moved is indexed, a held deletion and an unknown-side drift take Git's side, a parked effect+ * on an ignored path is reclassified as declared. Afterwards the tree is clean, the census shows no gap, the adopted rows+ * kept their revisions and a G3 pass changes nothing. A stale hash refuses; database content that would be discarded+ * refuses and writes nothing; a crash after a group's commit leaves the source non-strict and a rerun completes once;+ * --to mixed round-trips; remote callers and unmanaged brains cannot reach it.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { operations } from '../src/core/operations.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { acquireWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';+import { applyGitConversion, applyMixedConversion, CONVERSION_GROUP_MAX, planGitConversion, planMixedConversion } from '../src/core/persistence/git-conversion.ts';+import { withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';+import { censusGitGap } from '../src/commands/sources-git-gap.ts';+import { runSourcesCanonical } from '../src/commands/sources-canonical.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { managedBrain, type ManagedBrain } from './helpers/managed-brain.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const note = (slug: string, body: string, extra = '') => '---\ntype: concept\ntitle: ' + slug + '\n' + extra + '---\n\n' + body + '\n';+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const PROCESSING = { noEmbed: true, noExtract: true };+const putPage = operations.find(op => op.name === 'put_page')!;++const strict = async (engine: BrainEngine) => (await engine.executeRaw<{ s: boolean }>("SELECT COALESCE(config->>'canonical','')='git' AS s FROM sources WHERE id='default'"))[0]!.s;+const page = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ body: string; deleted: boolean; revision: string }>(+ "SELECT compiled_truth AS body, deleted_at IS NOT NULL AS deleted, knowledge_revision::text AS revision FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0];+const revisions = async (engine: BrainEngine) => Object.fromEntries((await engine.executeRaw<{ slug: string; revision: string }>(+ "SELECT slug, knowledge_revision::text AS revision FROM pages WHERE source_id='default' AND deleted_at IS NULL ORDER BY slug")).map(row => [row.slug, row.revision]));+const holds = async (engine: BrainEngine) => (await engine.executeRaw<{ r: { path: string; code: string } }>(+ "SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='sync-hold' ORDER BY fingerprint")).map(({ r }) => `${r.path} ${r.code}`);+/** A database-only edit: the page moves to a revision no request and no import wrote. */+const databaseOnlyEdit = (engine: BrainEngine, slug: string, body: string) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(+ "UPDATE pages SET compiled_truth=$1, knowledge_revision=$2::uuid, revision_write_request_id=NULL WHERE source_id='default' AND slug=$3", [body, randomUUID(), slug]), TEST_WRITE_ATTRIBUTION));+/** A page written while write-through is off: a row with no file. */+async function databaseOnlyPage(brain: ManagedBrain, slug: string, content: string): Promise<void> {+ await brain.engine.setConfig('sync.write_through', 'false');+ try { await putPage.handler(brain.ctx, { slug, content, wait_ms: 30_000 }); } finally { await brain.engine.setConfig('sync.write_through', 'true'); }+}+const conversionCommits = (root: string, since: string) => git(root, 'log', '--reverse', '--format=@%s', '--name-only', `${since}..HEAD`).split('@').filter(Boolean)+ .map(entry => { const [subject, ...paths] = entry.trim().split('\n').filter(Boolean); return { subject, paths: paths.sort() }; });++async function cli(engine: BrainEngine, args: string[]): Promise<Record<string, any>> {+ const lines: string[] = [];+ const log = console.log, priorExitCode = process.exitCode;+ console.log = (line: unknown) => { lines.push(String(line)); };+ try { await runSourcesCanonical(engine, [...args, '--json']); } finally { console.log = log; _resetCliExitVerdictForTests(); process.exitCode = priorExitCode ?? 0; }+ return JSON.parse(lines.at(-1)!);+}++/** A Git effect parked on an ignored target, as an older gbrain left one (the census test's fixture, test/git-gap-census.test.ts). */+async function parkIgnoredEffect(engine: BrainEngine, slug: string, code = 'git_target_ignored'): Promise<void> {+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");+ // Already terminal (state failed), as a parked receipt is: no owner pass claims it.+ const [request] = await tx.executeRaw<{ id: string }>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,+ intent_bytes,terminal_reservation,state,completed_at) VALUES ('local_cli','test',$1::uuid,'put_page','default',$2::uuid,$3,'x','{}'::jsonb,0,16384,'failed',now()) RETURNING id::text`, [randomUUID(), incarnation, slug]);+ await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,state,error_code,source_id,source_incarnation) VALUES ($1::uuid,'git',$2::text::jsonb,'failed','targets_parked','default',$3::uuid)`,+ [request!.id, JSON.stringify({ parked: [{ slug, error_code: code, rule: '.gitignore:1: scratch/' }] }), incarnation]);+ });+}++const SLUGS = ['notes/same', 'notes/ahead', 'notes/gitmoved', 'notes/drift', 'notes/removed'];+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ // The door commits with the repository's own identity: CI runners have no global one.+ git(root, 'config', 'user.name', 'Example Writer'); git(root, 'config', 'user.email', '[email protected]');+ writeFileSync(join(root, '.gitignore'), 'scratch/\n');+ for (const slug of SLUGS) writeFileSync(join(root, `${slug}.md`), note(slug, `The committed body of ${slug}.`));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'notes');+};++const BULK = CONVERSION_GROUP_MAX + 1;+const bulkSetup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'bulk'), { recursive: true }); git(root, 'init', '-q');+ git(root, 'config', 'user.name', 'Example Writer'); git(root, 'config', 'user.email', '[email protected]');+ for (let i = 0; i < BULK; i++) writeFileSync(join(root, `bulk/p${String(i).padStart(3, '0')}.md`), note(`bulk/p${i}`, `Committed body ${i}.`));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'bulk');+};++/**+ * Every category on one non-strict source: notes/ahead and notes/dbonly hold content Git lacks (adopt); notes/secret is+ * private and scratch/ignored is under an ignored path whose Git effect parked (declared, reclassified); notes/gitmoved got+ * a commit sync has not read (git wins); notes/removed was deleted in Git after a database edit and notes/drift moved on+ * both sides without an import record (held, Git wins).+ */+async function mixedSource(brain: ManagedBrain): Promise<void> {+ const { engine, root } = brain;+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ for (const slug of ['notes/ahead', 'notes/drift', 'notes/removed']) await databaseOnlyEdit(engine, slug, `Written to the database alone: ${slug}.`);+ writeFileSync(join(root, 'notes/drift.md'), note('notes/drift', 'The committed edit of notes/drift.'));+ git(root, 'rm', '-q', 'notes/removed.md'); git(root, 'commit', '-qam', 'edit drift, remove removed');+ const [drift] = await engine.executeRaw<{ id: string }>("SELECT id::text FROM pages WHERE slug='notes/drift'");+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-import-provenance' AND fingerprint LIKE $1", [`default:%:${drift!.id}`]);+ await databaseOnlyPage(brain, 'notes/dbonly', note('notes/dbonly', 'Only in the database.'));+ await databaseOnlyPage(brain, 'notes/secret', note('notes/secret', 'A private note.', 'visibility: private\n'));+ await putPage.handler(brain.ctx, { slug: 'scratch/ignored', content: note('scratch/ignored', 'Under an ignored path.'), wait_ms: 30_000 });+ await parkIgnoredEffect(engine, 'scratch/ignored');+ await performManagedSync(engine, OPTS);+ expect(await holds(engine)).toEqual(['notes/drift.md file_drift', 'notes/removed.md file_drift']);+ writeFileSync(join(root, 'notes/gitmoved.md'), note('notes/gitmoved', 'The committed edit of notes/gitmoved.'));+ git(root, 'commit', '-qam', 'edit gitmoved');+}++for (const backend of testBackends()) describe(`[${backend}] G8a: sources canonical converts a source to git-canonical and back`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ test('a mixed source with every category converts with the right action for each', () => managedBrain(async brain => {+ const { engine, root } = brain;+ await mixedSource(brain);+ const base = git(root, 'rev-parse', 'HEAD');+ const before = await revisions(engine);+ const { preview } = await planGitConversion(engine, 'default');+ expect(preview).toMatchObject({ strict: false, adopt: { count: 2, groups: 1, by: { database_ahead: 1, undeclared_database_only: 1, worktree_only: 0 } },+ declared: { count: 2, by: { private: 1, git_ignored: 1 } }, git_wins: { count: 3, by: { git_ahead: 1, held_deletion: 1, held_drift_unknown: 1, deleted_by_commit: 0 } },+ holds: { count: 2, by: { 'file_drift:unknown': 1, 'file_drift:deleted': 1 } }, parked_effects: { count: 1, retry: 0, reclassify: 1 }, discard: { count: 0 } });+ expect(preview.adopt.sample.sort()).toEqual(['notes/ahead.md', 'notes/dbonly.md']);+ expect(await strict(engine)).toBe(false);+ expect(git(root, 'rev-parse', 'HEAD')).toBe(base);++ const result = await applyGitConversion(engine, 'default', preview.preview_hash, PROCESSING);+ expect(result).toMatchObject({ status: 'converted', committed: { groups: 1, pages: 2 }, holds_cleared: 2, parked: { reclassified: 1 }, after: { remaining: 0, strict: true } });+ expect(await strict(engine)).toBe(true);+ expect(conversionCommits(root, base)).toEqual([{ subject: 'gbrain: persist 2 canonical memory updates', paths: ['notes/ahead.md', 'notes/dbonly.md'] }]);+ expect(git(root, 'status', '--porcelain')).toBe('');+ expect(readFileSync(join(root, 'notes/ahead.md'), 'utf8')).toContain('Written to the database alone: notes/ahead.');+ const after = await revisions(engine);+ expect(after['notes/ahead']).toBe(before['notes/ahead']);+ expect(after['notes/dbonly']).toBe(before['notes/dbonly']);+ expect(after['notes/same']).toBe(before['notes/same']);+ expect((await page(engine, 'notes/gitmoved'))!.body).toContain('The committed edit of notes/gitmoved.');+ expect((await page(engine, 'notes/drift'))!.body).toContain('The committed edit of notes/drift.');+ expect((await page(engine, 'notes/removed'))!.deleted).toBe(true);+ expect((await page(engine, 'notes/secret'))!.deleted).toBe(false);+ // The page under an ignored path stays database-only (declared git_ignored): no file is written, no git_target_ignored round trip.+ expect((await page(engine, 'scratch/ignored'))!.deleted).toBe(false);+ expect(existsSync(join(root, 'scratch/ignored.md'))).toBe(false);+ expect(await holds(engine)).toEqual([]);+ const census = await censusGitGap(engine, 'default', { sample: 20 });+ expect(census.states).toMatchObject({ database_ahead: 0, git_ahead: 0, undeclared_database_only: 0, worktree_only: 0, unparseable: 0, unsafe_path: 0 });+ expect(census.declared).toMatchObject({ private: 1, git_ignored: 1 });+ const [record] = await engine.executeRaw<{ r: Record<string, unknown> }>("SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='git-canonical-conversion'");+ expect(record!.r).toMatchObject({ source_id: 'default', to: 'git', preview_hash: preview.preview_hash });++ // A G3 pass afterwards changes nothing.+ const settled = await revisions(engine);+ expect((await performManagedSync(engine, OPTS)).status).toBe('up_to_date');+ expect(await revisions(engine)).toEqual(settled);+ expect(git(root, 'log', '--format=%H', '-1')).toBe(git(root, 'rev-parse', 'HEAD'));+ expect((await planGitConversion(engine, 'default')).preview).toMatchObject({ strict: true, remaining: 0 });+ }, { databaseUrl, setup }), 240_000);++ test('a stale hash refuses preview_changed and writes nothing', () => managedBrain(async brain => {+ const { engine, root } = brain;+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await databaseOnlyEdit(engine, 'notes/ahead', 'Written to the database alone.');+ const base = git(root, 'rev-parse', 'HEAD');+ const preview = await cli(engine, ['default', '--to', 'git']);+ expect(preview).toMatchObject({ status: 'preview', adopt: { count: 1 } });+ const refused = await cli(engine, ['default', '--to', 'git', '--apply', '--expect', 'stale']);+ expect(refused).toMatchObject({ status: 'refused', code: 'preview_changed' });+ expect(git(root, 'rev-parse', 'HEAD')).toBe(base);+ expect(await strict(engine)).toBe(false);+ expect(readFileSync(join(root, 'notes/ahead.md'), 'utf8')).toContain('The committed body of notes/ahead.');+ }, { databaseUrl, setup }), 180_000);++ test('database content that would be discarded refuses by category and writes nothing', () => managedBrain(async brain => {+ const { engine, root } = brain;+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await databaseOnlyEdit(engine, 'notes/ahead', 'Written to the database alone.');+ const edit = note('notes/ahead', 'An uncommitted edit of notes/ahead.');+ writeFileSync(join(root, 'notes/ahead.md'), edit);+ const base = git(root, 'rev-parse', 'HEAD');+ const { preview } = await planGitConversion(engine, 'default');+ expect(preview).toMatchObject({ adopt: { count: 0 }, discard: { count: 1, by: { uncommitted_edit: 1 }, sample: ['notes/ahead.md'] } });+ await expect(applyGitConversion(engine, 'default', preview.preview_hash, PROCESSING)).rejects.toMatchObject({ code: 'git_conversion_blocked', detail: 'uncommitted_edit' });+ expect(git(root, 'rev-parse', 'HEAD')).toBe(base);+ expect(readFileSync(join(root, 'notes/ahead.md'), 'utf8')).toBe(edit);+ expect(await strict(engine)).toBe(false);+ expect((await page(engine, 'notes/ahead'))!.body).toContain('Written to the database alone.');+ }, { databaseUrl, setup }), 180_000);++ test('a crash after a group commit leaves the source non-strict, and a rerun completes once', () => managedBrain(async brain => {+ const { engine, root } = brain;+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await databaseOnlyEdit(engine, 'notes/ahead', 'Written to the database alone.');+ await databaseOnlyPage(brain, 'notes/dbonly', note('notes/dbonly', 'Only in the database.'));+ const base = git(root, 'rev-parse', 'HEAD');+ const first = (await planGitConversion(engine, 'default')).preview;+ installFaultHook(point => { if (point === 'conversion:group_committed') throw new Error('crash after the group commit'); });+ try { await expect(applyGitConversion(engine, 'default', first.preview_hash, PROCESSING)).rejects.toThrow('crash after the group commit'); }+ finally { installFaultHook(undefined); }+ expect(await strict(engine)).toBe(false);+ expect(conversionCommits(root, base)).toHaveLength(1);+ const rerun = (await planGitConversion(engine, 'default')).preview;+ expect(rerun.preview_hash).not.toBe(first.preview_hash);+ expect(rerun).toMatchObject({ adopt: { count: 0 }, discard: { count: 0 } });+ expect(await applyGitConversion(engine, 'default', rerun.preview_hash, PROCESSING)).toMatchObject({ status: 'converted', committed: { pages: 0 } });+ expect(await strict(engine)).toBe(true);+ expect(conversionCommits(root, base)).toEqual([{ subject: 'gbrain: persist 2 canonical memory updates', paths: ['notes/ahead.md', 'notes/dbonly.md'] }]);+ expect(git(root, 'status', '--porcelain')).toBe('');+ }, { databaseUrl, setup }), 180_000);++ test('more pages than one group commit one door commit per group, and the writer lock is free between groups', () => managedBrain(async brain => {+ const { engine, root } = brain;+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(+ "UPDATE pages SET compiled_truth=compiled_truth || ' Edited in the database.', knowledge_revision=gen_random_uuid(), revision_write_request_id=NULL WHERE source_id='default' AND slug LIKE 'bulk/%'"), TEST_WRITE_ATTRIBUTION));+ const base = git(root, 'rev-parse', 'HEAD');+ const { preview } = await planGitConversion(engine, 'default');+ expect(preview).toMatchObject({ adopt: { count: BULK, groups: 2 }, discard: { count: 0 } });+ const { binding } = await resolveManagedSyncContext(engine, { ...OPTS, dryRun: true });+ const free: boolean[] = [];+ installFaultHook(async point => {+ if (point !== 'conversion:group_committed') return;+ const lock = await acquireWorktree(binding, 1_000, undefined, engine, { yieldLanes: true });+ free.push(lock !== null);+ await lock?.release();+ });+ try { expect(await applyGitConversion(engine, 'default', preview.preview_hash, PROCESSING)).toMatchObject({ status: 'converted', committed: { groups: 2, pages: BULK } }); }+ finally { installFaultHook(undefined); }+ expect(free).toEqual([true, true]);+ const commits = conversionCommits(root, base);+ expect(commits.map(commit => [commit.subject, commit.paths.length])).toEqual([+ [`gbrain: persist ${CONVERSION_GROUP_MAX} canonical memory updates`, CONVERSION_GROUP_MAX], ['gbrain: persist canonical memory update', 1]]);+ expect(git(root, 'status', '--porcelain')).toBe('');+ }, { databaseUrl, setup: bulkSetup }), 300_000);++ test('work that lands after the strict-equivalent pass leaves the source strict and reports incomplete', () => managedBrain(async brain => {+ const { engine, root } = brain;+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await databaseOnlyEdit(engine, 'notes/ahead', 'Written to the database alone.');+ const base = git(root, 'rev-parse', 'HEAD');+ const preview = await cli(engine, ['default', '--to', 'git']);+ installFaultHook(async point => { if (point === 'conversion:before_flip') await parkIgnoredEffect(engine, 'notes/same', 'git_target_unsafe'); });+ let result: Record<string, any>;+ try { result = await cli(engine, ['default', '--to', 'git', '--apply', '--expect', preview.preview_hash, '--no-embed', '--no-extract']); }+ finally { installFaultHook(undefined); }+ expect(result).toMatchObject({ status: 'incomplete', code: 'git_conversion_incomplete', result: { status: 'incomplete', committed: { pages: 1 },+ after: { strict: true, remaining: 1, parked_effects: { retry: 1 } } } });+ expect(await strict(engine)).toBe(true);+ expect(conversionCommits(root, base)).toHaveLength(1);+ }, { databaseUrl, setup }), 180_000);++ test('--to mixed removes the flag and nothing else, and converting back commits nothing', () => managedBrain(async brain => {+ const { engine, root } = brain;+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await databaseOnlyEdit(engine, 'notes/ahead', 'Written to the database alone.');+ await applyGitConversion(engine, 'default', (await planGitConversion(engine, 'default')).preview.preview_hash, PROCESSING);+ const head = git(root, 'rev-parse', 'HEAD'), settled = await revisions(engine);+ const mixed = await planMixedConversion(engine, 'default');+ expect(mixed).toMatchObject({ to: 'mixed', strict: true });+ await expect(applyMixedConversion(engine, 'default', 'stale')).rejects.toMatchObject({ code: 'preview_changed' });+ expect(await applyMixedConversion(engine, 'default', mixed.preview_hash)).toEqual({ status: 'mixed', source_id: 'default' });+ expect(await strict(engine)).toBe(false);+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);+ expect(await revisions(engine)).toEqual(settled);+ const back = (await planGitConversion(engine, 'default')).preview;+ expect(back).toMatchObject({ strict: false, adopt: { count: 0 }, git_wins: { count: 0 }, discard: { count: 0 } });+ expect(await applyGitConversion(engine, 'default', back.preview_hash, PROCESSING)).toMatchObject({ status: 'converted', committed: { pages: 0, groups: 0 } });+ expect(await strict(engine)).toBe(true);+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);+ }, { databaseUrl, setup }), 180_000);++ test('a remote caller cannot convert or run the strict-equivalent pass, and no MCP operation exposes it', () => managedBrain(async ({ engine }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ expect(operations.filter(op => /canonical|conversion/.test(op.name)).map(op => op.name)).toEqual([]);+ const remote = <T>(fn: () => Promise<T>) => withSubmissionAuthority({ version: 1, kind: 'remote_generic' } as never, fn);+ expect(await remote(() => cli(engine, ['default', '--to', 'git']))).toMatchObject({ status: 'refused', code: 'permission_denied', reason: 'trusted_cli_required' });+ await expect(remote(() => resolveManagedSyncContext(engine, { ...OPTS, full: true, canonicalOverride: 'git' }))).rejects.toMatchObject({ code: 'permission_denied' });+ expect(await strict(engine)).toBe(false);+ }, { databaseUrl, setup }), 180_000);++ test('an unmanaged brain refuses strict_requires_managed', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-g8a-unmanaged-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await cli(engine, ['default', '--to', 'git'])).toMatchObject({ status: 'refused', code: 'strict_requires_managed' });+ expect(await strict(engine)).toBe(false);+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ }, 120_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 4d9bfb6075..86f8c2b774 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -79,6 +79,7 @@ test/file-drift-soft-delete-hold-release-gbra133.test.tstest/forecast-journal.test.tstest/frontmatter-reserved-keys-6454.test.tstest/get-chunks-paging.test.ts+test/git-canonical-conversion-g8a.test.tstest/git-canonical-declared-g7a.test.tstest/git-canonical-indexer-g3.test.tstest/git-door-plumbing-gbra133.test.tsdiff --git a/test/sync-classify-strict-g3.test.ts b/test/sync-classify-strict-g3.test.tsindex d8e1efd8a1..99082381d7 100644--- a/test/sync-classify-strict-g3.test.ts+++ b/test/sync-classify-strict-g3.test.ts@@ -41,6 +41,12 @@ describe('G3: Git wins on a strict source', () => {expect(strict(settledKeep)).toMatchObject({ cls: 'import', action: 'import', gitWins: 'db_ahead' });});+ test('a page no import record proves imports the commit (G8a: the unknown side of a held drift after conversion clears it)', () => {+ const legacy = { ...base, baseline: 'B', record: null, page: { live: true, revision: 'R2', originMatches: true } };+ expect(classifySyncPath(legacy)).toMatchObject({ cls: 'legacy_unverified', settled: true });+ expect(strict(legacy)).toMatchObject({ cls: 'import', action: 'import', settled: false, gitWins: 'legacy_unverified' });+ });+test('an edited tombstone imports the committed file', () => {const tombstone = { ...gitMoved, page: { live: false, revision: 'R1', originMatches: true } };expect(classifySyncPath(tombstone)).toMatchObject({ cls: 'deleted_edited', action: 'hold' });