Skip to content
Merged
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
123 changes: 103 additions & 20 deletions pm-stack/aggregator/scripts/produce-charge-candidates.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
#!/usr/bin/env bun
// produce-charge-candidates (#1057): the Muse-side producer for the
// usage-hub charges auto-matcher. Runs on the sandbox, where the
// Plaid and Gmail connectors live, and writes the period's charge
// usage-hub charges auto-matcher. Writes the period's charge
// candidates to the state file the daily collector
// (scripts/collect-fleet-feed.ts) consumes:
//
// charges-candidates.json { version, generatedAt, period, candidates }
//
// Input modes:
// - live (default): shells out to the Plaid and Gmail connector CLIs
// (PLAID_CLI / GMAIL_CLI) — only possible where those CLIs live
// (the Muse sandbox).
// - staged (CHARGE_INPUTS_DIR set; the split of #4641): reads the
// raw CLI responses a thin sandbox fetcher stages in that
// directory — plaid-transactions.json (raw transactions-get
// stdout), gmail-triage.json (the two +triage responses, in query
// order), gmail-bodies.json (message id -> raw +read stdout) —
// with the period taken from charge-inputs-manifest.json. Bodies
// the producer needs but staging lacks are requested via
// gmail-body-requests.json and land on a later run once the
// fetcher stages them. This is how the producer runs on the
// laptop, next to the collector, with no sandbox repo copy.
//
// Sources:
// - Plaid `transactions-get` for the period (all linked
// institutions). Purchase-like transactions only: pending rows
Expand Down Expand Up @@ -34,8 +48,10 @@
// [--start YYYY-MM-DD] [--end YYYY-MM-DD] [--out <path>] [--skip-gmail]
// Defaults: start = first of the current month, end = today,
// out = CHARGE_CANDIDATES_PATH or the collector's hidden-files path.
// In staged mode the period comes from the staged manifest and
// --start/--end are ignored.
import { execFile } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { readFile, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
Expand All @@ -45,6 +61,16 @@ const run = promisify(execFile);
const PLAID_CLI = process.env.PLAID_CLI ?? "/opt/hatch/bin/plaid";
const GMAIL_CLI = process.env.GMAIL_CLI ?? "/opt/hatch/bin/hatch_gws_cli";
const MAX_GMAIL_BODY_READS = 25;
const INPUTS_DIR = process.env.CHARGE_INPUTS_DIR;

/** Raw staged CLI response text for one staged inputs file, or
* undefined in live mode. Throws in staged mode when the file is
* missing — a stale or absent staging must fail visibly, never
* silently produce an empty batch. */
async function stagedText(name: string): Promise<string | undefined> {
if (!INPUTS_DIR) return undefined;
return readFile(join(INPUTS_DIR, name), "utf8");
}

/** Plaid categories that are money movement, not merchant charges. */
const EXCLUDED_CATEGORIES = new Set(["Transfer", "Payment", "Interest", "Bank Fees"]);
Expand Down Expand Up @@ -86,9 +112,13 @@ function methodLabel(account: PlaidAccount | undefined): string | undefined {
}

async function plaidCandidates(start: string, end: string): Promise<ChargeCandidate[]> {
const { stdout } = await run(PLAID_CLI, ["transactions-get", "--start-date", start, "--end-date", end], {
maxBuffer: 64 * 1024 * 1024,
});
const stdout =
(await stagedText("plaid-transactions.json")) ??
(
await run(PLAID_CLI, ["transactions-get", "--start-date", start, "--end-date", end], {
maxBuffer: 64 * 1024 * 1024,
})
).stdout;
const wrapper = JSON.parse(stdout) as {
ok?: boolean;
body?: { accounts?: PlaidAccount[]; transactions?: PlaidTransaction[] };
Expand Down Expand Up @@ -236,7 +266,7 @@ export function amountFromBody(text: string): string | undefined {
async function gmailCandidates(
start: string,
end: string,
): Promise<{ candidates: ChargeCandidate[]; skipped: number }> {
): Promise<{ candidates: ChargeCandidate[]; skipped: number; bodyRequests: string[] }> {
const gmailDate = (d: string) => d.replaceAll("-", "/");
const after = gmailDate(start);
// before: is exclusive in Gmail search; step one day past the end.
Expand All @@ -253,12 +283,36 @@ async function gmailCandidates(
`${range} (subject:("card alert" OR charged OR purchase)) -from:googlealerts-noreply@google.com -from:notifications@github.com`,
];
const byId = new Map<string, TriageMessage>();
for (const query of queries) {
const { stdout } = await run(GMAIL_CLI, ["gmail", "+triage", "--query", query, "--max", "50", "--format", "json"], {
maxBuffer: 16 * 1024 * 1024,
});
const stagedTriage = await stagedText("gmail-triage.json");
const stagedResponses: string[] =
stagedTriage === undefined
? []
: (JSON.parse(stagedTriage) as unknown[]).map((el) => (typeof el === "string" ? el : JSON.stringify(el)));
for (const [i, query] of queries.entries()) {
const stdout =
stagedResponses[i] ??
(
await run(GMAIL_CLI, ["gmail", "+triage", "--query", query, "--max", "50", "--format", "json"], {
maxBuffer: 16 * 1024 * 1024,
})
).stdout;
for (const m of (JSON.parse(stdout) as { messages?: TriageMessage[] }).messages ?? []) byId.set(m.id, m);
}
// Staged gmail bodies (staged mode only): message id -> raw +read
// stdout. Bodies the producer still needs are collected in
// bodyRequests; the fetcher stages them for a later run.
const stagedBodies = new Map<string, string>();
if (INPUTS_DIR) {
try {
const raw = await readFile(join(INPUTS_DIR, "gmail-bodies.json"), "utf8");
for (const [id, text] of Object.entries(JSON.parse(raw) as Record<string, string>)) {
stagedBodies.set(id, text);
}
} catch {
/* no bodies staged yet */
}
}
const bodyRequests: string[] = [];
const candidates: ChargeCandidate[] = [];
let skipped = 0;
let bodyReads = 0;
Expand All @@ -278,12 +332,22 @@ async function gmailCandidates(
if ((!amount || !merchant) && bodyReads < MAX_GMAIL_BODY_READS) {
bodyReads++;
try {
const { stdout: body } = await run(GMAIL_CLI, ["gmail", "+read", "--id", m.id, "--format", "json"], {
maxBuffer: 16 * 1024 * 1024,
});
const text = (JSON.parse(body) as { body_text?: string }).body_text ?? "";
amount ??= amountFromBody(text);
merchant ??= cleanMerchant(/\bmerchant[:\s]+([A-Za-z0-9][A-Za-z0-9 .&'*+-]{1,40})/i.exec(text)?.[1]);
let body: string | undefined;
if (INPUTS_DIR) {
body = stagedBodies.get(m.id);
if (body === undefined) bodyRequests.push(m.id);
} else {
body = (
await run(GMAIL_CLI, ["gmail", "+read", "--id", m.id, "--format", "json"], {
maxBuffer: 16 * 1024 * 1024,
})
).stdout;
}
if (body !== undefined) {
const text = (JSON.parse(body) as { body_text?: string }).body_text ?? "";
amount ??= amountFromBody(text);
merchant ??= cleanMerchant(/\bmerchant[:\s]+([A-Za-z0-9][A-Za-z0-9 .&'*+-]{1,40})/i.exec(text)?.[1]);
}
} catch {
/* unreadable body: counted as skipped below */
}
Expand All @@ -294,13 +358,23 @@ async function gmailCandidates(
}
candidates.push({ source: "gmail", at, merchant, amountUsd: Number(amount.replaceAll(",", "")) });
}
return { candidates, skipped };
return { candidates, skipped, bodyRequests };
}

async function main(): Promise<void> {
const now = new Date();
const start = argValue("--start") ?? isoDay(new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)));
const end = argValue("--end") ?? isoDay(now);
let start = argValue("--start") ?? isoDay(new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)));
let end = argValue("--end") ?? isoDay(now);
if (INPUTS_DIR) {
// Staged mode: the fetcher's manifest period governs — the staged
// payloads were fetched for exactly that window.
const manifest = JSON.parse(await readFile(join(INPUTS_DIR, "charge-inputs-manifest.json"), "utf8")) as {
start: string;
end: string;
};
start = manifest.start;
end = manifest.end;
}
const outPath =
argValue("--out") ??
process.env.CHARGE_CANDIDATES_PATH ??
Expand All @@ -314,6 +388,15 @@ async function main(): Promise<void> {
const g = await gmailCandidates(start, end);
gmail = g.candidates;
gmailSkipped = g.skipped;
if (INPUTS_DIR && g.bodyRequests.length > 0) {
await writeFile(
join(INPUTS_DIR, "gmail-body-requests.json"),
JSON.stringify({ ids: g.bodyRequests, at: now.toISOString() }, null, 2),
);
console.error(
`producer: ${g.bodyRequests.length} gmail bodies not yet staged; requested from the fetcher, those candidates land on a later run`,
);
}
} catch (err) {
console.error(
`producer: gmail read failed (${err instanceof Error ? err.message : "error"}); plaid candidates only`,
Expand Down
Loading