Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions pm-stack/opencode-usage-export/opencode-usage-export.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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({
Expand All @@ -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);
Expand Down
57 changes: 57 additions & 0 deletions pm-stack/opencode-usage-export/opencode-usage-export.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
});