Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 1: content-addressed discovery prescreen, guarded kernel run and the file_drift guard

garrytan2ad41a3e4b8c
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index c25fab1957..49defef023 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -89,6 +89,7 @@ Every hold and error has three fields, from one table
|---|---|---|---|---|
| `worktree_dirty` | page | retry_when_clean | no | held 3 times: the file keeps changing without being committed |
| `concurrent_write` | page | reconcile | yes | always: the file and the database page diverge |
+| `file_drift` | page | reconcile | yes | always: the page changed in the database since its file was last imported |
| `preparation_stalled` | page | retry, upgrade | no | held 3 times, or writer status names a step that never finishes |
| `invalid_fence` | page | repair | no | the fence repair preview offers no plan (a manual reason) |
| `invalid_frontmatter` | page | repair | no | the repair preview needs an interpretation (--include-ambiguous) |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 4f42cdd6ce..806134adf4 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -12,7 +12,7 @@ src/commands/extract.ts 2637 ratchet grown v0.46.26.0 megawave: FS-walk stamp sn
src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes
src/commands/serve-http.ts 931 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts)
src/core/ai/gateway.ts 4523 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text
-src/commands/sync.ts 529 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts)
+src/commands/sync.ts 531 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); +2 #6712 PR 1 lane B: SyncResult.prescreened interface field (the prescreen lives in persistence/sync-prescreen.ts)
src/core/cycle.ts 3314 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field
src/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)
src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count
@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
src/core/config.ts 1978 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)
-src/core/persistence/sync-run.ts 1690 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)
+src/core/persistence/sync-run.ts 1722 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); +32 #6712 PR 1 lane B: prescreenRun (the cursor CAS of the guarded kernel run: waivedCursor/writeCursor/stampProgress are private here; the kernel checks live in sync-waivers.ts waivePrescreenedRun, the prescreen in sync-prescreen.ts), the freeze-time file_drift guard, the missing-manifest re-discovery and the prescreened count
src/core/bootstrap/harness.ts 2615 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
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 705 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
diff --git a/src/commands/doctor/checks/git-holds.ts b/src/commands/doctor/checks/git-holds.ts
index 0c18615d77..5f2b09464d 100644
--- a/src/commands/doctor/checks/git-holds.ts
+++ b/src/commands/doctor/checks/git-holds.ts
@@ -35,9 +35,9 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[
const route = coverageRoute(source);
const steps = holdRepairSteps(source.source_id, route, auto);
return { source_id: source.source_id, held: source.missing + source.stale, stale: source.stale, missing: source.missing, ...(route.fences ? { fences: route.fences } : {}), ...(route.concurrent ? { concurrent: route.concurrent } : {}),
- ...(route.stalled ? { stalled: route.stalled } : {}), ...(route.dirty ? { dirty: route.dirty } : {}),
+ ...(route.stalled ? { stalled: route.stalled } : {}), ...(route.dirty ? { dirty: route.dirty } : {}), ...(route.drift ? { drift: route.drift } : {}),
first: (listing.get(source.source_id) ?? []).map(hold => ({ path: hold.path, code: hold.code, ...(hold.meta.reason ? { reason: hold.meta.reason } : {}), why: gitHoldFix(hold, auto).why })),
- escalated: source.missing + source.stale - (images.get(source.source_id) ?? 0) > policy.escalateCount,
+ escalated: source.missing + source.stale - (images.get(source.source_id) ?? 0) - (route.drift ?? 0) > policy.escalateCount,
status: `gbrain sources status ${source.source_id}`, repair: steps.commands.join('; '),
argv: steps.argv, next: steps.text };
});
diff --git a/src/commands/sources-retry-held.ts b/src/commands/sources-retry-held.ts
index ac05d9200b..ae730b7e4e 100644
--- a/src/commands/sources-retry-held.ts
+++ b/src/commands/sources-retry-held.ts
@@ -90,8 +90,9 @@ function gitNextStep(sourceId: string, dryRun: boolean, scheduled: Scheduled): {
const concurrent = scheduled.items.filter(item => item.code === 'concurrent_write').length;
const stalled = scheduled.items.filter(item => item.code === 'preparation_stalled').length;
const dirty = scheduled.items.filter(item => item.code === 'worktree_dirty').length;
+ const drift = scheduled.items.filter(item => item.code === 'file_drift').length;
return { text: `${count} held file(s) scheduled for a re-screen; none has run yet. ${automatic} Run it now with: ${sync}, then verify with: gbrain sources status ${sourceId}. `
- + `A file that still refuses stays held; ${holdRepairSteps(sourceId, { fences, others: count - fences - concurrent - stalled - dirty, concurrent, stalled, dirty }, scheduled.fenceAuto).text}.`,
+ + `A file that still refuses stays held; ${holdRepairSteps(sourceId, { fences, others: count - fences - concurrent - stalled - dirty - drift, concurrent, stalled, dirty, drift }, scheduled.fenceAuto).text}.`,
fix: { argv: scheduled.sync, consent: [], actor: 'agent', requires_exclusive: false, verify,
why: `The sync re-screens the ${count} scheduled file(s): each one that now passes imports and its hold clears; the rest stay held without blocking the sync.` } };
}
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index a33e82590d..06590db5d5 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -53,7 +53,9 @@ export interface SyncResult {
*/
malformedSkipped?: number;
/** #5751: unchanged managed working-tree files skipped although a no-op publication cannot resolve their admit reason. */
- legacySkips?: { contextualMode: number; canonicalBytes: number }; /** #5984: managed entries advanced without a write (DX-A7), and how a still-unfinished managed write's wait ended (DX-A3). */ waived?: { imports: number; deletes: number }; writeWait?: import('../core/persistence/sync-write-diagnostic.ts').ManagedSyncWriteWait;
+ legacySkips?: { contextualMode: number; canonicalBytes: number }; /** #5984: managed entries advanced without a write (DX-A7), and how a still-unfinished managed write's wait ended (DX-A3). */ waived?: { imports: number; deletes: number };
+ /** #6712 PR 1: of `waived.imports`, the entries the guarded no-op kernel passed straight from the discovery prescreen (no freeze or preparation). */
+ prescreened?: number; writeWait?: import('../core/persistence/sync-write-diagnostic.ts').ManagedSyncWriteWait;
/** Managed sync: files skipped because another origin keeps their slug, and links derived after the checkpoint. */
slugCollisions?: import('../core/persistence/sync-discovery.ts').SyncSlugCollision[];
fileRefusals?: import('../core/persistence/sync-discovery.ts').SyncFileRefusal[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction;
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.ts
index 2afe131647..d090801d9d 100644
--- a/src/commands/sync/operator.ts
+++ b/src/commands/sync/operator.ts
@@ -51,6 +51,8 @@ leaves a file out, and each refusal names the file, why, and its fix.
at HEAD now (still dirty: refused still_dirty)
preparation_stalled re-screened (the writer, not the file, stalled)
concurrent_write refused: a person reconciles the two versions
+ file_drift refused: a person picks the database or the file
+ (gbrain repair file-drift --prefer database|file)
${CONTENT_HOLD_CODES.padEnd(22)}repaired by the content-repair lane (gbrain repair content,
each file bound to the bytes its plan read, under the
fences.repair caps), then re-screened; per
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index cf04bfd125..5ac1e60c90 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -205,6 +205,7 @@ export const CODES = {
feedback_not_authorized: { class: 'host_only', summary: "This caller may not change the brain's shared ranking for that source.", docs: 'docs/guides/retrieval-feedback.md#feedback_not_authorized' },
fetch_failed: { class: 'retryable', summary: "Fetching the upstream failed." },
fix_not_writable: { class: 'host_only', summary: "A gbrain lint fix was not applied because the file refused the write (EACCES, EPERM or EROFS); the file was left unchanged.", why: "Lint repairs files in place, and this file's permissions or a read-only mount stopped the write; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#fix-not-writable', suggestion: "Make the file writable by the user running gbrain, or pass its directory or file name to gbrain lint --exclude, then lint again." },
+ file_drift: { class: 'caller', summary: "A managed sync import would have overwritten a database version of the page that sync never saw (the page changed since its file was last imported), so the file is held and the page keeps the database version.", why: "Sync imports a file only when the page is still at the revision its last recorded import wrote, or when the import changes nothing. Here the page moved (a database-only write, or no import record to compare on an upgraded brain) and the file's content differs, so importing would silently replace the newer database copy. Pages under storage.keep_db prefixes are never held: the keep_db worker reconciles them from the database.", docs: 'docs/guides/write-refusals.md#file_drift', suggestion: 'Preview with gbrain repair file-drift --source <source> --slug <slug> --prefer database (keep the database copy and rewrite the file) or --prefer file (import the file), decide with the user, then apply it with the plan hash; the next gbrain sync --source <source> --no-pull re-screens the hold.' },
file_removed_during_scan: { class: 'retryable', summary: "A file lint listed was removed before lint read it, so it was not linted.", why: "Another process deleted or renamed the file during the run; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#file-removed-during-scan', suggestion: "Re-run gbrain lint on the same target; it lints the files present now." },
file_too_large: { class: 'caller', summary: "The file is over the page size limit (24 MiB for a Markdown page, 5 MB for a code file), so it was not imported.", why: "Every page under the limit is stored, chunked and searchable whatever its size; the limit bounds what one page may hold in this release. The same bytes refuse on every retry. A smaller page refused by an MCP or HTTP transport is a different refusal.", docs: 'docs/guides/write-refusals.md#file_too_large', suggestion: 'Leave the file out of the source (sync.exclude), or, if it must be in the brain, split it into files under the limit; then sync or import again. Never split a page under the limit.' },
follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index e2cdf876d2..d5541a192a 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -14,7 +14,7 @@ import type { WriteRequest } from './model.ts';
export type PublicationBoundary = Parameters<NonNullable<PublicationHooks['boundary']>>[0];
export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid` | 'effect:embedding:settle'
- | 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'consumer:prepared'
+ | 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'sync:prescreened' | 'consumer:prepared'
| 'consumer:preparing' | 'lane:applied'
// #6712 PR 0: after `freezeEntry` froze an import entry (its bytes are read) and before the request is admitted or published.
| 'sync:after_freeze'
diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.ts
index f508b14f2b..d0ea874a2b 100644
--- a/src/core/persistence/held-reads.ts
+++ b/src/core/persistence/held-reads.ts
@@ -37,7 +37,9 @@ export interface HeldCoverage { source_id: string; missing: number; stale: numbe
/** #6278 `preparation_stalled` holds: the writer stalled, not the file; they route to writer status and a re-screen. */
stalled?: number;
/** #6340 `worktree_dirty` holds: an uncommitted local edit; they clear once the file is committed and re-screened. */
- dirty?: number }
+ dirty?: number;
+ /** #6712 `file_drift` holds: a database edit sync would have overwritten; they route to `gbrain repair file-drift`. */
+ drift?: number }
/** `get_page.file_held`. */
export interface FileHeld {
@@ -94,10 +96,11 @@ export function readHeldCoverage(engine: Exec, scope: { sourceId?: string; sourc
const ids = scope.sourceIds ?? (scope.sourceId !== undefined && scope.sourceId !== ALL_SOURCES ? [scope.sourceId] : null);
if (ids && !ids.length) return Promise.resolve([]);
return cached(request, `coverage:${ids ? [...ids].sort().join(',') : '*'}`, async () => {
- const rows = await engine.executeRaw<{ source_id: string; count: number | string; stale: number | string; fences: number | string; concurrent: number | string; stalled: number | string; dirty: number | string }>(`SELECT s.id AS source_id,
+ const rows = await engine.executeRaw<{ source_id: string; count: number | string; stale: number | string; fences: number | string; concurrent: number | string; stalled: number | string; dirty: number | string; drift: number | string }>(`SELECT s.id AS source_id,
COALESCE((h.completed_keys->0->>'count')::int,0) AS count, COALESCE((h.completed_keys->0->>'stale')::int,0) AS stale,
COALESCE((h.completed_keys->0->>'fences')::int,0) AS fences, COALESCE((h.completed_keys->0->>'concurrent')::int,0) AS concurrent,
- COALESCE((h.completed_keys->0->>'stalled')::int,0) AS stalled, COALESCE((h.completed_keys->0->>'dirty')::int,0) AS dirty
+ COALESCE((h.completed_keys->0->>'stalled')::int,0) AS stalled, COALESCE((h.completed_keys->0->>'dirty')::int,0) AS dirty,
+ COALESCE((h.completed_keys->0->>'drift')::int,0) AS drift
FROM op_checkpoints h JOIN sources s ON h.fingerprint=s.id||':'||s.incarnation::text
WHERE h.op=$1 AND s.archived IS NOT TRUE AND ($2::text[] IS NULL OR s.id=ANY($2::text[]))
AND COALESCE((h.completed_keys->0->>'count')::int,0)>0
@@ -107,15 +110,18 @@ export function readHeldCoverage(engine: Exec, scope: { sourceId?: string; sourc
const concurrent = Math.min(Number(row.concurrent), count - fences);
const stalled = Math.min(Number(row.stalled), count - fences - concurrent);
const dirty = Math.min(Number(row.dirty), count - fences - concurrent - stalled);
- return { source_id: row.source_id, missing: count - stale, stale, ...(fences ? { fences } : {}), ...(concurrent ? { concurrent } : {}), ...(stalled ? { stalled } : {}), ...(dirty ? { dirty } : {}) };
+ const drift = Math.min(Number(row.drift), count - fences - concurrent - stalled - dirty);
+ return { source_id: row.source_id, missing: count - stale, stale, ...(fences ? { fences } : {}), ...(concurrent ? { concurrent } : {}), ...(stalled ? { stalled } : {}), ...(dirty ? { dirty } : {}),
+ ...(drift ? { drift } : {}) };
});
});
}
/** D6: which repair a held source needs, from its counts. */
export function coverageRoute(source: HeldCoverage): HoldRepairRoute {
- const fences = source.fences ?? 0, concurrent = source.concurrent ?? 0, stalled = source.stalled ?? 0, dirty = source.dirty ?? 0;
- return { fences, others: Math.max(0, source.missing + source.stale - fences - concurrent - stalled - dirty), ...(concurrent ? { concurrent } : {}), ...(stalled ? { stalled } : {}), ...(dirty ? { dirty } : {}) };
+ const fences = source.fences ?? 0, concurrent = source.concurrent ?? 0, stalled = source.stalled ?? 0, dirty = source.dirty ?? 0, drift = source.drift ?? 0;
+ return { fences, others: Math.max(0, source.missing + source.stale - fences - concurrent - stalled - dirty - drift), ...(concurrent ? { concurrent } : {}), ...(stalled ? { stalled } : {}),
+ ...(dirty ? { dirty } : {}), ...(drift ? { drift } : {}) };
}
/**
@@ -132,6 +138,7 @@ export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; rout
const concurrent = sources.filter(source => source.route?.concurrent).map(source => source.source_id);
const stalled = sources.filter(source => source.route?.stalled).map(source => source.source_id);
const dirty = sources.filter(source => source.route?.dirty).map(source => source.source_id);
+ const drift = sources.filter(source => source.route?.drift).map(source => source.source_id);
const first = sources[0]!;
const parts = [
...(frontmatter.length ? [`Please run ${frontmatter.join(', ')} on the brain host to preview the fixes, then apply them.`] : []),
@@ -139,6 +146,7 @@ export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; rout
+ `to see each one's state and repair the rest now, run ${fences.join(', ')} on the brain host (a read-only preview that prints the apply command).`] : []),
...(concurrent.length ? [`Some notes changed in their files while an agent saved a different version to the brain, so both were kept: on the brain host run ${concurrent.map(id => `'gbrain sources status ${id}'`).join(', ')} and reconcile each named note with 'gbrain sources reconcile <source> <slug> --preview'.`] : []),
...(stalled.length ? [`Some files are held because the brain's write owner could not finish preparing them (the files themselves are fine): on the brain host run ${stalled.map(id => `'gbrain sources writer status --source ${id} --json'`).join(', ')} to see what the owner was stuck on, fix that or upgrade gbrain, then 'gbrain sources retry-held <source>' and the same sync.`] : []),
+ ...(drift.length ? [`Some notes were edited in the brain after their files were last imported, so sync kept the brain's version instead of overwriting it: on the brain host run ${drift.map(id => `'gbrain sources status ${id}'`).join(', ')} and resolve each named note with 'gbrain repair file-drift --source <source> --slug <slug> --prefer database' (or '--prefer file').`] : []),
...(dirty.length ? [`Some files have uncommitted edits in the brain's checkout that sync would not overwrite: on the brain host commit them, then run ${dirty.map(id => `'gbrain sync unblock --source ${id} --apply'`).join(', ')} (or 'gbrain sources retry-held <source>') and the same sync.`] : []),
];
return { argv: holdRepairSteps(first.source_id, first.route ?? { fences: 0, others: 1 }).argv, consent: [], actor: 'host_admin', requires_exclusive: false, why,
@@ -148,7 +156,7 @@ export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; rout
/** The route of one hold record. */
export function recordRoute(record: Pick<GitHoldRecord, 'code'>): HoldRepairRoute {
return record.code === 'invalid_fence' ? { fences: 1, others: 0 } : record.code === 'concurrent_write' ? { fences: 0, others: 0, concurrent: 1 }
- : record.code === 'preparation_stalled' ? { fences: 0, others: 0, stalled: 1 } : record.code === 'worktree_dirty' ? { fences: 0, others: 0, dirty: 1 }
+ : record.code === 'preparation_stalled' ? { fences: 0, others: 0, stalled: 1 } : record.code === 'worktree_dirty' ? { fences: 0, others: 0, dirty: 1 } : record.code === 'file_drift' ? { fences: 0, others: 0, drift: 1 }
: record.code === 'frontmatter_slug_conflict' ? { fences: 0, others: 0, slug_conflicts: 1 } : { fences: 0, others: 1 };
}
diff --git a/src/core/persistence/noop-kernel.ts b/src/core/persistence/noop-kernel.ts
index 1ff346a70f..bf194dad15 100644
--- a/src/core/persistence/noop-kernel.ts
+++ b/src/core/persistence/noop-kernel.ts
@@ -55,6 +55,26 @@ export function screeningRequest(fields: Pick<WriteRequest, 'source_id' | 'sourc
updated_at: new Date().toISOString(), protocol_version: 1, target_kind: 'page', ...fields } as unknown as WriteRequest;
}
+/** What the kernel reads about a live page: its projection state, revision and recorded origin. */
+export interface KernelPage { id: number | string; slug: string; chunker_version: number | null; text_projection_revision: string | null; knowledge_revision: string;
+ mode_pending: boolean; unembedded: boolean; source_path: string | null }
+/** The kernel's page read; callers append the `WHERE` (one page by id, or #6712 PR 1 a prescreened run by slug). */
+export const KERNEL_PAGE_SQL = `SELECT p.id,p.slug,p.chunker_version,p.text_projection_revision::text,p.knowledge_revision::text,p.source_path,
+ (p.contextual_retrieval_mode IS NULL AND EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NOT NULL)) AS mode_pending,
+ EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NULL) AS unembedded
+ FROM pages p`;
+
+/**
+ * The projection and metadata work a no-op would leave undone on `page` (null: none): a safe-chunk re-seal, a text
+ * projection behind the knowledge revision, a contextual-mode stamp (unless `waived` lists it), unembedded chunks when
+ * the publication would queue embedding, or a stored source path that differs.
+ */
+export function kernelPageWork(page: KernelPage, input: { sourcePath: string | null; embeddingRequested?: boolean; waived?: readonly NoopKernelWaiver[] }): 'projection_work' | 'metadata_work' | null {
+ if (belowSafeChunkFence(page.chunker_version === null ? null : Number(page.chunker_version)) || page.text_projection_revision !== page.knowledge_revision
+ || page.mode_pending === true && !input.waived?.includes('contextual_mode') || input.embeddingRequested === true && page.unembedded === true) return 'projection_work';
+ return input.sourcePath !== null && page.source_path !== input.sourcePath ? 'metadata_work' : null;
+}
+
export async function inspectUnchanged(engine: Pick<BrainEngine, 'executeRaw'>, input: {
prepared: PreparedMutation; snapshot: PageSnapshot | null; sourcePath: string | null; databaseOnly: boolean;
/** The publication would queue an embedding effect: a page with unembedded chunks is then not skipped. */
@@ -71,23 +91,15 @@ export async function inspectUnchanged(engine: Pick<BrainEngine, 'executeRaw'>,
if (snapshot.page.deleted_at != null) return result('page_deleted');
if (!unchanged) return result('content_changed');
if (observedRevision !== snapshot.revision) return result('revision_moved');
- const [page] = await engine.executeRaw<{ chunker_version: number | null; text_projection_revision: string | null; knowledge_revision: string;
- mode_pending: boolean; unembedded: boolean; source_path: string | null }>(`SELECT p.chunker_version,p.text_projection_revision::text,p.knowledge_revision::text,p.source_path,
- (p.contextual_retrieval_mode IS NULL AND EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NOT NULL)) AS mode_pending,
- EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NULL) AS unembedded
- FROM pages p WHERE p.id=$1 AND p.deleted_at IS NULL`, [snapshot.page.id]);
+ const [page] = await engine.executeRaw<KernelPage>(`${KERNEL_PAGE_SQL} WHERE p.id=$1 AND p.deleted_at IS NULL`, [snapshot.page.id]);
if (!page) return result('page_missing');
// The page's current revision, read after the preparer ran: a write that landed since the snapshot was read is admitted.
if (page.knowledge_revision != null && page.knowledge_revision !== snapshot.revision) return result('revision_moved');
const waived: NoopKernelWaiver[] = [];
- const modePending = page.mode_pending === true;
- if (modePending && input.waive?.includes('contextual_mode')) waived.push('contextual_mode');
- const projectionWorkRequired = belowSafeChunkFence(page.chunker_version === null ? null : Number(page.chunker_version))
- || page.text_projection_revision !== page.knowledge_revision || modePending && !waived.includes('contextual_mode')
- || input.embeddingRequested === true && page.unembedded === true;
- if (projectionWorkRequired) return result('projection_work', { projectionWorkRequired });
- const metadataWorkRequired = input.sourcePath !== null && page.source_path !== input.sourcePath;
- if (metadataWorkRequired) return result('metadata_work', { metadataWorkRequired });
+ if (page.mode_pending === true && input.waive?.includes('contextual_mode')) waived.push('contextual_mode');
+ const pending = kernelPageWork(page, { sourcePath: input.sourcePath, embeddingRequested: input.embeddingRequested, waived });
+ if (pending === 'projection_work') return result(pending, { projectionWorkRequired: true });
+ if (pending === 'metadata_work') return result(pending, { metadataWorkRequired: true });
if (!input.databaseOnly) {
const file = prepared.file;
const onDisk = file && file.content !== null ? persistenceFileHash(file.path) : null;
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 07272a5493..cc591f21f2 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -26,6 +26,7 @@ import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
import { holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, readSyncImportProvenances } from './sync-holds.ts';
import { readBlobContents, readTreeBlobs, SYNC_READ_BOUND } from './sync-blobs.ts';
import { gitChildEnv } from '../git-env.ts';
+import { movedDriftHolds, prescreenSyncEntries, type SyncDriftSide } from './sync-prescreen.ts';
import { readSyncSlice, sliceEntries, syncCursorOptions, type SyncSliceCursor, type SyncSliceState } from './sync-slices.ts';
/** The page an import takes over from its previous origin: a Git rename, or a file that replaced a vanished origin at the same slug. */
@@ -35,7 +36,11 @@ export interface SyncEntry { path: string; sourcePath: string; action: 'import'
/** #5565: a deleted file no page records as its origin; its slug's page keeps another origin, so the deletion is a fenced no-op. */
unownedDeletion?: boolean;
/** #5988: a held rename destination whose source page changed since the rename was recorded; the freeze screen holds it as `rename_held`. */
- renameHeld?: SyncRename; }
+ renameHeld?: SyncRename;
+ /** #6712 PR 1: the import provenance matches the pinned blob, the frozen revision and this parser; the no-op kernel decides (sync-prescreen.ts). */
+ prescreened?: true;
+ /** #6712 PR 1: the page moved since its last recorded import (or has no record); imported only when the freeze proves it a no-op, else held `file_drift`. */
+ drift?: SyncDriftSide; }
/** Files that map to a slug another origin keeps; they are left out of the manifest until one is renamed. */
export interface SyncSlugCollision { slug: string; kept: string; skipped: string[]; }
/** #5032: a file sync skipped on this host with a named refusal, without failing the run. */
@@ -383,11 +388,11 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const hold = holdByPath.get(path), blob = blobs.get(toGitPath(path));
return hold && !hold.meta.blob_oid && !hold.meta.working && blob ? [blob] : [];
});
- const contents = readBlobContents(gitRoot, unversioned);
+ const contents = readBlobContents(gitRoot, unversioned), movedDrift = await movedDriftHolds(engine, sourceId, holds);
for (const path of checked) {
const hold = holdByPath.get(path), gitPath = toGitPath(path), blob = blobs.get(gitPath);
const workingHold = working && (hold?.meta.working === true || !blob);
- let changed = !hold || holdRescreenDue(hold, retry.has(path));
+ let changed = !hold || holdRescreenDue(hold, retry.has(path)) || movedDrift.has(path);
let present = !!blob;
if (workingHold) {
let bytes: Buffer | null = null;
@@ -546,6 +551,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
if (collisions.length) discovered.slugCollisions = collisions;
// Identities and origin collisions were resolved over the whole target above; only the frozen manifest is cut.
if (slicing) cutDiscoveryToSlice(discovered, slicing, head);
+ await prescreenSyncEntries(engine, discovered, { full: !!opts.full, treeWalk: delta?.status !== 'ok', noSchemaPack: !!opts.noSchemaPack, dryRun: !!opts.dryRun, held: holdByPath });
if (!working) {
const uncommitted = { added: new Set([...dirty.added,...dirty.renamed.map(r=>r.to)].filter(eligible)).size,
modified: new Set(dirty.modified.filter(eligible)).size,
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 43611cb3d2..117c5590a2 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -48,6 +48,8 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
escalate: `held ${HOLD_ATTEMPTS_NEEDS_HUMAN} times: the file keeps changing without being committed`, human_reason: 'Someone (or an agent) keeps editing the file without committing it; find out who and commit or restore it.' },
{ code: 'concurrent_write', class: 'page', safe_actions: ['reconcile'], needs_human: true, escalate: 'always: the file and the database page diverge',
human_reason: 'The Git file and the database page both changed; a person chooses which version wins (gbrain sources reconcile <source> <slug> --preview shows both and writes nothing).' },
+ { code: 'file_drift', class: 'page', safe_actions: ['reconcile'], needs_human: true, escalate: 'always: the page changed in the database since its file was last imported',
+ human_reason: 'The database page moved since sync last imported its file, and importing would replace it; a person chooses which version wins (gbrain repair file-drift --source <source> --slug <slug> --prefer database|file previews it and writes nothing until applied).' },
{ code: 'preparation_stalled', class: 'page', safe_actions: ['retry', 'upgrade'], needs_human: false,
escalate: `held ${HOLD_ATTEMPTS_NEEDS_HUMAN} times, or writer status names a step that never finishes`, human_reason: 'The write owner cannot finish preparing this file; writer status names the step, fix or report it.' },
{ code: 'invalid_fence', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the fence repair preview offers no plan (a manual reason)', human_reason: 'Edit the facts or takes table the hold names and commit.' },
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index cb51814891..f6ac8310c0 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -66,7 +66,7 @@ export const GIT_HOLD_ESCALATE_MIN_SCREENED = 40;
type Exec = Pick<BrainEngine, 'executeRaw'>;
-export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty';
+export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty' | 'file_drift';
/** #6278: what the owner recorded about a preparation it gave up on (step names and vocabulary only, never content). */
export interface PreparationStallMeta {
request_id: string;
@@ -101,6 +101,8 @@ export interface GitHoldMeta {
competing_request_id?: string;
competing_operation?: string;
page_revision?: string;
+ /** #6712 PR 1 `file_drift`: which side moved since the page's last recorded import (`unknown`: no usable record); `page_revision` is the page's revision when held. */
+ sides?: 'database' | 'both' | 'unknown';
/** #6340 `concurrent_write`: the revision the entry was frozen against (the page's live revision is `page_revision`). */
expected_revision?: string;
/** #6340 `worktree_dirty`: sha256 of the uncommitted working-tree bytes the hold protected (`blob_oid` is the pinned blob). */
@@ -214,9 +216,10 @@ async function lockSummary(tx: Exec, sourceId: string, incarnation: string): Pro
/**
* `count` is every hold; `stale` the holds of files whose page exists (the rest are missing pages);
* `images` the #5493 unsupported-image holds, which never escalate; `fences` the #6188 `invalid_fence` holds;
- * `concurrent` the #6194 `concurrent_write` holds; `stalled` the #6278 `preparation_stalled` holds; `dirty` the #6340 `worktree_dirty` holds.
+ * `concurrent` the #6194 `concurrent_write` holds; `stalled` the #6278 `preparation_stalled` holds; `dirty` the #6340 `worktree_dirty` holds;
+ * `drift` the #6712 `file_drift` holds, which never escalate (each is a database edit a person decides on, not a generator fault).
*/
-const SUMMARY_COUNTERS = ['stale', 'images', 'fences', 'concurrent', 'stalled', 'dirty'] as const;
+const SUMMARY_COUNTERS = ['stale', 'images', 'fences', 'concurrent', 'stalled', 'dirty', 'drift'] as const;
type SummaryWeights = Record<typeof SUMMARY_COUNTERS[number], number>;
async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number, weights: SummaryWeights): Promise<void> {
const pairs = SUMMARY_COUNTERS.map((name, i) => `'${name}',GREATEST(0,COALESCE((completed_keys->0->>'${name}')::int,0)+$${i + 4}::int)`).join(',');
@@ -231,8 +234,9 @@ const fenceWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code
const concurrentWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'concurrent_write' ? 1 : 0;
const stalledWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'preparation_stalled' ? 1 : 0;
const dirtyWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'worktree_dirty' ? 1 : 0;
+const driftWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'file_drift' ? 1 : 0;
const weightsOf = (record: Pick<GitHoldRecord, 'code' | 'page_id'>, sign = 1): SummaryWeights => ({ stale: sign * staleWeight(record), images: sign * imageWeight(record),
- fences: sign * fenceWeight(record), concurrent: sign * concurrentWeight(record), stalled: sign * stalledWeight(record), dirty: sign * dirtyWeight(record) });
+ fences: sign * fenceWeight(record), concurrent: sign * concurrentWeight(record), stalled: sign * stalledWeight(record), dirty: sign * dirtyWeight(record), drift: sign * driftWeight(record) });
async function readRow(tx: Exec, sourceId: string, incarnation: string, path: string): Promise<GitHoldRecord | null> {
const [row] = await tx.executeRaw<{ record: GitHoldRecord }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',
@@ -411,6 +415,8 @@ export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, re
* frontmatter repair preview; a source with several kinds names each.
*/
export interface HoldRepairRoute { fences: number; others: number; concurrent?: number; stalled?: number; dirty?: number;
+ /** #6712 `file_drift` holds: a database edit sync would have overwritten; each routes to `gbrain repair file-drift`. */
+ drift?: number;
/** #6377 `frontmatter_slug_conflict` holds, counted apart from `others` by callers that read codes (summary counts leave them in `others`). */
slug_conflicts?: number }
@@ -449,17 +455,20 @@ export function holdRepairSteps(sourceId: string, route: HoldRepairRoute, auto?:
const unblock = ['gbrain', 'sync', 'unblock', '--source', sourceId, '--apply'];
const dirtyText = `the ${route.dirty ?? 0} worktree-dirty hold(s) are uncommitted edits in the checkout that sync would not overwrite: commit them (gbrain sources status ${sourceId} names each file), `
+ `then run ${unblock.join(' ')}, which re-screens every held file that is now committed, and the same sync`;
- if (route.stalled && !route.others && !content && !route.concurrent && !route.dirty) {
+ const driftText = `for each file-drift hold, preview the resolution with gbrain repair file-drift --source ${sourceId} --slug <slug> --prefer database (or --prefer file) `
+ + `(gbrain sources status ${sourceId} names each slug and the database write sync did not overwrite), decide with the user, apply it with the plan hash, then run gbrain sync --source ${sourceId} --no-pull`;
+ if (route.stalled && !route.others && !content && !route.concurrent && !route.dirty && !route.drift) {
return { argv: stalled.status, commands: [stalled.status.join(' '), stalled.retry.join(' '), stalled.sync.join(' ')], text: stalledText };
}
- if (route.dirty && !route.others && !content && !route.concurrent && !route.stalled) {
+ if (route.dirty && !route.others && !content && !route.concurrent && !route.stalled && !route.drift) {
return { argv: unblock, commands: [`gbrain sources status ${sourceId} --json`, unblock.join(' '), `gbrain sync --source ${sourceId} --no-pull`], text: dirtyText };
}
- if (route.concurrent || route.stalled || route.dirty) {
- const parts = [...(route.others ? [frontmatterText] : []), ...(content ? [fenceText] : []), ...(route.concurrent ? [concurrentText] : []), ...(route.stalled ? [stalledText] : []), ...(route.dirty ? [dirtyText] : [])];
+ if (route.concurrent || route.stalled || route.dirty || route.drift) {
+ const parts = [...(route.others ? [frontmatterText] : []), ...(content ? [fenceText] : []), ...(route.concurrent ? [concurrentText] : []), ...(route.stalled ? [stalledText] : []),
+ ...(route.dirty ? [dirtyText] : []), ...(route.drift ? [driftText] : [])];
const commands = [...(route.others ? [frontmatter.join(' ')] : []), ...(content ? [fences.join(' ')] : []),
...(route.stalled ? [stalled.status.join(' ')] : []), `gbrain sources status ${sourceId} --json`, ...(route.dirty ? [unblock.join(' ')] : []), `gbrain sources retry-held ${sourceId}`, `gbrain sync --source ${sourceId} --no-pull`];
- return { argv: route.others ? frontmatter : content ? fences : route.concurrent ? ['gbrain', 'sources', 'status', sourceId, '--json'] : route.stalled ? stalled.status : unblock, commands, text: parts.join('; ') };
+ return { argv: route.others ? frontmatter : content ? fences : route.concurrent || route.drift ? ['gbrain', 'sources', 'status', sourceId, '--json'] : route.stalled ? stalled.status : unblock, commands, text: parts.join('; ') };
}
if (content && !route.others) return { argv: fences, commands: [fences.join(' ')], text: fenceText };
if (content) return { argv: frontmatter, commands: [frontmatter.join(' '), fences.join(' ')], text: `${frontmatterText}; ${fenceText}` };
@@ -502,6 +511,20 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
why: `Schedules ${record.path} for a re-screen on the next sync, after the page is reconciled.`, verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } },
verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };
}
+ case 'file_drift': {
+ const slug = record.slug ?? '<slug>';
+ const by = record.meta.competing_request_id ? `${record.meta.competing_operation ?? 'a database'} request ${record.meta.competing_request_id} wrote page ${slug} straight to the database`
+ : `page ${slug} changed in the database${record.meta.page_revision ? ` (revision ${record.meta.page_revision})` : ''}`;
+ const preview = (prefer: 'database' | 'file') => ['gbrain', 'repair', 'file-drift', '--source', source, '--slug', slug, '--prefer', prefer];
+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ return { argv: preview('database'), consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#file_drift',
+ why: `${by} since ${record.path} was last imported, so sync held the file instead of overwriting the database version (${record.meta.sides === 'database' ? 'the file did not change in Git'
+ : record.meta.sides === 'both' ? 'the file changed too' : 'no import record says which side changed'}). This preview (writes nothing) keeps the database copy and rewrites the file; `
+ + `${preview('file').join(' ')} previews importing the file instead. Decide with the user which version wins, run the apply command the preview prints, then sync again. The rest of the source is not blocked.`,
+ then: { argv: ['gbrain', 'sync', '--source', source, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Re-screens ${record.path} after the repair (a changed file or page revision re-screens it by itself).` },
+ verify };
+ }
case 'preparation_stalled': {
const stall = record.meta.stall;
const steps = stalledHoldSteps(source, stall?.sync_argv);
@@ -836,7 +859,8 @@ export function fencesNormalizedReport(sourceId: string, tally: FencesTally | un
export async function buildHoldReport(engine: Exec, input: { sourceId: string; incarnation: string; runId: string; remote: boolean;
policy: SyncHoldPolicy; screened: number; pendingScreen?: boolean }): Promise<Pick<import('../../commands/sync.ts').SyncResult,
'held' | 'held_count' | 'holds_outstanding' | 'holds_escalated' | 'holds_truncated' | 'holds_pending_screen' | 'holds_fix'>> {
- const [summary] = await engine.executeRaw<{ count: number | string; images: number | string; fences: number | string; stalled: number | string; concurrent: number | string; dirty: number | string }>(`SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count,
+ const [summary] = await engine.executeRaw<{ count: number | string; images: number | string; fences: number | string; stalled: number | string; concurrent: number | string; dirty: number | string; drift: number | string }>(`SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count,
+ COALESCE((completed_keys->0->>'drift')::int,0) AS drift,
COALESCE((completed_keys->0->>'images')::int,0) AS images, COALESCE((completed_keys->0->>'fences')::int,0) AS fences, COALESCE((completed_keys->0->>'stalled')::int,0) AS stalled,
COALESCE((completed_keys->0->>'concurrent')::int,0) AS concurrent, COALESCE((completed_keys->0->>'dirty')::int,0) AS dirty
FROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,
@@ -844,17 +868,18 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; i
const outstanding = Number(summary?.count ?? 0);
const runHolds = (await readGitSourceHolds(engine, { sourceIds: [input.sourceId], runId: input.runId }))[0]?.holds ?? [];
if (!outstanding && !runHolds.length) return {};
- const escalated = holdsEscalated(input.policy, outstanding - Number(summary?.images ?? 0),
- { held: runHolds.filter(hold => !imageWeight(hold)).length, screened: input.screened });
+ const escalated = holdsEscalated(input.policy, outstanding - Number(summary?.images ?? 0) - Number(summary?.drift ?? 0),
+ { held: runHolds.filter(hold => !imageWeight(hold) && !driftWeight(hold)).length, screened: input.screened });
const fences = Math.max(Number(summary?.fences ?? 0), runHolds.filter(hold => fenceWeight(hold)).length);
const stalled = Math.max(Number(summary?.stalled ?? 0), runHolds.filter(hold => stalledWeight(hold)).length);
const concurrent = Math.max(Number(summary?.concurrent ?? 0), runHolds.filter(hold => concurrentWeight(hold)).length);
const dirty = Math.max(Number(summary?.dirty ?? 0), runHolds.filter(hold => dirtyWeight(hold)).length);
+ const drift = Math.max(Number(summary?.drift ?? 0), runHolds.filter(hold => driftWeight(hold)).length);
// #6377: this run's slug-conflict holds route to the content lane; earlier runs' stay in `others` (the summary does not count them).
const slugConflicts = runHolds.filter(hold => hold.code === 'frontmatter_slug_conflict').length;
const auto = fences ? await readFenceAutoRepair(engine) : undefined;
- const steps = holdRepairSteps(input.sourceId, { fences, others: Math.max(0, outstanding - fences - stalled - concurrent - dirty - slugConflicts), ...(stalled ? { stalled } : {}),
- ...(concurrent ? { concurrent } : {}), ...(dirty ? { dirty } : {}), ...(slugConflicts ? { slug_conflicts: slugConflicts } : {}) }, auto);
+ const steps = holdRepairSteps(input.sourceId, { fences, others: Math.max(0, outstanding - fences - stalled - concurrent - dirty - drift - slugConflicts), ...(stalled ? { stalled } : {}),
+ ...(concurrent ? { concurrent } : {}), ...(dirty ? { dirty } : {}), ...(drift ? { drift } : {}), ...(slugConflicts ? { slug_conflicts: slugConflicts } : {}) }, auto);
// #6278: the escalation text is routed by code: stalled holds point at the writer, not at a generator.
const runStalled = runHolds.filter(hold => stalledWeight(hold)).length;
const escalation = runStalled * 2 > runHolds.length
@@ -866,7 +891,7 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; i
user_message: `Some files in source ${input.sourceId} could not be imported. Please run 'gbrain sources status ${input.sourceId}' on the brain host, then: ${steps.text}.` } };
const fix: Action = { argv: steps.argv, consent: [], actor: 'agent', requires_exclusive: false, verify,
why: `${runHolds.length} file(s) held this run, ${outstanding} held in source ${input.sourceId}; they do not block sync. Inspect them with 'gbrain sources status ${input.sourceId}'; `
- + (fences || stalled || concurrent || dirty || slugConflicts ? `then ${steps.text}.` : 'the repair preview proposes each fix and writes nothing.')
+ + (fences || stalled || concurrent || dirty || drift || slugConflicts ? `then ${steps.text}.` : 'the repair preview proposes each fix and writes nothing.')
+ (escalated ? escalation : '') };
return { held: runHolds.slice(0, input.policy.cap).map(hold => gitHoldItem(hold, auto)), held_count: runHolds.length, holds_outstanding: outstanding,
...(escalated ? { holds_escalated: true } : {}), ...(runHolds.length > input.policy.cap ? { holds_truncated: true } : {}),
diff --git a/src/core/persistence/sync-page-fault.ts b/src/core/persistence/sync-page-fault.ts
index 6af9c00976..e9db2a2b6d 100644
--- a/src/core/persistence/sync-page-fault.ts
+++ b/src/core/persistence/sync-page-fault.ts
@@ -90,7 +90,7 @@ export async function liveRevision(engine: Pick<BrainEngine, 'executeRaw'>, sour
return row?.revision ?? null;
}
-function base(entry: HoldEntry, slug: string, pageId: number | null, code: 'concurrent_write' | 'worktree_dirty',
+function base(entry: HoldEntry, slug: string, pageId: number | null, code: 'concurrent_write' | 'worktree_dirty' | 'file_drift',
message: string, content: string | null, blobOid: string | null | undefined, meta: Partial<GitHoldMeta>): HeldEntry {
const rename: SyncRename | undefined = entry.renameFrom ?? entry.renameHeld;
return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code, message, upstream_version: content === null ? null : sha256(content),
@@ -98,6 +98,24 @@ function base(entry: HoldEntry, slug: string, pageId: number | null, code: 'conc
...(rename ? { rename_from: rename } : {}), ...(entry.action === 'delete' ? { deleted: true as const } : {}), ...meta } };
}
+/**
+ * #6712 PR 1: the `file_drift` hold for an import whose page moved since its file was last imported (`sides`, from the
+ * discovery baseline, sync-prescreen.ts) and whose import is not a no-op: importing would overwrite a database version
+ * sync never saw. `proof` names the database-only request that wrote the current revision when one did. Identifiers
+ * and revisions only, never content. `repair file-drift` is the exit; the hold is re-screened when the file or the
+ * page revision changes.
+ */
+export function fileDriftHold(entry: HoldEntry, slug: string, pageId: number | null, intent: Pick<SyncIntent, 'content' | 'blobOid'>,
+ observed: { sides: 'database' | 'both' | 'unknown'; revision: string | null; proof: PageChangeProof | null }): HeldEntry {
+ const by = observed.proof ? `${observed.proof.operation} request ${observed.proof.request_id} wrote page ${slug} straight to the database` : `page ${slug} changed in the database`;
+ const file = observed.sides === 'database' ? 'its file did not change in Git' : observed.sides === 'both' ? 'its file changed too'
+ : 'there is no import record to tell which side changed';
+ return base(entry, slug, pageId, 'file_drift',
+ `${entry.path}: ${by} since the file was last imported and ${file}, so sync held the import instead of overwriting the database version; the rest of the source synced.`,
+ intent.content ?? null, intent.blobOid, { sides: observed.sides, ...(observed.revision ? { page_revision: observed.revision } : {}),
+ ...(observed.proof ? { competing_request_id: observed.proof.request_id, competing_operation: observed.proof.operation } : {}) });
+}
+
/**
* The `concurrent_write` hold for a page that changed in the database after this entry was enumerated (or after its
* import was admitted). `why` names the change as the caller saw it; identifiers and revisions only, never content.
diff --git a/src/core/persistence/sync-prescreen.ts b/src/core/persistence/sync-prescreen.ts
new file mode 100644
index 0000000000..70f266c896
--- /dev/null
+++ b/src/core/persistence/sync-prescreen.ts
@@ -0,0 +1,153 @@
+/**
+ * #6712 PR 1 (L1): the content-addressed discovery prescreen and the drift baseline of each frozen import.
+ *
+ * Import provenance (sync-holds.ts) records, per page, the bytes the last publish left on disk (`disk_blob_oid`), the
+ * page revision it wrote (`revision`) and the parser fingerprint (`parser`). Discovery compares them with the pinned
+ * tree (one `ls-tree`) and the frozen page revision, for every Git import of an existing page:
+ *
+ * - **prescreened**: the file is the recorded disk blob, the page is still at the recorded revision and the fingerprint
+ * is this binary's. The entry is only a candidate: the run sends it to the guarded no-op kernel's bounded checks
+ * (`waivePrescreenedRun`), and only those skip it durably; any mismatch there imports it as before. Bypassed under
+ * `--full`.
+ * - **no baseline concern**: the page is still at the recorded revision (only the file or the parser changed), so the
+ * import cannot overwrite a database-only edit.
+ * - **drift** (`entry.drift`): the page moved since the record and the file did not (`database`), or both moved
+ * (`both`), or there is no usable record (`unknown`: none, one written before PR 0, or a partial one). `database` is
+ * guarded in every discovery; `both` and `unknown` in a tree walk (first sync, `--full`, an unreachable checkpoint, a
+ * re-discovery), where no Git delta says the file is the side that changed. A page whose current revision a
+ * committed managed-sync request of this incarnation wrote (`pages.revision_write_request_id`) has no database-only
+ * edit to protect and is not guarded. A guarded entry is imported only when the freeze proves the import changes
+ * nothing (`sameContentAtOrigin`); otherwise it is held `file_drift` (sync-run.ts `driftHold`).
+ * - Under `storage.keep_db` prefixes a drifted page is not held: its entry leaves the manifest (nothing imported) and is
+ * recorded as a drift candidate the keep_db worker reconciles from the database (`liveFileDrift` confirms the file
+ * and the database still differ; an entry where they agree stays, and its import is a no-op).
+ */
+import { execFileSync } from 'node:child_process';
+import { realpathSync } from 'node:fs';
+import { join, relative, sep } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { gitChildEnv } from '../git-env.ts';
+import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
+import { isKeepDbSlug, loadStorageConfig } from '../storage-config.ts';
+import { readSyncImportProvenances, syncImportParserFor, type SyncImportParser, type SyncImportProvenance } from './sync-holds.ts';
+import { readTreeBlobs, type TreeBlob } from './sync-blobs.ts';
+import { syncOriginPath } from './sync-origin.ts';
+import { liveFileDrift, recordDriftSkip } from './drift-conflicts.ts';
+import type { SyncDiscovery, SyncEntry } from './sync-discovery.ts';
+
+/** Which side moved since the page's last recorded import (`unknown`: no usable record). */
+export type SyncDriftSide = 'database' | 'both' | 'unknown';
+
+/** Above this many candidates the pinned tree is listed once instead of path by path. */
+const WHOLE_TREE_AT = 1000;
+/** Provenance rows read per statement. */
+const PROVENANCE_CHUNK = 5000;
+
+/** The blob of each Git path at `target`: one recursive listing for a large set, else `readTreeBlobs`. */
+function pinnedBlobs(gitRoot: string, target: string, gitPaths: string[]): Map<string, TreeBlob> {
+ if (gitPaths.length < WHOLE_TREE_AT) return readTreeBlobs(gitRoot, target, gitPaths);
+ const wanted = new Set(gitPaths), out = new Map<string, TreeBlob>();
+ const listing = execFileSync('git', ['-c', 'core.quotepath=false', '-C', gitRoot, 'ls-tree', '-r', '-z', target],
+ { env: gitChildEnv(), encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 ** 2, stdio: ['ignore', 'pipe', 'pipe'] });
+ for (const row of listing.split('\0')) {
+ const tab = row.indexOf('\t');
+ if (tab < 0 || !wanted.has(row.slice(tab + 1))) continue;
+ const [, kind, oid] = row.slice(0, tab).split(' ');
+ if (kind === 'blob') out.set(row.slice(tab + 1), { oid: oid!, size: -1 });
+ }
+ return out;
+}
+
+const sameParser = (a: SyncImportParser | null | undefined, b: SyncImportParser) => !!a && a.parser_version === b.parser_version
+ && a.markdown_chunker === b.markdown_chunker && (a.schema_pack ?? null) === b.schema_pack;
+
+/** The drift side of one entry from its record and pinned blob, or null when nothing needs guarding (`prescreened`: a kernel candidate). */
+export function classifyBaseline(entry: Pick<SyncEntry, 'revision' | 'sourcePath'>, record: SyncImportProvenance | undefined, blob: TreeBlob | undefined,
+ expected: SyncImportParser, input: { full: boolean; treeWalk: boolean }): 'prescreened' | SyncDriftSide | null {
+ const complete = !!record?.disk_blob_oid && record.revision != null;
+ const fileSame = complete && !!blob && record!.disk_blob_oid === blob.oid;
+ const databaseSame = complete && String(record!.revision) === String(entry.revision);
+ if (fileSame && databaseSame && !input.full && sameParser(record!.parser, expected) && syncOriginPath(record!.origin) === syncOriginPath(entry.sourcePath)) return 'prescreened';
+ if (databaseSame) return null;
+ if (fileSame) return 'database';
+ return input.treeWalk ? complete ? 'both' : 'unknown' : null;
+}
+
+/**
+ * Marks the frozen manifest's prescreen candidates (`prescreened`) and guarded imports (`drift`), and moves the drifted
+ * entries under `storage.keep_db` prefixes to the keep_db worker. `held` paths (an active hold) are left to their
+ * re-screen. Runs after identities are frozen; a company-brain manifest is never prescreened.
+ */
+export async function prescreenSyncEntries(engine: BrainEngine, discovered: SyncDiscovery,
+ input: { full: boolean; treeWalk: boolean; noSchemaPack: boolean; dryRun: boolean; held: ReadonlyMap<string, { code: string }> }): Promise<void> {
+ if (discovered.companyPlan) return;
+ const candidates = discovered.entries.filter(entry => entry.action === 'import' && !entry.working && entry.pageId != null && entry.revision != null
+ && !entry.renameFrom && !entry.renameHeld);
+ if (!candidates.length) return;
+ const nativeRoot = realpathSync.native(discovered.root), nativeGitRoot = realpathSync.native(discovered.gitRoot);
+ const gitPathOf = (entry: SyncEntry) => relative(nativeGitRoot, join(nativeRoot, entry.path)).split(sep).join('/');
+ const blobs = pinnedBlobs(discovered.gitRoot, discovered.target, candidates.map(gitPathOf));
+ const records = new Map<number, SyncImportProvenance>();
+ for (let i = 0; i < candidates.length; i += PROVENANCE_CHUNK) {
+ const read = await readSyncImportProvenances(engine, discovered.sourceId, discovered.incarnation, candidates.slice(i, i + PROVENANCE_CHUNK).map(entry => Number(entry.pageId)));
+ for (const [id, record] of read) records.set(id, record);
+ }
+ const pack = input.noSchemaPack ? null : await loadActivePackForEngine(engine, { remote: false, sourceId: discovered.sourceId }).catch(() => null);
+ const guarded: SyncEntry[] = [];
+ for (const entry of candidates) {
+ const hold = input.held.get(entry.path);
+ const side = classifyBaseline(entry, records.get(Number(entry.pageId)), blobs.get(gitPathOf(entry)), syncImportParserFor(entry.sourcePath, pack?.identity ?? null),
+ { full: input.full || !!hold, treeWalk: input.treeWalk || hold?.code === 'file_drift' });
+ if (side === 'prescreened') entry.prescreened = true;
+ else if (side) { entry.drift = side; guarded.push(entry); }
+ }
+ if (!guarded.length) return;
+ const synced = await syncWrittenRevisions(engine, discovered, guarded.map(entry => Number(entry.pageId)));
+ const drifted = guarded.filter(entry => synced.has(Number(entry.pageId)) ? (delete entry.drift, false) : true);
+ await releaseKeepDbDrift(engine, discovered, drifted, input.dryRun);
+}
+
+/**
+ * `file_drift` holds whose page moved since the hold recorded it (another database write, a reconcile, a repair): each
+ * is re-screened like a hold whose file changed. One read for the source's drift holds.
+ */
+export async function movedDriftHolds(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string,
+ holds: ReadonlyArray<{ path: string; code: string; page_id: number | null; meta: { page_revision?: string } }>): Promise<Set<string>> {
+ const drift = holds.filter(hold => hold.code === 'file_drift' && hold.page_id !== null);
+ if (!drift.length) return new Set();
+ const rows = await engine.executeRaw<{ id: number | string; revision: string | null }>('SELECT id, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND id=ANY($2::bigint[])',
+ [sourceId, drift.map(hold => hold.page_id)]);
+ const revisions = new Map(rows.map(row => [Number(row.id), row.revision]));
+ return new Set(drift.filter(hold => (revisions.get(Number(hold.page_id)) ?? null) !== (hold.meta.page_revision ?? null)).map(hold => hold.path));
+}
+
+/** Pages whose current revision a committed managed-sync request of this incarnation wrote (no database-only edit since). */
+async function syncWrittenRevisions(engine: BrainEngine, discovered: Pick<SyncDiscovery, 'sourceId' | 'incarnation'>, pageIds: number[]): Promise<Set<number>> {
+ const out = new Set<number>();
+ for (let i = 0; i < pageIds.length; i += PROVENANCE_CHUNK) {
+ const rows = await engine.executeRaw<{ id: number | string }>(`SELECT p.id FROM pages p JOIN persistence_requests r ON r.id=p.revision_write_request_id
+ WHERE p.source_id=$1 AND p.id=ANY($2::bigint[]) AND r.state='committed' AND r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete')
+ AND r.source_id=p.source_id AND r.source_incarnation::text=$3 AND (r.page_id IS NULL OR r.page_id=p.id)`, [discovered.sourceId, pageIds.slice(i, i + PROVENANCE_CHUNK), discovered.incarnation]);
+ for (const row of rows) out.add(Number(row.id));
+ }
+ return out;
+}
+
+/**
+ * `storage.keep_db`: a drifted page under its prefixes is reconciled from the database by the keep_db worker, never
+ * imported or held by sync. Its entry leaves the manifest and is recorded as a drift candidate while the file and the
+ * database still differ (or the check cannot tell); where they agree the entry stays and imports as a no-op.
+ */
+async function releaseKeepDbDrift(engine: BrainEngine, discovered: SyncDiscovery, drifted: SyncEntry[], dryRun: boolean): Promise<void> {
+ if (!drifted.length) return;
+ let keepDb: string[] = [];
+ try { keepDb = loadStorageConfig(discovered.root)?.keep_db ?? []; } catch { return; }
+ const released = new Set<SyncEntry>();
+ for (const entry of drifted.filter(entry => keepDb.length && isKeepDbSlug(entry.slug!, keepDb))) {
+ const live = await liveFileDrift(engine, discovered.sourceId, entry.slug!);
+ if (live.still_present === false) { delete entry.drift; continue; }
+ if (!dryRun) await recordDriftSkip(engine, discovered.sourceId, entry.slug!, { file_hash: live.file_hash ?? null, db_revision: live.db_revision ?? entry.revision ?? null });
+ released.add(entry);
+ }
+ if (released.size) discovered.entries = discovered.entries.filter(entry => !released.has(entry));
+}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 3e886c07c1..c84b9a8a14 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -24,7 +24,7 @@ import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } f
import { startClaimPhase } from './claim-phase.ts';
import { screeningRequest } from './noop-kernel.ts';
import { FINISH_BUDGET_MS, stampDrainStep } from './drain-step.ts';
-import { noopWaiversEnabled, raceSyncBudget, screenWaiver, syncPreparationBudgetMs, unfinishedPageRequestParams, UNFINISHED_PAGE_REQUEST_SQL, waiveNoopEntry, waiveNoopRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';
+import { noopWaiversEnabled, prescreenedHead, raceSyncBudget, screenWaiver, syncPreparationBudgetMs, unfinishedPageRequestParams, UNFINISHED_PAGE_REQUEST_SQL, waiveNoopEntry, waiveNoopRun, waivePrescreenedRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';
import { resolve } from 'node:path';
import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';
import { readCommittedBlob } from '../company-brain/revision.ts';
@@ -53,7 +53,7 @@ import { fenceReceiptLocation } from '../fence-repair/refusal.ts';
import { managedSyncWriteDiagnostic, writeWaitOf } from './sync-write-diagnostic.ts';
import { checkpointSuperseded } from './sync-checkpoint-replaced.ts';
import { publicFailureDetail } from './publication-failure.ts';
-import { fileChangedAfterAdmission, headCommittedBytes, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';
+import { fileChangedAfterAdmission, fileDriftHold, headCommittedBytes, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';
import { faultPoint } from './fault-points.ts';
import { pipelined } from '../page-state/transactions.ts';
import { withCoordinatedWrite } from './context.ts';
@@ -96,6 +96,8 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authority
skippedContextualMode?: number; skippedCanonicalBytes?: number;
/** DX-A7: entries advanced without an admission because their publication would change nothing. */
waived?: { imports: number; deletes: number };
+ /** #6712 PR 1: of the waived imports, those the guarded kernel passed straight from the discovery prescreen (no preparation). */
+ prescreened?: number;
/** #5988: imports held, and files imported only after quoting frontmatter. */
held?: number; recovered?: { count: number; sample_paths: string[]; comment_values?: number };
/** #6188: files whose fences Tier 1 rewrote (and the Git effect committed). */
@@ -313,7 +315,7 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], rea
...(cursor.slugCollisions?.length ? { slugCollisions: cursor.slugCollisions } : {}),
...(cursor.fileRefusals?.length ? { fileRefusals: cursor.fileRefusals } : {}), ...(cursor.workingTreeKept?.length ? { working_tree_kept: cursor.workingTreeKept.length } : {}),
...(cursor.stagedHead && !cursor.authority.writer.remote ? { staged: { target: cursor.target, head: cursor.stagedHead, ...(cursor.slice && !cursor.slice.done ? { slice: { phase: cursor.slice.phase, after: cursor.slice.after } } : {}) } } : {}),
- waived: { imports: cursor.counts.waived?.imports ?? 0, deletes: cursor.counts.waived?.deletes ?? 0 },
+ waived: { imports: cursor.counts.waived?.imports ?? 0, deletes: cursor.counts.waived?.deletes ?? 0 }, prescreened: cursor.counts.prescreened ?? 0,
filesImported: cursor.index, bankedFiles: cursor.index,
managedCursor: { index: cursor.index, total: 'total' in cursor ? cursor.total : cursor.entries.length, ...(cursor.progress ? { progress: cursor.progress } : {}) },
...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}),
@@ -438,6 +440,13 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
`Page ${moved.slug}, which ${entry.path} was renamed from, changed or was deleted after this sync enumerated it, so the run stopped before admitting the rename.`);
}
}
+ // #6712 PR 1: an import whose page moved since its file was last imported runs only as a proven no-op (sync-prescreen.ts).
+ if (entry.drift && holdsOn && !occupantRebound && content !== null && snapshot && !(image ? sameImageBytes(imageBytes, snapshot.page)
+ : await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal))) {
+ const proof = await pageChangeProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pageId, expectedRevision: null });
+ assertActive();
+ return { hold: fileDriftHold(entry, slug, pageId, frozenIntent, { sides: entry.drift, revision: snapshot.revision, proof }) };
+ }
if (screening && !image) {
const hold = await screenFrozenImport(engine, { cursor, entry, slug, pageId, snapshot, content, rawHash, lineEndingOnly, blob, oversize,
retryCommand: checkpointRetryCommand(retry) }, screening);
@@ -992,6 +1001,29 @@ async function waiveRun(engine: BrainEngine, cursor: Cursor, head: Pending, key:
? saveCursor(engine, key, done.cursor, { ...done.cursor, pending: done.next as Pending }, false, assertActive) : done.cursor;
}
+/**
+ * #6712 PR 1 (L1): the consecutive prescreened entries at the head (sync-prescreen.ts), passed by the guarded kernel's
+ * bounded checks in one transaction (`waivePrescreenedRun`) without freezing or preparing them. Null when the head is
+ * not a prescreened entry or the kernel passed none; `missed` then remembers the head, so the ordinary path freezes,
+ * screens and imports it (the prescreen fails toward importing).
+ */
+async function prescreenRun(engine: BrainEngine, cursor: Cursor, key: string, run: { missed: Set<number>; limit: number; embeddingRequested: boolean;
+ drainStartedAt: number; assertActive: () => void; signal?: AbortSignal; onProgress: SyncOpts['onProgress'] }): Promise<Cursor | null> {
+ const entries = prescreenedHead(cursor.entries, cursor.index, run.missed, run.limit);
+ if (!entries.length || cursor.pending) return null;
+ stampDrainStep('waiver_run', run.signal);
+ const done = await waivePrescreenedRun(engine, cursor, entries, key, { embeddingRequested: run.embeddingRequested }, (tx, count) => {
+ let next: Cursor = cursor;
+ for (let i = 0; i < count; i++) next = waivedCursor(next, { kind: 'import', kernel: [] });
+ return writeCursor(tx, key, cursor, { ...next, counts: { ...next.counts, prescreened: (cursor.counts.prescreened ?? 0) + count },
+ progress: stampProgress(cursor.progress, cursor.index, cursor.index + count, run.drainStartedAt) });
+ }, tx => currentCursor(tx, key, cursor));
+ if (!done) { run.missed.add(cursor.index); return null; }
+ for (let index = cursor.index + 1; index <= cursor.index + done.waived; index++) run.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: index, total: cursor.entries.length, waived: true });
+ run.assertActive();
+ return done.cursor;
+}
+
/** waiveRun's screens: the head, then its followers four at a time while each one screens as a waiver. */
async function screenWaiverRun(engine: BrainEngine, cursor: Cursor, head: Pending, key: string, config: GBrainConfig, assertActive: () => void,
frozenRun: Parameters<typeof freezeEntry>[4], limit: number): Promise<WaiverRunEntry[] | null> {
@@ -1528,7 +1560,8 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
let creditedPages = 0, creditStarted = 0, foregroundQueued = false;
const sliceStarted = performance.now(), sliceFirstIndex = cursor.index, drainStartedAt = opts.drainStartedAt ?? Date.now();
const bulk: BulkPass = { settings: opts.bulk && !company ? opts.bulk : { enabled: false, reason: null, size: 1, maxTxnMs: 0 }, perMemberMs: null, foregroundFirst: await foregroundPriority(engine) };
- const waiveBatch = noopWaiversEnabled() && await waiverBatchEnabled(startupConfig);
+ const waiveBatch = noopWaiversEnabled() && await waiverBatchEnabled(startupConfig), prescreen = { missed: new Set<number>(), limit: Infinity, drainStartedAt, assertActive, signal, onProgress: opts.onProgress,
+ embeddingRequested: !(cursor.processingOptions ?? processingOptions).noEmbed && !opts.embedDeferred && !config.embedding_disabled && !!config.embedding_model?.trim() };
if (opts.capacityPreflight && !cursor.done) await preflightSyncCapacity(engine, { root: cursor.root, writer: cursor.authority.writer, entries: cursor.entries.slice(cursor.index) });
opts.onProgress?.({ phase: 'managed_sync.start', bankedFiles: cursor.index, total: cursor.entries.length });
while (!cursor.done) {
@@ -1554,6 +1587,9 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
creditedPages = 25; creditStarted = performance.now();
}
foregroundWaitStart = 0;
+ const prescreened = await prescreenRun(engine, cursor, key, { ...prescreen, limit: slice ? slice.maxPages - (cursor.index - sliceFirstIndex) : Infinity });
+ if (prescreened && slice && (prescreened.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(prescreened, 'partial', 'writer_yield');
+ if (prescreened) { cursor = prescreened; continue; }
phase = 'freeze'; stampDrainStep('freeze', signal);
const frozen = await freezeEntry(engine, cursor, key, assertActive, frozenRun);
if ('hold' in frozen) {
diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.ts
index 57bb9c7547..b909c7965c 100644
--- a/src/core/persistence/sync-waivers.ts
+++ b/src/core/persistence/sync-waivers.ts
@@ -9,12 +9,12 @@ import { join } from 'node:path';
import type { BrainEngine, PageSnapshot } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { prepareManagedSyncMutation, type SyncIntent } from './sync-prepare.ts';
-import { recordSyncImportProvenances, syncDiskProvenance, type SyncImportProvenance, type SyncImportProvenanceBase } from './sync-holds.ts';
+import { heldGitPaths, readSyncImportProvenances, recordSyncImportProvenances, syncDiskProvenance, type SyncImportProvenance, type SyncImportProvenanceBase } from './sync-holds.ts';
import { sha256 } from './digest.ts';
import { startClaimPhase } from './claim-phase.ts';
-import { inspectUnchanged, screeningRequest, type NoopKernelWaiver } from './noop-kernel.ts';
+import { inspectUnchanged, KERNEL_PAGE_SQL, kernelPageWork, screeningRequest, type KernelPage, type NoopKernelWaiver } from './noop-kernel.ts';
import { validateSyncAuthority, type SyncAuthority } from './sync-authority.ts';
-import { readSyncFile } from './sync-discovery.ts';
+import { readSyncFile, type SyncEntry } from './sync-discovery.ts';
import { isImageFilePath } from '../sync.ts';
import { getWorktreeBinding } from './ownership.ts';
import { assertSyncPageOrigin, syncOriginScope } from './sync-origin.ts';
@@ -238,6 +238,76 @@ export async function waiveNoopRun<C extends WaiverCursor>(engine: BrainEngine,
}
}
+/** #6712 PR 1: a prescreened manifest entry (sync-prescreen.ts), as the guarded kernel run checks it. */
+export interface PrescreenedEntry { slug: string; pageId: number; revision: string; path: string; sourcePath: string }
+/** The most prescreened entries one kernel transaction passes. */
+export const PRESCREEN_RUN_MAX = 500;
+/** The consecutive prescreened manifest entries from `index` (none the kernel already declined in this run), at most `limit`. */
+export function prescreenedHead(entries: ReadonlyArray<SyncEntry>, index: number, missed: ReadonlySet<number>, limit: number): PrescreenedEntry[] {
+ const run: PrescreenedEntry[] = [];
+ for (let at = index; at < entries.length && run.length < Math.min(PRESCREEN_RUN_MAX, limit); at++) {
+ const entry = entries[at]!;
+ if (!entry.prescreened || missed.has(at)) break;
+ run.push({ slug: entry.slug!, pageId: Number(entry.pageId), revision: String(entry.revision), path: entry.path, sourcePath: entry.sourcePath });
+ }
+ return run;
+}
+/**
+ * #6712 PR 1 (L1): the guarded no-op kernel's bounded checks for a run of consecutive prescreened entries at the cursor
+ * head, with no preparation: the prescreen already matched each file to its recorded import, so only the database side
+ * and the file on disk are re-checked here. One transaction takes every page guard, then the cursor row (still at the
+ * run's first entry, nothing pending), confirms the owner epoch, and passes the contiguous prefix whose entries each
+ * hold: authority (checked before the transaction; a revoked grant throws), identity (the same page id, live, at the
+ * frozen revision), projection and metadata (`kernelPageWork`), the import provenance (the record still names the
+ * frozen revision, and the file on disk still has the recorded bytes), no unfinished request for the page, and no
+ * active hold on the path. Returns null when not even the first entry holds (or on a lock or statement timeout): the
+ * caller imports that entry through the ordinary path. Only this run skips durably; the prescreen never does.
+ */
+export async function waivePrescreenedRun<C extends WaiverCursor & { binding: { owner_epoch: string | number } }>(engine: BrainEngine, cursor: C,
+ run: readonly PrescreenedEntry[], key: string, input: { embeddingRequested: boolean },
+ advance: (tx: BrainEngine, count: number) => Promise<C>, reread: (tx: BrainEngine) => Promise<C>): Promise<{ cursor: C; waived: number } | null> {
+ if (!run.length || !noopWaiversEnabled()) return null;
+ for (let i = 0; i < run.length; i += 16) await Promise.all(run.slice(i, i + 16).map(entry => validateSyncAuthority(engine, cursor.authority, entry.slug)));
+ try {
+ return await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('lock_timeout','2s',true),set_config('statement_timeout','10s',true)");
+ await tx.lockPageKeys(run.map(entry => ({ sourceId: cursor.sourceId, slug: entry.slug })));
+ const [held] = await tx.executeRaw<{ run_id: string | null; index: number | string | null; request_id: string | null }>(`SELECT completed_keys->0->>'runId' AS run_id,
+ completed_keys->0->'index' AS index,completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE`, [key]);
+ if (held?.run_id !== cursor.runId || Number(held.index) !== cursor.index || held.request_id != null) return { cursor: await reread(tx), waived: 0 };
+ await faultPoint('sync:prescreened', { sourceId: cursor.sourceId });
+ const binding = await getWorktreeBinding(tx, cursor.sourceId);
+ if (!binding || String(binding.owner_epoch) !== String(cursor.binding.owner_epoch)) return null;
+ const pages = new Map((await tx.executeRaw<KernelPage>(`${KERNEL_PAGE_SQL} WHERE p.source_id=$1 AND p.slug=ANY($2::text[]) AND p.deleted_at IS NULL`,
+ [cursor.sourceId, run.map(entry => entry.slug)])).map(page => [page.slug, page]));
+ const records = await readSyncImportProvenances(tx, cursor.sourceId, cursor.incarnation, run.map(entry => entry.pageId));
+ const holds = await heldGitPaths(tx, cursor.sourceId, cursor.incarnation, run.map(entry => entry.path));
+ let valid = 0;
+ chunks: for (let from = 0; from < run.length; from += WAIVER_PIPELINE_MAX) {
+ const chunk = run.slice(from, from + WAIVER_PIPELINE_MAX);
+ noteDrainSql(UNFINISHED_PAGE_REQUEST_SQL);
+ const unfinished = await pipelined(tx, chunk.map(entry => () => tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL,
+ unfinishedPageRequestParams(cursor, { slug: entry.slug, pageId: entry.pageId, intent: { path: entry.path, sourcePath: entry.sourcePath } as SyncIntent })))) as unknown[][];
+ for (const [i, entry] of chunk.entries()) {
+ const page = pages.get(entry.slug), record = records.get(entry.pageId);
+ if (!page || Number(page.id) !== entry.pageId || page.knowledge_revision !== entry.revision || unfinished[i]!.length || holds.has(entry.path)) break chunks;
+ if (kernelPageWork(page, { sourcePath: entry.sourcePath, embeddingRequested: input.embeddingRequested }) !== null) break chunks;
+ if (!record?.disk_sha256 || record.revision !== entry.revision) break chunks;
+ const bytes = readSyncFile(cursor.root, entry.path);
+ if (!bytes || sha256(bytes) !== record.disk_sha256) break chunks;
+ valid++;
+ }
+ }
+ if (!valid) return null;
+ return { cursor: await advance(tx, valid), waived: valid };
+ });
+ } catch (error) {
+ const code = (error as { code?: unknown } | null)?.code;
+ if (code === '55P03' || code === '57014') return null;
+ throw error;
+ }
+}
+
/** #5984: whether `waiveNoopEntry` would waive this frozen entry now (read-only; the bulk group stops before such an entry). */
export async function wouldWaiveEntry(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig, signal?: AbortSignal): Promise<boolean> {
if (!noopWaiversEnabled() || pending.pageId === null) return false;