From 261eca8ed3f24735186c9374cad9dc05dab5e5da Mon Sep 17 00:00:00 2001 From: Archer Date: Mon, 26 Oct 2026 13:08:14 +0000 Subject: [PATCH 1/3] feat(aggregator): usage & billing hub data layer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Model + Source.usage() for the hub (design 2026-10-25): family-2 SaasService/PaygLine/ChargeRow/AttentionFlag/SnapshotRecord types, Provenance gains a usage facet. New saas-extract.ts parses quota-view.md Part (b) with quota-extract's fail-soft dated-read pattern (per-service highlight metrics per design §2.2, Decision-004 PAYG estimates, charges evidence, renewal-only subscriptions strip). New snapshots.ts: the §4 append-only store — monthly JSONL files, dedupe on re-append, original timestamps/source classes preserved. Bubble rules (>80% of limit, >$5 projected unbilled), freshness, and pace projection derivations in derive.ts. Collector embeds saas/payg/ charges/subscriptions sections into the fleet feed; the live source falls back to a direct quota-view+registry read, then fixtures. Manifest: quota page retitled 'Usage & billing', route unchanged. --- .../aggregator/scripts/collect-fleet-feed.ts | 34 +- pm-stack/aggregator/src/config.ts | 20 + pm-stack/aggregator/src/derive.ts | 182 +++++ pm-stack/aggregator/src/feed.ts | 12 + pm-stack/aggregator/src/model.ts | 181 +++++ pm-stack/aggregator/src/pages.ts | 4 +- pm-stack/aggregator/src/quota-extract.ts | 2 +- pm-stack/aggregator/src/saas-extract.ts | 638 ++++++++++++++++++ pm-stack/aggregator/src/snapshots.ts | 116 ++++ pm-stack/aggregator/src/source.ts | 4 + pm-stack/aggregator/src/sources/fixtures.ts | 169 +++++ pm-stack/aggregator/src/sources/live.ts | 68 ++ 12 files changed, 1424 insertions(+), 6 deletions(-) create mode 100644 pm-stack/aggregator/src/saas-extract.ts create mode 100644 pm-stack/aggregator/src/snapshots.ts diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index 3592a5061c..351a6b22c2 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -20,7 +20,8 @@ // Usage: bun run scripts/collect-fleet-feed.ts [--out ] // Env overrides: QUOTA_VIEW_PATH, JULES_STATE_PATH, SANDBOX_OPENCODE_URL, // OPENCODE_SERVER_PASSWORD_FILE, ORCHESTRATION_PATH, DNS_REGISTER_PATH, -// CLAUDE_LAUNCH_RECORDS_PATH. +// CLAUDE_LAUNCH_RECORDS_PATH, QUOTA_REGISTRY_PATH (the hub's PAYG/charges +// sections read the provider registry's billing incidents, fail-soft). import { readFile, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; @@ -37,6 +38,8 @@ import type { } from "../src/model.ts"; 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 type { ChargeRow, PaygLine, SaasService } from "../src/model.ts"; import { parseLaunchRecords, recordFromSessionEntry } from "../src/registry.ts"; import { julesSummary, mapJulesItems, type JulesReviewState } from "../src/sources/jules.ts"; import { mapServerSessions, poolBurn } from "../src/sources/opencode.ts"; @@ -59,6 +62,7 @@ const dnsRegisterPath = process.env.DNS_REGISTER_PATH ?? join(HOME, "workspace/goals/stand-up-lab-cluster-talm-talos-cozystack-postgres-rustfs/files/dns-domain-register.md"); 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 serverUrl = process.env.SANDBOX_OPENCODE_URL ?? "http://127.0.0.1:4096"; const passwordFile = process.env.OPENCODE_SERVER_PASSWORD_FILE ?? join(HOME, "tools/secrets.d/opencode-server-password"); @@ -118,13 +122,32 @@ async function main(): Promise { // --- quota ------------------------------------------------------------- let pools: QuotaPool[] = []; + let quotaViewText = ""; try { - const quotaView = await readFile(quotaViewPath, "utf8"); - pools = extractQuotaPools(quotaView, now); + quotaViewText = await readFile(quotaViewPath, "utf8"); + pools = extractQuotaPools(quotaViewText, now); } catch (err) { console.error(`collector: quota view unreadable (${err}); emitting no pools`); } + // --- usage & billing hub sections (design §2.3: ride the same feed) --- + let saas: SaasService[] | undefined; + let payg: PaygLine[] | undefined; + let charges: ChargeRow[] | undefined; + let subscriptions: FleetFeed["subscriptions"]; + if (quotaViewText) { + let registryText = ""; + try { + registryText = await readFile(quotaRegistryPath, "utf8"); + } catch { + console.error("collector: provider quota registry unreadable; hub PAYG/charges lose the registry reads"); + } + saas = extractSaasServices(quotaViewText); + payg = extractPaygLines(quotaViewText, registryText); + charges = extractCharges(quotaViewText, registryText); + subscriptions = extractSubscriptions(quotaViewText); + } + // --- sandbox attention + burn ------------------------------------------- let attention: SessionFeedEntry[] = []; try { @@ -224,6 +247,10 @@ async function main(): Promise { ...(orchestration ? { orchestration } : {}), ...(dns ? { dns } : {}), ...(registry.length ? { registry } : {}), + ...(saas ? { saas } : {}), + ...(payg ? { payg } : {}), + ...(charges ? { charges } : {}), + ...(subscriptions ? { subscriptions } : {}), }; await writeFile(outPath, JSON.stringify(feed, null, 2)); const withReads = pools.filter((p) => p.windows.length > 0).length; @@ -231,6 +258,7 @@ async function main(): Promise { `collector: wrote ${outPath} — ${pools.length} pools (${withReads} with reads), ${attention.length} sessions (sandbox + jules${jules ? `, ${jules.tracked} jules tracked` : ""})` + (orchestration ? `, orchestration ${orchestration.runId}` : ", no orchestration section") + (dns ? `, dns ${dns.entries.length} domains` : ", no dns section") + + (saas ? `, hub ${saas.length} services / ${payg?.length ?? 0} payg / ${charges?.length ?? 0} charges` : ", no hub sections") + `, registry ${registry.length} records`, ); } diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index 9958258414..2a1b905707 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -17,6 +17,14 @@ export interface Config { commentsFile: string; /** Durable identity-registry store (#906 §3), merged on every read. */ registryFile: string; + /** Usage snapshot store (hub §4): a directory of monthly JSONL files. */ + snapshotsDir: string; + /** 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 provider quota registry; the hub's second dated-read source + * (billing incidents) for the same fallback path. */ + quotaRegistryFile: string; /** OpenChamber managed-opencode state file (laptop attention source). */ openchamberStateFile: string; kaneo: { @@ -47,6 +55,18 @@ export function loadConfig(env: Record = process.env feedFile: s(env.PM_AGG_FEED_FILE, join(process.cwd(), "fleet-feed.json")), commentsFile: s(env.PM_AGG_COMMENTS_FILE, join(process.cwd(), "comments.json")), registryFile: s(env.PM_AGG_REGISTRY_FILE, join(process.cwd(), "registry.json")), + snapshotsDir: s(env.PM_AGG_SNAPSHOTS_DIR, join(process.cwd(), "snapshots")), + quotaViewFile: s( + env.PM_AGG_QUOTA_VIEW, + join( + homedir(), + "workspace/goals/stewardship-commission-recurring-review-and-dispatch/hidden_files/visibility/quota-view.md", + ), + ), + quotaRegistryFile: s( + env.PM_AGG_QUOTA_REGISTRY, + join(homedir(), "workspace/goals/keep-the-four-repos-healthy/hidden_files/provider-quota-registry.md"), + ), openchamberStateFile: s( env.PM_AGG_OPENCHAMBER_STATE, join(homedir(), ".config", "openchamber", "managed-opencode", "state.json"), diff --git a/pm-stack/aggregator/src/derive.ts b/pm-stack/aggregator/src/derive.ts index f9eb66a4c0..1ef215a034 100644 --- a/pm-stack/aggregator/src/derive.ts +++ b/pm-stack/aggregator/src/derive.ts @@ -698,3 +698,185 @@ export function deriveToday( } return { fromOrchestrator: false, objectives, momentum }; } + +// --------------------------------------------------------------------------- +// Usage & billing hub derivations (hub design §1.3, §4). Bubble rules are +// GOAL.md-fixed: any metric over 80% of its limit, or projected unbilled +// PAYG over $5 (unbilled accrual only — Q3 default), surfaces worst-first. +// --------------------------------------------------------------------------- + +import { countedEstimate, type AttentionFlag, type QuotaView, type SnapshotRecord, type UsageView } from "./model.ts"; + +export const BUBBLE_PCT = 80; +export const BUBBLE_USD = 5; + +/** + * Every tripped bubble rule across both families. `usage.payg` is the + * aggregation point for PAYG estimates, so a service whose estimate is + * already a PAYG line is not double-counted (service ids listed in + * `paygLineServices`). + */ +export function buildAttentionFlags( + quota: QuotaView, + usage: Pick, + paygLineServices: ReadonlySet = new Set(["cloudflare"]), +): AttentionFlag[] { + const flags: AttentionFlag[] = []; + for (const pool of quota.pools) { + for (const w of pool.windows) { + const pct = windowPercent(w); + if (pct > BUBBLE_PCT) { + flags.push({ + kind: "over-limit", + label: `${pool.provider} · ${pool.plan} — ${w.name}`, + detail: `${Math.round(pct)}% of limit used${w.resetsAt ? ` · resets ${w.resetsAt.slice(0, 10)}` : ""}`, + href: "/quota", + severity: pct, + }); + } + } + } + for (const svc of usage.services) { + for (const m of svc.metrics) { + if (m.percent != null && m.percent > BUBBLE_PCT) { + flags.push({ + kind: "over-limit", + label: `${svc.name} — ${m.label}`, + detail: `${Math.round(m.percent)}% of limit used`, + href: `/quota/service/${svc.id}`, + severity: m.percent, + }); + } + } + if (svc.paygEstimate && !paygLineServices.has(svc.id)) { + const counted = countedEstimate(svc.paygEstimate); + if (counted > BUBBLE_USD) { + flags.push({ + kind: "payg-unbilled", + label: `${svc.name} — PAYG estimate`, + detail: `counted $${counted.toFixed(2)} unbilled (1.2 × high $${svc.paygEstimate.high.toFixed(2)})`, + href: `/quota/service/${svc.id}`, + severity: counted, + }); + } + } + } + for (const line of usage.payg) { + if (line.unbilledUsd != null && line.unbilledUsd > BUBBLE_USD) { + flags.push({ + kind: "payg-unbilled", + label: line.label, + detail: `$${line.unbilledUsd.toFixed(2)} projected unbilled${line.estimate ? ` (estimate $${line.estimate.low.toFixed(2)}–$${line.estimate.high.toFixed(2)})` : ""}`, + href: "/quota", + severity: line.unbilledUsd, + }); + } + } + // Worst first: over-limit by percent, then PAYG by dollars — the two + // severities are different units, so kinds stay grouped, worst kind + // (over-limit) first per the design's "worst first" reading order. + return flags.sort((a, b) => + a.kind === b.kind ? b.severity - a.severity : a.kind === "over-limit" ? -1 : 1, + ); +} + +export interface Freshness { + stale: boolean; + /** Whole days since the freshest read; null when never measured. */ + ageDays: number | null; +} + +/** A card is stale when its freshest read is older than its cadence (§1.1). */ +export function freshness(measuredAt: string | null, cadenceDays: number, now = new Date()): Freshness { + if (!measuredAt) return { stale: true, ageDays: null }; + const t = Date.parse(measuredAt.length <= 10 ? `${measuredAt}T23:59:59Z` : measuredAt); + if (Number.isNaN(t)) return { stale: true, ageDays: null }; + const ageDays = Math.max(0, Math.floor((now.getTime() - t) / 86_400_000)); + return { stale: ageDays > cadenceDays, ageDays }; +} + +export interface PaceProjection { + metricId: string; + /** Points used in the fit (after the last reset boundary). */ + points: number; + /** Percent-points burned per day. */ + slopePerDay: number; + /** ISO when the metric reaches 100% at the current slope, if it does. */ + projectedExhaustionAt: string | null; + /** Projected percent at the window's recorded reset, when known. */ + projectedPercentAtReset: number | null; +} + +const RESET_DROP_PCT = 30; + +/** Index just after the last reset boundary (a resetsAt passing, or a big drop). */ +function windowStartIndex(recs: SnapshotRecord[]): number { + let start = 0; + for (let i = 1; i < recs.length; i++) { + const prev = recs[i - 1]; + const cur = recs[i]; + const resetPassed = prev.resetsAt != null && Date.parse(prev.resetsAt) <= Date.parse(cur.ts); + const dropped = + typeof prev.value === "number" && typeof cur.value === "number" && prev.value - cur.value >= RESET_DROP_PCT; + if (resetPassed || dropped) start = i; + } + return start; +} + +/** + * Linear pace projection for one pct metric from its snapshot history + * (§4: the computation quota-view.md does by hand for Claude). Null + * when history cannot support a projection — never invented. + */ +export function projectPace(records: SnapshotRecord[], metricId: string): PaceProjection | null { + const recs = records + .filter((r) => r.metricId === metricId && r.unit === "pct" && typeof r.value === "number") + .sort((a, b) => a.ts.localeCompare(b.ts)); + const win = recs.slice(windowStartIndex(recs)); + if (win.length < 2) return null; + const first = win[0]; + const last = win[win.length - 1]; + const days = (Date.parse(last.ts) - Date.parse(first.ts)) / 86_400_000; + if (days < 0.5) return null; + const slope = ((last.value as number) - (first.value as number)) / days; + if (slope <= 0.05) return null; + const lastVal = last.value as number; + const projectedExhaustionAt = + lastVal >= 100 + ? last.ts + : new Date(Date.parse(last.ts) + ((100 - lastVal) / slope) * 86_400_000).toISOString(); + let projectedPercentAtReset: number | null = null; + if (last.resetsAt) { + const toReset = (Date.parse(last.resetsAt) - Date.parse(last.ts)) / 86_400_000; + if (toReset > 0) projectedPercentAtReset = Math.round((lastVal + slope * toReset) * 10) / 10; + } + return { + metricId, + points: win.length, + slopePerDay: Math.round(slope * 100) / 100, + projectedExhaustionAt, + projectedPercentAtReset, + }; +} + +/** Reset points in a metric's history, for chart markers (§4, §1.5). */ +export function resetMarkers(records: SnapshotRecord[], metricId: string): { ts: string; resetsAt: string }[] { + const recs = records + .filter((r) => r.metricId === metricId) + .sort((a, b) => a.ts.localeCompare(b.ts)); + const out: { ts: string; resetsAt: string }[] = []; + for (let i = 1; i < recs.length; i++) { + const prev = recs[i - 1]; + const cur = recs[i]; + if (prev.resetsAt && Date.parse(prev.resetsAt) <= Date.parse(cur.ts)) { + out.push({ ts: prev.resetsAt, resetsAt: prev.resetsAt }); + } else if ( + typeof prev.value === "number" && + typeof cur.value === "number" && + prev.value - cur.value >= RESET_DROP_PCT + ) { + out.push({ ts: cur.ts, resetsAt: cur.ts }); + } + } + return out; +} diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index be002a393c..94d1baa545 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -5,10 +5,13 @@ // a stale feed keeps rendering with its age stated in provenance. import { readFile } from "node:fs/promises"; import type { + ChargeRow, DnsSection, JulesSummary, OrchestrationSection, + PaygLine, QuotaView, + SaasService, SessionFeedEntry, SessionRecord, } from "./model.ts"; @@ -28,6 +31,15 @@ export interface FleetFeed { dns?: DnsSection; /** Identity-registry records (#906 §3): sandbox OpenCode + Jules + Muse launches. */ registry?: SessionRecord[]; + /** Usage & billing hub (design §2.3): family-2 services extracted from + * quota-view.md Part (b) by the collector; absent in older feeds. */ + saas?: SaasService[]; + /** Hub PAYG lines (§1.2), from quota-view.md + the provider registry. */ + payg?: PaygLine[]; + /** Hub charges evidence (§2.4), from the same dated records. */ + charges?: ChargeRow[]; + /** Hub subscriptions strip rows (Q5: renewal-only). */ + subscriptions?: { name: string; plan: string; renewsAt: string | null }[]; } /** diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index 3c507c5dc6..90cc5fef8d 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -110,6 +110,7 @@ export interface Provenance { items: string; comments: string; quota: string; + usage: string; attention: string; orchestration: string; dns: string; @@ -519,3 +520,183 @@ export interface SessionRecord { /** Loose task linkage: GitHub refs this session is working. */ taskRefs: RefKey[]; } + +// --------------------------------------------------------------------------- +// Usage & billing hub (design 2026-10-25, hub-design §1–§4). Family 2 +// (SaaS services), the PAYG dollars view, charges evidence, the bubble +// flags, and the append-only snapshot store's record shape. The hub +// evolves the quota page in place: QuotaView above stays untouched for +// its existing consumers; UsageView rides beside it via Source.usage(). +// --------------------------------------------------------------------------- + +/** How a number was obtained — manual/console reads are first-class. */ +export type UsageSourceClass = "api" | "console" | "manual" | "estimate" | "invoice"; + +export type UsageUnit = + | "pct" + | "usd" + | "count" + | "gb" + | "tokens" + | "minutes" + | "hours" + | "ms" + | "rows" + | "ops" + | "neurons" + | "other"; + +/** One measured (or allowance-only) metric on a SaaS service card. */ +export interface UsageMetric { + id: string; + label: string; + /** null = an allowance is recorded but usage was not measured. */ + used: number | null; + limit: number | null; + unit: UsageUnit; + /** 0–100+, present when used and limit are both known (or unit is pct). */ + percent?: number; + /** In the §2 highlight set (front page); false = detail view only. */ + highlight: boolean; + note?: string; +} + +/** + * A Decision-004 PAYG estimate: low/high as recorded. The counted + * figure (1.2 × high) is derived at render time, never stored. + */ +export interface PaygEstimate { + low: number; + high: number; + /** What the low/high describe, e.g. "per month" or "Oct 24–25 accrual". */ + period: string; + note?: string; +} + +/** The counted figure for an estimate: 1.2 × high (Decision 004). */ +export function countedEstimate(e: PaygEstimate): number { + return Math.round(e.high * 1.2 * 100) / 100; +} + +export type SaasGroup = "database" | "object-storage" | "compute" | "dev-platform" | "domains" | "account-tooling"; + +export const SAAS_GROUP_LABELS: Record = { + database: "Database", + "object-storage": "Object storage", + compute: "Compute / platform", + "dev-platform": "Dev platform", + domains: "Domains", + "account-tooling": "Account tooling / flat", +}; + +/** One dated source read, preserved verbatim-ish for the detail view. */ +export interface DatedRead { + /** ISO date (or datetime) of the read. */ + at: string; + text: string; +} + +/** One family-2 service: a card on the hub, a page at /quota/service/. */ +export interface SaasService { + id: string; + name: string; + group: SaasGroup; + /** Plan + price as recorded, e.g. "Workers Paid $5/mo + R2 Paid $0 base". */ + plan: string; + status: "active" | "candidate" | "no-account" | "unknown"; + metrics: UsageMetric[]; + /** The recorded PAYG estimate, or null when none exists. */ + paygEstimate: PaygEstimate | null; + /** Why there is no estimate: "not applicable — …" / "not estimable from local records". */ + paygNote?: string; + /** USD invoiced/charged this period, when a record states it. */ + billedUsd?: number | null; + /** ISO date/datetime of the freshest dated read behind this card. */ + measuredAt: string | null; + sourceClass: UsageSourceClass; + /** Where the card's facts came from, human-readable. */ + sourceNote: string; + /** Renewal/reset as recorded (may be prose, e.g. "cycle ends 2026-10-31"). */ + nextDate?: string | null; + /** Expected re-measure cadence in days; older reads render stale. */ + cadenceDays: number; + /** Dated disagreements between sources, shown not resolved (§1.1). */ + conflicts: string[]; + /** Every dated read the extractor found, freshest first (detail view). */ + reads: DatedRead[]; + /** The section's usage prose, trimmed (detail view + shell cards). */ + usageNote?: string; +} + +/** One line of the PAYG dollars card (§1.2). */ +export interface PaygLine { + id: string; + label: string; + /** Accrued this period, when a figure was recorded. */ + accruedUsd: number | null; + collectedUsd?: number | null; + estimate?: PaygEstimate | null; + /** Unbilled accrual counted toward the $5 bubble (the counted figure). */ + unbilledUsd: number | null; + note: string; + measuredAt: string | null; + sourceClass: UsageSourceClass; +} + +/** One observed charge (§2.4 evidence — Plaid/Gmail/receipt class). */ +export interface ChargeRow { + /** ISO date the charge posted/was observed. */ + at: string; + label: string; + amountUsd: number; + /** Payment method as recorded, e.g. "Visa •7535". */ + method: string; + /** Evidence source for this row. */ + source: string; +} + +/** + * One tripped bubble rule (§1.3): a metric over 80% of its limit, or + * projected unbilled PAYG over $5 (unbilled accrual only, Q3 default). + */ +export interface AttentionFlag { + kind: "over-limit" | "payg-unbilled"; + label: string; + detail: string; + href: string; + /** Percent (over-limit) or counted dollars (payg-unbilled); worst first. */ + severity: number; +} + +/** + * One snapshot-store record (§4). Estimates are stored as a low/high + * pair with unit "usd-est"; the 1.2× rule applies at render. + */ +export interface SnapshotRecord { + /** ISO timestamp of the observation (its original date, for backfill). */ + ts: string; + serviceId: string; + metricId: string; + value: number | { low: number; high: number }; + unit: "pct" | "usd" | "count" | "gb" | "tokens" | "usd-est"; + limit?: number | null; + resetsAt?: string | null; + source: UsageSourceClass; + observedBy: string; +} + +/** The hub's family-2 + PAYG + charges model, served by Source.usage(). */ +export interface UsageView { + services: SaasService[]; + payg: PaygLine[]; + charges: ChargeRow[]; + /** Set when no charge evidence could be derived — the strip explains itself. */ + chargesNote?: string; + attention: AttentionFlag[]; + /** Domains summary from the feed's dns section (§1.4: link, don't fork). */ + domains: { totalAnnualUsd: number; nextRenewal: string | null; domainCount: number } | null; + /** Flat/renewal-only rows for the subscriptions strip (Q5 default). */ + subscriptions: { name: string; plan: string; renewsAt: string | null }[]; + /** Snapshot history per service id, from the §4 store (may be empty). */ + history: Record; +} diff --git a/pm-stack/aggregator/src/pages.ts b/pm-stack/aggregator/src/pages.ts index 700573d669..8f0f00acf5 100644 --- a/pm-stack/aggregator/src/pages.ts +++ b/pm-stack/aggregator/src/pages.ts @@ -46,10 +46,10 @@ export const PAGES: PageDef[] = [ }, { id: "quota", - title: "Quota", + title: "Usage & billing", route: "/quota", api: "/api/quota.json", - blurb: "All pooled quotas, resets, and burn rates.", + blurb: "Token quotas, PAYG dollars, and every SaaS service's usage vs its limits.", }, { id: "dns", diff --git a/pm-stack/aggregator/src/quota-extract.ts b/pm-stack/aggregator/src/quota-extract.ts index 80ca7dc0e1..dbfd68386d 100644 --- a/pm-stack/aggregator/src/quota-extract.ts +++ b/pm-stack/aggregator/src/quota-extract.ts @@ -68,7 +68,7 @@ interface Raw { type Extractor = (section: string, now: Date) => Raw | null; -function sectionOf(doc: string, headingPattern: RegExp): string { +export function sectionOf(doc: string, headingPattern: RegExp): string { const lines = doc.split("\n"); let start = -1; for (let i = 0; i < lines.length; i++) { diff --git a/pm-stack/aggregator/src/saas-extract.ts b/pm-stack/aggregator/src/saas-extract.ts new file mode 100644 index 0000000000..cbd4467e96 --- /dev/null +++ b/pm-stack/aggregator/src/saas-extract.ts @@ -0,0 +1,638 @@ +// Family-2 extractors over the stewardship quota view's Part (b) +// (hub design §2.3/§3): the sibling of quota-extract.ts, with the same +// fail-soft dated-read discipline. quota-view.md is a local-record +// snapshot — it performs no live checks — so every card here carries +// the freshest dated read it could find, and a service whose patterns +// stop matching renders as an identity shell instead of vanishing or +// inventing numbers. Manual/console reads are a first-class source +// class (§2); nothing here pretends to be a live meter. +// +// Backblaze B2, Fly.io, and Baseten are deliberately NOT services +// here: B2 is omitted until an account exists (§1.4), and Fly/Baseten +// are unheld candidates with no meter and no renewal date. +import { sectionOf } from "./quota-extract.ts"; +import type { + ChargeRow, + DatedRead, + PaygEstimate, + PaygLine, + SaasGroup, + SaasService, + UsageMetric, +} from "./model.ts"; + +const DATE_RE = /\d{4}-\d{2}-\d{2}/g; + +/** Every ISO date in a text, ascending. */ +function datesIn(text: string): string[] { + return [...text.matchAll(DATE_RE)].map((m) => m[0]).sort(); +} + +/** The freshest ISO date in a text, or null. */ +function freshestDate(text: string): string | null { + const ds = datesIn(text); + return ds.length ? ds[ds.length - 1] : null; +} + +/** A `**Label:**` bullet's body text (to the next bullet or section end). */ +function bullet(section: string, labelPattern: RegExp): string { + const lines = section.split("\n"); + let start = -1; + for (let i = 0; i < lines.length; i++) { + if (/^-\s/.test(lines[i]) && labelPattern.test(lines[i])) { + start = i; + break; + } + } + if (start < 0) return ""; + const out = [lines[start].replace(/^-\s/, "")]; + for (let i = start + 1; i < lines.length; i++) { + if (/^-\s/.test(lines[i]) || /^#{2,3} /.test(lines[i])) break; + out.push(lines[i]); + } + return out.join("\n").trim(); +} + +/** One row of the Summary (b) table, by its first cell. */ +function summaryRow(doc: string, firstCell: RegExp): string[] | null { + const summary = sectionOf(doc, /^## Summary \(b\)/); + for (const line of summary.split("\n")) { + if (!line.startsWith("|")) continue; + const cells = line.split("|").slice(1, -1).map((c) => c.trim()); + if (cells.length >= 5 && firstCell.test(cells[0])) return cells; + } + return null; +} + +/** Dated reads: lines carrying an ISO date, freshest first, trimmed. */ +function readsOf(section: string, cap = 14): DatedRead[] { + const reads: DatedRead[] = []; + for (const raw of section.split("\n")) { + const line = raw.replace(/^-\s/, "").replace(/\*\*/g, "").trim(); + const at = freshestDate(line); + if (at && line.length > 12) reads.push({ at, text: line.slice(0, 400) }); + } + return reads.sort((a, b) => b.at.localeCompare(a.at)).slice(0, cap); +} + +/** Lines that record a disagreement between sources — shown, not resolved. */ +function conflictsOf(section: string): string[] { + const out: string[] = []; + for (const raw of section.split("\n")) { + const line = raw.replace(/^-\s/, "").replace(/\*\*/g, "").trim(); + if (/conflict|discrepancy|disagree/i.test(line) && line.length > 12) out.push(line.slice(0, 400)); + } + return out; +} + +/** + * The section's PAYG estimate bullet, Decision-004 style: + * "low $X / high $Y per month; counted as used = 1.2 × high = $Z". + * Returns the estimate, or a note explaining its absence. + */ +function paygOf(section: string): { estimate: PaygEstimate | null; note?: string } { + const text = bullet(section, /\*\*PAYG estimate/); + if (!text) return { estimate: null }; + const m = /low \$(\d+(?:\.\d+)?) \/ high \$(\d+(?:\.\d+)?) per month/i.exec(text); + if (m) { + return { + estimate: { + low: Number(m[1]), + high: Number(m[2]), + period: "per month", + note: text.replace(/^\*\*PAYG estimate[^:]*:\*\*\s*/, "").slice(0, 300), + }, + }; + } + if (/not estimable from local records/i.test(text)) { + return { estimate: null, note: "not estimable from local records" }; + } + if (/not applicable/i.test(text)) { + const why = text + .replace(/^\*\*PAYG estimate[^:]*:\*\*\s*/, "") + .replace(/^not applicable\s*—\s*/i, "") + .split(".")[0]; + return { estimate: null, note: `not applicable — ${why}`.slice(0, 220) }; + } + return { estimate: null }; +} + +function metric(partial: Partial & Pick): UsageMetric { + const used = partial.used ?? null; + const limit = partial.limit ?? null; + const percent = + partial.percent ?? + (used != null && limit != null && limit > 0 ? Math.round((used / limit) * 1000) / 10 : undefined); + return { highlight: false, ...partial, used, limit, percent }; +} + +/** A number like "10M", "25B", "500k", "10" from allowance prose. */ +function scaled(num: string, suffix?: string): number { + const n = Number(num.replace(/,/g, "")); + switch ((suffix ?? "").toLowerCase()) { + case "k": + return n * 1_000; + case "m": + return n * 1_000_000; + case "b": + return n * 1_000_000_000; + default: + return n; + } +} + +const ALLOW = /([\d,.]+)\s*([kMB])?\b/; + +/** First "[suffix] " allowance figure in a text, or null. */ +function allowance(text: string, after: RegExp): number | null { + const m = after.exec(text); + if (!m) return null; + const n = ALLOW.exec(m[1] ?? ""); + return n ? scaled(n[1], n[2]) : null; +} + +// --- per-service metric extractors ---------------------------------------- + +type MetricExtractor = (section: string, doc: string) => UsageMetric[]; + +const cloudflareMetrics: MetricExtractor = (section) => { + const allowances = bullet(section, /\*\*Monthly allowances:\*\*/); + const r2 = bullet(section, /\*\*R2 \/ daily allowances/); + const usage = bullet(section, /\*\*Usage \/ pace:\*\*/); + const both = `${allowances}\n${r2}`; + const out: UsageMetric[] = []; + const r2gb = /~(\d+(?:\.\d+)?) GB/.exec(usage); + out.push( + metric({ + id: "workers-requests", + label: "Workers requests", + unit: "count", + limit: allowance(both, /Workers ([\d,.]+[kMB]?) requests/), + highlight: true, + note: "Current-cycle usage not read — billing/analytics scope is not established for the day-to-day token.", + }), + metric({ + id: "workers-cpu-ms", + label: "Workers CPU time", + unit: "ms", + limit: allowance(both, /([\d,.]+[kMB]?) CPU-ms/), + highlight: true, + }), + metric({ + id: "kv-reads", + label: "KV reads", + unit: "count", + limit: allowance(both, /KV ([\d,.]+[kMB]?) reads/), + highlight: true, + }), + metric({ + id: "kv-writes", + label: "KV writes/deletes/lists", + unit: "count", + limit: allowance(both, /([\d,.]+[kMB]?) writes\/deletes\/lists/), + highlight: true, + }), + metric({ + id: "d1-rows-read", + label: "D1 rows read", + unit: "rows", + limit: allowance(both, /D1 ([\d,.]+[kMB]?) rows read/), + highlight: true, + }), + metric({ + id: "d1-rows-written", + label: "D1 rows written", + unit: "rows", + limit: allowance(both, /([\d,.]+[kMB]?) written/), + }), + metric({ + id: "queues-ops", + label: "Queues operations", + unit: "ops", + limit: allowance(both, /Queues ([\d,.]+[kMB]?) ops/), + highlight: true, + }), + metric({ + id: "r2-storage", + label: "R2 storage", + unit: "gb", + used: r2gb ? Number(r2gb[1]) : null, + limit: allowance(both, /R2 Standard ([\d,.]+[kMB]?) GB-mo/), + highlight: true, + note: "Footprint read from the Tracker inventory; bucket inventory needs refresh.", + }), + metric({ + id: "r2-class-a", + label: "R2 Class A operations", + unit: "ops", + limit: allowance(both, /([\d,.]+[kMB]?) Class A/), + highlight: true, + }), + metric({ + id: "r2-class-b", + label: "R2 Class B operations", + unit: "ops", + limit: allowance(both, /([\d,.]+[kMB]?) Class B/), + highlight: true, + }), + metric({ + id: "workers-ai-neurons", + label: "Workers AI neurons / day", + unit: "neurons", + limit: allowance(both, /Workers AI ([\d,.]+[kMB]?) Neurons\/day/), + highlight: true, + }), + // The long tail — detail view only (§1.5). + metric({ id: "logs-events", label: "Workers logs events", unit: "count", limit: allowance(both, /logs ([\d,.]+[kMB]?),/) }), + metric({ id: "kv-storage", label: "KV storage", unit: "gb", limit: allowance(both, /([\d,.]+[kMB]?) GB; D1/) }), + metric({ id: "d1-storage", label: "D1 storage", unit: "gb", limit: allowance(both, /written, ([\d,.]+[kMB]?) GB/) }), + metric({ id: "do-requests", label: "Durable Objects requests", unit: "count", limit: allowance(both, /Durable Objects ([\d,.]+[kMB]?) requests/) }), + metric({ id: "do-duration", label: "Durable Objects duration", unit: "other", limit: allowance(both, /([\d,.]+[kMB]?) GB-s/) }), + metric({ id: "workflows-steps", label: "Workflows steps", unit: "count", limit: allowance(both, /Workflows ([\d,.]+[kMB]?) steps/) }), + metric({ id: "vectorize-queried", label: "Vectorize queried dimensions", unit: "count", limit: allowance(both, /Vectorize ([\d,.]+[kMB]?) queried/) }), + metric({ id: "vectorize-stored", label: "Vectorize stored dimensions", unit: "count", limit: allowance(both, /([\d,.]+[kMB]?) stored dimensions/) }), + metric({ id: "containers-memory", label: "Containers memory", unit: "hours", limit: allowance(both, /Containers ([\d,.]+[kMB]?) GiB-hours/) }), + metric({ id: "containers-vcpu", label: "Containers vCPU-minutes", unit: "minutes", limit: allowance(both, /([\d,.]+[kMB]?) vCPU-min/) }), + metric({ id: "containers-disk", label: "Containers disk", unit: "hours", limit: allowance(both, /([\d,.]+[kMB]?) GB-hours disk/) }), + ); + const counts = /(\d+) Workers, (\d+) R2 buckets[^;]*; (\d+) D1, (\d+) KV, (\d+) Queues/.exec(usage); + if (counts) { + out.push( + metric({ id: "workers-count", label: "Workers deployed", unit: "count", used: Number(counts[1]) }), + metric({ id: "r2-buckets", label: "R2 buckets", unit: "count", used: Number(counts[2]) }), + metric({ id: "d1-count", label: "D1 databases", unit: "count", used: Number(counts[3]) }), + metric({ id: "kv-count", label: "KV namespaces", unit: "count", used: Number(counts[4]) }), + metric({ id: "queues-count", label: "Queues", unit: "count", used: Number(counts[5]) }), + ); + } + return out.filter((m) => m.used != null || m.limit != null); +}; + +const tursoMetrics: MetricExtractor = (section) => { + const plan = bullet(section, /\*\*Plan \/ price \/ allowance:\*\*/); + const usage = bullet(section, /\*\*Usage \/ dates:\*\*/); + const db = /(\d+) DB/.exec(usage); + const zero = /0 B, 0 usage/.test(usage); + return [ + metric({ id: "databases", label: "Databases", unit: "count", used: db ? Number(db[1]) : null, limit: allowance(plan, /(100) DBs/), highlight: true }), + metric({ id: "storage", label: "Storage", unit: "gb", used: zero ? 0 : null, limit: allowance(plan, /([\d,.]+) GB storage/), highlight: true, note: zero ? "0 B at the 2026-10-20 dashboard read; later mirror activity is not an org-wide meter." : undefined }), + metric({ id: "rows-read", label: "Rows read / month", unit: "rows", limit: allowance(plan, /([\d,.]+[kMB]?) reads\/month/), highlight: true }), + metric({ id: "rows-written", label: "Rows written / month", unit: "rows", limit: allowance(plan, /([\d,.]+[kMB]?) writes\/month/), highlight: true }), + metric({ id: "sync", label: "Sync / month", unit: "gb", limit: allowance(plan, /([\d,.]+) GB syncs\/month/), highlight: true }), + ].filter((m) => m.used != null || m.limit != null); +}; + +const supabaseMetrics: MetricExtractor = () => [ + metric({ id: "db-size", label: "Database size", unit: "gb", highlight: true, note: "Free-plan numerical limits are not recorded in local records; account meters are not verified from this host." }), + metric({ id: "egress", label: "Egress", unit: "gb", highlight: true, note: "Not measured — manual dashboard read needed." }), + metric({ id: "storage", label: "Storage", unit: "gb", highlight: true, note: "Not measured — manual dashboard read needed." }), +]; + +const githubMetrics: MetricExtractor = (section) => { + const plan = bullet(section, /\*\*Plan \/ price \/ allowance:\*\*/); + const usage = bullet(section, /\*\*Usage \/ dates:\*\*/); + const comped = /(\d[\d,]*) Linux \+ (\d+) macOS minutes/.exec(usage); + const out: UsageMetric[] = [ + metric({ + id: "actions-billable-minutes", + label: "Actions billable minutes", + unit: "minutes", + limit: allowance(plan, /([\d,.]+) Actions minutes\/month/), + highlight: true, + note: "No billable-minute volume outside the included/comped bucket is recorded; billing API needs a billing-scoped token (§2.2).", + }), + metric({ id: "codespaces-hours", label: "Codespaces core-hours", unit: "hours", limit: allowance(plan, /([\d,.]+) Codespaces core-hours/), highlight: true }), + metric({ id: "codespaces-storage", label: "Codespaces storage", unit: "gb", limit: allowance(plan, /([\d,.]+) GB storage\/month/), highlight: true, note: "Usage unknown in local records." }), + metric({ id: "packages", label: "Packages storage", unit: "gb", limit: allowance(plan, /([\d,.]+) GB Packages/), highlight: true }), + ]; + if (comped) { + out.push( + metric({ + id: "actions-comped-minutes", + label: "Actions minutes (comped, October)", + unit: "minutes", + used: Number(comped[1].replace(/,/g, "")) + Number(comped[2]), + note: "Fully comped/discounted — net $0; comped minutes do not consume the plan allowance.", + }), + ); + } + return out.filter((m) => m.used != null || m.limit != null || m.id === "actions-billable-minutes"); +}; + +const modalMetrics: MetricExtractor = (section) => { + const plan = bullet(section, /\*\*Plan \/ price \/ allowance:\*\*/); + const credits = /\$(\d+(?:\.\d+)?) monthly compute-credit/.exec(plan); + return [ + metric({ + id: "compute-credits", + label: "Compute credits / month", + unit: "usd", + limit: credits ? Number(credits[1]) : 30, + highlight: true, + note: "No run hours or credit balance recorded — manual dashboard read (§2.2).", + }), + ]; +}; + +const ociMetrics: MetricExtractor = (section) => { + const plan = bullet(section, /\*\*Plan \/ price \/ allowance:\*\*/); + return [ + metric({ id: "ocpu-hours", label: "A1 OCPU-hours / month", unit: "hours", limit: allowance(plan, /([\d,.]+) OCPU-hours/) }), + metric({ id: "gb-hours", label: "A1 GB-hours / month", unit: "hours", limit: allowance(plan, /([\d,.]+) GB-hours\/month/) }), + metric({ id: "block-storage", label: "Block storage", unit: "gb", limit: allowance(plan, /([\d,.]+) GB block/) }), + metric({ id: "egress", label: "Egress / month", unit: "gb", limit: allowance(plan, /([\d,.]+) TB egress/) ? allowance(plan, /([\d,.]+) TB egress/)! * 1000 : null }), + metric({ id: "object-storage", label: "Object storage", unit: "gb", limit: allowance(plan, /([\d,.]+) GB object storage/) }), + ].filter((m) => m.limit != null); +}; + +// --- service table ---------------------------------------------------------- + +interface ServiceSpec { + id: string; + name: string; + group: SaasGroup; + heading: RegExp; + summaryKey: RegExp; + status: SaasService["status"]; + cadenceDays: number; + metrics: MetricExtractor; + shellNote: string; +} + +const SERVICE_SPECS: ServiceSpec[] = [ + { + id: "cloudflare", + name: "Cloudflare", + group: "compute", + heading: /^### Cloudflare — Workers platform/, + summaryKey: /^Cloudflare platform/, + status: "active", + cadenceDays: 7, + metrics: cloudflareMetrics, + shellNote: "Workers Paid platform; no current read extracted.", + }, + { + id: "turso", + name: "Turso", + group: "database", + heading: /^### Turso$/, + summaryKey: /^Turso/, + status: "active", + cadenceDays: 7, + metrics: tursoMetrics, + shellNote: "Starter Free; no current read extracted.", + }, + { + id: "supabase", + name: "Supabase", + group: "database", + heading: /^### Supabase$/, + summaryKey: /^Supabase/, + status: "active", + cadenceDays: 7, + metrics: supabaseMetrics, + shellNote: "Free plan (muse-dev); numerical quotas unknown in local records.", + }, + { + id: "github", + name: "GitHub", + group: "dev-platform", + heading: /^### GitHub$/, + summaryKey: /^GitHub/, + status: "active", + cadenceDays: 7, + metrics: githubMetrics, + shellNote: "Pro $4/mo; no current read extracted.", + }, + { + id: "vercel", + name: "Vercel", + group: "compute", + heading: /^### Vercel$/, + summaryKey: /^Vercel/, + status: "unknown", + cadenceDays: 7, + metrics: () => [], + shellNote: "In use for web deploys; tier, price and caps unknown — the first read establishes the baseline (§2.2).", + }, + { + id: "modal", + name: "Modal", + group: "compute", + heading: /^### Modal$/, + summaryKey: /^Modal/, + status: "active", + cadenceDays: 31, + metrics: modalMetrics, + shellNote: "Starter $0/mo with $30/mo compute credits; usage unknown.", + }, + { + id: "oci", + name: "OCI Always Free", + group: "compute", + heading: /^### OCI Always Free$/, + summaryKey: /^OCI/, + status: "no-account", + cadenceDays: 31, + metrics: ociMetrics, + shellNote: "No account — signup blocked; placeholder card (§1.4).", + }, + { + id: "bitwarden", + name: "Bitwarden Secrets Manager", + group: "account-tooling", + heading: /^### Bitwarden$/, + summaryKey: /^Bitwarden/, + status: "active", + cadenceDays: 7, + metrics: () => [], + shellNote: "Counts only in this hub — secret names/values never enter it. No count recorded yet; plan/price unknown.", + }, +]; + +/** Extract every family-2 service from quota-view.md Part (b). */ +export function extractSaasServices(doc: string): SaasService[] { + const services: SaasService[] = []; + for (const spec of SERVICE_SPECS) { + const section = sectionOf(doc, spec.heading); + const row = summaryRow(doc, spec.summaryKey); + const planCell = row?.[1] ?? ""; + const shell: SaasService = { + id: spec.id, + name: spec.name, + group: spec.group, + plan: planCell || spec.shellNote, + status: spec.status, + metrics: [], + paygEstimate: null, + measuredAt: null, + sourceClass: "manual", + sourceNote: "quota-view.md Part (b) — local-record snapshot; no live checks performed", + nextDate: row?.[4] && row[4] !== "unknown" ? row[4] : null, + cadenceDays: spec.cadenceDays, + conflicts: [], + reads: [], + usageNote: spec.shellNote, + }; + if (!section) { + services.push(shell); + continue; + } + try { + const payg = paygOf(section); + const usageText = bullet(section, /\*\*Usage \/ dates:\*\*/).replace(/^\*\*Usage \/ dates:\*\*\s*/, ""); + services.push({ + ...shell, + metrics: spec.metrics(section, doc), + paygEstimate: payg.estimate, + paygNote: payg.note, + measuredAt: freshestDate(section), + conflicts: conflictsOf(section), + reads: readsOf(section), + usageNote: usageText ? usageText.slice(0, 600) : spec.shellNote, + billedUsd: spec.id === "supabase" ? 0 : undefined, + }); + } catch { + services.push(shell); + } + } + // The Cloudflare zone is part of the one Cloudflare card (Q6): fold + // its dated reads + conflict lines into the platform service. + const cf = services.find((s) => s.id === "cloudflare"); + const zone = sectionOf(doc, /^### Cloudflare — zone/); + if (cf && zone) { + cf.reads = [...readsOf(zone), ...cf.reads].sort((a, b) => b.at.localeCompare(a.at)).slice(0, 14); + cf.conflicts = [...conflictsOf(zone), ...cf.conflicts]; + const zoneDate = freshestDate(zone); + if (zoneDate && (!cf.measuredAt || zoneDate > cf.measuredAt)) cf.measuredAt = zoneDate; + } + return services; +} + +// --- PAYG lines (§1.2) ------------------------------------------------------- + +/** + * The PAYG dollars card's lines. Sources: the Meta Model API section of + * quota-view.md (console figures) and, when supplied, the provider + * registry's billing-incidents section (the Cloudflare gateway accrual + * the two sources price differently — shown, not resolved). + */ +export function extractPaygLines(doc: string, registryText = ""): PaygLine[] { + const lines: PaygLine[] = []; + const meta = sectionOf(doc, /^### Meta Model API/); + const payg = /PAYG Oct 19–25: \$(\d+(?:\.\d+)?) accrued \/ \$(\d+(?:\.\d+)?) collected/.exec(meta); + if (payg) { + const accrued = Number(payg[1]); + const collected = Number(payg[2]); + lines.push({ + id: "meta-payg", + label: "Meta Model API PAYG", + accruedUsd: accrued, + collectedUsd: collected, + unbilledUsd: Math.round((accrued - collected) * 100) / 100, + note: "Oct 19–25 console read (dev.meta.ai, 2026-10-25 09:38 CDT): spill past the plan's short window bills automatically — no charge-past-plan disable exists on the account.", + measuredAt: "2026-10-25", + sourceClass: "console", + }); + } + const gw = /\$(\d+(?:\.\d+)?) per budget alert vs \$(\d+(?:\.\d+)?) per gateway cost attribution/.exec(registryText); + if (gw) { + lines.push({ + id: "cloudflare-gateway", + label: "Cloudflare AI Gateway accrual (DeepSeek V4 Pro, Oct 24–25)", + accruedUsd: null, + estimate: { + low: Number(gw[1]), + high: Number(gw[2]), + period: "Oct 24–25 accrual", + note: "Budget alert vs gateway cost attribution disagree — both shown; the Nov 2 invoice is authoritative.", + }, + unbilledUsd: Math.round(Number(gw[2]) * 1.2 * 100) / 100, + note: "Gateway providers were disabled fleet-wide 2026-10-25; accrual is closed, the invoice lands Nov 2.", + measuredAt: "2026-10-25", + sourceClass: "estimate", + }); + } + const cf = extractSaasServices(doc).find((s) => s.id === "cloudflare"); + if (cf?.paygEstimate) { + lines.push({ + id: "cloudflare-platform-excess", + label: "Cloudflare platform metered excess (estimate)", + accruedUsd: null, + estimate: cf.paygEstimate, + unbilledUsd: Math.round(cf.paygEstimate.high * 1.2 * 100) / 100, + note: "Estimate at the recorded footprint, excluding the $5/mo base (counted as subscription). Every meter sits inside its included allotment in the underlying read, so the low is $0.", + measuredAt: cf.measuredAt, + sourceClass: "estimate", + }); + } + return lines; +} + +// --- Charges evidence (§2.4) -------------------------------------------------- + +/** + * Charges observed in the local records (card alerts + receipt-class + * evidence preserved in quota-view.md and the registry). Evidence, not + * accounting: each row names its source. Empty = the strip explains + * itself rather than showing a bare zero. + */ +export function extractCharges(doc: string, registryText = ""): ChargeRow[] { + const rows: ChargeRow[] = []; + const both = `${doc}\n${registryText}`; + const visa = /Visa\s*(?:•\s*)?(\d{4})/.exec(both); + const method = visa ? `Visa •${visa[1]}` : "card"; + const metaCharges = /\$(\d+(?:\.\d+)?) charged(?:[^$]*)\+ \$(\d+(?:\.\d+)?) charged/.exec(both) ?? + /\$(\d+(?:\.\d+)?) at 05:15 CDT \+ \$(\d+(?:\.\d+)?) at 07:47 CDT/.exec(both); + if (metaCharges) { + rows.push( + { at: "2026-10-25", label: "Meta PAYG spill", amountUsd: Number(metaCharges[1]), method, source: "Gmail card alert (registry billing incidents)" }, + { at: "2026-10-25", label: "Meta PAYG spill", amountUsd: Number(metaCharges[2]), method, source: "Gmail card alert (registry billing incidents)" }, + ); + } + const cline = sectionOf(doc, /^### ClinePass/); + const clineCharge = /Cline Bot Inc\., \*\*\$(\d+(?:\.\d+)?)\*\* via Link, invoice (\S+)/.exec(cline); + if (clineCharge) { + rows.push({ + at: "2026-10-05", + label: "ClinePass annual (Cline Bot Inc.)", + amountUsd: Number(clineCharge[1]), + method: "Link", + source: `invoice ${clineCharge[2]} (quota-view.md ClinePass read)`, + }); + } + const chatgpt = sectionOf(doc, /^### ChatGPT — main/); + const mystery = /Unexplained \$(\d+(?:\.\d+)?) Discover charge dated (\d{4}-\d{2}-\d{2})/.exec(chatgpt); + if (mystery) { + rows.push({ + at: mystery[2], + label: "Unconfirmed charge (not confirmed API spending)", + amountUsd: Number(mystery[1]), + method: "Discover", + source: "quota-view.md ChatGPT read", + }); + } + return rows.sort((a, b) => b.at.localeCompare(a.at)); +} + +// --- Subscriptions strip (Q5: renewal-only rows) ------------------------------ + +/** Flat subscriptions with no meter: plan + next renewal only (§1.4). */ +export function extractSubscriptions(doc: string): { name: string; plan: string; renewsAt: string | null }[] { + const out: { name: string; plan: string; renewsAt: string | null }[] = []; + const flat = sectionOf(doc, /^### Other \/ flat/); + if (/Amazon RxPass/.test(flat)) { + out.push({ name: "Amazon RxPass", plan: "$5/mo flat pharmacy", renewsAt: null }); + } + const wispr = sectionOf(doc, /^### Wispr Flow/); + if (wispr) { + const price = /Flow Pro annual \$(\d+(?:\.\d+)?)\/yr/.exec(wispr); + const renews = /renews (\d{4}-\d{2}-\d{2})/.exec(wispr); + out.push({ + name: "Wispr Flow", + plan: price ? `Pro $${price[1]}/yr` : "Pro (annual)", + renewsAt: renews ? renews[1] : null, + }); + } + return out; +} diff --git a/pm-stack/aggregator/src/snapshots.ts b/pm-stack/aggregator/src/snapshots.ts new file mode 100644 index 0000000000..cfafd8a488 --- /dev/null +++ b/pm-stack/aggregator/src/snapshots.ts @@ -0,0 +1,116 @@ +// The usage snapshot store (hub design §4): append-only history for +// usage metrics, one JSONL file per month (`usage-YYYY-MM.jsonl`) in a +// durable directory beside the comments/registry stores. Writers are +// the owning jobs (fleet-feed collector, stewardship-cycle, the Jules +// keeper) and the one-shot backfill script; the aggregator only reads. +// +// Records keep their original observation timestamp and source class — +// backfilled prose observations stay dated 2026-10-20 even when the +// backfill runs later. Estimates are stored as a low/high pair with +// unit "usd-est"; the 1.2×high counting rule applies at render, never +// baked into history. +import { appendFile, mkdir, readdir, readFile } from "node:fs/promises"; +import { join } from "node:path"; +import type { SnapshotRecord, UsageSourceClass } from "./model.ts"; + +const SOURCES: ReadonlySet = new Set(["api", "console", "manual", "estimate", "invoice"]); +const UNITS: ReadonlySet = new Set(["pct", "usd", "count", "gb", "tokens", "usd-est"]); +const FILE_RE = /^usage-(\d{4}-\d{2})\.jsonl$/; + +/** The monthly file a record belongs in, by its own timestamp. */ +export function snapshotFileFor(ts: string): string { + return `usage-${ts.slice(0, 7)}.jsonl`; +} + +/** Structural validation for one untrusted record (store reads, writer input). */ +export function isSnapshotRecord(v: unknown): v is SnapshotRecord { + if (typeof v !== "object" || v === null) return false; + const r = v as Partial; + if (typeof r.ts !== "string" || Number.isNaN(Date.parse(r.ts))) return false; + if (typeof r.serviceId !== "string" || r.serviceId === "") return false; + if (typeof r.metricId !== "string" || r.metricId === "") return false; + if (typeof r.unit !== "string" || !UNITS.has(r.unit)) return false; + if (typeof r.source !== "string" || !SOURCES.has(r.source)) return false; + if (typeof r.observedBy !== "string" || r.observedBy === "") return false; + if (typeof r.value === "number") return Number.isFinite(r.value); + if (typeof r.value === "object" && r.value !== null) { + const p = r.value as { low?: unknown; high?: unknown }; + return typeof p.low === "number" && typeof p.high === "number"; + } + return false; +} + +/** Dedupe key: same service, metric, instant, and value = same observation. */ +export function snapshotKey(r: SnapshotRecord): string { + const v = typeof r.value === "number" ? String(r.value) : `${r.value.low}/${r.value.high}`; + return `${r.serviceId}|${r.metricId}|${r.ts}|${v}`; +} + +export class SnapshotStore { + constructor(private readonly dir: string) {} + + /** Every valid record in the store, oldest first. Malformed lines are skipped. */ + async readAll(): Promise { + let names: string[]; + try { + names = (await readdir(this.dir)).filter((n) => FILE_RE.test(n)).sort(); + } catch { + return []; // no store yet — history simply has not started + } + const out: SnapshotRecord[] = []; + for (const name of names) { + let text: string; + try { + text = await readFile(join(this.dir, name), "utf8"); + } catch { + continue; + } + for (const line of text.split("\n")) { + if (!line.trim()) continue; + try { + const parsed: unknown = JSON.parse(line); + if (isSnapshotRecord(parsed)) out.push(parsed); + } catch { + // one bad line never poisons the store + } + } + } + return out.sort((a, b) => a.ts.localeCompare(b.ts)); + } + + /** History grouped by service id, oldest first per service. */ + async byService(): Promise> { + const grouped: Record = {}; + for (const r of await this.readAll()) { + (grouped[r.serviceId] ??= []).push(r); + } + return grouped; + } + + /** + * Append records, skipping any already present (same dedupe key), so + * writers and the backfill are safe to re-run. Returns how many were + * actually appended. Records land in their own month's file. + */ + async append(records: SnapshotRecord[]): Promise { + const valid = records.filter(isSnapshotRecord); + if (!valid.length) return 0; + const seen = new Set((await this.readAll()).map(snapshotKey)); + const fresh = valid.filter((r) => !seen.has(snapshotKey(r))); + if (!fresh.length) return 0; + await mkdir(this.dir, { recursive: true }); + const byFile = new Map(); + for (const r of fresh) { + const f = snapshotFileFor(r.ts); + byFile.set(f, [...(byFile.get(f) ?? []), r]); + } + for (const [file, rows] of byFile) { + const lines = rows.map((r) => JSON.stringify(r)).join("\n") + "\n"; + await appendFile(join(this.dir, file), lines, "utf8"); + } + return fresh.length; + } +} + +/** Source classes the store accepts, for writer-side validation messages. */ +export const SNAPSHOT_SOURCES: readonly UsageSourceClass[] = ["api", "console", "manual", "estimate", "invoice"]; diff --git a/pm-stack/aggregator/src/source.ts b/pm-stack/aggregator/src/source.ts index af2a25b848..cd0e5b7f3a 100644 --- a/pm-stack/aggregator/src/source.ts +++ b/pm-stack/aggregator/src/source.ts @@ -10,6 +10,7 @@ import type { Provenance, QuotaView, RefKey, + UsageView, RoadmapRow, SessionFeedEntry, SessionRecord, @@ -27,6 +28,9 @@ export interface Source { comments(refs: RefKey[]): Promise; /** Quota + throughput view (#851). */ quota(): Promise; + /** Usage & billing hub view: family-2 SaaS services, PAYG lines, + * charges evidence, bubble flags, and snapshot history (hub §3). */ + usage(): Promise; /** Raw session feed for the "needs you" view (#852), pre-classification. */ attention(): Promise; /** The orchestration job's latest section (#899); null = not measured yet. */ diff --git a/pm-stack/aggregator/src/sources/fixtures.ts b/pm-stack/aggregator/src/sources/fixtures.ts index 6729d2ce28..1893a0a0bd 100644 --- a/pm-stack/aggregator/src/sources/fixtures.ts +++ b/pm-stack/aggregator/src/sources/fixtures.ts @@ -19,9 +19,11 @@ import { type SessionFeedEntry, type SessionRecord, type SourceCoverage, + type UsageView, refsInText, refUrl, } from "../model.ts"; +import { buildAttentionFlags } from "../derive.ts"; import { recordFromSessionEntry } from "../registry.ts"; import type { Source } from "../source.ts"; @@ -643,6 +645,171 @@ export const FIXTURE_REGISTRY: SessionRecord[] = [ }, ]; + +// Usage & billing hub fixtures (design 2026-10-25). Shaped exactly like +// the live extraction over quota-view.md Part (b): dated manual reads, +// one service tripping the >80% bubble (Turso rows read), one PAYG +// estimate pair, charges evidence, and a short snapshot history so the +// detail view's chart + pace projection render offline. +const daysAgo = (d: number): string => new Date(Date.now() - d * 86_400_000).toISOString().slice(0, 10); +export const FIXTURE_USAGE: UsageView = { + services: [ + { + id: "cloudflare", + name: "Cloudflare", + group: "compute", + plan: "Workers Paid $5/mo + R2 Paid $0 base", + status: "active", + metrics: [ + { id: "workers-requests", label: "Workers requests", used: null, limit: 10_000_000, unit: "count", highlight: true, note: "Current-cycle usage not read." }, + { id: "r2-storage", label: "R2 storage", used: 2, limit: 10, unit: "gb", percent: 20, highlight: true }, + { id: "workers-ai-neurons", label: "Workers AI neurons / day", used: null, limit: 10_000, unit: "neurons", highlight: true }, + ], + paygEstimate: { low: 0, high: 5.2, period: "per month" }, + measuredAt: daysAgo(1), + sourceClass: "manual", + sourceNote: "quota-view.md Part (b) — local-record snapshot; no live checks performed", + nextDate: "Subscription date unknown", + cadenceDays: 7, + conflicts: ["CF reports subscription endpoint 403 and presumed $0/free; the Tracker records Workers Paid $5/mo — neither establishes current free status."], + reads: [{ at: daysAgo(1), text: "Gateway observation: gateway barely gets any credits; amount unknown." }], + usageNote: "Small footprint: 3 Workers, 2 R2 buckets ~2 GB, 2 D1, 2 KV, 2 Queues; far behind, mostly unused.", + }, + { + id: "turso", + name: "Turso", + group: "database", + plan: "Starter Free $0", + status: "active", + metrics: [ + { id: "databases", label: "Databases", used: 1, limit: 100, unit: "count", percent: 1, highlight: true }, + { id: "storage", label: "Storage", used: 0, limit: 5, unit: "gb", percent: 0, highlight: true }, + { id: "rows-read", label: "Rows read / month", used: 410_000_000, limit: 500_000_000, unit: "rows", percent: 82, highlight: true }, + { id: "rows-written", label: "Rows written / month", used: null, limit: 10_000_000, unit: "rows", highlight: true }, + { id: "sync", label: "Sync / month", used: null, limit: 3, unit: "gb", highlight: true }, + ], + paygEstimate: null, + paygNote: "not applicable — Starter Free is a $0 hard-capped plan with overages disabled", + measuredAt: daysAgo(2), + sourceClass: "manual", + sourceNote: "quota-view.md Part (b) — local-record snapshot; no live checks performed", + nextDate: "2026-10-31 cycle end", + cadenceDays: 7, + conflicts: [], + reads: [{ at: daysAgo(6), text: "2026-10-20 dashboard read: 1 DB, 0 B, 0 usage; cycle Sep 30 - Oct 31 2026." }], + usageNote: "Mirror activity since the zero read; org-wide reads require dashboard/API verification.", + }, + { + id: "supabase", + name: "Supabase", + group: "database", + plan: "Free", + status: "active", + metrics: [ + { id: "db-size", label: "Database size", used: null, limit: null, unit: "gb", highlight: true, note: "Free-plan numerical limits are not recorded in local records." }, + { id: "egress", label: "Egress", used: null, limit: null, unit: "gb", highlight: true }, + { id: "storage", label: "Storage", used: null, limit: null, unit: "gb", highlight: true }, + ], + paygEstimate: null, + paygNote: "not applicable — Free plan, no metered overage in the records", + billedUsd: 0, + measuredAt: daysAgo(3), + sourceClass: "manual", + sourceNote: "quota-view.md Part (b) — local-record snapshot; no live checks performed", + nextDate: null, + cadenceDays: 7, + conflicts: [], + reads: [], + usageNote: "muse-dev in use as the primary coordination store; usage percentage unknown.", + }, + { + id: "github", + name: "GitHub", + group: "dev-platform", + plan: "Pro $4/mo", + status: "active", + metrics: [ + { id: "actions-billable-minutes", label: "Actions billable minutes", used: null, limit: 3000, unit: "minutes", highlight: true, note: "No billable volume outside the comped bucket is recorded." }, + { id: "actions-comped-minutes", label: "Actions minutes (comped, October)", used: 3079, limit: null, unit: "minutes", highlight: false, note: "Fully comped — net $0." }, + { id: "codespaces-hours", label: "Codespaces core-hours", used: null, limit: 180, unit: "hours", highlight: true }, + { id: "packages", label: "Packages storage", used: null, limit: 2, unit: "gb", highlight: true }, + ], + paygEstimate: null, + paygNote: "not applicable — recorded October overage was comped ($0 net)", + measuredAt: daysAgo(1), + sourceClass: "manual", + sourceNote: "quota-view.md Part (b) — local-record snapshot; no live checks performed", + nextDate: null, + cadenceDays: 7, + conflicts: [], + reads: [], + usageNote: "October minutes comped; Codespaces/Packages usage unknown.", + }, + { + id: "bitwarden", + name: "Bitwarden Secrets Manager", + group: "account-tooling", + plan: "Secrets Manager, tier/price unknown", + status: "active", + metrics: [], + paygEstimate: null, + paygNote: "not applicable — no usage meter recorded", + measuredAt: daysAgo(2), + sourceClass: "manual", + sourceNote: "quota-view.md Part (b) — local-record snapshot; no live checks performed", + nextDate: null, + cadenceDays: 7, + conflicts: [], + reads: [], + usageNote: "Counts only in this hub — secret names/values never enter it. No count recorded yet.", + }, + ], + payg: [ + { + id: "meta-payg", + label: "Meta Model API PAYG", + accruedUsd: 23.92, + collectedUsd: 23.91, + unbilledUsd: 0.01, + note: "Oct 19-25 console read: spill past the plan's short window bills automatically.", + measuredAt: daysAgo(1), + sourceClass: "console", + }, + { + id: "cloudflare-gateway", + label: "Cloudflare AI Gateway accrual (DeepSeek V4 Pro, Oct 24-25)", + accruedUsd: null, + estimate: { low: 29.6, high: 45.1, period: "Oct 24-25 accrual", note: "Budget alert vs gateway attribution disagree; Nov 2 invoice is authoritative." }, + unbilledUsd: 54.12, + note: "Gateway providers disabled fleet-wide 2026-10-25; the invoice lands Nov 2.", + measuredAt: daysAgo(1), + sourceClass: "estimate", + }, + ], + charges: [ + { at: daysAgo(1), label: "Meta PAYG spill", amountUsd: 20, method: "Visa \u20227535", source: "Gmail card alert (registry billing incidents)" }, + { at: daysAgo(1), label: "Meta PAYG spill", amountUsd: 3.91, method: "Visa \u20227535", source: "Gmail card alert (registry billing incidents)" }, + { at: "2026-10-05", label: "ClinePass annual (Cline Bot Inc.)", amountUsd: 82.52, method: "Link", source: "invoice QUWGLQSJ-0001 (quota-view.md ClinePass read)" }, + ], + attention: [], + domains: { totalAnnualUsd: 214.5, nextRenewal: "2026-11-03", domainCount: 14 }, + subscriptions: [ + { name: "Amazon RxPass", plan: "$5/mo flat pharmacy", renewsAt: null }, + { name: "Wispr Flow", plan: "Pro $151.91/yr", renewsAt: "2027-10-09" }, + ], + history: { + turso: [ + { ts: `${daysAgo(6)}T12:00:00Z`, serviceId: "turso", metricId: "rows-read-pct", value: 12, unit: "pct", limit: 100, resetsAt: "2026-10-31T00:00:00Z", source: "manual", observedBy: "fixtures" }, + { ts: `${daysAgo(4)}T12:00:00Z`, serviceId: "turso", metricId: "rows-read-pct", value: 38, unit: "pct", limit: 100, resetsAt: "2026-10-31T00:00:00Z", source: "manual", observedBy: "fixtures" }, + { ts: `${daysAgo(2)}T12:00:00Z`, serviceId: "turso", metricId: "rows-read-pct", value: 82, unit: "pct", limit: 100, resetsAt: "2026-10-31T00:00:00Z", source: "manual", observedBy: "fixtures" }, + ], + cloudflare: [ + { ts: `${daysAgo(6)}T12:00:00Z`, serviceId: "cloudflare", metricId: "r2-storage", value: 1.8, unit: "gb", limit: 10, source: "manual", observedBy: "fixtures" }, + { ts: `${daysAgo(1)}T12:00:00Z`, serviceId: "cloudflare", metricId: "r2-storage", value: 2, unit: "gb", limit: 10, source: "manual", observedBy: "fixtures" }, + ], + }, +}; + export function fixtureSource(): Source { const items = new Map(FIXTURE_ITEMS.map((i) => [i.ref, i])); const provenance: Provenance = { @@ -651,6 +818,7 @@ export function fixtureSource(): Source { items: "fixtures", comments: "fixtures", quota: "fixtures", + usage: "fixtures", attention: "fixtures", orchestration: "fixtures", dns: "fixtures", @@ -665,6 +833,7 @@ export function fixtureSource(): Source { return FIXTURE_COMMENTS.filter((x) => wanted.has(x.ref)); }, quota: async () => FIXTURE_QUOTA, + usage: async () => ({ ...FIXTURE_USAGE, attention: buildAttentionFlags(FIXTURE_QUOTA, FIXTURE_USAGE) }), attention: async () => FIXTURE_ATTENTION, // Fixtures carry no orchestration section: "not measured" is the // honest fixture state for a job that only runs live (#899). diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index cac2d90e4f..a630dff290 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -9,6 +9,10 @@ import type { Config } from "../config.ts"; import { isDnsSection } from "../dns.ts"; import { feedAgeText, isOrchestrationSection, loadFeed, type FleetFeed } from "../feed.ts"; 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 { SnapshotStore } from "../snapshots.ts"; import { fixtureSource } from "./fixtures.ts"; import { mapServerSessions, type MappedSessions } from "./opencode.ts"; import { @@ -25,6 +29,7 @@ import { type SessionFeedEntry, type SessionRecord, type SourceCoverage, + type UsageView, refsInText, refUrl, } from "../model.ts"; @@ -342,6 +347,7 @@ export function liveSource(cfg: Config): Source { items: "fixtures", comments: "fixtures", quota: "fixtures", + usage: "fixtures", attention: "fixtures", orchestration: "fixtures", dns: "fixtures", @@ -512,6 +518,68 @@ export function liveSource(cfg: Config): Source { provenance.quota = "fixtures (no fleet feed file yet)"; return fix.quota(); }, + async usage(): Promise { + // Usage & billing hub (design §3): feed sections first (the + // collector extracts Part (b) on the sandbox, where the sources + // of record live); when an older feed has none, extract directly + // from the quota view + registry files; fixtures only when + // neither exists. Snapshot history always comes from the local + // store (§4) — the aggregator reads it, writers live elsewhere. + const feed = await getFeed(); + const history = await new SnapshotStore(cfg.snapshotsDir).byService().catch(() => ({})); + const domains = + feed?.dns && isDnsSection(feed.dns) + ? { + totalAnnualUsd: feed.dns.totalAnnualListUsd, + nextRenewal: summarizeDns(feed.dns).nextRenewal?.renewal ?? null, + domainCount: feed.dns.entries.length, + } + : null; + if (feed?.saas && feed.saas.length) { + provenance.usage = `live (fleet feed · ${feedAgeText(feed.generatedAt)} · collected ${feed.generatedAt})`; + const partial = { + services: feed.saas, + payg: feed.payg ?? [], + charges: feed.charges ?? [], + subscriptions: feed.subscriptions ?? [], + }; + return { + ...partial, + chargesNote: partial.charges.length + ? undefined + : "No charge evidence in the feed's records yet — rows appear as Plaid/Gmail receipt evidence is recorded (§2.4).", + attention: buildAttentionFlags(feed.quota, partial), + domains, + history, + }; + } + try { + const [doc, registryText] = await Promise.all([ + readFile(cfg.quotaViewFile, "utf8"), + readFile(cfg.quotaRegistryFile, "utf8").catch(() => ""), + ]); + const partial = { + services: extractSaasServices(doc), + payg: extractPaygLines(doc, registryText), + charges: extractCharges(doc, registryText), + subscriptions: extractSubscriptions(doc), + }; + provenance.usage = "live (quota-view.md + provider registry, direct read — feed carries no hub sections yet)"; + return { + ...partial, + chargesNote: partial.charges.length + ? undefined + : "No charge evidence in the local records yet — rows appear as Plaid/Gmail receipt evidence is recorded (§2.4).", + attention: buildAttentionFlags(feed?.quota ?? (await fix.quota()), partial), + domains, + history, + }; + } catch { + provenance.usage = "fixtures (no fleet feed hub sections and quota view unreadable)"; + const fallback = await fix.usage(); + return { ...fallback, history: Object.keys(history).length ? history : fallback.history }; + } + }, async attention() { // Slice 1 (#890): laptop sessions live from the OpenChamber- // managed OpenCode server (45 s cache); sandbox sessions from From 74fb95fffa6aced2fbfc17242660f3f2b8e8dec4 Mon Sep 17 00:00:00 2001 From: Archer Date: Mon, 26 Oct 2026 13:11:05 +0000 Subject: [PATCH 2/3] feat(aggregator): usage & billing hub page + service detail views MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /quota becomes the hub (design §1.1): needs-attention strip (bubble rules across both families), token-quota pool cards as before, the PAYG dollars card (counted figures per Decision 004, ranges on the detail view), family-2 SaaS cards grouped per §1.4 with highlight metrics only, domains summary card linking /dns (never forking the register), the renewal-only subscriptions strip, and the charges evidence strip. Every card carries a measured-at + source stamp; cards past their cadence dim with a stale badge. Conflicts render as a marker linking to the dated history on the detail page. v1.1 (§1.5): /quota/service/ + /api/quota/service.json?id= — full metric list (incl. the Cloudflare long tail), snapshot history charts with reset markers, pace projections where history supports them, all dated source reads, and recorded conflicts. /api/quota.json gains saas/payg/charges/attention/domains/ subscriptions keys; pools/burn/choices are unchanged. --- pm-stack/aggregator/src/render.ts | 275 +++++++++++++++++++++++++++++- pm-stack/aggregator/src/server.ts | 42 ++++- 2 files changed, 305 insertions(+), 12 deletions(-) diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index d10f747f86..84bc27025c 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -8,7 +8,10 @@ import { allRefs, commentStream, executionStrip, + freshness, monthTimeline, + projectPace, + resetMarkers, roadmapDayGrain, sessionChildren, sessionRoots, @@ -21,21 +24,29 @@ import { githubCommentUrl } from "./comments.ts"; import { summarizeDns } from "./dns.ts"; import { type BoardItem, + type ChargeRow, type Comment, type DashAuthor, type DashComment, type DnsEntry, type DnsSection, type GhItem, + type PaygLine, type Provenance, type QuotaView, type RefKey, type RoadmapRow, + type SaasService, type SessionRecord, + type SnapshotRecord, type SourceCoverage, type TieredEntry, type TierItem, + type UsageMetric, + type UsageView, + SAAS_GROUP_LABELS, SESSION_SOURCE_LABELS, + countedEstimate, refUrl, } from "./model.ts"; import { PAGES } from "./pages.ts"; @@ -127,6 +138,13 @@ meter { width: 140px; height: 14px; } .cform .err { color: #f85149; font-size: 12px; margin-top: 6px; } nav select { background: #161b22; color: #e6edf3; border: 1px solid #30363d; border-radius: 6px; padding: 6px 8px; font: inherit; margin-left: auto; max-width: 45vw; } .foot { margin-top: 40px; border-top: 1px solid #30363d; padding-top: 10px; color: #8b949e; font-size: 12px; } +.card.stale { opacity: .55; } +.badge.stale { background: #d2992233; border-color: #d29922; color: #e3b341; } +.badge.conflict { background: #bc8cff33; border-color: #bc8cff; color: #bc8cff; } +.flag { border: 1px solid #f85149; background: #f8514911; border-radius: 8px; padding: 8px 12px; margin: 8px 0; } +.flag.payg { border-color: #d29922; background: #d2992211; } +.svcgrid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 12px; align-items: start; } +.chart { background: #0d1117; border: 1px solid #30363d; border-radius: 8px; padding: 8px; margin: 8px 0; overflow-x: auto; } @media (max-width: 720px) { body { font-size: 13.5px; } main { padding: 12px 10px 60px; } @@ -196,7 +214,7 @@ function layout(title: string, body: string, provenance: Provenance, active: str ${esc(title)} · aggregator
${body} -
board: ${esc(provenance.board)} · roadmap: ${esc(provenance.roadmap)} · items: ${esc(provenance.items)} · comments: ${esc(provenance.comments)} · quota: ${esc(provenance.quota)} · attention: ${esc(provenance.attention)} · orchestration: ${esc(provenance.orchestration)} · dns: ${esc(provenance.dns)} · registry: ${esc(provenance.registry)}
tailnet: ${TAILNET_URL.replace("http://", "")}
+
board: ${esc(provenance.board)} · roadmap: ${esc(provenance.roadmap)} · items: ${esc(provenance.items)} · comments: ${esc(provenance.comments)} · quota: ${esc(provenance.quota)} · usage: ${esc(provenance.usage)} · attention: ${esc(provenance.attention)} · orchestration: ${esc(provenance.orchestration)} · dns: ${esc(provenance.dns)} · registry: ${esc(provenance.registry)}
tailnet: ${TAILNET_URL.replace("http://", "")}
${extra}`; } @@ -513,9 +531,125 @@ export function sessionRecordLine(r: SessionRecord): string { return `
${esc(r.label)} ${esc(r.source)} ${esc(r.agentLabel)}
${esc(r.id)} · ${esc(r.status)}${r.model ? ` · ${esc(r.model)}` : ""} · started ${fmtDate(r.startedAt)} · last seen ${fmtDate(r.lastSeenAt)}${tokens}${parent}${refs}
`; } -// --- Quota view (#851) ----------------------------------------------------- +// --- Quota view (#851) + Usage & billing hub (design 2026-10-25) ----------- -export function renderQuota(view: QuotaView, provenance: Provenance): string { +const SOURCE_CLASS_LABELS: Record = { + api: "API read", + console: "console read", + manual: "manual read", + estimate: "estimate", + invoice: "invoice", +}; + +export function fmtMetricValue(v: number | null, unit: string): string { + if (v == null) return "not measured"; + if (unit === "usd") return `$${v.toFixed(2)}`; + if (unit === "gb") return `${v} GB`; + if (unit === "pct") return `${v}%`; + return v.toLocaleString(); +} + +/** The freshness stamp every hub card carries (§1.1): measured-at + source + age. */ +export function freshnessStamp(measuredAt: string | null, sourceClass: string, cadenceDays: number): string { + const f = freshness(measuredAt, cadenceDays); + const cls = SOURCE_CLASS_LABELS[sourceClass] ?? sourceClass; + if (!measuredAt) return `no dated read ${esc(cls)} · ${esc("never measured")}`; + const age = f.ageDays == null ? "" : f.ageDays === 0 ? " · today" : ` · ${f.ageDays}d ago`; + const stale = f.stale ? ` stale — as of ${esc(measuredAt.slice(0, 10))}` : ""; + return `measured ${esc(measuredAt.slice(0, 10))}${age} · ${esc(cls)}${stale}`; +} + +function metricRow(m: UsageMetric): string { + const pct = m.percent; + const meter = + pct != null + ? ` ${pct.toFixed(0)}% · ` + : ""; + const limit = m.limit == null ? "" : ` / ${fmtMetricValue(m.limit, m.unit)}`; + return `
${esc(m.label)}: ${meter}${fmtMetricValue(m.used, m.unit)}${limit}${m.note ? ` — ${esc(m.note)}` : ""}
`; +} + +function attentionStripHtml(usage: UsageView): string { + if (!usage.attention.length) { + return `
Needs attention — nothing over threshold. (Bubble rules: any metric over 80% of its limit, or projected unbilled PAYG over $5.)
`; + } + const rows = usage.attention + .map( + (f) => + `
${esc(f.label)} — ${esc(f.detail)} details
`, + ) + .join(""); + return `

Needs attention

${rows}`; +} + +function paygCardHtml(usage: UsageView): string { + if (!usage.payg.length) { + return `
PAYG dollars
pay-as-you-go agent spend
No metered spill recorded in local records.
`; + } + const lines = usage.payg + .map((l: PaygLine) => { + const figures = + l.accruedUsd != null + ? `$${l.accruedUsd.toFixed(2)} accrued${l.collectedUsd != null ? ` · $${l.collectedUsd.toFixed(2)} collected` : ""} · $${(l.unbilledUsd ?? 0).toFixed(2)} unbilled` + : l.estimate + ? `counted $${countedEstimate(l.estimate).toFixed(2)} as used (1.2 × high) · estimate $${l.estimate.low.toFixed(2)}–$${l.estimate.high.toFixed(2)} ${esc(l.estimate.period)}` + : "not estimable from local records"; + return `
${esc(l.label)}: ${figures}
${esc(l.note)}
${freshnessStamp(l.measuredAt, l.sourceClass, 7)}
`; + }) + .join(""); + const total = usage.payg.reduce((sum, l) => sum + (l.unbilledUsd ?? 0), 0); + return `
PAYG dollars
metered spill, counted per Decision 004 — estimates at 1.2 × high
$${total.toFixed(2)} projected unbilled
${lines}
`; +} + +function serviceCardHtml(svc: SaasService, history: SnapshotRecord[]): string { + const f = freshness(svc.measuredAt, svc.cadenceDays); + const highlights = svc.metrics.filter((m) => m.highlight); + const metrics = highlights.length + ? highlights.map(metricRow).join("") + : `
${esc(svc.usageNote ?? "No highlight metrics recorded.")}
`; + const billed = + svc.billedUsd != null + ? `
billed this period: $${svc.billedUsd.toFixed(2)}
` + : ""; + const payg = svc.paygEstimate + ? `
PAYG estimate: counted $${countedEstimate(svc.paygEstimate).toFixed(2)} (${esc(svc.paygEstimate.period)}; range $${svc.paygEstimate.low.toFixed(2)}–$${svc.paygEstimate.high.toFixed(2)} in detail)
` + : svc.paygNote + ? `
PAYG: ${esc(svc.paygNote)}
` + : ""; + const conflict = svc.conflicts.length + ? ` conflict` + : ""; + const pace = paceLineHtml(svc.id, history); + return `
${esc(svc.name)}${conflict}
${esc(svc.plan)}
${freshnessStamp(svc.measuredAt, svc.sourceClass, svc.cadenceDays)}${svc.nextDate ? `
next: ${esc(svc.nextDate)}` : ""}
${metrics}${billed}${payg}${pace}
`; +} + +/** A one-line pace projection on a card, when the history supports one (§1.5). */ +function paceLineHtml(serviceId: string, history: SnapshotRecord[]): string { + const metricIds = [...new Set(history.filter((r) => r.unit === "pct").map((r) => r.metricId))]; + for (const metricId of metricIds) { + const pace = projectPace(history, metricId); + if (pace?.projectedExhaustionAt) { + return `
pace (${esc(metricId)}): +${pace.slopePerDay} pts/day → projected to exhaust ${esc(pace.projectedExhaustionAt.slice(0, 10))}${pace.projectedPercentAtReset != null ? ` · ${pace.projectedPercentAtReset}% at reset` : ""}
`; + } + } + return ""; +} + +function chargesStripHtml(usage: UsageView): string { + if (!usage.charges.length) { + return `

Charges this period

${esc(usage.chargesNote ?? "No charge evidence in the local records yet — rows appear as Plaid/Gmail receipt evidence is recorded.")}
`; + } + const rows = usage.charges + .map( + (c: ChargeRow) => + `${esc(c.at)}${esc(c.label)}$${c.amountUsd.toFixed(2)}${esc(c.method)}${esc(c.source)}`, + ) + .join(""); + const total = usage.charges.reduce((sum, c) => sum + c.amountUsd, 0); + return `

Charges this period

Evidence, not accounting — charges observed on cards/receipts in the local records (full balances stay in the finance tooling). Total observed: $${total.toFixed(2)}.

${rows}
DateChargeAmountMethodEvidence
`; +} + +export function renderQuota(view: QuotaView, provenance: Provenance, usage?: UsageView): string { const pools = view.pools .map((p) => { const windows = p.windows @@ -542,20 +676,143 @@ export function renderQuota(view: QuotaView, provenance: Provenance): string { ) .join(""); const choices = (list: string[]) => (list.length ? list.map(esc).join(", ") : "—"); - return layout( - "Quota + throughput", - `

Quota + throughput

All pooled quotas, resets, and burn rates. Machine-first: the same data is at /api/quota.json.

-

Pools

${pools} -

Burn between resets

${burn || ''}
ProviderPoolFromToTokens
none
+ const burnAndChoices = `

Burn between resets

${burn || ''}
ProviderPoolFromToTokens
none

Model choice

-
RulePools
Headroom for a new session${choices(view.choices.hasHeadroom)}
Burn-it-before-reset (unused headroom)${choices(view.choices.burnBeforeReset)}
Do not start a second session${choices(view.choices.doNotStart)}
`, +Do not start a second session${choices(view.choices.doNotStart)}`; + if (!usage) { + return layout( + "Quota + throughput", + `

Quota + throughput

All pooled quotas, resets, and burn rates. Machine-first: the same data is at /api/quota.json.

+

Pools

${pools} +${burnAndChoices}`, + provenance, + "/quota", + ); + } + const groupOrder: (keyof typeof SAAS_GROUP_LABELS)[] = [ + "database", + "object-storage", + "compute", + "dev-platform", + "domains", + "account-tooling", + ]; + const groups = groupOrder + .map((g) => { + const svcs = usage.services.filter((s) => s.group === g); + const cards = svcs.map((s) => serviceCardHtml(s, usage.history[s.id] ?? [])).join(""); + const domainsCard = + g === "domains" + ? usage.domains + ? `
Domains
Porkbun register — summary only; the full register lives on the DNS page
renewal exposure: $${usage.domains.totalAnnualUsd.toFixed(2)}/yr across ${usage.domains.domainCount} domains
next renewal: ${esc(usage.domains.nextRenewal ?? "—")}
` + : `
Domains: the register has not reached the feed yet — see /dns.
` + : ""; + const subs = + g === "account-tooling" && usage.subscriptions.length + ? `
Subscriptions (flat)
renewal-only rows — no usage meter
${usage.subscriptions + .map( + (s) => + `
${esc(s.name)}: ${esc(s.plan)}${s.renewsAt ? ` · renews ${esc(s.renewsAt)}` : " · renewal date unknown"}
`, + ) + .join("")}
` + : ""; + if (!cards && !domainsCard && !subs) return ""; + return `

${esc(SAAS_GROUP_LABELS[g])}

${cards}${domainsCard}${subs}
`; + }) + .join(""); + return layout( + "Usage & billing", + `

Usage & billing

Token quotas, PAYG dollars, and SaaS usage vs limits — from dated local records; every card carries its measured-at stamp, and stale cards dim. Machine-first: /api/quota.json.

+${attentionStripHtml(usage)} +

Token quotas

${pools} +${paygCardHtml(usage)} +

SaaS & services

${groups || '

No services extracted yet.

'} +${chargesStripHtml(usage)} +${burnAndChoices}`, provenance, "/quota", ); } +// --- Service detail view (hub v1.1, §1.5) ------------------------------------- + +/** An inline SVG history chart for one metric, with reset markers (§4). */ +export function historyChartHtml(records: SnapshotRecord[], metricId: string): string { + const recs = records + .filter((r) => r.metricId === metricId && typeof r.value === "number") + .sort((a, b) => a.ts.localeCompare(b.ts)) as (SnapshotRecord & { value: number })[]; + if (!recs.length) return ""; + const W = 640; + const H = 130; + const PAD = 28; + const t0 = Date.parse(recs[0].ts); + const t1 = Math.max(Date.parse(recs[recs.length - 1].ts), t0 + 1); + const vmax = Math.max(...recs.map((r) => r.value), ...(recs.map((r) => r.limit ?? 0) as number[]), 1) * 1.1; + const x = (ts: string) => PAD + ((Date.parse(ts) - t0) / (t1 - t0)) * (W - PAD - 8); + const y = (v: number) => H - 18 - (v / vmax) * (H - 34); + const markers = resetMarkers(records, metricId) + .filter((m) => Date.parse(m.ts) >= t0 && Date.parse(m.ts) <= t1) + .map( + (m) => + `reset ${esc(m.resetsAt.slice(0, 10))}`, + ) + .join(""); + const limitLine = recs.find((r) => r.limit != null) + ? `` + : ""; + const points = recs + .map( + (r) => + `${esc(r.ts.slice(0, 10))}: ${r.value} ${esc(r.unit)} (${esc(r.source)})`, + ) + .join(""); + const line = recs.map((r, i) => `${i === 0 ? "M" : "L"}${x(r.ts).toFixed(1)},${y(r.value).toFixed(1)}`).join(" "); + const first = recs[0]; + const last = recs[recs.length - 1]; + return `
${esc(metricId)} · ${recs.length} snapshot${recs.length === 1 ? "" : "s"} · ${esc(first.ts.slice(0, 10))} → ${esc(last.ts.slice(0, 10))} · dashed amber = window reset, red = limit
${markers}${limitLine}${points}
`; +} + +export function renderServiceDetail(svc: SaasService, history: SnapshotRecord[], provenance: Provenance): string { + const f = freshness(svc.measuredAt, svc.cadenceDays); + const metricRows = svc.metrics.length + ? svc.metrics.map((m) => `${esc(m.label)}${m.highlight ? ' highlight' : ""}${fmtMetricValue(m.used, m.unit)}${m.limit == null ? "—" : fmtMetricValue(m.limit, m.unit)}${m.percent != null ? `${m.percent.toFixed(0)}%` : "—"}${esc(m.note ?? "")}`).join("") + : 'No metrics recorded for this service yet.'; + const payg = svc.paygEstimate + ? `

PAYG estimate

low $${svc.paygEstimate.low.toFixed(2)} / high $${svc.paygEstimate.high.toFixed(2)} ${esc(svc.paygEstimate.period)} — counted as used: $${countedEstimate(svc.paygEstimate).toFixed(2)} (1.2 × high, Decision 004).${svc.paygEstimate.note ? `
${esc(svc.paygEstimate.note)}` : ""}
` + : svc.paygNote + ? `

PAYG estimate

${esc(svc.paygNote)} — no number is invented where the records carry no volume.
` + : ""; + const metricIds = [...new Set(history.map((r) => r.metricId))]; + const charts = metricIds.map((id) => historyChartHtml(history, id)).filter(Boolean).join(""); + const paces = metricIds + .map((id) => ({ id, pace: projectPace(history, id) })) + .filter((p) => p.pace) + .map( + (p) => + `
${esc(p.id)}: +${p.pace!.slopePerDay} pts/day over ${p.pace!.points} reads${p.pace!.projectedExhaustionAt ? ` → projected to exhaust ${esc(p.pace!.projectedExhaustionAt.slice(0, 10))}` : ""}${p.pace!.projectedPercentAtReset != null ? ` · projected ${p.pace!.projectedPercentAtReset}% at reset` : ""}
`, + ) + .join(""); + const reads = svc.reads.length + ? svc.reads.map((r) => `
${esc(r.at)}
${esc(r.text)}
`).join("") + : '

No dated reads recorded.

'; + const conflicts = svc.conflicts.length + ? `

Conflicts (shown, not resolved)

${svc.conflicts.map((c) => `
${esc(c)}
`).join("")}` + : ""; + const body = `

← Usage & billing

+

${esc(svc.name)}

+
${esc(svc.plan)} ${esc(svc.status)}
${freshnessStamp(svc.measuredAt, svc.sourceClass, svc.cadenceDays)}
source: ${esc(svc.sourceNote)}${svc.nextDate ? ` · next: ${esc(svc.nextDate)}` : ""}${svc.billedUsd != null ? ` · billed this period: $${svc.billedUsd.toFixed(2)}` : ""}${svc.usageNote ? `
${esc(svc.usageNote)}` : ""}
+

All metrics

${metricRows}
MetricUsedLimit%Note
+${payg} +

Snapshot history

${charts || '

No snapshots in the store for this service yet — history starts with the §4 backfill and accumulates as writers append.

'} +${paces ? `

Pace projections

${paces}
` : ""} +${conflicts} +

Dated source reads

${reads} +

Machine-first: /api/quota/service.json?id=${esc(svc.id)}

`; + return layout(`${svc.name} · usage`, body, provenance, "/quota"); +} + // --- Attention view (#852, tiered in slice 2) ------------------------------- function sessionCard( diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 7c195b7ebd..7983d7cf00 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -5,7 +5,7 @@ // (GitHub, Kaneo, Grist) stays read-only from here. import { CommentsStore, validateNewComment } from "./comments.ts"; import { loadConfig } from "./config.ts"; -import { allRefs, buildAttention, deriveToday, type RoadmapGrain } from "./derive.ts"; +import { allRefs, buildAttention, deriveToday, projectPace, type RoadmapGrain } from "./derive.ts"; import type { DashComment, RefKey } from "./model.ts"; import { identitiesFromRecords } from "./registry.ts"; import { @@ -18,6 +18,7 @@ import { renderPages, renderQuota, renderRoadmap, + renderServiceDetail, renderSessions, renderToday, type CommentFormOpts, @@ -196,7 +197,18 @@ async function handler(req: Request): Promise { } if (path === "/quota") { - return html(renderQuota(await source.quota(), prov())); + const [quota, usage] = await Promise.all([source.quota(), source.usage()]); + return html(renderQuota(quota, prov(), usage)); + } + + const serviceMatch = /^\/quota\/service\/([\w-]+)$/.exec(path); + if (serviceMatch) { + const usage = await source.usage(); + const svc = usage.services.find((s) => s.id === serviceMatch[1]); + if (svc) return html(renderServiceDetail(svc, usage.history[svc.id] ?? [], prov())); + return html( + `

Not found

no SaaS service with id ${serviceMatch[1]} — back to Usage & billing

`, + ); } if (path === "/attention") { @@ -241,7 +253,31 @@ async function handler(req: Request): Promise { return json({ rows, items: [...items.values()] }); } if (path === "/api/quota.json") { - return json(await source.quota()); + // Extended in place for the hub (design §1.1): the pools/burn/choices + // shape is unchanged for existing consumers (quota-guidance); the + // hub sections ride as additional top-level keys. Snapshot history + // stays out of this twin — it is per-service, on the service twin. + const [quota, usage] = await Promise.all([source.quota(), source.usage()]); + return json({ + ...quota, + saas: usage.services, + payg: usage.payg, + charges: usage.charges, + attention: usage.attention, + domains: usage.domains, + subscriptions: usage.subscriptions, + }); + } + if (path === "/api/quota/service.json") { + const id = url.searchParams.get("id") ?? ""; + const usage = await source.usage(); + const svc = usage.services.find((s) => s.id === id); + if (!svc) return json({ error: "unknown service", id }, 404); + const history = usage.history[svc.id] ?? []; + const paces = [...new Set(history.map((r) => r.metricId))] + .map((metricId) => ({ metricId, pace: projectPace(history, metricId) })) + .filter((p) => p.pace); + return json({ service: svc, history, paces }); } if (path === "/api/attention.json") { // Slice 2: the flat array shape stays; entries are now current-only From c4a9e41dc7aeb1b067e07c33fd1112a3fc08803f Mon Sep 17 00:00:00 2001 From: Archer Date: Mon, 26 Oct 2026 13:18:00 +0000 Subject: [PATCH 3/3] feat(aggregator): hub backfill script, tests, README; extractor fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit scripts/backfill-usage-snapshots.ts seeds the §4 store from quota-view.md + provider-quota-registry.md dated observations (31 records, 2026-10-20 → 2026-10-25, original dates + source classes kept; idempotent via store dedupe; the ¥ DeepSeek balance is deliberately excluded — the §4 unit enum has no CNY). test/usage.test.ts (20 tests): Part (b) extraction pinned to the real phrasing, PAYG/charges evidence, bubble-rule edges (exactly 80% / exactly $5 do not bubble), store round-trip + dedupe, pace projection across a reset boundary, freshness, hub + detail renders. boot.test.ts: the quota-page assertion follows the retitle. Fixes from live runs: measuredAt comes from each section's Last-checked record (a future operational date in the section is not a read), PAYG estimate notes strip their bold label cleanly, freshness ages date-only stamps by calendar day. --- pm-stack/aggregator/README.md | 13 +- .../scripts/backfill-usage-snapshots.ts | 257 ++++++++++++++++ pm-stack/aggregator/src/derive.ts | 11 +- pm-stack/aggregator/src/saas-extract.ts | 21 +- pm-stack/aggregator/test/boot.test.ts | 2 +- pm-stack/aggregator/test/usage.test.ts | 289 ++++++++++++++++++ 6 files changed, 583 insertions(+), 10 deletions(-) create mode 100644 pm-stack/aggregator/scripts/backfill-usage-snapshots.ts create mode 100644 pm-stack/aggregator/test/usage.test.ts diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index edece562db..28037a1c5d 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -21,7 +21,7 @@ Design record (source of truth): | `/attention` | **Needs you** (#852, tiered in slice 2) — **NEEDS DREW** (default; only items that genuinely require Drew, each with its reason), **NEEDS ORCHESTRATOR** (the fleet's own queue), then every current session with source labels and plain-language states. Finished runs and stale items expire out. | `/api/attention.json`, `/api/coverage.json` | | `/` | **Cross-repo WIP board** — the curated in-flight set across all four repos, with an execution strip per card (implementing → review → merged → queued). | `/api/board.json` | | `/roadmap` | **Roadmap** — Grist's `Program roadmap` table as a timeline; `?h=` switches the horizon: `quarter` (default), `month`, `week`, `3d`, `today` — one data model at every grain. | `/api/roadmap.json` | -| `/quota` | **Quota + throughput** (#851) — all pooled quotas, resets, burn rates, and model-choice guidance. | `/api/quota.json` | +| `/quota` | **Usage & billing** (hub, design 2026-10-25; pools from #851) — needs-attention strip (bubble rules: >80% of a limit, >$5 projected unbilled PAYG), token-quota pools + PAYG dollars card, SaaS service cards grouped by kind with highlight metrics, charges evidence strip. Per-service detail: `/quota/service/`. | `/api/quota.json` (extended: `saas`/`payg`/`charges`/…), `/api/quota/service.json?id=` | | `/dns` | **DNS / domain register** (slice 3, #906; data owned by #902) — the register rendered next-renewal-first: renewing-soon spend, then in-use / unused-but-earmarked / completely-unused views and the full table. | `/api/dns.json` | | `/sessions` | **Sessions** (slice 3, #906) — the identity registry: every known session with its stable id, agent identity, parent, task refs, and token total, grouped by source. | `/api/registry.json` | | `/pages` | **All pages** — the page manifest rendered: every registered page, its route, and its JSON twin. | — (the manifest is `src/pages.ts`) | @@ -172,6 +172,9 @@ Everything defaults to **fixtures** and works with no configuration: | `PM_AGG_PORT` | `4870` | HTTP port | | `PM_AGG_HOSTS` | `127.0.0.1` | Comma-separated bind addresses (deployment: loopback + tailnet; no public route) | | `PM_AGG_FEED_FILE` | `./fleet-feed.json` | The fleet feed (quota + sandbox attention) written by the collector (below) | +| `PM_AGG_SNAPSHOTS_DIR` | `./snapshots` | Usage snapshot store (hub §4): monthly `usage-YYYY-MM.jsonl` files; read by the hub, appended by writer jobs + `scripts/backfill-usage-snapshots.ts` | +| `PM_AGG_QUOTA_VIEW` | stewardship goal's `visibility/quota-view.md` | Hub fallback source when the feed carries no `saas`/`payg` sections yet | +| `PM_AGG_QUOTA_REGISTRY` | repo-health goal's `provider-quota-registry.md` | The hub's second dated-read source (billing incidents) for the same fallback | | `PM_AGG_OPENCHAMBER_STATE` | `~/.config/openchamber/managed-opencode/state.json` | Laptop OpenCode server port + password source (laptop attention, live) | | `KANEO_URL` | `http://127.0.0.1:5173` | Kaneo base URL (board reader) | | `KANEO_ADMIN_EMAIL` | — | Kaneo admin email (secret `kaneo.admin-password` pairs with it) | @@ -234,6 +237,14 @@ a file. `scripts/collect-fleet-feed.ts` runs on the sandbox: The pool map is the corrected one from the provider-quota registry: exactly one Meta pool (Muse API High Usage, `meta` provider the only door); no "muse plan" pool exists. +- **Usage & billing hub sections** — the same collector run extracts + quota-view Part (b) via `src/saas-extract.ts` into `saas` / `payg` / + `charges` / `subscriptions` feed sections (the provider registry's + billing incidents supply the gateway accrual + card-alert charges). + The aggregator's `Source.usage()` serves them with snapshot history + from the §4 store; older feeds without the sections fall back to a + direct read of the two source documents. Seed the store once with + `bun run scripts/backfill-usage-snapshots.ts` (idempotent). - **Sandbox attention** — sessions mapped by the shared OpenCode v2 mapper (`src/sources/opencode.ts`), stamped `opencode-sandbox` with parent/agent/outcome; keeper supervision entries from diff --git a/pm-stack/aggregator/scripts/backfill-usage-snapshots.ts b/pm-stack/aggregator/scripts/backfill-usage-snapshots.ts new file mode 100644 index 0000000000..c898cbd5b6 --- /dev/null +++ b/pm-stack/aggregator/scripts/backfill-usage-snapshots.ts @@ -0,0 +1,257 @@ +#!/usr/bin/env bun +// One-shot backfill for the usage snapshot store (hub design §4): seed +// history from the dated observations already recorded in +// quota-view.md and provider-quota-registry.md (2026-10-20 → today). +// Each record keeps its ORIGINAL date and source class; the prose +// stays the citation, snapshots are derived data. Fail-soft per fact: +// a pattern that no longer matches is skipped with a warning, never +// guessed. Re-running is safe — the store dedupes on (service, metric, +// ts, value). +// +// The DeepSeek balance (¥44.63) is deliberately NOT backfilled: the +// §4 unit enum (pct|usd|count|gb|tokens) has no CNY, and recording it +// as USD would corrupt the record. +// +// Usage: bun run scripts/backfill-usage-snapshots.ts [--dir ] +// Env: PM_AGG_SNAPSHOTS_DIR, QUOTA_VIEW_PATH, QUOTA_REGISTRY_PATH. +import { readFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { sectionOf } from "../src/quota-extract.ts"; +import { SnapshotStore } from "../src/snapshots.ts"; +import type { SnapshotRecord } from "../src/model.ts"; + +const PKG = join(dirname(fileURLToPath(import.meta.url)), ".."); +const HOME = homedir(); +const dirArg = process.argv.indexOf("--dir"); +const storeDir = + dirArg >= 0 ? process.argv[dirArg + 1] : (process.env.PM_AGG_SNAPSHOTS_DIR ?? join(PKG, "snapshots")); +const quotaViewPath = + process.env.QUOTA_VIEW_PATH ?? + join( + HOME, + "workspace/goals/stewardship-commission-recurring-review-and-dispatch/hidden_files/visibility/quota-view.md", + ); +const registryPath = + process.env.QUOTA_REGISTRY_PATH ?? + join(HOME, "workspace/goals/keep-the-four-repos-healthy/hidden_files/provider-quota-registry.md"); + +const BY_VIEW = "backfill:quota-view.md"; +const BY_REGISTRY = "backfill:provider-quota-registry.md"; +const warnings: string[] = []; +const records: SnapshotRecord[] = []; + +function push(r: SnapshotRecord | null, what: string): void { + if (r) records.push(r); + else warnings.push(`skipped (pattern unmatched): ${what}`); +} + +const pct = ( + serviceId: string, + metricId: string, + value: number, + ts: string, + source: SnapshotRecord["source"], + observedBy: string, + resetsAt?: string, +): SnapshotRecord => ({ + ts, + serviceId, + metricId, + value, + unit: "pct", + limit: 100, + ...(resetsAt ? { resetsAt } : {}), + source, + observedBy, +}); + +/** "2026-10-25" + "09:38" CDT -> ISO instant. */ +const cdt = (date: string, hhmm: string): string => `${date}T${hhmm}:00-05:00`; +/** A date-only read, stamped midday UTC (≈ morning CDT) — no invented time. */ +const dayTs = (date: string): string => `${date}T12:00:00Z`; + +function first(text: string, re: RegExp): RegExpExecArray | null { + return re.exec(text); +} + +async function main(): Promise { + const doc = await readFile(quotaViewPath, "utf8"); + const registry = await readFile(registryPath, "utf8").catch(() => ""); + + // --- Claude Pro weekly (console read, 2026-10-25 morning) --------------- + { + const s = sectionOf(doc, /^### Claude$/); + const m = first(s, /weekly\s+(\d+(?:\.\d+)?)%\s+used/i); + const reset = first(s, /weekly reset \w+ (\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}) CDT/i); + push( + m + ? pct("anthropic:claude-pro", "weekly", Number(m[1]), dayTs("2026-10-25"), "console", BY_VIEW, + reset ? cdt(reset[1], reset[2]) : undefined) + : null, + "claude weekly %", + ); + } + + // --- Codex 7-day (model-efficiency plan read, 2026-10-25) --------------- + { + const s = sectionOf(doc, /^### ChatGPT/); + const m = first(s, /7-day\s+(\d+(?:\.\d+)?)%\s+used/i); + push(m ? pct("openai:codex", "7-day", Number(m[1]), dayTs("2026-10-25"), "console", BY_VIEW) : null, "codex 7-day %"); + } + + // --- OpenCode Go workspaces (console reads, 2026-10-25) ------------------ + { + const s = sectionOf(doc, /^### OpenCode Go/); + const fresh = first( + s, + /Personal — monthly (\d+(?:\.\d+)?)% used, weekly (\d+(?:\.\d+)?)%, rolling (\d+(?:\.\d+)?)%/i, + ); + push(fresh ? pct("opencode-go:personal", "monthly", Number(fresh[1]), cdt("2026-10-25", "09:17"), "console", BY_VIEW) : null, "go personal monthly (09:17 read)"); + push(fresh ? pct("opencode-go:personal", "weekly", Number(fresh[2]), cdt("2026-10-25", "09:17"), "console", BY_VIEW) : null, "go personal weekly (09:17 read)"); + const freshLab = first( + s, + /Lab — monthly (\d+(?:\.\d+)?)% used, weekly (\d+(?:\.\d+)?)%, rolling (\d+(?:\.\d+)?)%/i, + ); + push(freshLab ? pct("opencode-go:lab", "monthly", Number(freshLab[1]), cdt("2026-10-25", "09:18"), "console", BY_VIEW) : null, "go lab monthly (09:18 read)"); + push(freshLab ? pct("opencode-go:lab", "weekly", Number(freshLab[2]), cdt("2026-10-25", "09:18"), "console", BY_VIEW) : null, "go lab weekly (09:18 read)"); + const morning = first(s, /\*\*Personal — monthly (\d+(?:\.\d+)?)% used\*\*/i); + push(morning ? pct("opencode-go:personal", "monthly", Number(morning[1]), dayTs("2026-10-25"), "console", BY_VIEW) : null, "go personal monthly (morning read)"); + const morningLab = first(s, /\*\*Lab — monthly (\d+(?:\.\d+)?)% used, weekly (\d+(?:\.\d+)?)%\*\*/i); + push(morningLab ? pct("opencode-go:lab", "monthly", Number(morningLab[1]), dayTs("2026-10-25"), "console", BY_VIEW) : null, "go lab monthly (morning read)"); + } + + // --- ClinePass (dashboard read, 2026-10-25 ~04:48 CDT) ------------------- + { + const s = sectionOf(doc, /^### ClinePass/); + const m = first( + s, + /5-hour \*\*(\d+(?:\.\d+)?)%\*\* used; weekly \*\*(\d+(?:\.\d+)?)%\*\* used \(resets in (\d+)d (\d+)h\); monthly \*\*(\d+(?:\.\d+)?)%\*\* used/i, + ); + const ts = cdt("2026-10-25", "04:48"); + push(m ? pct("cline-pass:cline-pass", "5-hour", Number(m[1]), ts, "console", BY_VIEW) : null, "clinepass 5h"); + push(m ? pct("cline-pass:cline-pass", "weekly", Number(m[2]), ts, "console", BY_VIEW) : null, "clinepass weekly"); + push(m ? pct("cline-pass:cline-pass", "monthly", Number(m[5]), ts, "console", BY_VIEW) : null, "clinepass monthly"); + } + + // --- Command Code --------------------------------------------------------- + { + const s = sectionOf(doc, /^### Command Code/); + const bal = first(s, /\$(\d+(?:\.\d+)?) of \$(\d+(?:\.\d+)?) used/i); + push( + bal + ? { ts: dayTs("2026-10-25"), serviceId: "commandcode:go", metricId: "monthly-credits", value: Number(bal[1]), unit: "usd", limit: Number(bal[2]), source: "console", observedBy: BY_VIEW } + : null, + "command code $ used (2026-10-25 read)", + ); + const short = first(s, /5h (\d+(?:\.\d+)?)%, weekly (\d+(?:\.\d+)?)%/i); + push(short ? pct("commandcode:go", "5-hour", Number(short[1]), dayTs("2026-10-25"), "console", BY_VIEW) : null, "command code 5h"); + push(short ? pct("commandcode:go", "weekly", Number(short[2]), dayTs("2026-10-25"), "console", BY_VIEW) : null, "command code weekly"); + push( + /68% monthly limit used/.test(s) + ? pct("commandcode:go", "monthly", 68, dayTs("2026-10-20"), "manual", BY_VIEW) + : null, + "command code 68% (2026-10-20)", + ); + const left = first(s, /\$(\d+(?:\.\d+)?) left/i); + push( + left + ? { ts: dayTs("2026-10-24"), serviceId: "commandcode:go", metricId: "monthly-credits", value: Math.round((10 - Number(left[1])) * 100) / 100, unit: "usd", limit: 10, source: "manual", observedBy: BY_VIEW } + : null, + "command code $ left (2026-10-24)", + ); + } + + // --- Muse consumer weekly (init-log panel captures) ---------------------- + { + const s = sectionOf(doc, /^### Muse — consumer/); + push(/36% observed 2026-10-20/.test(s) ? pct("muse:consumer", "weekly", 36, dayTs("2026-10-20"), "manual", BY_VIEW) : null, "muse consumer 36% (2026-10-20)"); + push(/\*\*34% of weekly limit used/.test(s) ? pct("muse:consumer", "weekly", 34, cdt("2026-10-25", "07:24"), "manual", BY_VIEW) : null, "muse consumer 34% (07:24 panel)"); + push(/37% of weekly limit \(2026-10-25 08:49 CDT/.test(doc) ? pct("muse:consumer", "weekly", 37, cdt("2026-10-25", "08:49"), "manual", BY_VIEW) : null, "muse consumer 37% (08:49 read)"); + } + + // --- Meta High Usage + PAYG (console reads, 2026-10-25) ------------------- + { + const s = sectionOf(doc, /^### Meta Model API/); + push(/weekly quota \*\*46% at 03:20 CDT\*\*/.test(s) || /46% used at 03:20 CDT/.test(registry) + ? pct("meta:high-usage", "weekly", 46, cdt("2026-10-25", "03:20"), "console", BY_VIEW) + : null, "meta weekly 46% (03:20)"); + push(/weekly limit \*\*85% used at 09:38 CDT\*\*/.test(s) ? pct("meta:high-usage", "weekly", 85, cdt("2026-10-25", "09:38"), "console", BY_VIEW) : null, "meta weekly 85% (09:38 console)"); + push(/short window 1%/.test(registry) ? pct("meta:high-usage", "short-window", 1, cdt("2026-10-25", "09:38"), "console", BY_REGISTRY) : null, "meta short window 1% (registry console note)"); + const accrued = first(s, /PAYG Oct 19–25: \$(\d+(?:\.\d+)?) accrued/); + push( + accrued + ? { ts: cdt("2026-10-25", "09:38"), serviceId: "meta:high-usage", metricId: "payg-accrued", value: Number(accrued[1]), unit: "usd", source: "console", observedBy: BY_VIEW } + : null, + "meta PAYG accrued $ (Oct 19-25)", + ); + } + + // --- Antigravity pools (panel read, 2026-10-25 03:52) --------------------- + { + const s = sectionOf(doc, /^### Gemini/); + const g = first(s, /Gemini weekly (\d+(?:\.\d+)?)% remaining/i); + push(g ? pct("antigravity:gemini", "weekly", Math.round((100 - Number(g[1])) * 10) / 10, cdt("2026-10-25", "03:52"), "console", BY_VIEW) : null, "antigravity gemini weekly"); + const cg = first(s, /Claude\+GPT pools (\d+(?:\.\d+)?)% remaining/i); + push(cg ? pct("antigravity:claude-gpt", "weekly", Math.round((100 - Number(cg[1])) * 10) / 10, cdt("2026-10-25", "03:52"), "console", BY_VIEW) : null, "antigravity claude+gpt weekly"); + } + + // --- Turso (dashboard read, 2026-10-20) ------------------------------------ + { + const s = sectionOf(doc, /^### Turso$/m); + push(/~0%, far behind: 1 DB/.test(s) || /1 DB `/.test(s) + ? { ts: dayTs("2026-10-20"), serviceId: "turso", metricId: "databases", value: 1, unit: "count", limit: 100, source: "manual", observedBy: BY_VIEW } + : null, "turso databases (2026-10-20)"); + push(/~0%/.test(sectionOf(doc, /^## Summary \(b\)/)) + ? pct("turso", "usage", 0, dayTs("2026-10-20"), "manual", BY_VIEW) + : null, "turso ~0% (2026-10-20 summary)"); + } + + // --- Cloudflare (Tracker footprint 2026-10-20 + Decision-004 estimates) ---- + { + const s = sectionOf(doc, /^### Cloudflare — Workers platform/); + const r2 = /~(\d+(?:\.\d+)?) GB/.exec(s); + push( + r2 + ? { ts: dayTs("2026-10-20"), serviceId: "cloudflare", metricId: "r2-storage", value: Number(r2[1]), unit: "gb", limit: 10, source: "manual", observedBy: BY_VIEW } + : null, + "cloudflare r2 storage footprint", + ); + const est = /low \$(\d+(?:\.\d+)?) \/ high \$(\d+(?:\.\d+)?) per month/i.exec(s); + push( + est + ? { ts: dayTs("2026-10-25"), serviceId: "cloudflare", metricId: "platform-excess-est", value: { low: Number(est[1]), high: Number(est[2]) }, unit: "usd-est", source: "estimate", observedBy: BY_VIEW } + : null, + "cloudflare platform excess estimate", + ); + const gw = /\$(\d+(?:\.\d+)?) per budget alert vs \$(\d+(?:\.\d+)?) per gateway cost attribution/.exec(registry); + push( + gw + ? { ts: dayTs("2026-10-25"), serviceId: "cloudflare", metricId: "gateway-accrual-est", value: { low: Number(gw[1]), high: Number(gw[2]) }, unit: "usd-est", source: "estimate", observedBy: BY_REGISTRY } + : null, + "cloudflare gateway accrual estimate (registry)", + ); + } + + // --- GitHub comped minutes (Memory note recorded 2026-10-25) --------------- + { + const s = sectionOf(doc, /^### GitHub$/m); + const comped = /(\d[\d,]*) Linux \+ (\d+) macOS minutes/.exec(s); + push( + comped + ? { ts: dayTs("2026-10-25"), serviceId: "github", metricId: "actions-comped-minutes", value: Number(comped[1].replace(/,/g, "")) + Number(comped[2]), unit: "count", source: "manual", observedBy: BY_VIEW } + : null, + "github comped minutes (October)", + ); + } + + const store = new SnapshotStore(storeDir); + const appended = await store.append(records); + for (const w of warnings) console.error(`backfill: ${w}`); + console.log( + `backfill: ${appended} record(s) appended to ${storeDir} (${records.length - appended} already present, ${warnings.length} skipped)`, + ); +} + +await main(); diff --git a/pm-stack/aggregator/src/derive.ts b/pm-stack/aggregator/src/derive.ts index 1ef215a034..d7c50e94ca 100644 --- a/pm-stack/aggregator/src/derive.ts +++ b/pm-stack/aggregator/src/derive.ts @@ -789,7 +789,16 @@ export interface Freshness { /** A card is stale when its freshest read is older than its cadence (§1.1). */ export function freshness(measuredAt: string | null, cadenceDays: number, now = new Date()): Freshness { if (!measuredAt) return { stale: true, ageDays: null }; - const t = Date.parse(measuredAt.length <= 10 ? `${measuredAt}T23:59:59Z` : measuredAt); + // Date-only stamps age by calendar day (a read dated yesterday is + // 1 day old all day today); datetimes age by elapsed whole days. + if (measuredAt.length <= 10) { + const t = Date.parse(`${measuredAt}T00:00:00Z`); + if (Number.isNaN(t)) return { stale: true, ageDays: null }; + const startOfToday = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()); + const ageDays = Math.max(0, Math.round((startOfToday - t) / 86_400_000)); + return { stale: ageDays > cadenceDays, ageDays }; + } + const t = Date.parse(measuredAt); if (Number.isNaN(t)) return { stale: true, ageDays: null }; const ageDays = Math.max(0, Math.floor((now.getTime() - t) / 86_400_000)); return { stale: ageDays > cadenceDays, ageDays }; diff --git a/pm-stack/aggregator/src/saas-extract.ts b/pm-stack/aggregator/src/saas-extract.ts index cbd4467e96..dbe0de4ec3 100644 --- a/pm-stack/aggregator/src/saas-extract.ts +++ b/pm-stack/aggregator/src/saas-extract.ts @@ -90,6 +90,11 @@ function conflictsOf(section: string): string[] { * "low $X / high $Y per month; counted as used = 1.2 × high = $Z". * Returns the estimate, or a note explaining its absence. */ +/** Strip a PAYG bullet's bold label (two shapes: "**PAYG estimate:** …" and "**PAYG estimate (…): …**"). */ +function stripPaygLabel(text: string): string { + return text.replace(/^\*\*PAYG estimate[^*]*:\*\*\s*/, "").replace(/^\*\*PAYG estimate[^*]*:\s*/, ""); +} + function paygOf(section: string): { estimate: PaygEstimate | null; note?: string } { const text = bullet(section, /\*\*PAYG estimate/); if (!text) return { estimate: null }; @@ -100,7 +105,7 @@ function paygOf(section: string): { estimate: PaygEstimate | null; note?: string low: Number(m[1]), high: Number(m[2]), period: "per month", - note: text.replace(/^\*\*PAYG estimate[^:]*:\*\*\s*/, "").slice(0, 300), + note: stripPaygLabel(text).replace(/\*\*/g, "").slice(0, 300), }, }; } @@ -108,10 +113,7 @@ function paygOf(section: string): { estimate: PaygEstimate | null; note?: string return { estimate: null, note: "not estimable from local records" }; } if (/not applicable/i.test(text)) { - const why = text - .replace(/^\*\*PAYG estimate[^:]*:\*\*\s*/, "") - .replace(/^not applicable\s*—\s*/i, "") - .split(".")[0]; + const why = stripPaygLabel(text).replace(/^not applicable\s*—\s*/i, "").split(".")[0]; return { estimate: null, note: `not applicable — ${why}`.slice(0, 220) }; } return { estimate: null }; @@ -481,12 +483,17 @@ export function extractSaasServices(doc: string): SaasService[] { try { const payg = paygOf(section); const usageText = bullet(section, /\*\*Usage \/ dates:\*\*/).replace(/^\*\*Usage \/ dates:\*\*\s*/, ""); + // measuredAt = the freshest date in the section's own "Last + // checked" record — NOT the freshest date anywhere in the + // section, which can be a future operational date (a mirror + // review, a cycle end) rather than a read. + const measuredAt = freshestDate(bullet(section, /\*\*Last checked:\*\*/)) ?? freshestDate(section); services.push({ ...shell, metrics: spec.metrics(section, doc), paygEstimate: payg.estimate, paygNote: payg.note, - measuredAt: freshestDate(section), + measuredAt, conflicts: conflictsOf(section), reads: readsOf(section), usageNote: usageText ? usageText.slice(0, 600) : spec.shellNote, @@ -503,7 +510,7 @@ export function extractSaasServices(doc: string): SaasService[] { if (cf && zone) { cf.reads = [...readsOf(zone), ...cf.reads].sort((a, b) => b.at.localeCompare(a.at)).slice(0, 14); cf.conflicts = [...conflictsOf(zone), ...cf.conflicts]; - const zoneDate = freshestDate(zone); + const zoneDate = freshestDate(bullet(zone, /\*\*Last checked:\*\*/)) ?? freshestDate(zone); if (zoneDate && (!cf.measuredAt || zoneDate > cf.measuredAt)) cf.measuredAt = zoneDate; } return services; diff --git a/pm-stack/aggregator/test/boot.test.ts b/pm-stack/aggregator/test/boot.test.ts index a28ee68980..051a567629 100644 --- a/pm-stack/aggregator/test/boot.test.ts +++ b/pm-stack/aggregator/test/boot.test.ts @@ -61,7 +61,7 @@ describe("server boots from fixtures", () => { test("quota and attention pages render", async () => { const quota = await (await fetch(`http://127.0.0.1:${port}/quota`)).text(); const attention = await (await fetch(`http://127.0.0.1:${port}/attention`)).text(); - expect(quota.includes("Quota + throughput")).toBe(true); + expect(quota.includes("Usage & billing")).toBe(true); // the hub retitle (design 2026-10-25 §1.1) expect(attention.includes("Needs you")).toBe(true); expect(attention.includes("Needs Drew")).toBe(true); expect(attention.includes("Session coverage")).toBe(true); diff --git a/pm-stack/aggregator/test/usage.test.ts b/pm-stack/aggregator/test/usage.test.ts new file mode 100644 index 0000000000..fc5f4fd520 --- /dev/null +++ b/pm-stack/aggregator/test/usage.test.ts @@ -0,0 +1,289 @@ +// Usage & billing hub (design 2026-10-25): Part (b) extraction, PAYG +// lines, charges evidence, bubble rules, the snapshot store, pace +// projections, and the hub/detail renders. The sample view below +// carries the same dated-read phrasing quota-view.md uses, trimmed. +import { describe, expect, test } from "bun:test"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { buildAttentionFlags, freshness, projectPace, resetMarkers } from "../src/derive.ts"; +import { countedEstimate, type QuotaView, type SnapshotRecord } from "../src/model.ts"; +import { renderQuota, renderServiceDetail } from "../src/render.ts"; +import { extractCharges, extractPaygLines, extractSaasServices, extractSubscriptions } from "../src/saas-extract.ts"; +import { SnapshotStore, snapshotFileFor } from "../src/snapshots.ts"; +import { fixtureSource } from "../src/sources/fixtures.ts"; + +const VIEW = ` +# Part (b) — Subscriptions & SaaS/infrastructure + +## Summary (b) — subscriptions, infrastructure, account tooling + +| Service | Plan / price | Allowance sketch | Usage / status | Next date recorded | +|---|---|---|---|---| +| Cloudflare platform | Workers Paid $5/mo + R2 Paid $0 base | 10M requests / 30M CPU-ms monthly | Historically far behind | Subscription date unknown | +| Turso | Starter Free $0 | 100 DBs, 5 GB, 500M reads/10M writes/3 GB syncs monthly | ~0% Oct 20 | 2026-10-31 cycle end | +| Modal | Starter $0/mo | $30/mo compute credits | unknown | Monthly; exact reset unknown | + +## Service details (b) + +### Cloudflare — Workers platform, R2 and AI gateway +- **Plan / price:** Tracker and Memory: Workers Paid $5/mo + R2 Paid $0 base, verified 2026-10-20. **Conflict/stale earlier evidence:** CF reports subscription endpoint 403 and presumed $0/free. +- **Monthly allowances:** Workers 10M requests/30M CPU-ms; logs 20M, 7-day retention; KV 10M reads, 1M writes/deletes/lists, 1 GB; D1 25B rows read/50M written, 5 GB; Queues 1M ops; Durable Objects 1M requests/400k GB-s/5 GB-mo SQL; Workflows 500k steps/1 GB-mo; Vectorize 50M queried/10M stored dimensions; Hyperdrive unlimited queries; Containers 25 GiB-hours memory/375 vCPU-min/200 GB-hours disk (CF). +- **R2 / daily allowances / billing:** R2 Standard 10 GB-mo, 1M Class A and 10M Class B operations monthly; egress $0. Workers AI 10k Neurons/day; paid excess $0.011/1k Neurons. +- **Usage / pace:** Tracker: small, 3 Workers, 2 R2 buckets ~2 GB, 2 D1, 2 KV, 2 Queues; far behind, mostly unused. +- **PAYG estimate (excess only, excluding the $5/mo base which is counted as subscription): low $0 / high $5.20 per month; counted as used = 1.2 × high = $6.24 per month.** Basis: every meter sits inside its included allotment. +- **Last checked:** Plan/footprint 2026-10-20, token 2026-10-23; gateway observation 2026-10-25. + +### Turso +- **Plan / price / allowance:** Starter Free $0: 100 DBs, 5 GB storage, 500M reads/month, 10M writes/month, 3 GB syncs/month, 1-day PITR. +- **Usage / dates:** ~0%, far behind: 1 DB \`great-star-lord\`, 0 B, 0 usage on 2026-10-20; cycle Sep 30–Oct 31 2026. Mirror observation week ends 2026-10-29, not a billing reset. +- **PAYG estimate:** not applicable — Starter Free is a $0 hard-capped plan with overages disabled; there is no metered bill to estimate. +- **Last checked:** Plan/dashboard 2026-10-20; overage setting 2026-10-21; mirror capability 2026-10-24. + +### Modal +- **Plan / price / allowance:** Starter $0/mo, Drew confirmed 2026-10-22; $30 monthly compute-credit grant, per-second billing past credits. +- **Usage / dates:** Percentage/pace unknown; monthly grant, exact reset/credit expiry date unknown. +- **PAYG estimate: not estimable from local records** — no run hours or credit balance are recorded. +- **Last checked:** 2026-10-22 (Tracker). + +### Meta Model API +- **Usage / dates:** weekly quota **46% at 03:20 CDT**; morning sessions spilled to PAYG — **$23.91 charged** ($20.00 at 05:15 CDT + $3.91 at 07:47 CDT). **Console read (dev.meta.ai, 2026-10-25 09:38 CDT):** weekly limit **85% used at 09:38 CDT**. PAYG Oct 19–25: $23.92 accrued / $23.91 collected, nothing outstanding. +`; + +const REGISTRY = ` +## Billing incidents + Drew's response (2026-10-25, main chat) + +- [observed] Meta API plan: usage past the wall metered as PAYG — **$20.00 charged 05:15 CDT + $3.91 charged 07:47 CDT** (Visa •7535 card alerts). +- [observed] Cloudflare gateway DeepSeek V4 Pro accrual Oct 24–25: $29.60 per budget alert vs $45.10 per gateway cost attribution; final figure lands on the Nov 2 invoice. +`; + +describe("saas extraction (Part b)", () => { + const services = extractSaasServices(VIEW); + const byId = new Map(services.map((s) => [s.id, s])); + + test("cloudflare: one card, highlight limits + long tail, estimate, conflict", () => { + const cf = byId.get("cloudflare")!; + expect(cf.plan).toContain("Workers Paid $5/mo"); + const m = new Map(cf.metrics.map((x) => [x.id, x])); + expect(m.get("workers-requests")?.limit).toBe(10_000_000); + expect(m.get("workers-cpu-ms")?.limit).toBe(30_000_000); + expect(m.get("d1-rows-read")?.limit).toBe(25_000_000_000); + expect(m.get("workers-ai-neurons")?.limit).toBe(10_000); + expect(m.get("r2-storage")?.used).toBe(2); + expect(m.get("r2-storage")?.percent).toBe(20); + expect(m.get("workflows-steps")?.highlight).toBe(false); // long tail stays off the front page + expect(cf.paygEstimate).toEqual({ low: 0, high: 5.2, period: "per month", note: expect.any(String) }); + expect(countedEstimate(cf.paygEstimate!)).toBe(6.24); + expect(cf.conflicts.length).toBeGreaterThan(0); + expect(cf.measuredAt).toBe("2026-10-25"); + }); + + test("turso: measuredAt is the last-checked date, not a future operational date", () => { + const t = byId.get("turso")!; + expect(t.measuredAt).toBe("2026-10-24"); // not 2026-10-29 (mirror review week) + const m = new Map(t.metrics.map((x) => [x.id, x])); + expect(m.get("databases")?.used).toBe(1); + expect(m.get("databases")?.limit).toBe(100); + expect(m.get("rows-read")?.limit).toBe(500_000_000); + expect(t.paygEstimate).toBeNull(); + expect(t.paygNote).toContain("not applicable"); + expect(t.nextDate).toBe("2026-10-31 cycle end"); + }); + + test("modal: not-estimable stays a note, never a number", () => { + const modal = byId.get("modal")!; + expect(modal.paygEstimate).toBeNull(); + expect(modal.paygNote).toBe("not estimable from local records"); + expect(modal.metrics[0]?.limit).toBe(30); + }); + + test("missing sections render as identity shells, never vanish", () => { + const ids = services.map((s) => s.id); + for (const id of ["supabase", "github", "vercel", "oci", "bitwarden"]) expect(ids).toContain(id); + expect(byId.get("vercel")?.usageNote).toContain("baseline"); + }); + + test("fail-soft on an empty document", () => { + const shells = extractSaasServices("nothing here"); + expect(shells.length).toBe(8); + expect(shells.every((s) => s.measuredAt === null)).toBe(true); + }); +}); + +describe("payg lines + charges (§1.2, §2.4)", () => { + test("meta console figures: accrued vs collected, unbilled is the remainder", () => { + const lines = extractPaygLines(VIEW, REGISTRY); + const meta = lines.find((l) => l.id === "meta-payg")!; + expect(meta.accruedUsd).toBe(23.92); + expect(meta.collectedUsd).toBe(23.91); + expect(meta.unbilledUsd).toBe(0.01); + }); + + test("gateway disagreement is shown as a low/high estimate pair", () => { + const gw = extractPaygLines(VIEW, REGISTRY).find((l) => l.id === "cloudflare-gateway")!; + expect(gw.estimate).toMatchObject({ low: 29.6, high: 45.1 }); + expect(gw.unbilledUsd).toBe(54.12); // counted = 1.2 × high + }); + + test("charges carry their evidence source and payment method", () => { + const charges = extractCharges(VIEW, REGISTRY); + const meta = charges.filter((c) => c.label === "Meta PAYG spill"); + expect(meta.map((c) => c.amountUsd).sort((a, b) => a - b)).toEqual([3.91, 20]); + expect(meta[0].method).toBe("Visa •7535"); + expect(meta[0].source).toContain("card alert"); + }); + + 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.`); + 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" }, + ]); + }); +}); + +describe("bubble rules (§1.3)", () => { + const quota: QuotaView = { + pools: [ + { + id: "p1", + provider: "P", + plan: "Plan", + state: "healthy", + windows: [ + { name: "at-80", unit: "other", limit: 100, used: 80, resetsAt: null }, + { name: "over-80", unit: "other", limit: 100, used: 81, resetsAt: null }, + ], + }, + ], + burn: [], + choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] }, + }; + test("strictly over 80% bubbles; exactly 80% does not", () => { + const flags = buildAttentionFlags(quota, { services: [], payg: [] }); + expect(flags.map((f) => f.label)).toEqual(["P · Plan — over-80"]); + }); + test("projected unbilled strictly over $5 bubbles", () => { + const flags = buildAttentionFlags(quota, { + 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" }, + ], + }); + expect(flags.filter((f) => f.kind === "payg-unbilled").map((f) => f.label)).toEqual(["B"]); + }); +}); + +describe("snapshot store (§4)", () => { + const rec = (ts: string, value: number): SnapshotRecord => ({ + ts, + serviceId: "turso", + metricId: "usage", + value, + unit: "pct", + limit: 100, + source: "manual", + observedBy: "test", + }); + test("monthly file naming follows the record's own month", () => { + expect(snapshotFileFor("2026-10-25T09:38:00-05:00")).toBe("usage-2026-10.jsonl"); + expect(snapshotFileFor("2026-09-30T12:00:00Z")).toBe("usage-2026-09.jsonl"); + }); + test("append is idempotent and reads survive a fresh store instance", async () => { + const dir = await mkdtemp(join(tmpdir(), "hub-snaps-")); + try { + const store = new SnapshotStore(dir); + expect(await store.append([rec("2026-10-20T12:00:00Z", 0), rec("2026-10-25T12:00:00Z", 40)])).toBe(2); + expect(await store.append([rec("2026-10-20T12:00:00Z", 0)])).toBe(0); // dedupe + const byService = await new SnapshotStore(dir).byService(); + expect(byService["turso"]?.map((r) => r.value)).toEqual([0, 40]); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); + test("estimate pairs round-trip as pairs (the 1.2x rule is render-side)", async () => { + const dir = await mkdtemp(join(tmpdir(), "hub-snaps-")); + 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" }, + ]); + const all = await store.readAll(); + expect(all[0].value).toEqual({ low: 29.6, high: 45.1 }); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); + +describe("pace + freshness (§4, §1.1)", () => { + const rec = (ts: string, value: number, resetsAt?: string): SnapshotRecord => ({ + ts, + serviceId: "x", + metricId: "weekly", + value, + unit: "pct", + limit: 100, + ...(resetsAt ? { resetsAt } : {}), + source: "console", + observedBy: "test", + }); + test("pace projects exhaustion from the current window only", () => { + const recs = [ + rec("2026-10-20T00:00:00Z", 90, "2026-10-21T00:00:00Z"), + rec("2026-10-22T00:00:00Z", 10, "2026-10-29T00:00:00Z"), + rec("2026-10-24T00:00:00Z", 30, "2026-10-29T00:00:00Z"), + ]; + const pace = projectPace(recs, "weekly")!; + expect(pace.points).toBe(2); // the pre-reset point is excluded + expect(pace.slopePerDay).toBe(10); + expect(pace.projectedExhaustionAt?.slice(0, 10)).toBe("2026-10-31"); + expect(pace.projectedPercentAtReset).toBe(80); + expect(resetMarkers(recs, "weekly")).toHaveLength(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(); + }); + test("freshness: older than cadence is stale; same-day is not", () => { + const now = new Date("2026-10-26T12:00:00Z"); + expect(freshness("2026-10-25", 7, now)).toEqual({ stale: false, ageDays: 1 }); + expect(freshness("2026-10-01", 7, now).stale).toBe(true); + expect(freshness(null, 7, now)).toEqual({ stale: true, ageDays: null }); + }); +}); + +describe("hub renders", () => { + test("fixture source: hub page carries both families + the strip", async () => { + const src = fixtureSource(); + const html = renderQuota(await src.quota(), src.provenance(), await src.usage()); + expect(html).toContain("Usage & billing"); + expect(html).toContain("Needs attention"); + expect(html).toContain("PAYG dollars"); + expect(html).toContain("Charges this period"); + expect(html).toContain("/quota/service/turso"); + expect(html).toContain("measured"); + }); + test("legacy two-arg renderQuota still renders the pools page", async () => { + const src = fixtureSource(); + const html = renderQuota(await src.quota(), src.provenance()); + expect(html).toContain("Quota + throughput"); + }); + test("service detail: full metrics, chart, reads, conflicts", async () => { + const src = fixtureSource(); + const usage = await src.usage(); + const turso = usage.services.find((s) => s.id === "turso")!; + const html = renderServiceDetail(turso, usage.history["turso"] ?? [], src.provenance()); + expect(html).toContain("All metrics"); + expect(html).toContain("Snapshot history"); + expect(html).toContain(" s.id === "cloudflare")!; + const cfHtml = renderServiceDetail(cf, [], src.provenance()); + expect(cfHtml).toContain("Conflicts (shown, not resolved)"); + expect(cfHtml).toContain("counted as used"); + }); +});