Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sync): Postgres delegation rung hands a managed catch-up to the resident serve; classifier admits the catch-up flags; --no-delegate keeps the own consumer on both engines (#6317 D1 a′)
garrytanf0567ef040a6
diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.tsindex 4a9a727887..e80bd18e38 100644--- a/src/commands/sync-delegate.ts+++ b/src/commands/sync-delegate.ts@@ -1,5 +1,5 @@/**- * Serve-delegated sync — the CLI half (decision ladder + poll loop).+ * Serve-delegated sync — the CLI half (decision ladders + poll loop).** On a PGLite brain a live `gbrain serve` holds the single-writer lock for* its lifetime, so `gbrain sync` cannot open the brain (LiveServeLockError@@ -10,7 +10,7 @@* core/context/sync-ipc.ts, execution in core/serve-sync-runner.ts) and this* module polls progress and prints the result.*- * Decision ladder (returns false = fall through to the normal connect path):+ * PGLite decision ladder (returns false = fall through to the normal connect path):* 0. --no-delegate / GBRAIN_SYNC_NO_DELEGATE=1 → false (opt-out).* 1. Non-host brain (mounts) → false — delegation targets the host data dir.* 2. No live holder, or a live NON-serve holder → false (existing behavior:@@ -25,6 +25,23 @@** Every refusal names three ways out: drop the flag (when flag-caused), stop* the serve, or --no-delegate.+ *+ * #6317 (D1 a′), Postgres managed brains: maybeDelegateManagedSyncToServe is+ * the same family one rung later. Postgres has no lock to lose, so the CLI+ * connects as usual and `runSingleSourceSync` asks this ladder right before+ * `performSync`: when a live full `serve` consumer owns this host (the B3+ * heartbeat row in `persistence_consumers`, read through the database, never+ * a socket), the managed drain runs inside that serve as THIS CLI's verified+ * `cli` writer (the registration rides in sync_start) and the CLI prints the+ * drain's own lines from sync_status. The result comes back as a SyncResult,+ * so the caller's printing, JSON envelope and exit verdict are the in-process+ * ones. Every rung that cannot delegate falls back to today's own consumer+ * with ONE actionable line, never a refusal: an unsupported flag, a missing+ * socket, GBRAIN_SERVE_SYNC_IPC=0, an older serve (`unknown_kind` /+ * `stale_serve` / `unsupported_kind`), a serve bound to another source, or a+ * serve that dies mid-drain (the durable cursor resumes in-process). Only an+ * authorization refusal of the hand-off is terminal, thrown as the same+ * OperationError the in-process path would raise.*/import { randomUUID } from 'node:crypto';@@ -33,15 +50,27 @@ import { serr } from '../core/console-prefix.ts';import { probeLivePgliteHolder } from '../core/bootstrap/uninstall.ts';import {IPC_UNAVAILABLE,+ hookResolveSocketForConfig,readIpcSecret,+ readIpcSecretForConfig,requestSyncAbort,requestSyncStart,requestSyncStatus,resolveSocketPath,+ type IpcPathConfig,type SyncStartIpcResult,} from '../core/context/resolve-ipc.ts';-import type { DelegatedSyncOptions, SyncStatusResponse, WireSyncResult } from '../core/context/sync-ipc.ts';-import type { SyncResult } from './sync.ts';+import {+ DELEGATED_SYNC_LANES_MAX,+ type DelegatedSyncOptions,+ type SyncStartRegistration,+ type SyncStatusResponse,+ type WireSyncResult,+} from '../core/context/sync-ipc.ts';+import { OperationError } from '../core/ops/contract.ts';+import type { BrainEngine } from '../core/engine.ts';+import type { ConsumerRow } from '../core/persistence/consumer-heartbeat.ts';+import type { SyncOpts, SyncResult } from './sync.ts';/** Poll cadence for sync_status while a delegated job runs. */const POLL_MS = 1000;@@ -69,11 +98,14 @@ export const WIRE_BOOL_FLAGS: Record<string, keyof DelegatedSyncOptions> = {'--skip-failed': 'skipFailed','--retry-failed': 'retryFailed','--include-gitignored': 'includeGitignored',+ '--no-bulk': 'noBulk',};-/** Value-taking flags the ladder consumes itself (never forwarded verbatim). */-export const VALUE_FLAGS = new Set(['--source', '--timeout', '--hard-deadline']);-/** Flags that are meaningful only outside delegation (or handled pre-ladder). */-export const IGNORED_FLAGS = new Set(['--yes', '--no-delegate', '--no-hard-deadline']);+/** Value-taking flags the ladder consumes itself (`--lanes` is validated and forwarded; the deadlines are derived). */+export const VALUE_FLAGS = new Set(['--source', '--timeout', '--hard-deadline', '--lanes']);+/** Flags that are meaningful only outside delegation, handled pre-ladder, or rendered by this client (`--json`). */+export const IGNORED_FLAGS = new Set(['--yes', '--no-delegate', '--no-hard-deadline', '--json']);+/** `--no-lanes` is `--lanes 1` (`src/commands/sync/args.ts`). */+const NO_LANES_FLAG = '--no-lanes';export type ParsedDelegatedArgs =| { ok: true; options: Omit<DelegatedSyncOptions, 'timeoutSeconds'>; explicitSource: string | null }@@ -92,18 +124,29 @@ export function parseDelegatedSyncArgs(args: string[]): ParsedDelegatedArgs {options[WIRE_BOOL_FLAGS[tok]] = true;continue;}+ if (tok === NO_LANES_FLAG) {+ options.lanes = 1;+ continue;+ }if (IGNORED_FLAGS.has(tok)) continue;if (VALUE_FLAGS.has(tok)) {const v = args[i + 1];if (v === undefined || v.startsWith('--')) return { ok: false, refused: `${tok} (missing value)` };if (tok === '--source') explicitSource = v;+ if (tok === '--lanes') {+ const lanes = Number(v);+ if (!Number.isInteger(lanes) || lanes < 1 || lanes > DELEGATED_SYNC_LANES_MAX) return { ok: false, refused: `${tok} (invalid value)` };+ options.lanes = lanes;+ }i++; // --timeout / --hard-deadline are consumed by the deadline derivationcontinue;}// Default-deny: subcommands (`trigger`), unsupported flags (--repo,- // --all, --watch, --exclude, --workers, --json, …) and anything future.+ // --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;return { ok: true, options: options as Omit<DelegatedSyncOptions, 'timeoutSeconds'>, explicitSource };}@@ -240,16 +283,7 @@ export async function maybeDelegateSyncToServe(dataDir: string, args: string[]):}const startResp = start as Exclude<SyncStartIpcResult, typeof IPC_UNAVAILABLE | { degraded: string }>;if (!startResp.ok) {- const messages: Record<string, string> = {- busy: `another delegated sync (job ${startResp.jobId ?? '?'}) is already running inside the serve — wait for it to finish and re-run.`,- unauthorized: `the serve rejected the IPC secret — restart the serve (it re-provisions \`.gbrain-ipc-secret\`) and re-run.`,- shutting_down: `the serve is shutting down — re-run in a moment (or after it exits, sync runs directly).`,- source_mismatch: `the serve is bound to a different source than this sync targets — run \`gbrain sync --source <the serve's source>\`, or stop the serve to sync this source directly.`,- unsupported_kind: `the serve has sync delegation disabled (GBRAIN_SERVE_SYNC_IPC=0 or a startup failure).`,- };- const detail = messages[startResp.error ?? ''] ??- `the serve refused the delegated sync (${startResp.error}).`;- serr(`[sync] ${detail} ${remediation(holder.pid, '')}`);+ serr(`[sync] ${startRefusalText(startResp)} ${remediation(holder.pid, '')}`);await setVerdict(1);return true;}@@ -264,31 +298,93 @@ export async function maybeDelegateSyncToServe(dataDir: string, args: string[]):);}- return pollToCompletion({ dataDir, sock, secret, jobId, pid: holder.pid, options });+ const polled = await pollDelegatedJob({+ sock, secret, jobId, pid: holder.pid,+ alive: () => { const still = probeLivePgliteHolder(dataDir); return !!still && still.serve; },+ });+ if (polled.kind === 'lost') { await setVerdict(1); return true; }+ if (polled.kind === 'failed') {+ if (polled.error instanceof OperationError) {+ const { reportPersistenceCliError } = await import('./persistence-delegate.ts');+ if (await reportPersistenceCliError(polled.error, args.includes('--json'))) return true;+ }+ serr(`[sync] delegated sync failed inside the serve: ${polled.error.message}`);+ await setVerdict(1);+ return true;+ }+ await printDelegatedResult(polled.result, options, { args, sourceId: polled.status.sourceId ?? sourceId ?? 'default', json: args.includes('--json') });+ return true;+}++function startRefusalText(resp: { error?: string; jobId?: string }): string {+ const messages: Record<string, string> = {+ busy: `another delegated sync (job ${resp.jobId ?? '?'}) is already running inside the serve — wait for it to finish and re-run.`,+ unauthorized: `the serve rejected the IPC secret — restart the serve (it re-provisions \`.gbrain-ipc-secret\`) and re-run.`,+ shutting_down: `the serve is shutting down — re-run in a moment (or after it exits, sync runs directly).`,+ source_mismatch: `the serve is bound to a different source than this sync targets — run \`gbrain sync --source <the serve's source>\`, or stop the serve to sync this source directly.`,+ unsupported_kind: `the serve has sync delegation disabled (GBRAIN_SERVE_SYNC_IPC=0 or a startup failure).`,+ };+ return messages[resp.error ?? ''] ?? `the serve refused the delegated sync (${resp.error}).`;}-async function pollToCompletion(ctx: {- dataDir: string;+/** The serve's `refusal` / `jobErrorEnvelope` (an OperationError.toJSON()) back into the error the in-process path throws. */+export function operationErrorFromEnvelope(envelope: Record<string, unknown>): OperationError {+ const code = typeof envelope.error === 'string' ? envelope.error : typeof envelope.code === 'string' ? envelope.code : 'unavailable';+ const error = new OperationError(code as OperationError['code'], typeof envelope.message === 'string' ? envelope.message : 'The serve refused the delegated sync.',+ typeof envelope.suggestion === 'string' ? envelope.suggestion : undefined, typeof envelope.docs === 'string' ? envelope.docs : undefined);+ if (typeof envelope.code === 'string' && envelope.code !== code) error.canonical = envelope.code as OperationError['canonical'];+ if (typeof envelope.detail === 'string') error.detail = envelope.detail;+ if (typeof envelope.reason === 'string') error.reason = envelope.reason;+ if (typeof envelope.why === 'string') error.why = envelope.why;+ if (envelope.fix && typeof envelope.fix === 'object') error.fix = envelope.fix as OperationError['fix'];+ if (envelope.contract_version === 1) error.contractVersion = 1;+ return error;+}++type PolledJob =+ | { kind: 'done'; result: WireSyncResult; status: SyncStatusResponse }+ | { kind: 'failed'; error: Error }+ /** The serve died, restarted or stopped answering; the failure was printed. */+ | { kind: 'lost' };++/**+ * Shared poll loop. Prints the job's human lines (a managed drain's own+ * progress, stall and lanes lines) or, for a legacy job, phase changes and+ * banked counts. `signal` (the caller's deadline or interrupt) and Ctrl-C both+ * send sync_abort once and keep polling until the serve settles the typed+ * partial; a second Ctrl-C exits without waiting. `alive` tells a busy serve+ * (transient poll timeouts) from a dead one.+ */+async function pollDelegatedJob(ctx: {sock: string;secret: string;jobId: string;pid: number;- options: DelegatedSyncOptions;-}): Promise<boolean> {- const { dataDir, sock, secret, jobId, pid, options } = ctx;+ alive: () => boolean | Promise<boolean>;+ signal?: AbortSignal;+}): Promise<PolledJob> {+ const { sock, secret, jobId, pid } = ctx;let failures = 0;let lastPhase: string | undefined;let lastBanked: number | undefined;+ let afterLine = 0;let abortRequested = false;- const onSigint = () => {- if (abortRequested) process.exit(130);+ const abort = (why: string): void => {+ if (abortRequested) return;abortRequested = true;- serr('[sync] Ctrl-C — aborting the delegated sync (progress is checkpointed; re-run to resume). Ctrl-C again to exit without waiting.');+ serr(`[sync] ${why} — aborting the delegated sync (progress is checkpointed; re-run to resume).`);void requestSyncAbort(sock, { secret, jobId });+ };+ const onSigint = () => {+ if (abortRequested) process.exit(130);+ abort('Ctrl-C');+ serr('[sync] Ctrl-C again to exit without waiting.');process.once('SIGINT', onSigint);};process.once('SIGINT', onSigint);+ const onAbort = () => abort('deadline reached');+ ctx.signal?.addEventListener('abort', onAbort, { once: true });const crashHint = () =>serr(@@ -300,23 +396,18 @@ async function pollToCompletion(ctx: {try {for (;;) {await new Promise((r) => setTimeout(r, POLL_MS));- const s = await requestSyncStatus(sock, { secret, jobId });+ const s = await requestSyncStatus(sock, { secret, jobId, afterLine });if (s === IPC_UNAVAILABLE || 'degraded' in (s as object)) {failures++;- if (failures % PID_PROBE_EVERY === 0) {- const still = probeLivePgliteHolder(dataDir);- if (!still || !still.serve) {- serr(`[sync] the serve (PID ${pid}) died mid-sync.`);- crashHint();- await setVerdict(1);- return true;- }+ if (failures % PID_PROBE_EVERY === 0 && !(await ctx.alive())) {+ serr(`[sync] the serve (PID ${pid}) died mid-sync.`);+ crashHint();+ return { kind: 'lost' };}if (failures >= MAX_POLL_FAILURES) {serr(`[sync] the serve (PID ${pid}) stopped answering its IPC socket mid-sync.`);crashHint();- await setVerdict(1);- return true;+ return { kind: 'lost' };}continue;}@@ -326,50 +417,204 @@ async function pollToCompletion(ctx: {if (status.error === 'unknown_job') {serr(`[sync] the serve restarted mid-sync (job ${jobId} is gone).`);crashHint();- } else {- serr(`[sync] delegated sync failed: ${status.error}`);+ return { kind: 'lost' };}- await setVerdict(1);- return true;- }- if (status.phase && status.phase !== lastPhase) {- lastPhase = status.phase;- serr(`[sync] serve: ${status.phase}`);+ return { kind: 'failed', error: new Error(`delegated sync failed: ${status.error}`) };}- if (status.bankedFiles !== undefined && status.bankedFiles !== lastBanked) {- lastBanked = status.bankedFiles;- serr(`[sync] serve: banked ${status.bankedFiles} file(s)`);+ if (status.managed) {+ for (const line of status.lines ?? []) {+ process.stderr.write(line.text + '\n');+ afterLine = Math.max(afterLine, line.seq);+ }+ } else {+ if (status.phase && status.phase !== lastPhase) {+ lastPhase = status.phase;+ serr(`[sync] serve: ${status.phase}`);+ }+ if (status.bankedFiles !== undefined && status.bankedFiles !== lastBanked) {+ lastBanked = status.bankedFiles;+ serr(`[sync] serve: banked ${status.bankedFiles} file(s)`);+ }}if (status.state === 'error') {- serr(`[sync] delegated sync failed inside the serve: ${status.jobError ?? 'unknown error'}`);- await setVerdict(1);- return true;- }- if (status.state === 'done' && status.result) {- await printDelegatedResult(status.result, options);- return true;+ return { kind: 'failed', error: status.jobErrorEnvelope ? operationErrorFromEnvelope(status.jobErrorEnvelope) : new Error(status.jobError ?? 'unknown error') };}+ if (status.state === 'done' && status.result) return { kind: 'done', result: status.result, status };// running / aborting → keep polling.}} finally {process.off('SIGINT', onSigint);+ ctx.signal?.removeEventListener('abort', onAbort);}}-async function printDelegatedResult(wire: WireSyncResult, options: DelegatedSyncOptions): Promise<void> {- const { printSyncResult } = await import('./sync.ts');+/** The wire result as the SyncResult the in-process printers take (the page list is capped on the wire). */+export function syncResultFromWire(wire: WireSyncResult): { result: SyncResult; pagesAffectedTotal: number } {const { pagesAffectedTotal, ...rest } = wire;- const result: SyncResult = { ...rest, pagesAffected: wire.pagesAffected };- printSyncResult(result);+ return { result: { ...rest, pagesAffected: wire.pagesAffected }, pagesAffectedTotal };+}++async function printDelegatedResult(wire: WireSyncResult, options: DelegatedSyncOptions, ctx: { args: string[]; sourceId: string; json: boolean }): Promise<void> {+ const { printSyncResult } = await import('./sync.ts');+ const { result, pagesAffectedTotal } = syncResultFromWire(wire);+ const human = ctx.json ? process.stderr : process.stdout;+ printSyncResult(result, human);if (pagesAffectedTotal > wire.pagesAffected.length) {serr(`[sync] (+${pagesAffectedTotal - wire.pagesAffected.length} more pages affected — list truncated for the IPC wire)`);}if (!options.dryRun && !options.noEmbed && result.added + result.modified > 0) {serr('[sync] embeds deferred — the serve drains them in background sweeps (its environment/keys apply).');}+ const { drainJsonFields, formatDrainSummary, syncOutcome } = await import('../core/persistence/sync-drain.ts');+ const { syncResumeCommand } = await import('../core/sync-reconcile.ts');+ const { getCliOptions } = await import('../core/cli-options.ts');+ const resume = syncResumeCommand(ctx.args.filter(a => a !== '--json'), getCliOptions().brain);+ for (const line of formatDrainSummary(result, resume, ctx.sourceId)) human.write(line + '\n');+ if (ctx.json) {+ // The single-source envelope the in-process `--json` path emits (#4888: stdout carries that one document).+ const { buildSingleSyncJsonEnvelope } = await import('../core/sync-embed-backfill.ts');+ const { writeStdoutFinal } = await import('../core/cli-force-exit.ts');+ await writeStdoutFinal(JSON.stringify({ ...buildSingleSyncJsonEnvelope(ctx.sourceId, result),+ ...(result.managedWrite ? { managed_write: result.managedWrite } : {}), ...drainJsonFields(result, resume, ctx.sourceId) }) + '\n');+ }// Mirror runSync's verdict rule (#3068): a pull_failed partial will not- // self-heal — exit non-zero so cron sees the wedge.- if (result.status === 'partial' && result.reason === 'pull_failed') {+ // self-heal — exit non-zero so cron sees the wedge. #5984: a blocked drain too.+ if ((result.status === 'partial' && result.reason === 'pull_failed') || syncOutcome(result) === 'blocked') {await setVerdict(1);}}++// ── #6317: Postgres managed brains ─────────────────────────────────────────++/** Test seams for the Postgres ladder: the brain config, the heartbeat probe and the socket/secret discovery. */+export interface ManagedDelegationDeps {+ config?: IpcPathConfig | null;+ probe?: (engine: BrainEngine) => Promise<ConsumerRow | null>;+ socket?: (sourceId: string) => Promise<{ sock: string | null; secret: string | null }>;+ env?: Record<string, string | undefined>;+}++export type ManagedDelegationOutcome =+ | { kind: 'delegated'; result: SyncResult; pid: number }+ /** Not delegated; `reason` names the rung, `line` is the one line printed (null when nothing was printed). */+ | { kind: 'own_consumer'; reason: 'opted_out' | 'not_host' | 'not_postgres' | 'not_managed' | 'no_owner' | 'owner_not_serve' | 'probe_failed'+ | 'kill_switch' | 'unsupported_flag' | 'no_socket' | 'older_serve' | 'serve_refused' | 'serve_lost'; line: string | null };++const fallbackLine = (pid: number, cause: string, fix = 'Restart that serve on this gbrain version to remove the second consumer.'): string =>+ `[sync] ${cause}; this run uses its own consumer beside the serve (PID ${pid}). ${fix}`;++/**+ * The Postgres rung of the delegation ladder (#6317). Called with the connected+ * engine and the sync's resolved options right before `performSync`; returns+ * the drain's SyncResult when the resident serve ran it, else the rung that+ * kept today's own consumer. Throws the hand-off's authorization refusal+ * (denied, revoked or stdio registration) as the OperationError the in-process+ * `managedSyncAuthority` would have thrown.+ */+export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args: string[], opts: SyncOpts, deps: ManagedDelegationDeps = {}): Promise<ManagedDelegationOutcome> {+ const env = deps.env ?? process.env;+ const own = (reason: Extract<ManagedDelegationOutcome, { kind: 'own_consumer' }>['reason'], line: string | null = null): ManagedDelegationOutcome => {+ if (line) serr(line);+ return { kind: 'own_consumer', reason, line };+ };+ // 0. Opt-outs bypass the ladder before anything is probed or classified.+ if (args.includes('--no-delegate') || env.GBRAIN_SYNC_NO_DELEGATE === '1') return own('opted_out');+ const { resolveBrainId } = await import('../core/brain-resolver.ts');+ const { getCliOptions } = await import('../core/cli-options.ts');+ if (resolveBrainId(getCliOptions().brain) !== 'host') return own('not_host');+ // The host brain's config decides the engine (the PGLite ladder ran pre-connect; a PGLite mount never reaches here).+ const cfg = deps.config !== undefined ? deps.config : (await import('../core/config.ts')).loadConfig();+ if (cfg?.engine !== 'postgres' || !cfg.database_url) return own('not_postgres');+ const sourceId = opts.sourceId ?? 'default';+ // 1. Only a managed source has the two-consumer problem; classic sync keeps its own path.+ const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');+ if (!brain?.enabled) return own('not_managed');+ // 2. The owner probe: the B3 heartbeat row, through the database (the persistence socket does not exist on Postgres).+ let owner: ConsumerRow | null;+ try {+ owner = deps.probe ? await deps.probe(engine) : await (async () => {+ const { probeLiveFullConsumer, consumerIdentity } = await import('../core/persistence/consumer-heartbeat.ts');+ const { localHostId } = await import('../core/persistence/identity.ts');+ return probeLiveFullConsumer(engine, localHostId(), consumerIdentity());+ })();+ } catch (e) {+ return own('probe_failed', `[sync] could not read this host's consumer heartbeat (${e instanceof Error ? e.message : String(e)}); this run uses its own consumer.`);+ }+ if (!owner) return own('no_owner');+ const pid = owner.pid;+ if (owner.kind !== 'serve') {+ return own('owner_not_serve', `[sync] the live write owner on this host is a ${owner.kind} process (PID ${pid}), which cannot host a delegated sync; this run uses its own consumer beside it.`);+ }+ if (env.GBRAIN_SERVE_SYNC_IPC === '0') {+ return own('kill_switch', fallbackLine(pid, 'GBRAIN_SERVE_SYNC_IPC=0 turns serve-delegated sync off', 'Unset it to run the catch-up inside the serve.'));+ }+ // 3. Argv gate (default-deny). On Postgres an unsupported flag keeps today's own consumer instead of refusing.+ const parsed = parseDelegatedSyncArgs(args);+ if (!parsed.ok) {+ return own('unsupported_flag', fallbackLine(pid, `\`${parsed.refused}\` isn't supported through serve-delegated sync`, 'Drop the flag to run the catch-up inside the serve.'));+ }+ // 4. Socket + secret: the serve bound to this source, else the legacy URL-keyed socket.+ const { sock, secret } = deps.socket ? await deps.socket(sourceId)+ : { sock: await hookResolveSocketForConfig(cfg, sourceId), secret: readIpcSecretForConfig(cfg) };+ if (!sock || !existsSync(sock) || !secret) {+ return own('no_socket', fallbackLine(pid, 'the running gbrain serve exposes no sync IPC socket (older gbrain, or GBRAIN_SERVE_SYNC_IPC=0 on the serve)'));+ }+ // 5. The hand-off: this CLI's durable writer registration (the one its own consumer would run under).+ const { registerLocalWriter } = await import('../core/persistence/identity.ts');+ const local = await registerLocalWriter(engine, 'cli');+ const registration: SyncStartRegistration = { id: local.id, credential: local.credential, lane: 'cli' };+ const { parseDurationSeconds } = await import('../core/sync-concurrency.ts');+ const soft = parseDurationSeconds(args.find((_, i) => args[i - 1] === '--timeout'), '--timeout');+ const hard = await deriveDelegatedTimeoutSeconds(args, { env });+ const timeoutSeconds = soft && soft > 0 ? (hard > 0 ? Math.min(soft, hard) : soft) : hard;+ const options: DelegatedSyncOptions = {+ 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] } : {}),+ };+ const clientToken = randomUUID();+ const { probeLiveFullConsumer, consumerIdentity } = await import('../core/persistence/consumer-heartbeat.ts');+ const { localHostId } = await import('../core/persistence/identity.ts');+ const ownerAlive = async (): Promise<boolean> => {+ try {+ const row = deps.probe ? await deps.probe(engine) : await probeLiveFullConsumer(engine, localHostId(), consumerIdentity());+ return !!row && row.pid === pid && row.nonce === owner!.nonce;+ } catch { return true; }+ };+ let start = await requestSyncStart(sock, { secret, clientToken, options, registration });+ if (start === IPC_UNAVAILABLE && await ownerAlive()) start = await requestSyncStart(sock, { secret, clientToken, options, registration });+ if (start === IPC_UNAVAILABLE) {+ return own('no_socket', fallbackLine(pid, 'the running gbrain serve is not answering its IPC socket'));+ }+ if ('degraded' in (start as object)) {+ return own('older_serve', fallbackLine(pid, 'the running gbrain serve predates serve-delegated managed sync'));+ }+ const startResp = start as Exclude<SyncStartIpcResult, typeof IPC_UNAVAILABLE | { degraded: string }>;+ if (!startResp.ok) {+ if (startResp.refusal) throw operationErrorFromEnvelope(startResp.refusal);+ if (startResp.error === 'unsupported_kind') {+ return own('older_serve', fallbackLine(pid, 'the running gbrain serve predates serve-delegated managed sync, or runs with GBRAIN_SERVE_SYNC_IPC=0'));+ }+ if (startResp.error === 'permission_denied') throw operationErrorFromEnvelope({ error: 'permission_denied', message: 'The serve refused this CLI\'s writer registration.' });+ return own('serve_refused', fallbackLine(pid, startRefusalText(startResp).replace(/\.$/, ''), 'Fix that, or let this run finish with its own consumer.'));+ }+ const jobId = startResp.jobId!;+ serr(startResp.completed+ ? `[sync] attached to an already-completed delegated sync inside the serve (job ${jobId}).`+ : `[sync] a live gbrain serve (PID ${pid}) owns this host's writes — running the managed catch-up inside it as this CLI's writer (job ${jobId}; Ctrl-C aborts, the cursor is durable).`);+ const polled = await pollDelegatedJob({ sock, secret, jobId, pid, alive: ownerAlive, signal: opts.signal });+ if (polled.kind === 'lost') return own('serve_lost', '[sync] continuing the catch-up with this process\'s own consumer; the durable cursor resumes where the serve left it.');+ if (polled.kind === 'failed') throw polled.error;+ const { result, pagesAffectedTotal } = syncResultFromWire(polled.result);+ if (pagesAffectedTotal > polled.result.pagesAffected.length) {+ serr(`[sync] (+${pagesAffectedTotal - polled.result.pagesAffected.length} more pages affected — list truncated for the IPC wire)`);+ }+ return { kind: 'delegated', result, pid };+}++function pick<T extends object, K extends keyof T>(source: T, keys: readonly K[]): Partial<Pick<T, K>> {+ const out: Partial<Pick<T, K>> = {};+ for (const key of keys) if (source[key] !== undefined) out[key] = source[key];+ return out;+}diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.tsindex abee269db0..500eee0425 100644--- a/src/commands/sync/args.ts+++ b/src/commands/sync/args.ts@@ -110,11 +110,14 @@ Options:order. Persist with 'gbrain config set sync.lanes N' orGBRAIN_SYNC_LANES; the drain reports what limited it.--no-lanes Same as --lanes 1: one bulk group at a time.- --no-delegate On a PGLite brain with a live 'gbrain serve', sync- normally delegates the run to the serve process over- its IPC socket (the lock owner does the work; embeds- defer to serve's background sweep). This flag (or- GBRAIN_SYNC_NO_DELEGATE=1) opts out — sync then fails+ --no-delegate Keep this process's own write consumer even when a+ live 'gbrain serve' could run the sync. Normally sync+ hands the run to that serve over its IPC socket and+ prints its progress: on PGLite because the serve holds+ the single-writer lock, on a managed Postgres brain so+ the host keeps one write consumer. This flag (or+ GBRAIN_SYNC_NO_DELEGATE=1) opts out: on Postgres the+ sync runs here beside the serve; on PGLite it failsfast if a live serve holds the brain.--no-schema-pack Skip loading the active schema pack (no per-file packregex runs; pages use legacy prefix typing). Escapediff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex 8f5b2523a3..32f876b907 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -128,7 +128,7 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {const resumeCommand = syncResumeCommand(args, getCliOptions().brain);if (syncAll) return await runSyncAll(engine, { ...flags, ...fanout }, { noEmbed, embeddingCredentialError, resumeCommand });- return await runSingleSourceSync(engine, { ...flags, ...fanout }, { sourceId, companyPolicy, noEmbed, resumeCommand });+ return await runSingleSourceSync(engine, { ...flags, ...fanout }, { sourceId, companyPolicy, noEmbed, resumeCommand, args });}async function runSyncBreakLock(@@ -713,14 +713,14 @@ function emitSyncAllEnvelope(input: {async function runSingleSourceSync(engine: BrainEngine,flags: SyncFlags & SyncFanoutFlags,- input: { sourceId: string; companyPolicy: Awaited<ReturnType<typeof getCompanyBrainProfile>> | null; noEmbed: boolean; resumeCommand: string },+ input: { sourceId: string; companyPolicy: Awaited<ReturnType<typeof getCompanyBrainProfile>> | null; noEmbed: boolean; resumeCommand: string; args: string[] },): Promise<void> {const {repoPath, watch, interval, dryRun, full, noPull, noBulk, lanes, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack,explicitProcessing, includeGitignored, workingTree, jsonOut, yesFlag, noAutoEmbed, strategyArg, srcSubpath,excludePatterns, includeHiddenPatterns, concurrency, timeoutSeconds,} = flags;- const { sourceId, companyPolicy, noEmbed, resumeCommand } = input;+ const { sourceId, companyPolicy, noEmbed, resumeCommand, args } = input;// v0.41.13.0 (T6) — single-source --timeout: same per-source AbortController// shape as the --all runOne closure. Timer scoped to this CLI invocation;// try/finally clears it after performSync resolves (or throws).@@ -813,7 +813,10 @@ async function runSingleSourceSync(let result: SyncResult;process.on('SIGINT', onSingleSourceSigint);try {- result = await performSync(engine, opts);+ // #6317 (D1 a′): on a managed Postgres brain whose host a live serve owns, the drain runs inside that serve as this+ // CLI's writer and returns the same SyncResult; every other case keeps this process's own consumer.+ const delegated = companyPolicy ? null : await (await import('../sync-delegate.ts')).maybeDelegateManagedSyncToServe(engine, args, opts);+ result = delegated?.kind === 'delegated' ? delegated.result : await performSync(engine, opts);} finally {if (singleSourceTimer !== undefined) clearTimeout(singleSourceTimer);process.off('SIGINT', onSingleSourceSigint);diff --git a/test/sync-delegate-ladder.test.ts b/test/sync-delegate-ladder.test.tsindex 91e1caee9d..383e9a15ca 100644--- a/test/sync-delegate-ladder.test.ts+++ b/test/sync-delegate-ladder.test.ts@@ -81,6 +81,8 @@ describe('parseDelegatedSyncArgs (default-deny)', () => {expect(r.options).toEqual({full: true, dryRun: true, noPull: true, noEmbed: true, noExtract: true,noSchemaPack: true, skipFailed: true, retryFailed: true, includeGitignored: true,+ // #6317: the processing flags the caller set, so the managed cursor supplies only the rest (#5632).+ explicitProcessing: ['noEmbed', 'noExtract', 'noSchemaPack'],});expect(r.explicitSource).toBe('notes');});@@ -92,7 +94,7 @@ describe('parseDelegatedSyncArgs (default-deny)', () => {test.each([['--repo'], ['--watch'], ['--all'], ['--workers'], ['--concurrency'],- ['--json'], ['--exclude'], ['--src-subpath'], ['--break-lock'],+ ['--exclude'], ['--src-subpath'], ['--break-lock'],['--force-break-lock'], ['--max-age'], ['--missing-path'], ['--parallel'],['--interval'], ['--serial'], ['--strategy'], ['trigger'],['--some-flag-added-in-2027'],@@ -100,6 +102,16 @@ describe('parseDelegatedSyncArgs (default-deny)', () => {expect(parseDelegatedSyncArgs([tok])).toEqual({ ok: false, refused: tok });});+ 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(['--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)' });+ expect(parseDelegatedSyncArgs(['--lanes'])).toEqual({ ok: false, refused: '--lanes (missing value)' });+ });+test('a value flag with a missing/flag-shaped value refuses loudly', () => {expect(parseDelegatedSyncArgs(['--source'])).toEqual({ ok: false, refused: '--source (missing value)' });expect(parseDelegatedSyncArgs(['--source', '--full'])).toEqual({ ok: false, refused: '--source (missing value)' });