Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-217 A2: sync mirrors gbrain-reason trailers into page history; purge redacts and tombstones reasons
garrytan0da862144b01
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 6eafb98264..39475e75d2 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -15,6 +15,7 @@ Under contract v1 an `error` value never changes. Where a surface sends a legacy| `error` (frozen) | `code` (canonical) | Meaning ||---|---|---|+| `invalid_params` | `change_reason_rejected` | The write's reason was refused before anything was admitted: it is longer than 500 characters, or it looks like it holds a secret. || `invalid_params` | `fact_withdrawn` | `remember`, or an owner `gbrain trust release` that writes a held fact into its entity page's `## Facts` table (a managed brain), refused a claim that was explicitly forgotten for this subject (wire `invalid_params`, message prefix `fact_withdrawn:`); nothing was saved, and a refused release leaves the fact held. || `permission_denied` | `insufficient_scope` | The connection lacks the OAuth scope the operation requires. || `invalid_params` | `invalid_fence` | A facts or takes fence in the page cannot be imported without dropping or guessing rows, so the page (or the file) was not written. |@@ -509,6 +510,18 @@ More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../|---|---|---|---|---|---|---|| Shared skill storage is not ready on this brain. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### change_reason_rejected++<a id="change_reason_rejected"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The write's reason was refused before anything was admitted: it is longer than 500 characters, or it looks like it holds a secret. | A reason is kept in page history and, on a page that reaches Git, in the commit message, which a push makes permanent; it is checked before the write is journaled so no copy of a refused reason is stored anywhere. | Shorten the reason, or remove the secret from it, and send the write again. | agent | `repeat the read that failed` | 1 | no |++Reasons: `reason_too_long`, `reason_contains_secret`.++More: [docs/guides/page-history.md#reasons](../../docs/guides/page-history.md#reasons)+### changed_since_preview<a id="changed_since_preview"></a>@@ -3353,6 +3366,56 @@ More: [docs/guides/graph-ranking.md#rank_entities_timeout](../../docs/guides/graMore: [docs/guides/dream-patterns.md#child-read-budget](../../docs/guides/dream-patterns.md#child-read-budget)+### reason_purge_scan_capped++<a id="reason_purge_scan_capped"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A fact purge stopped before deleting anything: the source's Git history has more commits than the purge reads (200,000) when it looks for change reasons quoting the claim. | Purge tombstones every commit whose gbrain-reason trailer quotes the claim, so no later sync or re-import stores that reason again. Past the limit it cannot say which older commits do, so the user decides. | Ask the user: purge now and check only the newest commits (--reason-scan-limit <n>, their choice; older commits are not tombstoned), or stop. | user | `repeat the read that failed` | 3 | no |++More: [docs/guides/page-history.md#purge-and-reasons](../../docs/guides/page-history.md#purge-and-reasons)++### reason_purge_scan_failed++<a id="reason_purge_scan_failed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A fact purge stopped before deleting anything: reading the change reasons in the source's Git history failed (a Git error or a timeout). | Purge reads the reason trailers that quote the claim before it changes anything, so it can tombstone them; nothing was removed, so retrying is safe. | Wait, then run the same purge again. | agent | `repeat the read that failed` | 1 | yes |++More: [docs/guides/page-history.md#purge-and-reasons](../../docs/guides/page-history.md#purge-and-reasons)++### reason_scan_capped++<a id="reason_scan_capped"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A sync imported its files but did not read their change reasons from Git: the range held more than 10,000 commits. Each reason in the pass is stored as empty and each page it changed is marked with a history gap. | Reasons are metadata, so content import never waits on them. The pass still advances last_commit and this release does not backfill reasons for that range; they stay in Git. | Nothing to repair. The reasons for the range are in Git: git log --first-parent <range> shows them. | agent | `gbrain doctor --json` | 1 | no |++More: [docs/guides/page-history.md#reasons-from-git](../../docs/guides/page-history.md#reasons-from-git)++### reason_scan_failed++<a id="reason_scan_failed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A sync imported its files but could not read their change reasons from Git (a Git error or a timeout). Each reason in the pass is stored as empty and each page it changed is marked with a history gap. | Reasons are metadata, so content import never waits on them. The pass still advances last_commit and this release does not backfill reasons for that range; they stay in Git. | Nothing to repair. The reasons for the range are in Git: git log --first-parent <range> shows them. | agent | `gbrain doctor --json` | 1 | no |++More: [docs/guides/page-history.md#reasons-from-git](../../docs/guides/page-history.md#reasons-from-git)++### reason_trailer_secret++<a id="reason_trailer_secret"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A gbrain-reason trailer already pushed to Git looks like it holds a secret; sync stored no reason for that commit and path. | A secret in a reason is refused at write time; a commit made outside gbrain can still carry one. Git history keeps commit messages, so the credential stays exposed until it is rotated. | Rotate the credential the notice names (by commit and path); the brain stores nothing of it. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/guides/page-history.md#reasons-from-git](../../docs/guides/page-history.md#reasons-from-git)+### receipt_conflict<a id="receipt_conflict"></a>diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 8d7f94c1d3..d0d5c73278 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -48,6 +48,7 @@ src/core/minions/queue.ts MinionQueue.add>result=this.engine.transaction(#0) 359src/core/minions/worker.ts MinionWorker.start 470 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/ops/facts.ts recall.handler 357 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #4830 (W14 PR3): every hit names its source_id, falling back to the scope's single source (the federated case stays absent); +3 W5: recall threads the page-unit ranking cut into its hybrid page arm (logic in search/page-rank-cut.ts; delivery reports it); +3 #7043: copies of one claim collapse before the limit cut (the collapse lives in facts/capture-dedup.ts collapseFactReads) and the row names its entity_slugs/collapsed_countsrc/core/ops/search.ts query.handler 338 +5 GBRA-81 item 5 per-stage search timings: the request's SearchTimings and setup-stage binding, the image branch's limit read hoisted out of the timed vector call, and its response stage wrapper (collector logic in search/stage-timings.ts); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 GBRA-49 explain_target: one TargetTrace prep line and its HybridSearchOpts thread (diagnosis/meta live in prepareExplainTarget/finishExplainTarget); +1 W5 (#6445): query passes the page-unit ranking cut to hybrid search (logic in search/page-rank-cut.ts), merged with master growth+src/core/persistence/sync-prepare.ts prepareSyncMutation 301 TODO GBRA-217: +1 the change-reason lookup for a file whose page exists (logic in persistence/sync-reasons.ts managedFileHistory); new row at 301src/core/progressive-batch/orchestrator.ts runProgressiveBatch 348 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/remediation/run.ts runRemediation 428 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/skillopt/orchestrator.ts runOptimizationLoop 704 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bfa01bceb3..f0218e0d5b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -12,12 +12,12 @@ 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 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/commands/sync.ts 559 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); +3 GBRA-217: SyncResult.reason_notices / reason_trailers_malformed interface fields and their doc line (the scan lives in core/reason-trailers.ts, the pass wiring in commands/sync/reasons.ts)src/core/cycle.ts 3345 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 list; +7 #7630 (GBRA-207): the sync phase refuses sync_anchor_relative when no source matches its directory and default's local_path is relativesrc/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 guardsrc/core/engine.ts 2866 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move; +1 GBRA-161 PR 2: deprecation notes on insertFacts({ deleteForPageFirst }), deleteFactsForPage and expireFact (interface docs cannot move); +7 GBRA-156: TransactionOptions.pipelineEarly (search read bodies go out behind BEGIN; predicate in postgres-engine/search-settings.ts); interface fields cannot move; +2 GBRA-156: TransactionOptions.readOnly (search read transactions open BEGIN READ ONLY; 2858 measured); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); re-summed at the Wave B PR 4 merge with v0.60.452.0 (2866 measured)-src/core/import-file.ts 2075 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation; +9 #7172: kept chunk rows move to their new index and a bounded managed publication defers its chunk replacement (logic in page-state/chunk-moves.ts and page-state/projections.ts continueDeferredProjection); merge v0.60.332.0: #7172 and master growth compose at 2075+src/core/import-file.ts 2076 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation; +9 #7172: kept chunk rows move to their new index and a bounded managed publication defers its chunk replacement (logic in page-state/chunk-moves.ts and page-state/projections.ts continueDeferredProjection); merge v0.60.332.0: #7172 and master growth compose at 2075; +2 GBRA-217: the importFromContent / importFromFile history option interface fields (the reason and history-gap marker a sync import stamps; logic in core/reason-trailers.ts and page-state/versions.ts)src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 245 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import; +1 GBRA-156: whois import (ops/whois.ts; spread shares the chunks line)src/core/pglite-engine.ts 3097 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); +2 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity with an orFallback rank parameter like Postgres (logic in search/keyword-or-rarity.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3097 measured)@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap insrc/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeoutsrc/core/config.ts 2012 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured)-src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts)+src/core/persistence/sync-run.ts 1687 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 GBRA-217: the import of persistence/sync-reasons.ts, where the managed pass reason notices livesrc/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 728 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts)diff --git a/src/cli/flag-equals.ts b/src/cli/flag-equals.tsindex 5bc6513770..5f9c9b8254 100644--- a/src/cli/flag-equals.ts+++ b/src/cli/flag-equals.ts@@ -109,7 +109,7 @@ export const EQUALS_READERS: Readonly<Record<string, readonly string[]>> = {// recall.ts:1183-1188 runForget (plain) and forget-purge.ts:44 flagValue (:114-123, purge); --match is purge-only, ignored by plain forget in any form.forget: ['--request-id', '--source', '--match'],// forget-purge.ts:131 flagValue --reason (runForgetPurge, routed on --purge at recall.ts:1170); plain forget reads only the separate token (recall.ts:1181).- 'forget --purge': ['--reason'],+ 'forget --purge': ['--reason', '--reason-scan-limit'],// frontmatter.ts:356 runValidate.'frontmatter validate': ['--path'],// frontmatter.ts:667 runAudit.diff --git a/src/commands/forget-purge.ts b/src/commands/forget-purge.tsindex bc3ecef5e5..29df123c68 100644--- a/src/commands/forget-purge.ts+++ b/src/commands/forget-purge.ts@@ -3,7 +3,7 @@* owner-only `purge_fact` operation.** gbrain forget <id> --purge [--dry-run] [--yes --request-id <uuid>] [--reason <text>]- * [--all-subjects] [--vacuum] [--source <id>] [--json]+ * [--all-subjects] [--vacuum] [--reason-scan-limit <n>] [--source <id>] [--json]* gbrain forget --purge --match "<text>" # list candidate ids; never purges* gbrain forget --purge --status --request-id <uuid> [--continue] # completion of an earlier purge; --continue resumes its derivation sweep*@@ -35,7 +35,7 @@ export const PURGE_FAMILY_HELP = `Purge family (remove content from live stores;const USAGE = `Usage: gbrain forget <fact-id> [--reason <text>] [--source <id>] [--request-id <uuid>] [--json](withdraws the fact: it expires and cannot be re-saved; the text stays in history and backups)- gbrain forget <fact-id> --purge [--dry-run] [--yes --request-id <uuid>] [--reason <text>] [--all-subjects] [--vacuum] [--source <id>] [--json]+ gbrain forget <fact-id> --purge [--dry-run] [--yes --request-id <uuid>] [--reason <text>] [--all-subjects] [--vacuum] [--reason-scan-limit <n>] [--source <id>] [--json]gbrain forget --purge --match "<text>"gbrain forget --purge --status --request-id <uuid> [--continue]@@ -129,7 +129,9 @@ export async function runForgetPurge(engine: BrainEngine | (() => Promise<BrainE}if (!idArg) { process.stderr.write(USAGE); setCliExitVerdict(1); return; }const reason = flagValue(args, '--reason');- const base = { id: Number(idArg), ...(reason !== undefined ? { reason } : {}), ...(args.includes('--all-subjects') ? { all_subjects: true } : {}) };+ const scanLimit = flagValue(args, '--reason-scan-limit');+ const base = { id: Number(idArg), ...(reason !== undefined ? { reason } : {}), ...(args.includes('--all-subjects') ? { all_subjects: true } : {}),+ ...(scanLimit !== undefined ? { reason_scan_limit: Number(scanLimit) } : {}) };const dry = await invoke({ ...base, dry_run: true });if (args.includes('--dry-run')) { out(dry, renderPurgeReceipt(dry)); return; }const token = String(dry.confirm_token);diff --git a/src/commands/import.ts b/src/commands/import.tsindex a0f357626b..b4f993c750 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -265,7 +265,7 @@ export async function runImport(args: string[],opts: {signal?: AbortSignal;- commit?: string;+ commit?: string; /** GBRA-217: a full sync's reason and history-gap note per file (absolute path) for the snapshot its import archives. */ history?: (filePath: string) => import('../core/page-state/versions.ts').VersionHistory | undefined;strategy?: SyncStrategy;sourceId?: string;managedBookmark?: boolean;@@ -741,7 +741,7 @@ export async function runImport(? await importManagedFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack, signal, slugRoot: opts.slugRoot }): isImageFilePath(relativePath) && process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true'? await importImageFile(eng, filePath, importRelPath, { noEmbed, sourceId })- : await importFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack, bodyPolicy, firstCommitAt: firstCommits?.get(filePath) });+ : await importFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack, bodyPolicy, firstCommitAt: firstCommits?.get(filePath), history: opts.history?.(filePath) });// An import that landed while cancellation arrived is still complete.// Account for it before stopping, so resume never loses a successful path.noteTypeWarning((result as { type_warning?: Parameters<typeof noteTypeWarning>[0] }).type_warning); fenceTally.note(importRelPath, result);diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 0e893801b6..a748cc14db 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -73,6 +73,9 @@ export interface SyncResult {fileRefusals?: import('../core/persistence/sync-discovery.ts').SyncFileRefusal[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction; /** #6729: inexact renames split into delete + add; once recorded each is an IdentityDowngrade (old slug, what stayed on it). */ identityDowngrades?: Array<import('../core/sync.ts').DowngradedRename | import('../core/sync-identity-downgrades.ts').IdentityDowngrade>;/** #6712 PR 2 (L5): the owed post-checkpoint tail (statistics, links) this call ran after releasing the lease; a degraded tail carries its notice. */tail?: Omit<import('../core/persistence/sync-tail.ts').SyncTailReport, 'links'>;+ /** GBRA-217: the pass's change-reason notices (a failed or capped trailer scan, a secret in a pushed trailer) and its count of skipped malformed trailers. */+ reason_notices?: import('../core/agent-output.ts').Notice[];+ reason_trailers_malformed?: number;/** #5459 (P4.5): live pages a `--full` tree walk kept because their file is in the working tree and their import provenance is the working tree or unknown. */working_tree_kept?: number;/**diff --git a/src/commands/sync/full.ts b/src/commands/sync/full.tsindex bffbcca8b3..6159834ccd 100644--- a/src/commands/sync/full.ts+++ b/src/commands/sync/full.ts@@ -52,6 +52,7 @@ import type { SyncOpts, SyncResult } from '../sync.ts';import { heldRenameOrigins, holdRefusedImport, moveHeldRenames, noteScreenedImport, settleFullSyncHolds, wouldHoldFields, type LegacyHolds } from './holds.ts';import { sweepOrphanedRenameSentinels } from './rename-reconcile.ts';import { classifyItemFailure } from '../../core/item-failure.ts';+import { fileHistory, scanClassicReasons, withReasonNotices } from './reasons.ts';import { OperationError } from '../../core/ops/contract.ts';export async function performFullSync(@@ -113,11 +114,17 @@ export async function performFullSync(serr(`[gbrain phase] sync.fullsync.import start strategy=${opts.strategy ?? 'markdown'}`);opts.onProgress?.({ phase: 'full_import' });await moveHeldRenames(engine, holds, holdRoot);+ // GBRA-217: a re-import of a source that already has pages reads its reasons from the whole history (a first sync creates+ // every page, so it archives no snapshot to annotate and runs no scan).+ const [known] = await engine.executeRaw<{ any: boolean }>('SELECT EXISTS (SELECT 1 FROM pages WHERE source_id = $1) AS any', [opts.sourceId ?? 'default']);+ const reasons = await scanClassicReasons(engine, { sourceId: opts.sourceId, company, anchorPath, from: null, to: headCommit,+ imports: known?.any === true ? 1 : 0 });let result: import('../import.ts').RunImportResult;try {result = await runImport(engine, importArgs, {signal: opts.signal,commit: headCommit,+ history: filePath => fileHistory(reasons, filePath),strategy: opts.strategy,sourceId: opts.sourceId,exclude: opts.exclude,@@ -195,7 +202,7 @@ export async function performFullSync(// that throws never clears anything, and the sweep carries the full// clear-then-verify-restore semantics.await sweepOrphanedRenameSentinels(engine, fullSourceId, fullFailureSet);- if (!fullGate.advanced) return await reportBlockedFullSync(engine, opts, anchorPath, headCommit, result, fullGate);+ if (!fullGate.advanced) return withReasonNotices(await reportBlockedFullSync(engine, opts, anchorPath, headCommit, result, fullGate), reasons, opts.sourceId);if (fullGate.acknowledged > 0) {serr(` Acknowledged ${fullGate.acknowledged} failure(s) and advanced past them.`);}@@ -240,7 +247,7 @@ export async function performFullSync(const { readPageSizeStates, addSizeState } = await import('../../core/page-embedding-budget.ts');const sizeStates = (await readPageSizeStates(engine, fullSourceId, null)).reduce<import('../../core/page-embedding-budget.ts').SyncSizeStates | undefined>((tally, state) => addSizeState(tally, state), undefined);- return {+ return withReasonNotices({status: 'first_sync',fromCommit: null,toCommit: headCommit,@@ -258,7 +265,7 @@ export async function performFullSync(...(result.malformedSkipped ? { malformedSkipped: result.malformedSkipped } : {}),...(result.type_warnings ? { type_warnings: result.type_warnings } : {}),...(result.resealed ? { resealed: result.resealed } : {}),- };+ }, reasons, opts.sourceId);}async function fullSyncDryRun(engine: BrainEngine, syncScopeRoot: string, headCommit: string, opts: SyncOpts & { metafilePages: MetafilePagesMode },diff --git a/src/commands/sync/imports.ts b/src/commands/sync/imports.tsindex 4bd7b91a65..24ec98fe94 100644--- a/src/commands/sync/imports.ts+++ b/src/commands/sync/imports.ts@@ -33,10 +33,11 @@ import type { SyncOpts, SyncResult } from '../sync.ts';import { clearLegacyHold, holdClassicFile, holdRefusedImport, noteScreenedImport, type LegacyHolds } from './holds.ts';import { classifyClassicFile } from '../../core/classic-file-holds.ts';import { partial, markCompleted, noteTypeWarning, maybeYield } from './sync-run.ts';+import { fileHistory } from './reasons.ts';import type { SyncPlan, SyncProgress, SyncRun } from './sync-run.ts';import { noteCommittedProgress } from '../../core/forward-progress.ts';-type ImportPlan = Pick<SyncPlan, 'opts' | 'filtered' | 'lastCommit' | 'pin' | 'company' | 'gitContextRoot' | 'syncImportRoot' | 'syncActivePack' | 'holds'>;+type ImportPlan = Pick<SyncPlan, 'opts' | 'filtered' | 'lastCommit' | 'pin' | 'company' | 'gitContextRoot' | 'syncImportRoot' | 'syncActivePack' | 'holds' | 'reasons'>;type ImportContext = {opts: SyncOpts;@@ -49,6 +50,7 @@ type ImportContext = {progressAt: { last: number };progress: SyncProgress;holds: LegacyHolds | null;+ reasons: SyncPlan['reasons'];};/** The add/modify drain. Returns a partial result when the run aborts. */@@ -59,7 +61,7 @@ export async function runImportsPhase(noEmbed: boolean,): Promise<SyncResult | undefined> {const { engine, completed } = run;- const { filtered, company, gitContextRoot, syncImportRoot, syncActivePack, holds } = plan;+ const { filtered, company, gitContextRoot, syncImportRoot, syncActivePack, holds, reasons } = plan;let { opts } = plan;// Process adds and modifies.//@@ -117,7 +119,7 @@ export async function runImportsPhase(opts = watchdog.opts;const { stallTimer, progressAt } = watchdog;- const ctx: ImportContext = { opts, company, gitContextRoot, syncRepoPath, syncActivePack, noEmbed, pacer, progressAt, progress, holds };+ const ctx: ImportContext = { opts, company, gitContextRoot, syncRepoPath, syncActivePack, noEmbed, pacer, progressAt, progress, holds, reasons };const aborted = await drainImports(run, plan, ctx, importsToDo, effectiveConcurrency, runParallel, stallTimer);if (aborted) return aborted;@@ -267,7 +269,7 @@ export function poolLine(engine: unknown): string {/** Core import logic shared by the serial and parallel paths. */async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine, path: string): Promise<void> {const { failedFiles, succeededPaths, pagesAffected, deletedSlugs } = run;- const { opts, company, gitContextRoot, syncRepoPath, syncActivePack, noEmbed, pacer, progressAt, progress, holds } = ctx;+ const { opts, company, gitContextRoot, syncRepoPath, syncActivePack, noEmbed, pacer, progressAt, progress, holds, reasons } = ctx;// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- `path` is a git-diff path from the synced repo (repo content can be hostile), but the joined path is checked by isPathSafe(filePath, gitContextRoot) realpath containment below before any readconst filePath = join(syncRepoPath, path);// #5032: Windows cannot store ':' in a file name (it names an alternate data@@ -353,7 +355,7 @@ async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine,const result = await observed(pacer, () =>isImageImportPath(path) && process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true'? importImageFile(eng, filePath, path, { noEmbed, sourceId: opts.sourceId })- : company ? importCompanyBrainFile(eng, filePath, opts.sourceId!) : importFile(eng, filePath, path, { noEmbed, sourceId: opts.sourceId, activePack: syncActivePack }));+ : company ? importCompanyBrainFile(eng, filePath, opts.sourceId!) : importFile(eng, filePath, path, { noEmbed, sourceId: opts.sourceId, activePack: syncActivePack, history: fileHistory(reasons, filePath) }));noteTypeWarning(run, result.type_warning);noteScreenedImport(holds, path, result);if (await holdRefusedImport(eng, holds, path, filePath, result)) {diff --git a/src/commands/sync/incremental.ts b/src/commands/sync/incremental.tsindex 92da35b19c..e057c49c9a 100644--- a/src/commands/sync/incremental.ts+++ b/src/commands/sync/incremental.ts@@ -17,7 +17,8 @@ import { runImportsPhase } from './imports.ts';import { preflightIncrementalSync } from './preflight.ts';import { runRenamesPhase } from './renames.ts';import { readUpstreamDivergence, type UpstreamResultField } from '../../core/sync-upstream-rewrite.ts';-import { createSyncRun, abortUnpersistedPin, registerCheckpointCleanup } from './sync-run.ts';+import { createSyncRun, abortUnpersistedPin, registerCheckpointCleanup, type SyncPlan } from './sync-run.ts';+import { scanClassicReasons, withReasonNotices } from './reasons.ts';export async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SyncResult & UpstreamResultField> {// #5988: content refusals are held, not failed; every exit reports the holds.@@ -30,9 +31,20 @@ export async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Proasync function runSyncPhases(engine: BrainEngine, opts: SyncOpts, holds: LegacyHolds | null): Promise<SyncResult> {const pre = await preflightIncrementalSync(engine, opts, holds);if ('done' in pre) return pre.done;- const { plan } = pre;- const { totalChanges, ckpt, pin } = plan;- opts = plan.opts;+ const plan = await withPassReasons(engine, pre.plan);+ return withReasonNotices(await runPlannedPhases(engine, plan), plan.reasons, plan.opts.sourceId);+}++/** GBRA-217: the pass's one reason-trailer scan over `last_commit..pin`, when it imports or renames files. */+async function withPassReasons(engine: BrainEngine, plan: SyncPlan): Promise<SyncPlan> {+ const { filtered } = plan;+ const reasons = await scanClassicReasons(engine, { sourceId: plan.opts.sourceId, company: plan.company, anchorPath: plan.anchorPath,+ from: plan.lastCommit, to: plan.pin, imports: filtered.added.length + filtered.modified.length + filtered.renamed.length });+ return { ...plan, reasons };+}++async function runPlannedPhases(engine: BrainEngine, plan: SyncPlan): Promise<SyncResult> {+ const { opts, totalChanges, ckpt, pin } = plan;const swept = await sweepUnsyncableModified(engine, plan);diff --git a/src/commands/sync/reasons.ts b/src/commands/sync/reasons.tsnew file mode 100644index 0000000000..59f437bc3d--- /dev/null+++ b/src/commands/sync/reasons.ts@@ -0,0 +1,24 @@+/**+ * GBRA-217 (A6): a classic sync pass mirrors page change reasons from Git. One trailer scan per pass over the range it+ * imports (`last_commit..pin` incremental, the whole history for a full re-import), run only when the pass imports+ * files; each imported file's snapshot then carries its newest first-parent commit's reason (`importHistoryFor`).+ */+import type { BrainEngine } from '../../core/engine.ts';+import { reasonScanNotices, scanSyncReasons, type SyncReasonScan } from '../../core/reason-trailers.ts';+import type { SyncResult } from '../sync.ts';++export { importHistoryFor as fileHistory } from '../../core/reason-trailers.ts';++/** The pass's scan, or null when it imports nothing or the source is a company brain (its pinned revision is not annotated). */+export async function scanClassicReasons(engine: BrainEngine, input: { sourceId: string | undefined; company: unknown; anchorPath: string;+ from: string | null; to: string; imports: number }): Promise<SyncReasonScan | null> {+ if (input.company || input.imports === 0) return null;+ return scanSyncReasons(engine, { sourceId: input.sourceId ?? 'default', sourceRoot: input.anchorPath, from: input.from, to: input.to });+}++/** The result with the pass's reason notices (a failed or capped scan, secrets in pushed trailers), when there are any. */+export function withReasonNotices(result: SyncResult, scan: SyncReasonScan | null | undefined, sourceId: string | undefined): SyncResult {+ const notices = reasonScanNotices(scan, sourceId ?? 'default');+ return { ...result, ...(notices.length ? { reason_notices: [...(result.reason_notices ?? []), ...notices] } : {}),+ ...(scan?.malformed ? { reason_trailers_malformed: scan.malformed } : {}) };+}diff --git a/src/commands/sync/renames.ts b/src/commands/sync/renames.tsindex 8ea49c4e7b..458c586b92 100644--- a/src/commands/sync/renames.ts+++ b/src/commands/sync/renames.ts@@ -34,12 +34,13 @@ import type { TrackedSlugIndex } from './rename-reconcile.ts';import { clearLegacyHold, holdRefusedImport, holdRenameDestination, noteScreenedImport, recordLegacyHold, type LegacyHolds } from './holds.ts';import { classifyItemFailure } from '../../core/item-failure.ts';import { partial, noteTypeWarning, markCompleted } from './sync-run.ts';+import { fileHistory } from './reasons.ts';import type { SyncPlan, SyncRun, SyncProgress } from './sync-run.ts';import { noteCommittedProgress } from '../../core/forward-progress.ts';import { recordFallbackRename } from '../../core/belief/identity.ts';import { markBeliefCommits } from '../../core/belief/append.ts';-type RenamePlan = Pick<SyncPlan, 'opts' | 'filtered' | 'manifest' | 'lastCommit' | 'pin' | 'gitContextRoot' | 'modePath' | 'syncImportRoot' | 'syncActivePack' | 'holds'>;+type RenamePlan = Pick<SyncPlan, 'opts' | 'filtered' | 'manifest' | 'lastCommit' | 'pin' | 'gitContextRoot' | 'modePath' | 'syncImportRoot' | 'syncActivePack' | 'holds' | 'reasons'>;type RenameContext = {renameOpts: { sourceId: string } | undefined;@@ -212,7 +213,7 @@ async function applyRename(identityHead?: string,): Promise<SyncResult | undefined> {const { engine, failedFiles, succeededPaths, pagesAffected, deletedSlugs } = run;- const { opts, gitContextRoot, syncImportRoot, syncActivePack, holds } = plan;+ const { opts, gitContextRoot, syncImportRoot, syncActivePack, holds, reasons } = plan;const { renameOpts, fromSlugByPath, noEmbed } = ctx;// v0.41.13.0 (T2 / D-V4-2): per-iteration abort check. Renames call// importFile() at line 1173-style sites which can be slow on big files;@@ -304,7 +305,7 @@ async function applyRename(// through importFile threw UTF-8 errors). Same gate as import.ts.const result = isImageImportPath(to) && process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true'? await importImageFile(engine, filePath, to, { noEmbed, sourceId: opts.sourceId })- : await importFile(engine, filePath, to, { noEmbed, sourceId: opts.sourceId, activePack: syncActivePack });+ : await importFile(engine, filePath, to, { noEmbed, sourceId: opts.sourceId, activePack: syncActivePack, history: fileHistory(reasons, filePath) });importResult = result;noteTypeWarning(run, result.type_warning);noteScreenedImport(holds, to, result);diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex d37223ebd9..5f3801df61 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -70,20 +70,22 @@ async function syncCapacityNotices(engine: BrainEngine, json: boolean, result?:const { capacityNotices, CAPACITY_READ_WAIT_MS } = await import('../../core/persistence/capacity-snapshot.ts');// #6712 PR 2 (L5): a degraded post-checkpoint tail rides the same notices. #6803 C4: the snapshot wait is bounded.const capacity = await capacityNotices(engine, { throttle: true, deadlineAt: Date.now() + CAPACITY_READ_WAIT_MS }).catch(() => []);- const notices = [...(result?.tail?.notice ? [result.tail.notice] : []), ...capacity].map(notice => renderNotice(notice, cliRenderContext()));+ const notices = [...(result?.tail?.notice ? [result.tail.notice] : []), ...(result?.reason_notices ?? []), ...capacity].map(notice => renderNotice(notice, cliRenderContext()));if (!json) for (const notice of notices) process.stderr.write(`[gbrain notice ${notice.code}] ${notice.why}\n`);return notices.length ? { notices } : {};}/** #6712 PR 2 (L5): one source's post-checkpoint tail in a `sync --all` receipt: its report and its rendered degraded notice. */function syncTailJsonFields(result: SyncResult): { tail?: Omit<NonNullable<SyncResult['tail']>, 'notice'>; notices?: unknown[] } {- if (!result.tail) return {};- const { notice, ...tail } = result.tail;- return { tail, ...(notice ? { notices: [renderNotice(notice, cliRenderContext())] } : {}) };+ const notices = [...(result.tail?.notice ? [result.tail.notice] : []), ...(result.reason_notices ?? [])].map(n => renderNotice(n, cliRenderContext()));+ const rendered = notices.length ? { notices } : {};+ if (!result.tail) return rendered;+ const { notice: _notice, ...tail } = result.tail;+ return { tail, ...rendered };}function printTailNotice(result: SyncResult): void {- if (result.tail?.notice) process.stderr.write(`[gbrain notice ${result.tail.notice.code}] ${result.tail.notice.why}\n`);+ for (const notice of [...(result.tail?.notice ? [result.tail.notice] : []), ...(result.reason_notices ?? [])]) process.stderr.write(`[gbrain notice ${notice.code}] ${notice.why}\n`);}export async function runSyncInner(engine: BrainEngine, args: string[]) {diff --git a/src/commands/sync/sync-run.ts b/src/commands/sync/sync-run.tsindex 8d15021b40..053d8f2e6b 100644--- a/src/commands/sync/sync-run.ts+++ b/src/commands/sync/sync-run.ts@@ -79,6 +79,8 @@ export interface SyncPlan {readonly holds: LegacyHolds | null;/** GBRA-133: gitlinks that appeared in this run's range (reported once, never followed). */readonly gitlinks: string[];+ /** GBRA-217: the pass's reason-trailer scan (null when it imports nothing); set after preflight, read by the import and rename drains. */+ readonly reasons?: import('../../core/reason-trailers.ts').SyncReasonScan | null;}export interface SyncRun {diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex b441be94f8..a31686773e 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -67,7 +67,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--held', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--retry-held', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],'feedback': ['--brain', '--help', '--json', '--page', '--source'],'files': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--timings', '--type', '--wait', '--yes'],- 'forget': ['--all-subjects', '--brain', '--continue', '--dry-run', '--help', '--json', '--match', '--purge', '--reason', '--request-id', '--source', '--status', '--vacuum', '--yes'],+ 'forget': ['--all-subjects', '--brain', '--continue', '--dry-run', '--help', '--json', '--match', '--purge', '--reason', '--reason-scan-limit', '--request-id', '--source', '--status', '--vacuum', '--yes'],'founder': ['--brain', '--help', '--json', '--mcp-only', '--request-id', '--since', '--source', '--until'],'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--literal-pathspecs', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],@@ -79,7 +79,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],@@ -102,7 +102,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--body', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],- 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],+ 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--reason-scan-limit', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],'reconcile-links': ['--accept-pending', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--include-cross-entity', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--repo', '--request', '--request-id', '--segmented', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--timings', '--trust', '--wait', '--workers', '--yes'],@@ -131,7 +131,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'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'],- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--clear', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--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', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--clear', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--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', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex ad8f6aa52d..6bb6ebf821 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -128,7 +128,7 @@ const ROWS: readonly Row[] = [['page_segment_derivation_purges', 'swept', 'segment_derivations', 'source_id needles patterns page_ids phase recheck cursor_pipeline stalled_reason pending_reason'],['page_segment_texts', 'swept', 'segment_texts', 'source_id sha256 body', 'body'],['page_view_digests', 'out_of_scope', 'no_memory_text', 'revision view audience sha256'],- ['page_versions', 'swept', 'page_versions', 'compiled_truth frontmatter timeline title type tags source_path write_principal_kind write_principal_id archived_principal_kind archived_principal_id trust_tier write_origin body_storage content_hash'],+ ['page_versions', 'swept', 'page_versions', 'compiled_truth frontmatter timeline title type tags source_path write_principal_kind write_principal_id archived_principal_kind archived_principal_id trust_tier write_origin body_storage content_hash change_reason'],['page_write_guards', 'out_of_scope', 'no_memory_text', 'slug'],['pages', 'swept', 'page_body', 'source_id slug type page_kind title compiled_truth timeline frontmatter content_hash effective_date_source import_filename database_only_reason withheld_source_path contextual_retrieval_mode corpus_generation search_vector source_path ingested_via source_uri source_kind embedding_signature revision_principal_kind revision_principal_id trust_tier write_origin body_storage body_flags truth_lead timeline_lead links_extract_failure'],['persistence_consumers', 'out_of_scope', 'no_memory_text', 'kind mode pool version nonce minted_under persistence_home host_json_path pid_ns boot_id process_start'],@@ -148,6 +148,7 @@ const ROWS: readonly Row[] = [['query_cache', 'swept', 'query_cache', 'id query_text source_id embedding results meta knobs_hash page_generations'],['question_evidence', 'out_of_scope', 'text_free_ledger', 'sentence_id kind source_id page_slug page_revision content_hash'],['raw_data', 'out_of_scope', 'probed_reported', 'source data', 'source data'],+ ['reason_purge_tombstones', 'out_of_scope', 'text_free_ledger', 'source_id commit_sha path'],['retrieval_event_links', 'out_of_scope', 'no_memory_text', 'event_id source_id edge_key to_slug'],['retrieval_event_pages', 'out_of_scope', 'no_memory_text', 'event_id source_id slug content_hash'],['retrieval_events', 'out_of_scope', 'no_memory_text', 'id client_id op'],diff --git a/src/core/engine.ts b/src/core/engine.tsindex 45037f3eac..7fc4f5ba9e 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -2437,8 +2437,8 @@ export interface BrainEngine {* without it the bare-slug lookup snapshots whichever row Postgres returns* first when the slug exists across multiple sources.*/- /** `preimage` (#5984): the caller's own read of the page under its page guard in this transaction; versioned without a re-read. */- createVersion(slug: string, opts?: { sourceId?: string; preimage?: PageSnapshot }): Promise<PageVersion>;+ /** `preimage` (#5984): the caller's own read of the page under its page guard in this transaction; versioned without a re-read. `reason`/`historyGap` (GBRA-217, sync imports): the snapshot's change reason and the page's history-gap marker. */+ createVersion(slug: string, opts?: { sourceId?: string; preimage?: PageSnapshot } & import('./page-state/versions.ts').VersionHistory): Promise<PageVersion>;/*** v0.31.8 (D12 + D16): `opts.sourceId` source-scopes the page-id lookup.* When omitted, returns versions for every same-slug page across sourcesdiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 670323c770..8cf4bf280c 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -578,6 +578,11 @@ export const CODES = {rank_entities_timeout: { class: 'caller', summary: "rank_entities did not finish within its statement deadline (Postgres statement_timeout); nothing was ranked.", why: 'The ranking aggregates every edge in scope in one statement; a whole-brain ranking on a large graph can exceed the deadline, and a partial ranking would misstate the top rows.', docs: 'docs/guides/graph-ranking.md#rank_entities_timeout', suggestion: 'Narrow the ranking with source_id, types or link_type, then call rank_entities again.' },rate_limited: { class: 'retryable', summary: "The request was rate-limited; retry after the stated delay." },read_budget_exhausted: { class: 'caller', summary: "A subagent's get_page result came back as a short summary because the job has used its read budget (for the dream patterns child, dream.patterns.child_read_budget_kb).", why: 'A CLI-backed model replays the whole transcript on every turn, so a child that read every page in full filled the model window. The summary keeps the slug, title, type and a short excerpt; writes still work.', docs: 'docs/guides/dream-patterns.md#child-read-budget', suggestion: 'Work from the pages already read and append with add_timeline_entry instead of rewriting a summarized page. An operator who needs more reads raises dream.patterns.child_read_budget_kb (0 turns the budget off).' },+ reason_purge_scan_capped: { class: 'consent', exit: 3, summary: "A fact purge stopped before deleting anything: the source's Git history has more commits than the purge reads (200,000) when it looks for change reasons quoting the claim.", why: 'Purge tombstones every commit whose gbrain-reason trailer quotes the claim, so no later sync or re-import stores that reason again. Past the limit it cannot say which older commits do, so the user decides.', docs: 'docs/guides/page-history.md#purge-and-reasons', suggestion: 'Ask the user: purge now and check only the newest commits (--reason-scan-limit <n>, their choice; older commits are not tombstoned), or stop.' },+ reason_purge_scan_failed: { class: 'retryable', summary: "A fact purge stopped before deleting anything: reading the change reasons in the source's Git history failed (a Git error or a timeout).", why: 'Purge reads the reason trailers that quote the claim before it changes anything, so it can tombstone them; nothing was removed, so retrying is safe.', docs: 'docs/guides/page-history.md#purge-and-reasons', suggestion: 'Wait, then run the same purge again.' },+ reason_scan_capped: { class: 'unavailable', summary: "A sync imported its files but did not read their change reasons from Git: the range held more than 10,000 commits. Each reason in the pass is stored as empty and each page it changed is marked with a history gap.", why: 'Reasons are metadata, so content import never waits on them. The pass still advances last_commit and this release does not backfill reasons for that range; they stay in Git.', docs: 'docs/guides/page-history.md#reasons-from-git', suggestion: 'Nothing to repair. The reasons for the range are in Git: git log --first-parent <range> shows them.' },+ reason_scan_failed: { class: 'unavailable', summary: "A sync imported its files but could not read their change reasons from Git (a Git error or a timeout). Each reason in the pass is stored as empty and each page it changed is marked with a history gap.", why: 'Reasons are metadata, so content import never waits on them. The pass still advances last_commit and this release does not backfill reasons for that range; they stay in Git.', docs: 'docs/guides/page-history.md#reasons-from-git', suggestion: 'Nothing to repair. The reasons for the range are in Git: git log --first-parent <range> shows them.' },+ reason_trailer_secret: { class: 'host_only', summary: "A gbrain-reason trailer already pushed to Git looks like it holds a secret; sync stored no reason for that commit and path.", why: 'A secret in a reason is refused at write time; a commit made outside gbrain can still carry one. Git history keeps commit messages, so the credential stays exposed until it is rotated.', docs: 'docs/guides/page-history.md#reasons-from-git', suggestion: 'Rotate the credential the notice names (by commit and path); the brain stores nothing of it.' },receipt_conflict: { class: 'retryable', summary: "The ingestion receipt changed since it was read.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },receipt_fence_changed: { class: 'caller', summary: "The managed owner, topology or source binding changed while the ingestion ran.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },receipt_fence_required: { class: 'host_only', summary: "Ingestion into a managed or bound source needs the worktree owner's fence.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },@@ -906,4 +911,7 @@ export const NOTICE_CODES = {write_capacity_low: { kind: 'info', summary: 'A cumulative write cap (request ids or receipt bytes) is at or past 80% or runs out within `persistence.capacity.warn_days`; writes still work. Write and sync receipts carry it at most once an hour per process per scope; sync status, doctor and autopilot cycle output every time. Mute on receipts with `gbrain notices mute write_capacity_low`; doctor still reports it.' },write_capacity_backpressure: { kind: 'degraded', summary: 'A cumulative write cap passed `persistence.capacity.background_pause_pct`, so background producers (maintenance, conversation facts, autopilot phases and catch-up syncs) pause while interactive writes keep the rest; shown once when the pause starts.' },embed_backfill_skipped: { kind: 'info', summary: 'The brain is keyless by choice (`embedding_disabled`), so no embed-backfill was queued or run (reason `embedding_disabled`) and search stays keyword-only. Reported once per brain state; the fix is the optional step that turns embedding on (names the provider key it needs).' },+ reason_scan_failed: { kind: 'degraded', summary: 'A sync could not read change reasons from Git for its range (a Git error or a timeout): content was imported, every reason in the pass is stored as empty, the pages it changed are marked with a history gap, and the range is not rescanned later. The fix lists the reasons with git log.' },+ reason_scan_capped: { kind: 'degraded', summary: 'A sync range held more than 10,000 commits, so its change reasons were not read: content was imported, every reason in the pass is stored as empty, the pages it changed are marked with a history gap, and the range is not rescanned later. The fix lists the reasons with git log.' },+ reason_trailer_secret: { kind: 'safety', summary: 'A gbrain-reason trailer already in Git looks like a secret; the notice names the commit and path (never the value), no reason was stored, and the user should rotate the credential because Git history keeps it.' },} as const satisfies Record<string, NoticeEntry>;diff --git a/src/core/facts/purge-reasons.ts b/src/core/facts/purge-reasons.tsnew file mode 100644index 0000000000..973cf0107e--- /dev/null+++ b/src/core/facts/purge-reasons.ts@@ -0,0 +1,94 @@+/**+ * GBRA-217 (A7): purge reaches page change reasons. A reason quoting a purged claim lives in three places this module+ * covers: the snapshots that carry it (`page_versions.change_reason`, redacted by `redactPageVersions`), Git effects+ * not yet run or retained after running (`commit_line`, `commit_trailers`, a legacy `commit_trailer`), and the commit+ * messages already in Git, which purge never rewrites: their (commit, path) pairs are tombstoned, text-free, so no later+ * sync, cold re-import or re-derive stores that reason again.+ */+import type { BrainEngine } from '../engine.ts';+import { opError } from '../ops/contract.ts';+import { reasonScanCap, scanTrailersCarrying } from '../reason-trailers.ts';+import { claimNeedles } from './purge-verify.ts';++const PURGE_REASON_DOCS = 'docs/guides/page-history.md#purge-and-reasons';++/** The preparation's trailer scan: nothing to tombstone without a checkout (repo-less brain, plain folder). */+export interface PurgeTrailerPlan { sourceRoot: string | null; head: string | null; hits: Array<{ commit: string; path: string }>; commits: number; limited: boolean }++const scanFailed = (sourceId: string, rawId: string, detail: string) => opError('reason_purge_scan_failed',+ `Reading the change reasons in the Git history of source ${sourceId} failed (${detail}), so nothing was purged.`,+ 'Purge reads every gbrain-reason trailer that quotes the claim before it deletes anything, so the reason can be blocked from coming back; nothing changed and retrying is safe. Wait, then run the same purge again.',+ { docs: PURGE_REASON_DOCS, retryable: true, fix: { argv: ['gbrain', 'forget', rawId, '--purge', '--dry-run', '--json'], consent: [], actor: 'provider', requires_exclusive: false,+ why: 'Nothing was changed; once Git can be read again, the dry run confirms the plan and the same purge can be retried.' } });++/**+ * Before the purge transaction, while the claim still exists: the commits whose reason quotes it. A failed read refuses+ * `reason_purge_scan_failed` (retry); more commits than the cap refuses `reason_purge_scan_capped` (the user chooses a+ * `--reason-scan-limit` or stops), and with a limit the older commits are left unread and the receipt says so.+ */+export async function scanPurgeTrailers(engine: BrainEngine, input: { sourceId: string; claim: string; rawId: string; limit?: number }): Promise<PurgeTrailerPlan> {+ const none: PurgeTrailerPlan = { sourceRoot: null, head: null, hits: [], commits: 0, limited: false };+ const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id = $1', [input.sourceId]);+ if (!source?.local_path) return none;+ const scan = await scanTrailersCarrying(source.local_path, [input.claim], input.limit === undefined ? {} : { limit: input.limit });+ if (scan.status === 'no_repository') return none;+ if (scan.status === 'failed') throw scanFailed(input.sourceId, input.rawId, scan.detail);+ if (scan.status === 'capped') {+ throw opError('reason_purge_scan_capped', `Source ${input.sourceId} has more than ${scan.cap} commits to check for change reasons that quote this claim, so nothing was purged.`,+ 'Ask the user: purge now and check only the newest commits (pass --reason-scan-limit with the number they choose; older commits are not checked, so a reason there could be mirrored again by a later re-import), or stop.',+ { docs: PURGE_REASON_DOCS, fix: { ask_user: true, argv: ['gbrain', 'forget', input.rawId, '--purge', '--reason-scan-limit', String(scan.cap)], consent: ['destructive'], actor: 'agent', requires_exclusive: false,+ why: `Purges and tombstones the reasons found in the newest ${scan.cap} commits; older commits are not read.`,+ user_message: `This brain's Git history is longer than ${scan.cap} commits. Purge now and check only the newest commits for change reasons quoting this claim (choose how many), or stop?` } });+ }+ return { sourceRoot: source.local_path, head: scan.head, hits: scan.hits, commits: scan.commits, limited: scan.limited };+}++/**+ * Inside the purge transaction: rechecks the commits that landed since the preparation's scan, then records every+ * (commit, path) the claim's reason was found under. Returns the tombstones added.+ */+export async function recordReasonTombstones(tx: BrainEngine, input: { sourceId: string; claim: string; rawId: string; plan: PurgeTrailerPlan }): Promise<number> {+ const { plan } = input;+ if (!plan.sourceRoot) return 0;+ const recheck = await scanTrailersCarrying(plan.sourceRoot, [input.claim], { from: plan.head, limit: reasonScanCap('purge') });+ if (recheck.status === 'failed') throw scanFailed(input.sourceId, input.rawId, recheck.detail);+ const hits = [...plan.hits, ...(recheck.status === 'complete' ? recheck.hits : [])];+ if (!hits.length) return 0;+ return (await tx.executeRaw(`INSERT INTO reason_purge_tombstones(source_id, commit_sha, path)+ SELECT $1, t.c, t.p FROM unnest($2::text[], $3::text[]) AS t(c, p) ON CONFLICT DO NOTHING RETURNING 1`,+ [input.sourceId, hits.map(hit => hit.commit), hits.map(hit => hit.path)])).length;+}++/**+ * Git effects of the source whose commit message would carry the claim: queued, failed and retained committed ones are+ * redacted in place (`commit_line` becomes "[purged]", a carrying trailer is dropped); one a worker is running refuses+ * `purge_blocked_pending_recovery` (its message may be in flight). Returns the effects redacted.+ */+export async function redactGitEffectReasons(tx: BrainEngine, sourceId: string, claim: string): Promise<number> {+ const [needle, escaped] = claimNeedles(claim);+ const rows = await tx.executeRaw<{ id: string; state: string; request_id: string; data: Record<string, unknown> }>(`SELECT e.id::text AS id, e.state, r.request_id::text AS request_id, e.data+ FROM persistence_effects e JOIN persistence_requests r ON r.id = e.request_id+ WHERE e.source_id = $1 AND e.kind = 'git' AND (strpos(lower(e.data::text), $2) > 0 OR strpos(lower(e.data::text), $3) > 0) ORDER BY e.id FOR UPDATE OF e`, [sourceId, needle, escaped]);+ const carries = (value: unknown) => typeof value === 'string' && value.toLowerCase().includes(needle);+ let redacted = 0;+ for (const row of rows) {+ const data = { ...row.data };+ const listed = Array.isArray(data.commit_trailers) ? data.commit_trailers : null;+ if (!carries(data.commit_line) && !carries(data.commit_trailer) && !listed?.some(carries)) continue;+ if (row.state === 'running') {+ throw opError('purge_blocked_pending_recovery', 'A Git commit that carries this content is being written, so nothing was purged.',+ `Request ${row.request_id} has a Git effect running whose commit message quotes the claim. Wait for it to finish, then retry the purge with the same request id.`,+ { fix: { argv: ['gbrain', 'write-request', '--', row.request_id], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Shows the blocking write\'s state, read-only; retry the purge once it is final.' } });+ }+ if (carries(data.commit_line)) data.commit_line = '[purged]';+ if (carries(data.commit_trailer)) delete data.commit_trailer;+ if (listed) {+ const kept = listed.filter(trailer => !carries(trailer));+ if (kept.length) data.commit_trailers = kept; else delete data.commit_trailers;+ }+ await tx.executeRaw('UPDATE persistence_effects SET data = $2::text::jsonb WHERE id = $1::bigint', [row.id, JSON.stringify(data)]);+ redacted++;+ }+ return redacted;+}diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex 4ab422b6ba..1f5c61b996 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -472,7 +472,9 @@ async function vectorProbe(engine: BrainEngine, target: PurgeTarget): Promise<Re/** Build the receipt: swept-store verification (or would-remove counts on a dry run), probes, residuals first. */export async function verifyFactPurge(engine: BrainEngine, input: { target: PurgeTarget; plan: PurgePlan; dryRun: boolean; removed?: StoreCount;- prose?: Array<{ slug: string; version_id: number }>; vacuum?: boolean; ledger?: LedgerPurgeReport | null; sweepVerified?: boolean }): Promise<PurgeReceipt> {+ prose?: Array<{ slug: string; version_id: number }>; vacuum?: boolean; ledger?: LedgerPurgeReport | null; sweepVerified?: boolean;+ /** GBRA-217 (A7): the source's commits whose change reason quoted the claim, tombstoned; absent without a Git checkout. */+ reasonCommits?: { tombstoned: number; commits: number; limited: boolean } }): Promise<PurgeReceipt> {const { target, plan, dryRun } = input;const deadline = performance.now() + probeLimits.totalMs;const claim = target.fact, needle = claim.toLowerCase(), src = target.source_id;@@ -495,7 +497,7 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purgstores[stores.length - 1] = await withSegmentedProse(engine, stores[stores.length - 1]!, src, [claim], deadline);await swept('content_chunks', `SELECT 1 FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 AND strpos(lower(c.chunk_text),$2)>0`,[src, needle], plan.pages.length, removed.chunks, prose);- await swept('page_versions', `SELECT 1 FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND ${carriesClaimSql('v', 2)}`,+ await swept('page_versions', `SELECT 1 FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND (${carriesClaimSql('v', 2)} OR strpos(lower(v.change_reason),$2)>0)`,[src, ...claimNeedles(claim)], plan.versions, removed.page_versions, { ...prose, items: (input.prose ?? []).slice(0, 20) });stores[stores.length - 1] = await withSegmentedProse(engine, stores[stores.length - 1]!, src, [claim], deadline);await swept('persistence_requests', `SELECT 1 FROM persistence_requests WHERE source_id=$1 AND (${['intent', 'outcome', 'error_detail', 'error_message']@@ -547,6 +549,11 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purgconst detail = r.store === 'database_physical' ? `${r.detail}${engine.kind === 'pglite' ? (vacuumed === 'ran' ? ' VACUUM ran on the touched tables; filesystem blocks and snapshots may still hold old pages.' : vacuumed ? ` VACUUM of the touched tables ${vacuumed}; rerun with --vacuum.` : ' PGLite has no autovacuum; rerun with --vacuum to compact the touched tables.') : ' On Postgres the operator runs VACUUM; WAL archives, replicas and PITR windows are outside gbrain.'}` : r.detail;residuals.push({ store: r.store, status: 'out_of_reach', detail });}+ if (input.reasonCommits?.tombstoned || input.reasonCommits?.limited) residuals.push({ store: 'git_commit_messages', status: 'out_of_reach', remaining: input.reasonCommits.tombstoned,+ ...(input.reasonCommits.limited ? { reason: 'reason_scan_limit' } : {}),+ detail: `${input.reasonCommits.tombstoned} commit message reason(s) in this repository quote the claim. Commits already pushed keep their message text, as they keep file history; purge never rewrites them. `+ + 'Each (commit, path) is tombstoned, so no later sync or re-import stores that reason again.'+ + (input.reasonCommits.limited ? ` Only the newest ${input.reasonCommits.commits} commits were checked (--reason-scan-limit); a reason in an older commit could be mirrored again by a re-import.` : '') });if (Number(other?.n ?? 0)) residuals.push({ store: 'facts_other_scope', status: 'out_of_scope', reason: plan.subject === '*' ? 'other_visibility' : 'other_subject', remaining: Number(other.n),detail: `${other.n} fact row(s) state the same claim about another entity or at another visibility; rerun with --all-subjects to purge every entity's copy.` });residuals.push(...stores.filter(s => s.reason === 'source_prose' || s.reason === 'probed_reported' || s.store === 'canonical_markdown' && s.status === 'out_of_scope'));diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 4c38668279..dbf4ee98d1 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -53,6 +53,8 @@ import { markBeliefCommits } from '../belief/append.ts';import { appendPurgeCommitted, appendPurgeIntent } from '../belief/purge-mirror.ts';import { createPageVersion } from '../page-state/versions.ts';import { clearRebuildableCache } from '../persistence/rebuildable-cache.ts';+import { recordReasonTombstones, redactGitEffectReasons, scanPurgeTrailers } from './purge-reasons.ts';+import { clearReasonScanCache } from '../reason-trailers.ts';import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, derivedStreamSlugs, redactCarryingFields, redactPurgedKeys, registerLiveCarriers, registerVersionCarriers, sourceHasBeliefEvents,type LedgerPurgeReport } from '../belief/purge.ts';@@ -179,7 +181,7 @@ export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, al'SELECT slug,id AS page_id,knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[])', [target.source_id, extra]) : [];const pages = [...discovered, ...takePages.map(p => ({ ...p, page_id: Number(p.page_id) }))].sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);const [versions] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id- WHERE p.source_id=$1 AND (${carriesClaimSql('v', 2)}+ WHERE p.source_id=$1 AND (${carriesClaimSql('v', 2)} OR strpos(lower(v.change_reason),$2)>0OR (v.body_storage='segmented' AND ${SEGMENTED_VERSION_CARRIES}))`, [target.source_id, ...claimNeedles(target.fact)]);const { stagings, held } = await stagingsHoldingClaim(engine, target.source_id, target.fact);// #6511 [R5]: a statement timeout of this unindexable substring search is deterministic on a large journal, not contention: the typed code, not a retry.@@ -306,7 +308,10 @@ const VERSION_REDACTION_BATCH = 5000;export async function redactPageVersions(tx: BrainEngine, sourceId: string, claim: string, pageIds: number[]):Promise<{ redacted: number; prose: Array<{ slug: string; version_id: number }>; segmentedPages: number[]; replaced: Uint8Array[] }> {const [needle, escaped] = claimNeedles(claim);- let redacted = 0;+ // GBRA-217 (A7): a change reason quoting the claim, on inline and segmented snapshots alike, wherever its page is.+ const reasons = new Set((await tx.executeRaw<{ id: number }>(`UPDATE page_versions v SET change_reason = '[purged]' FROM pages p+ WHERE p.id = v.page_id AND p.source_id = $1 AND strpos(lower(v.change_reason), $2) > 0 RETURNING v.id`, [sourceId, needle])).map(row => Number(row.id)));+ let redacted = reasons.size;const prose: Array<{ slug: string; version_id: number }> = [];for (let after = 0; ;) {const rows = await tx.executeRaw<{ id: number; slug: string; compiled_truth: string; timeline: string | null; metadata: boolean }>(`SELECT v.id,p.slug,v.compiled_truth,v.timeline,@@ -321,7 +326,7 @@ export async function redactPageVersions(tx: BrainEngine, sourceId: string, claiconst timeline = await dropPurgedFenceRows(tx, sourceId, v.timeline ?? '', v.slug);if (compiled !== v.compiled_truth || timeline !== (v.timeline ?? '')) {await tx.executeRaw('UPDATE page_versions SET compiled_truth=$2,timeline=$3 WHERE id=$1', [v.id, compiled, timeline]);- redacted++;+ if (!reasons.has(Number(v.id))) redacted++;}if (v.metadata || compiled.toLowerCase().includes(needle) || timeline.toLowerCase().includes(needle)) prose.push({ slug: v.slug, version_id: Number(v.id) });}@@ -386,16 +391,18 @@ export async function purgeSegmentStorage(tx: BrainEngine, sourceId: string, clareturn { texts, stagings: plan.stagings.length, parts, cancelled };}-interface PurgeParams { id: number; rawId: string; sourceId: string; reason: string | null; allSubjects: boolean; requestId: string }+interface PurgeParams { id: number; rawId: string; sourceId: string; reason: string | null; allSubjects: boolean; requestId: string; reasonScanLimit?: number }function parseParams(ctx: OperationContext, params: Record<string, unknown>): PurgeParams {const rawId = String(params.id ?? '').trim();const id = Number(rawId);if (!Number.isSafeInteger(id) || id <= 0) throw notFound(rawId);const reason = typeof params.reason === 'string' && params.reason.trim() ? params.reason.trim().slice(0, 200) : null;+ const limit = params.reason_scan_limit === undefined ? undefined : Number(params.reason_scan_limit);+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit <= 0)) throw opError('invalid_params', 'reason_scan_limit must be a positive whole number.', 'Pass the number of newest commits to check, or omit it.');return { id, rawId, reason, allSubjects: params.all_subjects === true,sourceId: typeof params.source_id === 'string' ? params.source_id : ctx.sourceId ?? 'default',- requestId: parseWriteRequestId(params.request_id) ?? randomUUID() };+ requestId: parseWriteRequestId(params.request_id) ?? randomUUID(), ...(limit !== undefined ? { reasonScanLimit: limit } : {}) };}/** `--match`: candidate facts for a text, so the owner picks an id (purge always needs a ref). Owner-only output. */@@ -463,6 +470,8 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rec`Run the dry run first (gbrain forget ${p.rawId} --purge --dry-run), review its receipt with the user, then confirm with the fact's token (the first 8 characters of its fingerprint).`,{ fix: { argv: ['gbrain', 'forget', p.rawId, '--purge', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false,why: 'Prints what the purge would remove and the confirmation token, without changing anything.' } });+ // GBRA-217 (A7): while the claim still exists, the commits whose change reason quotes it (rechecked inside the transaction).+ const trailers = await scanPurgeTrailers(ctx.engine, { sourceId: p.sourceId, claim: target.fact, rawId: p.rawId, ...(p.reasonScanLimit ? { limit: p.reasonScanLimit } : {}) });const { similarActiveAfterForget } = await import('./similar-active.ts');const similar = await similarActiveAfterForget(ctx.engine, { sourceId: p.sourceId, factId: p.id, remote: false, committed: true, semanticReview: false }).then(s => ({ ...s, candidates: s.candidates.filter(c => !plan.factIds.includes(Number(c.fact_id))) })).catch(() => null);@@ -501,6 +510,8 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Recreturn withCoordinatedWrite(tx, [p.sourceId], async () => {const plan = committedPlan;await assertNoPendingPublication(tx, p.sourceId, plan.pages, admitted.id);+ const effectReasons = await redactGitEffectReasons(tx, p.sourceId, current.fact);+ const reasonTombstones = await recordReasonTombstones(tx, { sourceId: p.sourceId, claim: current.fact, rawId: p.rawId, plan: trailers });const intents = await redactRequestIntents(tx, plan.requests, admitted.id, { needles: [current.fact] });const ledgerPresent = await sourceHasBeliefEvents(tx, p.sourceId);const streams = ledgerPresent ? await factPurgeStreams(tx, p.sourceId, plan) : [];@@ -561,7 +572,8 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: RecWHERE s.id=$2 ON CONFLICT(request_id,kind) DO NOTHING`, [admitted.id, p.sourceId, JSON.stringify({ version: 2, mode: 'purge',commit_subject: `gbrain: purge fact ${token}`, commit_line: `purge fact ${token}`,targets: pages.map(page => ({ slug: page.slug, page_id: Number(page.id), revision: page.knowledge_revision })) })]);- counts = { facts, takes, chunks, page_versions: versions.redacted, pages: rewritten.length, persistence_requests: intents,+ counts = { facts, takes, chunks, page_versions: versions.redacted, pages: rewritten.length, persistence_requests: intents, persistence_effects: effectReasons,+ reason_purge_tombstones: reasonTombstones,query_cache: cache, decide_review: review, open_loops: loops, take_proposals: proposals, core_edit_notices: notices, ...ledger,write_gate_holds: holdIds.length, write_gate_receipts: gateReceipts, page_segment_texts: segments.texts, page_segment_derivations: bodies.derivations,page_body_stagings: segments.stagings, page_body_staging_parts: segments.parts, persistence_requests_cancelled: segments.cancelled,@@ -596,8 +608,10 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Reccounts.page_segment_derivations = (counts.page_segment_derivations ?? 0) + await continueDerivationPurges(ctx.engine, p.sourceId, { first: row.id, inline: true });if (beliefReport.appended || ledger?.derived_hidden) await markBeliefCommits(ctx.engine, [row.id]).catch(() => undefined);const sweepVerified = !await derivationPurgeState(ctx.engine, row.id);+ clearReasonScanCache();const receipt: PurgeReceipt = await verifyFactPurge(ctx.engine, { target, plan: committedPlan, dryRun: false, removed: counts, prose,- vacuum: params.vacuum === true, ledger, sweepVerified });+ vacuum: params.vacuum === true, ledger, sweepVerified,+ reasonCommits: trailers.sourceRoot ? { tombstoned: counts.reason_purge_tombstones ?? 0, commits: trailers.commits, limited: trailers.limited } : undefined });if (sweepVerified && receipt.stores.some(s => s.store === 'page_segment_derivations' && s.status === 'incomplete')) {await recordDerivationPurge(ctx.engine, row.id, p.sourceId, committedPlan.pages.map(page => page.page_id), [target.fact, escapeFenceCell(target.fact)]);}diff --git a/src/core/hardened-git.ts b/src/core/hardened-git.tsindex 7d3302475a..25abfa0d66 100644--- a/src/core/hardened-git.ts+++ b/src/core/hardened-git.ts@@ -62,6 +62,14 @@ export function hardenedGitEnvironment(): NodeJS.ProcessEnv {export type HardenedGitResult = { ok: true; stdout: Buffer } | { ok: false; reason: 'exit' | 'timeout' | 'too_large' | 'unavailable'; status?: number };+/**+ * GBRA-217: the one `git log` gbrain runs in an untrusted checkout, the reason-trailer read (`reason-trailers.ts`). A+ * name-only listing of the first-parent line with no renames compares tree entries only, so no filter, textconv or+ * external diff runs; signatures are not verified (no gpg). Every option is required, so no other `log` passes.+ */+export const REASON_LOG_OPTIONS: readonly string[] = ['-z', '--first-parent', '--diff-merges=first-parent', '--root', '--name-only', '--no-renames', '--no-relative',+ '--no-ext-diff', '--no-textconv', '--no-show-signature', '--format=%x00%H%x00%(trailers:key=gbrain-reason,valueonly,unfold)'];+/*** The exact options each allowed plumbing subcommand may take; anything not* listed here refuses.@@ -76,6 +84,7 @@ const ALLOWED_OPTIONS: ReadonlyMap<string, ReadonlySet<string>> = new Map([['check-ignore', new Set(['-z', '--stdin'])],['diff-index', new Set(['--cached', '--quiet'])],['diff-tree', new Set(['-r', '-z', '--no-renames'])],+ ['log', new Set(REASON_LOG_OPTIONS)],]);/** Options a subcommand must carry, so its output stays raw and machine-readable. */@@ -83,6 +92,7 @@ const REQUIRED_OPTIONS: ReadonlyMap<string, readonly string[]> = new Map([['hash-object', ['--no-filters']],['diff-index', ['--cached']],['diff-tree', ['-r', '-z', '--no-renames']],+ ['log', REASON_LOG_OPTIONS],]);/**diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex a4586cb214..bd1cdcec90 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -256,6 +256,7 @@ export async function importFromContent(opts: {/** Coordinator seam: prepare without publishing, then commit under its guarded transaction. */prepare?: (prepared: import('./persistence/prepared-import.ts').PreparedContentImport) => Promise<ImportResult>;+ /** GBRA-217: a sync import's reason from Git and history-gap marker, stamped on the snapshot this import archives. */ history?: import('./page-state/versions.ts').VersionHistory;/** #5984, with `prepare`: the coordinator proves the base revision under its page guard, and the caller seals the text projection and checks the read-back (`contentHash`) from its own read after apply; apply skips all three. */coordinated?: boolean;/** #7172, with `prepare`: the caller forwards `afterCommit` and seals nothing on `projectionPending` (chunk-moves.ts). */@@ -753,7 +754,7 @@ export async function importFromContent(const demote = !segmented && bodyStorageOf(existing) === 'segmented';// Before the page write: an unpinned version reads the page itself, a demoted one references the generation it retires.- if (existing && (!preimage || demote)) await tx.createVersion(slug, preimage ? { ...txOpts, preimage } : txOpts);+ if (existing && (!preimage || demote)) await tx.createVersion(slug, preimage ? { ...txOpts, ...opts.history, preimage } : { ...txOpts, ...opts.history });if (demote) await demoteSegmentedPage(tx, Number(existing!.id));// Every import keeps each stored row that is identical to its new chunk and// writes only the rest, so an edit rewrites only the chunks it changed. The@@ -770,7 +771,7 @@ export async function importFromContent(let written: Page | undefined;await pipelined(tx, [() => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),- async () => { if (existing && preimage && !demote) await tx.createVersion(slug, { ...txOpts, preimage }); },+ async () => { if (existing && preimage && !demote) await tx.createVersion(slug, { ...txOpts, ...opts.history, preimage }); },async () => {if (segmented) return segmented.apply(tx, { type: parsed.type, title: parsed.title, frontmatter: parsed.frontmatter, page_kind: 'markdown',effective_date: effectiveDate, effective_date_source: effectiveDateSource, import_filename: filenameForChain, source_path: opts.sourcePath ?? null,@@ -1028,6 +1029,7 @@ export async function importFromFile(activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };/** Git first-commit date of the file (opt-in, see git-first-commit.ts); an undated page's fallback anchor. */firstCommitAt?: Date;+ /** GBRA-217: a sync import's reason from Git and history-gap marker for the snapshot this import archives. */ history?: import('./page-state/versions.ts').VersionHistory;/** Wave B: the segmented-storage policy, read once per command; with the switch on, a Markdown file over the single-string ceiling imports streamed. Absent: it refuses as before. */bodyPolicy?: PageBodyPolicy;} = {},@@ -1074,7 +1076,7 @@ export async function importFromFile(if (isCodeFilePath(relativePath)) {return importCodeFile(engine, relativePath, content, {noEmbed: opts.noEmbed,- sourceId: opts.sourceId,+ sourceId: opts.sourceId, history: opts.history,});}@@ -1227,7 +1229,7 @@ export async function importCodeFile(engine: BrainEngine,relativePath: string,content: string,- opts: { noEmbed?: boolean; force?: boolean; sourceId?: string;+ opts: { noEmbed?: boolean; force?: boolean; sourceId?: string; history?: import('./page-state/versions.ts').VersionHistory;prepare?: (prepared: import('./persistence/prepared-import.ts').PreparedContentImport) => Promise<ImportResult> } = {},): Promise<ImportResult> {if (!opts.prepare) await assertUnmanagedCanonicalWriter(engine, 'direct file import', { sourceId: opts.sourceId ?? 'default' });@@ -1361,7 +1363,7 @@ export async function importCodeFile(// under the schema DEFAULT.const apply = async (tx: BrainEngine) => {await assertImportBase(tx, slug, sourceId ?? 'default', existing);- if (existing) await tx.createVersion(slug, txOpts);+ if (existing) await tx.createVersion(slug, { ...txOpts, ...opts.history });await tx.putPage(slug, {type: 'code' as string,diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex abb2c1a536..9c0581f69e 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -477,6 +477,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["type": "number","description": "Commit wait ms (0-30000, default 5000)."},+ "reason": {+ "type": "string",+ "description": "Why this change, one line (max 500 chars); kept in page history."+ },"source_kind": {"type": "string","description": "Server-set remotely.",@@ -903,6 +907,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["request_id": {"type": "string","description": "Reuse only to retry."+ },+ "reason": {+ "type": "string",+ "description": "Why this change, one line (max 500 chars); kept in page history."}},"mutating": true,@@ -1005,6 +1013,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["drop_timeline": {"type": "boolean","description": "Content without a Timeline section deletes its dated entries."+ },+ "reason": {+ "type": "string",+ "description": "Why this change, one line (max 500 chars); kept in page history."}}}@@ -2527,7 +2539,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["outputRedaction": {"exempt": "full page version snapshots by slug; a page read governed by visibility like get_page (CEO-17)"},- "description": "Page version history, newest snapshot first: metadata only (id, snapshot_at, title, type, tags, frontmatter) for the newest 20 versions by default. Pass include_body: true for each version's compiled_truth and timeline, and a larger limit (at most 100 over MCP) for older versions. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). revert_version takes the id field.",+ "description": "Page version history, newest snapshot first: metadata only (id, snapshot_at, title, type, tags, frontmatter) for the newest 20 versions by default. Pass include_body: true for each version's compiled_truth and timeline, and a larger limit (at most 100 over MCP) for older versions. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). replaced_because is the reason given for the write that replaced the snapshot (null when none was given). revert_version takes the id field.","params": {"slug": {"type": "string",@@ -2598,6 +2610,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["type": "number","required": true,"description": "Numeric version id to revert to, as returned by get_versions. Not a version NUMBER offset — pass the id field."+ },+ "reason": {+ "type": "string",+ "description": "Why this change, one line (max 500 chars); kept in page history."}},"mutating": true,@@ -6030,6 +6046,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["source_id": {"type": "string","description": "Source holding the fact (default: the routed source)."+ },+ "reason_scan_limit": {+ "type": "number",+ "description": "Check only the newest N commits for change reasons quoting the claim (after a reason_purge_scan_capped refusal, with the user's choice); older commits are not tombstoned."}},"mutating": true,diff --git a/src/core/ops/purge.ts b/src/core/ops/purge.tsindex e1be578869..76ebeb67b6 100644--- a/src/core/ops/purge.ts+++ b/src/core/ops/purge.ts@@ -26,6 +26,7 @@ const purge_fact: Operation = {continue: { type: 'boolean', description: 'With status: first continue the purge\'s sweep of stored derivation results (derivation_sweep pending or stalled), then report.' },vacuum: { type: 'boolean', description: 'PGLite only: VACUUM the touched tables after the purge.' },source_id: { type: 'string', description: 'Source holding the fact (default: the routed source).' },+ reason_scan_limit: { type: 'number', description: 'Check only the newest N commits for change reasons quoting the claim (after a reason_purge_scan_capped refusal, with the user\'s choice); older commits are not tombstoned.' },},mutating: true,scope: 'admin',diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.tsindex 92453e20a6..1ccf885650 100644--- a/src/core/page-body/streamed-import.ts+++ b/src/core/page-body/streamed-import.ts@@ -95,6 +95,8 @@ type StreamedImportOptions = {forceRechunk?: boolean;activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };firstCommitAt?: Date;+ /** GBRA-217: a sync import's reason from Git and history-gap marker for the snapshot this import archives. */+ history?: import('../page-state/versions.ts').VersionHistory;/*** A page write of the file's content (`gbrain put|capture --file` on the trusted local CLI), not a file import: the* file records no origin (no source_path or file source_uri), no other file's slug claim applies, the staging is a@@ -451,7 +453,7 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom: { source_path: relativePath, source_kind: null, source_uri: fileOriginUri(existing?.source_uri, sourceRoot, relativePath), ingested_via: null }) };const refs = prepared.body.body_flags.has_protected ? [] : [...codeRefs.refs.values()];const apply = async (tx: BrainEngine, preimage?: PageSnapshot | null) => {- if (existing) await tx.createVersion(slug, preimage ? { sourceId, preimage } : { sourceId });+ if (existing) await tx.createVersion(slug, preimage ? { sourceId, ...opts.history, preimage } : { sourceId, ...opts.history });const result = await applySegmentedBody(tx, { slug, sourceId, pageId: live?.id ?? null, prepared, meta, promotion: live?.storage === 'inline', retireMaxRows: input.policy.flipRetireMaxRows });await tx.updatePageContextualRetrievalState(slug, sourceId, mode, corpusGeneration);await tx.executeRaw(`DELETE FROM tags t USING pages p WHERE p.id = t.page_id AND p.source_id = $1 AND p.slug = $2diff --git a/src/core/page-state/versions.ts b/src/core/page-state/versions.tsindex 96866c8b6d..3fc2b6d32e 100644--- a/src/core/page-state/versions.ts+++ b/src/core/page-state/versions.ts@@ -8,19 +8,27 @@ import { isSegmentedPage } from '../page-body/page-shape.ts';export { LARGE_PAGE_VERSIONS_KEPT };+/**+ * GBRA-217: what a sync import knows about the write a snapshot records: the reason Git gives for it+ * (`page_versions.change_reason`), and whether the import consumed more than one commit for the page's file, or could+ * not tell (`pages.version_history_gap_at`).+ */+export interface VersionHistory { reason?: string | null; historyGap?: boolean }+/*** Version the same canonical view an API reader receives, including withdrawals.* `preimage` (#5984) is the caller's own read of the page under its page guard* in this transaction; it is versioned as read, without a second read.*/-export async function createPageVersion(engine: BrainEngine, slug: string, sourceId: string, preimage?: PageSnapshot): Promise<PageVersion> {+export async function createPageVersion(engine: BrainEngine, slug: string, sourceId: string, preimage?: PageSnapshot, history: VersionHistory = {}): Promise<PageVersion> {const insert = async (tx: BrainEngine, snapshot: PageSnapshot) => {const { page, tags, revision } = snapshot;- if (isSegmentedPage(page)) return insertSegmentedVersion(tx, snapshot);+ if (history.historyGap) await tx.executeRaw('UPDATE pages SET version_history_gap_at = now() WHERE id = $1', [page.id]);+ if (isSegmentedPage(page)) return insertSegmentedVersion(tx, snapshot, history.reason ?? null);const rows = await tx.executeRaw<PageVersion>(`INSERT INTO page_versions- (page_id,compiled_truth,frontmatter,knowledge_revision,timeline,title,type,tags,is_deleted,source_path)- VALUES ($1,$2,$3::text::jsonb,$4::uuid,$5,$6,$7,$8::text::jsonb,$9,$10) RETURNING *`,- [page.id, page.compiled_truth, JSON.stringify(page.frontmatter), revision, page.timeline, page.title, page.type, JSON.stringify(tags), page.deleted_at != null, page.source_path ?? null]);+ (page_id,compiled_truth,frontmatter,knowledge_revision,timeline,title,type,tags,is_deleted,source_path,change_reason)+ VALUES ($1,$2,$3::text::jsonb,$4::uuid,$5,$6,$7,$8::text::jsonb,$9,$10,$11) RETURNING *`,+ [page.id, page.compiled_truth, JSON.stringify(page.frontmatter), revision, page.timeline, page.title, page.type, JSON.stringify(tags), page.deleted_at != null, page.source_path ?? null, history.reason ?? null]);if (isLargePageBytes(Buffer.byteLength(page.compiled_truth ?? '', 'utf-8') + Buffer.byteLength(page.timeline ?? '', 'utf-8'))) {const pruned = await tx.executeRaw<{ id: number }>(`DELETE FROM page_versions WHERE page_id = $1 AND id IN (SELECT id FROM page_versions WHERE page_id = $1AND octet_length(compiled_truth) + octet_length(COALESCE(timeline, '')) > $2 ORDER BY id DESC OFFSET $3) RETURNING id`,@@ -46,13 +54,13 @@ export async function createPageVersion(engine: BrainEngine, slug: string, sourc* before its generation flip, as every caller versions before its page write.* Then the page's segmented history is pruned by `pruneSegmentedVersions`.*/-async function insertSegmentedVersion(tx: BrainEngine, snapshot: PageSnapshot): Promise<PageVersion> {+async function insertSegmentedVersion(tx: BrainEngine, snapshot: PageSnapshot, reason: string | null): Promise<PageVersion> {const { page, tags, revision } = snapshot;const [row] = await tx.executeRaw<PageVersion>(`INSERT INTO page_versions- (page_id,body_storage,body_generation,body_bytes,content_hash,frontmatter,knowledge_revision,title,type,tags,is_deleted,source_path)- SELECT p.id,'segmented',p.body_generation,p.body_bytes,p.content_hash,$2::text::jsonb,$3::uuid,$4,$5,$6::text::jsonb,$7,$8+ (page_id,body_storage,body_generation,body_bytes,content_hash,frontmatter,knowledge_revision,title,type,tags,is_deleted,source_path,change_reason)+ SELECT p.id,'segmented',p.body_generation,p.body_bytes,p.content_hash,$2::text::jsonb,$3::uuid,$4,$5,$6::text::jsonb,$7,$8,$9FROM pages p WHERE p.id = $1 AND p.body_storage = 'segmented' RETURNING *`,- [page.id, JSON.stringify(page.frontmatter), revision, page.title, page.type, JSON.stringify(tags), page.deleted_at != null, page.source_path ?? null]);+ [page.id, JSON.stringify(page.frontmatter), revision, page.title, page.type, JSON.stringify(tags), page.deleted_at != null, page.source_path ?? null, reason]);if (!row) throw new Error(`createVersion failed: page id ${page.id} is no longer segmented`);if ((await pruneSegmentedVersions(tx, page.id)) > 0) await tx.sweepSegments({ pageId: page.id });return { ...row, snapshot_at: new Date(row.snapshot_at) };diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 52b34e4b60..22ee2a2398 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -13,6 +13,8 @@ import type { RegistryCode } from '../error-registry.ts';import { ownerGateInput, ownerImportTrust, ownerPageTrust } from '../trust/channel.ts';import { matchTrustAllowRule, type TrustAllowRule } from '../trust/allow-rules.ts';import { importFromContent, importCodeFile, verifyPageReadable } from '../import-file.ts';+import { managedFileHistory } from './sync-reasons.ts';+import type { VersionHistory } from '../page-state/versions.ts';import { screenImportContent, screenNormalized, type ContentRefusal, type ImportScreenResult, type ImportSanityConfig } from '../import-screen.ts';import { ContentSanityBlockError } from '../content-sanity.ts';import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, type ParseOpts } from '../markdown.ts';@@ -434,7 +436,7 @@ async function recordSliceCursor(tx: BrainEngine, row: WriteRequest, p: { syncOp/** The code-file branch of `prepareManagedSyncMutation`: `importCodeFile` with `prepare`, text embedding deferred to `embed --stale` (the image branch is `sync-image.ts`). */async function prepareManagedSyncCode(engine: BrainEngine, row: WriteRequest, p: { content: string; sourcePath: string; rawHash: string | null; lineEndingOnly?: boolean; companyApproval: boolean },ctx: { snapshot: Snapshot | null; validate: (tx: BrainEngine) => Promise<void>; releaseHold: (tx: BrainEngine) => Promise<void>; recordProvenance: (tx: BrainEngine) => Promise<void>; clock?: ClaimPhaseClock;- refuse: (code: RegistryCode, message: string, cause: string) => OperationError; contentRefusal: (refusal: ContentRefusal) => OperationError }): Promise<PreparedMutation> {+ history?: VersionHistory; refuse: (code: RegistryCode, message: string, cause: string) => OperationError; contentRefusal: (refusal: ContentRefusal) => OperationError }): Promise<PreparedMutation> {const { snapshot, validate, releaseHold, clock, refuse } = ctx;if (p.companyApproval) throw refuse('profile_incompatible', 'Company source approval permits only committed Markdown content.',`A company-brain source imports only committed Markdown, and ${row.slug} is a code file; remove it from the approved revision.`);@@ -446,7 +448,7 @@ async function prepareManagedSyncCode(engine: BrainEngine, row: WriteRequest, p:if (codeScreen.status === 'refused') throw ctx.contentRefusal(codeScreen.refusal);let prepared: PreparedContentImport | undefined;enterClaimStep(clock, 'code_import', undefined, 'db');- const result = await importCodeFile(engine, p.sourcePath, p.content, { sourceId: row.source_id, noEmbed: true,+ const result = await importCodeFile(engine, p.sourcePath, p.content, { sourceId: row.source_id, noEmbed: true, history: ctx.history,prepare: async value => { prepared = value; return value.result; } });if (!prepared || prepared.slug !== row.slug) throw refuse('invalid_params', result.error ?? 'The code file identity could not be prepared.',`The code file could not be prepared as page ${row.slug}.`);@@ -792,6 +794,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _cawait releaseHold(tx);return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop: !snapshot || snapshot.page.deleted_at != null };} };+ const history = snapshot && typeof p.path === 'string' ? await managedFileHistory(unbounded, clock, { sourceId: row.source_id, root, path: p.path, from: p.from, to: p.target }) : undefined;// Wave B: a Markdown file over the single-string ceiling (never a company-brain or image entry) streams; its body is never read here.if (p.body_ref && typeof p.sourcePath === 'string' && typeof p.path === 'string') {enterClaimStep(clock, 'schema_pack', undefined, 'db');@@ -802,7 +805,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _cthrow syncPublicationRefusal('revision_conflict', 'The renamed page changed after sync admission.', row, p,`Page ${renamed.slug}, which this file was renamed from, changed or was deleted after the sync was admitted.`);}- return prepareManagedSyncStreamed(engine, row, { ...p, body_ref: p.body_ref, sourcePath: p.sourcePath, path: p.path }, { root, snapshot, base, ...(renamed ? { renamed } : {}),+ return prepareManagedSyncStreamed(engine, row, { ...p, body_ref: p.body_ref, sourcePath: p.sourcePath, path: p.path }, { root, snapshot, base, ...(renamed ? { renamed } : {}), history,...(pack?.manifest ? { activePack: pack.manifest } : {}), validate, releaseHold, clock, screening: !!screening,importProvenance: { source_id: row.source_id, incarnation: row.source_incarnation, origin: p.sourcePath, raw_sha256: p.body_ref.sha256,...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, parser: syncImportParser(pack?.identity ?? null) },@@ -818,7 +821,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _crefuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause) });}if (isCodeFilePath(p.sourcePath)) return prepareManagedSyncCode(engine, row, { content: p.content, sourcePath: p.sourcePath, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly, companyApproval: !!p.companyApproval },- { snapshot, validate, releaseHold, recordProvenance: syncFileProvenance(row, p, root, sha256(p.content)), clock, refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause), contentRefusal: refusal => syncContentRefusal(refusal, row, p) });+ { snapshot, validate, history, releaseHold, recordProvenance: syncFileProvenance(row, p, root, sha256(p.content)), clock, refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause), contentRefusal: refusal => syncContentRefusal(refusal, row, p) });const schema = p.companyApproval?.schema;if (schema && p.processingOptions?.noSchemaPack) throw syncPublicationRefusal('profile_incompatible', 'Company source approval requires its pinned schema pack.', row,{ ...p, processingOptions: { ...p.processingOptions!, noSchemaPack: false } },@@ -862,7 +865,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c// #6188: the import reuses this screen's fence verdict for the same bytes (one fence scan per file at prepare).const importOptions = { ...source, noEmbed: true, remote: row.authority.remote, preserveGateMarkers: true, activePack, coordinated: true, fences: 'coordinated' as const, boundedChunkWrites: true as const, writeGate: await ownerGateInput(engine, row, parsedInput.frontmatter, p.sourcePath),...(importContent === p.content && screen.status === 'importable' ? { fenceScreen: screen.fences ?? null } : {}),- filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true,+ filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true, history,segmentedOwner: { kind: 'sync' as const, principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: base?.revision ?? null } };const result = await importFromContent(engine, renamed?.slug ?? row.slug, importContent, { ...importOptions,prepare: async value => { prepared = value; return value.result; } }).catch(error => {diff --git a/src/core/persistence/sync-reasons.ts b/src/core/persistence/sync-reasons.tsnew file mode 100644index 0000000000..707b0144b1--- /dev/null+++ b/src/core/persistence/sync-reasons.ts@@ -0,0 +1,32 @@+/**+ * GBRA-217 (A6): managed sync mirrors page change reasons from Git. A preparation that archives a snapshot (its page+ * exists) reads its file's reason from the pass's one trailer scan over `from..target` (`cachedSyncReasonScan`); the+ * pass result then carries that scan's notices (a failed or capped scan, a secret in a pushed trailer) and its count of+ * malformed trailers, reusing the scan when the consumer ran in this process.+ */+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import type { SyncResult } from '../../commands/sync.ts';+import type { VersionHistory } from '../page-state/versions.ts';+import { cachedSyncReasonScan, importHistoryFor, reasonScanNotices } from '../reason-trailers.ts';+import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';+import { getWorktreeBinding } from './ownership.ts';++export async function managedFileHistory(engine: BrainEngine, clock: ClaimPhaseClock | undefined,+ input: { sourceId: string; root: string; path: string; from: string | null; to: string }): Promise<VersionHistory | undefined> {+ enterClaimStep(clock, 'reason_scan', undefined, 'git');+ const scan = await cachedSyncReasonScan(engine, { sourceId: input.sourceId, sourceRoot: input.root, from: input.from, to: input.to });+ return importHistoryFor(scan, join(input.root, input.path));+}++/** A pass that changed no existing page archived no snapshot, so it ran no scan and has nothing to report. */+export async function withManagedReasonNotices(engine: BrainEngine, sourceId: string, result: SyncResult): Promise<SyncResult> {+ if (result.status === 'dry_run' || !result.toCommit || result.modified + result.renamed === 0) return result;+ const binding = await getWorktreeBinding(engine, sourceId).catch(() => null);+ if (!binding?.local_path) return result;+ const scan = await cachedSyncReasonScan(engine, { sourceId, sourceRoot: join(binding.local_path, binding.relative_path), from: result.fromCommit, to: result.toCommit })+ .catch(() => null);+ const notices = reasonScanNotices(scan, sourceId);+ return { ...result, ...(notices.length ? { reason_notices: [...(result.reason_notices ?? []), ...notices] } : {}),+ ...(scan?.malformed ? { reason_trailers_malformed: scan.malformed } : {}) };+}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 1e59282d75..a729355fd5 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -58,6 +58,7 @@ import { faultPoint } from './fault-points.ts';import { directoryAt, freezeFaultHold, noteFrozen, nullBytesRefusal } from './sync-entry-fault.ts';import { syncCursorOptions } from './sync-slices.ts';import { pipelined } from '../page-state/transactions.ts';+import { withManagedReasonNotices } from './sync-reasons.ts';import { withCoordinatedWrite } from './context.ts';import { principalAttribution } from './attribution.ts';import { recordSyncRunTrend } from '../fence-repair/census-store.ts';@@ -1272,7 +1273,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slasync function performManagedPass(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {const state: HoldRunState = {};// #6729: every managed entry point (CLI, drain, owner slice, worktree refresh) records the renames whose identity it did not keep.- const synced = await noteIdentityDowngrades(engine, opts.sourceId ?? 'default', await runManagedSync(engine, opts, slice, state), serr);+ const synced = await withManagedReasonNotices(engine, opts.sourceId ?? 'default', await noteIdentityDowngrades(engine, opts.sourceId ?? 'default', await runManagedSync(engine, opts, slice, state), serr));if (!state.sourceId || !state.incarnation || synced.status === 'dry_run' || currentDrainLease(state.sourceId)?.idleClear) return synced;const cursor = state.cursor?.() ?? null;try {diff --git a/src/core/persistence/sync-streamed.ts b/src/core/persistence/sync-streamed.tsindex 14402e0a5a..f9bad4f025 100644--- a/src/core/persistence/sync-streamed.ts+++ b/src/core/persistence/sync-streamed.ts@@ -74,6 +74,8 @@ export interface StreamedSyncContext {snapshot: PageSnapshot | null; base: PageSnapshot | null;renamed?: SyncRename;activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };+ /** GBRA-217: the file's reason from its pass's trailer scan, and its history-gap marker. */+ history?: import('../page-state/versions.ts').VersionHistory;importProvenance: SyncImportProvenanceBase;validate: (tx: BrainEngine) => Promise<void>;releaseHold: (tx: BrainEngine) => Promise<void>;@@ -101,7 +103,7 @@ export async function prepareManagedSyncStreamed(engine: BrainEngine, row: Writeif (!filePath || !stat || stat.size !== ref.bytes) throw changed();let ready: StreamedPreparedImport | undefined;enterClaimStep(ctx.clock, 'import_content', undefined, 'fs');- const result = await importStreamedMarkdownFile(engine, filePath, p.sourcePath, { sourceId: row.source_id, noEmbed: true, ...(ctx.activePack ? { activePack: ctx.activePack } : {}),+ const result = await importStreamedMarkdownFile(engine, filePath, p.sourcePath, { sourceId: row.source_id, noEmbed: true, ...(ctx.activePack ? { activePack: ctx.activePack } : {}), history: ctx.history,coordinated: { snapshot: base, sha256: ref.sha256, slug: row.slug, moved: !!renamed, prepare: async value => { ready = value; return value.result; },owner: { kind: 'sync', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: base?.revision ?? null } } }, stat, policy).catch(error => { throw error instanceof OperationError && error.code === 'source_changed' ? changed() : error; });diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 7ad2014a63..f2136ca324 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -11,7 +11,7 @@ import { assertOriginUnclaimed, assertRevivalUnclaimed, classifyOriginUniqueViolimport { lockUnheldPageKeys, withHeldPageKeys, type HeldPageKeys } from './page-state/guards.ts';import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';import { readPageSnapshotsBatch } from './page-snapshot-batch.ts';-import { createPageVersion } from './page-state/versions.ts';+import { createPageVersion, type VersionHistory } from './page-state/versions.ts';import { moveSlugBindings, recordRenameAlias } from './page-state/rename-alias.ts';import { dropPhantomMigrationDuplicates } from './facts/ontology-rekey.ts';import { composablePgliteTransaction, transactionMemo } from './page-state/transactions.ts';@@ -2690,8 +2690,8 @@ export class PGLiteEngine implements BrainEngine {}// Versions- async createVersion(slug: string, opts?: { sourceId?: string; preimage?: PageSnapshot }): Promise<PageVersion> {- return createPageVersion(this, slug, opts?.sourceId ?? 'default', opts?.preimage);+ async createVersion(slug: string, opts?: { sourceId?: string; preimage?: PageSnapshot } & VersionHistory): Promise<PageVersion> {+ return createPageVersion(this, slug, opts?.sourceId ?? 'default', opts?.preimage, opts);}async getVersions<B extends boolean = true>(slug: string, opts?: GetVersionsOpts<B>): Promise<PageVersionRows<B>> {diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex b6ed43249d..d91cfa8907 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -9,7 +9,7 @@ import { assertOriginUnclaimed, assertRevivalUnclaimed, classifyOriginUniqueViolimport { lockUnheldPageKeys, withHeldPageKeys, type HeldPageKeys } from './page-state/guards.ts';import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';import { readPageSnapshotsBatch } from './page-snapshot-batch.ts';-import { createPageVersion } from './page-state/versions.ts';+import { createPageVersion, type VersionHistory } from './page-state/versions.ts';import { moveSlugBindings, recordRenameAlias } from './page-state/rename-alias.ts';import { dropPhantomMigrationDuplicates } from './facts/ontology-rekey.ts';import { composablePostgresTransaction, transactionMemo, withCommitChecks } from './page-state/transactions.ts';@@ -2523,8 +2523,8 @@ export class PostgresEngine implements BrainEngine {}// Versions- async createVersion(slug: string, opts?: { sourceId?: string; preimage?: PageSnapshot }): Promise<PageVersion> {- return createPageVersion(this, slug, opts?.sourceId ?? 'default', opts?.preimage);+ async createVersion(slug: string, opts?: { sourceId?: string; preimage?: PageSnapshot } & VersionHistory): Promise<PageVersion> {+ return createPageVersion(this, slug, opts?.sourceId ?? 'default', opts?.preimage, opts);}async getVersions<B extends boolean = true>(slug: string, opts?: GetVersionsOpts<B>): Promise<PageVersionRows<B>> {diff --git a/src/core/reason-trailers.ts b/src/core/reason-trailers.tsnew file mode 100644index 0000000000..688006fe26--- /dev/null+++ b/src/core/reason-trailers.ts@@ -0,0 +1,273 @@+/**+ * GBRA-217 (A6, A7): page change reasons read back from Git. A commit gbrain makes, and an outside commit made with+ * `git commit --trailer "gbrain-reason: <path>: <text>"`, carries one `gbrain-reason` trailer per path. Sync mirrors+ * them into page history (`page_versions.change_reason` on the snapshot the import archives); purge finds the commits+ * whose reason quotes a purged claim and tombstones them (`reason_purge_tombstones`, text-free), so no later import+ * brings that reason back.+ *+ * One reader serves both: a single streaming `git log` over the first-parent line (merges diffed against their first+ * parent, so a merge's own trailer decides for a conflict resolution and a side-branch commit never decides), with no+ * pathspec and no grep on the command line, parsed as it streams and stopped at a commit cap.+ */+import { realpathSync } from 'node:fs';+import { basename, dirname, join, relative, sep } from 'node:path';+import { hardenedGitStream, hardenedGitSync, REASON_LOG_OPTIONS } from './hardened-git.ts';+import { canonicalChangeReason, CHANGE_REASON_MAX } from './persistence/change-reason.ts';+import { scanTextSpans } from './secret-scan.ts';+import type { BrainEngine } from './engine.ts';+import type { Notice } from './agent-output.ts';+import type { VersionHistory } from './page-state/versions.ts';++export const SYNC_REASON_SCAN_CAP = 10_000;+export const PURGE_REASON_SCAN_CAP = 200_000;+const SCAN_TIMEOUT_MS = 120_000;+const OID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;++export interface TrailerCommit { sha: string; values: string[]; paths: string[] }+export type TrailerRead = { status: 'complete' | 'capped'; commits: number } | { status: 'failed'; commits: number; detail: string };++let caps = { sync: SYNC_REASON_SCAN_CAP, purge: PURGE_REASON_SCAN_CAP };+let gitStream = hardenedGitStream;+let scans = 0;+/** Test seams: smaller caps, a replacement Git runner, and the number of scans run (no argument restores each). */+export function __setReasonScanCapsForTests(next?: Partial<typeof caps>): void { caps = { sync: SYNC_REASON_SCAN_CAP, purge: PURGE_REASON_SCAN_CAP, ...next }; }+export function __setReasonGitStreamForTests(runner?: typeof hardenedGitStream): void { gitStream = runner ?? hardenedGitStream; }+export function __reasonScansForTests(): number { return scans; }+export function reasonScanCap(kind: 'sync' | 'purge'): number { return caps[kind]; }++class CapReached extends Error {}++/**+ * Streams `git log` over `revisions` (a range `a..b`, or one commit for its whole history), newest first along the+ * first parent, calling `visit` for each commit up to `cap`. Output is `-z`: each commit is an empty token, its OID,+ * its trailer values (one per line, folded lines joined), then its paths (the first prefixed by Git's blank line).+ */+export async function readReasonTrailers(gitRoot: string, revisions: string, cap: number, visit: (commit: TrailerCommit) => void): Promise<TrailerRead> {+ scans++;+ let state: 'sha' | 'trailers' | 'paths' = 'sha';+ let current: TrailerCommit | null = null;+ let commits = 0;+ let pending: Buffer[] = [];+ const flush = () => { if (current) visit(current); current = null; };+ const token = (text: string) => {+ if (state === 'paths' && text === '') { flush(); state = 'sha'; return; }+ if (state === 'sha') {+ if (text === '') return;+ if (!OID.test(text)) throw new Error(`unexpected git log record ${JSON.stringify(text.slice(0, 60))}`);+ if (++commits > cap) throw new CapReached();+ current = { sha: text, values: [], paths: [] };+ state = 'trailers';+ return;+ }+ if (state === 'trailers') { current!.values = text.split('\n').map(line => line.trim()).filter(Boolean); state = 'paths'; return; }+ current!.paths.push(current!.paths.length === 0 && text.startsWith('\n') ? text.slice(1) : text);+ };+ const onChunk = (chunk: Buffer) => {+ let start = 0;+ for (let end = chunk.indexOf(0); end >= 0; end = chunk.indexOf(0, start)) {+ const piece = chunk.subarray(start, end);+ token((pending.length ? Buffer.concat([...pending, piece]) : piece).toString('utf8'));+ pending = [];+ start = end + 1;+ }+ if (start < chunk.length) pending.push(chunk.subarray(start));+ };+ try {+ const result = await gitStream(gitRoot, ['log', ...REASON_LOG_OPTIONS, '--end-of-options', revisions, '--'], { timeoutMs: SCAN_TIMEOUT_MS, onChunk });+ if (!result.ok) return { status: 'failed', commits, detail: `git log ${result.reason}${result.status === undefined ? '' : ` ${result.status}`}` };+ if (pending.length) token(Buffer.concat(pending).toString('utf8'));+ flush();+ return { status: 'complete', commits };+ } catch (error) {+ if (error instanceof CapReached) return { status: 'capped', commits: cap };+ return { status: 'failed', commits, detail: error instanceof Error ? error.message : String(error) };+ }+}++/** The spellings of a repository-relative path a trailer may use: itself, and (under a scoped source) relative to the scope. */+export function pathForms(scopePrefix: string): (path: string) => string[] {+ const prefix = scopePrefix && !scopePrefix.endsWith('/') ? `${scopePrefix}/` : scopePrefix;+ return path => prefix && path.startsWith(prefix) ? [path, path.slice(prefix.length)] : [path];+}++/**+ * Each trailer value of `commit` by the path it names (`<path>: <text>`). A path may itself hold ": ", so the longest+ * spelling of a path the commit touched that prefixes a value owns it; a value naming no such path is malformed.+ */+export function trailerTexts(commit: TrailerCommit, forms: (path: string) => string[]): { byPath: Map<string, string>; malformed: number } {+ const byPath = new Map<string, string>();+ let malformed = 0;+ for (const value of commit.values) {+ let best: { path: string; length: number } | null = null;+ for (const path of commit.paths) {+ for (const form of forms(path)) {+ if (value.startsWith(`${form}: `) && (!best || form.length > best.length)) best = { path, length: form.length };+ }+ }+ if (!best) { malformed++; continue; }+ if (!byPath.has(best.path)) byPath.set(best.path, value.slice(best.length + 2));+ }+ return { byPath, malformed };+}++export interface ReasonDecision { commit: string; reason: string | null; commits: number }+export interface SyncReasonScan {+ status: 'complete' | 'capped' | 'failed';+ /** The repository's top level, which the scanned paths are relative to. */+ gitRoot: string;+ /** The range as `git log` names it (`<from>..<to>`, or `<to>` for its whole history). */+ range: string;+ /** Repository-relative path -> the newest first-parent commit that touched it, its reason, and how many commits touched it. */+ byPath: Map<string, ReasonDecision>;+ malformed: number;+ secrets: Array<{ commit: string; path: string }>;+ detail?: string;+}+++/**+ * A6: one scan per sync pass. For each path, the newest first-parent commit in the range that touched it decides: its+ * trailer for that path, or NULL when it has none, so an older reason is never stamped on newer text. Each reason is+ * canonicalised and secret-scanned (a secret, an over-long value or a tombstoned (commit, path) gives NULL); a value+ * naming no path its commit touched is malformed and counted. A failed or capped scan maps nothing.+ */+export async function scanSyncReasons(engine: BrainEngine, input: { sourceId: string; sourceRoot: string; from: string | null; to: string }): Promise<SyncReasonScan | null> {+ const repo = gitTopLevel(input.sourceRoot);+ if (!repo) return null;+ const range = input.from ? `${input.from}..${input.to}` : input.to;+ const byPath = new Map<string, ReasonDecision>();+ const secrets: SyncReasonScan['secrets'] = [];+ let malformed = 0;+ const tombstones = new Set((await engine.executeRaw<{ commit_sha: string; path: string }>(+ 'SELECT commit_sha, path FROM reason_purge_tombstones WHERE source_id = $1', [input.sourceId])).map(row => `${row.commit_sha}\0${row.path}`));+ const forms = pathForms(repo.scopePrefix);+ const read = await readReasonTrailers(repo.gitRoot, range, caps.sync, commit => {+ const texts = trailerTexts(commit, forms);+ malformed += texts.malformed;+ for (const path of commit.paths) {+ const seen = byPath.get(path);+ if (seen) { seen.commits++; continue; }+ const raw = texts.byPath.get(path);+ let reason = raw === undefined ? null : canonicalChangeReason(raw);+ if (reason !== null && [...reason].length > CHANGE_REASON_MAX) { reason = null; malformed++; }+ if (reason !== null && scanTextSpans(reason).some(span => span.finding !== null)) { reason = null; secrets.push({ commit: commit.sha, path }); }+ if (reason !== null && tombstones.has(`${commit.sha}\0${path}`)) reason = null;+ byPath.set(path, { commit: commit.sha, reason, commits: 1 });+ }+ });+ if (read.status === 'complete') return { status: 'complete', gitRoot: repo.gitRoot, range, byPath, malformed, secrets };+ return { status: read.status, gitRoot: repo.gitRoot, range, byPath: new Map(), malformed: 0, secrets: [], ...(read.status === 'failed' ? { detail: read.detail } : {}) };+}++/**+ * The Git top level holding `sourceRoot` and the source's path under it (both real paths), or null when it is in no+ * Git repository (a plain folder source, a repo-less brain): such a source runs no scan.+ */+export function gitTopLevel(sourceRoot: string): { gitRoot: string; scopePrefix: string } | null {+ let root: string;+ try { root = realpathSync(sourceRoot); } catch { return null; }+ const top = hardenedGitSync(root, ['rev-parse', '--show-toplevel'], { timeoutMs: 10_000, maxBytes: 64 * 1024 });+ if (!top.ok) return null;+ const gitRoot = realpathSync(top.stdout.toString('utf8').trim());+ return { gitRoot, scopePrefix: relative(gitRoot, root).split(sep).join('/') };+}++/** A file's path relative to the scan's Git top level, resolving its directory's real path (the file itself may be gone). */+function repoPathOf(scan: SyncReasonScan, filePath: string): string {+ let dir = dirname(filePath);+ try { dir = realpathSync(dir); } catch { /* the lexical path is the best guess */ }+ return relative(scan.gitRoot, join(dir, basename(filePath))).split(sep).join('/');+}++/**+ * What the snapshot an import of one file (absolute path) archives carries: the deciding reason, and a history gap when+ * the range held more than one commit for the file or the scan could not say. Nothing when the pass ran no scan (no Git+ * checkout).+ */+export function importHistoryFor(scan: SyncReasonScan | null | undefined, filePath: string): VersionHistory | undefined {+ if (!scan) return undefined;+ if (scan.status !== 'complete') return { reason: null, historyGap: true };+ const decision = scan.byPath.get(repoPathOf(scan, filePath));+ return { reason: decision?.reason ?? null, historyGap: (decision?.commits ?? 0) > 1 };+}++/** The pass's notices: a failed or capped scan (reasons stored as NULL, no backfill), and secrets found in pushed trailers. */+export function reasonScanNotices(scan: SyncReasonScan | null | undefined, sourceId: string): Notice[] {+ if (!scan) return [];+ const notices: Notice[] = [];+ if (scan.status !== 'complete') {+ const what = scan.status === 'capped' ? `reached its limit of ${caps.sync} commits` : `failed (${scan.detail ?? 'git error'})`;+ notices.push({ code: scan.status === 'capped' ? 'reason_scan_capped' : 'reason_scan_failed', kind: 'degraded',+ why: `Source ${sourceId} synced, but reading change reasons from Git for ${scan.range} ${what}. Content was imported; every reason in this pass is stored as empty and each imported page is marked as having a history gap. `+ + 'This release does not backfill reasons for that range, and a later sync will not rescan it. The reasons are still in Git.',+ fix: { argv: ['git', 'log', '--first-parent', '--format=%H %(trailers:key=gbrain-reason,valueonly)', scan.range], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Lists the reasons Git holds for the range this pass could not read; read-only, nothing in the brain changes.' } });+ }+ if (scan.secrets.length) {+ const named = scan.secrets.slice(0, 10).map(hit => `${hit.commit.slice(0, 12)} ${hit.path}`).join(', ');+ const more = scan.secrets.length > 10 ? `, and ${scan.secrets.length - 10} more` : '';+ notices.push({ code: 'reason_trailer_secret', kind: 'safety',+ why: `A gbrain-reason trailer already in Git looks like it holds a secret (${named}${more}); that reason was not stored. Git history keeps the commit message, so rotate the credential.`,+ user_message: `A commit message in source ${sourceId} appears to contain a credential (${named}${more}). Rotate it: Git history keeps the commit text.` });+ }+ return notices;+}++const cache = new Map<string, { at: number; scan: Promise<SyncReasonScan | null> }>();+const CACHE_TTL_MS = 10 * 60_000;++/**+ * Managed sync prepares one request at a time, each naming its pass's range: the pass's scan runs once per process and+ * its later requests reuse it. A purge clears the cache, so the next request reads its new tombstones.+ */+export function cachedSyncReasonScan(engine: BrainEngine, input: Parameters<typeof scanSyncReasons>[1]): Promise<SyncReasonScan | null> {+ const key = [input.sourceId, input.sourceRoot, input.from ?? '', input.to].join('\0');+ const hit = cache.get(key);+ if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.scan;+ const scan = scanSyncReasons(engine, input);+ cache.set(key, { at: Date.now(), scan });+ scan.catch(() => cache.delete(key));+ while (cache.size > 16) cache.delete(cache.keys().next().value!);+ return scan;+}+export function clearReasonScanCache(): void { cache.clear(); }++/** A7: what a purge's trailer scan found: the (commit, path) pairs whose reason quotes the claim, read up to HEAD. */+export type PurgeTrailerScan =+ | { status: 'no_repository' }+ | { status: 'complete'; gitRoot: string; head: string | null; hits: Array<{ commit: string; path: string }>; commits: number; limited: boolean }+ | { status: 'failed'; detail: string }+ | { status: 'capped'; cap: number };++/**+ * A7: the commits on the first-parent line of HEAD (`from..HEAD` for a recheck) whose `gbrain-reason` trailer quotes one of+ * `needles` (case-insensitive), each with the path its trailer names: the touched path it prefixes, else the text before+ * its first ": ". Capped at the purge cap, or at `limit` when the user chose one (then older commits are not read).+ */+export async function scanTrailersCarrying(sourceRoot: string, needles: readonly string[], opts: { from?: string | null; limit?: number } = {}): Promise<PurgeTrailerScan> {+ const repo = gitTopLevel(sourceRoot);+ if (!repo) return { status: 'no_repository' };+ const head = hardenedGitSync(repo.gitRoot, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], { timeoutMs: 10_000, maxBytes: 1024 });+ if (!head.ok) return head.reason === 'exit' && head.status === 1 ? { status: 'complete', gitRoot: repo.gitRoot, head: null, hits: [], commits: 0, limited: false }+ : { status: 'failed', detail: `git rev-parse ${head.reason}` };+ const tip = head.stdout.toString('utf8').trim();+ if (opts.from === tip) return { status: 'complete', gitRoot: repo.gitRoot, head: tip, hits: [], commits: 0, limited: false };+ const lowered = needles.map(needle => needle.toLowerCase()).filter(Boolean);+ const forms = pathForms(repo.scopePrefix);+ const hits: Array<{ commit: string; path: string }> = [];+ const cap = opts.limit ?? caps.purge;+ const read = await readReasonTrailers(repo.gitRoot, opts.from ? `${opts.from}..${tip}` : tip, cap, commit => {+ for (const value of commit.values) {+ const lower = value.toLowerCase();+ if (!lowered.some(needle => lower.includes(needle))) continue;+ let best: { path: string; length: number } | null = null;+ for (const path of commit.paths) for (const form of forms(path)) {+ if (value.startsWith(`${form}: `) && (!best || form.length > best.length)) best = { path, length: form.length };+ }+ hits.push({ commit: commit.sha, path: best?.path ?? value.split(': ')[0]! });+ }+ });+ if (read.status === 'failed') return { status: 'failed', detail: read.detail };+ if (read.status === 'capped' && opts.limit === undefined) return { status: 'capped', cap };+ return { status: 'complete', gitRoot: repo.gitRoot, head: tip, hits, commits: read.commits, limited: read.status === 'capped' };+}diff --git a/test/cli-flag-equals.test.ts b/test/cli-flag-equals.test.tsindex 8e1f4c413b..c441832985 100644--- a/test/cli-flag-equals.test.ts+++ b/test/cli-flag-equals.test.ts@@ -405,6 +405,7 @@ describe('#7619 split rules', () => {'src/core/git-head.ts': 'git child argv','src/core/git-remote.ts': 'git child argv','src/core/git/commit-push.ts': 'git child argv',+ 'src/core/hardened-git.ts': 'git child argv (the reason-trailer log options)','src/core/persistence/checkout-state.ts': 'git child argv','src/core/persistence/effect-git.ts': 'git child argv','src/core/persistence/git-door.ts': 'git child argv',@@ -413,6 +414,7 @@ describe('#7619 split rules', () => {'src/core/persistence/sync-origin-evidence.ts': 'git child argv','src/core/persistence/topology-filesystem.ts': 'git child argv','src/core/persistence/worktree-refresh.ts': 'git child argv',+ 'src/core/reason-trailers.ts': 'git child argv (the reason scan and its notice fix)','src/core/skillpack/bundle.ts': 'git child argv','src/core/skillpack/tarball.ts': 'tar child argv','src/core/source-health.ts': 'git child argv',diff --git a/test/reason-trailers-gbra217.test.ts b/test/reason-trailers-gbra217.test.tsnew file mode 100644index 0000000000..ec8b9352ce--- /dev/null+++ b/test/reason-trailers-gbra217.test.ts@@ -0,0 +1,432 @@+/**+ * GBRA-217 lane A2: page change reasons mirrored from Git trailers by sync (A6), and purge's reach into them (A7).+ *+ * 1. Protects: a sync stamps each archived snapshot with the reason its newest first-parent commit gives for the file+ * (`gbrain-reason: <path>: <text>`), never an older reason on newer text and never a side-branch commit's; a failed or+ * capped trailer scan still imports content, stores NULL, marks the gap and says so; a purge redacts a quoted claim in+ * every reason copy (snapshots, queued and retained Git effects) and tombstones the pushed commit so no re-import+ * brings it back, refusing before it deletes anything when it cannot read the history. A repo-less brain (the default+ * keyless install) gets reasons and purge with no refusal, no notice and no gap marker.+ * 2. Fails when: a reason lands on the wrong snapshot, a malformed or secret trailer is stored, a scan failure blocks+ * content or is silent, a purge leaves a reason copy, a tombstoned reason returns on a cold re-import, or a repo-less+ * source refuses or is marked.+ * 3. Real temp Git repositories, the real classic and managed sync, the real purge_fact handler; PGLite, plus Postgres+ * when DATABASE_URL is set. The only seams are the scan caps and a failing Git runner (reason-trailers.ts).+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';+import { operations } from '../src/core/operations.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { admitWrite, completeWrite } from '../src/core/persistence/journal.ts';+import { requestPrincipalForContext } from '../src/core/persistence/page-mutations.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { runSources } from '../src/commands/sources.ts';+import { performSync, type SyncResult } from '../src/commands/sync.ts';+import { runImport } from '../src/commands/import.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { __setReasonGitStreamForTests, __setReasonScanCapsForTests, clearReasonScanCache, gitTopLevel, importHistoryFor, scanSyncReasons,+ scanTrailersCarrying } from '../src/core/reason-trailers.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-reason-trailers-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+let serial = 0;++const page = (body: string) => `---\ntitle: Note\ntype: note\n---\n\n${body}\n`;+const SECRET = 'ghp_' + 'A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8';+const failingGit = async () => ({ ok: false as const, reason: 'timeout' as const });++function git(root: string, ...args: string[]): string {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}+function write(root: string, files: Record<string, string>): void {+ for (const [path, body] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), body); }+}+function commit(root: string, message: string, reasons: string[] = []): string {+ git(root, 'add', '-A');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-q', '-m', message,+ ...reasons.flatMap(reason => ['--trailer', `gbrain-reason: ${reason}`]));+ return git(root, 'rev-parse', 'HEAD');+}+function newRepo(files: Record<string, string>): string {+ const root = join(home, `repo-${++serial}`);+ mkdirSync(root);+ git(root, 'init', '-q', '-b', 'main');+ write(root, files);+ commit(root, 'initial content');+ return root;+}++type Source = { id: string; root: string };+async function classicSource(engine: BrainEngine, files: Record<string, string>): Promise<Source> {+ const id = `rt-${++serial}`;+ const root = newRepo(files);+ await runSources(engine, ['add', id, '--path', root, '--no-federated']);+ return { id, root };+}+const sync = (engine: BrainEngine, source: Source): Promise<SyncResult> =>+ performSync(engine, { repoPath: source.root, sourceId: source.id, noPull: true, noEmbed: true, noExtract: true, concurrency: 1 });++async function reasonsOf(engine: BrainEngine, sourceId: string, slug: string): Promise<{ reasons: Array<string | null>; gap: boolean }> {+ const rows = await engine.executeRaw<{ reason: string | null }>(`SELECT v.change_reason AS reason FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = $1 AND p.slug = $2 ORDER BY v.id`, [sourceId, slug]);+ const [mark] = await engine.executeRaw<{ gap: boolean }>('SELECT version_history_gap_at IS NOT NULL AS gap FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, slug]);+ return { reasons: rows.map(row => row.reason), gap: mark?.gap ?? false };+}+async function bodyOf(engine: BrainEngine, sourceId: string, slug: string): Promise<string> {+ const [row] = await engine.executeRaw<{ body: string }>('SELECT compiled_truth AS body FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, slug]);+ return row?.body ?? '';+}+const codes = (result: SyncResult) => (result.reason_notices ?? []).map(notice => notice.code);++const ctx = (engine: BrainEngine, sourceId: string): OperationContext => ({ engine, sourceId, remote: false, dryRun: false,+ config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} } } as OperationContext);+const opNamed = (name: string) => operations.find(o => o.name === name)!;+const run = (engine: BrainEngine, sourceId: string, name: string, params: Record<string, unknown>) =>+ opNamed(name).handler(ctx(engine, sourceId), params) as Promise<Record<string, any>>;++const factFence = (claim: string) => `<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |+<!--- gbrain:facts:end -->`;+/** A database-only page holding the claim as a fact, so purge_fact has a target in the source. */+async function seedFact(engine: BrainEngine, sourceId: string, slug: string, claim: string): Promise<number> {+ await importFromContent(engine, slug, `---\ntitle: Holder\ntype: person\n---\n# Holder\n\nProse.\n\n## Facts\n\n${factFence(claim)}\n`, { noEmbed: true, sourceId });+ await runExtractFacts(engine, { slugs: [slug], sourceId });+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE fact = $1 AND entity_slug = $2', [claim, slug]);+ return Number(row!.id);+}+/** A committed journal request in the source, for Git effects to hang off. */+async function committedRequest(engine: BrainEngine, sourceId: string): Promise<string> {+ const c = ctx(engine, sourceId);+ const slug = `notes/effect-example-${++serial}`;+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id = $1', [sourceId]);+ const admitted = await admitWrite(engine, { principal: await requestPrincipalForContext(c), operation: 'remember', sourceId, sourceIncarnation: source!.incarnation,+ slug, requestId: randomUUID(), callerIntent: { note: 'effect' }, intent: { note: 'effect' },+ authority: await submissionAuthority(c, 'remember', sourceId, source!.incarnation, slug) });+ await engine.transaction(tx => completeWrite(tx, admitted, 'committed', { status: 'inserted' }));+ return admitted.id;+}+async function gitEffect(engine: BrainEngine, sourceId: string, state: string, data: Record<string, unknown>): Promise<string> {+ const [row] = await engine.executeRaw<{ id: string }>(`INSERT INTO persistence_effects(request_id, kind, data, state, source_id, source_incarnation)+ SELECT $1::uuid, 'git', $2::text::jsonb, $3, s.id, s.incarnation FROM sources s WHERE s.id = $4 RETURNING id::text AS id`,+ [await committedRequest(engine, sourceId), JSON.stringify(data), state, sourceId]);+ return row!.id;+}+async function purge(engine: BrainEngine, sourceId: string, id: number, extra: Record<string, unknown> = {}) {+ const dry = await run(engine, sourceId, 'purge_fact', { id, source_id: sourceId, dry_run: true });+ return run(engine, sourceId, 'purge_fact', { id, source_id: sourceId, confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID(), ...extra });+}+async function refusal(p: Promise<unknown>): Promise<Record<string, any>> {+ try { await p; } catch (error) { if (error instanceof OperationError) return error.toJSON() as Record<string, any>; throw error; }+ throw new Error('expected a refusal');+}++const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home }, fn);++beforeAll(async () => inHome(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);+ engines.push(pg.engine); closePostgres = pg.close;+ }+ for (const engine of engines) await registerLocalWriter(engine, 'cli');+}), 180_000);+afterEach(() => { __setReasonScanCapsForTests(); __setReasonGitStreamForTests(); clearReasonScanCache(); });+afterAll(async () => {+ await inHome(async () => { for (const engine of engines) await disposePersistenceConsumer(engine).catch(() => undefined); });+ await engines[0]?.disconnect();+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++describe('A6: sync mirrors gbrain-reason trailers', () => {+ test('an outside commit\'s reason lands on the archived snapshot; malformed and secret trailers store nothing', async () => inHome(async () => {+ for (const engine of engines) {+ const s = await classicSource(engine, { 'notes/a.md': page('Edition one.'), 'notes/b.md': page('B one.'), 'notes/c.md': page('C one.') });+ expect((await sync(engine, s)).status).toBe('first_sync');+ write(s.root, { 'notes/a.md': page('Edition two.'), 'notes/b.md': page('B two.'), 'notes/c.md': page('C two.') });+ const head = commit(s.root, 'edit from outside gbrain', ['notes/a.md: Client asked for the 30-day window.',+ 'notes/missing.md: Names a file this commit never touched.', `notes/b.md: rotated token ${SECRET}`]);+ const result = await sync(engine, s);++ expect(await reasonsOf(engine, s.id, 'notes/a')).toEqual({ reasons: ['Client asked for the 30-day window.'], gap: false });+ expect(await reasonsOf(engine, s.id, 'notes/b')).toEqual({ reasons: [null], gap: false });+ expect(await reasonsOf(engine, s.id, 'notes/c')).toEqual({ reasons: [null], gap: false });+ expect(result.reason_trailers_malformed).toBe(1);+ expect(codes(result)).toEqual(['reason_trailer_secret']);+ const notice = result.reason_notices![0]!;+ expect(notice.why).toContain(`${head.slice(0, 12)} notes/b.md`);+ expect(notice.why).toContain('rotate the credential');+ expect(JSON.stringify(result)).not.toContain(SECRET);+ expect(JSON.stringify(await engine.executeRaw('SELECT change_reason FROM page_versions'))).not.toContain(SECRET);+ }+ }), 120_000);++ test('the newest commit in the range decides: an unannotated edit gives NULL, three edits give the third; both mark the gap', async () => inHome(async () => {+ for (const engine of engines) {+ const s = await classicSource(engine, { 'notes/a.md': page('A one.'), 'notes/c.md': page('C one.') });+ await sync(engine, s);+ write(s.root, { 'notes/a.md': page('A two.'), 'notes/c.md': page('C two.') });+ commit(s.root, 'first', ['notes/a.md: Annotated edit.', 'notes/c.md: First reason.']);+ write(s.root, { 'notes/a.md': page('A three.'), 'notes/c.md': page('C three.') });+ commit(s.root, 'second', ['notes/c.md: Second reason.']);+ write(s.root, { 'notes/c.md': page('C four.') });+ commit(s.root, 'third', ['notes/c.md: Third reason.']);+ await sync(engine, s);++ expect(await reasonsOf(engine, s.id, 'notes/a')).toEqual({ reasons: [null], gap: true });+ expect(await reasonsOf(engine, s.id, 'notes/c')).toEqual({ reasons: ['Third reason.'], gap: true });+ }+ }), 120_000);++ test('merges: the merge\'s own trailer decides a conflict resolution, a merge without one gives NULL, a discarded side edit never decides', async () => inHome(async () => {+ for (const engine of engines) {+ const s = await classicSource(engine, { 'notes/m.md': page('Base m.'), 'notes/d.md': page('Base d.'), 'notes/n.md': page('Base n.') });+ await sync(engine, s);+ git(s.root, 'branch', 'side');+ write(s.root, { 'notes/m.md': page('Main m.'), 'notes/d.md': page('Main d.'), 'notes/n.md': page('Main n.') });+ commit(s.root, 'main edits');+ git(s.root, 'checkout', '-q', 'side');+ write(s.root, { 'notes/m.md': page('Side m.'), 'notes/d.md': page('Side d.'), 'notes/n.md': page('Side n.') });+ commit(s.root, 'side edits', ['notes/m.md: Side reason for m.', 'notes/d.md: Side reason for d.', 'notes/n.md: Side reason for n.']);+ git(s.root, 'checkout', '-q', 'main');+ try { git(s.root, 'merge', '--no-ff', '--no-commit', 'side'); } catch { /* the conflicts are resolved below */ }+ write(s.root, { 'notes/m.md': page('Resolved m.') });+ git(s.root, 'checkout', '--ours', 'notes/d.md');+ git(s.root, 'checkout', '--theirs', 'notes/n.md');+ git(s.root, 'add', '-A');+ git(s.root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-q', '-m', 'merge side', '-m', 'gbrain-reason: notes/m.md: Merged both drafts.');+ await sync(engine, s);++ expect((await reasonsOf(engine, s.id, 'notes/m')).reasons).toEqual(['Merged both drafts.']);+ expect((await reasonsOf(engine, s.id, 'notes/n')).reasons).toEqual([null]);+ expect((await reasonsOf(engine, s.id, 'notes/d')).reasons).toEqual([null]);+ expect(await bodyOf(engine, s.id, 'notes/n')).toContain('Side n.');+ expect(await bodyOf(engine, s.id, 'notes/d')).toContain('Main d.');+ }+ }), 120_000);++ test('a capped or failed scan imports content, stores NULL, marks the gap and says there is no backfill; an unchanged re-sync stays NULL', async () => inHome(async () => {+ for (const engine of engines) {+ const s = await classicSource(engine, { 'notes/a.md': page('A one.'), 'notes/b.md': page('B one.') });+ await sync(engine, s);+ __setReasonScanCapsForTests({ sync: 1 });+ write(s.root, { 'notes/a.md': page('A two.') });+ commit(s.root, 'a', ['notes/a.md: Reason for a.']);+ write(s.root, { 'notes/b.md': page('B two.') });+ commit(s.root, 'b', ['notes/b.md: Reason for b.']);+ const capped = await sync(engine, s);+ expect(codes(capped)).toEqual(['reason_scan_capped']);+ expect(capped.reason_notices![0]!.why).toContain('does not backfill');+ expect(await bodyOf(engine, s.id, 'notes/a')).toContain('A two.');+ expect(await reasonsOf(engine, s.id, 'notes/a')).toEqual({ reasons: [null], gap: true });+ expect(await reasonsOf(engine, s.id, 'notes/b')).toEqual({ reasons: [null], gap: true });+ __setReasonScanCapsForTests();+ expect(codes(await sync(engine, s))).toEqual([]);+ expect((await reasonsOf(engine, s.id, 'notes/a')).reasons).toEqual([null]);++ __setReasonGitStreamForTests(failingGit);+ write(s.root, { 'notes/a.md': page('A three.') });+ commit(s.root, 'a again', ['notes/a.md: Another reason for a.']);+ const failed = await sync(engine, s);+ expect(codes(failed)).toEqual(['reason_scan_failed']);+ expect(failed.reason_notices![0]!.fix).toMatchObject({ argv: expect.arrayContaining(['git', 'log', '--first-parent']) });+ expect(await bodyOf(engine, s.id, 'notes/a')).toContain('A three.');+ expect(await reasonsOf(engine, s.id, 'notes/a')).toEqual({ reasons: [null, null], gap: true });+ __setReasonGitStreamForTests();+ await sync(engine, s);+ expect((await reasonsOf(engine, s.id, 'notes/a')).reasons).toEqual([null, null]);+ }+ }), 120_000);++ test('a 5,000-path commit is read in process: every path is mapped, only the annotated one has a reason', async () => inHome(async () => {+ const root = newRepo({ 'README.md': 'seed\n' });+ const base = git(root, 'rev-parse', 'HEAD');+ const files: Record<string, string> = {};+ for (let i = 0; i < 5000; i++) files[`bulk/f${String(i).padStart(4, '0')}.md`] = page(`File ${i}.`);+ write(root, files);+ const head = commit(root, 'bulk', ['bulk/f4321.md: Only this file has a reason.']);+ const scan = await scanSyncReasons(engines[0]!, { sourceId: 'none', sourceRoot: root, from: base, to: head });+ expect(scan?.status).toBe('complete');+ expect(scan!.byPath.size).toBe(5000);+ expect(importHistoryFor(scan, join(root, 'bulk/f4321.md'))).toEqual({ reason: 'Only this file has a reason.', historyGap: false });+ expect(importHistoryFor(scan, join(root, 'bulk/f0001.md'))).toEqual({ reason: null, historyGap: false });+ }), 120_000);+});++describe('A7: purge reaches change reasons', () => {+ test('a claim inside a longer reason is redacted on every snapshot and Git effect, and a cold re-import does not bring it back', async () => inHome(async () => {+ for (const engine of engines) {+ const claim = `Door code is ${4400 + engines.indexOf(engine)}`;+ const s = await classicSource(engine, { 'notes/a.md': page('A one.'), 'notes/b.md': page('B one.') });+ await sync(engine, s);+ write(s.root, { 'notes/a.md': page('A two.'), 'notes/b.md': page('B two.') });+ const pushed = commit(s.root, 'edit', [`notes/a.md: Updated after the call where ${claim} was confirmed.`, 'notes/b.md: Routine tidy-up.']);+ await sync(engine, s);+ expect((await reasonsOf(engine, s.id, 'notes/a')).reasons).toEqual([`Updated after the call where ${claim} was confirmed.`]);+ const id = await seedFact(engine, s.id, 'people/holder-example', claim);++ const keep = 'gbrain-reason: notes/b.md: Routine tidy-up.';+ const carrying = `gbrain-reason: notes/a.md: Updated after the call where ${claim} was confirmed.`;+ const effectData = { version: 2, commit_line: `reason ${claim}`, commit_trailers: [carrying, keep], commit_trailer: carrying };+ const queued = await gitEffect(engine, s.id, 'queued', effectData);+ const retained = await gitEffect(engine, s.id, 'committed', effectData);++ const done = await purge(engine, s.id, id);+ expect(done.state).toBe('committed');+ expect(done.purge.removed).toMatchObject({ reason_purge_tombstones: 1, persistence_effects: 2 });+ expect(done.purge.removed.page_versions).toBeGreaterThanOrEqual(1);+ expect(done.residuals).toEqual(expect.arrayContaining([expect.objectContaining({ store: 'git_commit_messages', status: 'out_of_reach', remaining: 1 })]));+ expect((await reasonsOf(engine, s.id, 'notes/a')).reasons).toEqual(['[purged]']);+ expect((await reasonsOf(engine, s.id, 'notes/b')).reasons).toEqual(['Routine tidy-up.']);+ const lower = claim.toLowerCase();+ expect(await engine.executeRaw('SELECT 1 FROM page_versions WHERE strpos(lower(change_reason), $1) > 0', [lower])).toHaveLength(0);+ for (const effect of [queued, retained]) {+ const [after] = await engine.executeRaw<{ data: Record<string, unknown> }>('SELECT data FROM persistence_effects WHERE id = $1::bigint', [effect]);+ expect(after!.data).toEqual({ version: 2, commit_line: '[purged]', commit_trailers: [keep] });+ }+ expect(await engine.executeRaw('SELECT commit_sha, path FROM reason_purge_tombstones WHERE source_id = $1', [s.id]))+ .toEqual([{ commit_sha: pushed, path: 'notes/a.md' }]);++ // Cold re-import: the database pages go back to their first editions and the source forgets its last commit.+ await importFromContent(engine, 'notes/a', page('A one.'), { noEmbed: true, sourceId: s.id });+ await importFromContent(engine, 'notes/b', page('B one.'), { noEmbed: true, sourceId: s.id });+ await engine.executeRaw('UPDATE sources SET last_commit = NULL WHERE id = $1', [s.id]);+ await sync(engine, s);+ expect(await bodyOf(engine, s.id, 'notes/a')).toContain('A two.');+ expect((await reasonsOf(engine, s.id, 'notes/a')).reasons.at(-1)).toBeNull();+ expect((await reasonsOf(engine, s.id, 'notes/b')).reasons.at(-1)).toBe('Routine tidy-up.');+ }+ }), 180_000);++ test('a running Git effect carrying the claim blocks the purge with the pending-recovery refusal', async () => inHome(async () => {+ for (const engine of engines) {+ const claim = `Vault pin is ${7100 + engines.indexOf(engine)}`;+ const s = await classicSource(engine, { 'notes/a.md': page('A one.') });+ await sync(engine, s);+ const id = await seedFact(engine, s.id, 'people/runner-example', claim);+ await gitEffect(engine, s.id, 'running', { commit_line: `pin ${claim}` });+ expect((await refusal(purge(engine, s.id, id))).code).toBe('purge_blocked_pending_recovery');+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE id = $1', [id])).toHaveLength(1);+ }+ }), 120_000);++ test('A-T7b: a scan failure refuses before deleting anything (wait); over the cap refuses with ask_user, and a chosen limit proceeds', async () => inHome(async () => {+ for (const engine of engines) {+ const claim = `Gate code is ${5200 + engines.indexOf(engine)}`;+ const s = await classicSource(engine, { 'notes/a.md': page('A one.') });+ await sync(engine, s);+ write(s.root, { 'notes/a.md': page('A two.') });+ const pushed = commit(s.root, 'edit', [`notes/a.md: Changed once ${claim} was rotated.`]);+ await sync(engine, s);+ const id = await seedFact(engine, s.id, 'people/gate-example', claim);++ __setReasonGitStreamForTests(failingGit);+ const failed = await refusal(purge(engine, s.id, id));+ expect(failed).toMatchObject({ code: 'reason_purge_scan_failed' });+ expect(failed.fix).toMatchObject({ next: 'wait' });+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE id = $1', [id])).toHaveLength(1);+ expect((await reasonsOf(engine, s.id, 'notes/a')).reasons).toEqual([`Changed once ${claim} was rotated.`]);+ __setReasonGitStreamForTests();++ __setReasonScanCapsForTests({ purge: 1 });+ const capped = await refusal(purge(engine, s.id, id));+ expect(capped).toMatchObject({ code: 'reason_purge_scan_capped' });+ expect(capped.fix).toMatchObject({ next: 'ask_user', argv: expect.arrayContaining(['--reason-scan-limit']) });+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE id = $1', [id])).toHaveLength(1);++ const limited = await purge(engine, s.id, id, { reason_scan_limit: 1 });+ expect(limited.state).toBe('committed');+ expect(limited.residuals).toEqual(expect.arrayContaining([expect.objectContaining({ store: 'git_commit_messages', reason: 'reason_scan_limit' })]));+ expect(await engine.executeRaw('SELECT commit_sha FROM reason_purge_tombstones WHERE source_id = $1', [s.id])).toEqual([{ commit_sha: pushed }]);+ expect((await reasonsOf(engine, s.id, 'notes/a')).reasons).toEqual(['[purged]']);+ __setReasonScanCapsForTests();+ }+ }), 120_000);+});++describe('A-T11: repo-less brains are first class', () => {+ test('put_page reasons, purge of a quoted claim and a plain-folder import: no refusal, no notice, no gap marker', async () => inHome(async () => {+ for (const engine of engines) {+ const n = engines.indexOf(engine);+ const claim = `Alarm code is ${6300 + n}`;+ const slug = `policies/policy-4a-example-${n}`;+ const [source] = await engine.executeRaw<{ local_path: string | null }>(`SELECT local_path FROM sources WHERE id = 'default'`);+ expect(source?.local_path ?? null).toBeNull();+ await run(engine, 'default', 'put_page', { slug, content: page('Edition one.'), wait_ms: 30_000 });+ const revision = String((await run(engine, 'default', 'get_page', { slug, include_content: true })).revision);+ const second = await run(engine, 'default', 'put_page', { slug, content: page('Edition two.'), expected_revision: revision,+ reason: `Board asked because ${claim} leaked.`, wait_ms: 30_000 });+ expect((second.outcome ?? second).reason_recorded).toMatchObject({ version: true, git: 'no_repository' });+ const versions = await run(engine, 'default', 'get_versions', { slug }) as unknown as Array<Record<string, unknown>>;+ expect(versions.map(row => row.replaced_because)).toEqual([`Board asked because ${claim} leaked.`]);++ const id = await seedFact(engine, 'default', `people/alarm-example-${n}`, claim);+ const done = await purge(engine, 'default', id);+ expect(done.state).toBe('committed');+ expect(done.purge.removed.reason_purge_tombstones ?? 0).toBe(0);+ expect(done.residuals.map((r: { store: string }) => r.store)).not.toContain('git_commit_messages');+ const after = await run(engine, 'default', 'get_versions', { slug }) as unknown as Array<Record<string, unknown>>;+ expect(after.map(row => row.replaced_because)).toEqual(['[purged]']);+ expect(await engine.executeRaw(`SELECT 1 FROM pages WHERE source_id = 'default' AND slug = $1 AND version_history_gap_at IS NOT NULL`, [slug])).toHaveLength(0);++ const folder = join(home, `folder-${++serial}`);+ write(folder, { 'notes/plain.md': page('Plain one.') });+ expect(gitTopLevel(folder)).toBeNull();+ expect(await scanSyncReasons(engine, { sourceId: 'default', sourceRoot: folder, from: null, to: 'HEAD' })).toBeNull();+ expect(await scanTrailersCarrying(folder, [claim])).toEqual({ status: 'no_repository' });+ await runImport(engine, [folder, '--no-embed']);+ write(folder, { 'notes/plain.md': page('Plain two.') });+ await runImport(engine, [folder, '--no-embed']);+ expect(await bodyOf(engine, 'default', 'notes/plain')).toContain('Plain two.');+ expect(await reasonsOf(engine, 'default', 'notes/plain')).toEqual({ reasons: [null], gap: false });+ }+ }), 180_000);+});++describe('A6 on a managed source', () => {+ test('managed sync mirrors the reason on the archived snapshot; a failed scan reports on the pass result', async () => inHome(async () => {+ for (const engine of engines) {+ __setReasonGitStreamForTests();+ const id = `rt-managed-${++serial}`;+ const root = newRepo({ 'notes/a.md': page('A one.') });+ await engine.executeRaw('UPDATE persistence_brain SET enabled = false WHERE singleton = 1');+ await engine.executeRaw(`INSERT INTO sources(id, name, local_path, config) VALUES ($1, $1, $2, '{}')`, [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled = true WHERE singleton = 1');+ try {+ expect((await performManagedSync(engine, { sourceId: id, noPull: true })).status).toBe('first_sync');+ write(root, { 'notes/a.md': page('A two.') });+ commit(root, 'edit', ['notes/a.md: Managed reason.']);+ await performManagedSync(engine, { sourceId: id, noPull: true });+ expect(await reasonsOf(engine, id, 'notes/a')).toEqual({ reasons: ['Managed reason.'], gap: false });++ __setReasonGitStreamForTests(failingGit);+ clearReasonScanCache();+ write(root, { 'notes/a.md': page('A three.') });+ commit(root, 'edit again', ['notes/a.md: Lost reason.']);+ const failed = await performManagedSync(engine, { sourceId: id, noPull: true });+ expect(codes(failed)).toEqual(['reason_scan_failed']);+ expect(await reasonsOf(engine, id, 'notes/a')).toEqual({ reasons: ['Managed reason.', null], gap: true });+ } finally {+ await disposePersistenceConsumer(engine).catch(() => undefined);+ await engine.executeRaw('UPDATE persistence_brain SET enabled = false WHERE singleton = 1');+ }+ }+ }), 180_000);+});