diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index bcfe345158..15c2e22fbb 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -11,6 +11,16 @@ // - the sandbox OpenCode server API — sandbox session feed entries // (shared mapper, src/sources/opencode.ts) + live per-pool burn // attribution for the quota view. +// - charges-candidates.json — the Muse-side producer's +// (#1057, scripts/produce-charge-candidates.ts) Plaid + Gmail +// charge candidates for the period. The collector runs the pure +// matcher (src/charges-match.ts) over them, merges the rows with +// the hand-fed registry/quota-view charges (auto wins on a +// duplicate), and surfaces unmatched SaaS/AI-looking charges in +// the feed's chargesAttention exactly once — charges-surfaced- +// state.json persists the keys already shown. Absent file = the +// pre-#1057 hand-fed charges only. No balances or debt data ever +// pass through: candidates are charge evidence only. // - jules-review-state.json — keeper supervision entries annotate // matching sessions as evidence. // - orchestration.json — the orchestration job's latest section @@ -51,6 +61,8 @@ // USAGE_SNAPSHOT_OUTBOX_PATH (the §4 writers' outbox JSONL — stewardship // and check-usage append records there; each collection drains it into // the feed's snapshots field for the laptop store to ingest), +// CHARGE_CANDIDATES_PATH / CHARGES_SURFACED_STATE_PATH (#1057: the +// producer's candidates file and the collector's surfaced-once state), // SUPABASE_PROJECT_REF (default: the muse-dev project), // AA_OPENCODE_CONFIG_PATH (default: the repo's .opencode/opencode.jsonc). import { execFile } from "node:child_process"; @@ -70,6 +82,8 @@ import type { SessionFeedEntry, SessionRecord, } from "../src/model.ts"; +import { matchCharges, type UnmatchedCharge } from "../src/charges-match.ts"; +import { filterNewUnmatched, mergeChargeRows, parseChargeCandidates } from "../src/charges-collect.ts"; import { extractQuotaPools } from "../src/quota-extract.ts"; import { computeChoices } from "../src/quota-guidance.ts"; import { extractCharges, extractPaygLines, extractSaasServices, extractSubscriptions } from "../src/saas-extract.ts"; @@ -102,6 +116,8 @@ const dnsRegisterPath = const launchRecordsPath = process.env.CLAUDE_LAUNCH_RECORDS_PATH ?? join(HIDDEN, "claude-launch-records.jsonl"); const quotaRegistryPath = process.env.QUOTA_REGISTRY_PATH ?? join(HIDDEN, "provider-quota-registry.md"); const snapshotOutboxPath = process.env.USAGE_SNAPSHOT_OUTBOX_PATH ?? join(HIDDEN, "usage-snapshot-outbox.jsonl"); +const chargeCandidatesPath = process.env.CHARGE_CANDIDATES_PATH ?? join(HIDDEN, "charges-candidates.json"); +const chargesSurfacedStatePath = process.env.CHARGES_SURFACED_STATE_PATH ?? join(HIDDEN, "charges-surfaced-state.json"); const opencodeConfigPath = process.env.AA_OPENCODE_CONFIG_PATH ?? join(PKG, "..", "..", ".opencode", "opencode.jsonc"); const serverUrl = process.env.SANDBOX_OPENCODE_URL ?? "http://127.0.0.1:4096"; const passwordFile = @@ -394,6 +410,45 @@ async function main(): Promise { subscriptions = extractSubscriptions(quotaViewText); } + // --- charges auto-matching (#1057) ------------------------------------- + // The producer's candidates (Plaid + Gmail) run through the pure + // matcher; auto rows merge over the hand-fed rows above, and + // unmatched SaaS/AI charges surface exactly once via the persisted + // surfaced-state. Fail-soft like every other section: no readable + // candidates file = the hand-fed charges stand as they were. + let chargesAttention: UnmatchedCharge[] | undefined; + try { + const candidates = parseChargeCandidates(JSON.parse(await readFile(chargeCandidatesPath, "utf8"))); + if (candidates.length) { + const auto = matchCharges( + candidates, + (saas ?? []).map((s) => ({ name: s.name })), + ); + charges = mergeChargeRows(auto.rows, charges ?? []); + let surfaced = new Set(); + try { + const state: unknown = JSON.parse(await readFile(chargesSurfacedStatePath, "utf8")); + const keys = (state as { surfaced?: unknown }).surfaced; + if (Array.isArray(keys)) surfaced = new Set(keys.filter((k): k is string => typeof k === "string")); + } catch { + /* no state yet: everything unmatched is new */ + } + const { fresh, keys } = filterNewUnmatched(auto.unmatchedSaas, surfaced); + if (fresh.length) { + chargesAttention = fresh; + await writeFile( + chargesSurfacedStatePath, + JSON.stringify({ version: 1, surfaced: keys, updatedAt: now.toISOString() }, null, 2), + ); + } + console.log( + `collector: charges auto-match — ${auto.rows.length} rows from ${candidates.length} candidates, ${fresh.length} new unmatched surfaced`, + ); + } + } catch { + console.error("collector: charge candidates unreadable; hub charges stay hand-fed only this run"); + } + // --- sandbox attention + burn ------------------------------------------- let attention: SessionFeedEntry[] = []; try { @@ -563,6 +618,7 @@ async function main(): Promise { ...(saas ? { saas } : {}), ...(payg ? { payg } : {}), ...(charges ? { charges } : {}), + ...(chargesAttention ? { chargesAttention } : {}), ...(subscriptions ? { subscriptions } : {}), ...(dedupedSnapshots.length ? { snapshots: dedupedSnapshots } : {}), ...(projects ? { projects } : {}), diff --git a/pm-stack/aggregator/scripts/produce-charge-candidates.ts b/pm-stack/aggregator/scripts/produce-charge-candidates.ts new file mode 100644 index 0000000000..c470b44e54 --- /dev/null +++ b/pm-stack/aggregator/scripts/produce-charge-candidates.ts @@ -0,0 +1,260 @@ +#!/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 +// candidates to the state file the daily collector +// (scripts/collect-fleet-feed.ts) consumes: +// +// charges-candidates.json { version, generatedAt, period, candidates } +// +// Sources: +// - Plaid `transactions-get` for the period (all linked +// institutions). Purchase-like transactions only: pending rows +// and the money-movement categories (Transfer, Payment, Interest, +// Bank Fees) are excluded — card payments, balance transfers, +// interest and fees are not charges to a merchant. Plaid is the +// source of record; the matcher prefers it on a cross-source tie. +// - Gmail receipt / card-alert mail for the period, via two +// newest-first searches (receipts/invoices, then charged/alert +// mail) merged by message id. Amount and merchant are parsed +// conservatively from the subject; receipts whose subject +// carries no amount get one bounded body read (max 25) before +// being skipped. Cancellations/refunds, card-payment +// confirmations, promotions, and GitHub notification mail are +// excluded by construction. Unparseable mail is counted in the +// log line, never guessed at: a card alert that names no +// merchant is skipped (the sender is the bank, not the +// merchant), because Plaid already covers that charge. +// +// Charge evidence only: date, merchant, amount, payment-method +// label (card brand + mask). No balances, no debt, no account +// numbers, no account-owner names ever enter the file. +// +// Usage: bun run scripts/produce-charge-candidates.ts +// [--start YYYY-MM-DD] [--end YYYY-MM-DD] [--out ] [--skip-gmail] +// Defaults: start = first of the current month, end = today, +// out = CHARGE_CANDIDATES_PATH or the collector's hidden-files path. +import { execFile } from "node:child_process"; +import { writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import type { ChargeCandidate } from "../src/charges-match.ts"; + +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; + +/** Plaid categories that are money movement, not merchant charges. */ +const EXCLUDED_CATEGORIES = new Set(["Transfer", "Payment", "Interest", "Bank Fees"]); + +function argValue(flag: string): string | undefined { + const i = process.argv.indexOf(flag); + return i >= 0 ? process.argv[i + 1] : undefined; +} + +function isoDay(d: Date): string { + return d.toISOString().slice(0, 10); +} + +interface PlaidAccount { + account_id: string; + name?: string; + mask?: string | null; +} + +interface PlaidTransaction { + account_id: string; + amount: number; + date: string; + name?: string; + merchant_name?: string | null; + pending?: boolean; + category?: string[] | null; +} + +/** "Costco Anywhere Visa® Card by Citi" + 9545 -> "Visa •9545". */ +function methodLabel(account: PlaidAccount | undefined): string | undefined { + if (!account?.mask) return undefined; + const name = account.name ?? ""; + if (/visa/i.test(name)) return `Visa •${account.mask}`; + if (/mastercard/i.test(name)) return `Mastercard •${account.mask}`; + if (/amex|american express/i.test(name)) return `Amex •${account.mask}`; + if (/discover/i.test(name)) return `Discover •${account.mask}`; + return `card •${account.mask}`; +} + +async function plaidCandidates(start: string, end: string): Promise { + const { stdout } = await run(PLAID_CLI, ["transactions-get", "--start-date", start, "--end-date", end], { + maxBuffer: 64 * 1024 * 1024, + }); + const wrapper = JSON.parse(stdout) as { + ok?: boolean; + body?: { accounts?: PlaidAccount[]; transactions?: PlaidTransaction[] }; + }; + if (!wrapper.ok || !wrapper.body) throw new Error("plaid transactions-get returned no body"); + const accounts = new Map((wrapper.body.accounts ?? []).map((a) => [a.account_id, a])); + const out: ChargeCandidate[] = []; + for (const t of wrapper.body.transactions ?? []) { + if (t.pending || !(t.amount > 0)) continue; + if (EXCLUDED_CATEGORIES.has(t.category?.[0] ?? "")) continue; + const merchant = (t.merchant_name ?? t.name ?? "").trim(); + if (!merchant || !/^\d{4}-\d{2}-\d{2}$/.test(t.date)) continue; + const method = methodLabel(accounts.get(t.account_id)); + out.push({ source: "plaid", at: t.date, merchant, amountUsd: t.amount, ...(method ? { method } : {}) }); + } + return out; +} + +interface TriageMessage { + id: string; + from?: string; + subject?: string; + message_sent_at?: { user_local?: string }; + date?: string; +} + +const AMOUNT_RE = /\$([\d,]+\.\d{2})/; + +/** "Oct 25, 2026" / "2026-10-25" as a merchant is a parse failure, not a merchant. */ +function isDateLike(s: string): boolean { + return /^\d{4}-\d{2}-\d{2}$/.test(s) || /^[A-Z][a-z]{2,8}\s+\d{1,2},\s*\d{4}$/.test(s); +} + +function cleanMerchant(raw: string | undefined): string | undefined { + const m = raw?.trim(); + return m && !isDateLike(m) ? m : undefined; +} + +function merchantFromSubject(subject: string): string | undefined { + // "Your Google Play Order Receipt from Oct 25, 2026": the merchant + // leads, the date trails — capture the lead before "receipt from" + // can grab the date. + return ( + cleanMerchant(/^your (.+?)(?:\s+order)?\s+(?:receipt|invoice)\b/i.exec(subject)?.[1]) ?? + cleanMerchant(/(?:receipt|invoice|payment) from ([^#@<>]+?)(?:\s+#|\s*[-–|]\s*|\s*$)/i.exec(subject)?.[1]) ?? + cleanMerchant(/^your (.+?)(?:\s+api)?\s+(?:receipt|invoice)\b/i.exec(subject)?.[1]) ?? + cleanMerchant(/(?:payment to|paid to)\s+([^#@<>]+?)\s*$/i.exec(subject)?.[1]) ?? + cleanMerchant( + /\b(?:at|to)\s+([A-Z0-9][A-Za-z0-9 .&'*+-]{1,40}?)(?:\s+on\b|\s+was\b|\s+for\b|\.$|\s*$)/.exec( + subject.replace(AMOUNT_RE, " "), + )?.[1], + ) + ); +} + +/** Subjects that are not charges: money back, money movement, marketing. */ +function isNotChargeSubject(subject: string): boolean { + return ( + /cancellation|refund/i.test(subject) || + /last payment|payment received|payment was received|payment has posted|thank you for your payment|thanks for your payment|payment is due|payment reminder|payment coming due|autopay payment/i.test( + subject, + ) || + /% off|coupon|save \d|free .* with .* purchase/i.test(subject) + ); +} + +async function gmailCandidates( + start: string, + end: string, +): Promise<{ candidates: ChargeCandidate[]; skipped: number }> { + const gmailDate = (d: string) => d.replaceAll("-", "/"); + const after = gmailDate(start); + // before: is exclusive in Gmail search; step one day past the end. + const endNext = isoDay(new Date(Date.parse(end) + 86_400_000)); + // Two searches, merged: receipts/invoices are the SaaS evidence; + // charged/alert mail mirrors card charges. "alert" alone is + // unusable as a subject term — Google Alert digests match it + // dozens of times a day and crowd a newest-first page — and + // GitHub notification subjects quote issue titles full of + // receipt/invoice words, so both are excluded by construction. + const range = `after:${after} before:${gmailDate(endNext)}`; + const queries = [ + `${range} (subject:(receipt OR invoice)) -from:notifications@github.com`, + `${range} (subject:("card alert" OR charged OR purchase)) -from:googlealerts-noreply@google.com -from:notifications@github.com`, + ]; + const byId = new Map(); + for (const query of queries) { + const { stdout } = await run(GMAIL_CLI, ["gmail", "+triage", "--query", query, "--max", "50", "--format", "json"], { + maxBuffer: 16 * 1024 * 1024, + }); + for (const m of (JSON.parse(stdout) as { messages?: TriageMessage[] }).messages ?? []) byId.set(m.id, m); + } + const candidates: ChargeCandidate[] = []; + let skipped = 0; + let bodyReads = 0; + for (const m of byId.values()) { + const subject = m.subject ?? ""; + if (isNotChargeSubject(subject)) { + skipped++; + continue; + } + const at = (m.message_sent_at?.user_local ?? "").slice(0, 10) || isoDay(new Date(m.date ?? "")); + if (!/^\d{4}-\d{2}-\d{2}$/.test(at)) { + skipped++; + continue; + } + let amount = AMOUNT_RE.exec(subject)?.[1]; + let merchant = merchantFromSubject(subject); + 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 ??= + /(?:amount paid|amount charged|total charged|transaction amount|total)[:\s]*\$([\d,]+\.\d{2})/i.exec( + text, + )?.[1] ?? AMOUNT_RE.exec(text)?.[1]; + 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 */ + } + } + if (!amount || !merchant) { + skipped++; + continue; + } + candidates.push({ source: "gmail", at, merchant, amountUsd: Number(amount.replaceAll(",", "")) }); + } + return { candidates, skipped }; +} + +async function main(): Promise { + const now = new Date(); + const start = argValue("--start") ?? isoDay(new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1))); + const end = argValue("--end") ?? isoDay(now); + const outPath = + argValue("--out") ?? + process.env.CHARGE_CANDIDATES_PATH ?? + join(homedir(), "workspace/goals/keep-the-four-repos-healthy/hidden_files/charges-candidates.json"); + + const plaid = await plaidCandidates(start, end); + let gmail: ChargeCandidate[] = []; + let gmailSkipped = 0; + if (!process.argv.includes("--skip-gmail")) { + try { + const g = await gmailCandidates(start, end); + gmail = g.candidates; + gmailSkipped = g.skipped; + } catch (err) { + console.error( + `producer: gmail read failed (${err instanceof Error ? err.message : "error"}); plaid candidates only`, + ); + } + } + const candidates = [...plaid, ...gmail].sort( + (a, b) => a.at.localeCompare(b.at) || a.merchant.localeCompare(b.merchant), + ); + await writeFile( + outPath, + JSON.stringify({ version: 1, generatedAt: now.toISOString(), period: { start, end }, candidates }, null, 2), + ); + console.log( + `producer: wrote ${outPath} — ${candidates.length} candidates for ${start}..${end} (plaid ${plaid.length}, gmail ${gmail.length}, gmail skipped ${gmailSkipped})`, + ); +} + +await main(); diff --git a/pm-stack/aggregator/src/charges-collect.ts b/pm-stack/aggregator/src/charges-collect.ts new file mode 100644 index 0000000000..7a75fa7fc2 --- /dev/null +++ b/pm-stack/aggregator/src/charges-collect.ts @@ -0,0 +1,120 @@ +// charges-collect (#1057): the collector-side glue around the pure +// matcher in charges-match.ts. The Muse-side producer +// (scripts/produce-charge-candidates.ts) writes the period's Plaid + +// Gmail charge candidates to a state file; the daily collector reads +// that file here, runs matchCharges, merges the auto-matched rows +// with the hand-fed registry/quota-view rows (auto wins on a +// duplicate — it is the fresher, structured read), and surfaces +// unmatched SaaS/AI-looking charges in the hub attention strip +// exactly once via a persisted surfaced-keys state file. +// +// Everything here is pure except the state the collector itself +// passes in/out; file IO lives in collect-fleet-feed.ts, following +// the same split as charges-match.ts (decisions here, state there). + +import { + DEDUPE_WINDOW_DAYS, + normalizeMerchantName, + type ChargeCandidate, + type UnmatchedCharge, +} from "./charges-match.ts"; +import type { ChargeRow } from "./model.ts"; + +/** + * Structural validation of the producer's candidates file. Accepts + * the canonical `{ candidates: [...] }` object or a bare array. + * Malformed entries are dropped, never guessed at: a candidate needs + * a known source, an ISO date, a merchant string, and a finite + * amount. Returns [] for anything unusable (the collector logs and + * falls back to hand-fed rows only). + */ +export function parseChargeCandidates(raw: unknown): ChargeCandidate[] { + const list: unknown = Array.isArray(raw) + ? raw + : typeof raw === "object" && raw !== null && Array.isArray((raw as { candidates?: unknown }).candidates) + ? (raw as { candidates: unknown[] }).candidates + : null; + if (!Array.isArray(list)) return []; + const out: ChargeCandidate[] = []; + for (const entry of list) { + if (typeof entry !== "object" || entry === null) continue; + const c = entry as Partial; + if (c.source !== "plaid" && c.source !== "gmail") continue; + if (typeof c.at !== "string" || !/^\d{4}-\d{2}-\d{2}/.test(c.at)) continue; + if (typeof c.merchant !== "string" || !c.merchant.trim()) continue; + if (typeof c.amountUsd !== "number" || !Number.isFinite(c.amountUsd)) continue; + out.push({ + source: c.source, + at: c.at.slice(0, 10), + merchant: c.merchant, + amountUsd: c.amountUsd, + ...(typeof c.method === "string" && c.method ? { method: c.method } : {}), + }); + } + return out; +} + +function squash(normalized: string): string { + return normalized.replace(/\s+/g, ""); +} + +function daysBetween(a: string, b: string): number { + const ms = Math.abs(Date.parse(a) - Date.parse(b)); + return Math.floor(ms / 86_400_000); +} + +/** + * Does a hand-fed row describe the same charge as an auto-matched + * row? Same amount, dates within the matcher's dedupe window, and + * merchant/label token strings that contain one another once + * squashed ("Meta PAYG spill" vs "METAPAY" both squash around + * METAPAY). Conservative: a hand-fed row is only dropped when an + * auto row plausibly IS that charge. + */ +function sameCharge(handFed: ChargeRow, auto: ChargeRow): boolean { + if (handFed.amountUsd !== auto.amountUsd) return false; + if (daysBetween(handFed.at, auto.at) > DEDUPE_WINDOW_DAYS) return false; + const a = squash(normalizeMerchantName(handFed.label)); + const b = squash(normalizeMerchantName(auto.label)); + if (!a || !b) return false; + return a.includes(b) || b.includes(a); +} + +/** + * The feed's charges section: auto-matched rows first (source of + * record), plus any hand-fed rows the auto read did not already + * cover, date-ordered like matchCharges output. With no auto rows + * this is exactly the hand-fed list, sorted — the pre-#1057 feed. + */ +export function mergeChargeRows(autoRows: ChargeRow[], handFedRows: ChargeRow[]): ChargeRow[] { + const kept = handFedRows.filter((row) => !autoRows.some((auto) => sameCharge(row, auto))); + return [...autoRows, ...kept].sort((x, y) => x.at.localeCompare(y.at) || x.label.localeCompare(y.label)); +} + +/** Stable identity of one unmatched charge for the surfaced-once state. */ +export function unmatchedKey(u: UnmatchedCharge): string { + return `${u.normalized}|${u.amountUsd.toFixed(2)}|${u.at}`; +} + +/** + * Split unmatched charges into those never surfaced before (they go + * to the attention strip this run) and the full key set to persist. + * A charge surfaces exactly once: once its key is in the persisted + * set it never surfaces again, even though it stays in the charges + * rows as evidence. + */ +export function filterNewUnmatched( + unmatched: UnmatchedCharge[], + surfaced: ReadonlySet, +): { fresh: UnmatchedCharge[]; keys: string[] } { + const keys = new Set(surfaced); + const fresh: UnmatchedCharge[] = []; + for (const u of unmatched) { + const key = unmatchedKey(u); + if (!keys.has(key)) { + keys.add(key); + fresh.push(u); + } + } + return { fresh, keys: [...keys].sort() }; +} diff --git a/pm-stack/aggregator/src/charges-match.ts b/pm-stack/aggregator/src/charges-match.ts index 4f3c0c7f87..6740a5944f 100644 --- a/pm-stack/aggregator/src/charges-match.ts +++ b/pm-stack/aggregator/src/charges-match.ts @@ -142,6 +142,16 @@ const SAAS_MARKERS = [ "LINODE", "STRIPE", "PADDLE", + // The fleet's own AI tooling, seen in the October 2026 reads: + // charges to these are exactly the unmatched SaaS/AI charges the + // hub exists to surface. + "META", + "CLINE", + "OPENCODE", + "OPENDESIGN", + "COMMANDCODE", + "WINDSURF", + "CODEIUM", ]; /** Heuristic: does this normalized merchant look like a SaaS/AI charge? */ diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index 695dcf0408..ae48066ea4 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -4,6 +4,7 @@ // record live on the sandbox). The aggregator renders the feed as-is; // a stale feed keeps rendering with its age stated in provenance. import { readFile } from "node:fs/promises"; +import type { UnmatchedCharge } from "./charges-match.ts"; import type { AaFeedSection, ChargeRow, @@ -43,6 +44,12 @@ export interface FleetFeed { payg?: PaygLine[]; /** Hub charges evidence (§2.4), from the same dated records. */ charges?: ChargeRow[]; + /** Charges auto-matching (#1057): unmatched SaaS/AI-looking charges + * surfacing for the FIRST time this run — the collector filters out + * anything its persisted surfaced-state already showed, so a charge + * appears here exactly once and the live source turns each entry + * into a hub attention flag. Absent when nothing new surfaced. */ + chargesAttention?: UnmatchedCharge[]; /** Hub subscriptions strip rows (Q5: renewal-only). */ subscriptions?: { name: string; plan: string; renewsAt: string | null }[]; /** Usage snapshot records (hub §4 writers): derived by the collector diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index 0e55b711a4..15a480d089 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -1182,7 +1182,7 @@ export interface ChargeRow { * projected unbilled PAYG over $5 (unbilled accrual only, Q3 default). */ export interface AttentionFlag { - kind: "over-limit" | "payg-unbilled"; + kind: "over-limit" | "payg-unbilled" | "unmatched-charge"; label: string; detail: string; href: string; diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 69595ad1a7..ae9bbd44db 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -29,6 +29,7 @@ import { fixtureSource } from "./fixtures.ts"; import { mapServerSessions, type MappedSessions } from "./opencode.ts"; import { type AaFeedSection, + type AttentionFlag, type BoardItem, type Comment, type DnsSection, @@ -812,12 +813,23 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise ({ + kind: "unmatched-charge", + label: `${u.merchant} — unrecognized SaaS/AI charge`, + detail: `$${u.amountUsd.toFixed(2)} on ${u.at} via ${u.source === "plaid" ? "Plaid" : "Gmail alert"} — no hub service matched; classify it or add the service`, + href: "/quota", + severity: u.amountUsd, + })); return { ...partial, chargesNote: partial.charges.length ? undefined : "No charge evidence in the feed's records yet — rows appear as Plaid/Gmail receipt evidence is recorded (§2.4).", - attention: buildAttentionFlags(feed.quota, partial), + attention: [...buildAttentionFlags(feed.quota, partial), ...chargeFlags], domains, history, }; diff --git a/pm-stack/aggregator/test/charges-collect.test.ts b/pm-stack/aggregator/test/charges-collect.test.ts new file mode 100644 index 0000000000..0e42028af2 --- /dev/null +++ b/pm-stack/aggregator/test/charges-collect.test.ts @@ -0,0 +1,152 @@ +// #1057: collector glue for the charges auto-matcher — candidate +// file validation, auto/hand-fed row merge, surfaced-once state, +// and the packet's replay acceptance (one row per charge, rerun +// adds nothing and re-surfaces nothing). +import { describe, expect, test } from "bun:test"; +import { filterNewUnmatched, mergeChargeRows, parseChargeCandidates, unmatchedKey } from "../src/charges-collect.ts"; +import { matchCharges, type ChargeCandidate } from "../src/charges-match.ts"; +import type { ChargeRow } from "../src/model.ts"; + +const SERVICES = [ + { name: "Anthropic", aliases: ["Claude"] }, + { name: "OpenAI", aliases: ["ChatGPT"] }, + { name: "Cloudflare" }, +]; + +describe("parseChargeCandidates", () => { + test("accepts the canonical object form and keeps valid entries only", () => { + const raw = { + version: 1, + candidates: [ + { source: "plaid", at: "2026-10-28", merchant: "METAPAY*UC5DPA22Y4 US", amountUsd: 20, method: "Visa •7535" }, + { source: "gmail", at: "2026-10-27T14:03:00Z", merchant: "MetaPay", amountUsd: 20 }, + { source: "carrier-pigeon", at: "2026-10-27", merchant: "Nope", amountUsd: 5 }, + { source: "plaid", at: "not-a-date", merchant: "Nope", amountUsd: 5 }, + { source: "plaid", at: "2026-10-27", merchant: "Nope", amountUsd: "20" }, + { source: "plaid", at: "2026-10-27", merchant: " ", amountUsd: 5 }, + ], + }; + expect(parseChargeCandidates(raw)).toEqual([ + { source: "plaid", at: "2026-10-28", merchant: "METAPAY*UC5DPA22Y4 US", amountUsd: 20, method: "Visa •7535" }, + { source: "gmail", at: "2026-10-27", merchant: "MetaPay", amountUsd: 20 }, + ]); + }); + + test("accepts a bare array; rejects anything else", () => { + expect( + parseChargeCandidates([{ source: "gmail", at: "2026-10-01", merchant: "Cursor", amountUsd: 20 }]), + ).toHaveLength(1); + expect(parseChargeCandidates(null)).toEqual([]); + expect(parseChargeCandidates("nope")).toEqual([]); + expect(parseChargeCandidates({ charges: [] })).toEqual([]); + }); +}); + +describe("mergeChargeRows", () => { + const auto: ChargeRow[] = [ + { at: "2026-10-28", label: "METAPAY*UC5DPA22Y4 US", amountUsd: 20, method: "Visa •7535", source: "Plaid" }, + { at: "2026-10-11", label: "Anthropic", amountUsd: 100, method: "card", source: "Plaid" }, + ]; + + test("a hand-fed row for the same charge is dropped (auto is source of record)", () => { + const handFed: ChargeRow[] = [ + { + at: "2026-10-25", + label: "Meta PAYG spill", + amountUsd: 20, + method: "Visa •7535", + source: "Gmail card alert (registry billing incidents)", + }, + ]; + // 2026-10-25 vs 2026-10-28 is inside the 3-day window, same + // amount, and squashed "METAPAYGSPILL" contains "METAPAY" — so + // the hand-fed row dedupes against the auto row (date order out). + expect(mergeChargeRows(auto, handFed)).toEqual([auto[1], auto[0]]); + }); + + test("a hand-fed row outside the window or for another charge is kept", () => { + const handFed: ChargeRow[] = [ + { + at: "2026-10-01", + label: "Meta PAYG spill", + amountUsd: 20, + method: "Visa •7535", + source: "Gmail card alert (registry billing incidents)", + }, + { at: "2026-10-11", label: "Cline Bot Inc.", amountUsd: 42, method: "card", source: "quota view" }, + ]; + const merged = mergeChargeRows(auto, handFed); + expect(merged).toHaveLength(4); + expect(merged[0]?.at).toBe("2026-10-01"); + }); + + test("no auto rows = the hand-fed list, sorted (pre-#1057 behaviour)", () => { + const handFed: ChargeRow[] = [ + { at: "2026-10-11", label: "B", amountUsd: 1, method: "card", source: "x" }, + { at: "2026-10-01", label: "A", amountUsd: 2, method: "card", source: "x" }, + ]; + expect(mergeChargeRows([], handFed).map((r) => r.label)).toEqual(["A", "B"]); + }); +}); + +describe("filterNewUnmatched / surfaced-once", () => { + const unmatched = [ + { merchant: "CURSOR.COM", normalized: "CURSOR", amountUsd: 20, at: "2026-10-12", source: "plaid" as const }, + { merchant: "LINEAR", normalized: "LINEAR", amountUsd: 10, at: "2026-10-15", source: "gmail" as const }, + ]; + + test("first run surfaces all; persisting the keys makes the rerun surface none", () => { + const first = filterNewUnmatched(unmatched, new Set()); + expect(first.fresh).toEqual(unmatched); + const second = filterNewUnmatched(unmatched, new Set(first.keys)); + expect(second.fresh).toEqual([]); + expect(second.keys).toEqual(first.keys); + }); + + test("a genuinely new unmatched charge still surfaces alongside known ones", () => { + const known = new Set([unmatchedKey(unmatched[0]!)]); + const { fresh } = filterNewUnmatched(unmatched, known); + expect(fresh).toEqual([unmatched[1]]); + }); +}); + +describe("period replay (packet acceptance)", () => { + const candidates: ChargeCandidate[] = [ + { source: "plaid", at: "2026-10-28", merchant: "METAPAY*UC5DPA22Y4 US", amountUsd: 20, method: "Visa •7535" }, + { source: "gmail", at: "2026-10-27", merchant: "MetaPay", amountUsd: 20 }, + { source: "gmail", at: "2026-10-09", merchant: "ChatGPT Subscription", amountUsd: 20 }, + { source: "plaid", at: "2026-10-12", merchant: "CURSOR.COM", amountUsd: 20 }, + { source: "plaid", at: "2026-10-13", merchant: "WALMART STORE 1234", amountUsd: 54.12 }, + ]; + const handFed: ChargeRow[] = [ + { + at: "2026-10-25", + label: "Meta PAYG spill", + amountUsd: 7.5, + method: "Visa •7535", + source: "Gmail card alert (registry billing incidents)", + }, + ]; + + test("one row per charge with source labels, no cross-source duplicates", () => { + const { rows, unmatchedSaas } = matchCharges(candidates, SERVICES); + const feed = mergeChargeRows(rows, handFed); + // 4 deduped auto charges + the distinct $7.50 hand-fed incident. + expect(feed).toHaveLength(5); + expect(feed.filter((r) => r.amountUsd === 20 && r.source === "Plaid")).toHaveLength(2); + expect(feed.find((r) => r.label === "OpenAI")?.source).toBe("Gmail alert"); + expect(unmatchedSaas.map((u) => u.normalized)).toEqual(["CURSOR", "METAPAY"]); + }); + + test("re-running the collector for the same period adds no rows and re-surfaces nothing", () => { + const run = (surfaced: ReadonlySet) => { + const { rows, unmatchedSaas } = matchCharges(candidates, SERVICES); + return { feed: mergeChargeRows(rows, handFed), ...filterNewUnmatched(unmatchedSaas, surfaced) }; + }; + const first = run(new Set()); + const second = run(new Set(first.keys)); + expect(second.feed).toEqual(first.feed); + expect(first.fresh).toHaveLength(2); + expect(second.fresh).toEqual([]); + }); +});