Skip to content
Merged
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
13 changes: 13 additions & 0 deletions pm-stack/aggregator/scripts/produce-charge-candidates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,15 @@ async function gmailCandidates(
stagedTriage === undefined
? []
: (JSON.parse(stagedTriage) as unknown[]).map((el) => (typeof el === "string" ? el : JSON.stringify(el)));
// Staged mode never falls back to the live CLI (#4660): a staging with
// fewer responses than queries is a broken staging, and silently
// substituting a live read (or dropping the source) would produce a
// partial batch that looks complete. Fail visibly instead.
if (INPUTS_DIR && stagedResponses.length !== queries.length) {
throw new Error(
`staged gmail-triage.json holds ${stagedResponses.length} response(s) for ${queries.length} gmail queries — staging is short; refusing to fall back to the live gmail CLI in staged mode`,
);
}
for (const [i, query] of queries.entries()) {
const stdout =
stagedResponses[i] ??
Expand Down Expand Up @@ -398,6 +407,10 @@ async function main(): Promise<void> {
);
}
} catch (err) {
// Staged mode (#4660): any gmail failure means the batch would be
// silently partial, so the run fails visibly — non-zero exit, no
// candidates file. Live mode keeps the plaid-only fallback.
if (INPUTS_DIR) throw err;
console.error(
`producer: gmail read failed (${err instanceof Error ? err.message : "error"}); plaid candidates only`,
);
Expand Down
68 changes: 68 additions & 0 deletions pm-stack/aggregator/test/produce-charge-candidates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
// inside "Subtotal" as the charged total, and an explicit paid amount
// wins over an earlier bare total.
import { describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { amountFromBody, gmailMessageDay, isNotChargeSubject } from "../scripts/produce-charge-candidates.ts";

describe("amountFromBody", () => {
Expand Down Expand Up @@ -128,3 +132,67 @@ describe("gmailMessageDay (#2448)", () => {
expect(days).toEqual(["", "2026-10-25", ""]);
});
});

// #4660: staged mode must never fall back to the live Gmail CLI. A
// gmail-triage.json with fewer responses than the producer's queries is
// a broken staging: the run must fail visibly (non-zero exit, no
// candidates file) instead of silently writing a plaid-only batch with
// exit 0. Complete staging keeps working unchanged.
describe("staged mode gmail staging (#4660)", () => {
const script = join(import.meta.dir, "../scripts/produce-charge-candidates.ts");

function stage(gmailResponses: string[]): { dir: string; out: string } {
const dir = mkdtempSync(join(tmpdir(), "charge-inputs-"));
writeFileSync(join(dir, "charge-inputs-manifest.json"), JSON.stringify({ start: "2026-10-01", end: "2026-10-31" }));
writeFileSync(
join(dir, "plaid-transactions.json"),
JSON.stringify({
ok: true,
body: {
accounts: [{ account_id: "a1", name: "Visa Card", mask: "1234" }],
transactions: [
{ account_id: "a1", amount: 12.34, date: "2026-10-15", name: "Coffee Shop", merchant_name: "Coffee Shop", category: ["Food and Drink"] },
],
},
}),
);
writeFileSync(join(dir, "gmail-triage.json"), JSON.stringify(gmailResponses));
return { dir, out: join(dir, "candidates.json") };
}

function runProducer(dir: string, out: string) {
return spawnSync(process.execPath, ["run", script, "--out", out], {
env: { ...process.env, CHARGE_INPUTS_DIR: dir },
encoding: "utf8",
timeout: 60_000,
});
}

const bakery = JSON.stringify({
messages: [{ id: "m1", subject: "Receipt from Bakery - $9.99", date: "2026-10-10" }],
});
const empty = JSON.stringify({ messages: [] });

test("short staging fails visibly and writes no candidates file", () => {
const { dir, out } = stage([bakery]);
const res = runProducer(dir, out);
expect(res.status).not.toBe(0);
expect(res.stderr).toContain("staging is short");
expect(existsSync(out)).toBe(false);
});

test("complete staging yields both sources' candidates", () => {
const { dir, out } = stage([bakery, empty]);
const res = runProducer(dir, out);
expect(res.status).toBe(0);
const written = JSON.parse(readFileSync(out, "utf8")) as {
candidates: { source: string; merchant: string; amountUsd: number }[];
};
expect(written.candidates).toContainEqual(
expect.objectContaining({ source: "gmail", merchant: "Bakery", amountUsd: 9.99 }),
);
expect(written.candidates).toContainEqual(
expect.objectContaining({ source: "plaid", merchant: "Coffee Shop", amountUsd: 12.34 }),
);
});
});
Loading