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
33 changes: 33 additions & 0 deletions pm-stack/aggregator/src/feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ export interface FleetFeed {
* only when at least one row (or a non-array section) was dropped;
* absent on raw parsed feeds and on clean loads. */
subscriptionsDropped?: number;
/** Rows loadFeed's charges sanitization dropped (#2445), set only
* when drops occurred; absent on raw parsed feeds and clean loads. */
chargesDropped?: number;
/** Sandbox-server + Jules sessions, pre-classification (render classifies). */
attention: SessionFeedEntry[];
/** Jules keeper totals (slice 2); absent when the keeper state is unreadable. */
Expand Down Expand Up @@ -347,6 +350,20 @@ export function isBurnSegment(v: unknown): v is BurnSegment {
export function isUnmatchedCharge(v: unknown): v is UnmatchedCharge {
if (!isRecord(v)) return false;
return typeof v.merchant === "string" && isFiniteNumber(v.amountUsd) && typeof v.at === "string";

/** One charges-evidence row as the /quota charges strip renders it
* (#2445): a record with string at/label/method/source and a
* finite-number amountUsd (ChargeRow, model.ts). Built on the shared
* validate.ts primitives, like the quota element validators above. */
export function isChargeRow(v: unknown): v is ChargeRow {
if (!isRecord(v)) return false;
return (
typeof v.at === "string" &&
typeof v.label === "string" &&
isFiniteNumber(v.amountUsd) &&
typeof v.method === "string" &&
typeof v.source === "string"
);
}

/** The choices block renderQuota dereferences (hasHeadroom et al.). */
Expand Down Expand Up @@ -488,6 +505,21 @@ export async function loadFeed(path: string): Promise<FleetFeed | null> {
// drop individually and well-formed siblings still surface.
const charges = parsed.chargesAttention === undefined ? undefined : arrayOf(isUnmatchedCharge)(parsed.chargesAttention);
const subs = sanitizeSubscriptions(parsed.subscriptions);
// Charges rows get the same drop-and-count treatment at this same
// shared gate (#2445): the section is optional, so absence stays
// absent; a non-array section drops whole (counted as one dropped
// section) instead of silently emptying the charges strip or
// crashing a consumer; malformed rows drop individually. The
// count rides out on the feed when drops occur, never swallowed.
let chargesPart: { charges?: ChargeRow[]; chargesDropped?: number } = {};
if (parsed.charges !== undefined) {
const rows = arrayOf(isChargeRow)(parsed.charges);
if (rows === null) {
chargesPart = { charges: [], chargesDropped: 1 };
} else {
chargesPart = { charges: rows.values, ...(rows.dropped > 0 ? { chargesDropped: rows.dropped } : {}) };
Comment thread
dezren39 marked this conversation as resolved.
Resolved
}
}
return {
...parsed,
quota: san.view,
Expand All @@ -496,6 +528,7 @@ export async function loadFeed(path: string): Promise<FleetFeed | null> {
...(charges && charges.dropped > 0 ? { chargesAttentionDropped: charges.dropped } : {}),
subscriptions: subs.rows,
...(subs.dropped > 0 ? { subscriptionsDropped: subs.dropped } : {}),
...chargesPart,
};
} catch {
return null;
Expand Down
12 changes: 9 additions & 3 deletions pm-stack/aggregator/src/sources/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,12 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise<bo
// first-time unmatched SaaS/AI charges (the collector's
// surfaced-state guarantees exactly-once), so each becomes
// an attention flag here and never repeats on later feeds.
// Charges sanitization loss (#2445): rows loadFeed dropped are
// counted on the feed; surface that count in the usage
// provenance on every return path below, never swallow it.
const chargesDroppedNote = feed?.chargesDropped
? ` · sanitized at load: dropped ${feed.chargesDropped} malformed charge row(s) (#2445)`
: "";
const feedChargeFlags: AttentionFlag[] = (feed?.chargesAttention ?? []).map((u) => ({
kind: "unmatched-charge",
label: `${u.merchant} — unrecognized SaaS/AI charge`,
Expand All @@ -898,7 +904,7 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise<bo
severity: u.amountUsd,
}));
if (feed?.saas && feed.saas.length) {
provenance.usage = `live (fleet feed · ${feedAgeText(feed.generatedAt)} · collected ${feed.generatedAt})`;
provenance.usage = `live (fleet feed · ${feedAgeText(feed.generatedAt)} · collected ${feed.generatedAt})` + chargesDroppedNote;
// 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).
Expand Down Expand Up @@ -944,7 +950,7 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise<bo
subscriptions: extractSubscriptions(doc),
};
partial.services = await tursoOverlay(cfg, partial.services);
provenance.usage = "live (quota-view.md + provider registry, direct read — feed carries no hub sections yet)";
provenance.usage = "live (quota-view.md + provider registry, direct read — feed carries no hub sections yet)" + chargesDroppedNote;
return {
...partial,
chargesNote: partial.charges.length
Expand All @@ -955,7 +961,7 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise<bo
history,
};
} catch {
provenance.usage = "fixtures (no fleet feed hub sections and quota view unreadable)";
provenance.usage = "fixtures (no fleet feed hub sections and quota view unreadable)" + chargesDroppedNote;
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
Expand Down
72 changes: 71 additions & 1 deletion pm-stack/aggregator/test/feed.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test";
import { isFleetFeed, isProjectPoolSection, isUnmatchedCharge, loadFeed, poolFromFeed, projectPoolSectionProblem, sanitizeQuotaView, sanitizeSubscriptions } from "../src/feed.ts";
import { isChargeRow, isFleetFeed, isProjectPoolSection, isUnmatchedCharge, loadFeed, poolFromFeed, projectPoolSectionProblem, sanitizeQuotaView, sanitizeSubscriptions } from "../src/feed.ts";
import { renderQuota } from "../src/render.ts";
import { renderQuota } from "../src/render.ts";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
Expand Down Expand Up @@ -307,6 +308,75 @@ describe("feed subscriptions sanitization (#2446)", () => {
expect(clean?.subscriptionsDropped).toBeUndefined();
});
});
describe("isChargeRow + loadFeed charges sanitization (#2445)", () => {
const CHOICES = { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] };
const ROW = { at: "2026-10-30", label: "Mystery AI Inc", amountUsd: 42.5, method: "Visa \u20227535", source: "plaid" };
const feedWithCharges = (charges: unknown) => ({
version: 1,
generatedAt: "2026-10-01T00:00:00Z",
quota: { pools: [], burn: [], choices: CHOICES },
attention: [],
...(charges === undefined ? {} : { charges }),
});
const load = async (feed: unknown) => {
const dir = mkdtempSync(join(tmpdir(), "agg-feed-charges-"));
const file = join(dir, "feed.json");
writeFileSync(file, JSON.stringify(feed));
return loadFeed(file);
};

test("isChargeRow accepts a well-formed row and rejects malformed ones", () => {
expect(isChargeRow(ROW)).toBe(true);
expect(isChargeRow(null)).toBe(false);
expect(isChargeRow({ ...ROW, amountUsd: undefined })).toBe(false);
expect(isChargeRow({ ...ROW, amountUsd: "42.50" })).toBe(false);
expect(isChargeRow({ at: ROW.at, label: ROW.label, amountUsd: 1, source: "plaid" })).toBe(false);
});

test("charges [null] drops the row, keeps the feed, surfaces the count", async () => {
const loaded = await load(feedWithCharges([null]));
expect(loaded).not.toBeNull();
expect(loaded?.charges).toEqual([]);
expect(loaded?.chargesDropped).toBe(1);
});

test("[valid, null] keeps the valid row", async () => {
const loaded = await load(feedWithCharges([ROW, null]));
expect(loaded?.charges).toEqual([ROW]);
expect(loaded?.chargesDropped).toBe(1);
});

test("entries missing amountUsd or with a string amountUsd drop individually", async () => {
const noAmount = { at: ROW.at, label: ROW.label, method: ROW.method, source: ROW.source };
const loaded = await load(feedWithCharges([noAmount, { ...ROW, amountUsd: "42.50" }, ROW]));
expect(loaded?.charges).toEqual([ROW]);
expect(loaded?.chargesDropped).toBe(2);
});

test("a non-array charges section yields [] with the drop surfaced", async () => {
for (const bad of ["oops", { at: ROW.at }]) {
const loaded = await load(feedWithCharges(bad));
expect(loaded).not.toBeNull();
expect(loaded?.charges).toEqual([]);
expect(loaded?.chargesDropped).toBe(1);
}
});

test("an absent charges section stays absent", async () => {
const loaded = await load(feedWithCharges(undefined));
expect(loaded).not.toBeNull();
expect(loaded?.charges).toBeUndefined();
expect(loaded?.chargesDropped).toBeUndefined();
});

test("a well-formed feed is unchanged through the gate + loadFeed (collector self-acceptance)", async () => {
const feed = feedWithCharges([ROW]);
expect(isFleetFeed(feed)).toBe(true);
const loaded = await load(feed);
expect(loaded?.charges).toEqual([ROW]);
expect(loaded?.chargesDropped).toBeUndefined();
});
});

describe("feed chargesAttention gate + sanitization (#2439)", () => {
const UNMATCHED = { merchant: "Mystery AI Inc", normalized: "mystery ai", amountUsd: 42.5, at: "2026-10-30", source: "plaid" };
Expand Down