Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): #6712 PR 4b item 7: a CLI pass waits out its own held write; fewer dependent round trips per pass
garrytandc9f52e76731
diff --git a/scripts/bench/sync-convergence.ts b/scripts/bench/sync-convergence.tsindex e77a69078b..9976a9884e 100644--- a/scripts/bench/sync-convergence.ts+++ b/scripts/bench/sync-convergence.ts@@ -156,7 +156,7 @@ async function runLive(engine: import('../../src/core/engine.ts').BrainEngine, cconst sync = async () => {const t = performance.now();const r = await performManagedSync(engine, opts);- return { wall: performance.now() - t, status: r.status, reason: r.reason ?? null, pass: r.pass ?? null };+ return { at: performance.timeOrigin + t, wall: performance.now() - t, status: r.status, reason: r.reason ?? null, pass: r.pass ?? null };};let edits = 0;const commitOne = () => {@@ -339,6 +339,8 @@ function report(r: ReportInput): Record<string, unknown> {gbrain_commit: git(REPO, ['rev-parse', 'HEAD']),settings: { idle_rounds: r.idleRounds, full_rounds: r.fullRounds, warmup: r.warmup, rss_sample_ms: r.sampleMs, percentile: 'nearest-rank', full_round_episode: r.episode, live_pass: r.live },live_warmup: (r.measured as { warmup?: unknown } | null)?.warmup ?? null,+ live_runs: r.live ? { idle: idle.map(t => ({ at: (t as { at?: number }).at, wall: t.wall, status: (t as { status?: string }).status })),+ full: full.map(t => ({ at: (t as { at?: number }).at, wall: t.wall, status: (t as { status?: string }).status })) } : null,live_statuses: r.live ? { idle: (m?.idle ?? []).map(t => (t as { status?: string }).status), full: (m?.full ?? []).map(t => (t as { status?: string }).status) } : null,measured: m ? (m.available ? (m.error ? { error: m.error } : true) : { unavailable: m.reason }) : 'skipped (--seed-only)',idle_tick_ms: summarize(idle.map(t => t.wall)),diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex c48902ca1e..648f0e6691 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -218,7 +218,7 @@ export type WriteWait =* The waiter never owns a provider, database connection, or kernel lock.*/export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config: GBrainConfig,- opts: { waitMs?: number; signal?: AbortSignal } = {}): Promise<WriteWait> {+ opts: { waitMs?: number; signal?: AbortSignal; whileHeldMs?: number } = {}): Promise<WriteWait> {if (isTerminal(row)) return { kind: 'terminal', row };const consumer = startPersistenceConsumer(engine, config);const service = services.get(engine)!;@@ -233,14 +233,19 @@ export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config:// The admission transaction has committed: publish now, not after the idle backoff.consumer.wake(true);const waitMs = opts.waitMs ?? 5000;- const deadline = performance.now() + waitMs;+ const started = performance.now();+ // `whileHeldMs`: past `waitMs`, keep waiting (to that total) while this process's consumer is executing the request.+ let deadline = started + waitMs;const firstPoll = recentlySettled.get(engine)?.has(id) ? 0 : Math.min(WRITE_POLL_START_MS, waitMs / 2);let delay = firstPoll, failure: { error: unknown; attempts: number } | undefined;try {while (!service.stopping && !opts.signal?.aborted) {if (handed) { row = handed; handed = undefined; if (isTerminal(row)) return { kind: 'terminal', row }; }const remaining = deadline - performance.now();- if (remaining <= 0) break;+ if (remaining <= 0) {+ if (opts.whileHeldMs && opts.whileHeldMs > waitMs && deadline === started + waitMs && consumer.holds(id)) { deadline = started + opts.whileHeldMs; continue; }+ break;+ }await new Promise<void>(resolve => {const done = () => { clearTimeout(timer); wake = undefined; opts.signal?.removeEventListener('abort', done); resolve(); };const timer = setTimeout(done, Math.min(delay, remaining));diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 7070ec41d1..cf06e13057 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -70,10 +70,14 @@ export interface SyncPassInput {drainBatch: (key: string, batch: Cursor, sliceBase: { started: number; pages: number }) => Promise<SyncResult | Cursor>;}+/** The configured patterns a selection unions with its flags: read once, beside the pin's other reads. */+function selectionPatterns(engine: BrainEngine, opts: SyncOpts): Promise<[Iterable<string>, string | null]> {+ return Promise.all([syncExcludePatterns(engine, opts.exclude), engine.getConfig('sync.include_hidden')]);+}/** The selection a pass syncs (design §6), with the configured one's test: no selection flag differs from the source's configuration. */-async function passSelection(engine: BrainEngine, opts: SyncOpts, context: ManagedSyncContext, mode: SyncSelection['mode']): Promise<SyncSelection> {- const exclude = [...await syncExcludePatterns(engine, opts.exclude)].sort();- const includeHidden = [...new Set([...opts.includeHidden ?? [], ...(await engine.getConfig('sync.include_hidden') ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)]+function passSelection([excluded, hidden]: [Iterable<string>, string | null], opts: SyncOpts, context: ManagedSyncContext, mode: SyncSelection['mode']): SyncSelection {+ const exclude = [...excluded].sort();+ const includeHidden = [...new Set([...opts.includeHidden ?? [], ...(hidden ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))].sort();return { exclude, includeHidden, strategy: opts.strategy ?? (context.source.config?.strategy as string | undefined) ?? 'markdown', srcSubpath: opts.srcSubpath ?? null, mode };}@@ -295,13 +299,17 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prif (handover.wait) return { ...empty('partial', 'writer_pending'), ...(remote ? {} : { retryWait: handover.wait }) };if (handover.hostRequired) return empty('blocked_by_failures', 'reconcile_host_required');- // Pin (design §2.2): the row, sync.admission, HEAD and the mode.- const [prior, admission, configuredWorking] = await Promise.all([readPassRow(engine, sourceId, incarnation), readSyncAdmission(engine), engine.getConfig('sync.include_working_tree')]);+ // Pin (design §2.2): the row, sync.admission, HEAD and the mode. The reads the kind needs ride the same round trip: the+ // selection's patterns, the schema pack, the tail, the retry row and the source's holds (only the idle probe needs the row).+ const [prior, admission, configuredWorking, patterns, loadedPack, tail, retry, sourceHolds] = await Promise.all([readPassRow(engine, sourceId, incarnation),+ readSyncAdmission(engine), engine.getConfig('sync.include_working_tree'), selectionPatterns(engine, opts),+ input.processingOptions.noSchemaPack ? null : loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null),+ readSyncTail(engine, sourceId), readGitHoldRetryPaths(engine, sourceId, incarnation), readGitSourceHolds(engine, { sourceIds: [sourceId] })]);assertActive();let head = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();const detached = syncGit(context.gitRoot, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() === 'HEAD';const mode: SyncSelection['mode'] = detached || (opts.workingTree ?? configuredWorking === 'true') ? 'working' : 'committed';- const selection = await passSelection(engine, opts, context, mode);+ const selection = passSelection(patterns, opts, context, mode);const configured = !remote && !opts.exclude?.length && !opts.includeHidden?.length && opts.srcSubpath === undefined&& (opts.strategy === undefined || opts.strategy === ((context.source.config?.strategy as string | undefined) ?? 'markdown'))&& (detached || opts.workingTree === undefined || opts.workingTree === (configuredWorking === 'true'));@@ -323,13 +331,12 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prconst processingOptions: SyncProcessingOptions = { noEmbed: requested.noEmbed || !!episode?.inherited.noEmbed, noExtract: requested.noExtract || !!episode?.inherited.noExtract,noSchemaPack: requested.noSchemaPack || !!episode?.inherited.noSchemaPack };const inherited = (['noEmbed', 'noExtract', 'noSchemaPack'] as const).filter(key => processingOptions[key] && !requested[key]);- const pack = processingOptions.noSchemaPack ? null : (await loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null))?.identity ?? null;+ const pack = processingOptions.noSchemaPack ? null : loadedPack?.identity ?? null;// The kind (design §2.2), from the real converged state.const converged = obligations.converged;- const [probe, tail, retry, sourceHolds] = await Promise.all([- converged ? passIdleProbe(engine, { sourceId, incarnation, worktreeId: context.binding.worktree_id, requestHwm: converged.request_hwm, openAtStamp: converged.open_at_stamp ?? [] }) : null,- readSyncTail(engine, sourceId), readGitHoldRetryPaths(engine, sourceId, incarnation), readGitSourceHolds(engine, { sourceIds: [sourceId] })]);+ const probe = converged ? await passIdleProbe(engine, { sourceId, incarnation, worktreeId: context.binding.worktree_id, requestHwm: converged.request_hwm,+ openAtStamp: converged.open_at_stamp ?? [] }) : null;assertActive();const holds = (sourceHolds[0]?.holds ?? []).filter(hold => hold.incarnation === incarnation);// Working mode (design §2.2): the stat cache this process kept from the round its last stamp used; a cold process has none.@@ -362,8 +369,9 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prawait engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {assertActive();await assertDrainLease(tx, sourceId);- await tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]);- value.telemetry.started_at = await databaseNow(tx);+ // One round trip: the stamp and the transaction's clock read are pipelined.+ [, value.telemetry.started_at] = await Promise.all([tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]),+ databaseNow(tx)]);await writePassRow(tx, value, { pin: true });}, principalAttribution(authority.writer.principal)));await clearPassFailures(engine, sourceId, incarnation);@@ -375,7 +383,11 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Probligations.cost = costDecision.cost;let costDeferred: string | null = null;if (costDecision.defer && !processingOptions.noEmbed) { processingOptions.noEmbed = true; costDeferred = costDecision.defer; }- await engine.transaction(async tx => { await assertDrainLease(tx, sourceId); value.telemetry.started_at = await databaseNow(tx); await writePassRow(tx, value, { pin: true }); });+ await engine.transaction(async tx => {+ // The lease check and the clock read share a round trip: a lost lease aborts the transaction before the row is written.+ [, value.telemetry.started_at] = await Promise.all([assertDrainLease(tx, sourceId), databaseNow(tx)]);+ await writePassRow(tx, value, { pin: true });+ });assertActive();registerPassCost(passId, { sourceId, incarnation, scope: costScope, pricePerMTok: currentEmbeddingPricePerMTok() });@@ -559,7 +571,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr}// Design §6: an open episode closes by inclusion (a) or at the configured selection (b); chunker_version only by (b) over U_config.const closure = episode ? await passEpisodeClosure({ gitRoot: context.gitRoot, root: context.root, head, slugMode: levelSlugMode, episode, pass: selection, configured,- configuredSelection: await passSelection(engine, { sourceId } as SyncOpts, context, mode) }) : null;+ configuredSelection: passSelection(await selectionPatterns(engine, { sourceId } as SyncOpts), { sourceId } as SyncOpts, context, mode) }) : null;const closesEpisode = closure?.closes === true;if (closure?.released) counts.episodeReleased = closure.released;const stamp: PassStamp = { leaseToken: lease.token, incarnation, configured, stampChunker: configured && (context.source.last_commit === null || (closesEpisode && !!episode?.full_id && closure!.stampChunker)),@@ -634,8 +646,8 @@ async function databaseNow(tx: Pick<BrainEngine, 'executeRaw'>): Promise<string>/** A converged or idle pass clears what earlier stops recorded: the pass row's failure key and the incarnation's cursor key. */async function clearPassFailures(engine: BrainEngine, sourceId: string, incarnation: string): Promise<void> {- await clearManagedSyncFailureAfterSuccess(engine, passFingerprint(sourceId, incarnation));- await clearManagedSyncFailureAfterSuccess(engine, managedCursorKey(incarnation, undefined));+ await Promise.all([clearManagedSyncFailureAfterSuccess(engine, passFingerprint(sourceId, incarnation)),+ clearManagedSyncFailureAfterSuccess(engine, managedCursorKey(incarnation, undefined))]);}export type { SyncAdmission };diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 580008d63c..aabec4d980 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -256,11 +256,12 @@ async function saveCursor(engine: BrainEngine, key: string, before: Cursor | nul}/** Compare-and-swap inside the caller's transaction; a lost swap returns the cursor that won. */async function writeCursor(tx: BrainEngine, key: string, before: Cursor | null, next: Cursor, inTx?: (tx: BrainEngine) => Promise<unknown>, synchronous = false): Promise<Cursor> {- await assertDrainLease(tx, next.sourceId);// #6643: a cursor records the indexes it settles without a commit from its first save by this build on; a cursor saved// before (a run that began on an older build) starts recording at the index it had then.if (!next.settled) next.settled = before && before.runId === next.runId ? { from: before.settled?.from ?? before.index, ranges: before.settled?.ranges ?? [] } : { from: 0, ranges: [] };+ // A batch step fences itself with the drain lease (passBatchStep); a cursor row is fenced here.if (isPassBatchKey(key)) return await passBatchStep(tx, key, before && JSON.stringify(header(before)), next, JSON.stringify(header(next)), inTx) ? next : currentCursor(tx, key, next);+ await assertDrainLease(tx, next.sourceId);if (before === null) {if (synchronous) await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);@@ -856,16 +857,16 @@ const WAIVER_RUN_MAX = 64;* #5984 Phase 3: when the frozen head would be waived, freezes and screens the entries after it four at a time* (stopping at the first that would not be waived, is held, is overtaken, refuses to freeze, or at the checkpoint)* and waives the run in one transaction, without a `pending` cursor save per entry. Returns null to take the- * per-entry path for the head (its screen admits it, or the run's transaction validated nothing or timed out);- * otherwise the cursor past the waived prefix (or as another run moved it), with the entry that ended the prefix- * saved as pending.+ * per-entry path for the head when the run's transaction validated nothing or timed out, and `admit` when the head's own+ * screen admits it (the per-entry path then skips its screen: it would prepare the same frozen entry again); otherwise the+ * cursor past the waived prefix (or as another run moved it), with the entry that ended the prefix saved as pending.*/async function waiveRun(engine: BrainEngine, cursor: Cursor, head: Pending, key: string, config: GBrainConfig, assertActive: () => void,- frozenRun: Parameters<typeof freezeEntry>[4], drainStartedAt: number, limit: number, onProgress: SyncOpts['onProgress']): Promise<Cursor | null> {+ frozenRun: Parameters<typeof freezeEntry>[4], drainStartedAt: number, limit: number, onProgress: SyncOpts['onProgress']): Promise<Cursor | 'admit' | null> {// The run's screens share one memo of root-level path facts (screening-paths.ts); waiveNoopRun re-validates each entry.// GBRA-75 wave 9: and one bounded-read session (bounded-reads.ts), so the run's screens share one transaction.const run = await withScreeningPaths(() => withBoundedReadSession(engine, session => screenWaiverRun(session, cursor, head, key, config, assertActive, frozenRun, limit)));- if (!run) return null;+ if (!run) return 'admit';assertActive(); stampDrainStep('waiver_run', frozenRun.signal);const observedAt = frozenRun.observedAt ?? new Date().toISOString();const done = await waiveNoopRun(engine, cursor, run, key, async (tx, prefix) => {@@ -1095,7 +1096,7 @@ async function admitWindowGroup(engine: BrainEngine, cursor: Cursor, key: string* pending entry, so the single path settles it by its fault class; #6712: the* members after it stay admitted at the head of the window.*/-async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk: BulkPass, config: GBrainConfig, wait: { waitMs: number; signal?: AbortSignal },+async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk: BulkPass, config: GBrainConfig, wait: { waitMs: number; signal?: AbortSignal; whileHeldMs?: number },drainStartedAt: number, onProgress: SyncOpts['onProgress'], ahead?: (cursor: Cursor) => Promise<Cursor>): Promise<{ cursor: Cursor } | { result: SyncResult }> {const signal = wait.signal;const members = cursor.group!;@@ -1292,8 +1293,12 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPassertPersistenceAccepting(engine);validateManagedSyncOptions(opts);const context = await resolveManagedSyncContext(engine, opts);- 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);+ // Independent reads, one round trip; a refusal still wins over the authority's own error, as when they ran in turn.+ const [allowed, resolvedAuthority] = await Promise.allSettled([opts.dryRun ? null : assertManagedSyncAllowed(engine, context.binding.worktree_id, context.sourceId),+ managedSyncAuthority(engine, context.sourceId, context.incarnation, opts.repoPath ?? context.root)]);+ if (allowed.status === 'rejected') throw allowed.reason;+ if (resolvedAuthority.status === 'rejected') throw resolvedAuthority.reason;+ const authority = resolvedAuthority.value;const company = currentCompanyBrainSync(context.sourceId);const processingOptions = syncProcessingOptions(opts);const syncOptions = syncCursorOptions(opts);@@ -1326,8 +1331,12 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst observedAt = frozenRun.observedAt = cursor.discoveredAt ?? runStartedAt;const config = loadConfig() ?? { engine: engine.kind }, analyzeEvery = await importAnalyzeEveryPages(engine);let batchStart = performance.now(), batchPages = 0, foregroundWaitStart = 0, foregroundBaseline = 0;- let creditedPages = 0, creditStarted = 0, foregroundQueued = false;+ let creditedPages = 0, creditStarted = 0, foregroundQueued = false, screenedAdmit: string | null = null;const sliceStarted = sliceBase?.started ?? performance.now(), sliceFirstIndex = cursor.index - (sliceBase?.pages ?? 0), drainStartedAt = opts.drainStartedAt ?? Date.now();+ // #6712 PR 4b: a local live pass keeps waiting on its own write while this process's consumer is publishing it (up to a+ // drain's 30 s): a write still publishing past the CLI's 5 s (a cold process, a transaction-mode pooler's describe round+ // trips) ends no round. A write nobody here is working on (another process holds the worktree) still stops at 5 s.+ const whileHeld = !opts.drainStartedAt && !!cursor.passId && !authority.writer.remote ? { whileHeldMs: 30_000 } : {};const bulk: BulkPass = { settings: opts.bulk && !company ? opts.bulk : { enabled: false, reason: null, size: 1, maxTxnMs: 0 }, perMemberMs: null, foregroundFirst: await foregroundPriority(engine) };const waiveBatch = noopWaiversEnabled() && await waiverBatchEnabled(startupConfig), prescreen = { missed: new Set<number>(), limit: Infinity, drainStartedAt, assertActive, signal, onProgress: opts.onProgress,embeddingRequested: !(cursor.processingOptions ?? processingOptions).noEmbed && !opts.embedDeferred && !config.embedding_disabled && !!config.embedding_model?.trim() };@@ -1370,10 +1379,13 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPcontinue;}const { frozen, deferredAt } = next;- const waived: Cursor | null = waiveBatch && !frozen.rebound && deferredAt === undefined ? await waiveRun(engine, cursor, frozen, key, config, assertActive, frozenRun, drainStartedAt,+ const ran = waiveBatch && !frozen.rebound && deferredAt === undefined ? await waiveRun(engine, cursor, frozen, key, config, assertActive, frozenRun, drainStartedAt,slice ? slice.maxPages - (cursor.index - sliceFirstIndex) : WAIVER_RUN_MAX, opts.onProgress) : null;+ const waived = ran === 'admit' ? null : ran;if (waived && slice && (waived.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(waived, 'partial', 'writer_yield');if (waived) { cursor = waived; continue; }+ // The run's screen of this head already found it admits: its per-entry screen below would prepare it again.+ screenedAdmit = ran === 'admit' ? frozen.requestId : null;cursor = await saveCursor(engine, key, cursor, { ...cursor, ...(frozen.rebound ? { overtaken: true as const } : {}), pending: frozen }, false, assertActive);}if (!cursor.pending) continue; // another owner-loop advanced the cursor@@ -1383,7 +1395,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPassertActive();// #5470/#5984: a frozen entry whose publication would change nothing advances the cursor without an admission.const screened: Cursor = cursor;- const waived: Cursor | null = prior ? null : await waiveNoopEntry(engine, screened, pending, config, key,+ const waived: Cursor | null = prior || screenedAdmit === pending.requestId ? null : await waiveNoopEntry(engine, screened, pending, config, key,(tx, noop) => writeCursor(tx, key, screened, { ...waivedCursor(screened, noop, indexOf(screened, pending)), progress: stampProgress(screened.progress, screened.index, screened.index + 1, drainStartedAt) },holdClear(screened, pending.intent.path, observedAt)), tx => currentCursor(tx, key, screened), signal);if (waived) {@@ -1397,7 +1409,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst freezeAt: FreezeAt = base => async index => { if (base.entries[index]?.prescreened && !prescreen.missed.has(index)) return null; const frozen = await freezeEntry(engine, { ...base, index }, key, assertActive, frozenRun); return 'requestId' in frozen ? frozen : null; };if (bulk.settings.enabled && (bulk.foregroundFirst || !foregroundQueued) && !prior && !cursor.group && !pending.rebound && indexOf(cursor, pending) === cursor.index && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);if (cursor.group?.[0]?.requestId === pending.requestId && cursor.pending?.requestId === pending.requestId) {- const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000 }, drainStartedAt, opts.onProgress,+ const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000, ...whileHeld }, drainStartedAt, opts.onProgress,opts.drainStartedAt ? next => admitAhead(engine, next, key, bulk, config, freezeAt, assertActive) : undefined);if ('result' in step) return step.result;cursor = step.cursor;@@ -1435,7 +1447,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP// #5762: a checkpoint's validation runs under the coordinator's 5 s statement timeout, so its wait outlasts that// budget; a timed-out checkpoint then reports its terminal refusal and hint in this run instead of the next.// #5984: a drain re-enters anyway, so it waits longer per page instead of paying a full re-entry; its stop signal bounds the wait.- const waited = await awaitWrite(engine, row, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: pending.intent.kind === 'managed_sync_checkpoint' ? 8000 : 5000 });+ const waited = await awaitWrite(engine, row, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: pending.intent.kind === 'managed_sync_checkpoint' ? 8000 : 5000, ...whileHeld });const done = waited.row;assertSyncDispatchActive();if (!isTerminalWriteState(done.state)) {diff --git a/src/core/schema-pack/engine-resolution.ts b/src/core/schema-pack/engine-resolution.tsindex 7ef74b9e46..8b5462324c 100644--- a/src/core/schema-pack/engine-resolution.ts+++ b/src/core/schema-pack/engine-resolution.ts@@ -17,12 +17,11 @@ export async function engineSchemaInput(engine: Pick<BrainEngine, 'getConfig'> | null | undefined,options: EngineSchemaOptions,): Promise<LoadActivePackInput> {- const dbConfig = await readDbSchemaPack(engine);+ const [dbConfig, sourceValue] = await Promise.all([readDbSchemaPack(engine),+ options.sourceId ? engine?.getConfig(`schema_pack.source.${options.sourceId}`) : undefined]);const perSourceDb = new Map<string, string>();- if (options.sourceId) {- const value = (await engine?.getConfig(`schema_pack.source.${options.sourceId}`))?.trim();- if (value) perSourceDb.set(options.sourceId, value);- }+ const value = sourceValue?.trim();+ if (options.sourceId && value) perSourceDb.set(options.sourceId, value);return { ...options, cfg: loadConfigFileOnly(), dbConfig, perSourceDb };}diff --git a/test/sync-pass-live-6712.test.ts b/test/sync-pass-live-6712.test.tsindex a2bf912a60..f47da1eda8 100644--- a/test/sync-pass-live-6712.test.ts+++ b/test/sync-pass-live-6712.test.ts@@ -106,6 +106,20 @@ describe('#6712 PR 4b live pass fences (pglite)', () => {expect(await liveSlugs(engine)).toEqual(['notes/b', 'notes/c']);}, { setup }), 180_000);+ test('item 7: a CLI pass keeps waiting on its own write while this process\'s consumer still holds it, past the 5 s wait: synced, not writer_pending', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A body that takes longer than the wait to prepare.')); commit(root, 'edit a');+ // The write's preparation outlasts the pass's 5 s wait, as a publication over a high-latency link does.+ let slowed = false;+ installFaultHook(async (point, detail) => {+ if (point === 'consumer:prepared' && detail.operation === 'submit_job' && !slowed) { slowed = true; await new Promise(resolve => setTimeout(resolve, 6500)); }+ });+ const synced = await performManagedSync(engine, OPTS);+ installFaultHook(undefined);+ expect({ slowed, status: synced.status, reason: synced.reason }).toEqual({ slowed: true, status: 'synced', reason: undefined });+ expect((await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))?.page.compiled_truth).toContain('takes longer than the wait');+ }, { setup }), 180_000);+test('not_converged: a working copy that changes under every round ends the pass not_converged; the third in a row reports', () => managedBrain(async ({ engine, root }) => {expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');let edits = 0;