diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index 996f99ab9..80e77fde2 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -81,6 +81,9 @@ export interface FleetFeed { /** Rows loadFeed's charges sanitization dropped (#2445), set only * when drops occurred; absent on raw parsed feeds and clean loads. */ chargesDropped?: number; + /** SaaS service rows loadFeed's sanitization dropped (#2451), set + * only when drops occurred; absent on raw parsed feeds and clean loads. */ + saasDropped?: number; /** PAYG lines loadFeed's sanitization dropped (#2450), set only * when drops occurred; absent on raw parsed feeds and clean loads. */ paygDropped?: number; @@ -582,6 +585,102 @@ export function isChargeRow(v: unknown): v is ChargeRow { ); } +const SAAS_GROUPS = ["database", "object-storage", "compute", "dev-platform", "domains", "account-tooling"]; +const USAGE_UNITS = [ + "pct", + "usd", + "cny", + "count", + "gb", + "tokens", + "minutes", + "hours", + "ms", + "rows", + "ops", + "neurons", + "other", +]; +const USAGE_SOURCE_CLASSES = ["api", "console", "manual", "estimate", "invoice"]; + +function isUsageMetric(v: unknown): boolean { + if (!isRecord(v)) return false; + return ( + typeof v.id === "string" && + typeof v.label === "string" && + (v.used === null || isFiniteNumber(v.used)) && + (v.limit === null || isFiniteNumber(v.limit)) && + typeof v.unit === "string" && + USAGE_UNITS.includes(v.unit) && + (v.percent === undefined || isFiniteNumber(v.percent)) && + (v.lowerBound === undefined || typeof v.lowerBound === "boolean") && + typeof v.highlight === "boolean" && + (v.note === undefined || typeof v.note === "string") + ); +} + +function isPaygEstimate(v: unknown): boolean { + if (!isRecord(v)) return false; + return ( + isFiniteNumber(v.low) && + isFiniteNumber(v.high) && + typeof v.period === "string" && + (v.note === undefined || typeof v.note === "string") + ); +} + +function isSaasService(v: unknown): v is SaasService { + if (!isRecord(v)) return false; + const sources = v.sources; + const sourcesValid = + sources === undefined || + (isRecord(sources) && + typeof sources.quotaViewSection === "string" && + (typeof sources.trackerRow === "string" || sources.trackerRow === null) && + typeof sources.baselineDoc === "string"); + return ( + typeof v.id === "string" && + typeof v.name === "string" && + typeof v.group === "string" && + SAAS_GROUPS.includes(v.group) && + typeof v.plan === "string" && + (v.status === "active" || v.status === "candidate" || v.status === "no-account" || v.status === "unknown") && + Array.isArray(v.metrics) && + v.metrics.every(isUsageMetric) && + (v.paygEstimate === null || isPaygEstimate(v.paygEstimate)) && + (v.paygNote === undefined || typeof v.paygNote === "string") && + (v.billedUsd === undefined || v.billedUsd === null || isFiniteNumber(v.billedUsd)) && + (typeof v.measuredAt === "string" || v.measuredAt === null) && + typeof v.sourceClass === "string" && + USAGE_SOURCE_CLASSES.includes(v.sourceClass) && + typeof v.sourceNote === "string" && + sourcesValid && + (v.nextDate === undefined || typeof v.nextDate === "string" || v.nextDate === null) && + isFiniteNumber(v.cadenceDays) && + isStringArray(v.conflicts) && + Array.isArray(v.reads) && + v.reads.every((read) => isRecord(read) && typeof read.at === "string" && typeof read.text === "string") && + (v.usageNote === undefined || typeof v.usageNote === "string") + ); +} + +export interface SaasSanitization { + /** Renderer-safe services, or undefined when the optional section is absent/non-array. */ + rows?: SaasService[]; + /** Invalid array elements, or one when a present section is not an array. */ + dropped: number; +} + +/** Drop malformed service rows at the feed boundary (#2451). One bad + * service must not take down usage(); non-arrays are treated as absent + * so they cannot silently choose the feed usage branch. */ +export function sanitizeSaasServices(v: unknown): SaasSanitization { + if (v === undefined) return { dropped: 0 }; + if (!Array.isArray(v)) return { dropped: 1 }; + const rows = v.filter(isSaasService); + return { rows, dropped: v.length - rows.length }; +} + /** The choices block renderQuota dereferences (hasHeadroom et al.). */ function isQuotaChoices(v: unknown): boolean { if (!isRecord(v)) return false; @@ -855,6 +954,7 @@ export async function loadFeed(path: string): Promise { // attached to the feed so they are visible, not swallowed. const san = sanitizeQuotaView(parsed.quota); const meta = sanitizeFeedMetadata(parsed.meta); + const saas = sanitizeSaasServices(parsed.saas); // Same drop-and-count treatment for chargesAttention elements // (#2439): the gate has already pinned the section to array-or- // absent, so arrayOf cannot return null here; malformed entries @@ -891,6 +991,8 @@ export async function loadFeed(path: string): Promise { ...feed, meta, quota: san.view, + saas: saas.rows, + saasDropped: saas.dropped || undefined, quotaDropped: { pools: san.droppedPools, credentials: san.droppedCredentials, diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 568ee4b88..29e9431df 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -1098,6 +1098,10 @@ export function liveSource( const chargesDroppedNote = feed?.chargesDropped ? ` · sanitized at load: dropped ${feed.chargesDropped} malformed charge row(s) (#2445)` : ""; + const saasDroppedNote = feed?.saasDropped + ? ` · sanitized at load: dropped ${feed.saasDropped} malformed SaaS service row(s) (#2451)` + : ""; + const feedSanitizationNotes = saasDroppedNote + chargesDroppedNote; const feedChargeFlags: AttentionFlag[] = (feed?.chargesAttention ?? []).map((u) => ({ kind: "unmatched-charge", label: `${u.merchant} — unrecognized SaaS/AI charge`, @@ -1107,7 +1111,7 @@ export function liveSource( })); if (feed?.saas && feed.saas.length) { provenance.usage = - `live (fleet feed · ${feedAgeText(feed.generatedAt)} · collected ${feed.generatedAt})` + chargesDroppedNote; + `live (fleet feed · ${feedAgeText(feed.generatedAt)} · collected ${feed.generatedAt})` + feedSanitizationNotes; // The Cloudflare live export overlays tracker prose on BOTH // service sources — a healthy fleet feed must not keep stale // prose values when a fresh export exists (Codex, PR #2228). @@ -1155,7 +1159,7 @@ export function liveSource( partial.services = await tursoOverlay(cfg, partial.services); provenance.usage = "live (quota-view.md + provider registry, direct read — feed carries no hub sections yet)" + - chargesDroppedNote; + feedSanitizationNotes; return { ...partial, chargesNote: partial.charges.length @@ -1166,7 +1170,7 @@ export function liveSource( history, }; } catch { - provenance.usage = "fixtures (no fleet feed hub sections and quota view unreadable)" + chargesDroppedNote; + provenance.usage = "fixtures (no fleet feed hub sections and quota view unreadable)" + feedSanitizationNotes; const fallback = await fix.usage(); // #3124: even the fixtures fallback keeps the feed's charge // evidence when a feed exists — fixtures stand in for the diff --git a/pm-stack/aggregator/test/saas-feed-gate.test.ts b/pm-stack/aggregator/test/saas-feed-gate.test.ts new file mode 100644 index 000000000..ecc3fdfb8 --- /dev/null +++ b/pm-stack/aggregator/test/saas-feed-gate.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { loadConfig } from "../src/config.ts"; +import { loadFeed, sanitizeSaasServices } from "../src/feed.ts"; +import type { SaasService } from "../src/model.ts"; +import { renderQuota } from "../src/render.ts"; +import { liveSource } from "../src/sources/live.ts"; +import { extractSaasServices } from "../src/saas-extract.ts"; + +const VALID: SaasService = { + id: "turso", + name: "Turso", + group: "database", + plan: "Starter", + status: "active", + metrics: [{ id: "rows", label: "Rows", used: 9, limit: 10, unit: "count", percent: 90, highlight: true }], + paygEstimate: null, + measuredAt: "2026-10-30", + sourceClass: "manual", + sourceNote: "test record", + nextDate: null, + cadenceDays: 30, + conflicts: [], + reads: [{ at: "2026-10-30", text: "9 rows used" }], +}; + +const VIEW = ` +## Summary (b) — subscriptions, infrastructure, account tooling + +| Service | Plan / price | Allowance sketch | Usage / status | Next date recorded | +|---|---|---|---|---| +| Supabase | Free plan (muse-dev) | DB + egress + storage | manual dashboard read needed | unknown | +`; + +function feed(saas?: unknown) { + return { + version: 1, + generatedAt: new Date().toISOString(), + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], + ...(saas === undefined ? {} : { saas }), + }; +} + +async function load(saas?: unknown) { + const dir = await mkdtemp(join(tmpdir(), "pm-saas-feed-")); + const path = join(dir, "fleet-feed.json"); + await writeFile(path, JSON.stringify(feed(saas))); + return loadFeed(path); +} + +async function sourceWith(saas: unknown, quotaView = VIEW) { + const dir = await mkdtemp(join(tmpdir(), "pm-saas-live-")); + const feedFile = join(dir, "fleet-feed.json"); + await writeFile(feedFile, JSON.stringify(feed(saas))); + const quotaViewFile = join(dir, "quota-view.md"); + await writeFile(quotaViewFile, quotaView); + const cfg = loadConfig({ + PM_AGG_SOURCE: "live", + PM_AGG_FEED_FILE: feedFile, + PM_AGG_QUOTA_VIEW: quotaViewFile, + PM_AGG_SUPABASE_EXPORT: join(dir, "no-supabase-export.json"), + PM_AGG_CLOUDFLARE_EXPORT: join(dir, "no-cloudflare-export.json"), + PM_AGG_REGISTRY_FILE: join(dir, "registry.json"), + PM_AGG_COMMENTS_FILE: join(dir, "comments.json"), + PM_AGG_SNAPSHOTS_DIR: join(dir, "snapshots"), + PM_AGG_OPENCHAMBER_STATE: join(dir, "no-state.json"), + PM_PROJECTOR_URL: "off", + KANEO_ADMIN_EMAIL: "", + KANEO_ADMIN_PASSWORD: "", + GRIST_API_KEY: "", + }); + return liveSource(cfg); +} + +describe("fleet feed SaaS sanitization (#2451)", () => { + test("drops null rows and preserves valid services in a mixed array", async () => { + const loaded = await load([VALID, null]); + expect(loaded?.saas).toEqual([VALID]); + expect(loaded?.saasDropped).toBe(1); + }); + + test("a null-only array drops all services but keeps the feed", async () => { + const loaded = await load([null]); + expect(loaded).not.toBeNull(); + expect(loaded?.saas).toEqual([]); + expect(loaded?.saasDropped).toBe(1); + }); + + test("non-array strings and objects are treated as absent and counted", async () => { + for (const invalid of ["oops", { id: "turso" }]) { + const loaded = await load(invalid); + expect(loaded).not.toBeNull(); + expect(loaded?.saas).toBeUndefined(); + expect(loaded?.saasDropped).toBe(1); + expect(sanitizeSaasServices(invalid)).toEqual({ dropped: 1 }); + } + }); + + test("service rows missing metrics or conflicts drop individually", async () => { + const { metrics: _metrics, ...withoutMetrics } = VALID; + const { conflicts: _conflicts, ...withoutConflicts } = VALID; + const loaded = await load([withoutMetrics, VALID, withoutConflicts]); + expect(loaded?.saas).toEqual([VALID]); + expect(loaded?.saasDropped).toBe(2); + }); + + test("valid remainder renders and contributes attention flags", async () => { + const src = await sourceWith([VALID, null]); + const usage = await src.usage(); + expect(usage.services).toEqual([VALID]); + expect(usage.attention).toContainEqual( + expect.objectContaining({ kind: "over-limit", label: "Turso — Rows" }), + ); + const html = renderQuota(await src.quota(), src.provenance(), usage); + expect(html).toContain("Turso"); + expect(src.provenance().usage).toContain("dropped 1 malformed SaaS service row(s)"); + }); + + test("all-dropped and non-array sections expose loss on the fallback path", async () => { + for (const malformed of [[null], { invalid: true }]) { + const src = await sourceWith(malformed); + const usage = await src.usage(); + expect(usage.services.length).toBeGreaterThan(0); + expect(src.provenance().usage).toContain("dropped 1 malformed SaaS service row(s)"); + expect(src.provenance().usage).toContain("direct read"); + } + }); + + test("clean and collector-shaped services are unchanged with no diagnostic", async () => { + const collectorServices = extractSaasServices(VIEW); + expect(collectorServices.length).toBeGreaterThan(0); + expect(sanitizeSaasServices(collectorServices)).toEqual({ rows: collectorServices, dropped: 0 }); + const collectorFeed = await load(collectorServices); + expect(collectorFeed?.saas).toEqual(collectorServices); + expect(collectorFeed?.saasDropped).toBeUndefined(); + + const loaded = await load([VALID]); + expect(loaded?.saas).toEqual([VALID]); + expect(loaded?.saasDropped).toBeUndefined(); + const src = await sourceWith([VALID]); + await src.usage(); + expect(src.provenance().usage).not.toContain("sanitized at load"); + }); +});