Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(serve-sync): verified CLI-registration hand-off runs the managed drain inside the serve; sync_status carries its lines, DrainReport and next (#6317 D1 a′)

garrytanba3d48eef874
diff --git a/src/core/console-prefix.ts b/src/core/console-prefix.ts
index 0a14f0f70f..ff95cdc0c2 100644
--- a/src/core/console-prefix.ts
+++ b/src/core/console-prefix.ts
@@ -68,6 +68,27 @@ let __stdoutLoggingRedirected = false;
// already; direct console.log(JSON.stringify(..)) sites are untouched.
const __humanToStderr = new AsyncLocalStorage<true>();
+// #6317: a resident serve running a delegated managed sync captures the
+// drain's human lines for the polling CLI instead of printing them to its
+// own stderr. Scoped like the prefix: it rides every await (and Bun's
+// timers) under the wrap, so the drain's progress and stall lines, which an
+// interval prints, reach the sink too.
+const __lineSink = new AsyncLocalStorage<(line: string) => void>();
+
+/**
+ * Run `fn` with every `slog` / `serr` line delivered to `sink` (one call
+ * per formatted line, prefix applied, no trailing newline) instead of the
+ * process streams. Nests with `withSourcePrefix`; the innermost sink wins.
+ */
+export function withHumanLineSink<T>(sink: (line: string) => void, fn: () => Promise<T>): Promise<T> {
+ return __lineSink.run(sink, fn);
+}
+
+function deliverToSink(sink: (line: string) => void, args: unknown[], prefix: string | null): void {
+ const text = prefix === null ? formatArgs(args) : prefixLines(formatArgs(args), prefix);
+ for (const line of text.split('\n')) sink(line);
+}
+
/**
* Run `fn` with every `slog` line (prefixed or not) routed to stderr, so a
* command's human output cannot interleave with the JSON it emits on
@@ -147,6 +168,8 @@ export function getSourcePrefix(): string | null {
*/
export function slog(...args: unknown[]): void {
const prefix = getSourcePrefix();
+ const sink = __lineSink.getStore();
+ if (sink) { deliverToSink(sink, args, prefix); return; }
const toStderr = __stdoutLoggingRedirected || __humanToStderr.getStore() === true;
if (prefix === null) {
// Back-compat fast path: bare console.log semantics. (Under the stdio
@@ -168,6 +191,8 @@ export function slog(...args: unknown[]): void {
*/
export function serr(...args: unknown[]): void {
const prefix = getSourcePrefix();
+ const sink = __lineSink.getStore();
+ if (sink) { deliverToSink(sink, args, prefix); return; }
if (prefix === null) {
// eslint-disable-next-line no-console
console.error(...args);
diff --git a/src/core/context/sync-ipc.ts b/src/core/context/sync-ipc.ts
index d8f15c8234..d16d8e41b3 100644
--- a/src/core/context/sync-ipc.ts
+++ b/src/core/context/sync-ipc.ts
@@ -12,6 +12,12 @@
* sync_status { jobId } → job state + progress + final result
* sync_abort { jobId } → begins cooperative abort (typed partial)
*
+ * #6317 (managed brains, Postgres): sync_start may carry the CLI's durable
+ * `cli` writer registration. The serve verifies it and runs the managed
+ * drain (`drainManagedSync`) as that writer; sync_status then carries the
+ * drain's report, the `next` action and the numbered human lines the drain
+ * printed, so the polling CLI shows the same lines its in-process run would.
+ *
* This module is deliberately a LEAF: pure types + pure functions, imported by
* both the resolve-ipc client/server plumbing and the serve-sync-runner. It
* must not import resolve-ipc.ts (cycle) or any engine module.
@@ -19,6 +25,7 @@
import { isValidSourceId } from '../source-id.ts';
import type { SyncResult } from '../../commands/sync.ts';
+import type { DrainNext, DrainReport } from '../persistence/sync-drain.ts';
// ── Options allowlist ──────────────────────────────────────────────────────
@@ -44,9 +51,17 @@ export const DELEGATED_SYNC_OPTION_FIELDS = {
skipFailed: 'boolean',
retryFailed: 'boolean',
includeGitignored: 'boolean',
+ noBulk: 'boolean',
+ lanes: 'number',
+ explicitProcessing: 'string[]',
timeoutSeconds: 'number',
} as const;
+/** `--lanes N` bounds (`src/commands/sync/args.ts`). */
+export const DELEGATED_SYNC_LANES_MAX = 16;
+/** The processing keys an unfinished managed cursor supplies unless the caller set them (#5632). */
+export const DELEGATED_SYNC_PROCESSING_KEYS = ['noEmbed', 'noExtract', 'noSchemaPack'] as const;
+
export type DelegatedSyncOptionField = keyof typeof DELEGATED_SYNC_OPTION_FIELDS;
/** Hard ceiling on a delegated job's runtime (24h) — matches the sync hard-deadline scale. */
@@ -65,6 +80,12 @@ export interface DelegatedSyncOptions {
skipFailed?: boolean;
retryFailed?: boolean;
includeGitignored?: boolean;
+ /** #6317: `--no-bulk` for the managed catch-up. */
+ 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. */
+ explicitProcessing?: Array<typeof DELEGATED_SYNC_PROCESSING_KEYS[number]>;
/**
* REQUIRED — the client always sends its resolved hard deadline so a job
* whose client died stays bounded. `0` is the single unbounded encoding
@@ -99,9 +120,23 @@ export function validateDelegatedSyncOptions(raw: unknown): DelegatedSyncValidat
for (const [key, type] of Object.entries(DELEGATED_SYNC_OPTION_FIELDS)) {
const v = rec[key];
if (v === undefined) continue;
+ if (type === 'string[]') {
+ if (!Array.isArray(v) || v.some(item => typeof item !== 'string')) return { ok: false, error: `invalid_options:${key}` };
+ out[key] = [...v];
+ continue;
+ }
if (typeof v !== type) return { ok: false, error: `invalid_options:${key}` };
out[key] = v;
}
+ if (out.lanes !== undefined && (!Number.isInteger(out.lanes) || (out.lanes as number) < 1 || (out.lanes as number) > DELEGATED_SYNC_LANES_MAX)) {
+ return { ok: false, error: 'invalid_options:lanes' };
+ }
+ if (out.explicitProcessing !== undefined) {
+ const keys = out.explicitProcessing as string[];
+ if (keys.length > DELEGATED_SYNC_PROCESSING_KEYS.length || keys.some(key => !(DELEGATED_SYNC_PROCESSING_KEYS as readonly string[]).includes(key))) {
+ return { ok: false, error: 'invalid_options:explicitProcessing' };
+ }
+ }
const timeout = out.timeoutSeconds;
if (typeof timeout !== 'number' || !Number.isInteger(timeout) || timeout < 0) {
return { ok: false, error: 'invalid_options:timeoutSeconds' };
@@ -143,6 +178,25 @@ export function toWireSyncResult(r: SyncResult): WireSyncResult {
export type DelegatedSyncState = 'running' | 'aborting' | 'done' | 'error';
+/**
+ * #6317: the CLI's durable `cli` writer registration (id + private credential,
+ * the same document `local-client.ts` sends over the PGLite persistence IPC).
+ * The serve verifies it against `persistence_local_writers` and runs the
+ * managed drain AS that writer, so revocation and grant checks still apply;
+ * the shared secret alone never authorizes a managed sync.
+ */
+export interface SyncStartRegistration { id: string; credential: string; lane: 'cli' }
+
+export function isSyncStartRegistration(value: unknown): value is SyncStartRegistration {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
+ const keys = Object.keys(value);
+ if (keys.length !== 3 || !['id', 'credential', 'lane'].every(key => keys.includes(key))) return false;
+ const rec = value as Record<string, unknown>;
+ return typeof rec.id === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(rec.id)
+ && typeof rec.credential === 'string' && /^[a-f0-9]{64}$/.test(rec.credential)
+ && rec.lane === 'cli';
+}
+
export interface SyncStartRequest {
kind: 'sync_start';
protocol: 2;
@@ -155,6 +209,8 @@ export interface SyncStartRequest {
*/
clientToken: string;
options: DelegatedSyncOptions;
+ /** #6317: present when the CLI asks the serve to run a managed drain as its verified writer. */
+ registration?: SyncStartRegistration;
}
export type SyncStartError =
@@ -175,6 +231,13 @@ export interface SyncStartResponse {
/** True when a token retry matched the retained terminal job — poll sync_status for its result. */
completed?: boolean;
error?: SyncStartError;
+ /**
+ * #6317: the agent-operator envelope (`OperationError.toJSON()`) behind an
+ * authorization refusal of the registration hand-off (`permission_denied`
+ * for a denied, revoked or stdio registration), so the CLI renders the same
+ * error its in-process path would have thrown.
+ */
+ refusal?: Record<string, unknown>;
}
export interface SyncStatusRequest {
@@ -182,8 +245,13 @@ export interface SyncStatusRequest {
protocol: 2;
secret: string;
jobId: string;
+ /** #6317: return only the job's human lines after this sequence number (the client's cursor). */
+ afterLine?: number;
}
+/** #6317: a human line the job printed (the drain's progress, stall and lanes lines), numbered so a poll resumes where it left off. */
+export interface SyncStatusLine { seq: number; text: string }
+
export interface SyncStatusResponse {
ok: boolean;
protocol: 2;
@@ -197,6 +265,18 @@ export interface SyncStatusResponse {
result?: WireSyncResult;
/** Present when state === 'error' — the job's failure message. */
jobError?: string;
+ /** #6317: the job's error as an agent-operator envelope when it was an OperationError (state === 'error'). */
+ jobErrorEnvelope?: Record<string, unknown>;
+ /** #6317: true when the job runs the managed drain as a verified CLI writer (its `lines` are the drain's own output). */
+ managed?: boolean;
+ /** #6317: the managed drain's report so far (final when state is terminal), when the job is a managed drain. */
+ drain?: DrainReport;
+ /** #6317: what to run next once the drain is terminal; null when it synced; absent before then. */
+ next?: DrainNext | null;
+ /** #6317: the human lines printed since the request's `afterLine` cursor, oldest first (bounded; older lines are dropped). */
+ lines?: SyncStatusLine[];
+ /** #6317: the newest line sequence the server holds (the client's next cursor). */
+ lineSeq?: number;
/** ok:false protocol errors: 'unauthorized' | 'unknown_job' | 'unsupported_kind' | 'unsupported_protocol'. */
error?: string;
}
diff --git a/src/core/serve-sync-runner.ts b/src/core/serve-sync-runner.ts
index ae3df21740..d80fe8b124 100644
--- a/src/core/serve-sync-runner.ts
+++ b/src/core/serve-sync-runner.ts
@@ -37,21 +37,45 @@
* closes its own embedding loop. NOT submitEmbedBackfill: on PGLite nothing
* drains minion_jobs (workers refuse the engine) and a stuck `waiting` row
* cooldown-blocks every later submit.
+ *
+ * #6317 (managed brains): a sync_start that carries the CLI's durable `cli`
+ * writer registration is an authorization hand-off, not a lifted gate. The
+ * shared-secret lane still runs under withLegacySyncDelegation, where
+ * assertDurableSyncCaller refuses managed sync by design; the verified lane
+ * runs under withVerifiedLocalRegistration instead, so managedSyncAuthority
+ * sees the CLI's own principal and its revocation and grant checks apply to
+ * every admission. A denied, revoked or stdio registration is refused at
+ * sync_start with the OperationError envelope (`refusal`). On a managed brain
+ * the verified job runs the managed drain (`performSync` with `drain: true`,
+ * the CLI's own path) with the drain's human lines captured per job
+ * (withHumanLineSink) for sync_status, where the CLI prints them verbatim.
+ * The one-job-at-a-time guard, the per-job deadline, abort and shutdown
+ * settle are shared by both lanes. Embeds on the managed lane follow the
+ * CLI's effective flags (the managed cursor owns processing options).
*/
import { randomUUID } from 'node:crypto';
import { withLegacySyncDelegation } from './persistence/sync-authority.ts';
+import { verifyLocalWriter, withVerifiedLocalRegistration } from './persistence/identity.ts';
+import { OperationError } from './ops/contract.ts';
+import { trustedCliRequired } from './ops/op-fix.ts';
+import { withHumanLineSink } from './console-prefix.ts';
import type { BrainEngine } from './engine.ts';
import { registerBackgroundWorkDrainer } from './background-work.ts';
import {
+ isSyncStartRegistration,
toWireSyncResult,
validateDelegatedSyncOptions,
+ type DelegatedSyncOptions,
type DelegatedSyncState,
type SyncAbortResponse,
+ type SyncStartRegistration,
type SyncStartResponse,
+ type SyncStatusLine,
type SyncStatusResponse,
type WireSyncResult,
} from './context/sync-ipc.ts';
+import type { DrainNext, DrainReport } from './persistence/sync-drain.ts';
interface DelegatedSyncJob {
id: string;
@@ -64,11 +88,24 @@ interface DelegatedSyncJob {
bankedFiles?: number;
result?: WireSyncResult;
jobError?: string;
+ /** #6317: the job's OperationError envelope, when its failure was one. */
+ jobErrorEnvelope?: Record<string, unknown>;
+ /** #6317: true when the job ran the managed drain as a verified CLI writer. */
+ managed: boolean;
+ drain?: DrainReport;
+ next?: DrainNext | null;
+ /** #6317: the human lines the job printed, numbered from 1; the oldest are dropped past LINE_BUFFER_MAX. */
+ lines: SyncStatusLine[];
+ lineSeq: number;
controller: AbortController;
/** Resolves when the job reaches done/error — the shutdown settle target. */
settled: Promise<void>;
}
+/** Lines retained per job and lines returned per sync_status poll (the response must fit the IPC message cap). */
+const LINE_BUFFER_MAX = 2000;
+export const LINES_PER_STATUS_MAX = 400;
+
/** Running job, or the retained last terminal job (replaced by the next start). */
let current: DelegatedSyncJob | null = null;
let shuttingDown = false;
@@ -111,14 +148,17 @@ export function isDelegatedSyncRunning(): boolean {
/**
* Handle a sync_start request. `rawOptions` is the untrusted wire payload —
* validated here (the runner is the single authority) even though the IPC
- * layer types it.
+ * layer types it. `opts.registration` is the untrusted #6317 hand-off
+ * payload; when present the start is asynchronous (one verification read).
*/
+export function startDelegatedSync(engine: BrainEngine, rawOptions: unknown, clientToken: string, opts?: { boundSourceId?: string }): SyncStartResponse;
+export function startDelegatedSync(engine: BrainEngine, rawOptions: unknown, clientToken: string, opts: { boundSourceId?: string; registration?: unknown }): SyncStartResponse | Promise<SyncStartResponse>;
export function startDelegatedSync(
engine: BrainEngine,
rawOptions: unknown,
clientToken: string,
- opts: { boundSourceId?: string } = {},
-): SyncStartResponse {
+ opts: { boundSourceId?: string; registration?: unknown } = {},
+): SyncStartResponse | Promise<SyncStartResponse> {
if (typeof clientToken !== 'string' || clientToken.length === 0 || clientToken.length > 128) {
return { ok: false, protocol: 2, error: 'invalid_options:clientToken' };
}
@@ -136,6 +176,9 @@ export function startDelegatedSync(
if (current && !isTerminal(current.state)) {
return { ok: false, protocol: 2, error: 'busy', jobId: current.id };
}
+ if (opts.registration !== undefined && !isSyncStartRegistration(opts.registration)) {
+ return { ok: false, protocol: 2, error: 'invalid_options:registration' };
+ }
const v = validateDelegatedSyncOptions(rawOptions);
if (!v.ok) return { ok: false, protocol: 2, error: v.error };
const options = v.options;
@@ -150,6 +193,9 @@ export function startDelegatedSync(
state: 'running',
sourceId: options.sourceId ?? opts.boundSourceId,
startedAt: Date.now(),
+ managed: false,
+ lines: [],
+ lineSeq: 0,
controller,
settled: Promise.resolve(),
};
@@ -170,31 +216,32 @@ export function startDelegatedSync(
}, options.timeoutSeconds * 1000);
deadlineTimer.unref?.();
}
+ const settle = (): void => {
+ if (deadlineTimer) clearTimeout(deadlineTimer);
+ job.finishedAt = Date.now();
+ };
+ const fail = (e: unknown): void => {
+ job.jobError = e instanceof Error ? e.message : String(e);
+ if (e instanceof OperationError) job.jobErrorEnvelope = e.toJSON();
+ job.state = 'error';
+ log(`error job=${job.id}: ${job.jobError}`);
+ };
+
+ if (opts.registration !== undefined) {
+ return startVerifiedDelegatedSync(engine, job, options, opts.registration as SyncStartRegistration, { settle, fail });
+ }
job.settled = withLegacySyncDelegation(async () => {
try {
await (await import('./persistence/maintenance.ts')).assertUnmanagedCanonicalWriter(engine, 'shared-secret sync delegation');
const { performSync } = await import('../commands/sync.ts');
- let sourceId = job.sourceId;
- if (!sourceId) {
- const { resolveSourceWithTier } = await import('./source-resolver.ts');
- sourceId = (await resolveSourceWithTier(engine, null)).source_id;
- job.sourceId = sourceId;
- }
+ const sourceId = await resolveJobSource(engine, job);
log(
`start job=${job.id} source=${sourceId ?? 'default'} ` +
`opts=${JSON.stringify({ ...options, timeoutSeconds: undefined })} deadline=${options.timeoutSeconds}s`,
);
const r = await performSync(engine, {
- sourceId,
- dryRun: options.dryRun,
- full: options.full,
- noPull: options.noPull,
- noExtract: options.noExtract,
- noSchemaPack: options.noSchemaPack,
- skipFailed: options.skipFailed,
- retryFailed: options.retryFailed,
- includeGitignored: options.includeGitignored,
+ ...classicSyncOpts(options, sourceId),
// ALWAYS deferred — see module header. Drained by maybeDrainDeferredEmbeds.
noEmbed: true,
signal: controller.signal,
@@ -215,24 +262,126 @@ export function startDelegatedSync(
scheduleDeferredSyncEmbeds(engine, sourceId);
}
} catch (e) {
- job.jobError = e instanceof Error ? e.message : String(e);
- job.state = 'error';
- log(`error job=${job.id}: ${job.jobError}`);
+ fail(e);
} finally {
- if (deadlineTimer) clearTimeout(deadlineTimer);
- job.finishedAt = Date.now();
+ settle();
}
});
return { ok: true, protocol: 2, jobId: job.id };
}
-/** Handle a sync_status poll. */
-export function getDelegatedSyncStatus(jobId: string): SyncStatusResponse {
+async function resolveJobSource(engine: BrainEngine, job: DelegatedSyncJob): Promise<string | undefined> {
+ if (job.sourceId) return job.sourceId;
+ const { resolveSourceWithTier } = await import('./source-resolver.ts');
+ job.sourceId = (await resolveSourceWithTier(engine, null)).source_id;
+ return job.sourceId;
+}
+
+function classicSyncOpts(options: DelegatedSyncOptions, sourceId: string | undefined) {
+ return {
+ sourceId,
+ dryRun: options.dryRun,
+ full: options.full,
+ noPull: options.noPull,
+ noExtract: options.noExtract,
+ noSchemaPack: options.noSchemaPack,
+ skipFailed: options.skipFailed,
+ retryFailed: options.retryFailed,
+ includeGitignored: options.includeGitignored,
+ };
+}
+
+/**
+ * #6317: the verified lane. The registration is checked before the start is
+ * acknowledged (a refusal answers sync_start itself, with the envelope); the
+ * job then runs under withVerifiedLocalRegistration, which re-verifies at
+ * entry, so a registration revoked between the two reads never runs either.
+ * The job slot is already reserved (`current`), so a concurrent sync_start
+ * answers `busy` while the verification read is in flight.
+ */
+async function startVerifiedDelegatedSync(
+ engine: BrainEngine,
+ job: DelegatedSyncJob,
+ options: DelegatedSyncOptions,
+ registration: SyncStartRegistration,
+ hooks: { settle: () => void; fail: (e: unknown) => void },
+): Promise<SyncStartResponse> {
+ const refuse = (e: unknown): SyncStartResponse => {
+ hooks.fail(e);
+ hooks.settle();
+ const envelope = e instanceof OperationError ? e.toJSON() : undefined;
+ return { ok: false, protocol: 2, jobId: job.id, error: e instanceof OperationError ? e.code : 'permission_denied', ...(envelope ? { refusal: envelope } : {}) };
+ };
+ let verified: Awaited<ReturnType<typeof verifyLocalWriter>>;
+ try { verified = await verifyLocalWriter(engine, registration); }
+ catch (e) { return refuse(e); }
+ if (verified.remote || verified.principal.kind !== 'local_cli') {
+ return refuse(trustedCliRequired('Serve-delegated managed sync requires this host\'s trusted CLI registration; a stdio writer registration cannot run it.'));
+ }
+ job.managed = true;
+ const push = (text: string): void => {
+ job.lines.push({ seq: ++job.lineSeq, text });
+ if (job.lines.length > LINE_BUFFER_MAX) job.lines.splice(0, job.lines.length - LINE_BUFFER_MAX);
+ };
+ job.settled = (async () => {
+ try {
+ await withVerifiedLocalRegistration(engine, registration, () => withHumanLineSink(push, async () => {
+ const { performSync } = await import('../commands/sync.ts');
+ const sourceId = await resolveJobSource(engine, job);
+ const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ const managed = brain?.enabled === true;
+ log(
+ `start job=${job.id} source=${sourceId ?? 'default'} writer=${verified.principal.id} managed=${managed} ` +
+ `opts=${JSON.stringify({ ...options, timeoutSeconds: undefined })} deadline=${options.timeoutSeconds}s`,
+ );
+ const r = await performSync(engine, {
+ ...classicSyncOpts(options, sourceId),
+ // 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 }
+ : { noEmbed: true }),
+ signal: job.controller.signal,
+ onProgress: (p) => {
+ job.phase = p.phase;
+ if (p.bankedFiles !== undefined) job.bankedFiles = p.bankedFiles;
+ },
+ });
+ job.result = toWireSyncResult(r);
+ job.drain = r.drain;
+ if (managed) {
+ const { drainNext } = await import('./persistence/sync-drain.ts');
+ const { managedSyncResumeArgs, syncResumeCommand } = await import('./sync-reconcile.ts');
+ const id = sourceId ?? 'default';
+ job.next = drainNext(r, syncResumeCommand(managedSyncResumeArgs({ sourceId: id, processingOptions: options })), id);
+ }
+ job.state = 'done';
+ log(
+ `done job=${job.id} status=${r.status} added=${r.added} modified=${r.modified} ` +
+ `deleted=${r.deleted}${r.drain ? ` drain=${r.drain.outcome}` : ''} in=${Math.round((Date.now() - job.startedAt) / 1000)}s`,
+ );
+ if (!managed && !options.dryRun && !options.noEmbed && r.added + r.modified > 0) {
+ scheduleDeferredSyncEmbeds(engine, sourceId);
+ }
+ }));
+ } catch (e) {
+ hooks.fail(e);
+ } finally {
+ hooks.settle();
+ }
+ })();
+ return { ok: true, protocol: 2, jobId: job.id };
+}
+
+/** Handle a sync_status poll. `afterLine` is the client's line cursor (#6317); lines before it are not resent. */
+export function getDelegatedSyncStatus(jobId: string, afterLine = 0): SyncStatusResponse {
const job = current;
if (!job || job.id !== jobId) {
return { ok: false, protocol: 2, error: 'unknown_job' };
}
+ const since = Number.isFinite(afterLine) ? afterLine : 0;
+ const lines = job.lines.filter(line => line.seq > since).slice(0, LINES_PER_STATUS_MAX);
return {
ok: true,
protocol: 2,
@@ -242,8 +391,12 @@ export function getDelegatedSyncStatus(jobId: string): SyncStatusResponse {
elapsedMs: (job.finishedAt ?? Date.now()) - job.startedAt,
phase: job.phase,
bankedFiles: job.bankedFiles,
+ ...(job.managed ? { managed: true, lines, lineSeq: job.lineSeq } : {}),
+ ...(job.drain ? { drain: job.drain } : {}),
+ ...(job.next !== undefined ? { next: job.next } : {}),
...(job.state === 'done' && job.result ? { result: job.result } : {}),
...(job.state === 'error' && job.jobError ? { jobError: job.jobError } : {}),
+ ...(job.state === 'error' && job.jobErrorEnvelope ? { jobErrorEnvelope: job.jobErrorEnvelope } : {}),
};
}
diff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.ts
index 6ef441cce1..17aab6d1b7 100644
--- a/src/mcp/resolve-ipc-binding.ts
+++ b/src/mcp/resolve-ipc-binding.ts
@@ -134,8 +134,10 @@ export async function bindResolveIpcForServe(
sync_start: (req) =>
runner.startDelegatedSync(engine, req.options, req.clientToken, {
boundSourceId: defaultSource,
+ // #6317: the CLI's writer registration for a managed drain (verified by the runner, never here).
+ registration: req.registration,
}),
- sync_status: (req) => runner.getDelegatedSyncStatus(req.jobId),
+ sync_status: (req) => runner.getDelegatedSyncStatus(req.jobId, typeof req.afterLine === 'number' ? req.afterLine : 0),
sync_abort: (req) => runner.abortDelegatedSync(req.jobId),
};
} catch (e) {
diff --git a/test/context/sync-ipc-validation.test.ts b/test/context/sync-ipc-validation.test.ts
index 5de10fb21c..341ea178cc 100644
--- a/test/context/sync-ipc-validation.test.ts
+++ b/test/context/sync-ipc-validation.test.ts
@@ -12,6 +12,7 @@ import {
DELEGATED_SYNC_OPTION_FIELDS,
DELEGATED_SYNC_TIMEOUT_MAX_SECONDS,
WIRE_PAGES_AFFECTED_MAX,
+ isSyncStartRegistration,
toWireSyncResult,
validateDelegatedSyncOptions,
} from '../../src/core/context/sync-ipc.ts';
@@ -39,6 +40,27 @@ describe('validateDelegatedSyncOptions', () => {
expect(v.options).not.toBe(raw as never);
});
+ test('#6317: the managed catch-up fields validate by shape (lanes 1..16, explicitProcessing from the three processing keys)', () => {
+ const ok = validateDelegatedSyncOptions({ noBulk: true, lanes: 4, explicitProcessing: ['noEmbed', 'noExtract'], timeoutSeconds: 60 });
+ expect(ok.ok).toBe(true);
+ if (!ok.ok) throw new Error('unreachable');
+ expect(ok.options).toEqual({ noBulk: true, lanes: 4, explicitProcessing: ['noEmbed', 'noExtract'], timeoutSeconds: 60 });
+ for (const lanes of [0, 17, 1.5, '4']) expect(validateDelegatedSyncOptions({ lanes, timeoutSeconds: 60 })).toEqual({ ok: false, error: 'invalid_options:lanes' });
+ for (const explicitProcessing of ['noEmbed', ['repoPath'], [1], ['noEmbed', 'noEmbed', 'noExtract', 'noSchemaPack']]) {
+ expect(validateDelegatedSyncOptions({ explicitProcessing, timeoutSeconds: 60 })).toEqual({ ok: false, error: 'invalid_options:explicitProcessing' });
+ }
+ });
+
+ test('#6317: a registration rides sync_start only in the agreed shape (uuid id, 64-hex credential, lane cli)', () => {
+ const id = '11111111-2222-4333-8444-555555555555', credential = 'a'.repeat(64);
+ expect(isSyncStartRegistration({ id, credential, lane: 'cli' })).toBe(true);
+ expect(isSyncStartRegistration({ id, credential, lane: 'stdio' })).toBe(false);
+ expect(isSyncStartRegistration({ id, credential: 'short', lane: 'cli' })).toBe(false);
+ expect(isSyncStartRegistration({ id: 'not-a-uuid', credential, lane: 'cli' })).toBe(false);
+ expect(isSyncStartRegistration({ id, credential, lane: 'cli', extra: 1 })).toBe(false);
+ expect(isSyncStartRegistration(null)).toBe(false);
+ });
+
test('minimal valid payload: only timeoutSeconds', () => {
const v = validateDelegatedSyncOptions({ timeoutSeconds: 60 });
expect(v.ok).toBe(true);
@@ -107,8 +129,11 @@ describe('validateDelegatedSyncOptions', () => {
// that drift loud.
expect(Object.keys(DELEGATED_SYNC_OPTION_FIELDS).sort()).toEqual([
'dryRun',
+ 'explicitProcessing',
'full',
'includeGitignored',
+ 'lanes',
+ 'noBulk',
'noEmbed',
'noExtract',
'noPull',