diff --git a/pm-stack/aggregator/scripts/append-usage-snapshots.ts b/pm-stack/aggregator/scripts/append-usage-snapshots.ts index 3de6d32c5c..5fffdcec93 100644 --- a/pm-stack/aggregator/scripts/append-usage-snapshots.ts +++ b/pm-stack/aggregator/scripts/append-usage-snapshots.ts @@ -45,8 +45,7 @@ const quotaViewPath = "workspace/goals/stewardship-commission-recurring-review-and-dispatch/hidden_files/visibility/quota-view.md", ); const registryPath = process.env.QUOTA_REGISTRY_PATH ?? join(HIDDEN, "provider-quota-registry.md"); -const providerUsagePath = - process.env.PROVIDER_USAGE_SNAPSHOT_PATH ?? join(HIDDEN, "provider-usage-snapshot.json"); +const providerUsagePath = process.env.PROVIDER_USAGE_SNAPSHOT_PATH ?? join(HIDDEN, "provider-usage-snapshot.json"); const outboxPath = process.env.USAGE_SNAPSHOT_OUTBOX_PATH ?? join(HIDDEN, "usage-snapshot-outbox.jsonl"); async function main(): Promise { diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index bcfe345158..32ee57f5db 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -52,6 +52,13 @@ // and check-usage append records there; each collection drains it into // the feed's snapshots field for the laptop store to ingest), // SUPABASE_PROJECT_REF (default: the muse-dev project), +// CHARGES_EXPORT_PATH (the #1057 charges producer export — +// ChargeCandidate[] JSON written by a Muse-side producer holding +// the Plaid/Gmail connectors; when present and parseable, the hub +// charges section comes from the auto-matcher in src/charges-match.ts +// instead of the prose extractor), CHARGES_SURFACED_STATE_PATH (the +// persisted keys of unmatched SaaS charges already surfaced in the +// feed, so each one surfaces exactly once), // AA_OPENCODE_CONFIG_PATH (default: the repo's .opencode/opencode.jsonc). import { execFile } from "node:child_process"; import { access, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; @@ -73,6 +80,13 @@ import type { import { extractQuotaPools } from "../src/quota-extract.ts"; import { computeChoices } from "../src/quota-guidance.ts"; import { extractCharges, extractPaygLines, extractSaasServices, extractSubscriptions } from "../src/saas-extract.ts"; +import { matchCharges, type UnmatchedCharge } from "../src/charges-match.ts"; +import { + parseChargeCandidatesExport, + parseSurfacedState, + planUnmatchedSurfacing, + serviceRefsFromSaas, +} from "../src/charges-collect.ts"; import type { ChargeRow, PaygLine, SaasService, SnapshotRecord } from "../src/model.ts"; import { recordsFromDns, recordsFromPaygLines, recordsFromSaasServices } from "../src/snapshot-records.ts"; import { isSnapshotRecord, snapshotKey } from "../src/snapshots.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 chargesExportPath = process.env.CHARGES_EXPORT_PATH ?? join(HOME, "atlas/charges-export/latest.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 = @@ -380,6 +396,8 @@ async function main(): Promise { let saas: SaasService[] | undefined; let payg: PaygLine[] | undefined; let charges: ChargeRow[] | undefined; + let chargesUnmatched: UnmatchedCharge[] | undefined; + let pendingSurfacedKeys: string[] | undefined; let subscriptions: FleetFeed["subscriptions"]; if (quotaViewText) { let registryText = ""; @@ -391,6 +409,23 @@ async function main(): Promise { saas = extractSaasServices(quotaViewText); payg = extractPaygLines(quotaViewText, registryText); charges = extractCharges(quotaViewText, registryText); + // --- charges auto-match (#1057): a producer export, when present + // and parseable, replaces the prose evidence with matched rows --- + try { + const candidates = parseChargeCandidatesExport(await readFile(chargesExportPath, "utf8")); + if (candidates && saas) { + const matched = matchCharges(candidates, serviceRefsFromSaas(saas)); + charges = matched.rows; + const stateText = await readFile(chargesSurfacedStatePath, "utf8").catch(() => ""); + const plan = planUnmatchedSurfacing(matched.unmatchedSaas, parseSurfacedState(stateText)); + chargesUnmatched = plan.fresh; + pendingSurfacedKeys = plan.nextKeys; + } else if (candidates === null) { + console.error("collector: charges export unparseable; keeping prose-extracted charges"); + } + } catch { + // No export yet: prose extraction stays in charge (fail-soft). + } subscriptions = extractSubscriptions(quotaViewText); } @@ -563,12 +598,28 @@ async function main(): Promise { ...(saas ? { saas } : {}), ...(payg ? { payg } : {}), ...(charges ? { charges } : {}), + ...(chargesUnmatched?.length ? { chargesUnmatched } : {}), ...(subscriptions ? { subscriptions } : {}), ...(dedupedSnapshots.length ? { snapshots: dedupedSnapshots } : {}), ...(projects ? { projects } : {}), aa, }; await writeFile(outPath, JSON.stringify(feed, null, 2)); + if (pendingSurfacedKeys) { + await writeFile(chargesSurfacedStatePath, JSON.stringify({ surfacedKeys: pendingSurfacedKeys }, null, 2)).catch( + (err) => + console.error( + "collector: could not persist charges surfaced state (" + err + "); unmatched charges may re-surface", + ), + ); + console.log( + "collector: charges auto-match - " + + (charges?.length ?? 0) + + " rows, " + + (chargesUnmatched?.length ?? 0) + + " newly surfaced unmatched SaaS", + ); + } const withReads = pools.filter((p) => p.windows.length > 0).length; console.log( `collector: wrote ${outPath} — ${pools.length} pools (${withReads} with reads), ${attention.length} sessions (sandbox + jules${jules ? `, ${jules.tracked} jules tracked` : ""})` + diff --git a/pm-stack/aggregator/scripts/gather-charges.ts b/pm-stack/aggregator/scripts/gather-charges.ts new file mode 100644 index 0000000000..0d91fbbad5 --- /dev/null +++ b/pm-stack/aggregator/scripts/gather-charges.ts @@ -0,0 +1,100 @@ +#!/usr/bin/env bun +// Charges producer (#1057): the Muse-side half of the charges +// auto-matcher. The aggregator's collector cannot reach the Plaid or +// Gmail connectors in-process, so an agent holding those connectors +// saves their raw reads to files and this script normalizes them into +// the charges export the collector ingests +// (~/atlas/charges-export/latest.json — the file-export convention, +// gather-quota.ts family 2). +// +// Inputs (both fail-soft; either may be absent): +// PLAID_TRANSACTIONS_PATH — a Plaid transactions-get response saved +// verbatim: { accounts?: [{account_id, name, mask}], transactions: +// [{date, name, merchant_name?, amount, pending?}] }. Plaid's +// amount sign: positive = money out. Pending rows are skipped. +// Balances are never read or written — charge evidence only. +// GMAIL_ALERTS_PATH — receipt/card alert extractions as an array of +// {at, merchant, amountUsd, method?} (the reading agent extracts +// these fields from the mail; this script does not parse mail). +// +// Output: { generatedAt, candidates: ChargeCandidate[] } written +// atomically to CHARGES_EXPORT_PATH (default +// ~/atlas/charges-export/latest.json). The collector's matcher +// dedupes across sources, so overlapping reads are safe; re-running +// for the same period republishes the same candidates. +// +// Usage: bun run scripts/gather-charges.ts +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import type { ChargeCandidate } from "../src/charges-match.ts"; +import { parseChargeCandidatesExport } from "../src/charges-collect.ts"; + +const HOME = homedir(); +const plaidPath = process.env.PLAID_TRANSACTIONS_PATH ?? join(HOME, "atlas/charges-export/plaid-transactions.json"); +const gmailPath = process.env.GMAIL_ALERTS_PATH ?? join(HOME, "atlas/charges-export/gmail-alerts.json"); +const outPath = process.env.CHARGES_EXPORT_PATH ?? join(HOME, "atlas/charges-export/latest.json"); + +interface PlaidAccount { + account_id?: string; + name?: string; + mask?: string; +} +interface PlaidTransaction { + date?: string; + name?: string; + merchant_name?: string; + amount?: number; + pending?: boolean; + account_id?: string; +} + +function plaidCandidates(doc: unknown): ChargeCandidate[] { + const d = doc as { accounts?: PlaidAccount[]; transactions?: PlaidTransaction[] }; + if (!Array.isArray(d?.transactions)) return []; + const accounts = new Map((d.accounts ?? []).map((a) => [a.account_id, a])); + const out: ChargeCandidate[] = []; + for (const tx of d.transactions) { + if (tx.pending) continue; + if (typeof tx.amount !== "number" || !(tx.amount > 0)) continue; + if (typeof tx.date !== "string") continue; + const merchant = (tx.merchant_name || tx.name || "").trim(); + if (!merchant) continue; + const account = tx.account_id ? accounts.get(tx.account_id) : undefined; + const method = + account?.name && account?.mask + ? account.name + " •" + account.mask + : account?.mask + ? "•" + account.mask + : undefined; + out.push({ source: "plaid", at: tx.date, merchant, amountUsd: tx.amount, ...(method ? { method } : {}) }); + } + return out; +} + +async function readJson(path: string): Promise { + try { + return JSON.parse(await readFile(path, "utf8")); + } catch { + return null; + } +} + +const candidates: ChargeCandidate[] = []; +const plaidDoc = await readJson(plaidPath); +if (plaidDoc) candidates.push(...plaidCandidates(plaidDoc)); +else console.error("gather-charges: no readable Plaid transactions at " + plaidPath); + +const gmailDoc = await readJson(gmailPath); +if (gmailDoc) { + const parsed = parseChargeCandidatesExport(JSON.stringify(gmailDoc)); + candidates.push(...(parsed ?? []).filter((c) => c.source === "gmail")); +} else { + console.error("gather-charges: no readable Gmail alerts at " + gmailPath); +} + +await mkdir(dirname(outPath), { recursive: true }); +const tmp = outPath + ".tmp"; +await writeFile(tmp, JSON.stringify({ generatedAt: new Date().toISOString(), candidates }, null, 2)); +await rename(tmp, outPath); +console.log("gather-charges: wrote " + candidates.length + " candidates to " + outPath); diff --git a/pm-stack/aggregator/src/charges-collect.ts b/pm-stack/aggregator/src/charges-collect.ts new file mode 100644 index 0000000000..bc3d41e6f6 --- /dev/null +++ b/pm-stack/aggregator/src/charges-collect.ts @@ -0,0 +1,109 @@ +// charges-collect (#1057): the collector-side half of the charges +// auto-matcher. The pure matching core lives in src/charges-match.ts; +// this module owns everything stateful or parsing-shaped around it: +// +// - the charges export contract: a Muse-side producer (an agent +// with the Plaid and Gmail connectors, which the collector process +// cannot reach in-process) writes ChargeCandidate[] JSON to +// ~/atlas/charges-export/latest.json — the file-export convention +// gather-quota.ts family 2 established (#1301). The collector +// ingests that file; an absent or malformed export changes +// nothing (the prose extractor stays in charge). +// - building the matcher's service refs from the hub's own SaaS +// service list, so a charge matches the services the hub tracks. +// - the persisted "already surfaced" state for unmatched SaaS +// charges: an unmatched charge joins the feed's chargesUnmatched +// section exactly once; the collector records its key in a state +// file and never surfaces the same charge again. Re-running the +// collector for the same period is a no-op for surfacing. +// +// No balances or debt data ever enter here: candidates are charge +// evidence only (date, merchant, amount, payment-method label). + +import type { ChargeCandidate, ChargeServiceRef, UnmatchedCharge } from "./charges-match.ts"; +import type { SaasService } from "./model.ts"; + +/** + * Parse a charges export document into candidates. Returns null when + * the document is not JSON at all (the caller keeps its fallback); + * a JSON document with malformed entries yields the valid subset — + * one bad row from a producer must not sink the whole period. + */ +export function parseChargeCandidatesExport(text: string): ChargeCandidate[] | null { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return null; + } + const list = Array.isArray(parsed) ? parsed : (parsed as { candidates?: unknown })?.candidates; + if (!Array.isArray(list)) return null; + const out: ChargeCandidate[] = []; + for (const entry of list) { + if (typeof entry !== "object" || entry === null) continue; + const e = entry as Record; + if (e.source !== "plaid" && e.source !== "gmail") continue; + if (typeof e.at !== "string" || !Number.isFinite(Date.parse(e.at))) continue; + if (typeof e.merchant !== "string" || !e.merchant.trim()) continue; + if (typeof e.amountUsd !== "number" || !Number.isFinite(e.amountUsd)) continue; + out.push({ + source: e.source, + at: e.at, + merchant: e.merchant, + amountUsd: e.amountUsd, + ...(typeof e.method === "string" && e.method.trim() ? { method: e.method } : {}), + }); + } + return out; +} + +/** The matcher's service refs: the hub's tracked SaaS services by name. */ +export function serviceRefsFromSaas(saas: SaasService[]): ChargeServiceRef[] { + return saas.map((s) => ({ name: s.name })); +} + +/** + * Identity of one unmatched charge for surfacing purposes: the same + * charge re-observed next period (a new posting date) is a new + * charge and may surface again; the same posting re-collected is not. + */ +export function unmatchedChargeKey(u: UnmatchedCharge): string { + return `${u.normalized}|${u.amountUsd.toFixed(2)}|${u.at}`; +} + +export interface SurfacingPlan { + /** Unmatched charges not present in the persisted state. */ + fresh: UnmatchedCharge[]; + /** The full key set to persist (prior keys plus the fresh ones). */ + nextKeys: string[]; +} + +/** + * Decide which unmatched charges surface this run. Pure: the + * collector loads the persisted keys, plans, publishes `fresh`, and + * writes `nextKeys` back — in that order, so a crash between publish + * and persist can re-surface (visible, harmless) but never lose a + * surfacing silently. + */ +export function planUnmatchedSurfacing(unmatched: UnmatchedCharge[], surfacedKeys: string[]): SurfacingPlan { + const seen = new Set(surfacedKeys); + const fresh: UnmatchedCharge[] = []; + for (const u of unmatched) { + const key = unmatchedChargeKey(u); + if (seen.has(key)) continue; + seen.add(key); + fresh.push(u); + } + return { fresh, nextKeys: [...seen] }; +} + +/** Parse the persisted surfaced-keys state file; anything odd = empty state. */ +export function parseSurfacedState(text: string): string[] { + try { + const parsed: unknown = JSON.parse(text); + const keys = (parsed as { surfacedKeys?: unknown })?.surfacedKeys; + return Array.isArray(keys) ? keys.filter((k): k is string => typeof k === "string") : []; + } catch { + return []; + } +} diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index 695dcf0408..9939f806e0 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -20,6 +20,7 @@ import type { SessionRecord, SnapshotRecord, } from "./model.ts"; +import type { UnmatchedCharge } from "./charges-match.ts"; export interface FleetFeed { version: 1; @@ -43,6 +44,10 @@ export interface FleetFeed { payg?: PaygLine[]; /** Hub charges evidence (§2.4), from the same dated records. */ charges?: ChargeRow[]; + /** Unmatched SaaS/AI-looking charges surfaced for classification + * (#1057): only charges the collector has never surfaced before + * (persisted state decides), so each appears exactly once. */ + chargesUnmatched?: 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/projects.ts b/pm-stack/aggregator/src/projects.ts index e509fffa30..4817f68e62 100644 --- a/pm-stack/aggregator/src/projects.ts +++ b/pm-stack/aggregator/src/projects.ts @@ -150,10 +150,7 @@ export function projectPageInfo(json: unknown): { hasNextPage: boolean; endCurso /** Fetch the whole pool (paginated). Throws on HTTP/GraphQL errors so * the collector can fail-soft and omit the section. Never logs the token. */ -export async function fetchProjectPool( - token: string, - fetchFn: typeof fetch = fetch, -): Promise { +export async function fetchProjectPool(token: string, fetchFn: typeof fetch = fetch): Promise { const out: ProjectPoolItem[] = []; let cursor: string | null = null; for (let page = 0; page < 10; page++) { diff --git a/pm-stack/aggregator/src/snapshot-records.ts b/pm-stack/aggregator/src/snapshot-records.ts index 293772c486..18e98b4b3e 100644 --- a/pm-stack/aggregator/src/snapshot-records.ts +++ b/pm-stack/aggregator/src/snapshot-records.ts @@ -17,14 +17,7 @@ // (service, metric, ts, value), so an unchanged read re-derives the // identical record and appends nothing. import { POOL_SPECS, sectionOf } from "./quota-extract.ts"; -import type { - DnsSection, - PaygLine, - QuotaPool, - SaasService, - SnapshotRecord, - UsageUnit, -} from "./model.ts"; +import type { DnsSection, PaygLine, QuotaPool, SaasService, SnapshotRecord, UsageUnit } from "./model.ts"; const DATE_RE = /\d{4}-\d{2}-\d{2}/g; diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 69595ad1a7..e4f1a41ad9 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -817,7 +817,16 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise ({ + kind: "unmatched-charge" as const, + label: `Unmatched SaaS charge - ${u.merchant}`, + detail: `${u.amountUsd.toFixed(2)} on ${u.at} via ${u.source === "plaid" ? "Plaid" : "Gmail alert"} - classify it or add the service to the hub registry.`, + href: "#quota", + severity: u.amountUsd, + })), + ], 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..40e82c8e4c --- /dev/null +++ b/pm-stack/aggregator/test/charges-collect.test.ts @@ -0,0 +1,83 @@ +// #1057: collector-level fixture replay for the charges auto-matcher — +// an export document in, feed rows + once-only surfacing out. Replaying +// the same period twice must add nothing and re-surface nothing (the +// packet's acceptance shape, exercised without live Plaid/Gmail data). +import { describe, expect, test } from "bun:test"; +import { matchCharges } from "../src/charges-match.ts"; +import { + parseChargeCandidatesExport, + parseSurfacedState, + planUnmatchedSurfacing, + serviceRefsFromSaas, +} from "../src/charges-collect.ts"; +import type { SaasService } from "../src/model.ts"; + +const SAAS = [ + { id: "anthropic", name: "Anthropic" }, + { id: "openai", name: "OpenAI" }, +] as SaasService[]; + +// One period as a producer would export it: the Anthropic charge seen +// by both sources, a Gmail-only Cursor charge (SaaS, unmatched), a +// Plaid-only grocery charge (not SaaS, not unmatched-worthy). +const EXPORT = JSON.stringify({ + candidates: [ + { source: "gmail", at: "2026-10-27", merchant: "Anthropic", amountUsd: 20 }, + { source: "plaid", at: "2026-10-28", merchant: "ANTHROPIC", amountUsd: 20, method: "Visa •7535" }, + { source: "gmail", at: "2026-10-26", merchant: "CURSOR.COM", amountUsd: 20 }, + { source: "plaid", at: "2026-10-25", merchant: "WALMART STORE 1234", amountUsd: 84.12 }, + { source: "plaid", at: "2026-10-25", merchant: "", amountUsd: 5 }, + { source: "other", at: "2026-10-25", merchant: "NOPE", amountUsd: 5 }, + ], +}); + +describe("parseChargeCandidatesExport", () => { + test("keeps valid entries, drops malformed ones", () => { + const candidates = parseChargeCandidatesExport(EXPORT); + expect(candidates).toHaveLength(4); + expect(candidates?.[0].source).toBe("gmail"); + }); + + test("non-JSON and wrong-shape documents return null", () => { + expect(parseChargeCandidatesExport("not json")).toBeNull(); + expect(parseChargeCandidatesExport('{"nope": true}')).toBeNull(); + }); + + test("a bare array is also an export", () => { + expect(parseChargeCandidatesExport("[]")).toEqual([]); + }); +}); + +describe("collector replay", () => { + test("one row per charge, source labelled, cross-source deduped", () => { + const candidates = parseChargeCandidatesExport(EXPORT)!; + const { rows, unmatchedSaas } = matchCharges(candidates, serviceRefsFromSaas(SAAS)); + expect(rows).toHaveLength(3); + const anthropic = rows.find((r) => r.label === "Anthropic"); + expect(anthropic?.source).toBe("Plaid"); + expect(anthropic?.method).toBe("Visa •7535"); + expect(unmatchedSaas.map((u) => u.normalized)).toEqual(["CURSOR"]); + }); + + test("unmatched surfacing happens exactly once across replays", () => { + const candidates = parseChargeCandidatesExport(EXPORT)!; + const { unmatchedSaas } = matchCharges(candidates, serviceRefsFromSaas(SAAS)); + + const first = planUnmatchedSurfacing(unmatchedSaas, parseSurfacedState("not json")); + expect(first.fresh).toHaveLength(1); + + const stateText = JSON.stringify({ surfacedKeys: first.nextKeys }); + const second = planUnmatchedSurfacing(unmatchedSaas, parseSurfacedState(stateText)); + expect(second.fresh).toEqual([]); + expect(second.nextKeys).toEqual(first.nextKeys); + }); + + test("a new posting of the same merchant next period surfaces again", () => { + const candidates = parseChargeCandidatesExport(EXPORT)!; + const { unmatchedSaas } = matchCharges(candidates, serviceRefsFromSaas(SAAS)); + const first = planUnmatchedSurfacing(unmatchedSaas, []); + const nextPeriod = [{ ...unmatchedSaas[0], at: "2026-11-26" }]; + const plan = planUnmatchedSurfacing(nextPeriod, first.nextKeys); + expect(plan.fresh).toHaveLength(1); + }); +}); diff --git a/pm-stack/aggregator/test/snapshot-writers.test.ts b/pm-stack/aggregator/test/snapshot-writers.test.ts index 18fb18a0af..31275d3450 100644 --- a/pm-stack/aggregator/test/snapshot-writers.test.ts +++ b/pm-stack/aggregator/test/snapshot-writers.test.ts @@ -87,7 +87,15 @@ describe("recordsFromSaasServices", () => { describe("recordsFromPaygLines", () => { test("backfill ids are reused so the series continues", () => { const lines: PaygLine[] = [ - { id: "meta-payg", label: "Meta", accruedUsd: 23.92, unbilledUsd: 0.01, note: "", measuredAt: "2026-10-25", sourceClass: "console" }, + { + id: "meta-payg", + label: "Meta", + accruedUsd: 23.92, + unbilledUsd: 0.01, + note: "", + measuredAt: "2026-10-25", + sourceClass: "console", + }, { id: "cloudflare-gateway", label: "GW", @@ -126,7 +134,9 @@ describe("recordsFromPools", () => { provider: "Anthropic", plan: "Claude Pro", state: "healthy", - windows: [{ name: "weekly", unit: "other", limit: 100, used: 42, percent: 42, resetsAt: "2026-10-28T14:00:00-05:00" }], + windows: [ + { name: "weekly", unit: "other", limit: 100, used: 42, percent: 42, resetsAt: "2026-10-28T14:00:00-05:00" }, + ], }; // The 2027 renewal date elsewhere in the section is an operational // date, not a read — the Last checked bullet wins. @@ -162,7 +172,11 @@ describe("recordsFromDns", () => { describe("recordsFromProviderUsage", () => { test("session count always; codex windows only when the endpoint answered", () => { - const walled = { generated_at: "2026-10-26T10:59:33Z", sessions: [1, 2, 3], codex_usage: { status: "http 403", usage: null } }; + const walled = { + generated_at: "2026-10-26T10:59:33Z", + sessions: [1, 2, 3], + codex_usage: { status: "http 403", usage: null }, + }; expect(recordsFromProviderUsage(walled, "check-usage")).toEqual([ { ts: "2026-10-26T10:59:33Z", @@ -205,13 +219,21 @@ describe("writer dedupe invariant", () => { const store = new SnapshotStore(dir); const batch = [ ...recordsFromSaasServices( - [svc({ metrics: [{ id: "databases", label: "Databases", unit: "count", used: 1, limit: 100, highlight: true }] })], + [ + svc({ + metrics: [{ id: "databases", label: "Databases", unit: "count", used: 1, limit: 100, highlight: true }], + }), + ], "fleet-feed-collector", ), // The same fact derived by another writer (different // observedBy) is the same record to the store. ...recordsFromSaasServices( - [svc({ metrics: [{ id: "databases", label: "Databases", unit: "count", used: 1, limit: 100, highlight: true }] })], + [ + svc({ + metrics: [{ id: "databases", label: "Databases", unit: "count", used: 1, limit: 100, highlight: true }], + }), + ], "stewardship-cycle", ), ]; diff --git a/pm-stack/aggregator/test/usage.test.ts b/pm-stack/aggregator/test/usage.test.ts index c4e0ed309c..802d33e609 100644 --- a/pm-stack/aggregator/test/usage.test.ts +++ b/pm-stack/aggregator/test/usage.test.ts @@ -149,7 +149,9 @@ describe("payg lines + charges (§1.2, §2.4)", () => { }); test("subscriptions strip is renewal-only rows from the records", () => { - const subs = extractSubscriptions(`${VIEW}\n### Other / flat (b)\n- **Amazon RxPass:** Subscription $5/mo; flat pharmacy.\n### Wispr Flow\n- **Plan:** Flow Pro annual $151.91/yr charged; renews 2027-10-09.`); + const subs = extractSubscriptions( + `${VIEW}\n### Other / flat (b)\n- **Amazon RxPass:** Subscription $5/mo; flat pharmacy.\n### Wispr Flow\n- **Plan:** Flow Pro annual $151.91/yr charged; renews 2027-10-09.`, + ); expect(subs).toEqual([ { name: "Amazon RxPass", plan: "$5/mo flat pharmacy", renewsAt: null }, { name: "Wispr Flow", plan: "Pro $151.91/yr", renewsAt: "2027-10-09" }, @@ -183,7 +185,15 @@ describe("bubble rules (§1.3)", () => { services: [], payg: [ { id: "a", label: "A", accruedUsd: null, unbilledUsd: 5, note: "", measuredAt: null, sourceClass: "estimate" }, - { id: "b", label: "B", accruedUsd: null, unbilledUsd: 5.01, note: "", measuredAt: null, sourceClass: "estimate" }, + { + id: "b", + label: "B", + accruedUsd: null, + unbilledUsd: 5.01, + note: "", + measuredAt: null, + sourceClass: "estimate", + }, ], }); expect(flags.filter((f) => f.kind === "payg-unbilled").map((f) => f.label)).toEqual(["B"]); @@ -222,7 +232,15 @@ describe("snapshot store (§4)", () => { try { const store = new SnapshotStore(dir); await store.append([ - { ts: "2026-10-25T12:00:00Z", serviceId: "cloudflare", metricId: "est", value: { low: 29.6, high: 45.1 }, unit: "usd-est", source: "estimate", observedBy: "test" }, + { + ts: "2026-10-25T12:00:00Z", + serviceId: "cloudflare", + metricId: "est", + value: { low: 29.6, high: 45.1 }, + unit: "usd-est", + source: "estimate", + observedBy: "test", + }, ]); const all = await store.readAll(); expect(all[0].value).toEqual({ low: 29.6, high: 45.1 }); @@ -259,9 +277,7 @@ describe("pace + freshness (§4, §1.1)", () => { }); test("no projection from a single point or a flat series", () => { expect(projectPace([rec("2026-10-24T00:00:00Z", 30)], "weekly")).toBeNull(); - expect( - projectPace([rec("2026-10-22T00:00:00Z", 30), rec("2026-10-24T00:00:00Z", 30)], "weekly"), - ).toBeNull(); + expect(projectPace([rec("2026-10-22T00:00:00Z", 30), rec("2026-10-24T00:00:00Z", 30)], "weekly")).toBeNull(); }); test("freshness: older than cadence is stale; same-day is not", () => { const now = new Date("2026-10-26T12:00:00Z");