Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync: one exported flag table; serve, IPC and owner-lane allowlists derive from it (#6712 PR 2, L3)

garrytan11676ccb3095
diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.ts
index a527e65632..acbbf62fb7 100644
--- a/src/commands/sync-delegate.ts
+++ b/src/commands/sync-delegate.ts
@@ -68,6 +68,7 @@ import {
type WireSyncResult,
} from '../core/context/sync-ipc.ts';
import { OperationError } from '../core/ops/contract.ts';
+import { SYNC_FLAGS, syncFlagsRouted, type SyncFlagSpec } from '../core/sync-flags.ts';
import type { BrainEngine } from '../core/engine.ts';
import type { ConsumerRow } from '../core/persistence/consumer-heartbeat.ts';
import type { SyncOpts, SyncResult } from './sync.ts';
@@ -84,28 +85,17 @@ const MAX_POLL_FAILURES = 60;
const PID_PROBE_EVERY = 5;
/**
- * Flags forwardable over the wire (boolean → DelegatedSyncOptions field).
- * Everything not in this table, VALUE_FLAGS, or IGNORED_FLAGS refuses —
- * default-deny is what keeps a future flag from being silently dropped.
+ * The serve hand-off's view of the one sync flag table (`src/core/sync-flags.ts`). Everything the table does not
+ * route through the serve refuses: default-deny is what keeps a future flag from being silently dropped.
*/
-export const WIRE_BOOL_FLAGS: Record<string, keyof DelegatedSyncOptions> = {
- '--full': 'full',
- '--dry-run': 'dryRun',
- '--no-pull': 'noPull',
- '--no-embed': 'noEmbed',
- '--no-extract': 'noExtract',
- '--no-schema-pack': 'noSchemaPack',
- '--skip-failed': 'skipFailed',
- '--retry-failed': 'retryFailed',
- '--include-gitignored': 'includeGitignored',
- '--no-bulk': 'noBulk',
-};
+const SERVE_FLAGS = SYNC_FLAGS as Record<string, SyncFlagSpec>;
+/** Boolean flags forwarded over the wire (flag → DelegatedSyncOptions field). */
+export const WIRE_BOOL_FLAGS: Record<string, keyof DelegatedSyncOptions> = Object.fromEntries(syncFlagsRouted('serve', 'forward')
+ .filter(flag => SERVE_FLAGS[flag].arity === 'boolean' && SERVE_FLAGS[flag].sets === undefined).map(flag => [flag, SERVE_FLAGS[flag].field as keyof DelegatedSyncOptions]));
/** 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']);
+export const VALUE_FLAGS = new Set<string>([...syncFlagsRouted('serve', 'client'), ...syncFlagsRouted('serve', 'forward')].filter(flag => SERVE_FLAGS[flag].arity === 'value'));
/** 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 const IGNORED_FLAGS = new Set<string>(syncFlagsRouted('serve', 'client').filter(flag => SERVE_FLAGS[flag].arity === 'boolean'));
export type ParsedDelegatedArgs =
| { ok: true; options: Omit<DelegatedSyncOptions, 'timeoutSeconds'>; explicitSource: string | null }
@@ -124,8 +114,9 @@ export function parseDelegatedSyncArgs(args: string[]): ParsedDelegatedArgs {
options[WIRE_BOOL_FLAGS[tok]] = true;
continue;
}
- if (tok === NO_LANES_FLAG) {
- options.lanes = 1;
+ const fixed = SERVE_FLAGS[tok];
+ if (fixed?.serve === 'forward' && fixed.sets !== undefined && fixed.field) {
+ options[fixed.field] = fixed.sets;
continue;
}
if (IGNORED_FLAGS.has(tok)) continue;
@@ -581,7 +572,8 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:
const options: DelegatedSyncOptions = {
// #6696 (A5): an operator's sync keeps the capacity background producers leave free.
sourceId, timeoutSeconds, origin: 'interactive',
- ...pick(opts, ['dryRun', 'full', 'noPull', 'noEmbed', 'noExtract', 'noSchemaPack', 'skipFailed', 'retryFailed', 'includeGitignored', 'noBulk'] as const),
+ // The table's forwarded booleans only: a field a newer gbrain retired (src/core/wire-skew.ts) is never in it, so it is never sent.
+ ...pick(opts as unknown as Record<string, boolean | undefined>, Object.values(WIRE_BOOL_FLAGS)) as Partial<DelegatedSyncOptions>,
...(opts.lanes !== undefined ? { lanes: opts.lanes } : {}),
// Sent only when set, so a serve that predates the field keeps accepting every run without a deferral.
...(opts.embedDeferred ? { embedDeferred: true } : {}),
diff --git a/src/commands/sync-persistence-delegate.ts b/src/commands/sync-persistence-delegate.ts
index 3cac9ece96..aedb668624 100644
--- a/src/commands/sync-persistence-delegate.ts
+++ b/src/commands/sync-persistence-delegate.ts
@@ -9,7 +9,8 @@ import { OperationError, opError } from '../core/ops/contract.ts';
import { readFix } from '../core/ops/op-fix.ts';
import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';
import { PersistenceIpcTransportError } from '../core/persistence/ipc.ts';
-import { SYNC_BOOLEAN_FLAGS, SYNC_VALUE_FLAGS, validateSyncWireParams } from '../core/persistence/sync-wire.ts';
+import { SYNC_BOOLEAN_FLAGS, SYNC_CLIENT_FLAGS, SYNC_VALUE_FLAGS, validateSyncWireParams } from '../core/persistence/sync-wire.ts';
+import { SYNC_FLAGS, type SyncFlagSpec } from '../core/sync-flags.ts';
import { deriveDelegatedTimeoutSeconds } from './sync-delegate.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
@@ -28,13 +29,16 @@ export async function parsePersistenceSyncArgs(args:string[],cwd=process.cwd())
const options:Record<string,unknown>={};
for(let i=0;i<args.length;i++) {
const arg=args[i];
- const boolean=SYNC_BOOLEAN_FLAGS[arg as keyof typeof SYNC_BOOLEAN_FLAGS];
+ const boolean=SYNC_BOOLEAN_FLAGS[arg];
if(boolean){options[boolean]=true;continue;}
- if(['--json','--yes','--no-hard-deadline'].includes(arg))continue;
- if(['--timeout','--hard-deadline'].includes(arg)){if(!args[++i]||args[i].startsWith('--'))throw invalid(`${arg} requires a value.`,`Give ${arg} a duration right after it, e.g. ${arg} 10m.`);continue;}
- const key=SYNC_VALUE_FLAGS[arg as keyof typeof SYNC_VALUE_FLAGS];
+ // The client's own flags (output, deadlines) and the ones a PGLite owner has no use for (--lanes: no bulk lanes).
+ if(SYNC_CLIENT_FLAGS.has(arg)){
+ if((SYNC_FLAGS as Record<string,SyncFlagSpec>)[arg]!.arity==='value'&&(!args[++i]||args[i].startsWith('--')))throw invalid(`${arg} requires a value.`,`Give ${arg} its value right after it, e.g. ${arg==='--lanes'?`${arg} 4`:`${arg} 10m`}.`);
+ continue;
+ }
+ const key=SYNC_VALUE_FLAGS[arg];
if(!key)throw invalid(`Unsupported owner-delegated sync option: ${arg.split('=')[0]}.`,
- `Remove ${arg.split('=')[0]}; while the running serve holds the brain, sync runs inside it and accepts ${[...Object.keys(SYNC_BOOLEAN_FLAGS),...Object.keys(SYNC_VALUE_FLAGS),'--timeout','--hard-deadline','--json','--yes'].join(', ')}.`);
+ `Remove ${arg.split('=')[0]}; while the running serve holds the brain, sync runs inside it and accepts ${[...Object.keys(SYNC_BOOLEAN_FLAGS),...Object.keys(SYNC_VALUE_FLAGS),...SYNC_CLIENT_FLAGS].join(', ')}.`);
const value=args[++i];if(!value||value.startsWith('--'))throw invalid(`${arg} requires a value.`,`Give ${arg} its value right after it, as ${arg} VALUE.`);
if(key==='exclude'||key==='includeHidden')options[key]=[...(options[key] as string[]??[]),value];
else options[key]=key==='repoPath'?resolve(cwd,value):value;
diff --git a/src/core/context/sync-ipc.ts b/src/core/context/sync-ipc.ts
index 5676b3d0b3..9fb250d506 100644
--- a/src/core/context/sync-ipc.ts
+++ b/src/core/context/sync-ipc.ts
@@ -24,6 +24,8 @@
*/
import { isValidSourceId } from '../source-id.ts';
+import { syncWireFields, type SyncWireType } from '../sync-flags.ts';
+import { retiredWireFields } from '../wire-skew.ts';
import type { SyncResult } from '../../commands/sync.ts';
import type { DrainNext, DrainReport } from '../persistence/sync-drain.ts';
@@ -41,28 +43,17 @@ import type { DrainNext, DrainReport } from '../persistence/sync-drain.ts';
* drain (absent → the serve sweep drains them later).
*/
export const DELEGATED_SYNC_OPTION_FIELDS = {
+ // The flags the one sync flag table forwards through the serve (src/core/sync-flags.ts) ...
+ ...syncWireFields('serve'),
+ // ... and the fields the client derives rather than parses.
sourceId: 'string',
- dryRun: 'boolean',
- full: 'boolean',
- noPull: 'boolean',
- noEmbed: 'boolean',
- noExtract: 'boolean',
- noSchemaPack: 'boolean',
- skipFailed: 'boolean',
- retryFailed: 'boolean',
- includeGitignored: 'boolean',
- noBulk: 'boolean',
- lanes: 'number',
- explicitProcessing: 'string[]',
embedDeferred: 'boolean',
timeoutSeconds: 'number',
origin: 'string',
-} as const;
+} as const satisfies Record<string, SyncWireType>;
/** `--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;
@@ -100,7 +91,8 @@ export interface DelegatedSyncOptions {
}
export type DelegatedSyncValidation =
- | { ok: true; options: DelegatedSyncOptions }
+ /** `ignored`: retired fields an older client sent (src/core/wire-skew.ts), accepted and dropped. */
+ | { ok: true; options: DelegatedSyncOptions; ignored?: string[] }
| { ok: false; error: string };
/**
@@ -115,13 +107,22 @@ export function validateDelegatedSyncOptions(raw: unknown): DelegatedSyncValidat
return { ok: false, error: 'invalid_options:options' };
}
const rec = raw as Record<string, unknown>;
+ const retired = retiredWireFields('serve');
+ const ignored: string[] = [];
for (const key of Object.keys(rec)) {
+ const window = retired.get(key);
+ if (window) {
+ // Accepted from an older client and ignored until its window in src/core/wire-skew.ts closes.
+ if (rec[key] !== undefined && !window.accepts(rec[key])) return { ok: false, error: `invalid_options:${key}` };
+ ignored.push(key);
+ continue;
+ }
if (!(key in DELEGATED_SYNC_OPTION_FIELDS)) {
return { ok: false, error: `invalid_options:${key}` };
}
}
const out: Record<string, unknown> = {};
- for (const [key, type] of Object.entries(DELEGATED_SYNC_OPTION_FIELDS)) {
+ for (const [key, type] of Object.entries(DELEGATED_SYNC_OPTION_FIELDS) as Array<[string, SyncWireType]>) {
const v = rec[key];
if (v === undefined) continue;
if (type === 'string[]') {
@@ -135,14 +136,6 @@ export function validateDelegatedSyncOptions(raw: unknown): DelegatedSyncValidat
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' };
- }
- // #6712 PR 1: accepted from an older CLI and ignored (WIRE_SKEW_WINDOWS.explicitProcessing); the cursor's opt-outs are inherited.
- delete out.explicitProcessing;
- }
if (out.origin !== undefined && out.origin !== 'interactive' && out.origin !== 'background') {
return { ok: false, error: 'invalid_options:origin' };
}
@@ -154,7 +147,7 @@ export function validateDelegatedSyncOptions(raw: unknown): DelegatedSyncValidat
if (out.sourceId !== undefined && !isValidSourceId(out.sourceId as string)) {
return { ok: false, error: 'invalid_options:sourceId' };
}
- return { ok: true, options: out as unknown as DelegatedSyncOptions };
+ return { ok: true, options: out as unknown as DelegatedSyncOptions, ...(ignored.length ? { ignored } : {}) };
}
// ── Progress + result shapes ───────────────────────────────────────────────
diff --git a/src/core/persistence/sync-administration.ts b/src/core/persistence/sync-administration.ts
index ca75de5891..0559c10cbe 100644
--- a/src/core/persistence/sync-administration.ts
+++ b/src/core/persistence/sync-administration.ts
@@ -5,6 +5,7 @@ import { currentVerifiedLocalWriter } from './identity.ts';
import { submissionAuthority } from './authority.ts';
import type { OperationContext } from '../ops/contract.ts';
import { validateSyncWireParams } from './sync-wire.ts';
+import { retiredWireNotice } from '../wire-skew.ts';
import { readManagedMode } from './managed-mode.ts';
import { trustedCliRequired } from '../ops/op-fix.ts';
@@ -13,6 +14,7 @@ export async function runAuthenticatedSyncSlice(engine: BrainEngine, params: Rec
const verified=currentVerifiedLocalWriter();
if(!verified||verified.remote||verified.principal.kind!=='local_cli')throw trustedCliRequired('Sync requires a current trusted CLI registration.');
const wire=validateSyncWireParams(params);
+ if(wire.ignored)console.error(retiredWireNotice(wire.ignored));
const sourceId=await resolveSourceId(engine,wire.options.sourceId??null,wire.cwd,{skipLocalSignals:true});
const [source]=await engine.executeRaw<{incarnation:string;archived:boolean}>('SELECT incarnation,archived FROM sources WHERE id=$1',[sourceId]);
if(!source||source.archived)throw opError('source_changed','The selected sync source is unavailable.',
diff --git a/src/core/persistence/sync-wire.ts b/src/core/persistence/sync-wire.ts
index 25b3d3aad9..c7b5ebc931 100644
--- a/src/core/persistence/sync-wire.ts
+++ b/src/core/persistence/sync-wire.ts
@@ -1,17 +1,18 @@
import { isAbsolute } from 'node:path';
import type { SyncOpts } from '../../commands/sync.ts';
import { opError } from '../ops/contract.ts';
-import { SYNC_PROCESSING_KEYS } from './sync-authority.ts';
-import { WIRE_SKEW_WINDOWS } from '../wire-skew.ts';
+import { SYNC_FLAGS, syncFlagsRouted, syncWireFields, type SyncFlagSpec } from '../sync-flags.ts';
+import { retiredWireFields } from '../wire-skew.ts';
-export const SYNC_BOOLEAN_FLAGS = {
- '--full':'full','--dry-run':'dryRun','--no-pull':'noPull','--no-embed':'noEmbed','--no-extract':'noExtract',
- '--no-schema-pack':'noSchemaPack','--retry-failed':'retryFailed','--skip-failed':'skipFailed',
- '--include-gitignored':'includeGitignored','--working-tree':'workingTree','--reset-checkpoint':'resetCheckpoint','--no-bulk':'noBulk',
-} as const;
-export const SYNC_VALUE_FLAGS = { '--source':'sourceId','--repo':'repoPath','--src-subpath':'srcSubpath','--strategy':'strategy',
- '--exclude':'exclude','--include-hidden':'includeHidden' } as const;
-export interface SyncWireParams { options: SyncOpts; cwd: string; timeoutSeconds: number; }
+const OWNER_FLAGS = SYNC_FLAGS as Record<string, SyncFlagSpec>;
+const forwarded = syncFlagsRouted('owner', 'forward');
+/** The owner lane's view of the one sync flag table (`src/core/sync-flags.ts`): boolean flags it forwards. */
+export const SYNC_BOOLEAN_FLAGS: Record<string, string> = Object.fromEntries(forwarded.filter(flag => OWNER_FLAGS[flag].arity === 'boolean').map(flag => [flag, OWNER_FLAGS[flag].field!]));
+/** Value flags it forwards (`--exclude` and `--include-hidden` repeat). */
+export const SYNC_VALUE_FLAGS: Record<string, string> = Object.fromEntries(forwarded.filter(flag => OWNER_FLAGS[flag].arity !== 'boolean').map(flag => [flag, OWNER_FLAGS[flag].field!]));
+/** Flags the CLI consumes itself or that mean nothing to a PGLite owner (`--lanes`: PGLite runs no bulk lanes); never sent. */
+export const SYNC_CLIENT_FLAGS: ReadonlySet<string> = new Set(syncFlagsRouted('owner', 'client'));
+export interface SyncWireParams { options: SyncOpts; cwd: string; timeoutSeconds: number; ignored?: string[] }
const invalid = () => opError('invalid_params','Invalid or unsupported local sync options.',
'Run gbrain sync from the CLI (gbrain sync --help lists its flags); it builds the options this owner lane accepts.');
export function validateSyncWireParams(value: Record<string,unknown>): SyncWireParams {
@@ -19,19 +20,19 @@ export function validateSyncWireParams(value: Record<string,unknown>): SyncWireP
!isAbsolute(value.cwd) || value.cwd.length>32768 || value.cwd.includes('\0') || typeof value.timeoutSeconds!=='number' ||
!Number.isInteger(value.timeoutSeconds) || value.timeoutSeconds<0 || value.timeoutSeconds>86400 ||
!value.options || typeof value.options!=='object' || Array.isArray(value.options)) throw invalid();
- const booleanFields=new Set<string>(Object.values(SYNC_BOOLEAN_FLAGS));
- const stringFields=new Set<string>(['sourceId','repoPath','srcSubpath','strategy']);
+ const fields=syncWireFields('owner'), retired=retiredWireFields('owner'), ignored:string[]=[];
+ const options:Record<string,unknown>={};
for(const [key,item] of Object.entries(value.options)) {
- if (booleanFields.has(key)) { if(typeof item!=='boolean')throw invalid(); }
- else if(stringFields.has(key)) { if(typeof item!=='string'||!item||item.length>32768||item.includes('\0'))throw invalid(); }
- else if(['exclude','includeHidden'].includes(key)) {
+ const window=retired.get(key);
+ if(window) { if(!window.accepts(item))throw invalid(); ignored.push(key); continue; }
+ const type=fields[key];
+ if(type==='boolean') { if(typeof item!=='boolean')throw invalid(); }
+ else if(type==='string') { if(typeof item!=='string'||!item||item.length>32768||item.includes('\0'))throw invalid(); }
+ else if(type==='string[]') {
if(!Array.isArray(item)||item.length>256||item.some(v=>typeof v!=='string'||!v||v.length>4096||v.includes('\0')))throw invalid();
- } else if(key===WIRE_SKEW_WINDOWS.explicitProcessing.field) {
- // #6712 PR 1: accepted from an older client and ignored until the window in wire-skew.ts closes.
- if(!Array.isArray(item)||new Set(item).size!==item.length||item.some(v=>!(SYNC_PROCESSING_KEYS as readonly unknown[]).includes(v)))throw invalid();
} else throw invalid();
+ options[key]=item;
}
- const { [WIRE_SKEW_WINDOWS.explicitProcessing.field]: _ignored, ...options } = value.options as SyncOpts & Record<string, unknown>;
- if(options.strategy&&!['markdown','code','auto'].includes(options.strategy))throw invalid();
- return {options:{...options},cwd:value.cwd,timeoutSeconds:value.timeoutSeconds};
+ if(options.strategy&&!['markdown','code','auto'].includes(options.strategy as string))throw invalid();
+ return {options:options as SyncOpts,cwd:value.cwd,timeoutSeconds:value.timeoutSeconds,...(ignored.length?{ignored}:{})};
}
diff --git a/src/core/serve-sync-runner.ts b/src/core/serve-sync-runner.ts
index 2eb24675c3..96f03da56c 100644
--- a/src/core/serve-sync-runner.ts
+++ b/src/core/serve-sync-runner.ts
@@ -57,6 +57,7 @@
import { isAdmissionOrigin, withAdmissionOrigin } from './persistence/admission-origin.ts';
import { randomUUID } from 'node:crypto';
import { withLegacySyncDelegation } from './persistence/sync-authority.ts';
+import { retiredWireNotice } from './wire-skew.ts';
import { verifyLocalWriter, withVerifiedLocalRegistration } from './persistence/identity.ts';
import { readManagedMode } from './persistence/managed-mode.ts';
import { OperationError } from './ops/contract.ts';
@@ -213,6 +214,12 @@ function startDelegatedSyncScoped(
settled: Promise.resolve(),
};
current = job;
+ // An older client's retired fields (src/core/wire-skew.ts) were dropped: say so in the serve log and to that client.
+ if (v.ignored) {
+ const notice = retiredWireNotice(v.ignored);
+ log(notice);
+ job.lines.push({ seq: ++job.lineSeq, text: notice });
+ }
ensureDrainerRegistered();
// Per-job hard deadline: 0 is the single unbounded encoding (an explicit
diff --git a/src/core/sync-flags.ts b/src/core/sync-flags.ts
new file mode 100644
index 0000000000..c74cc38bec
--- /dev/null
+++ b/src/core/sync-flags.ts
@@ -0,0 +1,95 @@
+/**
+ * #6712 PR 2 (L3): every `gbrain sync` flag in one table, with where it travels when the run is handed to a resident
+ * process. The serve-delegation ladder (`src/commands/sync-delegate.ts`), its wire validator
+ * (`src/core/context/sync-ipc.ts`) and the PGLite owner lane (`src/commands/sync-persistence-delegate.ts`,
+ * `src/core/persistence/sync-wire.ts`) derive their allowlists from it, so a flag is classified once.
+ *
+ * Routes, per hand-off:
+ * - `forward`: the flag's `field` goes on the wire and the resident process runs with it.
+ * - `client`: the client consumes the flag itself (deadlines, output, the opt-out) or it means nothing to that
+ * resident (`--lanes` on the PGLite owner, which never runs bulk lanes); it is accepted and never sent.
+ * - `refuse`: the hand-off cannot honor it. The serve ladder refuses it by name (PGLite) or keeps the run in this
+ * process (Postgres); the owner lane refuses it.
+ *
+ * Fields a newer gbrain stopped using stay readable from an older peer for a window in `src/core/wire-skew.ts`; they
+ * are never in this table, so a newer client never sends them.
+ */
+
+export type SyncFlagRoute = 'forward' | 'client' | 'refuse';
+export type SyncWireType = 'boolean' | 'number' | 'string' | 'string[]';
+
+export interface SyncFlagSpec {
+ /** `boolean`: presence sets the field; `value`: one value; `repeat`: one value per occurrence. */
+ arity: 'boolean' | 'value' | 'repeat';
+ /** The SyncOpts and wire field the flag sets (none for flags the client consumes). */
+ field?: string;
+ /** The wire type of `field`. */
+ type?: SyncWireType;
+ /** A fixed value instead of `true` (`--no-lanes` is `--lanes 1`). */
+ sets?: number;
+ /** Serve-delegated sync (`sync_start` over the serve's IPC socket). */
+ serve: SyncFlagRoute;
+ /** The PGLite persistence owner lane (`writer_sync`). */
+ owner: SyncFlagRoute;
+}
+
+const bool = (field: string, serve: SyncFlagRoute, owner: SyncFlagRoute): SyncFlagSpec => ({ arity: 'boolean', field, type: 'boolean', serve, owner });
+const local = (arity: SyncFlagSpec['arity'], serve: SyncFlagRoute = 'refuse', owner: SyncFlagRoute = 'refuse'): SyncFlagSpec => ({ arity, serve, owner });
+
+export const SYNC_FLAGS = {
+ '--source': { arity: 'value', field: 'sourceId', type: 'string', serve: 'client', owner: 'forward' },
+ '--full': bool('full', 'forward', 'forward'),
+ '--dry-run': bool('dryRun', 'forward', 'forward'),
+ '--no-pull': bool('noPull', 'forward', 'forward'),
+ '--no-embed': bool('noEmbed', 'forward', 'forward'),
+ '--no-extract': bool('noExtract', 'forward', 'forward'),
+ '--no-schema-pack': bool('noSchemaPack', 'forward', 'forward'),
+ '--skip-failed': bool('skipFailed', 'forward', 'forward'),
+ '--retry-failed': bool('retryFailed', 'forward', 'forward'),
+ '--include-gitignored': bool('includeGitignored', 'forward', 'forward'),
+ '--no-bulk': bool('noBulk', 'forward', 'forward'),
+ '--working-tree': bool('workingTree', 'refuse', 'forward'),
+ '--reset-checkpoint': bool('resetCheckpoint', 'refuse', 'forward'),
+ '--lanes': { arity: 'value', field: 'lanes', type: 'number', serve: 'forward', owner: 'client' },
+ '--no-lanes': { arity: 'boolean', field: 'lanes', type: 'number', sets: 1, serve: 'forward', owner: 'client' },
+ '--repo': { arity: 'value', field: 'repoPath', type: 'string', serve: 'refuse', owner: 'forward' },
+ '--src-subpath': { arity: 'value', field: 'srcSubpath', type: 'string', serve: 'refuse', owner: 'forward' },
+ '--strategy': { arity: 'value', field: 'strategy', type: 'string', serve: 'refuse', owner: 'forward' },
+ '--exclude': { arity: 'repeat', field: 'exclude', type: 'string[]', serve: 'refuse', owner: 'forward' },
+ '--include-hidden': { arity: 'repeat', field: 'includeHidden', type: 'string[]', serve: 'refuse', owner: 'forward' },
+ '--timeout': local('value', 'client', 'client'),
+ '--hard-deadline': local('value', 'client', 'client'),
+ '--no-hard-deadline': local('boolean', 'client', 'client'),
+ '--json': local('boolean', 'client', 'client'),
+ '--yes': local('boolean', 'client', 'client'),
+ '--no-delegate': local('boolean', 'client', 'client'),
+ '--all': local('boolean'),
+ '--watch': local('boolean'),
+ '--interval': local('value'),
+ '--workers': local('value'),
+ '--concurrency': local('value'),
+ '--parallel': local('value'),
+ '--serial': local('boolean'),
+ '--max-sources': local('value'),
+ '--no-auto-embed': local('boolean'),
+ '--missing-path': local('value'),
+ '--acknowledge-managed': local('boolean'),
+ '--break-lock': local('boolean'),
+ '--force-break-lock': local('boolean'),
+ '--max-age': local('value'),
+} as const satisfies Record<string, SyncFlagSpec>;
+
+export type SyncFlag = keyof typeof SYNC_FLAGS;
+type Lane = 'serve' | 'owner';
+
+/** The flags a hand-off takes the given route for. */
+export function syncFlagsRouted(lane: Lane, route: SyncFlagRoute): SyncFlag[] {
+ return (Object.keys(SYNC_FLAGS) as SyncFlag[]).filter(flag => (SYNC_FLAGS[flag] as SyncFlagSpec)[lane] === route);
+}
+
+/** The wire fields a hand-off forwards, with their types (one entry per field). */
+export function syncWireFields(lane: Lane): Record<string, SyncWireType> {
+ const out: Record<string, SyncWireType> = {};
+ for (const spec of Object.values(SYNC_FLAGS) as SyncFlagSpec[]) if (spec[lane] === 'forward' && spec.field && spec.type) out[spec.field] = spec.type;
+ return out;
+}
diff --git a/src/core/wire-skew.ts b/src/core/wire-skew.ts
index ef1795aa02..a6bc7032d0 100644
--- a/src/core/wire-skew.ts
+++ b/src/core/wire-skew.ts
@@ -1,14 +1,60 @@
/**
- * Wire-compatibility windows: fields a gbrain process still accepts from an older peer after it stopped using them.
+ * Compatibility windows, recorded in one place: wire fields a gbrain process still accepts from an older peer after it
+ * stopped using them, and config keys a published notice names as the way back.
*
* Master ships many PATCH releases a day, so a window counted in releases lasts hours. Each window is a calendar
- * period plus a version floor: a field is accepted (validated, then ignored) until `accept_until`, and only peers below
- * `floor` still send it. After `accept_until` the field may be deleted from the wire tables that cite its entry here.
+ * period plus a version floor.
+ * - A retired wire field is accepted (validated by shape, ignored, and noted) until `accept_until`, and only peers
+ * below `floor` still send it. A newer client never sends it: the one sync flag table (`src/core/sync-flags.ts`)
+ * does not list it. After `accept_until` the field may be deleted from here and from the validators.
+ * - A rollback key stays readable and honored at least until `honored_until`, by every release from `floor` on; the
+ * notice or migration that names it (`named_in`) promised users that way back. It is listed as a rollback key,
+ * never as a tunable (`src/core/sync-config-keys.ts`).
*/
-export interface WireSkewWindow { field: string; floor: string; accept_until: string; why: string }
+export type SyncWire = 'serve' | 'owner';
+export interface WireSkewWindow {
+ field: string;
+ floor: string;
+ accept_until: string;
+ why: string;
+ /** The hand-offs that still accept it: serve delegation (`sync-ipc.ts`) and the PGLite owner lane (`sync-wire.ts`). */
+ wires: readonly SyncWire[];
+ /** The shape an older peer sends; anything else is refused as an invalid option. */
+ accepts: (value: unknown) => boolean;
+}
+
+const PROCESSING_KEYS: readonly unknown[] = ['noEmbed', 'noExtract', 'noSchemaPack'];
export const WIRE_SKEW_WINDOWS = {
/** #6712 PR 1: the managed cursor's processing options are inherited, so the explicit-flag list no longer decides anything. */
- explicitProcessing: { field: 'explicitProcessing', floor: '0.60.255.0', accept_until: '2026-11-14',
+ explicitProcessing: { field: 'explicitProcessing', floor: '0.60.255.0', accept_until: '2026-11-14', wires: ['serve', 'owner'],
+ accepts: value => Array.isArray(value) && new Set(value).size === value.length && value.every(item => PROCESSING_KEYS.includes(item)),
why: 'Sync clients below the floor send the processing flags their user typed (#6317, #6696); a resume now inherits the cursor\'s opt-outs instead.' },
} as const satisfies Record<string, WireSkewWindow>;
+
+/** The retired fields one hand-off still accepts, by field name. */
+export function retiredWireFields(wire: SyncWire): ReadonlyMap<string, WireSkewWindow> {
+ return new Map((Object.values(WIRE_SKEW_WINDOWS) as WireSkewWindow[]).filter(window => window.wires.includes(wire)).map(window => [window.field, window]));
+}
+
+/** The one notice a resident prints when it ignores retired fields an older client sent. */
+export function retiredWireNotice(fields: readonly string[]): string {
+ const windows = fields.map(field => (Object.values(WIRE_SKEW_WINDOWS) as WireSkewWindow[]).find(window => window.field === field)!);
+ return `[gbrain notice] this gbrain ignores ${windows.map(window => `\`${window.field}\` (sent by gbrain below ${window.floor}; accepted until ${window.accept_until})`).join(', ')} `
+ + 'from an older sync client and runs without it. Upgrade the gbrain that runs `gbrain sync` to match this one.';
+}
+
+export interface ConfigRollbackWindow { key: string; floor: string; honored_until: string; named_in: string; restores: string }
+
+export const CONFIG_ROLLBACK_WINDOWS = {
+ 'sync.job_drain': { key: 'sync.job_drain', floor: '0.60.256.0', honored_until: '2027-01-14', named_in: '0.60.233.0 behavior notice (#6706)',
+ restores: 'single-pass managed `sync` jobs instead of draining to the job deadline' },
+ 'sync.foreground_priority': { key: 'sync.foreground_priority', floor: '0.60.256.0', honored_until: '2027-01-14', named_in: 'docs/guides/live-sync.md (#5984)',
+ restores: 'first-in-first-out bulk groups instead of letting foreground writes go first' },
+ 'sync.federated_v2': { key: 'sync.federated_v2', floor: '0.60.256.0', honored_until: '2027-01-14', named_in: 'skills/migrations/v0.40.5.md',
+ restores: 'the v0.39 sequential sync --all instead of the federated v2 path' },
+ 'sync.waive_batch': { key: 'sync.waive_batch', floor: '0.60.256.0', honored_until: '2027-01-14', named_in: '#5984 behavior notice',
+ restores: 'one waived entry per transaction instead of batched waivers' },
+ 'sync.bulk': { key: 'sync.bulk', floor: '0.60.256.0', honored_until: '2027-01-14', named_in: '#5984 behavior notice and docs/guides/live-sync.md',
+ restores: 'one page per transaction on managed Postgres sync instead of bulk groups' },
+} as const satisfies Record<string, ConfigRollbackWindow>;
diff --git a/test/context/sync-ipc-validation.test.ts b/test/context/sync-ipc-validation.test.ts
index 6b169bde38..c7c141ad69 100644
--- a/test/context/sync-ipc-validation.test.ts
+++ b/test/context/sync-ipc-validation.test.ts
@@ -138,7 +138,6 @@ describe('validateDelegatedSyncOptions', () => {
expect(Object.keys(DELEGATED_SYNC_OPTION_FIELDS).sort()).toEqual([
'dryRun',
'embedDeferred',
- 'explicitProcessing',
'full',
'includeGitignored',
'lanes',
@@ -153,6 +152,9 @@ describe('validateDelegatedSyncOptions', () => {
'sourceId',
'timeoutSeconds',
]);
+ // #6712 PR 2: a retired field is not in the table (a newer client never sends it); its window still accepts it.
+ expect(Object.keys(DELEGATED_SYNC_OPTION_FIELDS)).not.toContain('explicitProcessing');
+ expect(validateDelegatedSyncOptions({ explicitProcessing: ['noEmbed'], timeoutSeconds: 0 })).toEqual({ ok: true, options: { timeoutSeconds: 0 }, ignored: ['explicitProcessing'] });
});
});
diff --git a/test/sync-flag-table-6712.test.ts b/test/sync-flag-table-6712.test.ts
new file mode 100644
index 0000000000..1b21f246db
--- /dev/null
+++ b/test/sync-flag-table-6712.test.ts
@@ -0,0 +1,147 @@
+/**
+ * #6712 PR 2 (L3): every `gbrain sync` flag is classified once, in `SYNC_FLAGS` (src/core/sync-flags.ts). The serve
+ * ladder, its wire validator and the PGLite owner lane derive their allowlists from it.
+ *
+ * Protects:
+ * - every flag the sync argv parsers read is in the table, and every table flag is in the generated flag registry;
+ * - the three hand-offs agree with the table (a flag the table forwards is forwarded by each, one it routes to the
+ * client is accepted and never sent, everything else refuses);
+ * - a retired wire field (src/core/wire-skew.ts) is never sent by a newer client, and a newer resident accepts it
+ * from an older one, drops it and prints one notice naming it, on both hand-offs;
+ * - the PGLite owner lane accepts `--lanes N` and `--no-lanes` (it used to refuse them) without sending them.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { readFileSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomBytes, randomUUID } from 'node:crypto';
+import type net from 'node:net';
+import { SYNC_FLAGS, syncFlagsRouted, syncWireFields, type SyncFlagSpec } from '../src/core/sync-flags.ts';
+import { WIRE_SKEW_WINDOWS, retiredWireFields } from '../src/core/wire-skew.ts';
+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
+import { IGNORED_FLAGS, VALUE_FLAGS, WIRE_BOOL_FLAGS, maybeDelegateManagedSyncToServe, parseDelegatedSyncArgs } from '../src/commands/sync-delegate.ts';
+import { DELEGATED_SYNC_OPTION_FIELDS, validateDelegatedSyncOptions } from '../src/core/context/sync-ipc.ts';
+import { SYNC_BOOLEAN_FLAGS, SYNC_CLIENT_FLAGS, SYNC_VALUE_FLAGS, validateSyncWireParams } from '../src/core/persistence/sync-wire.ts';
+import { parsePersistenceSyncArgs } from '../src/commands/sync-persistence-delegate.ts';
+import { startResolveIpcServer } from '../src/core/context/resolve-ipc.ts';
+import { localIpcSocketPath } from '../src/core/context/ipc-path.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { __resetDelegatedSyncForTests, startDelegatedSync } from '../src/core/serve-sync-runner.ts';
+import type { SyncOpts } from '../src/commands/sync.ts';
+import type { ConsumerRow } from '../src/core/persistence/consumer-heartbeat.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const flags = SYNC_FLAGS as Record<string, SyncFlagSpec>;
+const retired = Object.values(WIRE_SKEW_WINDOWS).map(window => window.field);
+let engine: PGLiteEngine;
+const servers: net.Server[] = [];
+const home = mkdtempSync(join(tmpdir(), 'gbrain-sync-flags-'));
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => {
+ for (const server of servers) server.close();
+ __resetDelegatedSyncForTests();
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+});
+
+test('every flag the sync argv parsers read is in the one table, and every table flag is in the flag registry', () => {
+ const parsers = ['src/commands/sync/args.ts', 'src/commands/sync/run.ts'].map(path => readFileSync(path, 'utf8')).join('\n');
+ const read = new Set([...parsers.matchAll(/args(?:\[i - 1\]|\[i\]|\[i\s*-\s*1\])?\s*(?:===|\.includes\(|\.indexOf\()\s*'(--[a-z][a-z-]*)'/g)].map(match => match[1]!));
+ for (const match of parsers.matchAll(/args\.(?:includes|indexOf)\('(--[a-z][a-z-]*)'\)/g)) read.add(match[1]!);
+ // `--retry-held` is refused by name with its own fix; `--help` is the router's.
+ const unclassified = [...read].filter(flag => !(flag in flags) && !['--retry-held', '--help'].includes(flag));
+ expect(read.size).toBeGreaterThan(25);
+ expect(unclassified).toEqual([]);
+ const registry = new Set(CLI_FLAG_REGISTRY.sync);
+ expect(Object.keys(flags).filter(flag => !registry.has(flag))).toEqual([]);
+});
+
+test('the serve ladder, its wire validator and the owner lane are views of the table', () => {
+ for (const [flag, spec] of Object.entries(flags)) {
+ // Serve ladder: forward → on the wire (or fixed), client → accepted and not sent, refuse → refused by name.
+ const argv = spec.arity === 'boolean' ? [flag] : [flag, flag === '--lanes' ? '4' : 'x'];
+ const parsed = parseDelegatedSyncArgs(argv);
+ if (spec.serve === 'refuse') expect(parsed).toEqual({ ok: false, refused: flag });
+ else {
+ expect(parsed.ok).toBe(true);
+ const sent = parsed.ok ? Object.keys(parsed.options) : [];
+ expect(sent).toEqual(spec.serve === 'forward' && spec.field ? [spec.field] : []);
+ if (spec.serve === 'forward') expect(spec.field! in DELEGATED_SYNC_OPTION_FIELDS).toBe(true);
+ }
+ // Owner lane: forward → a wire field, client → consumed by the CLI, refuse → absent.
+ const owner = spec.owner === 'forward' ? (spec.arity === 'boolean' ? SYNC_BOOLEAN_FLAGS[flag] : SYNC_VALUE_FLAGS[flag]) : undefined;
+ expect(owner).toBe(spec.owner === 'forward' ? spec.field : undefined);
+ expect(SYNC_CLIENT_FLAGS.has(flag)).toBe(spec.owner === 'client');
+ }
+ expect(Object.keys(WIRE_BOOL_FLAGS).sort()).toEqual(syncFlagsRouted('serve', 'forward').filter(flag => flags[flag].arity === 'boolean' && flags[flag].sets === undefined).sort());
+ expect([...VALUE_FLAGS].sort()).toEqual(['--hard-deadline', '--lanes', '--source', '--timeout']);
+ expect([...IGNORED_FLAGS].sort()).toEqual(['--json', '--no-delegate', '--no-hard-deadline', '--yes']);
+ expect(Object.keys(syncWireFields('owner')).sort()).toEqual(['dryRun', 'exclude', 'full', 'includeGitignored', 'includeHidden', 'noBulk', 'noEmbed', 'noExtract',
+ 'noPull', 'noSchemaPack', 'repoPath', 'resetCheckpoint', 'retryFailed', 'skipFailed', 'sourceId', 'srcSubpath', 'strategy', 'workingTree']);
+});
+
+test('a retired wire field is never in the table and is accepted, dropped and named once by both residents', async () => {
+ expect(retired).toContain('explicitProcessing');
+ for (const field of retired) {
+ expect(Object.values(flags).map(spec => spec.field)).not.toContain(field);
+ expect(field in DELEGATED_SYNC_OPTION_FIELDS).toBe(false);
+ }
+ // Serve: accepted by shape, dropped, reported as ignored; a wrong shape still refuses.
+ expect(validateDelegatedSyncOptions({ noPull: true, explicitProcessing: ['noEmbed'], timeoutSeconds: 5 }))
+ .toEqual({ ok: true, options: { noPull: true, timeoutSeconds: 5 }, ignored: ['explicitProcessing'] });
+ expect(validateDelegatedSyncOptions({ explicitProcessing: ['repoPath'], timeoutSeconds: 5 })).toEqual({ ok: false, error: 'invalid_options:explicitProcessing' });
+ // Owner lane: the same window, the same drop.
+ const wire = validateSyncWireParams({ options: { sourceId: 'notes', noPull: true, explicitProcessing: [] }, cwd: home, timeoutSeconds: 5 });
+ expect(wire).toEqual({ options: { sourceId: 'notes', noPull: true }, cwd: home, timeoutSeconds: 5, ignored: ['explicitProcessing'] });
+ expect(() => validateSyncWireParams({ options: { explicitProcessing: 'noEmbed' }, cwd: home, timeoutSeconds: 5 })).toThrow();
+ expect([...retiredWireFields('owner').keys()]).toEqual([...retiredWireFields('serve').keys()]);
+ // The serve prints one notice naming the field, its floor and its window.
+ const lines: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ process.stderr.write = ((chunk: string) => { lines.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ try {
+ const started = await startDelegatedSync(engine, { sourceId: 'missing-source', dryRun: true, explicitProcessing: ['noEmbed'], timeoutSeconds: 5 }, randomUUID());
+ expect(started.ok).toBe(true);
+ } finally { process.stderr.write = write; }
+ const notices = lines.filter(line => line.includes('[gbrain notice]'));
+ expect(notices).toHaveLength(1);
+ expect(notices[0]).toContain('`explicitProcessing`');
+ expect(notices[0]).toContain(WIRE_SKEW_WINDOWS.explicitProcessing.accept_until);
+ __resetDelegatedSyncForTests();
+});
+
+test('a newer CLI never sends a retired field to the serve, whatever its options carry', async () => {
+ const secret = randomBytes(32).toString('hex');
+ const sock = localIpcSocketPath(join(mkdtempSync(join(home, 'sock-')), 'resolve.sock'));
+ const received: Array<Record<string, unknown>> = [];
+ const server = await startResolveIpcServer(sock, {
+ resolve: async () => null,
+ sync_start: req => { received.push(req.options as Record<string, unknown>); return { ok: false, protocol: 2, error: 'shutting_down' }; },
+ sync_status: () => ({ ok: false, protocol: 2, error: 'unknown_job' }),
+ sync_abort: () => ({ ok: true, protocol: 2 as const }),
+ } as never, { secret });
+ servers.push(server!);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const serve: 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 err = console.error; console.error = () => {};
+ const write = process.stderr.write.bind(process.stderr); process.stderr.write = (() => true) as typeof process.stderr.write;
+ let outcome: unknown;
+ try {
+ outcome = await withEnv({ GBRAIN_HOME: home }, () => maybeDelegateManagedSyncToServe(engine, ['--source', 'notes', '--no-pull', '--no-embed'],
+ { sourceId: 'notes', noPull: true, noEmbed: true, explicitProcessing: ['noEmbed'] } as unknown as SyncOpts,
+ { config: { engine: 'postgres', database_url: 'postgresql://example.invalid/brain' }, probe: async () => serve, socket: async () => ({ sock, secret }), env: {} }));
+ } finally { console.error = err; process.stderr.write = write; }
+ expect(outcome).toMatchObject({ kind: 'own_consumer', reason: 'serve_refused' });
+ expect(received).toHaveLength(1);
+ expect(received[0]).toMatchObject({ sourceId: 'notes', noPull: true, noEmbed: true });
+ for (const options of received) for (const field of retired) expect(field in options).toBe(false);
+ for (const options of received) expect(Object.keys(options).every(key => key in DELEGATED_SYNC_OPTION_FIELDS)).toBe(true);
+});
+
+test('the PGLite owner lane accepts --lanes N and --no-lanes and never sends them', async () => {
+ const params = await parsePersistenceSyncArgs(['--source', 'notes', '--no-pull', '--no-bulk', '--no-lanes', '--lanes', '4', '--hard-deadline', '13m', '--json'], home);
+ expect(params.options).toEqual({ sourceId: 'notes', noPull: true, noBulk: true });
+ await expect(parsePersistenceSyncArgs(['--source', 'notes', '--lanes'], home)).rejects.toMatchObject({ code: 'invalid_params' });
+});