Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(jobs): reject invalid numeric flags on jobs submit instead of enqueueing silently (#5936)

garrytan9a9f457dd6f8
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index 61b6e5e6ea..67236bccb4 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -1017,6 +1017,7 @@
"test/jobs-ops-token-redaction.test.ts": 644,
"test/jobs-sidechannel-fence.test.ts": 492,
"test/jobs-submit-identity-stamp.test.ts": 270,
+ "test/jobs-submit-numeric-flags.test.ts": 1000,
"test/jobs-thin-client-date-rehydration.test.ts": 8,
"test/jobs-unify-types-default-dryrun.test.ts": 642,
"test/jobs-watch-mode.test.ts": 2,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index de0000914d..52ba2ad6ee 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -1576,6 +1576,7 @@
"unit:test/jobs-ops-token-redaction.test.ts": 2750,
"unit:test/jobs-sidechannel-fence.test.ts": 1190,
"unit:test/jobs-submit-identity-stamp.test.ts": 1625,
+ "unit:test/jobs-submit-numeric-flags.test.ts": 1000,
"unit:test/jobs-thin-client-date-rehydration.test.ts": 372,
"unit:test/jobs-unify-types-default-dryrun.test.ts": 1915,
"unit:test/jobs-watch-mode.test.ts": 157,
diff --git a/src/cli/flag-values.ts b/src/cli/flag-values.ts
new file mode 100644
index 0000000000..729b969636
--- /dev/null
+++ b/src/cli/flag-values.ts
@@ -0,0 +1,52 @@
+/**
+ * Agent contract v1 (D4): strict numeric values for CLI-only command flags.
+ * A malformed, out-of-range or missing value is a usage error
+ * (`invalid_params`, exit 2 through renderCliError) naming the flag, what it
+ * accepts and a valid example, instead of a silent NaN/parseInt fallback.
+ * Absorbs the community numeric-flag fixes (#5936 #5934 #5933 #5931 #5930
+ * #5909) behind one rule set.
+ */
+import { inertText } from '../core/agent-output.ts';
+import type { OperationError } from '../core/ops/contract.ts';
+import { usageError } from './cli-error.ts';
+
+export interface NumericFlagRule {
+ min?: number;
+ max?: number;
+ /** A valid value for the suggestion. */
+ example: number;
+}
+
+function requirement(kind: 'integer' | 'number', r: NumericFlagRule): string {
+ if (r.min !== undefined && r.max !== undefined) return `${kind === 'integer' ? 'an integer' : 'a number'} from ${r.min} to ${r.max}`;
+ if (r.min === 1 && kind === 'integer') return 'a positive integer';
+ if (r.min === 0) return `a non-negative ${kind}`;
+ return kind === 'integer' ? 'an integer' : 'a finite number';
+}
+
+/** The usage error for a bad flag value (also used by commands with their own rules). */
+export function flagValueError(flag: string, raw: string | undefined, accepts: string, example: number | string): OperationError {
+ const missing = raw === undefined || raw.trim() === '' || raw.startsWith('--');
+ return usageError(
+ missing ? `${flag} requires a value: ${accepts}.` : `${flag} must be ${accepts}; got '${inertText(raw, 40)}'.`,
+ `Pass ${accepts}, e.g. ${flag} ${example}.`,
+ );
+}
+
+/** Digits only (a leading sign when negatives are allowed), a safe integer, within [min, max]. */
+export function intFlagValue(raw: string | undefined, flag: string, rule: NumericFlagRule): number {
+ const text = raw?.trim() ?? '';
+ const signed = rule.min === undefined || rule.min < 0;
+ const n = Number(text);
+ if ((signed ? /^[+-]?\d+$/ : /^\+?\d+$/).test(text) && Number.isSafeInteger(n)
+ && n >= (rule.min ?? -Infinity) && n <= (rule.max ?? Infinity)) return n;
+ throw flagValueError(flag, raw, requirement('integer', rule), rule.example);
+}
+
+/** A finite number within [min, max]. */
+export function numberFlagValue(raw: string | undefined, flag: string, rule: NumericFlagRule): number {
+ const text = raw?.trim() ?? '';
+ const n = Number(text);
+ if (text !== '' && Number.isFinite(n) && n >= (rule.min ?? -Infinity) && n <= (rule.max ?? Infinity)) return n;
+ throw flagValueError(flag, raw, requirement('number', rule), rule.example);
+}
diff --git a/src/commands/jobs/submit.ts b/src/commands/jobs/submit.ts
index 35e8e25372..4d52430fa9 100644
--- a/src/commands/jobs/submit.ts
+++ b/src/commands/jobs/submit.ts
@@ -5,6 +5,7 @@ import { assertEmbedBackfillQueueAdmission } from '../../core/minions/embed-back
import { clampLockDurationMs } from '../../core/minions/handler-timeouts.ts';
import { MinionWorker } from '../../core/minions/worker.ts';
import { reportInlineWorkerConfiguration } from '../jobs-readiness.ts';
+import { intFlagValue, numberFlagValue } from '../../cli/flag-values.ts';
export async function runJobsSubmit({ args, engine, queue }: JobsCommandContext): Promise<void> {
// Lazy: jobs.ts imports this module statically, so a static import back would be a cycle.
@@ -22,11 +23,15 @@ export async function runJobsSubmit({ args, engine, queue }: JobsCommandContext)
catch { console.error('Error: --params must be valid JSON'); process.exit(1); }
}
- const priority = parseInt(parseFlag(args, '--priority') ?? '0', 10);
- const delay = parseInt(parseFlag(args, '--delay') ?? '0', 10);
- const maxAttempts = parseInt(parseFlag(args, '--max-attempts') ?? '3', 10);
- const maxStalledRaw = parseFlag(args, '--max-stalled');
- const maxStalled = maxStalledRaw !== undefined ? parseInt(maxStalledRaw, 10) : undefined;
+ // #5936 (D4): numeric flags are validated strictly (usage error, exit 2) before anything is enqueued.
+ const optionalInt = (flag: string, rule: Parameters<typeof intFlagValue>[2]) => {
+ const raw = parseFlag(args, flag);
+ return raw === undefined ? undefined : intFlagValue(raw, flag, rule);
+ };
+ const priority = optionalInt('--priority', { example: 0 }) ?? 0;
+ const delay = optionalInt('--delay', { min: 0, example: 0 }) ?? 0;
+ const maxAttempts = optionalInt('--max-attempts', { min: 1, example: 3 }) ?? 3;
+ const maxStalled = optionalInt('--max-stalled', { min: 0, example: 1 });
// --max-waiting N: submission-time backpressure cap. Mirrors --max-stalled
// clamp [1, 100]. Feature is usable from CLI as of v0.19.1; pre-v0.19.1
// only programmatic callers reached it.
@@ -39,25 +44,14 @@ export async function runJobsSubmit({ args, engine, queue }: JobsCommandContext)
const backoffType = backoffTypeRaw === 'fixed' || backoffTypeRaw === 'exponential'
? backoffTypeRaw
: undefined;
- const backoffDelayRaw = parseFlag(args, '--backoff-delay');
- const backoffDelay = backoffDelayRaw !== undefined ? parseInt(backoffDelayRaw, 10) : undefined;
+ const backoffDelay = optionalInt('--backoff-delay', { min: 0, example: 1000 });
const backoffJitterRaw = parseFlag(args, '--backoff-jitter');
- const backoffJitter = backoffJitterRaw !== undefined ? parseFloat(backoffJitterRaw) : undefined;
- const timeoutMsRaw = parseFlag(args, '--timeout-ms');
- const timeoutMs = timeoutMsRaw !== undefined ? parseInt(timeoutMsRaw, 10) : undefined;
- if (timeoutMsRaw !== undefined && (isNaN(timeoutMs!) || timeoutMs! <= 0)) {
- console.error('Error: --timeout-ms must be a positive integer (milliseconds)');
- process.exit(1);
- }
+ const backoffJitter = backoffJitterRaw === undefined ? undefined : numberFlagValue(backoffJitterRaw, '--backoff-jitter', { min: 0, max: 1, example: 0.2 });
+ const timeoutMs = optionalInt('--timeout-ms', { min: 1, example: 60000 });
// #4145: per-job lock lease. Clamped to [5s,1h] in queue.add via
// clampLockDurationMs (shared with the MCP op); NULL falls to the
// handler map, then the worker default.
- const lockDurationMsRaw = parseFlag(args, '--lock-duration-ms');
- const lockDurationMs = lockDurationMsRaw !== undefined ? parseInt(lockDurationMsRaw, 10) : undefined;
- if (lockDurationMsRaw !== undefined && (isNaN(lockDurationMs!) || lockDurationMs! <= 0)) {
- console.error('Error: --lock-duration-ms must be a positive integer (milliseconds)');
- process.exit(1);
- }
+ const lockDurationMs = optionalInt('--lock-duration-ms', { min: 1, example: 300000 });
const idempotencyKey = parseFlag(args, '--idempotency-key');
const queueName = parseFlag(args, '--queue') ?? 'default';
const dryRun = hasFlag(args, '--dry-run');
diff --git a/test/jobs-submit-numeric-flags.test.ts b/test/jobs-submit-numeric-flags.test.ts
new file mode 100644
index 0000000000..e2e444fb13
--- /dev/null
+++ b/test/jobs-submit-numeric-flags.test.ts
@@ -0,0 +1,67 @@
+/**
+ * #5936 (absorbed in agent contract v1 D4): jobs submit rejects malformed
+ * numeric flags with an invalid_params usage error (exit 2 via the CLI's
+ * renderCliError seam) before anything is enqueued.
+ */
+import { describe, expect, spyOn, test } from 'bun:test';
+import { runJobsSubmit } from '../src/commands/jobs/submit.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+
+function makeContext(args: string[]) {
+ const added: unknown[][] = [];
+ const queue = {
+ ensureSchema: async () => {},
+ add: async (...input: unknown[]) => {
+ added.push(input);
+ return { id: 1 };
+ },
+ };
+ return {
+ context: { args, engine: { kind: 'postgres' }, queue } as never,
+ added,
+ };
+}
+
+async function invoke(args: string[]) {
+ const { context, added } = makeContext(['submit', 'fixture-job', ...args]);
+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});
+ try {
+ let thrown: unknown;
+ try { await runJobsSubmit(context); } catch (error) { thrown = error; }
+ return { thrown, added };
+ } finally {
+ logSpy.mockRestore();
+ }
+}
+
+describe('jobs submit numeric flag validation', () => {
+ test.each([
+ ['--delay', 'nope', 'non-negative integer'],
+ ['--priority', '1.5', 'integer'],
+ ['--max-attempts', '2oops', 'positive integer'],
+ ['--max-stalled', '-1', 'non-negative integer'],
+ ['--backoff-delay', 'Infinity', 'non-negative integer'],
+ ['--backoff-jitter', '1.1', 'from 0 to 1'],
+ ['--timeout-ms', '3ms', 'positive integer'],
+ ['--lock-duration-ms', '9007199254740992', 'positive integer'],
+ ])('%s %s is rejected before enqueue', async (flag, value, message) => {
+ const { thrown, added } = await invoke([flag, value]);
+ expect(thrown, `${flag} assertion: usage error`).toBeInstanceOf(OperationError);
+ expect((thrown as OperationError).code).toBe('invalid_params');
+ expect((thrown as OperationError).message, `${flag} assertion: reports validation`).toContain(message);
+ expect((thrown as OperationError).message).toContain(flag);
+ expect((thrown as OperationError).suggestion).toContain(`e.g. ${flag}`);
+ expect(added, `${flag} assertion: does not enqueue`).toHaveLength(0);
+ });
+
+ test('valid zero delay and zero-valued optional budgets retain their meaning', async () => {
+ const { added, thrown } = await invoke([
+ '--delay', '0', '--priority', '-2', '--max-stalled', '0', '--backoff-delay', '0', '--backoff-jitter', '0',
+ ]);
+ expect(thrown).toBeUndefined();
+ expect(added).toHaveLength(1);
+ expect(added[0]?.[2]).toMatchObject({
+ delay: undefined, priority: -2, max_stalled: 0, backoff_delay: 0, backoff_jitter: 0,
+ });
+ });
+});