Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6696 C1: delegated sync keeps the in-process processing-option contract

garrytand3e6f7815485
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 72ce737f2d..6088ca4229 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -12,7 +12,7 @@ src/commands/extract.ts 2637 ratchet grown v0.46.26.0 megawave: FS-walk stamp sn
src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes
src/commands/serve-http.ts 931 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts)
src/core/ai/gateway.ts 4523 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text
-src/commands/sync.ts 523 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts)
+src/commands/sync.ts 525 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the runtime cost-gate deferral; consumed in persistence/sync-run.ts freezeEntry)
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/scripts/serial-files.tsv b/scripts/serial-files.tsv
index d60c1bf25a..ec5b87bdb0 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -364,6 +364,7 @@ test/subagent-put-page-rejection.serial.test.ts global-state global-state: proce
test/sync-convergence.serial.test.ts global-state global-state: binds local servers/ports (two latency proxies) and spawns serve/sync/put processes against one shared brain; its oracle tests read the single chaos scenario that beforeAll ran, across it() boundaries
test/sync-cost-gate.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
test/sync-default-write-guard.serial.test.ts global-state global-state: spyOn console.error, console.log, process.exit
+test/sync-delegated-options-6696.serial.test.ts global-state global-state: process-wide test seams __resetDelegatedSyncForTests and the embedding transport; binds local servers/ports; patches process stdout/stderr/console
test/sync-delete-trailing-hyphen.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
test/sync-failure-ledger.serial.test.ts R1 R1: mutates process.env (HOME, GBRAIN_SYNC_AUTOSKIP_AFTER)
test/sync-index-matches-tree.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.ts
index c78caf37b1..250dd8945b 100644
--- a/src/commands/sync-delegate.ts
+++ b/src/commands/sync-delegate.ts
@@ -62,6 +62,7 @@ import {
} from '../core/context/resolve-ipc.ts';
import {
DELEGATED_SYNC_LANES_MAX,
+ DELEGATED_SYNC_PROCESSING_KEYS,
type DelegatedSyncOptions,
type SyncStartRegistration,
type SyncStatusResponse,
@@ -145,8 +146,8 @@ export function parseDelegatedSyncArgs(args: string[]): ParsedDelegatedArgs {
// --all, --watch, --exclude, --workers, …) and anything future.
return { ok: false, refused: tok };
}
- const explicitProcessing = (['noEmbed', 'noExtract', 'noSchemaPack'] as const).filter(key => options[key] === true);
- if (explicitProcessing.length) options.explicitProcessing = explicitProcessing;
+ // #6696: always sent, so a flagless run adopts an unfinished cursor's options on the serve as it does in-process.
+ options.explicitProcessing = (['noEmbed', 'noExtract', 'noSchemaPack'] as const).filter(key => options[key] === true);
return { ok: true, options: options as Omit<DelegatedSyncOptions, 'timeoutSeconds'>, explicitSource };
}
@@ -580,7 +581,10 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:
sourceId, timeoutSeconds,
...pick(opts, ['dryRun', 'full', 'noPull', 'noEmbed', 'noExtract', 'noSchemaPack', 'skipFailed', 'retryFailed', 'includeGitignored', 'noBulk'] as const),
...(opts.lanes !== undefined ? { lanes: opts.lanes } : {}),
- ...(opts.explicitProcessing?.length ? { explicitProcessing: [...opts.explicitProcessing] } : {}),
+ // #6696: an empty list crosses the wire (a flagless run adopts the cursor's options); a caller that set none is strict, as in-process.
+ explicitProcessing: [...opts.explicitProcessing ?? DELEGATED_SYNC_PROCESSING_KEYS],
+ // Sent only when set, so a serve that predates the field keeps accepting every run without a deferral.
+ ...(opts.embedDeferred ? { embedDeferred: true } : {}),
};
const clientToken = randomUUID();
const { probeLiveFullConsumer, consumerIdentity } = await import('../core/persistence/consumer-heartbeat.ts');
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 931fd56e28..f28e9bb29f 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -176,6 +176,8 @@ export interface SyncOpts {
noSchemaPack?: boolean;
/** Processing options this caller set; an unfinished managed cursor supplies the rest (unset = all explicit). */
explicitProcessing?: Array<'noEmbed' | 'noExtract' | 'noSchemaPack'>;
+ /** #6696: a runtime paid-work constraint (the cost gate deferred this run's embedding); never a processing option, never lifted by cursor adoption. */
+ embedDeferred?: boolean;
/**
* v0.18.0 Step 5 — sync a specific named source. When set, sync reads
* local_path + last_commit from the sources table (not the global
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index 1da04b3652..47e9373d09 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -492,6 +492,8 @@ async function runSyncAll(
repoPath: msysToNativePath(src.local_path!), // #2955: heal MSYS /c/... before joins
dryRun, full, noPull,
noEmbed: effectiveNoEmbed,
+ // #6696: a planned or cost-gate deferral (not the user's --no-embed) survives cursor adoption.
+ embedDeferred: effectiveNoEmbed && !noEmbed,
noExtract,
skipFailed, retryFailed, noSchemaPack, explicitProcessing,
includeGitignored,
@@ -817,6 +819,8 @@ async function runSingleSourceSync(
if (gate.stop) return;
if (gate.autoDeferEmbeds) {
opts.noEmbed = true;
+ // #6696: a runtime constraint, not an explicit flag: adopting an unfinished cursor's options must not lift it.
+ opts.embedDeferred = true;
singleSourceAutoDefer = true;
}
}
diff --git a/src/core/context/sync-ipc.ts b/src/core/context/sync-ipc.ts
index d16d8e41b3..39c386e9ff 100644
--- a/src/core/context/sync-ipc.ts
+++ b/src/core/context/sync-ipc.ts
@@ -54,6 +54,7 @@ export const DELEGATED_SYNC_OPTION_FIELDS = {
noBulk: 'boolean',
lanes: 'number',
explicitProcessing: 'string[]',
+ embedDeferred: 'boolean',
timeoutSeconds: 'number',
} as const;
@@ -84,8 +85,10 @@ export interface DelegatedSyncOptions {
noBulk?: boolean;
/** #6317: `--lanes N` / `--no-lanes` (1..DELEGATED_SYNC_LANES_MAX) for the managed catch-up. */
lanes?: number;
- /** #6317: the processing options the caller set itself; the managed cursor supplies the rest. */
+ /** #6317: the processing options the caller set itself; the managed cursor supplies the rest. #6696: a missing list (an older CLI) means none. */
explicitProcessing?: Array<typeof DELEGATED_SYNC_PROCESSING_KEYS[number]>;
+ /** #6696: the client's cost gate deferred this run's embedding; cursor adoption never lifts it. Sent only when true. */
+ embedDeferred?: boolean;
/**
* REQUIRED — the client always sends its resolved hard deadline so a job
* whose client died stays bounded. `0` is the single unbounded encoding
diff --git a/src/core/persistence/sync-cursor-key.ts b/src/core/persistence/sync-cursor-key.ts
new file mode 100644
index 0000000000..be51d59f5a
--- /dev/null
+++ b/src/core/persistence/sync-cursor-key.ts
@@ -0,0 +1,42 @@
+/**
+ * The durable cursor key of a managed sync run, and the one boundary that picks it (#6696 C1).
+ *
+ * The key digests the source incarnation, the writer principal and authority, a company approval and the run's
+ * cursor-selecting options (`syncCursorOptions`). `sync --all` passes a source's configured strategy while a
+ * single-source CLI run, the cycle, a serve-delegated run and a sync job pass none, so one source used to get two keys:
+ * two unfinished cursors that could not resume each other. `selectManagedCursor` runs inside `runManagedSync` (every
+ * managed caller crosses it) and `managedSyncCursorKey`: a run without `--strategy` selects its cursor with the
+ * configured strategy, for fresh cursors only. When an unfinished cursor is held under the key the run's raw options
+ * select (written before this rule, or before the strategy was configured), the run resumes it under that key, so the
+ * requests it already admitted (their `intent.cursorKey`) keep matching their cursor.
+ */
+import type { SyncOpts } from '../../commands/sync.ts';
+import type { BrainEngine } from '../engine.ts';
+import type { currentCompanyBrainSync } from '../company-brain/profile.ts';
+import { digest } from './digest.ts';
+import type { SyncAuthority } from './sync-authority.ts';
+import type { ManagedSyncContext } from './sync-discovery.ts';
+import type { SyncCursorOptions } from './sync-prepare.ts';
+import { syncCursorOptions } from './sync-slices.ts';
+
+type CompanySync = ReturnType<typeof currentCompanyBrainSync>;
+
+export function managedCursorKey(incarnation: string, authority: SyncAuthority, company: CompanySync, syncOptions: SyncCursorOptions): string {
+ return digest({ source: incarnation, principal: authority.writer.principal, authority, ...(company ? { company: { receiptId: company.receiptId, planDigest: company.plan.plan_digest } } : {}),
+ options: syncOptions });
+}
+
+/** The options, cursor-selecting options and key a managed run uses; `opts.strategy` is the configured one when the key was normalized. */
+export async function selectManagedCursor(engine: Pick<BrainEngine, 'executeRaw'>, input: { opts: SyncOpts; context: Pick<ManagedSyncContext, 'incarnation' | 'source'>;
+ authority: SyncAuthority; company: CompanySync }): Promise<{ opts: SyncOpts; syncOptions: SyncCursorOptions; key: string }> {
+ const { opts, context, authority, company } = input;
+ const raw = syncCursorOptions(opts);
+ const rawKey = managedCursorKey(context.incarnation, authority, company, raw);
+ const configured = context.source.config?.strategy;
+ if (company || opts.strategy || typeof configured !== 'string' || !configured) return { opts, syncOptions: raw, key: rawKey };
+ const live = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 AND COALESCE(completed_keys->0->>'done','false')<>'true'", [rawKey]);
+ if (live.length) return { opts, syncOptions: raw, key: rawKey };
+ const normalized = { ...opts, strategy: configured as SyncOpts['strategy'] };
+ const syncOptions = syncCursorOptions(normalized);
+ return { opts: normalized, syncOptions, key: managedCursorKey(context.incarnation, authority, company, syncOptions) };
+}
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 38dba7b70b..8ac38c7581 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -76,6 +76,8 @@ export interface SyncIntent extends Record<string, unknown> {
slice?: SyncSliceState;
/** #5988: the run's discovery time; committing this entry clears the path's hold unless a newer run wrote it. */
holdObservedAt?: string;
+ /** #6696: the run that froze this entry deferred embedding at runtime (cost gate); the cursor's `noEmbed` may still be false. */
+ embedDeferred?: boolean;
/** #5988 checkpoint only: held paths that left the source (excluded); their holds clear when the run checkpoints. */
releasedHolds?: string[];
/** #5988: the pinned Git blob of the imported content, recorded as import provenance. */
@@ -568,7 +570,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
// #6529: an image entry (frozen as base64 bytes) takes the coordinated image importer; its text embedding waits for embed --stale.
if (isImageFilePath(p.sourcePath)) {
return prepareManagedSyncImage(engine, row, { content: p.content, sourcePath: p.sourcePath, path: p.path, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly },
- { root, snapshot, ...(moved && moved.slug !== row.slug ? { renamedFrom: { slug: moved.slug } } : {}), noEmbed: p.processingOptions?.noEmbed === true, companyApproval: !!p.companyApproval, validate, releaseHold, clock, screening: !!screening,
+ { root, snapshot, ...(moved && moved.slug !== row.slug ? { renamedFrom: { slug: moved.slug } } : {}), noEmbed: p.processingOptions?.noEmbed === true || p.embedDeferred === true, companyApproval: !!p.companyApproval, validate, releaseHold, clock, screening: !!screening,
refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause) });
}
if (isCodeFilePath(p.sourcePath)) return prepareManagedSyncCode(engine, row, { content: p.content, sourcePath: p.sourcePath, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly, companyApproval: !!p.companyApproval },
@@ -658,7 +660,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
contentUnchanged: ready.noop && !moved && !writeback,
...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),
validate: async tx => { await validate(tx); await ready.validate(tx); },
- deferEmbedding: p.processingOptions?.noEmbed,
+ deferEmbedding: p.processingOptions?.noEmbed || p.embedDeferred === true,
...(writeback ? { file: { root, path: join(root, p.path), content: canonicalFile, expectedBeforeHash: p.rawHash } } : {}),
...(mirrorReadOnly ? { databaseOnlyReason: 'mirror_read_only' as const } : {}),
apply: async (tx, preimage) => {
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 5db166780a..530e460dc0 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -13,7 +13,7 @@ import { preparationConfigView } from './config-snapshot.ts';
import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';
import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer } from './service.ts';
import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';
-import { syncCursorOptions } from './sync-slices.ts';
+import { selectManagedCursor } from './sync-cursor-key.ts';
import { isImageFilePath, isMultimodalEnabled } 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';
@@ -329,7 +329,7 @@ function remember(snapshot: PageSnapshot | null | undefined, pending: Pending):
return pending;
}
async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assertActive: () => void,
- run: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string; signal?: AbortSignal }): Promise<Pending | Held> {
+ run: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string; signal?: AbortSignal; embedDeferred?: boolean }): Promise<Pending | Held> {
assertActive();
const entry = cursor.entries[cursor.index];
const retry = { sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? run.syncOptions, repoPath: run.repoPath };
@@ -447,7 +447,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly,
...(entry?.unownedDeletion ? { unownedDeletion: true } : {}),
...(entry?.renameFrom ? { renameFrom: entry.renameFrom } : {}),
- ...(run.observedAt ? { holdObservedAt: run.observedAt } : {}), ...(blob ? { blobOid: blob.oid } : {}),
+ ...(run.observedAt ? { holdObservedAt: run.observedAt } : {}), ...(blob ? { blobOid: blob.oid } : {}), ...(entry && run.embedDeferred ? { embedDeferred: true } : {}),
...(!entry && cursor.releasedHolds?.length ? { releasedHolds: cursor.releasedHolds } : {}),
...(!entry && cursor.convertedFromFailed?.length ? { supersededRequests: cursor.convertedFromFailed } : {}),
...(!entry && cursor.settled ? { settled: cursor.settled } : {}),
@@ -1309,17 +1309,11 @@ interface HoldRunState { sourceId?: string; incarnation?: string; remote?: boole
* #5988: every result (resumed, no-change and blocked runs included) carries this run's holds and the source's outstanding total.
*/
-/** The cursor-selecting options of a managed run; part of its durable cursor key. */
-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 });
-}
/** The durable cursor key performManagedSync would use for these options, so --retry-failed can count only the failures it retries. */
export async function managedSyncCursorKey(engine: BrainEngine, opts: SyncOpts): Promise<string> {
const context = await resolveManagedSyncContext(engine, opts);
const authority = await managedSyncAuthority(engine, context.sourceId, context.incarnation, opts.repoPath ?? context.root);
- return managedCursorKey(context.incarnation, authority, currentCompanyBrainSync(context.sourceId), cursorSyncOptions(opts));
+ return (await selectManagedCursor(engine, { opts, context, authority, company: currentCompanyBrainSync(context.sourceId) })).key;
}
/**
* `--retry-failed` on an unfinished cursor whose pending request failed (or whose run has a ledger row). #6340: a pending
@@ -1399,11 +1393,14 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
if (!opts.dryRun) await assertManagedSyncAllowed(engine, context.binding.worktree_id, context.sourceId);
const authority = await managedSyncAuthority(engine, context.sourceId, context.incarnation, opts.repoPath ?? context.root);
const company = currentCompanyBrainSync(context.sourceId);
+ // #6696: the one boundary that normalizes the strategy (fresh cursors only); discovery below reads the selected opts.
+ const selected = await selectManagedCursor(engine, { opts, context, authority, company });
+ opts = selected.opts;
const processingOptions = syncProcessingOptions(opts);
- const syncOptions = cursorSyncOptions(opts);
- const frozenRun: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string; signal?: AbortSignal } = { syncOptions, ...(opts.repoPath ? { repoPath: resolve(opts.repoPath) } : {}) };
+ const syncOptions = selected.syncOptions;
+ const frozenRun: Parameters<typeof freezeEntry>[4] = { syncOptions, ...(opts.repoPath ? { repoPath: resolve(opts.repoPath) } : {}), ...(opts.embedDeferred ? { embedDeferred: true } : {}) };
const runStartedAt = new Date().toISOString();
- const key = managedCursorKey(context.incarnation, authority, company, syncOptions);
+ const key = selected.key;
let cursor: Cursor | null = null;
let missingManifestCursor: CursorHeader | null = null;
if (!company) Object.assign(state, { sourceId: context.sourceId, incarnation: context.incarnation, remote: authority.writer.remote, cursor: () => cursor });
diff --git a/src/core/serve-sync-runner.ts b/src/core/serve-sync-runner.ts
index 7d421e9ef9..5c246ec870 100644
--- a/src/core/serve-sync-runner.ts
+++ b/src/core/serve-sync-runner.ts
@@ -340,7 +340,9 @@ async function startVerifiedDelegatedSync(
// The managed drain is the CLI's own path: the cursor owns processing options, so the CLI's effective
// flags ride through; the classic path keeps the always-deferred embed rule of the legacy lane.
...(managed
- ? { drain: true, noBulk: options.noBulk, lanes: options.lanes, noEmbed: options.noEmbed, explicitProcessing: options.explicitProcessing }
+ ? { drain: true, noBulk: options.noBulk, lanes: options.lanes, noEmbed: options.noEmbed, embedDeferred: options.embedDeferred,
+ // #6696: an older CLI drops an empty list; a delegated run without one set no processing flag.
+ explicitProcessing: options.explicitProcessing ?? [] }
: { noEmbed: true }),
signal: job.controller.signal,
onProgress: (p) => {
diff --git a/test/context/sync-ipc-validation.test.ts b/test/context/sync-ipc-validation.test.ts
index 341ea178cc..cc58c78282 100644
--- a/test/context/sync-ipc-validation.test.ts
+++ b/test/context/sync-ipc-validation.test.ts
@@ -129,6 +129,7 @@ describe('validateDelegatedSyncOptions', () => {
// that drift loud.
expect(Object.keys(DELEGATED_SYNC_OPTION_FIELDS).sort()).toEqual([
'dryRun',
+ 'embedDeferred',
'explicitProcessing',
'full',
'includeGitignored',
diff --git a/test/persistence-sync-cursor-strategy-6696.test.ts b/test/persistence-sync-cursor-strategy-6696.test.ts
new file mode 100644
index 0000000000..446307d9af
--- /dev/null
+++ b/test/persistence-sync-cursor-strategy-6696.test.ts
@@ -0,0 +1,88 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { SyncOpts } from '../src/commands/sync.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { managedSyncCursorKey, performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+// #6696 C1: `sync --all` passes the source's configured strategy while a single-source CLI run, autopilot's cycle and a
+// serve-delegated run pass none, so the same source got two cursor keys (two unfinished cursors that could not resume each
+// other). Strategy normalization picks the configured strategy for a run without --strategy, for fresh cursors only: an
+// unfinished cursor written under the old (un-normalized) key keeps resuming under that key, so the requests it already
+// admitted (their intent.cursorKey) still match their cursor.
+//
+// Regression guarded: the normalization done in one caller only (the keys keep diverging), or applied to a live cursor
+// (its queued requests are fenced out by the cursor they no longer match).
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-cursor-strategy-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+async function fixture(engine: BrainEngine, config: Record<string, unknown>) {
+ const id = `strategy-${randomUUID().slice(0, 12)}`, root = join(home, id);
+ mkdirSync(root); git(root, 'init', '-q');
+ for (const name of ['a', 'b', 'c', 'd']) writeFileSync(join(root, `${name}.md`), `---\ntitle: ${name}\n---\nA durable observation named ${name} at fund-a.\n`);
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');
+ await disposePersistenceConsumer(engine);
+ 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,$3::text::jsonb)', [id, root, JSON.stringify(config)]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return id;
+}
+const isolated = (fn: (engine: BrainEngine) => Promise<void>) => withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {
+ for (const engine of engines) await fn(engine);
+});
+const cursors = async (engine: BrainEngine, id: string) => engine.executeRaw<{ key: string; done: string | null; strategy: string | null }>(
+ "SELECT fingerprint AS key,completed_keys->0->>'done' AS done,completed_keys->0->'syncOptions'->>'strategy' AS strategy FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]);
+const refused = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state IN ('failed','conflict','cancelled')", [id]))[0]!.n;
+// What each caller passes: the single-source CLI, the cycle and a delegated run pass no strategy; `sync --all` passes the configured one.
+const single = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, explicitProcessing: [] } as SyncOpts);
+const all = (sourceId: string): SyncOpts => ({ ...single(sourceId), strategy: 'markdown' });
+
+test('a single-source run and a `sync --all` run of a source configured with a strategy select one cursor key', async () => isolated(async engine => {
+ const id = await fixture(engine, { strategy: 'markdown' });
+ expect(await managedSyncCursorKey(engine, single(id))).toBe(await managedSyncCursorKey(engine, all(id)));
+ expect(await performManagedSync(engine, single(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
+ expect((await performManagedSync(engine, all(id))).status).toBe('first_sync');
+ expect(await cursors(engine, id)).toEqual([expect.objectContaining({ strategy: 'markdown' })]);
+ expect(await refused(engine, id)).toBe(0);
+}), 120_000);
+
+test('an unfinished cursor under the old key (no strategy) finishes under that key; the next fresh run is normalized', async () => isolated(async engine => {
+ const id = await fixture(engine, {});
+ // A cursor written while the source had no strategy configured (the key an older binary computed for this source).
+ expect(await performManagedSync(engine, single(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
+ const [legacy] = await cursors(engine, id);
+ expect(legacy).toMatchObject({ strategy: null });
+ await engine.executeRaw(`UPDATE sources SET config='{"strategy":"markdown"}'::jsonb WHERE id=$1`, [id]);
+ expect(await managedSyncCursorKey(engine, single(id))).toBe(legacy!.key);
+ expect((await performManagedSync(engine, single(id))).status).toBe('first_sync');
+ expect(await cursors(engine, id)).toEqual([{ key: legacy!.key, done: 'true', strategy: null }]);
+ expect(await refused(engine, id)).toBe(0);
+ // Finished: a fresh run takes the normalized key, and `sync --all` agrees with it.
+ expect(await managedSyncCursorKey(engine, single(id))).not.toBe(legacy!.key);
+ expect(await managedSyncCursorKey(engine, single(id))).toBe(await managedSyncCursorKey(engine, all(id)));
+}), 120_000);
+
+test('an explicit --strategy that differs from the configured one keeps its own key', async () => isolated(async engine => {
+ const id = await fixture(engine, { strategy: 'markdown' });
+ expect(await managedSyncCursorKey(engine, { ...single(id), strategy: 'auto' })).not.toBe(await managedSyncCursorKey(engine, single(id)));
+}), 120_000);
diff --git a/test/sync-delegate-ladder.test.ts b/test/sync-delegate-ladder.test.ts
index 383e9a15ca..d9cd6263fe 100644
--- a/test/sync-delegate-ladder.test.ts
+++ b/test/sync-delegate-ladder.test.ts
@@ -66,8 +66,8 @@ function captureConsoleError(): { lines: string[]; restore: () => void } {
}
describe('parseDelegatedSyncArgs (default-deny)', () => {
- test('bare sync → empty options, no explicit source', () => {
- expect(parseDelegatedSyncArgs([])).toEqual({ ok: true, options: {}, explicitSource: null });
+ test('bare sync → no options but an empty explicit-processing list (#6696: a flagless run adopts the cursor), no explicit source', () => {
+ expect(parseDelegatedSyncArgs([])).toEqual({ ok: true, options: { explicitProcessing: [] }, explicitSource: null });
});
test('the full wire-forwardable set maps field-for-field', () => {
@@ -105,7 +105,7 @@ describe('parseDelegatedSyncArgs (default-deny)', () => {
test('#6317: the managed catch-up flags are admitted explicitly (--json is rendered by this client, never forwarded)', () => {
const r = parseDelegatedSyncArgs(['--source', 'notes', '--no-pull', '--json', '--no-bulk', '--lanes', '4', '--no-embed']);
expect(r).toEqual({ ok: true, explicitSource: 'notes', options: { noPull: true, noBulk: true, lanes: 4, noEmbed: true, explicitProcessing: ['noEmbed'] } });
- expect(parseDelegatedSyncArgs(['--no-lanes'])).toEqual({ ok: true, explicitSource: null, options: { lanes: 1 } });
+ expect(parseDelegatedSyncArgs(['--no-lanes'])).toEqual({ ok: true, explicitSource: null, options: { lanes: 1, explicitProcessing: [] } });
expect(parseDelegatedSyncArgs(['--lanes', '0'])).toEqual({ ok: false, refused: '--lanes (invalid value)' });
expect(parseDelegatedSyncArgs(['--lanes', '17'])).toEqual({ ok: false, refused: '--lanes (invalid value)' });
expect(parseDelegatedSyncArgs(['--lanes', 'four'])).toEqual({ ok: false, refused: '--lanes (invalid value)' });
diff --git a/test/sync-delegated-options-6696.serial.test.ts b/test/sync-delegated-options-6696.serial.test.ts
new file mode 100644
index 0000000000..00e426bf85
--- /dev/null
+++ b/test/sync-delegated-options-6696.serial.test.ts
@@ -0,0 +1,225 @@
+/**
+ * #6696 C1: delegated managed sync keeps the processing-option contract of the
+ * in-process path.
+ *
+ * What these tests protect:
+ * - a flagless delegated run adopts an unfinished cursor's stored options,
+ * exactly as the in-process CLI does: both client builders send
+ * `explicitProcessing: []` instead of dropping the empty list (which made
+ * every processing key explicit on the serve and refused the resume with
+ * `invalid_params`);
+ * - an older CLI that still omits the list is read the same way by a newer
+ * serve (a missing list on a delegated run means "no flags");
+ * - a runtime embedding deferral (the cost gate's auto-defer) is not a
+ * processing option: adopting a cursor that stores `noEmbed=false` never
+ * turns embedding back on for the run, in-process or delegated. A provider
+ * spy sees zero embedding calls and no embedding effect is queued.
+ *
+ * Regression each guards: dropping `explicitProcessing` on either builder, the
+ * serve passing `undefined` through, and the deferral riding only as `noEmbed`.
+ * Existing coverage (`serve-sync-handoff.serial.test.ts`) delegates only onto
+ * fresh sources, so a resume never crossed the wire there.
+ *
+ * Serial: the runner is a module singleton and the tests bind local sockets.
+ */
+
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomBytes, randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type net from 'node:net';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { startResolveIpcServer, type IpcHandlers } from '../src/core/context/resolve-ipc.ts';
+import { localIpcSocketPath } from '../src/core/context/ipc-path.ts';
+import { __resetDelegatedSyncForTests, getDelegatedSyncStatus, startDelegatedSync } from '../src/core/serve-sync-runner.ts';
+import { maybeDelegateManagedSyncToServe, parseDelegatedSyncArgs, type ManagedDelegationDeps } from '../src/commands/sync-delegate.ts';
+import { runSync, type SyncOpts } from '../src/commands/sync.ts';
+import type { ConsumerRow } from '../src/core/persistence/consumer-heartbeat.ts';
+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-delegated-options-'));
+const SECRET = randomBytes(32).toString('hex');
+const servers: net.Server[] = [];
+const sources: string[] = [];
+let engine: BrainEngine;
+const embedded: string[] = [];
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_BACKUP_CHECK: 'off', GBRAIN_SYNC_NO_EXTRACT_NUDGE: '1', OPENAI_API_KEY: 'sk-test-delegated-options' };
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+
+async function fixture(count: number): Promise<{ id: string; root: string }> {
+ const id = `options-${randomUUID().replace(/-/g, '').slice(0, 20)}`; sources.push(id);
+ const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (let i = 0; i < count; i++) writeFileSync(join(root, 'notes', `n${i}.md`), `---\ntitle: Note ${i}\n---\nA durable observation number ${i} about acme-example.\n`);
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root };
+}
+
+/** An unfinished cursor: one page of `count` committed under the given options, the rest still to freeze. */
+async function partialCursor(id: string, opts: Partial<SyncOpts>): Promise<void> {
+ expect(await performManagedSync(engine, { sourceId: id, noPull: true, explicitProcessing: [], ...opts } as SyncOpts, { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
+ await drainEffects();
+ embedded.length = 0;
+}
+
+const storedOptions = async (id: string) => (await engine.executeRaw<{ options: unknown }>(
+ "SELECT completed_keys->0->'processingOptions' AS options FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]))[0]?.options;
+/** Embedding effects queued for this source's page requests (any state): zero means no provider call can follow. */
+const embeddingEffects = async (id: string) => (await engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM persistence_effects WHERE source_id=$1 AND kind='embedding'", [id]))[0]!.n;
+
+/** Runs the effect worker the way the owner does, with the embedding provider replaced by the spy. */
+async function drainEffects(): Promise<void> {
+ await disposePersistenceConsumer(engine);
+ for (let i = 0; i < 10; i++) {
+ const n = await runPersistenceEffects(engine, { engine: 'pglite', embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536 }, { hostId: localHostId(), limit: 20 });
+ if (!n) break;
+ }
+}
+
+async function waitTerminal(jobId: string): Promise<ReturnType<typeof getDelegatedSyncStatus>> {
+ const deadline = Date.now() + 120_000;
+ for (;;) {
+ const s = getDelegatedSyncStatus(jobId);
+ if (!s.ok || s.state === 'done' || s.state === 'error') return s;
+ if (Date.now() > deadline) throw new Error(`job ${jobId} did not settle: ${JSON.stringify(s)}`);
+ await Bun.sleep(50);
+ }
+}
+
+async function serveSocket(): Promise<string> {
+ const sock = localIpcSocketPath(join(mkdtempSync(join(tmpdir(), 'options-sock-')), 'resolve.sock'));
+ const handlers: IpcHandlers = {
+ resolve: async () => null,
+ sync_start: (req) => startDelegatedSync(engine, req.options, req.clientToken, { registration: req.registration }),
+ sync_status: (req) => getDelegatedSyncStatus(req.jobId, typeof req.afterLine === 'number' ? req.afterLine : 0),
+ sync_abort: () => ({ ok: true, protocol: 2 as const }),
+ };
+ const server = await startResolveIpcServer(sock, handlers, { secret: SECRET });
+ if (!server) throw new Error('could not bind the test IPC socket');
+ servers.push(server);
+ return sock;
+}
+
+const serveRow = (): ConsumerRow => ({
+ host_id: 'host', pid: 4242, nonce: 'n1', pid_ns: null, kind: 'serve', mode: 'full', started_at: new Date().toISOString(),
+ renewed_at: new Date().toISOString(), restart_required: false, root_barrier_age_ms: null, pool: null,
+ host_json_path: '/tmp/host.json', persistence_home: '/tmp', minted_under: null, version: 'test',
+});
+const deps = (sock: string): ManagedDelegationDeps => ({
+ config: { engine: 'postgres', database_url: 'postgresql://example.invalid/brain' },
+ probe: async () => serveRow(), socket: async () => ({ sock, secret: SECRET }), env: {},
+});
+const quiet = async <T>(fn: () => Promise<T>): Promise<T> => {
+ const origError = console.error, origLog = console.log, origWrite = process.stderr.write.bind(process.stderr), origOut = process.stdout.write.bind(process.stdout);
+ console.error = () => {}; console.log = () => {};
+ process.stderr.write = (() => true) as typeof process.stderr.write; process.stdout.write = (() => true) as typeof process.stdout.write;
+ try { return await fn(); } finally { console.error = origError; console.log = origLog; process.stderr.write = origWrite; process.stdout.write = origOut; }
+};
+
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: env.OPENAI_API_KEY } });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
+ embedded.push(...values);
+ return { embeddings: values.map(() => [1, ...new Array(1535).fill(0)]) };
+ }) as never);
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite;
+}, 120_000);
+afterEach(() => { __resetDelegatedSyncForTests(); _resetCliExitVerdictForTests(); process.exitCode = 0; });
+afterAll(async () => {
+ for (const server of servers) { try { server.close(); } catch { /* noop */ } }
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ });
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('the client builders send an empty explicit-processing list', () => {
+ test('parseDelegatedSyncArgs: a flagless argv sets none explicitly; a processing flag sets exactly that key', () => {
+ const flagless = parseDelegatedSyncArgs(['--source', 'acme-example', '--no-pull']);
+ expect(flagless.ok && flagless.options.explicitProcessing).toEqual([]);
+ const flagged = parseDelegatedSyncArgs(['--source', 'acme-example', '--no-pull', '--no-extract']);
+ expect(flagged.ok && flagged.options.explicitProcessing).toEqual(['noExtract']);
+ });
+
+ test('a flagless delegated run adopts the unfinished cursor\'s stored options (noEmbed=true) instead of refusing', async () => withEnv(env, async () => {
+ const f = await fixture(3);
+ await partialCursor(f.id, { noEmbed: true, noExtract: true });
+ expect(await storedOptions(f.id)).toEqual({ noEmbed: true, noExtract: true, noSchemaPack: false });
+ const sock = await serveSocket();
+ const delegated = await quiet(() => maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--no-pull'],
+ { sourceId: f.id, noPull: true, explicitProcessing: [], drain: true } as SyncOpts, deps(sock)).catch((error: unknown) => error));
+ expect(delegated).toMatchObject({ kind: 'delegated', result: { status: 'first_sync' } });
+ expect(await engine.getPage('notes/n2', { sourceId: f.id })).not.toBeNull();
+ // The adopted options are the cursor's: no page request of this source embeds.
+ expect(await embeddingEffects(f.id)).toBe(0);
+ }), 180_000);
+});
+
+describe('the serve reads a missing list from an older CLI as "no flags"', () => {
+ test('sync_start without explicitProcessing (older CLI) adopts the stored options', async () => withEnv(env, async () => {
+ const f = await fixture(3);
+ await partialCursor(f.id, { noEmbed: true, noExtract: true });
+ const local = await registerLocalWriter(engine, 'cli');
+ const start = await startDelegatedSync(engine, { sourceId: f.id, noPull: true, timeoutSeconds: 120 }, randomUUID(),
+ { registration: { id: local.id, credential: local.credential, lane: 'cli' } });
+ expect(start.ok).toBe(true);
+ const done = await quiet(() => waitTerminal(start.jobId!));
+ expect(done.jobErrorEnvelope).toBeUndefined();
+ expect(done).toMatchObject({ state: 'done', result: { status: 'first_sync' } });
+ }), 180_000);
+});
+
+describe('a runtime embedding deferral is never lifted by cursor adoption', () => {
+ test('delegated: the deferral crosses the wire; a cursor storing noEmbed=false embeds nothing in this run', async () => withEnv(env, async () => {
+ const f = await fixture(3);
+ await partialCursor(f.id, {});
+ expect(await storedOptions(f.id)).toEqual({ noEmbed: false, noExtract: false, noSchemaPack: false });
+ const before = await embeddingEffects(f.id);
+ const sock = await serveSocket();
+ const delegated = await quiet(() => maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--no-pull'],
+ { sourceId: f.id, noPull: true, noEmbed: true, embedDeferred: true, explicitProcessing: [], drain: true } as SyncOpts, deps(sock)).catch((error: unknown) => error));
+ expect(delegated).toMatchObject({ kind: 'delegated', result: { status: 'first_sync' } });
+ await drainEffects();
+ expect(await embeddingEffects(f.id)).toBe(before);
+ expect(embedded).toEqual([]);
+ // The cursor's own options are untouched: the deferral is a property of this run, not of the cursor.
+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->'processingOptions'->>'noEmbed'='false'", [f.id])).toHaveLength(1);
+ }), 180_000);
+
+ test('in-process CLI: the cost gate auto-defers (non-TTY, floor $0); adoption of noEmbed=false still makes zero embedding calls', async () => withEnv(env, async () => {
+ const f = await fixture(3);
+ await engine.setConfig('sync.cost_gate_min_usd', '0');
+ try {
+ await engine.executeRaw("UPDATE sources SET config=jsonb_set(config,'{syncEnabled}','false'::jsonb) WHERE id<>$1", [f.id]);
+ await partialCursor(f.id, {});
+ const before = await embeddingEffects(f.id);
+ await quiet(() => runSync(engine, ['--source', f.id, '--no-pull', '--no-auto-embed']));
+ expect(await engine.getPage('notes/n2', { sourceId: f.id })).not.toBeNull();
+ await drainEffects();
+ expect(await embeddingEffects(f.id)).toBe(before);
+ expect(embedded).toEqual([]);
+ } finally {
+ await engine.executeRaw("DELETE FROM config WHERE key='sync.cost_gate_min_usd'");
+ await engine.executeRaw("UPDATE sources SET config=config-'syncEnabled'");
+ }
+ }), 180_000);
+});