Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(cli): stop rerouting sync --timeout into dispatchReadOnlyCommand (#3013) (#3650)

Masabb69aa8b655c
diff --git a/src/cli.ts b/src/cli.ts
index a044e171a0..854c1de885 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1707,14 +1707,12 @@ async function handleCliOnly(command: string, args: string[]) {
// Per-command default: search 30s, sources list 10s. User --timeout=Ns wins.
// Other commands (import, embed, doctor, etc.) keep their existing
// unbounded connect — destructive / long-running commands shouldn't get
- // a default kill switch.
- const readOnlyDefaultTimeoutMs =
- command === 'search' ? 30_000 :
- command === 'sources' && (args[0] === 'list' || args[0] === undefined) ? 10_000 :
- null;
+ // a default kill switch. The gate below is per-command (#3013): only the
+ // commands dispatchReadOnlyCommand handles may enter this path — a
+ // user-supplied --timeout on a write command must never reroute it here.
const cliOptsResolved = getCliOptions();
const userTimeoutMs = cliOptsResolved.timeoutMs;
- const readOnlyTimeoutMs = userTimeoutMs ?? readOnlyDefaultTimeoutMs;
+ const readOnlyTimeoutMs = resolveReadOnlyDispatchTimeoutMs(command, args, userTimeoutMs);
if (readOnlyTimeoutMs !== null) {
const { withTimeout, OperationTimeoutError } = await import('./core/timeout.ts');
@@ -2313,6 +2311,28 @@ async function handleCliOnly(command: string, args: string[]) {
}
}
+/**
+ * #3013: decide whether an invocation enters the read-only connect+dispatch
+ * timeout path, and with what wallclock. Returns null for every command
+ * dispatchReadOnlyCommand can't handle. The gate used to be "a timeout is
+ * present" — so a user-supplied --timeout on a write command (`sync`,
+ * `embed`, `import`, ...) hijacked dispatch into the read-only path, which
+ * threw and exited 1 before any work ran. Pure; exported for the
+ * regression test.
+ */
+export function resolveReadOnlyDispatchTimeoutMs(
+ command: string,
+ subArgs: string[],
+ userTimeoutMs: number | null,
+): number | null {
+ if (command !== 'search' && command !== 'sources') return null;
+ const defaultMs =
+ command === 'search' ? 30_000 :
+ (subArgs[0] === 'list' || subArgs[0] === undefined) ? 10_000 :
+ null;
+ return userTimeoutMs ?? defaultMs;
+}
+
/**
* v0.41.6.0 D3: dispatch helper for the read-only commands that take a
* default wallclock timeout (`gbrain search`, `gbrain sources list`).
diff --git a/src/core/cli-options.ts b/src/core/cli-options.ts
index 385bc67062..e005495aec 100644
--- a/src/core/cli-options.ts
+++ b/src/core/cli-options.ts
@@ -51,9 +51,29 @@ export const DEFAULT_CLI_OPTIONS: CliOptions = {
*
* Unknown flags are passed through unchanged — per-command parsers see them.
*/
+/**
+ * #3013: commands that parse their own `--timeout` flag out of argv.
+ * `sync` reads a seconds-based graceful-abort budget (src/commands/sync.ts +
+ * resolveSyncHardDeadline); `remote` reads a ms-based request budget
+ * (src/commands/remote.ts). For these commands the global parser must hand
+ * the flag back: claiming it stripped the flag before the per-command parser
+ * could read it, and — for `sync` — a non-null global timeoutMs flipped the
+ * read-only dispatch gate in cli.ts, rerouting a write command into
+ * dispatchReadOnlyCommand (exit 1 before any work ran).
+ */
+export const TIMEOUT_OWNING_COMMANDS = new Set(['sync', 'remote']);
+
export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: string[] } {
const cliOpts: CliOptions = { ...DEFAULT_CLI_OPTIONS };
- const rest: string[] = [];
+ // #3013: --timeout can't be resolved inline — whether the GLOBAL parser
+ // claims it depends on which command is running, and the command token is
+ // only known once the whole argv has been scanned (global flags may precede
+ // it). The scan collects positional slots; --timeout slots are resolved in
+ // a second pass below.
+ type Slot =
+ | { plain: string }
+ | { timeoutValue: string; equalsForm: boolean };
+ const slots: Slot[] = [];
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
@@ -74,7 +94,7 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s
continue;
}
// not a number — let per-command parser handle; pass through
- rest.push(a);
+ slots.push({ plain: a });
continue;
}
if (a.startsWith('--progress-interval=')) {
@@ -84,29 +104,20 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s
cliOpts.progressInterval = parsed;
continue;
}
- rest.push(a);
+ slots.push({ plain: a });
continue;
}
// v0.31.1: --timeout=Ns or --timeout Ns. Accepts plain ms, "30s", "2m".
- if (a === '--timeout' && i + 1 < argv.length) {
- const next = argv[i + 1];
- const parsed = parseTimeout(next);
- if (parsed !== null) {
- cliOpts.timeoutMs = parsed;
- i++;
- continue;
- }
- rest.push(a);
+ // A following token that is itself a flag is NOT a value — leave it for
+ // its own iteration (pre-#3013 behavior: an unparseable next token was
+ // never consumed).
+ if (a === '--timeout' && i + 1 < argv.length && !argv[i + 1].startsWith('-')) {
+ slots.push({ timeoutValue: argv[i + 1], equalsForm: false });
+ i++;
continue;
}
if (a.startsWith('--timeout=')) {
- const val = a.slice('--timeout='.length);
- const parsed = parseTimeout(val);
- if (parsed !== null) {
- cliOpts.timeoutMs = parsed;
- continue;
- }
- rest.push(a);
+ slots.push({ timeoutValue: a.slice('--timeout='.length), equalsForm: true });
continue;
}
// v0.40.4 — --explain for `gbrain search/query` per-stage attribution.
@@ -114,8 +125,49 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s
cliOpts.explain = true;
continue;
}
- rest.push(a);
+ slots.push({ plain: a });
+ }
+
+ // The command is the first plain token (matches `command = rest[0]` in
+ // cli.ts). If it owns --timeout, every --timeout is handed back in the
+ // space-separated spelling (the only form the owning parsers read; this
+ // also normalizes `--timeout=60s`), value verbatim so the owning command
+ // applies its own unit + validity rules (`sync`: bare integers are
+ // SECONDS, `ms`/fractional rejected loudly; `remote` accepts `h`).
+ // Handed-back flags are APPENDED after every other token: both owning
+ // commands treat leading args as positional subcommands (`sync trigger`,
+ // `remote ping`) and locate --timeout by scanning args, so appending can't
+ // shadow a subcommand while duplicate flags keep their argv order (the
+ // owning parsers' first-occurrence-wins precedence matches what the user
+ // typed). Non-owning commands keep the pre-#3013 global behavior:
+ // parseable values are claimed into cliOpts.timeoutMs (last one wins),
+ // unparseable ones pass through in their original spelling for the
+ // per-command parser.
+ const commandSlot = slots.find((s): s is { plain: string } => 'plain' in s);
+ const commandOwnsTimeout =
+ commandSlot !== undefined && TIMEOUT_OWNING_COMMANDS.has(commandSlot.plain);
+
+ const rest: string[] = [];
+ const handback: string[] = [];
+ for (const s of slots) {
+ if ('plain' in s) {
+ rest.push(s.plain);
+ continue;
+ }
+ if (commandOwnsTimeout) {
+ handback.push('--timeout', s.timeoutValue);
+ continue;
+ }
+ const parsed = parseTimeout(s.timeoutValue);
+ if (parsed !== null) {
+ cliOpts.timeoutMs = parsed;
+ } else if (s.equalsForm) {
+ rest.push(`--timeout=${s.timeoutValue}`);
+ } else {
+ rest.push('--timeout', s.timeoutValue);
+ }
}
+ rest.push(...handback);
return { cliOpts, rest };
}
diff --git a/test/sync-timeout-cli-dispatch.test.ts b/test/sync-timeout-cli-dispatch.test.ts
new file mode 100644
index 0000000000..335e2d67d2
--- /dev/null
+++ b/test/sync-timeout-cli-dispatch.test.ts
@@ -0,0 +1,142 @@
+import { describe, test, expect } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { join } from 'node:path';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { resolveReadOnlyDispatchTimeoutMs } from '../src/cli.ts';
+import { parseGlobalFlags } from '../src/core/cli-options.ts';
+
+// #3013 — `gbrain sync --timeout <s>` was unreachable: the global option
+// parser claimed --timeout before dispatch, and the read-only timeout path
+// gated on "a timeout is present" rather than "the command is read-only".
+// Any command carrying a user --timeout was rerouted into
+// dispatchReadOnlyCommand, which throws on everything but search/sources.
+
+describe('read-only dispatch gate is per-command (#3013)', () => {
+ test('sync with a user --timeout never enters the read-only path', () => {
+ expect(resolveReadOnlyDispatchTimeoutMs('sync', ['--source', 'x'], 60_000)).toBe(null);
+ });
+
+ test('other write commands with a user --timeout never enter the read-only path', () => {
+ for (const command of ['embed', 'import', 'doctor', 'extract']) {
+ expect(resolveReadOnlyDispatchTimeoutMs(command, [], 5_000)).toBe(null);
+ }
+ });
+
+ test('search keeps its 30s default and user override', () => {
+ expect(resolveReadOnlyDispatchTimeoutMs('search', ['hello'], null)).toBe(30_000);
+ expect(resolveReadOnlyDispatchTimeoutMs('search', ['hello'], 5_000)).toBe(5_000);
+ });
+
+ test('sources list keeps its 10s default; other subcommands only bound on user --timeout', () => {
+ expect(resolveReadOnlyDispatchTimeoutMs('sources', ['list'], null)).toBe(10_000);
+ expect(resolveReadOnlyDispatchTimeoutMs('sources', [], null)).toBe(10_000);
+ expect(resolveReadOnlyDispatchTimeoutMs('sources', ['add', 'x'], null)).toBe(null);
+ expect(resolveReadOnlyDispatchTimeoutMs('sources', ['add', 'x'], 5_000)).toBe(5_000);
+ });
+});
+
+describe('CLI integration: sync --timeout reaches the sync handler (#3013)', () => {
+ const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');
+
+ // No configured brain needed: the sync hard-deadline watchdog arms from
+ // argv BEFORE connectEngine, so its stderr banner proves (a) dispatch fell
+ // through to the sync branch instead of dispatchReadOnlyCommand, (b) the
+ // handed-back --timeout was parsed with sync's SECONDS semantics (60s, not
+ // the 60ms the global parser used to produce for a bare "60").
+ const run = (args: string[]) =>
+ spawnSync('bun', [CLI, ...args], {
+ encoding: 'utf-8',
+ env: {
+ ...process.env,
+ NO_COLOR: '1',
+ GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'gbrain-3013-')),
+ },
+ });
+
+ test('space form: `sync --source x --dry-run --timeout 60`', () => {
+ const res = run(['sync', '--source', 'x', '--dry-run', '--timeout', '60']);
+ const all = `${res.stdout}\n${res.stderr}`;
+ expect(all).not.toContain('dispatchReadOnlyCommand');
+ expect(all).not.toContain('connect timed out');
+ expect(res.stderr).toContain('hard deadline armed: 60s');
+ expect(res.stderr).toContain('(flag:--timeout)');
+ });
+
+ test('equals form: `sync --source x --dry-run --timeout=60s`', () => {
+ const res = run(['sync', '--source', 'x', '--dry-run', '--timeout=60s']);
+ const all = `${res.stdout}\n${res.stderr}`;
+ expect(all).not.toContain('dispatchReadOnlyCommand');
+ expect(all).not.toContain('connect timed out');
+ expect(res.stderr).toContain('hard deadline armed: 60s');
+ expect(res.stderr).toContain('(flag:--timeout)');
+ });
+});
+
+describe('parseGlobalFlags hands --timeout back to owning commands (#3013)', () => {
+ test('sync, space form: flag returned to rest, global timeoutMs stays null', () => {
+ const r = parseGlobalFlags(['sync', '--source', 'x', '--dry-run', '--timeout', '60']);
+ expect(r.cliOpts.timeoutMs).toBe(null);
+ expect(r.rest).toEqual(['sync', '--source', 'x', '--dry-run', '--timeout', '60']);
+ });
+
+ test('sync, equals form: normalized to the space form sync parses', () => {
+ const r = parseGlobalFlags(['sync', '--source', 'x', '--timeout=60s']);
+ expect(r.cliOpts.timeoutMs).toBe(null);
+ expect(r.rest).toEqual(['sync', '--source', 'x', '--timeout', '60s']);
+ });
+
+ test('flag before the command still hands back (appended after the args)', () => {
+ const r = parseGlobalFlags(['--timeout', '60', 'sync', '--source', 'x']);
+ expect(r.cliOpts.timeoutMs).toBe(null);
+ expect(r.rest).toEqual(['sync', '--source', 'x', '--timeout', '60']);
+ });
+
+ // codex review round-2 W3: handback must not shadow positional
+ // subcommands — both owning commands read args[0] as a subcommand
+ // (`remote ping`, `sync trigger`) and find --timeout by scanning, so the
+ // handed-back flag always lands after every other token.
+ test('handback never lands in front of a positional subcommand', () => {
+ const r1 = parseGlobalFlags(['remote', '--timeout', '5m', 'ping']);
+ expect(r1.rest).toEqual(['remote', 'ping', '--timeout', '5m']);
+ const r2 = parseGlobalFlags(['--timeout=5m', 'remote', 'ping']);
+ expect(r2.rest).toEqual(['remote', 'ping', '--timeout', '5m']);
+ const r3 = parseGlobalFlags(['--timeout', '60', 'sync', 'trigger']);
+ expect(r3.rest).toEqual(['sync', 'trigger', '--timeout', '60']);
+ });
+
+ test('remote owns --timeout too (ms-based budget in commands/remote.ts)', () => {
+ const r = parseGlobalFlags(['remote', 'doctor', '--timeout=5m']);
+ expect(r.cliOpts.timeoutMs).toBe(null);
+ expect(r.rest).toEqual(['remote', 'doctor', '--timeout', '5m']);
+ });
+
+ test('non-owning commands keep the global claim (thin-client / read-only budgets)', () => {
+ const r = parseGlobalFlags(['search', '--timeout=30s', 'X']);
+ expect(r.cliOpts.timeoutMs).toBe(30_000);
+ expect(r.rest).toEqual(['search', 'X']);
+ });
+
+ // codex review W1: values outside the GLOBAL grammar (no `h` unit) must
+ // still be handed back — the owning command's grammar decides validity.
+ test('values the global grammar rejects still hand back (--timeout=2h)', () => {
+ const r = parseGlobalFlags(['sync', '--source', 'x', '--timeout=2h']);
+ expect(r.cliOpts.timeoutMs).toBe(null);
+ expect(r.rest).toEqual(['sync', '--source', 'x', '--timeout', '2h']);
+ });
+
+ // codex review W2: duplicate flags keep their relative argv order, so the
+ // owning command's first-occurrence-wins precedence matches what the
+ // user typed.
+ test('duplicate --timeout flags keep argv order', () => {
+ const r = parseGlobalFlags(['sync', '--timeout', '60', '--timeout', '2h', '--source', 'x']);
+ expect(r.cliOpts.timeoutMs).toBe(null);
+ expect(r.rest).toEqual(['sync', '--source', 'x', '--timeout', '60', '--timeout', '2h']);
+ });
+
+ test('a flag token after bare --timeout is not consumed as its value', () => {
+ const r = parseGlobalFlags(['sync', '--timeout', '--source', 'x']);
+ expect(r.cliOpts.timeoutMs).toBe(null);
+ expect(r.rest).toEqual(['sync', '--timeout', '--source', 'x']);
+ });
+});