Skip to content
8 changes: 5 additions & 3 deletions pm-stack/aggregator/src/feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -934,9 +934,11 @@ export interface RegistrySanitization {
* dropped individually. */
export function sanitizeRegistry(v: unknown): RegistrySanitization {
if (v === undefined) return { dropped: 0 };
if (!Array.isArray(v)) return { rows: [], dropped: 1 };
const rows = v.filter(isSessionRecord);
return { rows, dropped: v.length - rows.length };
// Shared container primitive (#2576 Phase 1): a non-array section is one
// shape failure; malformed array entries drop individually and count.
const parsed = arrayOf(isSessionRecord)(v);
if (parsed === null) return { rows: [], dropped: 1 };
return { rows: parsed.values, dropped: parsed.dropped };
}

/** A PAYG line safe for both the attention derivation and the quota renderer. */
Expand Down
46 changes: 44 additions & 2 deletions pm-stack/aggregator/src/quota-extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
// never collapse them into one pool.
import { poolState } from "./derive.ts";
import type { QuotaPool, QuotaWindow } from "./model.ts";
import { parseIsoDate } from "./validate.ts";

const MONTHS: Record<string, number> = {
Jan: 0,
Expand Down Expand Up @@ -164,6 +165,10 @@ function dateTimeCentral(date: string, hhmm: string): string {
* flow through the shared conversion unchanged.
*/
function resetDateTimeCentral(date: string, hhmm: string): string | null {
// Gate the calendar date and clock time with the shared primitive FIRST:
// dateTimeCentral supplies the Central-time offset conversion, but the
// ingest contract's real-date check belongs to validate.ts (#2470).
if (parseIsoDate(`${date}T${hhmm}`) === null) return null;
try {
return dateTimeCentral(date, hhmm);
} catch {
Expand Down Expand Up @@ -322,15 +327,52 @@ function goWorkspace(name: "drewrypope" | "popesdrew"): Extractor {
};
}

/** ClinePass has 5-hour, weekly, and monthly windows; an offset beyond a
* year is not a plausible reset for any of them (#2383). */
const MAX_CLINEPASS_RESET_OFFSET_DAYS = 366;

const extractClinePass: Extractor = (s) => {
const measured = first(s, /Measured (\d{4}-\d{2}-\d{2}) ~(\d{2}:\d{2}) CDT/i);
const m = first(
s,
/5-hour \*\*(\d+(?:\.\d+)?)%\*\* used; weekly \*\*(\d+(?:\.\d+)?)%\*\* used \(resets in (\d+)d (\d+)h\); monthly \*\*(\d+(?:\.\d+)?)%\*\* used \(resets in (\d+)d (\d+)h\)/i,
);
if (!measured || !m) return null;
const base = Date.parse(dateTimeCentral(measured[1], measured[2]));
const rel = (d: string, h: string) => new Date(base + (Number(d) * 24 + Number(h)) * 3_600_000).toISOString();
// The measured capture is the anchor for both relative resets (#2383).
// The measured capture anchors reset dates, not the percentages. If it
// is an impossible calendar/wall time, retain the matched windows and
// mark only their resets unknown (#2383). The shared primitive owns
// date validity; dateTimeCentral owns the Central-time offset conversion.
let base: number | null = null;
if (parseIsoDate(`${measured[1]}T${measured[2]}`) !== null) {
try {
const anchor = dateTimeCentral(measured[1], measured[2]);
base = parseIsoDate(anchor)?.getTime() ?? null;
} catch {
// Nonexistent Central wall time: keep the read, with no reset anchor.
}
}
const rel = (d: string, h: string): string | null => {
const days = Number(d);
const hours = Number(h);
if (
base === null ||
!Number.isInteger(days) ||
!Number.isInteger(hours) ||
days < 0 ||
hours < 0 ||
hours > 23 ||
days > MAX_CLINEPASS_RESET_OFFSET_DAYS
) {
return null;
}
const resetMs = base + (days * 24 + hours) * 3_600_000;
if (!Number.isFinite(resetMs)) return null;
const reset = new Date(resetMs);
if (!Number.isFinite(reset.getTime())) return null;
const iso = reset.toISOString();
return parseIsoDate(iso) === null ? null : iso;
};
return {
windows: [
pctWindow("5-hour", Number(m[1]), null),
Expand Down
108 changes: 71 additions & 37 deletions pm-stack/aggregator/src/quota-gather-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,15 @@
// its raw usage on the entry and yields no windows (never zeros).
import type { QuotaCurrentEntry, QuotaCurrentWindow, SnapshotRecord } from "./model.ts";
import { safeProviderReason } from "./credential-lifecycle.ts";
import { isIsoDate } from "./validate.ts";
import {
isFiniteNumber,
isIsoDate,
isNonEmptyString,
isNonNegative,
isPercentOf,
isRecord,
parseIsoDate,
} from "./validate.ts";

/** The subset of a quota-module result the mapper reads. */
export interface QuotaProviderResult {
Expand All @@ -39,18 +47,20 @@ interface RawWindow {
valueLabel?: unknown;
}

const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
const num = (v: unknown): number | null => (isFiniteNumber(v) ? v : null);

/** Provider reset stamps arrive as epoch ms (or s); normalize to ISO. */
export function normalizeResetAt(v: unknown): string | null {
if (typeof v === "number" && Number.isFinite(v) && v > 0) {
if (isFiniteNumber(v) && v > 0) {
const ms = v < 1e12 ? v * 1000 : v;
const d = new Date(ms);
return Number.isNaN(d.getTime()) ? null : d.toISOString();
return Number.isFinite(d.getTime()) ? d.toISOString() : null;
}
if (typeof v === "string" && v !== "") {
const t = Date.parse(v);
return Number.isNaN(t) ? null : new Date(t).toISOString();
// Shared epoch/calendar primitive: an impossible date (2026-02-30)
// is not silently rolled into the next month (#2383/#2470).
const d = parseIsoDate(v);
return d === null ? null : d.toISOString();
}
return null;
}
Expand Down Expand Up @@ -268,35 +278,54 @@ export function entryFromFileExport(
entry.error = "file-export stale (latest.json older than the staleness bound — producer unreachable)";
return entry;
}
const measuredMs = doc.measuredAt ? Date.parse(doc.measuredAt) : Number.NaN;
if (doc.status !== "ok" || Number.isNaN(measuredMs)) {
const measured = parseIsoDate(doc.measuredAt);
if (doc.status !== "ok" || measured === null) {
entry.error = `file-export status: ${doc.status ?? "unknown"}`;
return entry;
}
const measuredAt = new Date(measuredMs).toISOString();
entry.state = "ok";
entry.measuredAt = measuredAt;
for (const w of doc.windows ?? []) {
const pct = num(w.usedPct);
if (!w.name || pct == null || pct < 0 || pct > 100) continue;
entry.windows.push({
name: w.name,
// Fail-closed shape check (#2551): a window container or element that
// is not what the document promises is an unparseable document, so the
// caller retains the previous read. A null element used to throw out of
// the mapper; a non-string name was accepted into the entry.
if (!Array.isArray(doc.windows)) {
entry.error = "file-export unparseable: windows missing or not an array";
return entry;
}
for (const w of doc.windows) {
if (!isRecord(w) || !isNonEmptyString(w.name)) {
entry.error = "file-export unparseable: malformed window element";
return entry;
}
}
const measuredAt = measured.toISOString();
const mapped: QuotaCurrentEntry["windows"] = [];
for (const w of doc.windows) {
const name = w.name as string;
const pct = isFiniteNumber(w.usedPct) ? w.usedPct : null;
// A percent outside [0, its limit] is not data (#2571): drop the
// window rather than publish it as a live reading.
if (pct === null || !isPercentOf(100)(pct)) continue;
mapped.push({
name,
value: pct,
pctOfLimit: pct,
valueLabel: null,
// Own-key rule (#2781, design #2792): a window name that is not an
// own key — including prototype spellings (constructor/__proto__/
// toString) — is an unknown window and gets null, never a prototype
// member as its windowSeconds.
windowSeconds: Object.hasOwn(FILE_EXPORT_WINDOW_SECONDS, w.name) ? FILE_EXPORT_WINDOW_SECONDS[w.name] : null,
windowSeconds: Object.hasOwn(FILE_EXPORT_WINDOW_SECONDS, name) ? FILE_EXPORT_WINDOW_SECONDS[name] : null,
resetsAt: normalizeResetAt(w.resetAt),
measuredAt,
source: entry.source,
state: "ok",
});
}
entry.state = "ok";
entry.measuredAt = measuredAt;
entry.windows = mapped;
const labelWindow = (name: string, usd: number | null | undefined): void => {
if (typeof usd !== "number" || !Number.isFinite(usd) || usd < 0) return;
if (!isNonNegative(usd)) return;
entry.windows.push({
name,
value: null,
Expand Down Expand Up @@ -347,8 +376,10 @@ export function entryFromResult(result: QuotaProviderResult, tickIso: string): Q
if (result.usage != null) entry.usage = result.usage;

const pushWindow = (name: string, raw: RawWindow | null | undefined): void => {
const pct = num(raw?.usedPercent);
if (pct != null && (pct < 0 || pct > 100)) return;
const pct = isFiniteNumber(raw?.usedPercent) ? raw.usedPercent : null;
// Percent is bounded by the window's own 100-point limit (#2571);
// out-of-range values are dropped, not republished as live data.
if (pct !== null && !isPercentOf(100)(pct)) return;
entry.windows.push({
name,
value: pct,
Expand All @@ -361,8 +392,8 @@ export function entryFromResult(result: QuotaProviderResult, tickIso: string): Q
state: result.ok ? "ok" : "error",
});
};
const usageObj = result.usage as { windows?: unknown; models?: unknown } | null | undefined;
if (typeof usageObj?.windows === "object" && usageObj.windows !== null) {
const usageObj = result.usage;
if (isRecord(usageObj) && isRecord(usageObj.windows)) {
for (const [name, raw] of Object.entries(usageObj.windows as Record<string, RawWindow>)) {
pushWindow(name, raw);
}
Expand All @@ -371,9 +402,9 @@ export function entryFromResult(result: QuotaProviderResult, tickIso: string): Q
// whole shape): flatten to "<model>:<window>" so the data lands in
// the same contract. Pool attribution across models is the hub's
// modeling step, not the gatherer's.
if (typeof usageObj?.models === "object" && usageObj.models !== null) {
for (const [model, mu] of Object.entries(usageObj.models as Record<string, { windows?: unknown }>)) {
if (typeof mu?.windows !== "object" || mu.windows === null) continue;
if (isRecord(usageObj) && isRecord(usageObj.models)) {
for (const [model, mu] of Object.entries(usageObj.models as Record<string, unknown>)) {
if (!isRecord(mu) || !isRecord(mu.windows)) continue;
for (const [name, raw] of Object.entries(mu.windows as Record<string, RawWindow>)) {
pushWindow(`${model}:${name}`, raw);
}
Expand Down Expand Up @@ -582,10 +613,7 @@ const pct3 = (used: number, limit: number): number => Math.round((used / limit)
* treated exactly like a metric the response does not carry (#2553) — the
* window is omitted, never published negative. Local to entryFromTurso:
* the shared num() keeps its semantics for the other mappers. */
const numNonNegative = (v: unknown): number | null => {
const n = num(v);
return n !== null && n < 0 ? null : n;
};
const numNonNegative = (v: unknown): number | null => (isNonNegative(v) ? v : null);

/**
* Map one Turso usage + subscription read onto a quota-current
Expand Down Expand Up @@ -621,29 +649,35 @@ export function entryFromTurso(
return entry;
}
const usage = usageDoc?.organization?.usage ?? usageDoc?.usage;
if (!usage || typeof usage !== "object") {
if (!isRecord(usage)) {
entry.error = "turso usage response missing organization.usage";
return entry;
}
const periodEnd = sub?.current_billing_period_end ?? sub?.current_period_end ?? sub?.period_end ?? sub?.ends_at;
const periodStart =
sub?.current_billing_period_start ?? sub?.current_period_start ?? sub?.period_start ?? sub?.starts_at;
const resetsAt = normalizeResetAt(periodEnd);
// Gate both stamps with isIsoDate before Date.parse (#5091): Date.parse
// rolls impossible dates (2026-02-30 -> Mar 2) and parses non-ISO strings
// timezone-dependently, so a malformed period would silently publish a
// window length days off. A present-but-invalid stamp yields null.
const startMs = isIsoDate(periodStart) ? Date.parse(periodStart) : Number.NaN;
const endMs = isIsoDate(periodEnd) ? Date.parse(periodEnd) : Number.NaN;
// Gate both stamps with parseIsoDate (#5091): Date.parse rolls impossible
// dates (2026-02-30 -> Mar 2) and parses non-ISO strings timezone-
// dependently, so a malformed period would silently publish a window
// length days off. A present-but-invalid stamp yields null.
const startMs = parseIsoDate(periodStart)?.getTime() ?? Number.NaN;
const endMs = parseIsoDate(periodEnd)?.getTime() ?? Number.NaN;
const windowSeconds =
Number.isFinite(startMs) && Number.isFinite(endMs) && endMs > startMs ? Math.round((endMs - startMs) / 1000) : null;

const push = (name: string, rawUsed: number | null, limit: number, value: number, valueLabel: string): void => {
if (rawUsed == null) return;
const rawPctOfLimit = (rawUsed / limit) * 100;
const pctOfLimit = pct3(rawUsed, limit);
// The raw count can be finite while scaling it to a percentage
// overflows, or the source can report a value outside its quota.
// Neither is a usable live window (#2579).
if (!isPercentOf(100)(rawPctOfLimit) || !isPercentOf(100)(pctOfLimit)) return;
entry.windows.push({
name,
value,
pctOfLimit: pct3(rawUsed, limit),
pctOfLimit,
valueLabel,
windowSeconds,
resetsAt,
Expand Down
49 changes: 22 additions & 27 deletions pm-stack/aggregator/src/saas-extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import type { ChargeRow, DatedRead, PaygEstimate, PaygLine, SaasGroup, SaasService, UsageMetric } from "./model.ts";
import { sectionOf } from "./quota-extract.ts";
import { parseIsoDate } from "./validate.ts";
import { isFiniteNumber, isNonEmptyString, isNonNegative, isRecord, parseIsoDate } from "./validate.ts";

const DATE_RE = /\d{4}-\d{2}-\d{2}/g;

Expand Down Expand Up @@ -944,37 +944,38 @@ export function applySupabaseExport(
nowMs: number = Date.now(),
): SaasService[] {
if (!doc || (doc.status !== "ok" && doc.status !== "partial")) return services;
// The freshness anchor must be a real calendar date, not merely a
// string Date.parse accepts (#2508, #5018): a non-string or impossible
// timestamp cannot pass the gate and corrupt the card.
if (typeof doc.measuredAt !== "string" || !doc.measuredAt || !Array.isArray(doc.metrics)) return services;
// Real-calendar ISO only (#5018): see the Cloudflare gate above.
const measured = parseIsoDate(doc.measuredAt);
if (!measured) return services;
if (measured === null) return services;
const measuredMs = measured.getTime();
const measuredAt = doc.measuredAt;
if (nowMs - measuredMs > SUPABASE_EXPORT_STALE_MS || measuredMs > nowMs + 5 * 60 * 1000) return services;
const supabase = services.find((s) => s.id === "supabase");
if (!supabase) return services;
const byId = new Map(
doc.metrics
.filter(
(m) =>
m &&
typeof m.id === "string" &&
!(typeof m.used === "number" && m.used < 0) &&
!(typeof m.limit === "number" && m.limit < 0),
)
.map((m) => [m.id, m]),
);
// Element-wise contract check (#2508): a metric needs a non-empty id,
// and a present used/limit must be finite and non-negative. A metric
// with a null used is a documented gap, not bad data.
const isLiveMetric = (m: unknown): m is SupabaseExportMetric =>
isRecord(m) &&
isNonEmptyString(m.id) &&
(m.used == null || isNonNegative(m.used)) &&
(m.limit == null || isNonNegative(m.limit));
const byId = new Map(doc.metrics.filter(isLiveMetric).map((m) => [m.id, m]));
if (!byId.size) return services;
supabase.metrics = supabase.metrics.map((m) => {
const live = byId.get(m.id);
if (!live) return m;
const unit = live.unit === "gb" || live.unit === "pct" || live.unit === "count" ? live.unit : m.unit;
const used = typeof live.used === "number" && Number.isFinite(live.used) ? live.used : null;
const limit = typeof live.limit === "number" && Number.isFinite(live.limit) ? live.limit : m.limit;
const used = isFiniteNumber(live.used) ? live.used : null;
const limit = isFiniteNumber(live.limit) ? live.limit : m.limit;
const parts: string[] = [];
if (used == null) {
parts.push(`Not measured this tick${live.detail ? ` — ${live.detail}` : ""}`);
} else {
parts.push(`Live via ${live.source ?? doc.source ?? "file-export/supabase"}, measured ${doc.measuredAt}.`);
parts.push(`Live via ${live.source ?? doc.source ?? "file-export/supabase"}, measured ${measuredAt}.`);
if (live.detail) parts.push(live.detail);
if (live.flag === "approaching-paid-trigger") {
parts.push(
Expand All @@ -991,13 +992,7 @@ export function applySupabaseExport(
note: parts.join(" ").slice(0, 600),
};
});
if (
doc.billing &&
doc.billing.measured !== false &&
typeof doc.billing.billedUsd === "number" &&
Number.isFinite(doc.billing.billedUsd) &&
doc.billing.billedUsd >= 0
) {
if (doc.billing && doc.billing.measured !== false && isNonNegative(doc.billing.billedUsd)) {
supabase.billedUsd = doc.billing.billedUsd;
} else {
// Codex P2 (PR #2369 re-review, 2026-10-29): an accepted export with no
Expand All @@ -1008,12 +1003,12 @@ export function applySupabaseExport(
supabase.billedUsd = null;
}
supabase.plan = doc.billing?.plan
? `Free plan (${doc.project ?? "supabase"}); measured ${doc.measuredAt}`
? `Free plan (${doc.project ?? "supabase"}); measured ${measuredAt}`
: supabase.plan;
supabase.measuredAt = doc.measuredAt.slice(0, 10);
supabase.measuredAt = measuredAt.slice(0, 10);
supabase.sourceClass = "api";
const gapCount = (doc.scope ?? []).filter((s) => typeof s.status === "number" && s.status >= 400).length;
supabase.sourceNote = `Supabase usage collector (#1050): ${doc.source ?? "file-export/supabase"}, measured ${doc.measuredAt}; ${
supabase.sourceNote = `Supabase usage collector (#1050): ${doc.source ?? "file-export/supabase"}, measured ${measuredAt}; ${
gapCount ? `${gapCount} documented scope gap(s) — see the export's scope array` : "every probed endpoint answered"
}; limits from the Free-plan record.`;
return services;
Expand Down
Loading
Loading