Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(cli): sources writer movement owns its --wait; malformed write wait is invalid_params (#6625)

time-attack61fd02f32032
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index cd249121b8..a5064579c5 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cli-force-exit.ts` — single owner of one-shot CLI exit + teardown, designed as a PAIR with the exit seam `runCli()` in `src/cli/main.ts` (called by the `src/cli.ts` entry point after its fast paths). `finishCliTeardown({engine, drainTimeoutMs?})` is teardown-ONLY (never exits on the clean path): arms a REF'D backstop (unref'd would let a hung teardown exit naturally, skipping the flush and exiting with whatever PGLite scribbled into `process.exitCode`) whose deadline is COMPUTED from the bounds it guards (`computeTeardownDeadlineMs` = sinks × drainTimeoutMs + sinks × `SINK_DRAIN_TIMEOUT_MS` disconnect-drain bound + the RESOLVED PGLite close bound (`pgliteCloseTimeoutMs()` from background-work.ts — an operator-raised `GBRAIN_PGLITE_CLOSE_TIMEOUT_MS` widens this backstop too, never a hardcoded copy of the default) + facts-abort grace + 2 × pool-end bound + slack, floor 10s — the disconnect-drain and close terms budget `engine.disconnect()`'s own drain pass and bounded close so the backstop can't fire while every component honored its own bound; `GBRAIN_TEARDOWN_DEADLINE_MS` env override is the incident escape hatch), drains every background-work sink, disconnects the engine (a throw is warned + swallowed — the exit code reports the OPERATION, not the cleanup), then returns. The exit VERDICT lives in a gbrain-owned channel (`setCliExitVerdict`/`currentExitCode`; mirror-writes `process.exitCode` but NEVER reads it back) because PGLite's Emscripten runtime scribbles its own status into `process.exitCode` at arbitrary points mid-run — every writer that means to set the CLI exit code (op-dispatch catch, reindex, frontmatter, transcripts, brainstorm, autopilot, doctor's FAIL verdict, extract, and cli.ts's swept inner exits — friction, claw-test, smoke-test, the no-DB eval runners, status/status-thin, whoknows-thin) calls `setCliExitVerdict`; `test/cli-exit-verdict-pin.test.ts` greps src/ so the next raw `process.exitCode =` write fails CI instead of silently reporting success on failure. The deadline arms at TEARDOWN start, never before the op handler (arming before the handler would measure handler + teardown combined, taxing PgBouncer deployments with a flat force-exit deadline on every query and killing any long op mid-run with exit 0). All nine cli.ts disconnect sites route through it; the ONE process exit happens in cli.ts's `main().then/catch` via `flushThenExit(currentExitCode())`, gated by `shouldForceExitAfterMain()` (daemon list: `serve`) — the CLI never waits for Bun's event loop to drain, because `endPoolBounded` deliberately races past stuck PgBouncer sockets that would keep it alive. `flushThenExit(code)` fences stdout+stderr (`write('', cb)` raced with an unref'd guard, EPIPE-safe both sync and async), then exits as soon as no non-TTY stream holds queued bytes — Bun delivers queued pipe writes only while the process is alive (write callbacks fire on accept, not delivery). process.stdout's one-shot writes go through the fd-1 write chain, and `installStdoutPipeDelivery` wraps process.stderr to track Bun's native queue (`write()` returns false exactly when bytes stayed queued; `'drain'` fires when it empties), so with nothing queued the exit is immediate, a queued stream ends the wait at its `'drain'`, and the REF'D grace (250 ms, `GBRAIN_FLUSH_GRACE_MS`) is only the upper bound — or a fixed sleep for a stream nothing tracks (a daemon's fatal path, test doubles). `test/cli-exit-drain.test.ts` pins it on real pipes. Scope claim is deliberately cli.ts-only: command modules' mid-run engine lifecycles stay local (process-exit semantics inside them would be wrong) and are absorbed by the final explicit exit. Pinned by `test/cli-finish-teardown.test.ts`, `test/flush-then-exit-harness.test.ts` (real spawned-Bun pipe semantics), `test/cli-should-force-exit.test.ts`, `test/cli-pipe-truncation.test.ts` (real-CLI piped --tools-json byte-stable), `test/cli-exit-verdict-pin.test.ts`, the teardown describes in `test/fix-wave-structural.test.ts` + `test/e2e/pglite-cli-exit.serial.test.ts`, and `test/e2e/pgbouncer-teardown.test.ts` (CI transaction-mode pooler). Agent contract v1: `jsonRequested(argv)`; `installStdoutPipeDelivery({ json })` guard mode (see `src/cli/json-guard.ts` in [agent contract](agent-contract.md)); `writeNdjsonLine`; `spawnCliChild` (the one `stdio: 'inherit'` site); `noteRenderedErrorCode` feeds the fallback document's `code`. D2 helpers: `writeJsonDocument` (the one document under the guard, the caller's legacy writer otherwise), `writeJsonLine` (its NDJSON analog), `jsonGuardActive()`, `cliChildStdio()` (sync child CLIs: child stdout to fd 2 under the guard); an empty NDJSON stream at exit 0 is valid (no `json_document_missing`).
- `src/core/exit-codes.ts` — CLI exit statuses with a contract beyond 0/1: `MIGRATIONS_RUNNING_EXIT_CODE` (75, read by `gbrain upgrade` as a lock conflict; re-exported by `migration-orchestration-lock.ts`) and `PENDING_WRITE_EXIT_CODE` (10, an admitted write still pending) and `BUDGET_STOP_EXIT_CODE` (11, `gbrain embed --stale` stopped at its time budget with stale chunks left; stdout names the remaining count and resume command). Agent contract v1 table: 0 ok, 1 failed, 2 usage (`USAGE_EXIT_CODE`), 3 `confirmation_required` only (`CONFIRMATION_REQUIRED_EXIT_CODE`), 10 pending write, 11 budget stop, 75 migration lock, 124 timeout, 130 interrupted; `test/exit-codes.test.ts` enumerates every exit 3 in src/; guide `docs/guides/exit-codes.md`.
-- `src/core/cli-options.ts` — Global CLI flag parser. `parseGlobalFlags(argv)` returns `{cliOpts, rest}` with `--quiet` / `--progress-json` / `--progress-interval=<ms>` / `--brain <id>` stripped. `--brain` is the brain-axis (which database) selector: exact-match only (`--brain-*` per-command flags pass through), value validated against the mount-id regex at parse time, missing/malformed value THROWS — never a silent host fallback. `connectEngine` in `src/cli.ts` feeds it (plus the ambient `GBRAIN_BRAIN_ID` / `.gbrain-mount` / mount-path tiers) through `resolveBrainId` → `BrainRegistry.getBrain`, which throws `UnknownBrainError` for an unregistered id; mounts get no auto-migrations and keep the host-config AI gateway. `getCliOptions()` / `setCliOptions()` expose a module-level singleton so commands reach resolved flags without parameter threading. `cliOptsToProgressOptions()` maps to reporter options. `childGlobalFlags()` returns the flag suffix to append to `execSync('gbrain ...')` calls in migration orchestrators (propagates `--brain=<id>` so children stay on the parent's brain). `OperationContext.cliOpts` extends shared-op dispatch for MCP callers. `CliOptions` carries `explain: boolean`. `parseGlobalFlags` recognizes `--explain` anywhere in argv (stripped before command dispatch). `src/cli.ts` `formatResult` for `search` + `query` cases routes to `formatResultsExplain` from `src/core/search/explain-formatter.ts` when `CliOptions.explain` is set; falls through to the existing JSON / human formatters otherwise. `maybeBackground(opName, fingerprintArgs, runDirect)` helper. Same semantics in TTY and cron (no `--no-tty-detect` flag, no surprise behavior change between contexts): when `--background` is passed, submits the op as a Minion job via `op_checkpoints` for resumability and returns the `job_id`. `--background --follow` execs `gbrain jobs follow <id>` so the user sees the same stderr stream they'd get from a direct call. PGLite degrades to inline execution with a clear stderr note ("PGLite worker pool not yet supported; running inline"). Returns a tagged union the caller dispatches on.
+- `src/core/cli-options.ts` — Global CLI flag parser. `parseGlobalFlags(argv)` returns `{cliOpts, rest}` with `--quiet` / `--progress-json` / `--progress-interval=<ms>` / `--brain <id>` stripped. `--brain` is the brain-axis (which database) selector: exact-match only (`--brain-*` per-command flags pass through), value validated against the mount-id regex at parse time, missing/malformed value THROWS — never a silent host fallback. `connectEngine` in `src/cli.ts` feeds it (plus the ambient `GBRAIN_BRAIN_ID` / `.gbrain-mount` / mount-path tiers) through `resolveBrainId` → `BrainRegistry.getBrain`, which throws `UnknownBrainError` for an unregistered id; mounts get no auto-migrations and keep the host-config AI gateway. `getCliOptions()` / `setCliOptions()` expose a module-level singleton so commands reach resolved flags without parameter threading. `cliOptsToProgressOptions()` maps to reporter options. `childGlobalFlags()` returns the flag suffix to append to `execSync('gbrain ...')` calls in migration orchestrators (propagates `--brain=<id>` so children stay on the parent's brain). `OperationContext.cliOpts` extends shared-op dispatch for MCP callers. `CliOptions` carries `explain: boolean`. `parseGlobalFlags` recognizes `--explain` anywhere in argv (stripped before command dispatch). `--wait <seconds>` (#5232 write wait, 0-600 s, no units; a malformed value is `invalid_params`, exit 2) is slotted like `--timeout`: a route in `WAIT_OWNING_ROUTES` (`sources writer movement`, whose own `--wait` takes a duration) gets every `--wait` handed back appended in the space spelling, order kept (#6625). `src/cli.ts` `formatResult` for `search` + `query` cases routes to `formatResultsExplain` from `src/core/search/explain-formatter.ts` when `CliOptions.explain` is set; falls through to the existing JSON / human formatters otherwise. `maybeBackground(opName, fingerprintArgs, runDirect)` helper. Same semantics in TTY and cron (no `--no-tty-detect` flag, no surprise behavior change between contexts): when `--background` is passed, submits the op as a Minion job via `op_checkpoints` for resumability and returns the `job_id`. `--background --follow` execs `gbrain jobs follow <id>` so the user sees the same stderr stream they'd get from a direct call. PGLite degrades to inline execution with a clear stderr note ("PGLite worker pool not yet supported; running inline"). Returns a tagged union the caller dispatches on.
- `src/core/cli-preflight.ts` — `runCliPreflight()`, the first statement of `cli.ts:main()`. (0) Re-run detection: `GBRAIN_CWD_ENV_QUARANTINED` (`CWD_ENV_QUARANTINED_MARKER`) is parsed as JSON `{cwd, neutral, wrapperPid}` and honoured ONLY when the process's startup cwd realpath-equals `neutral` and `neutral` holds none of `CWD_DOTENV_FILES` (`wrapperPid` is informational — accepted only as a positive safe integer, otherwise ignored); on a verified hop it deletes the marker, `chdir(cwd)`s back, skips step 1 (the parent already warned), and arms `installWrapperWatchdog`: an `unref()`ed 1 s interval comparing `process.ppid` (live in Bun) with `wrapperPid` — a mismatch prints one `[env]` line, `rmdirSync`s the empty neutral dir the wrapper's `finally` never reached, and exits 137, so a supervisor that SIGKILLs the wrapper pid (`restartCurrentChild`, job-isolation children, hook pushes) takes the real re-run down within about a second instead of leaving an orphan; an unverified marker is ignored, never chdir'd on. (1) `parseCwdDotenv(cwd)` ONCE, shared by the cwd == config dir check and `quarantineCwdDotenv(process.env, cwd, { assignments })`. (1a) If the drop removed a NON-EMPTY `GBRAIN_GUARDRAILS_MODULE`, print `GUARDRAILS_ASSIGNED_BY_CWD_DOTENV` and exit 1 — fail-closed, never a re-run without the operator's firewall (the `~/.gbrain/.env` home is read after the quarantine and unaffected). (1b) Otherwise, whenever anything was dropped: `Bun.spawn([execPath, ...execArgv (dev runtime only; `resolveRuntimePaths` resolves a `./`/`../`-relative — or bare-and-existing — value of `--preload`/`-r`/`--require`/`--import`, `--config`/`-c`, `--env-file`, `--tsconfig-override`, both spellings, against the ORIGINAL cwd because the re-run starts in the empty neutral dir; everything else passes through verbatim, in order), entry/user args], { cwd: <fresh mkdtemp dir, realpath'd so `neutral` is absolute+canonical>, env: process.env minus undefined + marker, plus the operator's real `HOME` (`USERPROFILE` on win32, from `os.userInfo().homedir`, which Bun derives from the startup environ before the `.env` merge) when a planted one was dropped, stdio: inherit })` — the re-run's Bun never loads the hostile `.env`, so dropped keys are absent (never `''`, which git and the loader presence-check); signal handlers are installed BEFORE the spawn (no orphan window); `reexecSanitized` first removes every pre-existing SIGINT/SIGTERM/SIGHUP listener (cli.ts installs process-cleanup handlers before `main()`; the wrapper relays the child and nothing else), then forwards SIGINT only when `hasControllingTerminal()` is false (`/dev/tty` `O_NOCTTY` probe; isTTY flags on win32 — a terminal delivers Ctrl-C to both processes itself), always forwards SIGTERM/SIGHUP, removes the neutral dir, and exits with the child's code or 128+signal — never earlier. Termination is structural (a re-run's startup cwd has no `.env`); gbrain self-spawns starting in the hostile cwd hop once per subtree. (2) `loadGbrainEnvFile(configDir)`; (3) the #3688 guardrails loader (moved from cli.ts; fail-closed; passes `skipCwdCheck: collision`). cwd == config dir (`cwdIsOperatorConfigDir`, exported for tests): quarantine skipped only when no cwd `.env` assigns any of `GBRAIN_HOME`, `HOME`, `USERPROFILE` and `realpath(cwd) === realpath(configDir())`. Script mode (`isScriptRuntime()`: `process.execPath` is a bun runtime, not a compiled binary): `warnScriptModeBunfig` prints `SCRIPT_MODE_BUNFIG_WARNING` once when the STARTUP cwd's `bunfig.toml` declares a top-level `preload` and the cwd is not the checkout containing the running entry (Bun ran that preload before this code; the compiled binary is built with `--no-compile-autoload-bunfig`); never repeated on the re-run. Zero cost when nothing protected is assigned. Pinned by `test/cli-cwd-dotenv-quarantine.test.ts` (hostile git checkout with planted `core.fsmonitor` via `GIT_CONFIG_*` AND via `XDG_CONFIG_HOME`; `sh` presence probe for `GIT_SSL_NO_VERIFY`; four forged-marker shapes; depth-2 re-spawn; SIGTERM/SIGKILL; native Bun terminal (`Bun.spawn({ terminal })`, skipped on win32) tty-SIGINT ignore vs non-tty SIGINT forward; SIGHUP forward; execArgv preservation across the hop; chdir-back-when-original-cwd-vanished; relative-`TMPDIR` hop; guardrails fail-closed refusal + control; wrapper outlives SIGTERM until the child exits (exit = child's, neutral dir removed); planted-`HOME` drop → real home restored in both the cron and the exported-HOME shapes; forged-home config-dir exemption refused; script-mode bunfig warning (foreign cwd warns once, own checkout silent, `[test]`-section preload silent); cwd + relative-argv restoration; compiled binary from `GBRAIN_COMPILED_BIN ?? bin/gbrain`, including a cwd `bunfig.toml` `preload` staying inert).
diff --git a/src/core/cli-options.ts b/src/core/cli-options.ts
index cea90870c7..d32c437434 100644
--- a/src/core/cli-options.ts
+++ b/src/core/cli-options.ts
@@ -10,6 +10,7 @@
*/
import type { ProgressOptions } from './progress.ts';
+import { opError } from './ops/contract.ts';
export interface CliOptions {
quiet: boolean;
@@ -58,11 +59,13 @@ export const DEFAULT_CLI_OPTIONS: CliOptions = {
brain: null,
};
-/** `--wait` takes seconds (`--wait 45`, `--wait 2.5`), 0 to 600. A malformed value throws. */
+/** `--wait` takes seconds (`--wait 45`, `--wait 2.5`), 0 to 600. A malformed value is a usage error (exit 2). */
function parseWaitSeconds(val: string | undefined): number {
const seconds = val !== undefined && /^\d+(?:\.\d+)?$/.test(val) ? Number(val) : NaN;
if (!Number.isFinite(seconds) || seconds > 600) {
- throw new Error(`--wait requires a number of seconds from 0 to 600 (got ${val === undefined ? 'nothing' : JSON.stringify(val)}).`);
+ throw opError('invalid_params',
+ `--wait takes a number of seconds from 0 to 600, no units (got ${val === undefined ? 'nothing' : JSON.stringify(val)}).`,
+ 'Give --wait seconds with no unit, for example --wait 45 or --wait 300 for five minutes.');
}
return Math.round(seconds * 1000);
}
@@ -128,6 +131,15 @@ export const TIMEOUT_OWNING_COMMANDS = new Set(['sync', 'remote']);
*/
export const EXPLAIN_CLAIMING_COMMANDS = new Set(['query', 'search', 'ask', 'call']);
+/**
+ * #6625: command routes whose own parser reads `--wait` (a duration such as
+ * `5m`, not the #5232 write wait in seconds). For these the global parser
+ * hands every `--wait` back, appended in the space-separated spelling;
+ * everyone else keeps the global write wait. Matched on the leading plain
+ * tokens, so `sources writer movement` owns it and `sources list` does not.
+ */
+export const WAIT_OWNING_ROUTES: readonly (readonly string[])[] = [['sources', 'writer', 'movement']];
+
export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: string[] } {
const cliOpts: CliOptions = { ...DEFAULT_CLI_OPTIONS };
// #3013: --timeout can't be resolved inline — whether the GLOBAL parser
@@ -138,7 +150,8 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s
type Slot =
| { plain: string }
| { timeoutValue: string; equalsForm: boolean }
- | { explainFlag: true };
+ | { explainFlag: true }
+ | { waitValue: string | undefined };
const slots: Slot[] = [];
for (let i = 0; i < argv.length; i++) {
@@ -209,13 +222,14 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s
}
// #5232 write wait + pending opt-in. Global like --timeout so every write
// lane (generated ops, call, capture, remember, takes) reads one value.
+ // #6625: slotted like --timeout, since `sources writer movement` owns its own --wait.
if (a === '--wait') {
- cliOpts.writeWaitMs = parseWaitSeconds(argv[i + 1]);
+ slots.push({ waitValue: argv[i + 1] });
i++;
continue;
}
if (a.startsWith('--wait=')) {
- cliOpts.writeWaitMs = parseWaitSeconds(a.slice('--wait='.length));
+ slots.push({ waitValue: a.slice('--wait='.length) });
continue;
}
if (a === '--accept-pending' || a === '--no-accept-pending') {
@@ -247,6 +261,8 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s
// everyone else gets it back in place (extract/whoknows/onboard own it).
const commandClaimsExplain =
commandSlot !== undefined && EXPLAIN_CLAIMING_COMMANDS.has(commandSlot.plain);
+ const leading = slots.filter((s): s is { plain: string } => 'plain' in s).map(s => s.plain);
+ const routeOwnsWait = WAIT_OWNING_ROUTES.some(route => route.every((token, i) => leading[i] === token));
const rest: string[] = [];
const handback: string[] = [];
@@ -289,6 +305,12 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s
}
continue;
}
+ if ('waitValue' in s) {
+ if (!routeOwnsWait) cliOpts.writeWaitMs = parseWaitSeconds(s.waitValue);
+ else if (s.waitValue === undefined) handback.push('--wait');
+ else handback.push('--wait', s.waitValue);
+ continue;
+ }
if (commandOwnsTimeout) {
handback.push('--timeout', s.timeoutValue);
continue;
diff --git a/test/cli-options.test.ts b/test/cli-options.test.ts
index 027aec2631..f0da91dbe4 100644
--- a/test/cli-options.test.ts
+++ b/test/cli-options.test.ts
@@ -393,6 +393,49 @@ describe('--brain flag (brain axis routing)', () => {
});
});
+describe('--wait flag (#5232 write wait; #6625 movement owns its own)', () => {
+ test('a write command keeps the global write wait in seconds, either spelling', () => {
+ expect(parseGlobalFlags(['remember', 'a fact', '--wait', '45'])).toEqual({ cliOpts: { ...DEFAULT_CLI_OPTIONS, writeWaitMs: 45_000 }, rest: ['remember', 'a fact'] });
+ expect(parseGlobalFlags(['--wait=2.5', 'remember', 'a fact']).cliOpts.writeWaitMs).toBe(2_500);
+ });
+
+ test('a write command refuses a unit or an out-of-range value as invalid_params (exit 2), naming seconds with no units', () => {
+ for (const argv of [['remember', 'x', '--wait', '5m'], ['remember', 'x', '--wait=601'], ['remember', 'x', '--wait']]) {
+ let error: unknown;
+ try { parseGlobalFlags(argv); } catch (e) { error = e; }
+ expect(error).toMatchObject({ code: 'invalid_params', message: expect.stringContaining('seconds from 0 to 600, no units') });
+ }
+ });
+
+ test('sources writer movement gets --wait back unparsed, in both argument orders', () => {
+ for (const argv of [['sources', 'writer', 'movement', '--wait', '5m', '--json'], ['--wait', '5m', 'sources', 'writer', 'movement', '--json']]) {
+ const r = parseGlobalFlags(argv);
+ expect(r.cliOpts.writeWaitMs).toBeUndefined();
+ expect(r.rest).toEqual(['sources', 'writer', 'movement', '--json', '--wait', '5m']);
+ }
+ });
+
+ test('movement: a numeric value is not taken as a write wait, = is normalized, duplicates keep their order', () => {
+ const r = parseGlobalFlags(['sources', 'writer', 'movement', '--wait=300', 'src-a', '--wait', '1h']);
+ expect(r.cliOpts.writeWaitMs).toBeUndefined();
+ expect(r.rest).toEqual(['sources', 'writer', 'movement', 'src-a', '--wait', '300', '--wait', '1h']);
+ });
+
+ test('other sources subcommands keep the global write wait', () => {
+ expect(parseGlobalFlags(['sources', 'writer', 'status', '--wait', '10']).cliOpts.writeWaitMs).toBe(10_000);
+ });
+
+ test('CLI: a malformed write wait exits 2 with invalid_params; movement reads its own duration', () => {
+ const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');
+ const write = spawnSync('bun', [CLI, 'remember', 'x', '--wait', '5m'], { encoding: 'utf-8', env: { ...process.env, NO_COLOR: '1' } });
+ expect(write.status).toBe(2);
+ expect(write.stderr).toContain('Error [invalid_params]: --wait takes a number of seconds from 0 to 600, no units (got "5m").');
+ const movement = spawnSync('bun', [CLI, 'sources', 'writer', 'movement', '--wait', '10x'], { encoding: 'utf-8', env: { ...process.env, NO_COLOR: '1' } });
+ expect(movement.stderr).toContain('--wait must be a positive integer with optional s/m/h suffix');
+ expect(movement.stderr).not.toContain('seconds from 0 to 600');
+ });
+});
+
describe('childGlobalFlags propagates --brain', () => {
test('explicit brain rides into child gbrain subprocess commands', async () => {
const { childGlobalFlags } = await import('../src/core/cli-options.ts');