Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Keep working-tree imports on --full and slice a sync above the cursor bound (P4.5 [R15], #6349 P4.4)

garrytan1d593c85ce55
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 79254587c1..141768d711 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -11,3 +11,7 @@
- `src/core/cycle/extract-atoms-page-state.ts` — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Atom item completion still waits for all atoms and provenance links; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.
- `src/core/persistence/grandfather.ts` — provider-free canonical publication for the grandfather compatibility flag on active managed Markdown pages. Admission retains a checkpointed request UUID, exact source/incarnation/page/revision identity and a private rollback snapshot. Publication preserves chunks/vectors and only already-valid text seals, carries matching atom scan state across the metadata hash change, and defers embeddings without queuing fact extraction. Explicit validation choices, archived sources and non-Markdown artifacts remain untouched; unpublished file edits refuse. Pages under a declared `storage.db_only` dir without a local cache file publish database-only. The committed revision is returned so the migration's verify phase can tell a later rewrite from a lost write. `admitCanonicalGrandfather` splits admission from `complete()` (wait, then settle the checkpoint exactly as the serial `grandfatherCanonicalPage` does); the migration admits a 50-page window before waiting, so the pages' Git effects coalesce (#5530). The unmanaged migration keeps its bounded SQL batches. `test/grandfather-managed.test.ts` covers both engines, replay, races and preserved artifacts; the unchanged local-install lifecycle exercises the public upgrade path.
+
+- `src/core/persistence/managed-mode.ts` — the one reader of the brain's persistence mode (#6482). `readManagedMode` / `readPersistenceBrain` accept exactly one `persistence_brain` row with a boolean `enabled` (optionally `FOR SHARE` / `FOR UPDATE`) and refuse anything else (`storage_error`, `detail: persistence_mode_unknown`, fix `gbrain sources writer status --probe --json`); only a well-formed `enabled: false` row selects the unmanaged path, so a missing, duplicated or malformed row can never route a write around the owner. Every non-test reader of the mode goes through it (`test/persistence-mode-reader-guard.test.ts` lists the few schema and admin-intent files allowed their own statement); `ownership.ts` re-exports it for callers that already import ownership.
+
+- `src/core/persistence/sync-slices.ts` — #6349 path-sliced staging for a managed target that exceeds the cursor bound with no commit axis to stage on (a first sync, a `--full` tree walk, one commit above the bound). `sliceEntries` cuts the whole resolved manifest in `(phase, code-unit path)` order: every import slice, then bounded deletion slices, the longest prefix the bound admits. The slice cursor `{ phase, after, head, target }` lives in `op_checkpoints` (`managed-sync-slice`, keyed by source, incarnation and the run's cursor options so a resumed invocation with other exclusions starts over), written or cleared by the slice's checkpoint in the same transaction that leaves `last_commit` untouched until the last slice settles; `sync-discovery.ts` resumes an unfinished target pinned at its recorded commit.
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 2ef83a875c..e62f5bf08f 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -30,7 +30,8 @@
| [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` |
| A managed catch-up on a live checkout keeps dying (`revision_conflict`, `pinned_git_worktree_conflict`, `page_identity_changed`, `write ECONNABORTED`), or you want an agent to drive the recovery | `gbrain sync status --source <id> --json` (cursor, `committed_last_10m`, each hold and the last error with `class` / `safe_actions` / `needs_human`); when nothing moved and `needs_human` is false, `gbrain sync unblock --source <id> --apply`, then the sync it prints ([runbook](sync-unblock-runbook.md)) | agent; a person only when `needs_human` names a slug | none | `gbrain sync status --source <id> --json` |
| [Sync held a file with `worktree_dirty`](#worktree-dirty-hold) | commit (or restore) the file, then `gbrain sync unblock --source <id> --apply` and the sync it prints | agent; whoever edits the file commits it | none | `gbrain sources status <id> --json` |
-| A managed sync of a source far behind HEAD prints `staged catch-up: synced to <commit>, short of HEAD`, or refuses `request_too_large` with `One commit exceeds the bounded cursor size` | Staging is automatic: `gbrain sync --source <id> --no-pull` takes stage after stage (each the furthest first-parent commit whose delta fits 100,000 entries and 16 MiB) until it reaches HEAD, and a stop resumes at the stored cursor; a scheduled sync takes one stage per run. When one commit alone is above the bound, exclude part of it (`--exclude`, or `gbrain config set sync.exclude`) and rerun; `--full` above the bound still refuses | agent | none | `gbrain sync status --source <id> --json` (cursor target reaches HEAD) |
+| A managed sync of a source far behind HEAD prints `staged catch-up: synced to <commit>, short of HEAD`, or `sliced catch-up: committed the <phase> slice of <commit> through <path>` | Staging is automatic: `gbrain sync --source <id> --no-pull` takes stage after stage (each the furthest first-parent commit whose delta fits 100,000 entries and 16 MiB) until it reaches HEAD, and a stop resumes at the stored cursor; a scheduled sync takes one stage per run. A first sync, a `--full` sync or one commit that alone exceeds the bound is cut into path slices instead (#6349): every import slice, then bounded deletion slices, pinned at one target; `last_commit` moves only when the last slice settles, and the same command resumes an unfinished target at its stored slice. Only one file whose manifest entry alone exceeds the byte bound still refuses `request_too_large`, naming it; exclude it (`--exclude`, or `gbrain config set sync.exclude`) and rerun | agent | none | `gbrain sync status --source <id> --json` (cursor target reaches HEAD) |
+| A write, sync, connector run or activation refuses `storage_error` with `requires exactly one known boolean persistence state` (`detail: persistence_mode_unknown`) | The `persistence_brain` singleton is missing, duplicated or malformed, so gbrain cannot tell whether the brain is managed and refuses instead of writing around the owner (#6482). Run `gbrain sources writer status --probe --json` on the brain host (it reports `mode: unknown` and the problem instead of refusing), restore the one row (`gbrain doctor --json` names the repair), then rerun the command | host operator | none | `gbrain doctor --json` |
| The drain stopped `connection_lost` | check the database and pooler (`gbrain doctor --json`), then rerun the same sync; it resumes at the stored cursor | agent | none | `gbrain sync status --source <id> --json` |
| [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic` / `write_capacity`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` |
| [The catch-up is parked: `data_moving: false`, doctor `managed_sync_not_moving`, or `gbrain sources writer movement` exited 1](#managed-sync-not-moving) | `gbrain sources status <id> --json` prints the exact writer-status command; run it: `gbrain sources writer status --source <id> --json` ends each running claim in a `claim.next` (`claim_running`: rerun after `retry_after_ms`; `claim_overdue`: `tell_user_to_run`, restart the named owner pid) | agent; the restart after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources writer movement <id>` (exit 0 when the data moves again), then `gbrain doctor --only managed_sync_not_moving --json` |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 93157d474b..a3dd173317 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 4511 ratchet +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)
-src/commands/sync.ts 517 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)
+src/commands/sync.ts 519 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)
src/core/cycle.ts 3303 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)
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
diff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.ts
index 280fd9afea..d3848a47df 100644
--- a/src/commands/sync-diagnostics.ts
+++ b/src/commands/sync-diagnostics.ts
@@ -69,6 +69,7 @@ export function printManagedSyncNotes(result: SyncResult, write: (line: string)
for (const refusal of result.fileRefusals ?? []) {
write(` Refused ${refusal.code}: ${refusal.message} ${refusal.suggestion} (${refusal.docs})`);
}
+ if (result.working_tree_kept) write(` ${result.working_tree_kept} page(s) whose file is in the working tree but not in Git were kept (imported from the working tree, or import provenance unknown); delete the file, or commit it, to change that.`);
const skips = result.legacySkips;
if (skips?.contextualMode) write(` ${skips.contextualMode} legacy file(s) skipped because they parse to the same page but have no contextual retrieval mode, which a skipped import cannot stamp; to stamp it: gbrain repair contextual-mode`);
if (skips?.canonicalBytes) write(` ${skips.canonicalBytes} legacy file(s) skipped because they parse to the same page but their bytes are not what gbrain reads back (for example, not valid UTF-8); re-save them as UTF-8 to publish them exactly.`);
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 5930ff715f..6f940dc26a 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -51,6 +51,8 @@ export interface SyncResult {
/** 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;
+ /** #5459 (P4.5): live pages a `--full` tree walk kept because their file is in the working tree and their import provenance is the working tree or unknown. */
+ working_tree_kept?: number;
/**
* Aggregated alias/undeclared explicit-type warnings (schema.type_warnings,
* default on) — one entry per distinct non-canonical type this run.
@@ -96,8 +98,8 @@ export interface SyncResult {
bankedFiles?: number;
/** #5984: the managed drain's verdict and the next step for the agent (see sync-drain.ts). */
drain?: import('../core/persistence/sync-drain.ts').DrainReport;
- /** #6349: this run synced a staged first-parent commit (`target`) short of `head`, because the delta to HEAD exceeded the cursor bound; `stages` counts the stages a CLI loop took. */
- staged?: { target: string; head: string; stages?: number };
+ /** #6349: this run synced a staged first-parent commit (`target`) short of `head`, because the delta to HEAD exceeded the cursor bound; `stages` counts the stages a CLI loop took. P4.4: `slice` names the path slice of `target` this run committed when the target itself exceeds the bound. */
+ staged?: { target: string; head: string; stages?: number; slice?: { phase: 'import' | 'delete'; after: string | null } };
/** #6278: the run stopped because too many writes stalled while preparing (one systemic diagnostic instead of a pile of holds). */
breaker?: import('../core/persistence/sync-run.ts').ManagedSyncBreaker;
/** #5984: managed cursor position (`index` of `total` manifest entries) and its active drain window. */
diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.ts
index 2446530967..da0f4ad571 100644
--- a/src/commands/sync/perform.ts
+++ b/src/commands/sync/perform.ts
@@ -64,7 +64,9 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<
// #6349: a delta past the cursor bound syncs in stages; a drain takes the next stage from where the last one landed
// until it reaches HEAD (each stage freezes its own bounded manifest, and a stop resumes at the stored cursor).
while (opts.drain && result.staged && result.drain?.outcome === 'synced' && !opts.dryRun && !opts.signal?.aborted) {
- serr(`[sync] staged catch-up: synced to ${result.staged.target.slice(0, 12)}, short of HEAD ${result.staged.head.slice(0, 12)} (the delta exceeds the cursor bound); taking the next stage.`);
+ serr(result.staged.slice
+ ? `[sync] sliced catch-up: committed the ${result.staged.slice.phase} slice of ${result.staged.target.slice(0, 12)} through ${result.staged.slice.after ?? '(start)'} (the target exceeds the cursor bound); taking the next slice.`
+ : `[sync] staged catch-up: synced to ${result.staged.target.slice(0, 12)}, short of HEAD ${result.staged.head.slice(0, 12)} (the delta exceeds the cursor bound); taking the next stage.`);
const next = await (await import('../../core/persistence/sync-drain.ts')).drainManagedSync(engine, opts, true);
const stages = (result.staged.stages ?? 1) + 1, d = result.drain, n = next.drain;
result = { ...next, fromCommit: result.fromCommit, added: result.added + next.added, modified: result.modified + next.modified, deleted: result.deleted + next.deleted,
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 04f73052dd..099dc0d5b2 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -437,6 +437,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.165.0', text: '`gbrain extract --stale` and `extract links|all --source db` skip and count a page another writer changed mid-run (`skipped_concurrent_write`) instead of aborting the run; the page stays stale for the next run. `extract all --source db` marks a page extracted only when both its links and its timeline finished at the same revision. On a managed brain, `extract timeline --from-meetings` (and its job) now writes through the coordinator as one `managed_maintenance_meeting_timeline` request per entity page, gated at the meeting\'s trust tier; a refused or pending write fails the job and the command exits 1. An owner on an older build refuses that request kind until it upgrades. On a managed brain, `extract_entities` now writes stubs, timeline rows and backlinks through the coordinator (creating a stub needs permission to write pages); a refusal or pending write returns its error envelope and names the entities already written, instead of a raw `writer_coordinator_required` error or a silently missing timeline row.' },
// Memory proof wave 2 W1 (question-ranked recall).
{ since: '0.60.169.0', text: '`recall` takes an optional `question` and returns saved facts ranked by relevance to it (facts below the match threshold are left out); calls without it still return the newest facts, every response now says `facts_order`, and a call that passes only `query` carries a `recall_hint` notice. `gbrain recall --question` passes the question instead of reading its value as an entity name. In `query`, the facts of an entity the question names come only from that entity page\'s own source, and the temporal fact reserve (`search.temporal_fact_reserve`, off by default) scores with the same question scorer: whole-word matches, and a long fact\'s word matches count for less.' },
+ // Fix wave 15 group 1 (managed sync authority and data safety).
+ { since: '0.60.176.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index c0faaa55b1..5181133aa9 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -21,9 +21,10 @@ import type { CompanyBrainPlan } from '../company-brain/types.ts';
import { assertDistinctSyncOrigins, legacySyncOrigin, sameSyncOrigin, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive } from './sync-authority.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
-import { holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds } from './sync-holds.ts';
+import { holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, readSyncImportProvenances } from './sync-holds.ts';
import { readBlobContents, readTreeBlobs } from './sync-blobs.ts';
import { gitChildEnv } from '../git-env.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. */
export interface SyncRename { sourcePath: string; slug: string; pageId: number; revision: string; }
@@ -47,7 +48,11 @@ export interface SyncDiscovery { binding: WorktreeBinding; root: string; gitRoot
/** #5988: `sources retry-held` paths this discovery consumed (screened as an entry or a candidate, or no longer eligible); cleared with the cursor save. */
retryTaken?: string[];
/** #6349: the checkout's HEAD when the delta to it exceeded the cursor bound and `target` is a staged first-parent commit short of it. */
- stagedHead?: string; }
+ stagedHead?: string;
+ /** #5459 (P4.5): live pages the tree walk left alone because their file is in the working tree and their import provenance is the working tree or unknown. */
+ workingTreeKept?: string[];
+ /** #6349 (P4.4): this discovery is one path slice of its target; the checkpoint records it instead of advancing `last_commit` until `done`. */
+ slice?: SyncSliceState; }
export interface ManagedSyncContext { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;
source: { last_commit: string | null; config: Record<string, unknown> }; }
/** The persisted `sync.exclude` globs (plus a run's `--exclude`), as discovery matches them against a path relative to the source root. */
@@ -55,6 +60,10 @@ export async function syncExcludePatterns(engine: Pick<BrainEngine, 'getConfig'>
return [...extra, ...(await engine.getConfig('sync.exclude') ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)]
.map(v => v.endsWith('/') ? `${v}**` : v);
}
+/** Whether `commit` is still reachable in the checkout (a sliced target pinned before a history rewrite is not). */
+function commitExists(gitRoot: string, commit: string): boolean {
+ try { syncGit(gitRoot, ['cat-file', '-e', `${commit}^{commit}`]); return true; } catch { return false; }
+}
export function syncGit(root: string, args: string[]): string {
return execFileSync('git', ['-c', 'core.quotepath=false', '-C', root, ...args],
{ env: gitChildEnv(), encoding: 'utf8', timeout: 30_000, maxBuffer: 32 * 1024 ** 2, stdio: ['ignore', 'pipe', 'pipe'] });
@@ -96,6 +105,10 @@ export function readSyncFile(root: string, path: string): Buffer | null {
return readFileSync(absolute);
} catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
}
+/** Whether a file backs `path` in the working tree; a file that exists but cannot be read as a sync target (a symlink, oversized) still counts as present. */
+function workingTreeFilePresent(root: string, path: string): boolean {
+ try { return readSyncFile(root, path) !== null; } catch { return true; }
+}
export const syncRawHash = (root: string, path: string): string | null => { const bytes = readSyncFile(root, path); return bytes === null ? null : sha256(bytes); };
export function assertConfiguredSyncRoot(root: string, configuredRoot: string | null): void {
if (configuredRoot === null) return;
@@ -201,9 +214,50 @@ export function stagedSyncTarget(gitRoot: string, from: string, target: string,
return good < 0 ? { oversized: commits[0] ?? target } : { commit: commits[good]!, first: commits[0]! };
}
-export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, context?: ManagedSyncContext, stage?: { target: string; head: string }): Promise<SyncDiscovery> {
+/**
+ * #6349 (P4.4): an unfinished path-sliced target of this source under these exact options continues where its last
+ * slice checkpointed, pinned at the same target; a target history no longer holds starts over from HEAD.
+ */
+async function resumableSliceStage(engine: BrainEngine, opts: SyncOpts, gitRoot: string, sourceId: string, incarnation: string):
+ Promise<{ target: string; head: string; slice: Pick<SyncSliceCursor, 'phase' | 'after'> } | null> {
+ const resume = await readSyncSlice(engine, sourceId, incarnation, syncCursorOptions(opts));
+ if (!resume || !commitExists(gitRoot, resume.target)) return null;
+ return { target: resume.target, head: syncGit(gitRoot, ['rev-parse', 'HEAD']).trim(), slice: { phase: resume.phase, after: resume.after } };
+}
+/**
+ * #5459 (P4.5): "not in the Git tree" is not "deleted" for a page imported from the working tree. The durable import
+ * provenance (not the request intent, which compaction nulls) says where the bytes came from; a working-tree import
+ * whose file is still present is kept, and unknown provenance with the file present is held rather than deleted. A
+ * page whose provenance is the pinned Git blob follows Git even when a copy of the file lingers untracked.
+ */
+async function keptWorkingTreePages(engine: BrainEngine, scope: { sourceId: string; incarnation: string; root: string; nativeRoot: string; nativeGitRoot: string },
+ absent: ReadonlyArray<{ id: number; gitPath: string }>): Promise<Set<string>> {
+ const provenance = await readSyncImportProvenances(engine, scope.sourceId, scope.incarnation, absent.map(page => page.id));
+ const kept = new Set<string>();
+ for (const page of absent) {
+ const record = provenance.get(Number(page.id));
+ const fromGit = record?.working === false || (record?.working === undefined && !!record?.blob_oid);
+ if (!fromGit && workingTreeFilePresent(scope.root, relative(scope.nativeRoot, join(scope.nativeGitRoot, page.gitPath)).split(sep).join('/'))) kept.add(page.gitPath);
+ }
+ return kept;
+}
+/** #6349 (P4.4): cuts the resolved manifest to its next path slice and marks the discovery as one slice of a pinned target. */
+function cutDiscoveryToSlice(discovered: SyncDiscovery, slicing: Pick<SyncSliceCursor, 'phase' | 'after'>, head: string): void {
+ const cut = sliceEntries(discovered.entries, slicing, manifestFits);
+ if (!manifestFits(cut.entries)) throw opError('request_too_large', 'One sync entry exceeds the bounded cursor size.',
+ `Entry ${cut.entries[0]?.path} of ${discovered.sourceId} alone exceeds the ${Math.round(cursorBound.bytes / 1024 ** 2)} MiB cursor bound; nothing was written. Exclude it with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${discovered.sourceId}.`);
+ discovered.entries = cut.entries;
+ discovered.slice = { phase: cut.phase, after: cut.after, head, target: discovered.target, done: cut.done };
+ if (cut.done && discovered.target === head) delete discovered.stagedHead; else discovered.stagedHead = head;
+}
+export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, context?: ManagedSyncContext,
+ stage?: { target: string; head: string; slice?: Pick<SyncSliceCursor, 'phase' | 'after'> }): Promise<SyncDiscovery> {
const { binding, root, gitRoot, sourceId, incarnation, source } = context ?? await resolveManagedSyncContext(engine, opts);
const company = currentCompanyBrainSync(sourceId);
+ if (!company && !stage && !opts.dryRun) {
+ const resume = await resumableSliceStage(engine, opts, gitRoot, sourceId, incarnation);
+ if (resume) return discoverManagedSync(engine, opts, context ?? { binding, root, gitRoot, sourceId, incarnation, source }, resume);
+ }
const strategy = opts.strategy ?? source.config?.strategy ?? 'markdown';
const nativeRoot = realpathSync.native(root), nativeGitRoot = realpathSync.native(gitRoot);
const scope = relative(nativeGitRoot, nativeRoot).split(sep).join('/');
@@ -220,6 +274,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
!matchesAnyGlob(scope ? path.slice(scope.length + 1) : path, exclude) && !isReservedSkillBundlePath(sourcePath(path)) &&
isSyncable(path, { strategy: strategy as 'markdown', includeHidden });
const target = stage?.target ?? company?.plan.revision?.commit ?? syncGit(gitRoot, ['rev-parse', 'HEAD']).trim();
+ const head = stage?.head ?? target;
+ const slicing = stage?.slice ?? null;
const detached = !company && syncGit(gitRoot, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() === 'HEAD';
// #6349: a staged run stops at a commit, so uncommitted working-tree changes wait for the stage that reaches HEAD.
const working = !company && !stage && (detached || (opts.workingTree ?? (await engine.getConfig('sync.include_working_tree') === 'true')));
@@ -227,6 +283,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const delta = !opts.full && source.last_commit ? computeSyncDelta(gitRoot, source.last_commit, target) : null;
const entries = new Map<string, SyncEntry>();
const renamedFrom = new Map<string, string>();
+ let workingTreeKept: string[] | undefined;
+ let treeAbsent: Array<{ id: number; gitPath: string }> = [];
const discoveredAt = new Date().toISOString();
// #5988: active holds are re-screened when their file changed, left, or a newer reader may import it.
const holds = company ? [] : (await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds.filter(hold => hold.incarnation === incarnation) ?? [];
@@ -280,26 +338,32 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
assertDistinctSyncOrigins(paths);
const present = new Set(paths.map(path => syncOriginPath(sourcePath(path))));
for (const path of paths) put(path, 'import');
- const livePages = await engine.executeRaw<{ slug: string; source_path: string }>('SELECT slug,source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);
+ const livePages = await engine.executeRaw<{ id: number; slug: string; source_path: string }>('SELECT slug,source_path,id FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);
const gitPathOf = (origin: string) => slugMode === 'source-root' && scope ? `${scope}/${origin}` : origin;
const listedSet = new Set(listed);
for (const page of livePages) if (!storable(page) && !listedSet.has(gitPathOf(page.source_path))) refuse(gitPathOf(page.source_path), 'delete');
const pages = livePages.filter(storable);
assertDistinctSyncOrigins([...present, ...pages.map(page => page.source_path)]);
- for (const page of pages) {
+ const absent = pages.filter(page => {
const origin = syncOriginPath(page.source_path);
const stripped = slugMode === 'source-root' && scope && origin.startsWith(`${scope}/`) ? origin.slice(scope.length + 1) : null;
- if (present.has(origin) || stripped !== null && present.has(stripped) && sameSyncOrigin(origin, stripped, originScope, page.slug)) continue;
+ if (present.has(origin) || stripped !== null && present.has(stripped) && sameSyncOrigin(origin, stripped, originScope, page.slug)) return false;
// #5988: the old page of a held rename keeps its origin until the renamed file imports.
- if (holdRenameOrigins.has(origin)) continue;
- put(gitPathOf(origin), 'delete');
- }
+ return !holdRenameOrigins.has(origin);
+ });
+ treeAbsent = absent.map(page => ({ id: page.id, gitPath: gitPathOf(syncOriginPath(page.source_path)) }));
}
if (working) {
for (const path of [...dirty.added, ...dirty.modified]) put(path, 'import', true);
for (const path of dirty.deleted) put(path, 'delete', true);
for (const rename of dirty.renamed) putRename(rename, true);
}
+ if (treeAbsent.length) {
+ // A path the selected working tree already decided (an import or a deletion above) is not re-judged.
+ const kept = await keptWorkingTreePages(engine, { sourceId, incarnation, root, nativeRoot, nativeGitRoot }, treeAbsent.filter(page => !entries.has(page.gitPath)));
+ for (const page of treeAbsent) if (!entries.has(page.gitPath) && !kept.has(page.gitPath)) put(page.gitPath, 'delete');
+ if (kept.size) workingTreeKept = [...kept];
+ }
// #6278 (B7): every scheduled path is consumed by this discovery: it is screened as an entry (the file changed in Git),
// re-screened as a candidate below, or can never be screened (no longer eligible), so none may outlive the run.
const released: string[] = [], retryTaken = [...retry];
@@ -349,7 +413,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const unsupported = selected.find(e => e.action === 'import' && !/\.mdx?$/i.test(e.path) && !isCodeFilePath(e.path) && (company || !isImageFilePath(e.path)));
if (unsupported) throw opError('writer_coordinator_required', 'Managed image sync requires a prepared importer; this sync was refused before any page write.',
`Managed sync of ${sourceId} imports only Markdown and code files, and this run selected others (for example ${unsupported.path}). Exclude them with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);
- if (!manifestFits(selected)) {
+ if (!manifestFits(selected) && !slicing) {
// #6349: an incremental delta past the bound is synced in stages: the furthest first-parent commit whose delta fits,
// then the next stage from there (the CLI loops; a scheduled sync takes one stage per run).
if (delta?.status === 'ok' && !company && source.last_commit) {
@@ -360,19 +424,20 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const paths = [...step.manifest.added, ...step.manifest.modified, ...step.manifest.deleted, ...step.manifest.renamed.flatMap(r => [r.from, r.to])].filter(eligible);
return paths.map(path => ({ path: relative(nativeRoot, join(nativeGitRoot, path)).split(sep).join('/'), sourcePath: sourcePath(path), action: 'import', working: false }));
};
- const staged = stagedSyncTarget(gitRoot, last, stage?.head ?? target, commit => { const entries = deltaEntries(commit); return !!entries && manifestFits(entries); });
- if ('commit' in staged && staged.commit !== target) return discoverManagedSync(engine, opts, context, { target: staged.commit, head: stage?.head ?? target });
- if ('oversized' in staged) {
- const size = deltaEntries(staged.oversized)?.length ?? selected.length;
- throw opError('request_too_large', 'One commit exceeds the bounded cursor size.',
- `Commit ${staged.oversized.slice(0, 12)} alone changes ${size} syncable entries in ${sourceId} (from ${last.slice(0, 12)}), above the ${cursorBound.entries.toLocaleString('en-US')}-entry and ${Math.round(cursorBound.bytes / 1024 ** 2)} MiB cursor bound, so it cannot be synced in stages; nothing was written. Exclude part of it with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);
- }
+ const staged = stagedSyncTarget(gitRoot, last, head, commit => { const entries = deltaEntries(commit); return !!entries && manifestFits(entries); });
+ if ('commit' in staged && staged.commit !== target) return discoverManagedSync(engine, opts, context, { target: staged.commit, head });
+ // #6349 (P4.4): one commit alone above the bound is a fixed set, so it is pinned and cut into path slices.
+ if ('oversized' in staged) return discoverManagedSync(engine, opts, context, { target: staged.oversized, head, slice: { phase: 'import', after: null } });
}
- throw opError('request_too_large', 'Sync discovery exceeds the bounded cursor size.',
+ if (company) throw opError('request_too_large', 'Sync discovery exceeds the bounded cursor size.',
`This sync of ${sourceId} selected ${selected.length} entries, above the 100,000-entry and 16 MiB cursor bound; nothing was written. Narrow it with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);
+ // #6349 (P4.4): a first sync or a `--full` tree walk has no commit axis to stage on; the target is cut into path slices
+ // (re-entered as a stage so the slices read the pinned tree alone, never the working tree).
+ return discoverManagedSync(engine, opts, context ?? { binding, root, gitRoot, sourceId, incarnation, source }, { target, head, slice: { phase: 'import', after: null } });
}
const discovered: SyncDiscovery = { discoveredAt, ...(released.length ? { releasedHolds: released } : {}), ...(retryTaken.length ? { retryTaken } : {}),
- ...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}), ...(stage ? { stagedHead: stage.head } : {}) };
+ ...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}), ...(stage ? { stagedHead: stage.head } : {}),
+ ...(workingTreeKept ? { workingTreeKept } : {}) };
// Freeze all logical identities in one database statement, before yielding
// between pages. A later interactive edit must conflict with this scan.
const identities = await engine.executeRaw<{ id: number; slug: string; source_path: string | null; knowledge_revision: string }>(
@@ -473,6 +538,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
}
if (retired.size) discovered.entries = selected.filter(entry => !retired.has(entry));
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);
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-holds.ts b/src/core/persistence/sync-holds.ts
index e3ab7c1a33..6c6c13a14e 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -669,6 +669,8 @@ export interface SyncImportProvenance {
origin: string;
raw_sha256: string;
blob_oid?: string;
+ /** #5459 (P4.5): true when the bytes came from the working tree (an untracked or uncommitted file), false from the pinned Git blob; absent on records written before the stamp. */
+ working?: boolean;
gbrain_version: string;
validated: true;
recovery?: Array<{ kind: string; key: string; line: number; recovery_version: number }>;
@@ -684,6 +686,14 @@ export async function recordSyncImportProvenance(tx: Exec, value: Omit<SyncImpor
[SYNC_IMPORT_PROVENANCE_OP, provenanceFingerprint(value.source_id, value.incarnation, value.page_id), JSON.stringify([record])]);
}
+/** The provenance of several pages in one statement, keyed by page id; pages without a record are absent. */
+export async function readSyncImportProvenances(engine: Exec, sourceId: string, incarnation: string, pageIds: readonly number[]): Promise<Map<number, SyncImportProvenance>> {
+ if (!pageIds.length) return new Map();
+ const rows = await engine.executeRaw<{ record: SyncImportProvenance }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint = ANY($2::text[])',
+ [SYNC_IMPORT_PROVENANCE_OP, pageIds.map(id => provenanceFingerprint(sourceId, incarnation, id))]);
+ return new Map(rows.map(row => [Number(row.record.page_id), row.record]));
+}
+
export async function readSyncImportProvenance(engine: Exec, sourceId: string, incarnation: string, pageId: number): Promise<SyncImportProvenance | null> {
const [row] = await engine.executeRaw<{ record: SyncImportProvenance }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',
[SYNC_IMPORT_PROVENANCE_OP, provenanceFingerprint(sourceId, incarnation, pageId)]);
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 698a2803f6..deb748be81 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -40,6 +40,7 @@ import { checkpointRetryCommand, findIncompleteSyncReceipt } from './checkpoint-
import { frontmatterSlugConflictMessage } from './verb-errors.ts';
import { chunkerStamp } from '../chunkers/code.ts';
import { clearGitHold, countGitHolds, recordSyncImportProvenance } from './sync-holds.ts';
+import { clearSyncSlice, writeSyncSlice, type SyncSliceState } from './sync-slices.ts';
import { readPagePurgeTombstones } from './page-purge.ts';
import { fenceWhere } from '../fence-repair/refusal.ts';
import { fencesNormalizeEnabled } from '../fence-repair/config.ts';
@@ -67,6 +68,8 @@ export interface SyncIntent extends Record<string, unknown> {
repoPath?: string;
/** #5522: another cursor of this source imported entries of this run, so the source may already sit at the target. */
overtaken?: boolean;
+ /** #6349 (P4.4) checkpoint only: this run was one path slice of its target; `last_commit` advances only with `done`. */
+ slice?: SyncSliceState;
/** #5988: the run's discovery time; committing this entry clears the path's hold unless a newer run wrote it. */
holdObservedAt?: string;
/** #5988 checkpoint only: held paths that left the source (excluded); their holds clear when the run checkpoints. */
@@ -303,6 +306,15 @@ async function resolveSyncOrigin(engine: BrainEngine, row: WriteRequest, p: Sync
* Its validation also accepts this run's cursor with nothing pending; the waiver transaction then requires exactly that
* cursor (run, index, nothing pending) under its lock.
*/
+/**
+ * #6349 (P4.4): a slice short of its target's end leaves `last_commit` where it was (the caller binds `from` back) and
+ * records where the next slice starts, in the checkpoint's transaction; the last slice clears the record.
+ */
+async function recordSliceCursor(tx: BrainEngine, row: WriteRequest, p: { syncOptions?: SyncCursorOptions; slice?: SyncSliceState }, settled: boolean): Promise<void> {
+ if (!p.syncOptions) return;
+ if (settled) await clearSyncSlice(tx, row.source_id, row.source_incarnation, p.syncOptions);
+ else await writeSyncSlice(tx, row.source_id, row.source_incarnation, p.syncOptions, p.slice!);
+}
export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock?: ClaimPhaseClock,
screening?: { unsaved: true }): Promise<PreparedMutation> {
const engine = boundedReads(unbounded, clock);
@@ -402,15 +414,17 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
`Page request ${incomplete} of this sync run is still open or needs recovery, so checkpoint request ${row.request_id} of ${row.source_id} did not commit. `
+ `Inspect request ${incomplete} and let it finish; do not resubmit it. Then run: ${checkpointRetryCommand({ sourceId: row.source_id, processingOptions: p.processingOptions, syncOptions: p.syncOptions, repoPath: p.repoPath })}`,
{ fix: syncInspectFix(row, incomplete, false) });
+ const settled = !p.slice || p.slice.done;
// #5522: an overtaken run accepts a source another cursor already checkpointed at this exact target.
const changed = await tx.executeRaw(`UPDATE sources SET last_commit=$3,last_sync_at=now(),config=jsonb_set(${SOURCE_CONFIG_OBJECT_SQL},'{slug_root_mode}',to_jsonb($5::text)),
newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL)
WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR ($6::boolean AND last_commit=$3))
- AND (config->>'slug_root_mode' IS NULL OR config->>'slug_root_mode'=$5) RETURNING id`, [row.source_id, row.source_incarnation, p.target, p.from, p.slugMode, p.overtaken === true]);
+ AND (config->>'slug_root_mode' IS NULL OR config->>'slug_root_mode'=$5) RETURNING id`, [row.source_id, row.source_incarnation, settled ? p.target : p.from, p.from, p.slugMode, p.overtaken === true]);
if (!changed.length) throw syncPublicationRefusal('revision_conflict', 'The source checkpoint changed during this sync.', row, p,
`Another sync moved the commit checkpoint of ${row.source_id} while this run published.`);
+ await recordSliceCursor(tx, row, p, settled);
// #5566: a full walk re-chunked every stale page, so acknowledge the chunker version as the legacy gate does.
- if (p.from === null || p.syncOptions?.full === true) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, chunkerStamp()]);
+ if (settled && (p.from === null || p.syncOptions?.full === true)) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, chunkerStamp()]);
await tx.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,done}','true'::jsonb),updated_at=now() WHERE op='managed-sync' AND fingerprint=$1", [p.cursorKey]);
for (const path of p.releasedHolds ?? []) await releaseHold(tx, path);
return { status: 'synced', source_id: row.source_id, committed_pages: p.total };
@@ -591,7 +605,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
},
() => releaseHold(tx),
async () => { if (final) await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(final.page.id), origin: p.sourcePath!,
- raw_sha256: sha256(p.content!), ...(p.blobOid ? { blob_oid: p.blobOid } : {}), gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}) }); },
+ raw_sha256: sha256(p.content!), ...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}) }); },
]);
preparedImport.postimage = final;
return { status: moved ? 'renamed' : applied.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 72ab04cca0..1606a97b3d 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -13,6 +13,7 @@ import { preparationConfigView } from './config-snapshot.ts';
import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';
import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer, type WriteWait } from './service.ts';
import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';
+import { syncCursorOptions } from './sync-slices.ts';
import { isImageFilePath } from '../sync.ts';
import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
@@ -286,8 +287,8 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], rea
toCommit: cursor.authority.writer.remote ? '' : cursor.target, added: cursor.counts.added, modified: cursor.counts.modified,
deleted: cursor.counts.deleted, renamed: cursor.counts.renamed ?? 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],
...(cursor.slugCollisions?.length ? { slugCollisions: cursor.slugCollisions } : {}),
- ...(cursor.fileRefusals?.length ? { fileRefusals: cursor.fileRefusals } : {}),
- ...(cursor.stagedHead && !cursor.authority.writer.remote ? { staged: { target: cursor.target, head: cursor.stagedHead } } : {}),
+ ...(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 },
filesImported: cursor.index, bankedFiles: cursor.index,
managedCursor: { index: cursor.index, total: 'total' in cursor ? cursor.total : cursor.entries.length, ...(cursor.progress ? { progress: cursor.progress } : {}) },
@@ -430,7 +431,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
processingOptions: cursor.processingOptions,
// A cursor created before its options were recorded has the same key, so this run's options are its options.
...(!entry ? { syncOptions: cursor.syncOptions ?? run.syncOptions, ...(run.repoPath ? { repoPath: run.repoPath } : {}) } : {}),
- ...(!entry && cursor.overtaken ? { overtaken: true } : {}),
+ ...(!entry && cursor.overtaken ? { overtaken: true } : {}), ...(!entry && cursor.slice ? { slice: cursor.slice } : {}),
ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority, cursorKey: key, runId: cursor.runId,
slugMode: cursor.slugMode, index: cursor.index, total: cursor.entries.length, from: cursor.from, target: cursor.target, working: entry?.working ?? false,
...(cursor.companyPlan ? { companyApproval: { schema: cursor.companyPlan.schema!, planDigest: cursor.companyPlan.plan_digest, extractorVersion: cursor.companyPlan.extractor_version,
@@ -1150,10 +1151,7 @@ interface HoldRunState { sourceId?: string; incarnation?: string; remote?: boole
*/
/** The cursor-selecting options of a managed run; part of its durable cursor key. */
-function cursorSyncOptions(opts: SyncOpts): SyncCursorOptions {
- return { full: opts.full ?? false, workingTree: opts.workingTree ?? false, srcSubpath: opts.srcSubpath ?? null,
- exclude: opts.exclude ?? [], includeHidden: opts.includeHidden ?? [], strategy: opts.strategy ?? null };
-}
+const cursorSyncOptions = syncCursorOptions;
function managedCursorKey(incarnation: string, authority: SyncAuthority, company: ReturnType<typeof currentCompanyBrainSync>, syncOptions: SyncCursorOptions): string {
return digest({ source: incarnation, principal: authority.writer.principal, authority, ...(company ? { company: { receiptId: company.receiptId, planDigest: company.plan.plan_digest } } : {}),
options: syncOptions });
diff --git a/src/core/persistence/sync-slices.ts b/src/core/persistence/sync-slices.ts
new file mode 100644
index 0000000000..c10c4ada84
--- /dev/null
+++ b/src/core/persistence/sync-slices.ts
@@ -0,0 +1,79 @@
+/**
+ * #6349 (fix wave 15 P4.4): path-sliced staging for a managed sync whose selected entries exceed the cursor bound
+ * when no commit staging applies: a first sync (no `last_commit`), a `--full` tree walk, or one commit that alone
+ * changes more than the bound. The whole target is discovered every time (origin collisions are screened over the
+ * whole set), then cut into slices ordered `(phase, path)`: every import slice first, then bounded deletion slices,
+ * each pinned at the same target. The slice cursor `{ phase, after, head, target }` is written by the slice's
+ * checkpoint, in the same transaction, instead of `last_commit`, which advances only when the last slice settles.
+ * The record is keyed by source, incarnation and the run's cursor-selecting options, so a resumed invocation with
+ * other exclusions starts over instead of borrowing a slice cut under different options.
+ */
+import type { SyncOpts } from '../../commands/sync.ts';
+import type { BrainEngine } from '../engine.ts';
+import { digest } from './digest.ts';
+import type { SyncEntry } from './sync-discovery.ts';
+import type { SyncCursorOptions } from './sync-prepare.ts';
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+export const SYNC_SLICE_OP = 'managed-sync-slice';
+export type SyncSlicePhase = 'import' | 'delete';
+/** Where the next slice starts: the phase and the last path the previous slice of that phase committed. */
+export interface SyncSliceCursor { phase: SyncSlicePhase; after: string | null; head: string; target: string }
+/** The slice a discovery produced, carried on the cursor and the checkpoint intent; `done` marks the target's last slice. */
+export interface SyncSliceState extends SyncSliceCursor { done: boolean }
+
+/** The cursor-selecting options of a managed run; part of its durable cursor key and of the slice record's key. */
+export function syncCursorOptions(opts: SyncOpts): SyncCursorOptions {
+ return { full: opts.full ?? false, workingTree: opts.workingTree ?? false, srcSubpath: opts.srcSubpath ?? null,
+ exclude: opts.exclude ?? [], includeHidden: opts.includeHidden ?? [], strategy: opts.strategy ?? null };
+}
+const sliceFingerprint = (sourceId: string, incarnation: string, options: SyncCursorOptions) => `${sourceId}:${incarnation}:${digest(options)}`;
+
+export async function readSyncSlice(engine: Exec, sourceId: string, incarnation: string, options: SyncCursorOptions): Promise<SyncSliceCursor | null> {
+ const [row] = await engine.executeRaw<{ record: SyncSliceCursor }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',
+ [SYNC_SLICE_OP, sliceFingerprint(sourceId, incarnation, options)]);
+ const record = row?.record;
+ if (!record || (record.phase !== 'import' && record.phase !== 'delete') || typeof record.target !== 'string' || typeof record.head !== 'string') return null;
+ return { phase: record.phase, after: typeof record.after === 'string' ? record.after : null, head: record.head, target: record.target };
+}
+export async function writeSyncSlice(tx: Exec, sourceId: string, incarnation: string, options: SyncCursorOptions, slice: SyncSliceCursor): Promise<void> {
+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,
+ [SYNC_SLICE_OP, sliceFingerprint(sourceId, incarnation, options), JSON.stringify([{ ...slice, recorded_at: new Date().toISOString() }])]);
+}
+export async function clearSyncSlice(tx: Exec, sourceId: string, incarnation: string, options: SyncCursorOptions): Promise<void> {
+ await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_SLICE_OP, sliceFingerprint(sourceId, incarnation, options)]);
+}
+
+/** Code-unit order: the cursor's `after` must compare the same way on every host, which `localeCompare` does not promise. */
+const byPath = (a: SyncEntry, b: SyncEntry) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
+
+/**
+ * The next slice of `entries` (the whole target, identities resolved): the import phase runs to its end before the
+ * first deletion; within a phase, entries after `resume.after` in code-unit path order, the longest prefix the bound
+ * admits (at least one entry, so a single oversized entry still refuses through `fits` at the caller). `done` is true
+ * when nothing follows the slice in either phase.
+ */
+export function sliceEntries(entries: readonly SyncEntry[], resume: Pick<SyncSliceCursor, 'phase' | 'after'> | null,
+ fits: (entries: readonly SyncEntry[]) => boolean): { entries: SyncEntry[]; phase: SyncSlicePhase; after: string | null; done: boolean } {
+ const imports = entries.filter(entry => entry.action === 'import').sort(byPath);
+ const deletes = entries.filter(entry => entry.action === 'delete').sort(byPath);
+ let phase: SyncSlicePhase = resume?.phase ?? 'import';
+ let after = resume?.after ?? null;
+ let remaining = (phase === 'import' ? imports : deletes).filter(entry => after === null || entry.path > after);
+ if (phase === 'import' && !remaining.length) { phase = 'delete'; after = null; remaining = deletes; }
+ // Gallop up, then bisect: `fits` serializes the candidate, so the probes stay logarithmic.
+ let good = 0, step = 1;
+ while (good < remaining.length) {
+ const at = Math.min(good + step, remaining.length);
+ if (fits(remaining.slice(0, at))) { good = at; step *= 2; continue; }
+ let low = good, high = at;
+ while (high - low > 1) { const mid = (low + high) >> 1; if (fits(remaining.slice(0, mid))) low = mid; else high = mid; }
+ good = low;
+ break;
+ }
+ const slice = remaining.slice(0, Math.max(good, remaining.length ? 1 : 0));
+ const last = slice.at(-1)?.path ?? after;
+ const done = slice.length === remaining.length && (phase === 'delete' || !deletes.length);
+ return { entries: slice, phase, after: last, done };
+}
diff --git a/test/persistence-sync-options.serial.test.ts b/test/persistence-sync-options.serial.test.ts
index 4b071c8d33..06a324243d 100644
--- a/test/persistence-sync-options.serial.test.ts
+++ b/test/persistence-sync-options.serial.test.ts
@@ -588,7 +588,7 @@ async function syncState(engine: BrainEngine, sourceId: string) {
type SyncBarrier = 'discovery' | 'discovery-commit' | 'foreground' | 'freeze' | 'freeze-commit' | 'request-lookup' | 'admission-commit';
function matchesSyncBarrier(boundary: SyncBarrier, sql: string, params: unknown[] | undefined, transactional: boolean): boolean {
- if (boundary === 'discovery') return sql.startsWith('SELECT slug,source_path FROM pages WHERE source_id=');
+ if (boundary === 'discovery') return sql.startsWith('SELECT slug,source_path,id FROM pages WHERE source_id=');
if (boundary === 'foreground') return sql.includes("NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%') LIMIT 1");
if (boundary === 'freeze') return sql.startsWith('SELECT id,slug,source_path FROM pages WHERE source_id=') && !transactional;
if (boundary === 'request-lookup') return sql.startsWith('SELECT') && sql.includes('FROM persistence_requests') && sql.includes('request_id=') && !transactional;
@@ -701,7 +701,7 @@ for (const boundary of ['retry-discovery', 'retry-commit', 'missing-manifest', '
let observed = false;
engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
const rows = await execute.call(this, sql, params);
- if (!observed && (boundary === 'retry-discovery' ? sql.startsWith('SELECT slug,source_path FROM pages WHERE source_id=')
+ if (!observed && (boundary === 'retry-discovery' ? sql.startsWith('SELECT slug,source_path,id FROM pages WHERE source_id=')
: boundary === 'completed-cleanup' ? sql.startsWith('DELETE FROM op_checkpoints WHERE op=$1')
: this !== engine && sql === 'SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2' && params?.[0] === 'managed-sync')) {
observed = true; abort.abort();
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 909aa7570f..115275885b 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -126,6 +126,8 @@ test/sync-drain-inpass-stall.test.ts
test/sync-drain-write-capacity.test.ts
test/sync-frontmatter-recovery.test.ts
test/sync-frontmatter-slug-conflict.test.ts
+test/sync-full-cursor-slices-6349.test.ts
+test/sync-full-untracked-import-5459.test.ts
test/sync-group-member-order.test.ts
test/sync-legacy-holds.test.ts
test/sync-staged-catchup.test.ts
diff --git a/test/sync-full-cursor-slices-6349.test.ts b/test/sync-full-cursor-slices-6349.test.ts
new file mode 100644
index 0000000000..e70a405858
--- /dev/null
+++ b/test/sync-full-cursor-slices-6349.test.ts
@@ -0,0 +1,212 @@
+/**
+ * #6349 (fix wave 15 P4.4, [R32]): a first sync, a `--full` tree walk or one commit whose change set alone exceeds the
+ * cursor bound used to refuse forever (`request_too_large`, with `--exclude` as the only exit, which is not completion).
+ * Discovery now cuts such a target into path slices ordered `(phase, path)`: every import slice, then bounded deletion
+ * slices, pinned at one target. Each slice's checkpoint records `{ phase, after, head, target }` in the same transaction
+ * instead of advancing `last_commit`, which moves only when the last slice settles. The bound is lowered through the
+ * test seam. Synthetic content only.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync, unlinkSync, renameSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { drainManagedSync } from '../src/core/persistence/sync-drain.ts';
+import { _setCursorBoundForTest } from '../src/core/persistence/sync-discovery.ts';
+import { sliceEntries, SYNC_SLICE_OP } from '../src/core/persistence/sync-slices.ts';
+import type { SyncEntry } from '../src/core/persistence/sync-discovery.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-slices-'));
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+afterEach(() => _setCursorBoundForTest());
+
+function repo() {
+ const root = join(home, `r-${randomUUID().slice(0, 8)}`);
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ const write = (name: string, body = `A synthetic observation about ${name}.`) => writeFileSync(join(root, 'notes', `${name}.md`), `---\ntitle: ${name}\n---\n${body}\n`);
+ const remove = (name: string) => unlinkSync(join(root, 'notes', `${name}.md`));
+ const move = (from: string, to: string) => renameSync(join(root, 'notes', `${from}.md`), join(root, 'notes', `${to}.md`));
+ const commit = (message: string) => { git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message, '--allow-empty'); return git('rev-parse', 'HEAD'); };
+ git('init', '-q');
+ return { root, git, write, remove, move, commit };
+}
+
+const entry = (path: string, action: SyncEntry['action']): SyncEntry => ({ path, sourcePath: path, action, working: false });
+const bound = (n: number) => (entries: readonly SyncEntry[]) => entries.length <= n;
+
+describe('sliceEntries (phase, then code-unit path order)', () => {
+ const all = [entry('b', 'import'), entry('a', 'import'), entry('d', 'delete'), entry('c', 'import'), entry('e', 'delete'), entry('f', 'delete')];
+ test('imports first, then deletions, each cut to the bound; after names the last path committed', () => {
+ const first = sliceEntries(all, null, bound(2));
+ expect(first).toMatchObject({ phase: 'import', after: 'b', done: false });
+ expect(first.entries.map(e => e.path)).toEqual(['a', 'b']);
+ const second = sliceEntries(all, first, bound(2));
+ expect(second).toMatchObject({ phase: 'import', after: 'c', done: false });
+ const third = sliceEntries(all, second, bound(2));
+ expect(third).toMatchObject({ phase: 'delete', after: 'e', done: false });
+ expect(third.entries.map(e => e.path)).toEqual(['d', 'e']);
+ const last = sliceEntries(all, third, bound(2));
+ expect(last).toMatchObject({ phase: 'delete', after: 'f', done: true });
+ });
+ test('a target with no deletions is done with its last import slice; a cursor past every import moves to deletions', () => {
+ expect(sliceEntries([entry('a', 'import'), entry('b', 'import')], { phase: 'import', after: 'a' }, bound(5))).toMatchObject({ phase: 'import', after: 'b', done: true });
+ expect(sliceEntries(all, { phase: 'import', after: 'c' }, bound(5))).toMatchObject({ phase: 'delete', after: 'f', done: true });
+ });
+ test('an entry that alone exceeds the bound is still returned, so the caller can refuse it by name', () => {
+ expect(sliceEntries([entry('big', 'import')], null, () => false).entries.map(e => e.path)).toEqual(['big']);
+ });
+});
+
+describe('path-sliced managed sync on a real brain', () => {
+ const engines: BrainEngine[] = [];
+ let closePostgres: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }
+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+ }, 120_000);
+ afterAll(async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } await closePostgres?.(); });
+
+ async function managedSource(engine: BrainEngine, seed: (r: ReturnType<typeof repo>) => void = r => { r.write('base'); r.commit('base'); }) {
+ const r = repo();
+ const id = `slc-${randomUUID().replace(/-/g, '').slice(0, 16)}`;
+ seed(r);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, r.root]);
+ await claimWorktree(engine, id, r.root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };
+ const pages = async () => (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [id])).map(p => p.slug);
+ const lastCommit = async () => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0]!.last_commit;
+ const sliceRecords = async () => (await engine.executeRaw<{ n: string }>("SELECT COUNT(*)::text AS n FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2", [SYNC_SLICE_OP, `${id}:%`]))[0]!.n;
+ return { r, id, opts, pages, lastCommit, sliceRecords };
+ }
+ const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };
+
+ test('a first sync above the bound completes over several import slices; last_commit lands only at the end and the slice record is gone', () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const names = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
+ let head = '';
+ const { opts, pages, lastCommit, sliceRecords } = await managedSource(engine, r => { for (const n of names) r.write(n); head = r.commit('seven at once'); });
+ _setCursorBoundForTest({ entries: 3, bytes: 1024 ** 2 });
+ const first = await drainManagedSync(engine, opts, false);
+ expect(first.drain?.outcome).toBe('synced');
+ expect(first.staged).toMatchObject({ target: head, head, slice: { phase: 'import', after: 'notes/c.md' } });
+ expect(await lastCommit()).toBeNull();
+ expect(await pages()).toEqual(['notes/a', 'notes/b', 'notes/c']);
+ expect(await sliceRecords()).toBe('1');
+ const result = await performSync(engine, { ...opts, drain: true });
+ expect(result.drain?.outcome).toBe('synced');
+ expect(result.staged).toBeUndefined();
+ expect(await lastCommit()).toBe(head);
+ expect(await pages()).toEqual(names.map(n => `notes/${n}`));
+ expect(await sliceRecords()).toBe('0');
+ }
+ }), 300_000);
+
+ test('deletions above the bound run in bounded slices after every import slice; a drain finishes the target', () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const { r, opts, pages, lastCommit } = await managedSource(engine, r => { for (const n of ['a', 'b', 'c', 'd', 'e', 'f', 'g']) r.write(n); r.commit('seven'); });
+ expect((await drainManagedSync(engine, opts, false)).drain).toMatchObject({ outcome: 'synced' });
+ const synced = await lastCommit();
+ for (const n of ['b', 'c', 'd', 'e', 'f']) r.remove(n);
+ r.write('a', 'Edited after the deletions.'); r.write('h');
+ const head = r.commit('delete five, edit one, add one');
+ _setCursorBoundForTest({ entries: 2, bytes: 1024 ** 2 });
+ const full = { ...opts, full: true };
+ const phases: string[] = [];
+ for (let slice = 0; slice < 10; slice++) {
+ const step = await drainManagedSync(engine, full, false);
+ expect(step.drain?.outcome).toBe('synced');
+ if (!step.staged) break;
+ phases.push(`${step.staged.slice!.phase}:${step.staged.slice!.after}`);
+ expect(await lastCommit()).toBe(synced);
+ }
+ // Imports (a, g, h: the tree walk re-screens every path, two per slice) precede the deletions (five, two per slice).
+ expect(phases).toEqual(['import:notes/g.md', 'import:notes/h.md', 'delete:notes/c.md', 'delete:notes/e.md']);
+ expect(await lastCommit()).toBe(head);
+ expect(await pages()).toEqual(['notes/a', 'notes/g', 'notes/h']);
+ expect((await engine.getPage('notes/a', { sourceId: opts.sourceId }))?.compiled_truth).toContain('Edited after the deletions.');
+ }
+ }), 300_000);
+
+ test('a run stopped inside a slice resumes at the stored slice cursor with the pinned target; no page is skipped or duplicated', () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const names = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
+ let head = '';
+ const { r, opts, pages, lastCommit, sliceRecords, id } = await managedSource(engine, r => { for (const n of names) r.write(n); head = r.commit('seven at once'); });
+ _setCursorBoundForTest({ entries: 3, bytes: 1024 ** 2 });
+ // First slice committed whole; the second slice is aborted after its first page.
+ expect((await drainManagedSync(engine, opts, false)).staged?.slice).toEqual({ phase: 'import', after: 'notes/c.md' });
+ const abort = new AbortController();
+ let committed = 0;
+ const stopped = await drainManagedSync(engine, { ...opts, signal: abort.signal, onProgress: event => { if (event.phase === 'managed_sync.page_committed' && ++committed === 1) abort.abort(); } }, false);
+ expect(stopped.drain?.outcome).not.toBe('synced');
+ expect(await lastCommit()).toBeNull();
+ expect(await sliceRecords()).toBe('1');
+ // HEAD moves on while the sliced target is pending: the resume stays pinned at the sliced target.
+ r.write('z'); const later = r.commit('after the pin');
+ const resumed = await performSync(engine, { ...opts, drain: true });
+ expect(resumed.drain?.outcome).toBe('synced');
+ expect(await pages()).toEqual([...names, 'z'].map(n => `notes/${n}`));
+ expect(await lastCommit()).toBe(later);
+ expect(await sliceRecords()).toBe('0');
+ const rows = await engine.executeRaw<{ slug: string; n: string }>('SELECT slug,COUNT(*)::text AS n FROM pages WHERE source_id=$1 GROUP BY slug HAVING COUNT(*)>1', [id]);
+ expect(rows).toEqual([]);
+ expect(head).not.toBe(later);
+ }
+ }), 300_000);
+
+ test('a byte bound slices by path bytes; one commit above the entry bound is pinned and sliced instead of refused; a rename inside it keeps the page', () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const { r, opts, pages, lastCommit, id } = await managedSource(engine, r => { r.write('base'); r.write('keep'); r.commit('base'); });
+ expect((await drainManagedSync(engine, opts, false)).drain).toMatchObject({ outcome: 'synced' });
+ const before = await lastCommit();
+ const long = Array.from({ length: 6 }, (_, i) => `a-rather-long-synthetic-name-${i}-${'x'.repeat(40)}`);
+ for (const n of long) r.write(n);
+ r.move('keep', 'kept');
+ const big = r.commit('seven paths in one commit, one a rename');
+ r.write('tail'); const head = r.commit('one more');
+ // Ample entries, but the serialized manifest of three long paths already exceeds the byte bound (one resolved entry is ~150 bytes).
+ const one = Buffer.byteLength(JSON.stringify([{ path: `notes/${long[0]}.md`, sourcePath: `notes/${long[0]}.md`, action: 'import', working: false, pageId: null, revision: null }]));
+ _setCursorBoundForTest({ entries: 100, bytes: Math.round(one * 2.5) });
+ const first = await drainManagedSync(engine, opts, false);
+ expect(first.drain?.outcome).toBe('synced');
+ expect(first.staged).toMatchObject({ target: big, head, slice: { phase: 'import' } });
+ // Path bytes cut the import phase short of its last entry: the slice ends on one of the long paths, not the whole set.
+ expect(long.slice(0, 4).map(n => `notes/${n}.md`)).toContain(first.staged!.slice!.after ?? '');
+ expect(await lastCommit()).toBe(before);
+ const result = await performSync(engine, { ...opts, drain: true });
+ expect(result.drain?.outcome).toBe('synced');
+ expect(result.staged).toBeUndefined();
+ expect(await lastCommit()).toBe(head);
+ expect(await pages()).toEqual([...long.map(n => `notes/${n}`), 'notes/base', 'notes/kept', 'notes/tail'].sort());
+ const kept = await engine.executeRaw<{ slug: string; deleted_at: string | null }>("SELECT slug,deleted_at FROM pages WHERE source_id=$1 AND slug IN ('notes/keep','notes/kept')", [id]);
+ expect(kept).toEqual([{ slug: 'notes/kept', deleted_at: null }]);
+ }
+ }), 300_000);
+
+ test('a single entry above the byte bound refuses by name with nothing written', () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const { r, opts, pages, lastCommit } = await managedSource(engine, r => { r.write('base'); r.commit('base'); });
+ expect((await drainManagedSync(engine, opts, false)).drain).toMatchObject({ outcome: 'synced' });
+ const before = await lastCommit();
+ r.write(`a${'y'.repeat(200)}`); r.write('small'); r.commit('one enormous path');
+ _setCursorBoundForTest({ entries: 100, bytes: 200 });
+ const refusal = await drainManagedSync(engine, opts, false).then(() => null, (error: { code?: string; message: string }) => error);
+ expect(refusal).toMatchObject({ code: 'request_too_large' });
+ expect(refusal!.message).toContain('One sync entry exceeds the bounded cursor size.');
+ expect(await lastCommit()).toBe(before);
+ expect(await pages()).toEqual(['notes/base']);
+ }
+ }), 300_000);
+});
diff --git a/test/sync-full-untracked-import-5459.test.ts b/test/sync-full-untracked-import-5459.test.ts
new file mode 100644
index 0000000000..51f5bad415
--- /dev/null
+++ b/test/sync-full-untracked-import-5459.test.ts
@@ -0,0 +1,155 @@
+/**
+ * #5459-adjacent (fix wave 15 P4.5): a `--full` tree walk used to schedule a Git deletion for every live page whose
+ * origin is absent from `ls-tree <target>`, including pages imported from untracked working-tree files
+ * (`--working-tree` / `sync.include_working_tree`). The walk now reads the page's durable import provenance
+ * (`sync-import-provenance` in op_checkpoints, written by the import itself and untouched by receipt compaction,
+ * which nulls `persistence_requests.intent`): a page imported from the working tree whose file is still present is
+ * kept and counted as `working_tree_kept`; unknown provenance with the file present holds too; a tracked Git
+ * deletion is still applied even when a copy of the file lingers untracked. Synthetic content only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { drainManagedSync } from '../src/core/persistence/sync-drain.ts';
+import { compactWriteReceipts } from '../src/core/persistence/journal.ts';
+import { readSyncImportProvenance, SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { maintenanceAttribution } from '../src/core/persistence/attribution.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-untracked-'));
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+function repo() {
+ const root = join(home, `r-${randomUUID().slice(0, 8)}`);
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ const write = (name: string, body = `A synthetic observation about ${name}.`) => writeFileSync(join(root, 'notes', `${name}.md`), `---\ntitle: ${name}\n---\n${body}\n`);
+ const remove = (name: string) => unlinkSync(join(root, 'notes', `${name}.md`));
+ const commitStaged = (message: string) => { git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message, '--allow-empty'); return git('rev-parse', 'HEAD'); };
+ const commit = (message: string) => { git('add', '-A'); return commitStaged(message); };
+ git('init', '-q');
+ return { root, git, write, remove, commit, commitStaged };
+}
+
+describe('--full tree walk keeps pages imported from untracked working-tree files', () => {
+ const engines: BrainEngine[] = [];
+ let closePostgres: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }
+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+ }, 120_000);
+ afterAll(async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } await closePostgres?.(); });
+
+ async function managedSource(engine: BrainEngine) {
+ const r = repo();
+ const id = `wt-${randomUUID().replace(/-/g, '').slice(0, 16)}`;
+ r.write('base'); r.commit('base');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, r.root]);
+ await claimWorktree(engine, id, r.root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };
+ expect((await drainManagedSync(engine, opts, false)).drain).toMatchObject({ outcome: 'synced' });
+ const live = async () => (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [id])).map(p => p.slug);
+ const page = async (slug: string) => (await engine.executeRaw<{ id: number; deleted_at: string | null; knowledge_revision: string }>('SELECT id,deleted_at,knowledge_revision FROM pages WHERE source_id=$1 AND slug=$2', [id, slug]))[0] ?? null;
+ const incarnation = (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]))[0]!.incarnation;
+ const full = async () => { const result = await drainManagedSync(engine, { ...opts, full: true }, false); expect(result.drain).toMatchObject({ outcome: 'synced' }); return result; };
+ return { r, id, opts, live, page, incarnation, full };
+ }
+
+ test('working-tree import survives a --full walk (fresh, compacted and legacy provenance; after a non-sync write), and is counted', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) {
+ const { r, id, opts, live, page, incarnation, full } = await managedSource(engine);
+ r.write('scratch', 'An untracked working-tree note.');
+ expect((await drainManagedSync(engine, { ...opts, workingTree: true }, false)).drain).toMatchObject({ outcome: 'synced' });
+ expect(await live()).toEqual(['notes/base', 'notes/scratch']);
+ const scratch = (await page('notes/scratch'))!;
+
+ // 1. Fresh provenance: the walk keeps the page and counts it.
+ let result = await full();
+ expect(await live()).toEqual(['notes/base', 'notes/scratch']);
+ expect(result.working_tree_kept).toBe(1);
+ expect(await readSyncImportProvenance(engine, id, incarnation, scratch.id)).toMatchObject({ origin: 'notes/scratch.md', working: true });
+
+ // 2. Receipt compaction nulls every request intent (journal.ts); the proof must not live there.
+ await compactWriteReceipts(engine, 0);
+ expect((await engine.executeRaw<{ n: number }>("SELECT COUNT(*)::int AS n FROM persistence_requests WHERE intent IS NOT NULL AND intent->>'kind'='managed_sync_import'"))[0].n).toBe(0);
+ result = await full();
+ expect(await live()).toEqual(['notes/base', 'notes/scratch']);
+ expect(result.working_tree_kept).toBe(1);
+
+ // 3. An intervening non-sync write (a coordinated maintenance edit) moves the page's revision; the page still stays.
+ await engine.transaction(async tx => withCoordinatedWrite(tx, [id], async () => {
+ await tx.executeRaw("UPDATE pages SET compiled_truth=compiled_truth||E'\\nEdited by maintenance.', knowledge_revision=gen_random_uuid() WHERE source_id=$1 AND slug='notes/scratch'", [id]);
+ }, await maintenanceAttribution(tx)));
+ expect((await page('notes/scratch'))!.knowledge_revision).not.toBe(scratch.knowledge_revision);
+ result = await full();
+ expect(await live()).toEqual(['notes/base', 'notes/scratch']);
+ expect(result.working_tree_kept).toBe(1);
+
+ // 4. Legacy provenance (recorded before the `working` stamp existed): unknown provenance plus a present file holds.
+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0}',(completed_keys->0)-'working') WHERE op=$1 AND fingerprint=$2",
+ [SYNC_IMPORT_PROVENANCE_OP, `${id}:${incarnation}:${scratch.id}`]);
+ expect(await readSyncImportProvenance(engine, id, incarnation, scratch.id)).not.toHaveProperty('working');
+ result = await full();
+ expect(await live()).toEqual(['notes/base', 'notes/scratch']);
+ expect(result.working_tree_kept).toBe(1);
+
+ // 5. The untracked file is gone: nothing backs the page any more, so the walk deletes it, and the counter is absent.
+ r.remove('scratch');
+ result = await full();
+ expect(await live()).toEqual(['notes/base']);
+ expect((await page('notes/scratch'))!.deleted_at).not.toBeNull();
+ expect(result.working_tree_kept).toBeUndefined();
+ }
+ }), 300_000);
+
+ test('an explicit tracked Git deletion is applied even when a copy of the file lingers untracked (Git is the truth for tracked paths)', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) {
+ const { r, id, live, page, incarnation, full } = await managedSource(engine);
+ r.write('tracked'); r.commit('add tracked');
+ await full();
+ expect(await live()).toEqual(['notes/base', 'notes/tracked']);
+ const tracked = (await page('notes/tracked'))!;
+ r.git('rm', '-q', '--cached', 'notes/tracked.md'); r.commitStaged('stop tracking');
+ // The bytes are still on disk, untracked.
+ expect(r.git('status', '--porcelain')).toContain('?? notes/tracked.md');
+ const result = await full();
+ expect(await live()).toEqual(['notes/base']);
+ expect((await page('notes/tracked'))!.deleted_at).not.toBeNull();
+ expect(result.working_tree_kept).toBeUndefined();
+ expect(await readSyncImportProvenance(engine, id, incarnation, tracked.id)).toMatchObject({ working: false });
+ }
+ }), 300_000);
+
+ test('the same slug in another source is judged by its own provenance; the kept page never shields or dooms it', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) {
+ const a = await managedSource(engine);
+ const b = await managedSource(engine);
+ a.r.write('shared', 'Untracked in source A.');
+ expect((await drainManagedSync(engine, { ...a.opts, workingTree: true }, false)).drain).toMatchObject({ outcome: 'synced' });
+ b.r.write('shared', 'Tracked in source B.'); b.r.commit('add shared');
+ await b.full();
+ expect(await a.live()).toEqual(['notes/base', 'notes/shared']);
+ expect(await b.live()).toEqual(['notes/base', 'notes/shared']);
+ // B removes its tracked copy: B's page goes, A's untracked-backed page stays, each walk counting only its own source.
+ b.r.remove('shared'); b.r.commit('remove shared');
+ const resultB = await b.full();
+ expect(await b.live()).toEqual(['notes/base']);
+ expect(resultB.working_tree_kept).toBeUndefined();
+ const resultA = await a.full();
+ expect(await a.live()).toEqual(['notes/base', 'notes/shared']);
+ expect(resultA.working_tree_kept).toBe(1);
+ }
+ }), 300_000);
+});
diff --git a/test/sync-staged-catchup.test.ts b/test/sync-staged-catchup.test.ts
index 0e874a4a92..b5b4bcfe45 100644
--- a/test/sync-staged-catchup.test.ts
+++ b/test/sync-staged-catchup.test.ts
@@ -2,8 +2,8 @@
* #6349 (P2.14): a managed source whose delta since its last synced commit exceeds the cursor bound used to refuse every
* sync forever. Discovery now stages it: the furthest first-parent commit whose delta fits, found by a forward gallop that
* verifies every candidate (a net delta is not monotone along history, so binary search has no valid predicate); a drain
- * then takes stage after stage to HEAD. One commit above the bound still refuses, naming that commit. The bound is
- * lowered through the test seam. Synthetic content only.
+ * then takes stage after stage to HEAD. One commit above the bound is pinned and cut into path slices (#6349 P4.4,
+ * `test/sync-full-cursor-slices-6349.test.ts`). The bound is lowered through the test seam. Synthetic content only.
*/
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
@@ -129,21 +129,21 @@ describe('staged managed catch-up on a real brain', () => {
}
}), 300_000);
- test('the byte bound stages too, and one commit above the bound refuses naming it', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ test('the byte bound stages too, and one commit above the bound is pinned and path-sliced (#6349 P4.4) instead of refused', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
for (const engine of engines) {
- const { r, opts, lastCommit } = await managedSource(engine);
+ const { r, opts, lastCommit, pages } = await managedSource(engine);
const before = await lastCommit();
for (const n of ['p', 'q', 'r', 's']) r.write(n);
const big = r.commit('add 4 in one commit');
_setCursorBoundForTest({ entries: 3, bytes: 1024 ** 2 });
- const refusal = await drainManagedSync(engine, opts, false).then(() => null, (error: { code?: string; message: string; suggestion?: string }) => error);
- expect(refusal).toMatchObject({ code: 'request_too_large' });
- expect(refusal!.message).toContain('One commit exceeds the bounded cursor size.');
- expect(refusal!.suggestion).toContain(`Commit ${big.slice(0, 12)} alone changes 4 syncable entries`);
+ const sliced = await drainManagedSync(engine, opts, false);
+ expect(sliced.staged).toMatchObject({ target: big, head: big, slice: { phase: 'import', after: 'notes/r.md' } });
expect(await lastCommit()).toBe(before);
+ expect((await drainManagedSync(engine, opts, false)).staged).toBeUndefined();
+ expect(await lastCommit()).toBe(big);
+ expect(await pages()).toEqual(['notes/base', 'notes/p', 'notes/q', 'notes/r', 'notes/s']);
// The byte bound: ample entries, but only one entry's worth of bytes per stage.
_setCursorBoundForTest({ entries: 100, bytes: 120 });
- r.git('reset', '-q', '--hard', before!);
r.write('x'); const c1 = r.commit('x'); r.write('y'); r.commit('y');
const staged = await drainManagedSync(engine, opts, false);
expect(staged.staged?.target).toBe(c1);