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
7 changes: 7 additions & 0 deletions pm-stack/aggregator/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ export interface Config {
/** The stewardship quota view; the hub's live fallback source when the
* fleet feed carries no saas/payg sections yet (hub §2.3). */
quotaViewFile: string;
/** The Supabase usage exporter's document (#1050): the gathered live read
* preferred over the quota view's Supabase prose when fresh. */
supabaseExportFile: string;
/** The provider quota registry; the hub's second dated-read source
* (billing incidents) for the same fallback path. */
quotaRegistryFile: string;
Expand Down Expand Up @@ -78,6 +81,10 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
"workspace/goals/stewardship-commission-recurring-review-and-dispatch/hidden_files/visibility/quota-view.md",
),
),
supabaseExportFile: s(
env.PM_AGG_SUPABASE_EXPORT,
join(homedir(), "atlas/supabase-export/latest.json"),
),
quotaRegistryFile: s(
env.PM_AGG_QUOTA_REGISTRY,
join(homedir(), "workspace/goals/keep-the-four-repos-healthy/hidden_files/provider-quota-registry.md"),
Expand Down
105 changes: 105 additions & 0 deletions pm-stack/aggregator/src/saas-extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,111 @@ export function extractSaasServices(doc: string): SaasService[] {
return services;
}

// --- Supabase live export overlay (#1050) -----------------------------------

/** One metric row of a supabase-quota-export document. */
export interface SupabaseExportMetric {
id: string;
label?: string;
/** null = the probe could not measure it this tick (a documented gap). */
used: number | null;
limit?: number | null;
unit?: string;
source?: string;
detail?: string;
/** "approaching-paid-trigger" when used >= 80% of the Free limit. */
flag?: string;
}

/** The file-export document written by pm-stack/supabase-export. */
export interface SupabaseExportDoc {
service?: string;
source?: string;
/** ok | partial (some scope gaps recorded) — measurements are present. */
status?: string;
measuredAt?: string | null;
project?: string;
ref?: string;
metrics?: SupabaseExportMetric[];
billing?: { plan?: string; billedUsd?: number; measured?: boolean; source?: string };
scope?: { endpoint?: string; path?: string; status?: number; note?: string }[];
}

/** Freshness bound mirroring the #1151 tick: > 30 min means the producer is
* unreachable/stale and the card falls back to its recorded prose. */
export const SUPABASE_EXPORT_STALE_MS = 30 * 60 * 1000;

/**
* Prefer a fresh supabase-export document on the Supabase card (#1050).
* Matching metric ids take `used`, `limit`, `unit` and a measured-at/source
* note from the export; a metric the probe could not measure keeps today's
* null-but-recorded behaviour with the export's gap detail. `billedUsd`
* becomes the export's measured addon read instead of the hardcoded 0 —
* or unknown (null) when the accepted export carries no valid billing
* measurement, so a failed billing probe never renders as $0.00 billed.
* Missing, failed, unparseable or stale documents change nothing.
*/
export function applySupabaseExport(
services: SaasService[],
doc: SupabaseExportDoc | null,
nowMs: number = Date.now(),
): SaasService[] {
if (!doc || (doc.status !== "ok" && doc.status !== "partial")) return services;
if (!doc.measuredAt || !Array.isArray(doc.metrics)) return services;
const measuredMs = Date.parse(doc.measuredAt);
if (!Number.isFinite(measuredMs)) return services;
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").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 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}.`);
if (live.detail) parts.push(live.detail);
if (live.flag === "approaching-paid-trigger") {
parts.push("Approaching-paid trigger: at or above 80% of the Free-plan limit (Drew's $30/mo ceiling is the decision context).");
}
}
return {
...m,
used,
limit,
unit,
percent: used != null && limit != null && limit > 0 ? Math.round((used / limit) * 1000) / 10 : undefined,
note: parts.join(" ").slice(0, 600),
};
});
if (doc.billing && doc.billing.measured !== false && typeof doc.billing.billedUsd === "number" && Number.isFinite(doc.billing.billedUsd)) {
supabase.billedUsd = doc.billing.billedUsd;
} else {
// Codex P2 (PR #2369 re-review, 2026-10-29): an accepted export with no
// valid billing measurement must not keep the hardcoded 0 from
// extractSaasServices — the card is stamped fresh/api below, so $0.00
// would read as a measured billed amount. Unknown (null) renders as
// no billed line at all.
supabase.billedUsd = null;
}
supabase.plan = doc.billing?.plan ? `Free plan (${doc.project ?? "supabase"}); measured ${doc.measuredAt}` : supabase.plan;
supabase.measuredAt = doc.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}; ${
gapCount ? `${gapCount} documented scope gap(s) — see the export's scope array` : "every probed endpoint answered"
}; limits from the Free-plan record.`;
return services;
}

// --- PAYG lines (§1.2) -------------------------------------------------------

/**
Expand Down
14 changes: 11 additions & 3 deletions pm-stack/aggregator/src/sources/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ import {
import { isSessionRecord, mergeRecords, recordFromSessionEntry } from "../registry.ts";
import { buildAttentionFlags } from "../derive.ts";
import { summarizeDns } from "../dns.ts";
import { extractCharges, extractPaygLines, extractSaasServices, extractSubscriptions } from "../saas-extract.ts";
import { applySupabaseExport, extractCharges, extractPaygLines, extractSaasServices, extractSubscriptions } from "../saas-extract.ts";
import type { SupabaseExportDoc } from "../saas-extract.ts";
import { isProjectPoolItem, poolItemToGhItem } from "../projects.ts";
import { INITIAL_STANDING_AUTO, sanitizeTierItemExtensions, withUserFallbacks } from "../tier-items.ts";
import { overlayQuotaCurrent, parseQuotaCurrent } from "../quota-current.ts";
Expand Down Expand Up @@ -805,10 +806,17 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise<bo
domainCount: feed.dns.entries.length,
}
: null;
// The Supabase export overlay applies to BOTH service sources:
// the collector's feed.saas cards are built with plain
// extractSaasServices, so without this the fresh export would be
// ignored exactly when the fleet collector is operating (#1050).
const supabaseExport = await readFile(cfg.supabaseExportFile, "utf8")
.then((text) => JSON.parse(text) as SupabaseExportDoc)
.catch(() => null);
if (feed?.saas && feed.saas.length) {
provenance.usage = `live (fleet feed · ${feedAgeText(feed.generatedAt)} · collected ${feed.generatedAt})`;
const partial = {
services: feed.saas,
services: applySupabaseExport(feed.saas, supabaseExport),
payg: feed.payg ?? [],
charges: feed.charges ?? [],
subscriptions: feed.subscriptions ?? [],
Expand Down Expand Up @@ -840,7 +848,7 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise<bo
readFile(cfg.quotaRegistryFile, "utf8").catch(() => ""),
]);
const partial = {
services: extractSaasServices(doc),
services: applySupabaseExport(extractSaasServices(doc), supabaseExport),
Comment thread
dezren39 marked this conversation as resolved.
Resolved
payg: extractPaygLines(doc, registryText),
charges: extractCharges(doc, registryText),
subscriptions: extractSubscriptions(doc),
Expand Down
157 changes: 157 additions & 0 deletions pm-stack/aggregator/test/supabase-export.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// Supabase live-export overlay (#1050 / queue task 2985): a fresh
// supabase-export document puts measured used/limit + the measured
// billed state on the Supabase card; a missing, failed or stale
// document reproduces the recorded prose exactly.
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 { applySupabaseExport, extractSaasServices, type SupabaseExportDoc } from "../src/saas-extract.ts";
import { liveSource } from "../src/sources/live.ts";

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 |

## Service details (b)

### Supabase
- **Plan / price:** Free plan (muse-dev); numerical quotas unknown in local records.
- **Usage / dates:** Not measured — manual dashboard read needed.
- **Last checked:** 2026-10-28.
`;

const NOW = Date.parse("2026-10-29T15:00:00Z");

function freshDoc(overrides: Partial<SupabaseExportDoc> = {}): SupabaseExportDoc {
return {
service: "supabase",
source: "file-export/supabase",
status: "partial",
measuredAt: "2026-10-29T14:55:00Z",
project: "muse-dev",
ref: "nltgxorqwxhgfzseiirt",
metrics: [
{ id: "db-size", label: "Database size", used: 1.154, limit: 0.5, unit: "gb", source: "management-api:/database/query pg_database_size", flag: "approaching-paid-trigger" },
{ id: "egress", label: "Egress (cycle)", used: null, limit: 5, unit: "gb", source: "none", detail: "No Management API endpoint reports egress bytes." },
{ id: "storage", label: "File storage", used: 0, limit: 1, unit: "gb", source: "management-api:/storage/buckets", detail: "0 buckets on the project" },
],
billing: { plan: "free", billedUsd: 0, measured: true, source: "management-api:/billing/addons" },
scope: [
{ endpoint: "projects", status: 200 },
{ endpoint: "organizations/:slug", status: 403, note: "scope gap" },
{ endpoint: "usage.egress", status: 404 },
],
...overrides,
};
}

const supabaseCard = (services: ReturnType<typeof extractSaasServices>) => services.find((s) => s.id === "supabase")!;
const metricOf = (services: ReturnType<typeof extractSaasServices>, id: string) =>
supabaseCard(services).metrics.find((m) => m.id === id)!;

describe("applySupabaseExport", () => {
test("a fresh export supplies measured used + Free limits for db-size and storage", () => {
const out = applySupabaseExport(extractSaasServices(VIEW), freshDoc(), NOW);
const db = metricOf(out, "db-size");
expect(db.used).toBe(1.154);
expect(db.limit).toBe(0.5);
expect(db.unit).toBe("gb");
expect(db.percent).toBe(230.8);
expect(db.note).toContain("measured 2026-10-29T14:55:00Z");
expect(db.note).toContain("Approaching-paid trigger");
const storage = metricOf(out, "storage");
expect(storage.used).toBe(0);
expect(storage.limit).toBe(1);
expect(supabaseCard(out).sourceClass).toBe("api");
expect(supabaseCard(out).measuredAt).toBe("2026-10-29");
});

test("egress keeps a recorded limit but stays unmeasured, with the gap detail", () => {
const out = applySupabaseExport(extractSaasServices(VIEW), freshDoc(), NOW);
const egress = metricOf(out, "egress");
expect(egress.used).toBeNull();
expect(egress.limit).toBe(5);
expect(egress.percent).toBeUndefined();
expect(egress.note).toContain("Not measured this tick");
expect(egress.note).toContain("egress bytes");
});

test("billed is the export's measured addon read, not the hardcoded 0", () => {
const out = applySupabaseExport(extractSaasServices(VIEW), freshDoc({ billing: { plan: "free", billedUsd: 25, measured: true } }), NOW);
expect(supabaseCard(out).billedUsd).toBe(25);
expect(supabaseCard(out).plan).toContain("measured 2026-10-29T14:55:00Z");
});

test("an accepted export without a valid billing measurement clears billed to unknown", () => {
const noBilling = applySupabaseExport(extractSaasServices(VIEW), freshDoc({ billing: null as unknown as SupabaseExportDoc["billing"] }), NOW);
expect(supabaseCard(noBilling).billedUsd).toBeNull();
expect(supabaseCard(noBilling).sourceClass).toBe("api"); // the rest of the overlay still applied
expect(metricOf(noBilling, "db-size").used).toBe(1.154);
const unmeasured = applySupabaseExport(extractSaasServices(VIEW), freshDoc({ billing: { plan: "free" } }), NOW);
expect(supabaseCard(unmeasured).billedUsd).toBeNull();
});

test("a stale export falls back to exactly today's card", () => {
const base = extractSaasServices(VIEW);
const out = applySupabaseExport(base, freshDoc({ measuredAt: "2026-10-29T12:00:00Z" }), NOW);
expect(out).toEqual(base);
expect(supabaseCard(out).billedUsd).toBe(0); // today's constant
expect(metricOf(out, "db-size").used).toBeNull();
});

test("missing, failed and unparseable documents change nothing", () => {
const base = extractSaasServices(VIEW);
expect(applySupabaseExport(base, null, NOW)).toEqual(base);
expect(applySupabaseExport(base, freshDoc({ status: "fetch-failed", metrics: undefined }), NOW)).toEqual(base);
expect(applySupabaseExport(base, freshDoc({ measuredAt: "not-a-date" }), NOW)).toEqual(base);
expect(applySupabaseExport(base, freshDoc({ metrics: [] }), NOW)).toEqual(base);
});

test("a document without a Supabase card in the view is a no-op", () => {
const out = applySupabaseExport(extractSaasServices("nothing here"), freshDoc(), NOW);
expect(out.find((s) => s.id === "supabase")!.metrics).toEqual([]);
});
});

describe("live source usage(): the overlay reaches fleet-feed services too", () => {
test("feed.saas cards get the fresh export overlay, not just the quota-view fallback", async () => {
const dir = await mkdtemp(join(tmpdir(), "pm-supa-feed-"));
const nowIso = new Date().toISOString();
const feedFile = join(dir, "fleet-feed.json");
const exportFile = join(dir, "latest.json");
await writeFile(exportFile, JSON.stringify(freshDoc({ measuredAt: nowIso })));
await writeFile(
feedFile,
JSON.stringify({
version: 1,
generatedAt: nowIso,
quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } },
attention: [],
saas: extractSaasServices(VIEW),
}),
);
const cfg = loadConfig({
PM_AGG_SOURCE: "live",
PM_AGG_FEED_FILE: feedFile,
PM_AGG_SUPABASE_EXPORT: exportFile,
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: "",
});
const usage = await liveSource(cfg).usage();
const db = metricOf(usage.services, "db-size");
expect(db.used).toBe(1.154);
expect(db.limit).toBe(0.5);
expect(supabaseCard(usage.services).billedUsd).toBe(0);
});
});
Loading
Loading