From 1318049c90b15cc7cc0e2381e273a81d2ede985f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 3 Nov 2026 01:51:31 -0600 Subject: [PATCH] fix(usage-export): validate hours flags --- .../opencode-usage-export.mjs | 40 +++++++++++-- .../opencode-usage-export.test.mjs | 57 +++++++++++++++++++ 2 files changed, 93 insertions(+), 4 deletions(-) diff --git a/pm-stack/opencode-usage-export/opencode-usage-export.mjs b/pm-stack/opencode-usage-export/opencode-usage-export.mjs index 32935bf434..a1978ddfc7 100755 --- a/pm-stack/opencode-usage-export/opencode-usage-export.mjs +++ b/pm-stack/opencode-usage-export/opencode-usage-export.mjs @@ -51,6 +51,8 @@ * * Failure documents carry status + attemptedAt + detail and NO * sessions — a failed tick can never be mistaken for a reading: + * invalid-argument a CLI value flag is missing, flag-shaped, NaN, + * infinite, zero, or negative. Exit 2. * store-missing no candidate DB file exists. Exit 3. * store-stale candidates exist but none has fresh session_v2 * activity (the store moved somewhere unknown, or @@ -308,19 +310,49 @@ async function readState(outDir) { } } +/** Extract --out-dir without validating anything else, so even a + * usage failure can record its document where the caller asked. A + * missing or flag-shaped --out-dir falls back to the default. */ +function peekOutDir(argv, home) { + for (let i = 0; i < argv.length - 1; i += 1) { + if (argv[i] === "--out-dir") { + const v = argv[i + 1]; + if (v != null && !v.startsWith("--")) return v; + } + } + return join(home, "atlas/opencode-usage-export"); +} + function parseArgs(argv) { const args = { db: null, outDir: null, windowHours: DEFAULT_WINDOW_HOURS, freshHours: DEFAULT_FRESH_HOURS }; for (let i = 0; i < argv.length; i += 1) { const a = argv[i]; if (a === "--db") args.db = argv[++i]; else if (a === "--out-dir") args.outDir = argv[++i]; - else if (a === "--window-hours") args.windowHours = Number(argv[++i]); - else if (a === "--fresh-hours") args.freshHours = Number(argv[++i]); + else if (a === "--window-hours") args.windowHours = parseHoursFlag(a, argv[++i]); + else if (a === "--fresh-hours") args.freshHours = parseHoursFlag(a, argv[++i]); else throw new Error(`unknown argument: ${a}`); } return args; } +/** Validate a value-taking hours flag. A missing token, a flag-shaped + * token, NaN, an infinite value, zero, or a negative value is a usage + * error (exit 2) that names the flag — raised before any store is + * opened or read, so junk can never produce a zero-filled success or + * a misleading store-stale diagnosis. */ +function parseHoursFlag(flag, raw) { + const value = Number(raw); + if (raw == null || !Number.isFinite(value) || value <= 0) { + throw new ExportError( + "invalid-argument", + 2, + `${flag} requires a positive finite number of hours, got ${raw == null ? "(missing)" : JSON.stringify(String(raw))}`, + ); + } + return value; +} + /** One exporter tick. Injectable `now`/`home` keep the tests offline * and deterministic; production uses the defaults. */ export async function run({ @@ -329,10 +361,10 @@ export async function run({ now = Date.now(), home = homedir(), } = {}) { - const args = parseArgs(argv); - const outDir = args.outDir ?? join(home, "atlas/opencode-usage-export"); const attemptedAt = new Date(now).toISOString(); + const outDir = peekOutDir(argv, home); try { + const args = parseArgs(argv); const explicit = args.db ?? env.OPENCODE_USAGE_DB ?? null; const candidates = explicit ? [explicit] : defaultCandidatePaths(home); const state = await readState(outDir); diff --git a/pm-stack/opencode-usage-export/opencode-usage-export.test.mjs b/pm-stack/opencode-usage-export/opencode-usage-export.test.mjs index 8dfe251632..c567a4bbe5 100644 --- a/pm-stack/opencode-usage-export/opencode-usage-export.test.mjs +++ b/pm-stack/opencode-usage-export/opencode-usage-export.test.mjs @@ -156,3 +156,60 @@ test("no candidate exists: store-missing failure document, exit 3", async () => assert.equal(doc.status, "store-missing"); assert.equal(doc.sessions, undefined); }); + +test("invalid --window-hours values fail closed with usage exit 2 and name the flag", async () => { + const { home, outDir } = await fakeHome(); + await makeStore(defaultDb(home), { sessions: [{ id: "ses_live" }] }); + for (const extra of [["banana"], ["-5"], ["0"], ["Infinity"], ["--fresh-hours"], []]) { + const { exitCode, doc } = await run({ home, now: NOW, argv: ["--out-dir", outDir, "--window-hours", ...extra] }); + assert.equal(exitCode, 2, `argv tail: ${JSON.stringify(extra)}`); + assert.equal(doc.status, "invalid-argument"); + assert.equal(doc.sessions, undefined); + assert.match(doc.detail, /--window-hours/); + } + const latest = JSON.parse(await readFile(join(outDir, "latest.json"), "utf8")); + assert.equal(latest.status, "invalid-argument"); +}); + +test("invalid --fresh-hours values fail closed with usage exit 2 and name the flag", async () => { + const { home, outDir } = await fakeHome(); + await makeStore(defaultDb(home), { sessions: [{ id: "ses_live" }] }); + for (const extra of [["banana"], ["-1"], ["0"], ["Infinity"], []]) { + const { exitCode, doc } = await run({ home, now: NOW, argv: ["--out-dir", outDir, "--fresh-hours", ...extra] }); + assert.equal(exitCode, 2, `argv tail: ${JSON.stringify(extra)}`); + assert.equal(doc.status, "invalid-argument"); + assert.equal(doc.sessions, undefined); + assert.match(doc.detail, /--fresh-hours/); + } +}); + +test("invalid flags are rejected before any store read", async () => { + const { home, outDir } = await fakeHome(); + // No store exists at all: a store-first implementation would report + // store-missing (3); validation-first reports invalid-argument (2). + const { exitCode, doc } = await run({ + home, now: NOW, + argv: ["--out-dir", outDir, "--db", join(home, "nope.db"), "--window-hours", "banana"], + }); + assert.equal(exitCode, 2); + assert.equal(doc.status, "invalid-argument"); + assert.match(doc.detail, /--window-hours/); +}); + +test("explicit valid window and freshness values retain existing behavior", async () => { + const { home, outDir } = await fakeHome(); + await makeStore(defaultDb(home), { + sessions: [ + { id: "ses_recent" }, + { id: "ses_old", updated: NOW - 48 * HOUR, created: NOW - 49 * HOUR }, + ], + messages: [assistantMsg("ses_recent")], + }); + const { exitCode, doc } = await run({ + home, now: NOW, argv: ["--out-dir", outDir, "--window-hours", "48", "--fresh-hours", "12"], + }); + assert.equal(exitCode, 0); + assert.equal(doc.status, "ok"); + assert.equal(doc.windowHours, 48); + assert.equal(doc.sessions.length, 2); // both sessions fall inside the 48h window +});