diff --git a/pm-stack/aggregator/src/analytics-store.ts b/pm-stack/aggregator/src/analytics-store.ts new file mode 100644 index 0000000000..96b9304238 --- /dev/null +++ b/pm-stack/aggregator/src/analytics-store.ts @@ -0,0 +1,695 @@ +// Data layer for the /quota "Analytics & projection" section +// (Drew's order, 2026-11-13). Everything here is a READ of a store +// that already exists — nothing is estimated into existence: +// +// - Burn, models, efforts, legs: the route proxy's route_attempt +// ledger in the OpenCode database (~/.local/share/opencode/ +// opencode.db) — one row per model call with provider, model, +// variant (effort), token columns (input / output / reasoning / +// cache read / cache write), recorded cost, and outcome. +// - Sessions, sub-sessions, turns, tool calls, skill use, mcpx: +// session_v2 + session_message in the same database (tool parts +// carry the tool name; `skill` parts carry the skill name in +// their input; mcpx tools are named mcpx_*). +// - Fleet binary use per subcommand: INFERRED — counted by +// scanning shell tool-call inputs for `fleet `. +// There is no fleet invocation ledger; the UI labels this +// "inferred" and the gap is filed as an issue. +// - Pool percent history (for projections + week-over-week): +// the aggregator's own usage-snapshot store, via UsageView +// .history — dated quota reads, never a model. +// +// The OpenCode database is opened READ-ONLY. Any failure (missing +// file, locked, schema drift) degrades the section to an explicit +// unavailable state — the page never breaks over analytics. + +import { Database } from "bun:sqlite"; +import { existsSync, readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import type { QuotaPool, QuotaView, SnapshotRecord, UsageView } from "./model.ts"; +import { + projectWindow, + tokenRatios, + unlockPicture, + usFederalHoliday, + wowDelta, + type PctPoint, + type TokenTotals, + type UnlockPicture, + type WindowProjection, + type WowDelta, +} from "./quota-analytics.ts"; + +export const OPENCODE_DB_DEFAULT = join(homedir(), ".local", "share", "opencode", "opencode.db"); + +const HOUR_MS = 3_600_000; +const DAY_MS = 24 * HOUR_MS; + +// --------------------------------------------------------------------------- +// Shapes +// --------------------------------------------------------------------------- + +export interface BurnBucket extends TokenTotals { + calls: number; + success: number; + /** Recorded cost (route proxy's list-price equivalent), summed + * over the rows that carry one; costRows says how many did. */ + costUsd: number; + costRows: number; +} + +export const emptyBurn = (): BurnBucket => ({ + calls: 0, + success: 0, + input: 0, + output: 0, + reasoning: 0, + cacheRead: 0, + cacheWrite: 0, + costUsd: 0, + costRows: 0, +}); + +export interface BurnGroup extends BurnBucket { + key: string; + label: string; +} + +export interface PoolWindowAnalytics { + name: string; + percent: number; + resetsAt: string | null; + /** ms from now until the reset; null when no reset is recorded. */ + durationUntilResetMs: number | null; + projection: WindowProjection; + /** Duration-until-wall now vs the projection computed as of 7 + * days ago from the same series; null when either side has no + * measured duration. */ + wowDurationUntilWall: WowDelta | null; +} + +export interface PoolAnalytics { + poolId: string; + provider: string; + plan: string; + state: string; + windows: PoolWindowAnalytics[]; + /** The window that gates the pool: walled first, then earliest + * projected wall, then fullest. Null when the pool has none. */ + bindingWindow: string | null; + unlock: UnlockPicture | null; + /** Burn attributed to this pool's legs (see POOL_LEG_BASIS); + * null when no leg maps to the pool. */ + burnToday: BurnBucket | null; + burn7d: BurnBucket | null; + burnWowTokens: WowDelta | null; + /** How the burn attribution was made — shown in the UI. */ + legBasis: "credential" | "provider-id" | "shared-credential" | null; + legLabel: string | null; +} + +export interface ActivityCounts { + /** Window the counts cover. */ + rangeLabel: string; + sessions: number; + rootSessions: number; + subSessions: number; + turns: number; + toolCallsTotal: number; + topTools: { name: string; count: number }[]; + skillTotal: number; + topSkills: { name: string; count: number }[]; + /** Direct mcpx tool calls (mcpx_discover / mcpx_exec / mcpx_project). */ + mcpx: { name: string; count: number }[]; + /** The `execute` code-gateway tool (mcpx-style namespace calls go + * through it; counted separately, not folded into mcpx). */ + executeGateway: number; + /** INFERRED fleet binary use from shell tool-call inputs. */ + fleetInferred: { subcommand: string; count: number }[]; + fleetInferredTotal: number; +} + +export interface QuotaAnalytics { + generatedAt: string; + now: number; + dbAvailable: boolean; + /** route_attempt coverage, ISO instants; null when unavailable. */ + attemptsFrom: string | null; + attemptsTo: string | null; + /** Percent of route_attempt rows in the last 7d that carry a + * credential id (the pool-attribution coverage). */ + credentialCoveragePct: number | null; + pools: PoolAnalytics[]; + totals: { lastHour: BurnBucket; today: BurnBucket; last7d: BurnBucket; prev7d: BurnBucket }; + totalsWowTokens: WowDelta; + byModel7d: BurnGroup[]; + byEffort7d: BurnGroup[]; + byLeg7d: BurnGroup[]; + hourly7d: { hour: number; calls: number; tokens: number }[]; + dowHistory: { dow: number; calls: number; tokens: number }[]; + daily21d: { day: string; calls: number; tokens: number; holiday: string | null }[]; + /** Null while the first (slow) transcript scan is still running — + * the section says so instead of blocking the page. */ + activity7d: ActivityCounts | null; +} + +// --------------------------------------------------------------------------- +// OpenCode DB access (read-only, fail-soft) +// --------------------------------------------------------------------------- + +function openDb(path: string): Database | null { + try { + if (!existsSync(path)) return null; + return new Database(path, { readonly: true }); + } catch { + return null; + } +} + +/** One shared read-only handle for the process: the background + * activity scan runs after the triggering request returns, so the + * handle must outlive any single build. Read-only + WAL means the + * running OpenCode server is never disturbed. */ +let sharedDb: { path: string; db: Database | null } | null = null; +function getDb(path: string): Database | null { + if (!sharedDb || sharedDb.path !== path) sharedDb = { path, db: openDb(path) }; + return sharedDb.db; +} + +interface DayLegRow { + day: string; + provider_id: string; + credential_id: string | null; + calls: number; + success: number; + input: number; + output: number; + reasoning: number; + cache_read: number; + cache_write: number; + cost: number; + cost_rows: number; +} + +interface DayModelRow { + day: string; + model_id: string; + variant: string | null; + calls: number; + success: number; + input: number; + output: number; + reasoning: number; + cache_read: number; + cache_write: number; + cost: number; + cost_rows: number; +} + +const BURN_TTL_MS = 120_000; +let burnCache: { at: number; days: string[]; legRows: DayLegRow[]; modelRows: DayModelRow[] } | null = null; + +function loadBurnRows(db: Database, now: number): { legRows: DayLegRow[]; modelRows: DayModelRow[]; days: string[] } { + if (burnCache && now - burnCache.at < BURN_TTL_MS) return burnCache; + const legRows = db + .query( + `SELECT date(time_started/1000, 'unixepoch', 'localtime') AS day, + provider_id, credential_id, + COUNT(*) AS calls, + SUM(outcome = 'success') AS success, + COALESCE(SUM(tokens_input), 0) AS input, + COALESCE(SUM(tokens_output), 0) AS output, + COALESCE(SUM(tokens_reasoning), 0) AS reasoning, + COALESCE(SUM(tokens_cache_read), 0) AS cache_read, + COALESCE(SUM(tokens_cache_write), 0) AS cache_write, + COALESCE(SUM(cost_usd), 0) AS cost, + COUNT(cost_usd) AS cost_rows + FROM route_attempt + WHERE time_started >= ? + GROUP BY day, provider_id, credential_id`, + ) + .all(now - 15 * DAY_MS) as DayLegRow[]; + const modelRows = db + .query( + `SELECT date(time_started/1000, 'unixepoch', 'localtime') AS day, + model_id, variant, + COUNT(*) AS calls, + SUM(outcome = 'success') AS success, + COALESCE(SUM(tokens_input), 0) AS input, + COALESCE(SUM(tokens_output), 0) AS output, + COALESCE(SUM(tokens_reasoning), 0) AS reasoning, + COALESCE(SUM(tokens_cache_read), 0) AS cache_read, + COALESCE(SUM(tokens_cache_write), 0) AS cache_write, + COALESCE(SUM(cost_usd), 0) AS cost, + COUNT(cost_usd) AS cost_rows + FROM route_attempt + WHERE time_started >= ? + GROUP BY day, model_id, variant`, + ) + .all(now - 15 * DAY_MS) as DayModelRow[]; + const days = [...new Set([...legRows, ...modelRows].map((r) => r.day))].sort(); + burnCache = { at: now, days, legRows, modelRows }; + return burnCache; +} + +function addInto(into: BurnBucket, r: { calls: number; success: number; input: number; output: number; reasoning: number; cache_read: number; cache_write: number; cost: number; cost_rows: number }): void { + into.calls += r.calls; + into.success += r.success; + into.input += r.input; + into.output += r.output; + into.reasoning += r.reasoning; + into.cacheRead += r.cache_read; + into.cacheWrite += r.cache_write; + into.costUsd += r.cost; + into.costRows += r.cost_rows; +} + +/** Local (America/Chicago on the laptop) ISO day for an instant. */ +function localDay(ms: number): string { + const d = new Date(ms); + const mm = String(d.getMonth() + 1).padStart(2, "0"); + const dd = String(d.getDate()).padStart(2, "0"); + return `${d.getFullYear()}-${mm}-${dd}`; +} + +function dayRange(now: number, daysBack: number): Set { + const out = new Set(); + for (let i = 0; i < daysBack; i++) out.add(localDay(now - i * DAY_MS)); + return out; +} + +// --------------------------------------------------------------------------- +// Activity scan (tool calls / skills / mcpx / fleet) — slow over the +// transcript store (~30s for 7d), so it runs on a stale-while- +// revalidate cache: the first caller gets null + a background +// computation; later callers get the last computed value. +// --------------------------------------------------------------------------- + +const ACTIVITY_TTL_MS = 600_000; +let activityCache: { at: number; data: ActivityCounts } | null = null; +let activityComputing = false; + +function computeActivity(db: Database, now: number): ActivityCounts { + const since = now - 7 * DAY_MS; + const toolRows = db + .query( + `SELECT json_extract(j.value, '$.name') AS name, COUNT(*) AS c + FROM session_message sm, json_each(sm.data, '$.content') j + WHERE sm.type = 'assistant' AND sm.time_created >= ? + AND json_extract(j.value, '$.type') = 'tool' + GROUP BY name ORDER BY c DESC`, + ) + .all(since) as { name: string | null; c: number }[]; + const named = toolRows.filter((r) => r.name); + const total = named.reduce((s, r) => s + r.c, 0); + const byName = new Map(named.map((r) => [r.name as string, r.c])); + const skillRows = db + .query( + `SELECT json_extract(j.value, '$.state.input.name') AS name, COUNT(*) AS c + FROM session_message sm, json_each(sm.data, '$.content') j + WHERE sm.type = 'assistant' AND sm.time_created >= ? + AND json_extract(j.value, '$.type') = 'tool' + AND json_extract(j.value, '$.name') = 'skill' + GROUP BY name ORDER BY c DESC`, + ) + .all(since) as { name: string | null; c: number }[]; + // INFERRED fleet use: shell inputs mentioning the fleet binary. + const shellRows = db + .query( + `SELECT json_extract(j.value, '$.state.input.command') AS command + FROM session_message sm, json_each(sm.data, '$.content') j + WHERE sm.type = 'assistant' AND sm.time_created >= ? + AND json_extract(j.value, '$.type') = 'tool' + AND json_extract(j.value, '$.name') = 'shell' + AND json_extract(j.value, '$.state.input.command') LIKE '%fleet%'`, + ) + .all(since) as { command: string | null }[]; + const fleet = new Map(); + let fleetTotal = 0; + for (const row of shellRows) { + if (!row.command) continue; + for (const m of row.command.matchAll(/(?:^|[\s;|&\/])fleet\s+([a-z][a-z0-9-]*)/g)) { + fleet.set(m[1], (fleet.get(m[1]) ?? 0) + 1); + fleetTotal++; + } + } + const sessionRow = db + .query( + `SELECT COUNT(*) AS total, + SUM(parent_id IS NULL) AS roots, + SUM(parent_id IS NOT NULL) AS subs + FROM session_v2 WHERE time_created >= ?`, + ) + .get(since) as { total: number; roots: number; subs: number }; + const turnRow = db + .query(`SELECT COUNT(*) AS c FROM session_message WHERE type = 'user' AND time_created >= ?`) + .get(since) as { c: number }; + return { + rangeLabel: "last 7 days", + sessions: sessionRow.total, + rootSessions: sessionRow.roots, + subSessions: sessionRow.subs, + turns: turnRow.c, + toolCallsTotal: total, + topTools: named.slice(0, 12).map((r) => ({ name: r.name as string, count: r.c })), + skillTotal: byName.get("skill") ?? 0, + topSkills: skillRows.filter((r) => r.name).slice(0, 10).map((r) => ({ name: r.name as string, count: r.c })), + mcpx: ["mcpx_discover", "mcpx_exec", "mcpx_project"] + .filter((n) => byName.has(n)) + .map((n) => ({ name: n, count: byName.get(n) as number })), + executeGateway: byName.get("execute") ?? 0, + fleetInferred: [...fleet.entries()].sort((a, b) => b[1] - a[1]).slice(0, 12).map(([subcommand, count]) => ({ subcommand, count })), + fleetInferredTotal: fleetTotal, + }; +} + +function loadActivity(db: Database, now: number): ActivityCounts | null { + if (activityCache && now - activityCache.at < ACTIVITY_TTL_MS) return activityCache.data; + if (!activityComputing) { + activityComputing = true; + setTimeout(() => { + try { + const data = computeActivity(db, Date.now()); + activityCache = { at: Date.now(), data }; + } catch { + // fail-soft: leave the cache unset; a later call retries + } finally { + activityComputing = false; + } + }, 0); + } + return activityCache?.data ?? null; +} + +// --------------------------------------------------------------------------- +// Pool leg attribution +// --------------------------------------------------------------------------- + +/** How each quota pool's burn is attributed from route_attempt. + * "credential": the gatherer's credential id for the pool's service + * (read live from quota-current.json) — the exact join. + * "provider-id": no credential join exists for the pool; the route + * legs are matched by provider_id (the label says so in the UI). + * "shared-credential": both Antigravity pools ride ONE credential — + * both cards show the same burn, labelled shared. */ +const POOL_LEG_BASIS: Record; gathererProviders?: string[]; providerIds?: string[] }> = { + "_openai.main": { basis: "credential", gathererProviders: ["_openai.main"] }, + "_openai.alt": { basis: "credential", gathererProviders: ["_openai.alt"] }, + "opencode-go.drewrypope": { basis: "credential", gathererProviders: ["opencode-go.drewrypope"] }, + "opencode-go.popesdrew": { basis: "credential", gathererProviders: ["opencode-go.popesdrew"] }, + "opencode-go.developing-today-0": { basis: "credential", gathererProviders: ["opencode-go.developing-today-0"] }, + "cline-pass": { basis: "credential", gathererProviders: ["cline-pass"] }, + _commandcode: { basis: "credential", gathererProviders: ["_commandcode"] }, + mistral: { basis: "credential", gathererProviders: ["mistral"] }, + // Antigravity attempts carry NO credential id (verified live: + // 21.8k rows, all NULL) — the credential join can never match, so + // both pools attribute by provider id over the same leg set (the + // two pools share those legs; each card says so via its label). + "_antigravity.gemini": { basis: "provider-id", providerIds: ["antigravity-direct", "_antigravity", "antigravity-ls", "antigravity-agy"] }, + "_antigravity.claude-gpt": { basis: "provider-id", providerIds: ["antigravity-direct", "_antigravity", "antigravity-ls", "antigravity-agy"] }, + opendesign: { basis: "provider-id", providerIds: ["opendesign"] }, + "anthropic:claude-pro": { basis: "provider-id", providerIds: ["_claude", "claude-code"] }, + meta: { basis: "provider-id", providerIds: ["_muse", "muse-direct"] }, + deepseek: { basis: "provider-id", providerIds: ["deepseek"] }, +}; + +function readCredentialMap(quotaCurrentPath: string): Map { + const out = new Map(); + try { + const doc = JSON.parse(readFileSync(quotaCurrentPath, "utf8")) as { + providers?: { providerId?: string; credentialId?: string }[]; + }; + for (const p of doc.providers ?? []) { + if (p.providerId && p.credentialId && !out.has(p.providerId)) out.set(p.providerId, p.credentialId); + } + } catch { + // fail-soft: credential pools simply get no attribution + } + return out; +} + +// --------------------------------------------------------------------------- +// Percent series for projections, from the snapshot store +// --------------------------------------------------------------------------- + +const WINDOW_METRIC_ALIASES: Record = { + "5-hour": ["5h", "5-hour"], + "7d": ["7d", "weekly"], + weekly: ["weekly", "7d"], + monthly: ["monthly"], + api: ["api"], + vibe: ["vibe"], +}; + +function seriesForWindow(history: UsageView["history"], pool: QuotaPool, windowName: string): PctPoint[] { + // Snapshot service ids drifted across writer generations: the same + // pool appears as `_openai.main`, `openai.main`, `cline-pass: + // cline-pass`, `antigravity:gemini` (for pool `_antigravity + // .gemini`)... Normalize both sides (strip a leading underscore, + // treat ':' as '.') and accept the pool's own id plus sub-ids + // under it (`cline-pass.cline-pass` for pool `cline-pass`). + const normSvc = (s: string) => s.replace(/^_/, "").replace(/:/g, "."); + const poolSvc = normSvc(pool.id); + const metrics = new Set(WINDOW_METRIC_ALIASES[windowName] ?? [windowName]); + const points: PctPoint[] = []; + const seen = new Set(); + for (const [serviceId, records] of Object.entries(history)) { + const ns = normSvc(serviceId); + if (ns !== poolSvc && !ns.startsWith(`${poolSvc}.`)) continue; + for (const r of records as SnapshotRecord[]) { + if (typeof r.value !== "number" || r.unit !== "pct") continue; + if (!metrics.has(r.metricId) && !r.metricId.endsWith(`:${windowName}`) && !r.metricId.endsWith(`:${WINDOW_METRIC_ALIASES[windowName]?.[0] ?? windowName}`)) continue; + const ts = Date.parse(r.ts); + if (!Number.isFinite(ts)) continue; + const key = `${ts}|${r.value}`; + if (seen.has(key)) continue; + seen.add(key); + points.push({ ts, pct: r.value, resetsAt: r.resetsAt ?? null }); + } + } + return points.sort((a, b) => a.ts - b.ts); +} + +function percentOf(w: QuotaPool["windows"][number]): number { + if (typeof w.percent === "number") return w.percent; + return w.limit ? (w.used / w.limit) * 100 : 0; +} + +// --------------------------------------------------------------------------- +// Builder +// --------------------------------------------------------------------------- + +export function buildQuotaAnalytics(args: { + quota: QuotaView; + usage: UsageView; + quotaCurrentPath: string; + opencodeDbPath?: string; + now?: number; +}): QuotaAnalytics { + const now = args.now ?? Date.now(); + const dbPath = args.opencodeDbPath ?? OPENCODE_DB_DEFAULT; + const db = getDb(dbPath); + const base: QuotaAnalytics = { + generatedAt: new Date(now).toISOString(), + now, + dbAvailable: !!db, + attemptsFrom: null, + attemptsTo: null, + credentialCoveragePct: null, + pools: [], + totals: { lastHour: emptyBurn(), today: emptyBurn(), last7d: emptyBurn(), prev7d: emptyBurn() }, + totalsWowTokens: wowDelta(0, 0), + byModel7d: [], + byEffort7d: [], + byLeg7d: [], + hourly7d: [], + dowHistory: [], + daily21d: [], + activity7d: null, + }; + if (!db) return base; + try { + const { legRows, modelRows } = loadBurnRows(db, now); + const coverage = db.query(`SELECT MIN(time_started) AS f, MAX(time_started) AS t FROM route_attempt`).get() as { f: number; t: number }; + base.attemptsFrom = coverage.f ? new Date(coverage.f).toISOString() : null; + base.attemptsTo = coverage.t ? new Date(coverage.t).toISOString() : null; + + const today = localDay(now); + const last7 = dayRange(now, 7); + const prev7 = new Set([...dayRange(now - 7 * DAY_MS, 7)]); + const sumWhere = (rows: DayLegRow[] | DayModelRow[], pred: (day: string) => boolean): BurnBucket => { + const b = emptyBurn(); + for (const r of rows) if (pred(r.day)) addInto(b, r); + return b; + }; + base.totals.today = sumWhere(modelRows, (d) => d === today); + base.totals.last7d = sumWhere(modelRows, (d) => last7.has(d)); + base.totals.prev7d = sumWhere(modelRows, (d) => prev7.has(d)); + base.totalsWowTokens = wowDelta( + base.totals.last7d.input + base.totals.last7d.output + base.totals.last7d.cacheRead + base.totals.last7d.cacheWrite + base.totals.last7d.reasoning, + base.totals.prev7d.input + base.totals.prev7d.output + base.totals.prev7d.cacheRead + base.totals.prev7d.cacheWrite + base.totals.prev7d.reasoning, + ); + const hourRows = db + .query( + `SELECT model_id, variant, COUNT(*) AS calls, SUM(outcome='success') AS success, + COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, + COALESCE(SUM(tokens_reasoning),0) AS reasoning, COALESCE(SUM(tokens_cache_read),0) AS cache_read, + COALESCE(SUM(tokens_cache_write),0) AS cache_write, COALESCE(SUM(cost_usd),0) AS cost, COUNT(cost_usd) AS cost_rows + FROM route_attempt WHERE time_started >= ? GROUP BY model_id, variant`, + ) + .all(now - HOUR_MS) as DayModelRow[]; + base.totals.lastHour = sumWhere(hourRows, () => true); + + const group = (rows: DayModelRow[], keyOf: (r: DayModelRow) => { key: string; label: string }): BurnGroup[] => { + const map = new Map(); + for (const r of rows) { + if (!last7.has(r.day)) continue; + const { key, label } = keyOf(r); + const g = map.get(key) ?? { key, label, ...emptyBurn() }; + addInto(g, r); + map.set(key, g); + } + return [...map.values()].sort((a, b) => b.calls - a.calls); + }; + base.byModel7d = group(modelRows, (r) => ({ key: r.model_id, label: r.model_id })); + base.byEffort7d = group(modelRows, (r) => { + const v = r.variant && r.variant !== "default" ? r.variant : "(default)"; + return { key: v, label: v }; + }); + const legGroups = new Map(); + for (const r of legRows) { + if (!last7.has(r.day)) continue; + const g = legGroups.get(r.provider_id) ?? { key: r.provider_id, label: r.provider_id, ...emptyBurn() }; + addInto(g, r); + legGroups.set(r.provider_id, g); + } + base.byLeg7d = [...legGroups.values()].sort((a, b) => b.calls - a.calls); + + const credCov = db + .query(`SELECT COUNT(*) AS n, COUNT(credential_id) AS c FROM route_attempt WHERE time_started >= ?`) + .get(now - 7 * DAY_MS) as { n: number; c: number }; + base.credentialCoveragePct = credCov.n > 0 ? (credCov.c / credCov.n) * 100 : null; + + base.hourly7d = db + .query( + `SELECT CAST(strftime('%H', time_started/1000, 'unixepoch', 'localtime') AS INTEGER) AS hour, + COUNT(*) AS calls, + COALESCE(SUM(tokens_input + tokens_output + tokens_cache_read + tokens_cache_write), 0) AS tokens + FROM route_attempt WHERE time_started >= ? GROUP BY hour ORDER BY hour`, + ) + .all(now - 7 * DAY_MS) as { hour: number; calls: number; tokens: number }[]; + base.dowHistory = db + .query( + `SELECT CAST(strftime('%w', time_started/1000, 'unixepoch', 'localtime') AS INTEGER) AS dow, + COUNT(*) AS calls, + COALESCE(SUM(tokens_input + tokens_output + tokens_cache_read + tokens_cache_write), 0) AS tokens + FROM route_attempt GROUP BY dow ORDER BY dow`, + ) + .all() as { dow: number; calls: number; tokens: number }[]; + const daily = db + .query( + `SELECT date(time_started/1000, 'unixepoch', 'localtime') AS day, + COUNT(*) AS calls, + COALESCE(SUM(tokens_input + tokens_output + tokens_cache_read + tokens_cache_write), 0) AS tokens + FROM route_attempt WHERE time_started >= ? GROUP BY day ORDER BY day`, + ) + .all(now - 21 * DAY_MS) as { day: string; calls: number; tokens: number }[]; + base.daily21d = daily.map((d) => ({ ...d, holiday: usFederalHoliday(d.day) })); + + // ---- pools ------------------------------------------------------------- + const credMap = readCredentialMap(args.quotaCurrentPath); + const legBurn = (poolId: string, pred: (day: string) => boolean): { burn: BurnBucket | null; basis: PoolAnalytics["legBasis"]; label: string | null } => { + const spec = POOL_LEG_BASIS[poolId]; + if (!spec) return { burn: null, basis: null, label: null }; + const credIds = new Set((spec.gathererProviders ?? []).map((p) => credMap.get(p)).filter(Boolean) as string[]); + const provIds = new Set(spec.providerIds ?? []); + if (spec.basis !== "provider-id" && credIds.size === 0) return { burn: null, basis: spec.basis, label: null }; + const b = emptyBurn(); + let any = false; + for (const r of legRows) { + if (!pred(r.day)) continue; + const match = spec.basis === "provider-id" ? provIds.has(r.provider_id) : r.credential_id != null && credIds.has(r.credential_id); + if (match) { + addInto(b, r); + any = true; + } + } + const label = + spec.basis === "provider-id" + ? [...provIds].join(", ") + : [...(spec.gathererProviders ?? [])].join(", ") + (spec.basis === "shared-credential" ? " (one credential, both Antigravity pools)" : ""); + return { burn: any ? b : null, basis: spec.basis, label }; + }; + + base.pools = args.quota.pools.map((pool) => { + const windows: PoolWindowAnalytics[] = pool.windows.map((w) => { + const percent = percentOf(w); + const series = seriesForWindow(args.usage.history, pool, w.name); + const projection = projectWindow({ points: series, pctNow: percent, resetsAt: w.resetsAt, now }); + let wow: WowDelta | null = null; + // Duration-until-wall WoW is only meaningful when BOTH the + // current and the as-of-last-week projections are real + // projections — a walled window has duration 0 by fiat and a + // nearly-flat past slope manufactures absurd durations. + if (projection.state === "projected" && projection.durationUntilWallMs != null) { + const then = now - 7 * DAY_MS; + const past = series.filter((p) => p.ts <= then); + if (past.length) { + const last = past[past.length - 1]; + const pastProjection = projectWindow({ points: past, pctNow: last.pct, resetsAt: last.resetsAt, now: then }); + if (pastProjection.state === "projected" && pastProjection.durationUntilWallMs != null) { + wow = wowDelta(projection.durationUntilWallMs / HOUR_MS, pastProjection.durationUntilWallMs / HOUR_MS); + } + } + } + return { + name: w.name, + percent, + resetsAt: w.resetsAt, + durationUntilResetMs: w.resetsAt ? Date.parse(w.resetsAt) - now : null, + projection, + wowDurationUntilWall: wow, + }; + }); + const binding = + windows.find((w) => w.projection.state === "walled") ?? + windows.filter((w) => w.projection.projectedWallAt != null).sort((a, b) => (a.projection.projectedWallAt as number) - (b.projection.projectedWallAt as number))[0] ?? + windows.slice().sort((a, b) => b.percent - a.percent)[0] ?? + null; + const unlock = binding + ? unlockPicture( + pool.windows.map((w) => ({ name: w.name, percent: percentOf(w), resetsAt: w.resetsAt })), + { name: binding.name, percent: binding.percent, resetsAt: binding.resetsAt }, + ) + : null; + const today7 = legBurn(pool.id, (d) => d === today); + const week = legBurn(pool.id, (d) => last7.has(d)); + const prev = legBurn(pool.id, (d) => prev7.has(d)); + const tok = (b: BurnBucket | null) => (b ? b.input + b.output + b.reasoning + b.cacheRead + b.cacheWrite : 0); + return { + poolId: pool.id, + provider: pool.provider, + plan: pool.plan, + state: pool.state, + windows, + bindingWindow: binding?.name ?? null, + unlock, + burnToday: today7.burn, + burn7d: week.burn, + burnWowTokens: week.burn && prev.burn ? wowDelta(tok(week.burn), tok(prev.burn)) : null, + legBasis: week.basis, + legLabel: week.label, + } satisfies PoolAnalytics; + }); + + base.activity7d = loadActivity(db, now); + return base; + } catch { + // Schema drift or a locked DB must never break /quota: the + // section renders its unavailable state from the base model. + return { ...base, dbAvailable: false }; + } +} + +export { tokenRatios }; diff --git a/pm-stack/aggregator/src/quota-analytics-view.ts b/pm-stack/aggregator/src/quota-analytics-view.ts new file mode 100644 index 0000000000..2e9951dbc8 --- /dev/null +++ b/pm-stack/aggregator/src/quota-analytics-view.ts @@ -0,0 +1,220 @@ +// Rendering for the /quota "Analytics & projection" section +// (Drew's order, 2026-11-13): a cleaner key-value format over the +// model analytics-store.ts builds. Every number names its source in +// a footnote; inferred series (fleet subcommands from shell inputs) +// are labelled "inferred" at the row, never in fine print only. + +import type { BurnBucket, PoolAnalytics, QuotaAnalytics } from "./analytics-store.ts"; +import { fmtDuration, tokenRatios, type WowDelta } from "./quota-analytics.ts"; + +function esc(s: string): string { + return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} + +const whenFmt = new Intl.DateTimeFormat("en-US", { + timeZone: "America/Chicago", + weekday: "short", + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", +}); + +function fmtWhen(ms: number | null): string { + if (ms == null || !Number.isFinite(ms)) return "—"; + return whenFmt.format(new Date(ms)); +} + +function fmtIso(iso: string | null, now: number): string { + if (!iso) return "—"; + const ms = Date.parse(iso); + return Number.isFinite(ms) ? `${fmtWhen(ms)} (in ${fmtDuration(ms - now)})` : iso; +} + +/** Compact counts: 789 · 45.6k · 1.23M · 5.78B. */ +export function fmtN(n: number): string { + const abs = Math.abs(n); + if (abs >= 1e9) return `${(n / 1e9).toFixed(2)}B`; + if (abs >= 1e6) return `${(n / 1e6).toFixed(2)}M`; + if (abs >= 1e3) return `${(n / 1e3).toFixed(1)}k`; + return `${Math.round(n)}`; +} + +function fmtWow(w: WowDelta | null, unit: string): string { + if (!w) return ""; + const sign = w.abs > 0 ? "+" : ""; + const pct = w.pct != null ? ` / ${sign}${w.pct.toFixed(0)}%` : ""; + return ` · vs last week ${sign}${fmtN(w.abs)}${unit}${pct}`; +} + +function burnLine(label: string, b: BurnBucket | null): string { + if (!b) return `
${esc(label)}: no recorded burn
`; + const r = tokenRatios(b); + const cost = + b.costUsd > 0 + ? ` · recorded cost $${b.costUsd.toFixed(2)} (on ${Math.round((b.costRows / Math.max(1, b.calls)) * 100)}% of calls)` + : b.costRows > 0 + ? ` · no recorded cost (subscription legs record $0 in the ledger — not a price)` + : ""; + const perDollar = b.costUsd > 0 ? ` · ${fmtN(r.total / b.costUsd)} tok/$ recorded` : ""; + return ( + `
${esc(label)}: ${fmtN(r.total)} tok · ${fmtN(b.calls)} calls · ` + + `in ${fmtN(b.input)} / out ${fmtN(b.output)} / cache-read ${fmtN(b.cacheRead)}` + + `${r.inPerOut != null ? ` · in:out ${r.inPerOut.toFixed(1)}:1` : ""}` + + `${r.cacheSharePct != null ? ` · cache ${r.cacheSharePct.toFixed(0)}% of input` : ""}${cost}${perDollar}
` + ); +} + +function projectionText(p: PoolAnalytics["windows"][number], now: number): string { + const pr = p.projection; + switch (pr.state) { + case "walled": + return `walled now`; + case "projected": + return `projected wall ${fmtWhen(pr.projectedWallAt)} (in ${fmtDuration(pr.durationUntilWallMs)}) — before the reset · burn ${pr.ratePtsPerHour?.toFixed(2)} pts/h over ${pr.samples} readings`; + case "no-wall-before-reset": + return pr.projectedWallAt != null + ? `no wall before reset at the measured burn (${pr.ratePtsPerHour?.toFixed(2)} pts/h) — projected wall ${fmtWhen(pr.projectedWallAt)} lands after it` + : `no wall before reset at the measured burn${pr.ratePtsPerHour != null ? ` (${pr.ratePtsPerHour.toFixed(2)} pts/h)` : ""}`; + case "insufficient-history": + return `projection unavailable — ${esc(pr.reason ?? "not enough readings")}`; + } +} + +function poolCard(p: PoolAnalytics, now: number, display: (n: string) => string): string { + const windows = p.windows + .map((w) => { + const wowDur = + w.wowDurationUntilWall && w.projection.durationUntilWallMs != null + ? ` · time-to-wall vs last week: ${w.wowDurationUntilWall.abs >= 0 ? "+" : ""}${w.wowDurationUntilWall.abs.toFixed(1)}h${w.wowDurationUntilWall.pct != null ? ` (${w.wowDurationUntilWall.abs >= 0 ? "+" : ""}${w.wowDurationUntilWall.pct.toFixed(0)}%)` : ""}` + : ""; + return ( + `
${esc(w.name)}: ${w.percent.toFixed(0)}% used` + + ` · resets ${fmtIso(w.resetsAt, now)}` + + `${w.durationUntilResetMs != null ? ` · ${fmtDuration(w.durationUntilResetMs)} until reset` : ""}
` + + `
${projectionText(w, now)}${wowDur}
` + ); + }) + .join(""); + const unlock = p.unlock + ? `
unlock: at the ${esc(p.bindingWindow ?? "")} reset (${fmtIso(p.unlock.bindingResetsAt, now)}) frees: ${p.unlock.freesAtReset.map(esc).join(", ") || "—"}` + + `${p.unlock.stillWalledAfter.length ? ` · still walled after: ${p.unlock.stillWalledAfter.map((w) => `${esc(w.name)} (until ${fmtIso(w.resetsAt, now)})`).join(", ")}` : ` · nothing else stays walled`}
` + : ""; + const legNote = p.legBasis + ? `
burn legs: ${esc(p.legLabel ?? "")} · attribution by ${p.legBasis === "provider-id" ? "provider id" : p.legBasis === "shared-credential" ? "shared credential" : "credential id"} · source: route_attempt ledger
` + : `
burn: no route leg maps to this pool yet
`; + return ( + `
${esc(display(p.provider))}
` + + `${esc(p.plan)}
${esc(p.state)} ` + + `↑ at-risk summary
` + + `
${windows}${unlock}${burnLine("burn today", p.burnToday)}${burnLine("burn 7d", p.burn7d)}` + + `${p.burnWowTokens ? `
7d tokens${fmtWow(p.burnWowTokens, "")}
` : ""}${legNote}
` + ); +} + +function summaryStrip(a: QuotaAnalytics, display: (n: string) => string): string { + const rows: { rank: number; html: string }[] = []; + for (const p of a.pools) { + for (const w of p.windows) { + const pr = w.projection; + const atRisk = w.percent >= 80 || pr.state === "walled" || pr.state === "projected"; + if (!atRisk) continue; + const rank = pr.state === "walled" ? 0 : pr.state === "projected" ? 1 : 2; + const verdict = + pr.state === "walled" + ? `walled · unlocks ${fmtIso(w.resetsAt, a.now)}` + : pr.state === "projected" + ? `projected wall ${fmtWhen(pr.projectedWallAt)} (in ${fmtDuration(pr.durationUntilWallMs)}) · resets ${fmtIso(w.resetsAt, a.now)}` + : `${w.percent.toFixed(0)}% · no measured wall before reset · resets ${fmtIso(w.resetsAt, a.now)}`; + const still = + p.unlock && p.bindingWindow === w.name && p.unlock.stillWalledAfter.length + ? ` · after unlock: ${p.unlock.stillWalledAfter.map((s) => esc(s.name)).join(", ")} still walled` + : ""; + rows.push({ + rank, + html: `
${esc(display(p.provider))} · ${esc(p.plan)} — ${esc(w.name)} — ${w.percent.toFixed(0)}% of limit used · ${verdict}${still}
`, + }); + } + } + rows.sort((x, y) => x.rank - y.rank); + if (!rows.length) return `
At risk — no pool window is walled, projected to wall, or over 80%.
`; + return rows.map((r) => r.html).join(""); +} + +function shareTable(title: string, groups: { label: string; calls: number; tokens: number; extra?: string }[]): string { + const totalCalls = groups.reduce((s, g) => s + g.calls, 0); + const totalTokens = groups.reduce((s, g) => s + g.tokens, 0); + const rows = groups + .map((g) => { + const share = totalCalls > 0 ? (g.calls / totalCalls) * 100 : 0; + return `${esc(g.label)}${fmtN(g.calls)} ${share.toFixed(0)}%${fmtN(g.tokens)}${totalTokens > 0 ? ((g.tokens / totalTokens) * 100).toFixed(0) : "0"}%${g.extra ? `${g.extra}` : ""}`; + }) + .join(""); + return `

${esc(title)}

${groups[0]?.extra ? "" : ""}${rows}
CallsCall shareTokensToken shareDetail
`; +} + +function barStrip(values: { label: string; value: number; note?: string }[]): string { + const max = Math.max(1, ...values.map((v) => v.value)); + return `
${values + .map( + (v) => + `
${esc(v.label)}: ${fmtN(v.value)}${v.note ? ` ${esc(v.note)}` : ""}
`, + ) + .join("")}
`; +} + +export function analyticsSectionHtml(a: QuotaAnalytics, display: (n: string) => string): string { + if (!a.dbAvailable) { + return ( + `

Analytics & projection

` + + `
Analytics unavailable — the OpenCode route ledger could not be read on this host right now. ` + + `Pool state above still comes from the quota gatherer. Source: route_attempt ledger (opencode.db), read-only.
` + ); + } + const totals = a.totals; + const modelGroups = a.byModel7d.slice(0, 12).map((g) => { + const r = tokenRatios(g); + return { + label: g.label, + calls: g.calls, + tokens: r.total, + extra: `in:out ${r.inPerOut != null ? `${r.inPerOut.toFixed(1)}:1` : "—"} · cache ${r.cacheSharePct != null ? `${r.cacheSharePct.toFixed(0)}%` : "—"}${g.costRows ? ` · $${g.costUsd.toFixed(2)} recorded` : ""}`, + }; + }); + const effortGroups = a.byEffort7d.map((g) => ({ label: g.label, calls: g.calls, tokens: tokenRatios(g).total })); + const legGroups = a.byLeg7d.slice(0, 12).map((g) => ({ label: display(g.label), calls: g.calls, tokens: tokenRatios(g).total })); + const act = a.activity7d; + const activityHtml = act + ? `
sessions (7d): ${fmtN(act.sessions)} · root ${fmtN(act.rootSessions)} · sub-sessions ${fmtN(act.subSessions)} · user turns ${fmtN(act.turns)}
` + + `
tool calls (7d): ${fmtN(act.toolCallsTotal)} · ${act.topTools.map((t) => `${esc(t.name)} ${fmtN(t.count)}`).join(" · ")}
` + + `
skill use (7d): ${fmtN(act.skillTotal)}${act.topSkills.length ? ` · ${act.topSkills.map((s) => `${esc(s.name)} ${fmtN(s.count)}`).join(" · ")}` : ""}
` + + `
mcpx (7d): ${act.mcpx.length ? act.mcpx.map((m) => `${esc(m.name)} ${fmtN(m.count)}`).join(" · ") : "no direct mcpx tool calls"} · execute gateway (code-tool calls): ${fmtN(act.executeGateway)}
` + + `
fleet binary (7d, inferred from shell inputs — no invocation ledger exists): ${fmtN(act.fleetInferredTotal)}${act.fleetInferred.length ? ` · ${act.fleetInferred.map((f) => `fleet ${esc(f.subcommand)} ${fmtN(f.count)}`).join(" · ")}` : ""}
` + : `
activity scan (sessions, tools, skills, mcpx, fleet) is still computing — reload in about a minute.
`; + const dowNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + return ( + `

Analytics & projection

` + + `

Key values first: what is walled, what walls next and when, what unlocks at each reset and what stays walled. ` + + `Burn from the route_attempt ledger (${a.attemptsFrom ? esc(a.attemptsFrom.slice(0, 10)) : "—"} → ${a.attemptsTo ? esc(a.attemptsTo.slice(0, 10)) : "—"}); ` + + `projections from dated quota reads in the snapshot store. Sections: ` + + `at-risk summary · pool projections · breakdowns · time patterns · activity · ` + + `data: /api/quota-analytics.json · prices: model review · rules: model choice

` + + `

At-risk summary

${summaryStrip(a, display)}` + + `
All-route burn
` + + burnLine("last hour", totals.lastHour) + + burnLine("today", totals.today) + + burnLine("last 7 days", totals.last7d) + + `
7d tokens${fmtWow(a.totalsWowTokens, "")} · credential id recorded on ${a.credentialCoveragePct != null ? a.credentialCoveragePct.toFixed(0) : "—"}% of 7d calls (pool attribution coverage)
` + + `
` + + `

Pool projections

${a.pools.map((p) => poolCard(p, a.now, display)).join("")}` + + `

Breakdowns — last 7 days

` + + shareTable("Model usage ratio", modelGroups) + + shareTable("Effort (variant)", effortGroups) + + shareTable("Provider legs", legGroups) + + `

Time patterns

` + + `

Hour of day (calls, last 7d, local)

${barStrip(a.hourly7d.map((h) => ({ label: `${String(h.hour).padStart(2, "0")}:00`, value: h.calls })))}` + + `

Day of week (calls, all recorded history)

${barStrip(a.dowHistory.map((d) => ({ label: dowNames[d.dow] ?? `${d.dow}`, value: d.calls, note: `${fmtN(d.tokens)} tok` })))}` + + `

Daily (last 21 days)

${barStrip(a.daily21d.map((d) => ({ label: d.day, value: d.calls, note: `${fmtN(d.tokens)} tok${d.holiday ? ` · ${d.holiday}` : ""}` })))}` + + `

Activity

${activityHtml}
` + ); +} diff --git a/pm-stack/aggregator/src/quota-analytics.test.ts b/pm-stack/aggregator/src/quota-analytics.test.ts new file mode 100644 index 0000000000..a1f1eb1203 --- /dev/null +++ b/pm-stack/aggregator/src/quota-analytics.test.ts @@ -0,0 +1,158 @@ +import { describe, expect, test } from "bun:test"; +import { + fmtDuration, + projectWindow, + tokenRatios, + unlockPicture, + usFederalHoliday, + wowDelta, + type PctPoint, +} from "./quota-analytics.ts"; + +const H = 3_600_000; +const NOW = Date.parse("2026-11-13T12:00:00Z"); +const RESET = "2026-11-17T21:22:46.000Z"; // _openai.main weekly reset + +function series(pcts: number[], startAgoH: number, resetsAt: string | null = RESET): PctPoint[] { + return pcts.map((pct, i) => ({ + ts: NOW - startAgoH * H + (i * (startAgoH * H)) / Math.max(1, pcts.length - 1), + pct, + resetsAt, + })); +} + +describe("projectWindow", () => { + test("already walled: state walled, zero duration, walls before reset", () => { + const p = projectWindow({ points: [], pctNow: 100, resetsAt: RESET, now: NOW }); + expect(p.state).toBe("walled"); + expect(p.durationUntilWallMs).toBe(0); + expect(p.wallsBeforeReset).toBe(true); + }); + + test("steady measured burn projects the wall before the reset", () => { + // 50% -> 75% over the last 10 hours = 2.5 pts/h; 25 points remain + // => wall in 10h, well before the reset ~4.4 days out. + const p = projectWindow({ points: series([50, 62.5, 75], 10), pctNow: 75, resetsAt: RESET, now: NOW }); + expect(p.state).toBe("projected"); + expect(p.ratePtsPerHour).toBeCloseTo(2.5, 5); + expect(p.durationUntilWallMs).toBeCloseTo(10 * H, -4); + expect(p.projectedWallAt).toBeCloseTo(NOW + 10 * H, -4); + expect(p.wallsBeforeReset).toBe(true); + expect(p.samples).toBe(3); + }); + + test("slow burn that would wall only after the reset is no-wall-before-reset", () => { + // 0.1 pts/h from 90%: wall in 100h, reset in ~105h... use a reset + // 24h out so the wall clearly lands after it. + const reset = new Date(NOW + 24 * H).toISOString(); + const pts = series([88, 89, 90], 20, reset); + const p = projectWindow({ points: pts, pctNow: 90, resetsAt: reset, now: NOW }); + expect(p.ratePtsPerHour).toBeCloseTo(0.1, 5); + expect(p.state).toBe("no-wall-before-reset"); + expect(p.wallsBeforeReset).toBe(false); + expect(p.projectedWallAt).toBeGreaterThan(NOW + 24 * H); + }); + + test("flat burn never walls", () => { + const p = projectWindow({ points: series([40, 40, 40], 6), pctNow: 40, resetsAt: RESET, now: NOW }); + expect(p.state).toBe("no-wall-before-reset"); + expect(p.projectedWallAt).toBeNull(); + expect(p.reason).toContain("flat"); + }); + + test("one reading is insufficient history, never a guess", () => { + const p = projectWindow({ points: series([80], 1), pctNow: 80, resetsAt: RESET, now: NOW }); + expect(p.state).toBe("insufficient-history"); + expect(p.projectedWallAt).toBeNull(); + expect(p.samples).toBe(1); + }); + + test("readings from a previous reset period do not join the fit", () => { + const old = series([10, 90], 30, "2026-11-10T21:22:46.000Z"); + const p = projectWindow({ points: old, pctNow: 75, resetsAt: RESET, now: NOW }); + expect(p.state).toBe("insufficient-history"); + expect(p.samples).toBe(0); + }); + + test("reset instants jittered by seconds still count as one period", () => { + // The Claude gatherer reports the same reset as ...59.304Z, + // ...00.255Z etc. on consecutive reads; the fit must not split. + const pts: PctPoint[] = [ + { ts: NOW - 10 * H, pct: 50, resetsAt: "2026-11-17T21:22:45.900Z" }, + { ts: NOW - 5 * H, pct: 62.5, resetsAt: "2026-11-17T21:22:46.400Z" }, + { ts: NOW, pct: 75, resetsAt: "2026-11-17T21:22:46.000Z" }, + ]; + const p = projectWindow({ points: pts, pctNow: 75, resetsAt: RESET, now: NOW }); + expect(p.state).toBe("projected"); + expect(p.samples).toBe(3); + }); + + test("readings packed inside 10 minutes are insufficient", () => { + const pts: PctPoint[] = [ + { ts: NOW - 5 * 60_000, pct: 70, resetsAt: RESET }, + { ts: NOW - 60_000, pct: 71, resetsAt: RESET }, + ]; + const p = projectWindow({ points: pts, pctNow: 71, resetsAt: RESET, now: NOW }); + expect(p.state).toBe("insufficient-history"); + }); +}); + +describe("wowDelta", () => { + test("absolute and percent", () => { + expect(wowDelta(150, 100)).toEqual({ abs: 50, pct: 50 }); + expect(wowDelta(80, 100)).toEqual({ abs: -20, pct: -20 }); + }); + test("zero previous yields null pct, not Infinity", () => { + expect(wowDelta(10, 0)).toEqual({ abs: 10, pct: null }); + expect(wowDelta(0, 0)).toEqual({ abs: 0, pct: null }); + }); +}); + +describe("tokenRatios", () => { + test("in-per-out and cache share", () => { + const r = tokenRatios({ input: 1000, output: 250, reasoning: 0, cacheRead: 3000, cacheWrite: 0 }); + expect(r.inPerOut).toBe(4); + expect(r.cacheSharePct).toBe(75); + expect(r.total).toBe(4250); + }); + test("no output / no input side yields nulls", () => { + const r = tokenRatios({ input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0 }); + expect(r.inPerOut).toBeNull(); + expect(r.cacheSharePct).toBeNull(); + expect(r.total).toBe(0); + }); +}); + +describe("unlockPicture", () => { + const wins = [ + { name: "weekly", percent: 100, resetsAt: "2026-11-17T21:22:46.000Z" }, + { name: "5-hour", percent: 0, resetsAt: "2026-11-13T12:30:00.000Z" }, + { name: "monthly", percent: 100, resetsAt: "2026-12-03T00:00:00.000Z" }, + ]; + test("what frees at the binding reset and what stays walled", () => { + const u = unlockPicture(wins, wins[0]); + expect(u.bindingResetsAt).toBe("2026-11-17T21:22:46.000Z"); + expect(u.freesAtReset).toEqual(["weekly"]); + expect(u.stillWalledAfter).toEqual([{ name: "monthly", resetsAt: "2026-12-03T00:00:00.000Z" }]); + }); + test("a walled window with no reset stays walled", () => { + const ws = [...wins, { name: "api", percent: 100, resetsAt: null }]; + const u = unlockPicture(ws, wins[0]); + expect(u.stillWalledAfter.map((w) => w.name)).toContain("api"); + }); +}); + +describe("fmtDuration + holidays", () => { + test("durations", () => { + expect(fmtDuration(null)).toBe("—"); + expect(fmtDuration(0)).toBe("now"); + expect(fmtDuration(42 * 60_000)).toBe("42m"); + expect(fmtDuration(5 * H + 12 * 60_000)).toBe("5h 12m"); + expect(fmtDuration(4 * 24 * H + 8 * H)).toBe("4d 8h"); + }); + test("holidays are labelled, ordinary days are not", () => { + expect(usFederalHoliday("2026-11-26")).toBe("Thanksgiving"); + expect(usFederalHoliday("2026-11-11")).toBe("Veterans Day"); + expect(usFederalHoliday("2026-11-13")).toBeNull(); + }); +}); diff --git a/pm-stack/aggregator/src/quota-analytics.ts b/pm-stack/aggregator/src/quota-analytics.ts new file mode 100644 index 0000000000..1966f880f6 --- /dev/null +++ b/pm-stack/aggregator/src/quota-analytics.ts @@ -0,0 +1,284 @@ +// Analytics + projection math for the /quota "Analytics & projection" +// section (Drew's order, 2026-11-13). Pure functions over plain +// values — no I/O, no clock reads except through arguments. The data +// layer is analytics-store.ts; rendering is quota-analytics-view.ts. +// +// Honesty rules (mirroring burn-history.ts / quota-exhaustion.ts): +// a projection that cannot be measured is an explicit state with a +// reason — never an invented date, never "safe". + +/** One dated percent reading of one pool window. */ +export interface PctPoint { + /** Observation instant, ms epoch. */ + ts: number; + /** Percent of the window's limit used at that instant, 0..100+. */ + pct: number; + /** The window's reset instant as reported with that reading; two + * readings belong to the same reset period only when their resets + * agree within PROJECTION_PERIOD_TOLERANCE_MS (gatherers jitter + * the reported reset by seconds between reads — string equality + * would split one period into hundreds). */ + resetsAt: string | null; +} + +export type ProjectionState = + /** Percent is already at/over the limit. */ + | "walled" + /** Measured burn crosses 100% before the reset. */ + | "projected" + /** Measured burn does not cross 100% before the reset (or the + * window has no reset to cross before). */ + | "no-wall-before-reset" + /** Not enough same-period readings to measure a rate. */ + | "insufficient-history"; + +export interface WindowProjection { + state: ProjectionState; + /** Measured burn in percentage points per hour: the least-squares + * slope of the same-period readings inside the fit window. Null + * when no rate was measured. */ + ratePtsPerHour: number | null; + /** Same-period readings behind the rate. */ + samples: number; + /** Projected instant the window reaches 100%, when a positive rate + * was measured (may fall after the reset — the caller decides how + * to present that; the state already says so). */ + projectedWallAt: number | null; + /** now -> projected wall in ms; 0 when already walled; null when + * no positive rate was measured. */ + durationUntilWallMs: number | null; + /** Whether the projected wall lands before the reset, when both + * exist. True when already walled. */ + wallsBeforeReset: boolean | null; + /** Why no projection exists, when state is "insufficient-history" + * or the rate is flat/falling. */ + reason?: string; +} + +/** Minimum span of readings before a slope means anything. */ +export const PROJECTION_MIN_SPAN_MS = 10 * 60_000; +/** Two reset instants closer than this are the same period: the + * shortest real window is 5h, so adjacent periods always differ by + * at least that, while one period's reported reset jitters by + * seconds. */ +export const PROJECTION_PERIOD_TOLERANCE_MS = 2 * 60 * 60_000; + +function samePeriod(pointResetsAt: string | null, liveResetsAt: string | null): boolean { + if (liveResetsAt == null) return true; + if (pointResetsAt == null) return false; + const a = Date.parse(pointResetsAt); + const b = Date.parse(liveResetsAt); + if (!Number.isFinite(a) || !Number.isFinite(b)) return pointResetsAt === liveResetsAt; + return Math.abs(a - b) <= PROJECTION_PERIOD_TOLERANCE_MS; +} +/** Only readings inside this trailing window join a fit: older burn + * says little about the current pace, and the same-period filter + * bounds the fit to the live reset period anyway. */ +export const PROJECTION_FIT_WINDOW_MS = 24 * 60 * 60_000; + +/** + * Project one pool window from its percent-reading series. + * + * The fit uses only readings from the CURRENT reset period (same + * resetsAt as the live window) inside the trailing fit window — a + * pair straddling a reset measures the reset, not the burn. + */ +export function projectWindow(args: { + points: PctPoint[]; + pctNow: number; + resetsAt: string | null; + now: number; +}): WindowProjection { + const { pctNow, resetsAt, now } = args; + if (pctNow >= 100) { + return { + state: "walled", + ratePtsPerHour: null, + samples: 0, + projectedWallAt: null, + durationUntilWallMs: 0, + wallsBeforeReset: true, + }; + } + const period = args.points + .filter( + (p) => + p.ts <= now && + now - p.ts <= PROJECTION_FIT_WINDOW_MS && + samePeriod(p.resetsAt, resetsAt) && + Number.isFinite(p.pct), + ) + .sort((a, b) => a.ts - b.ts); + if (period.length < 2 || period[period.length - 1].ts - period[0].ts < PROJECTION_MIN_SPAN_MS) { + return { + state: "insufficient-history", + ratePtsPerHour: null, + samples: period.length, + projectedWallAt: null, + durationUntilWallMs: null, + wallsBeforeReset: null, + reason: "fewer than two same-period readings spanning 10 minutes", + }; + } + const n = period.length; + const meanTs = period.reduce((s, p) => s + p.ts, 0) / n; + const meanPct = period.reduce((s, p) => s + p.pct, 0) / n; + let num = 0; + let den = 0; + for (const p of period) { + num += (p.ts - meanTs) * (p.pct - meanPct); + den += (p.ts - meanTs) ** 2; + } + const ratePtsPerHour = den > 0 ? (num / den) * 3_600_000 : 0; + if (!(ratePtsPerHour > 0)) { + return { + state: "no-wall-before-reset", + ratePtsPerHour, + samples: n, + projectedWallAt: null, + durationUntilWallMs: null, + wallsBeforeReset: false, + reason: "measured burn is flat or falling", + }; + } + const wallAt = now + ((100 - pctNow) / ratePtsPerHour) * 3_600_000; + const resetMs = resetsAt ? Date.parse(resetsAt) : NaN; + const wallsBeforeReset = Number.isFinite(resetMs) ? wallAt < resetMs : null; + return { + state: wallsBeforeReset === false ? "no-wall-before-reset" : "projected", + ratePtsPerHour, + samples: n, + projectedWallAt: wallAt, + durationUntilWallMs: wallAt - now, + wallsBeforeReset, + }; +} + +/** Absolute + percent difference of a current value vs a previous + * (e.g. same window last week). pct is null when the previous value + * is 0 — an honest absence, not Infinity. */ +export interface WowDelta { + abs: number; + pct: number | null; +} + +export function wowDelta(current: number, previous: number): WowDelta { + const abs = current - previous; + return { abs, pct: previous !== 0 ? (abs / Math.abs(previous)) * 100 : null }; +} + +/** Token totals as recorded by the route proxy (route_attempt): + * `input` excludes cache reads/writes where the provider reports + * them separately — the columns are presented as recorded. */ +export interface TokenTotals { + input: number; + output: number; + reasoning: number; + cacheRead: number; + cacheWrite: number; +} + +export const EMPTY_TOKENS: TokenTotals = { input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0 }; + +export function totalTokens(t: TokenTotals): number { + return t.input + t.output + t.reasoning + t.cacheRead + t.cacheWrite; +} + +export interface TokenRatios { + /** Uncached input tokens per output token; null with no output. */ + inPerOut: number | null; + /** Cache reads as a percent of all input-side tokens + * (input + cacheRead + cacheWrite); null with no input side. */ + cacheSharePct: number | null; + total: number; +} + +export function tokenRatios(t: TokenTotals): TokenRatios { + const inputSide = t.input + t.cacheRead + t.cacheWrite; + return { + inPerOut: t.output > 0 ? t.input / t.output : null, + cacheSharePct: inputSide > 0 ? (t.cacheRead / inputSide) * 100 : null, + total: totalTokens(t), + }; +} + +/** One quota window as the unlock picture needs it. */ +export interface WindowLike { + name: string; + percent: number; + resetsAt: string | null; +} + +export interface UnlockPicture { + /** The binding (gating) window's reset — when the pool unlocks. */ + bindingResetsAt: string | null; + /** Names of windows that free up at that same reset. */ + freesAtReset: string[]; + /** Windows still at/over 100% after that reset (later or no + * reset): what stays walled when the binding window unlocks. */ + stillWalledAfter: { name: string; resetsAt: string | null }[]; +} + +/** + * The unlock picture for one pool, relative to its binding window + * (the window that gates the pool — the caller picks it, normally + * the fullest or the one projected to wall first): what frees when + * the binding window resets, and what stays walled past it. + */ +export function unlockPicture(windows: WindowLike[], binding: WindowLike): UnlockPicture { + const bindingResetsAt = binding.resetsAt; + const freesAtReset = windows + .filter((w) => w.resetsAt != null && w.resetsAt === bindingResetsAt) + .map((w) => w.name); + const bindingMs = bindingResetsAt ? Date.parse(bindingResetsAt) : NaN; + const stillWalledAfter = windows + .filter((w) => { + if (w === binding || w.percent < 100) return false; + if (w.resetsAt == null) return true; + if (!Number.isFinite(bindingMs)) return false; + return Date.parse(w.resetsAt) > bindingMs; + }) + .map((w) => ({ name: w.name, resetsAt: w.resetsAt })); + return { bindingResetsAt, freesAtReset, stillWalledAfter }; +} + +/** Compact duration for key-value rows: "4d 8h", "5h 12m", "42m". */ +export function fmtDuration(ms: number | null): string { + if (ms == null || !Number.isFinite(ms)) return "—"; + if (ms <= 0) return "now"; + const minutes = Math.round(ms / 60_000); + if (minutes < 60) return `${minutes}m`; + const hours = Math.floor(minutes / 60); + const days = Math.floor(hours / 24); + if (days > 0) return `${days}d ${hours % 24}h`; + return `${hours}h ${minutes % 60}m`; +} + +/** + * US federal holidays (the observed federal calendar), keyed by + * local ISO day. Only the years the route-attempt history covers + * are tabled; an untabled day is simply unannotated, never guessed. + */ +const US_FEDERAL_HOLIDAYS: Record = { + "2025-10-13": "Columbus Day", + "2025-11-11": "Veterans Day", + "2025-11-27": "Thanksgiving", + "2025-12-25": "Christmas", + "2026-01-01": "New Year's Day", + "2026-01-19": "MLK Day", + "2026-02-16": "Presidents Day", + "2026-05-25": "Memorial Day", + "2026-06-19": "Juneteenth", + "2026-07-03": "Independence Day (observed)", + "2026-09-07": "Labor Day", + "2026-10-12": "Columbus Day", + "2026-11-11": "Veterans Day", + "2026-11-26": "Thanksgiving", + "2026-12-25": "Christmas", + "2027-01-01": "New Year's Day", + "2027-01-18": "MLK Day", +}; + +export function usFederalHoliday(isoDay: string): string | null { + return US_FEDERAL_HOLIDAYS[isoDay] ?? null; +} diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 89eec4c006..f2b707db07 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -1,6 +1,7 @@ // Pure HTML rendering. Every view function takes already-assembled data and // returns a full HTML string — nothing here does I/O, which keeps the smoke // tests cheap (render from fixtures and assert on output). +import { analyticsSectionHtml } from "./quota-analytics-view.ts"; import { type AttentionView, type RoadmapGrain, @@ -2329,6 +2330,10 @@ export function renderQuota( /** Lazy-refresh state (#1171): renders the "refreshing" marker and the * manual refresh-now control. Absent means no request was made. */ refresh?: import("./quota-refresh.ts").RefreshStatus, + /** Analytics & projection model (2026-11-13): built by the server + * from the route ledger + snapshot store; absent/null renders no + * section (older callers and tests are unaffected). */ + analytics?: import("./analytics-store.ts").QuotaAnalytics | null, ): string { // "-direct" display rule (#6125): judged over every provider name/id // this surface renders — pool providers, pool ids, burn rows, the @@ -2421,7 +2426,7 @@ export function renderQuota( .join(""); const choices = (list: string[]) => (list.length ? list.map((id) => esc(display(id))).join(", ") : "—"); const burnAndChoices = `

Burn between resets

${burn || ''}
Burn between resets
ProviderPoolFromToTokens
none
-

Model choice

+

Model choice

Model choice rules
RulePools
Model choice rules
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)}
`; @@ -2433,6 +2438,7 @@ ${credentialLifecycle} ${providerAuthSection} ${quotaRefreshHtml(refresh, view.gatherer?.generatedAt ?? null)}

Pools

${pools} +${analytics ? analyticsSectionHtml(analytics, display) : ""} ${burnAndChoices}`, provenance, "/quota", @@ -2477,6 +2483,7 @@ ${credentialLifecycle} ${providerAuthSection} ${quotaRefreshHtml(refresh, view.gatherer?.generatedAt ?? null)}

Token quotas

${pools} +${analytics ? analyticsSectionHtml(analytics, display) : ""} ${paygCardHtml(usage)}

SaaS & services

${groups || '

No services extracted yet.

'}${uninstrumentedServicesHtml(usage.uninstrumentedServices ?? [])} ${chargesStripHtml(usage)} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 137ac8f186..b8255d1210 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -8,6 +8,7 @@ // apply actions; the dashboard only records them. import { readFile, stat } from "node:fs/promises"; import { createQuotaRefresher, systemdTrigger } from "./quota-refresh.ts"; +import { buildQuotaAnalytics, type QuotaAnalytics } from "./analytics-store.ts"; import { decodePathSegment } from "./path-segment.ts"; import { errorBoundaryResponse, notFoundResponse } from "./error-boundary.ts"; import { ACTION_STATES, ActionsStore, validateNewAction, type DashAction } from "./actions.ts"; @@ -2565,6 +2566,20 @@ async function handler(req: Request): Promise { }); } + if (path === "/api/quota-analytics.json") { + // The analytics & projection model behind /quota's section — + // the identical object the page renders from. + const [quota, usage] = await Promise.all([ + source.quota().catch(() => emptyQuotaView()), + source.usage().catch(() => emptyUsageView()), + ]); + try { + return json(buildQuotaAnalytics({ quota, usage, quotaCurrentPath: cfg.quotaCurrentFile })); + } catch { + return json({ error: "analytics unavailable" }, 503); + } + } + if (path === "/quota") { const [quota, usage] = await Promise.all([ source.quota().catch(() => emptyQuotaView()), @@ -2573,7 +2588,15 @@ async function handler(req: Request): Promise { // Never block on providers (#1171): decide from the stored measurement, // ask the gatherer to run in the background, render what we have. const refresh = quotaRefresher.request(quota); - return html(renderQuota(quota, prov(), usage, provDetail(), refresh)); + // Analytics fail-soft: a broken ledger read must never take the + // quota page down with it (the builder itself also degrades). + let analytics: QuotaAnalytics | null = null; + try { + analytics = buildQuotaAnalytics({ quota, usage, quotaCurrentPath: cfg.quotaCurrentFile }); + } catch { + analytics = null; + } + return html(renderQuota(quota, prov(), usage, provDetail(), refresh, analytics)); } if (req.method === "POST" && path === "/quota/refresh") {