diff --git a/pm-stack/aggregator/scripts/gather-quota.ts b/pm-stack/aggregator/scripts/gather-quota.ts index cef7782912..58003d6f57 100755 --- a/pm-stack/aggregator/scripts/gather-quota.ts +++ b/pm-stack/aggregator/scripts/gather-quota.ts @@ -121,6 +121,7 @@ import { import { SnapshotStore, isSnapshotRecord, snapshotKey } from "../src/snapshots.ts"; import { safeProviderReason } from "../src/credential-lifecycle.ts"; import { renewOpenDesignSession, type OpenDesignCredentialLike } from "../src/opendesign-renewal.ts"; +import { readProviderAuthAlerts } from "../src/provider-auth-alerts.ts"; import { renewMetaSession } from "../src/meta-renewal.ts"; const PKG = join(dirname(fileURLToPath(import.meta.url)), ".."); @@ -727,12 +728,24 @@ async function main(): Promise { durationMs: Date.now() - started, perProvider, }; + // #6671: embed the keeper alert projection so the board/readout + // surfaces a dying provider session within one gather cycle. The + // keepers ran earlier this tick; reading their state files back + // also covers a keeper that failed before writing (missing/stale + // project as "keeper not reporting", never silence). Fail-soft: + // the reader never throws. + const providerAuth = await readProviderAuthAlerts({ + opendesign: + process.env.OPENDESIGN_RENEWAL_STATE_PATH ?? join(dirname(currentPath), "opendesign-renewal.json"), + meta: process.env.META_RENEWAL_STATE_PATH ?? join(dirname(currentPath), "meta-renewal.json"), + }); const file: QuotaCurrentFile = { version: 1, generatedAt: tickAt, source: GATHERER_SOURCE, heartbeat, providers: entries, + providerAuth, }; await writeAtomic(currentPath, JSON.stringify(file, null, 2) + "\n"); await writeHeartbeat(heartbeat); diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index 8d5be5b08c..b621c7806c 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -331,6 +331,10 @@ export interface QuotaView { /** Gatherer overlay provenance (#1151); absent when no * quota-current.json was read. Additive for existing consumers. */ gatherer?: GathererSummary; + /** Provider-auth keeper alerts (#6671), carried from + * quota-current.json by overlayQuotaCurrent; the board renders + * every non-ok keeper. Absent when no gatherer file was read. */ + providerAuth?: import("./provider-auth-alerts.ts").ProviderAuthAlert[]; /** Feed-load sanitization counts (#2429/#3921): present only when the * loader dropped malformed pools, credentials, windows, active sessions, * or burn segments, so an @@ -1375,6 +1379,10 @@ export interface QuotaCurrentFile { source: string; heartbeat: QuotaGatherHeartbeat; providers: QuotaCurrentEntry[]; + /** Provider-auth keeper projection (#6671): both keepers' alert + * state, embedded by the gatherer from the renewal state files + * beside quota-current.json. Additive; absent on older files. */ + providerAuth?: import("./provider-auth-alerts.ts").ProviderAuthAlert[]; /** Parser diagnostics for malformed entries removed at the ingest boundary. */ sanitized?: { droppedProviders: number; droppedWindows: number }; } diff --git a/pm-stack/aggregator/src/provider-auth-alerts.ts b/pm-stack/aggregator/src/provider-auth-alerts.ts new file mode 100644 index 0000000000..3868f90c93 --- /dev/null +++ b/pm-stack/aggregator/src/provider-auth-alerts.ts @@ -0,0 +1,199 @@ +// Provider-auth keeper alerts (#6671): the board/readout projection of +// the two provider browser-auth keepers' state files — +// opendesign-renewal.json (src/opendesign-renewal.ts) and +// meta-renewal.json (src/meta-renewal.ts), written beside +// quota-current.json in the aggregator state dir. +// +// Why this exists: the keepers record `status: "attention"` + `alert` + +// `alertSince` when a provider session is dying, but before #6671 +// nothing outside the keeper modules and their tests read those files, +// so a failing renewal was invisible where a human looks every day — +// exactly the silent-expiry failure mode Drew's 2026-11-05 +// provider-auth rule exists to prevent. The gatherer embeds this +// projection in quota-current.json (one gather cycle), the overlay +// carries it onto the board's QuotaView, and renderQuota shows every +// non-ok keeper as a visible badge. +// +// Truth contract: a missing state file, an unparsable one, and a stale +// one (checkedAt older than PROVIDER_AUTH_STALE_MS) each project as +// their own visible reporting state — "keeper not reporting" — never +// as silence and never as ok. Only whitelisted status/alert fields are +// projected; no credential or session value is read or rendered (the +// state files do not carry any, and the whitelist keeps it that way). + +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; + +export type ProviderAuthProvider = "opendesign" | "meta"; + +export type ProviderAuthReporting = "attention" | "ok" | "missing" | "stale" | "invalid"; + +export interface ProviderAuthAlert { + provider: ProviderAuthProvider; + /** The keeper's own status string ("valid", "attention", ...), or + * null when no state could be read at all. */ + status: string | null; + alert: string | null; + alertSince: string | null; + checkedAt: string | null; + /** OpenDesign: when the current session expires (the horizon the + * keeper records). Null for meta / when unknown. */ + sessionExpiresAt: string | null; + /** OpenDesign: hours of session horizon left at checkedAt. */ + horizonHours: number | null; + /** Meta: the exporter's last good read. Null for opendesign. */ + lastGoodAt: string | null; + reporting: ProviderAuthReporting; +} + +/** Keepers run on every gather tick (15 min); a state file older than + * three ticks has missed runs — the keeper is not reporting. */ +export const PROVIDER_AUTH_STALE_MS = 45 * 60_000; + +export const PROVIDER_AUTH_FILES: Record = { + opendesign: "opendesign-renewal.json", + meta: "meta-renewal.json", +}; + +const str = (v: unknown): string | null => (typeof v === "string" ? v : null); +const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null); + +/** Project one keeper state document (parsed JSON, or null when the + * file could not be read) into the board shape. Pure. */ +export function projectKeeperState( + provider: ProviderAuthProvider, + doc: unknown, + now = new Date(), + staleMs = PROVIDER_AUTH_STALE_MS, +): ProviderAuthAlert { + const base: ProviderAuthAlert = { + provider, + status: null, + alert: null, + alertSince: null, + checkedAt: null, + sessionExpiresAt: null, + horizonHours: null, + lastGoodAt: null, + reporting: "missing", + }; + if (doc === null || doc === undefined) return base; + if (typeof doc !== "object" || Array.isArray(doc)) return { ...base, reporting: "invalid" }; + const rec = doc as Record; + const checkedAt = str(rec.checkedAt); + if (!checkedAt || Number.isNaN(Date.parse(checkedAt))) return { ...base, reporting: "invalid" }; + const out: ProviderAuthAlert = { + ...base, + status: str(rec.status), + alert: str(rec.alert), + alertSince: str(rec.alertSince), + checkedAt, + sessionExpiresAt: str(rec.sessionExpiresAt), + horizonHours: num(rec.horizonHours), + lastGoodAt: str(rec.lastGoodAt), + reporting: "ok", + }; + if (out.status === "attention" || out.alert) { + out.reporting = "attention"; + } else if (now.getTime() - Date.parse(checkedAt) > staleMs) { + out.reporting = "stale"; + } + return out; +} + +export function isProviderAuthAlert(v: unknown): v is ProviderAuthAlert { + if (typeof v !== "object" || v === null || Array.isArray(v)) return false; + const rec = v as Record; + return ( + (rec.provider === "opendesign" || rec.provider === "meta") && + (rec.reporting === "attention" || + rec.reporting === "ok" || + rec.reporting === "missing" || + rec.reporting === "stale" || + rec.reporting === "invalid") + ); +} + +/** The keepers that need a human's eye: everything not reporting ok. */ +export function providerAuthProblems(alerts: ProviderAuthAlert[]): ProviderAuthAlert[] { + return alerts.filter((a) => a.reporting !== "ok"); +} + +/** One human line per problem keeper, for readout/log surfaces. */ +export function providerAuthProblemLines(alerts: ProviderAuthAlert[]): string[] { + return providerAuthProblems(alerts).map((a) => { + switch (a.reporting) { + case "attention": { + const since = a.alertSince ? ` since ${a.alertSince}` : ""; + const horizon = a.sessionExpiresAt + ? `; session expires ${a.sessionExpiresAt}` + : a.lastGoodAt + ? `; last good ${a.lastGoodAt}` + : ""; + return `${a.provider} provider auth: ${a.alert ?? a.status ?? "attention"}${since}${horizon}`; + } + case "stale": + return `${a.provider} provider auth: keeper not reporting — last check ${a.checkedAt ?? "unknown"} is stale`; + case "invalid": + return `${a.provider} provider auth: keeper not reporting — state file is invalid`; + default: + return `${a.provider} provider auth: keeper not reporting — no state file`; + } + }); +} + +/** Re-derive freshness at serve time (#6671, Codex P2 on the first + * cut): the gather-time `reporting` classification freezes when the + * gatherer stops — a keeper whose last tick said ok would render ok + * forever. An ok keeper whose checkedAt is older than the stale + * horizon at serve time is reclassified stale; attention (already + * visible), missing, stale, and invalid pass through unchanged. */ +export function reevaluateProviderAuth( + alerts: ProviderAuthAlert[], + now = new Date(), + staleMs = PROVIDER_AUTH_STALE_MS, +): ProviderAuthAlert[] { + return alerts.map((a) => { + if (a.reporting !== "ok" || !a.checkedAt) return a; + return now.getTime() - Date.parse(a.checkedAt) > staleMs + ? { ...a, reporting: "stale" as const } + : a; + }); +} + +export interface ProviderAuthPaths { + opendesign: string; + meta: string; +} + +export function providerAuthPathsIn(dir: string): ProviderAuthPaths { + return { + opendesign: join(dir, PROVIDER_AUTH_FILES.opendesign), + meta: join(dir, PROVIDER_AUTH_FILES.meta), + }; +} + +/** Read both keeper state files and project them. A file that cannot + * be read projects as "missing"; one that cannot be parsed projects + * as "invalid" — the read distinguishes the two so a corrupt file is + * not mistaken for an absent keeper. */ +export async function readProviderAuthAlerts( + paths: ProviderAuthPaths, + opts: { now?: Date; staleMs?: number; readText?: (path: string) => Promise } = {}, +): Promise { + const readText = opts.readText ?? ((p: string) => readFile(p, "utf8")); + const one = async (provider: ProviderAuthProvider): Promise => { + let text: string; + try { + text = await readText(paths[provider]); + } catch { + return projectKeeperState(provider, null, opts.now, opts.staleMs); + } + try { + return projectKeeperState(provider, JSON.parse(text) as unknown, opts.now, opts.staleMs); + } catch { + return { ...projectKeeperState(provider, null, opts.now, opts.staleMs), reporting: "invalid" }; + } + }; + return [await one("opendesign"), await one("meta")]; +} diff --git a/pm-stack/aggregator/src/quota-current.ts b/pm-stack/aggregator/src/quota-current.ts index 6133afa5dc..025460dad1 100644 --- a/pm-stack/aggregator/src/quota-current.ts +++ b/pm-stack/aggregator/src/quota-current.ts @@ -19,6 +19,7 @@ // fresh ok entry wins over an error entry; otherwise the newest // entry decides the surfaced state. import { poolState } from "./derive.ts"; +import { isProviderAuthAlert, reevaluateProviderAuth } from "./provider-auth-alerts.ts"; import { lifecycleForEntry, safeProviderReason } from "./credential-lifecycle.ts"; import { computeChoices } from "./quota-guidance.ts"; import type { @@ -119,9 +120,17 @@ export function parseQuotaCurrent(doc: unknown): QuotaCurrentFile | null { windows: windows.values, }; }); + // #6671: the optional providerAuth section is isolated at this + // boundary like the provider list — a non-array value is dropped + // and malformed rows are filtered, so one bad section can never + // throw in the overlay and suppress the unrelated quota data. + const providerAuth = Array.isArray(doc.providerAuth) + ? doc.providerAuth.filter(isProviderAuthAlert) + : undefined; return { ...doc, providers: validProviders, + providerAuth, sanitized: { droppedProviders: providers.dropped, droppedWindows }, } as unknown as QuotaCurrentFile; } @@ -402,6 +411,10 @@ export function overlayQuotaCurrent(view: QuotaView, file: QuotaCurrentFile, now const allPools = [...pools, ...synthesized]; const out: QuotaView = { ...view, pools: allPools, gatherer: summarize(file, nowMs) }; + // #6671: keeper alerts ride the same overlay; malformed rows are + // dropped at this boundary like every other gatherer field. + if (Array.isArray(file.providerAuth)) + out.providerAuth = reevaluateProviderAuth(file.providerAuth.filter(isProviderAuthAlert), now); const credentialLifecycle = file.providers .filter((entry) => entry.credentialWatch === true) .map((entry) => lifecycleForEntry(entry, now)); diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 938119a10c..18cc3946a7 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -2177,6 +2177,26 @@ export function renderQuota( }) .join("")}` : ""; + // #6671: provider-auth keeper problems render as their own card — + // a dying provider session (or a keeper that stopped reporting) + // must be visible on the board, not only in a state file. All-ok + // keepers render nothing here (no alert, no noise). + const providerAuthProblems = (view.providerAuth ?? []).filter((a) => a.reporting !== "ok"); + const providerAuthSection = providerAuthProblems.length + ? `

Provider auth

${providerAuthProblems + .map((a) => { + const detail = + a.reporting === "attention" + ? `${esc(a.alert ?? a.status ?? "attention")}${a.alertSince ? ` · since ${fmtDate(a.alertSince)}` : ""}${a.sessionExpiresAt ? ` · session expires ${fmtDate(a.sessionExpiresAt)}` : ""}${a.lastGoodAt ? ` · last good ${fmtDate(a.lastGoodAt)}` : ""}` + : a.reporting === "stale" + ? `keeper not reporting · last check ${fmtDate(a.checkedAt)}` + : a.reporting === "invalid" + ? "keeper not reporting · state file invalid" + : "keeper not reporting · no state file"; + return `
${esc(a.provider)} ${esc(a.reporting)} ${detail}
`; + }) + .join("")}
` + : ""; const pools = view.pools .map((p) => { const windows = p.windows @@ -2226,6 +2246,7 @@ export function renderQuota( "Quota + throughput", `

Quota + throughput

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

${credentialLifecycle} +${providerAuthSection} ${quotaRefreshHtml(refresh, view.gatherer?.generatedAt ?? null)}

Pools

${pools} ${burnAndChoices}`, @@ -2269,6 +2290,7 @@ ${burnAndChoices}`, `

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)} ${credentialLifecycle} +${providerAuthSection} ${quotaRefreshHtml(refresh, view.gatherer?.generatedAt ?? null)}

Token quotas

${pools} ${paygCardHtml(usage)} diff --git a/pm-stack/aggregator/test/provider-auth-alerts.test.ts b/pm-stack/aggregator/test/provider-auth-alerts.test.ts new file mode 100644 index 0000000000..6ff98155b2 --- /dev/null +++ b/pm-stack/aggregator/test/provider-auth-alerts.test.ts @@ -0,0 +1,187 @@ +// #6671: the provider-auth keeper alert projection — fixture state +// files in the shapes the keepers actually write (following the +// keeper test patterns: injected clock, temp state files, no network). +// Cases: attention, valid, missing file, stale file, invalid file — +// plus the gather->overlay->board hops that carry the projection to +// the surface a human reads. + +import { describe, expect, test } from "bun:test"; +import { mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + providerAuthPathsIn, + providerAuthProblemLines, + readProviderAuthAlerts, +} from "../src/provider-auth-alerts.ts"; +import { overlayQuotaCurrent, parseQuotaCurrent } from "../src/quota-current.ts"; +import { renderQuota } from "../src/render.ts"; +import type { QuotaCurrentFile, QuotaView } from "../src/model.ts"; + +const NOW = new Date("2026-11-06T12:00:00.000Z"); +const iso = (msAgo: number) => new Date(NOW.getTime() - msAgo).toISOString(); + +const opendesignAttention = { + provider: "opendesign", + checkedAt: iso(5 * 60_000), + status: "attention", + sessionExpiresAt: iso(-48 * 3_600_000), + horizonHours: 48, + capture: { attempted: true, result: "failed" }, + alert: "OpenDesign session expires in 48h and browser capture failed", + alertSince: iso(3_600_000), +}; + +const metaValid = { + provider: "meta", + checkedAt: iso(5 * 60_000), + status: "valid", + exporterStatus: "ok", + lastGoodAt: iso(5 * 60_000), + recovery: { attempted: false, result: null }, + alert: null, + alertSince: null, +}; + +async function fixtureDir(files: Record): Promise { + const dir = await mkdtemp(join(tmpdir(), "provider-auth-")); + for (const [name, doc] of Object.entries(files)) { + await writeFile(join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc)); + } + return dir; +} + +describe("readProviderAuthAlerts", () => { + test("attention state projects as attention, naming alertSince and the horizon", async () => { + const dir = await fixtureDir({ "opendesign-renewal.json": opendesignAttention, "meta-renewal.json": metaValid }); + const alerts = await readProviderAuthAlerts(providerAuthPathsIn(dir), { now: NOW }); + const od = alerts.find((a) => a.provider === "opendesign")!; + expect(od.reporting).toBe("attention"); + expect(od.alertSince).toBe(opendesignAttention.alertSince); + expect(od.sessionExpiresAt).toBe(opendesignAttention.sessionExpiresAt); + const lines = providerAuthProblemLines(alerts); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain("opendesign"); + expect(lines[0]).toContain(opendesignAttention.alertSince); + }); + + test("both keepers valid: no problems, no alert lines", async () => { + const odValid = { ...opendesignAttention, status: "valid", alert: null, alertSince: null }; + const dir = await fixtureDir({ "opendesign-renewal.json": odValid, "meta-renewal.json": metaValid }); + const alerts = await readProviderAuthAlerts(providerAuthPathsIn(dir), { now: NOW }); + expect(alerts.map((a) => a.reporting)).toEqual(["ok", "ok"]); + expect(providerAuthProblemLines(alerts)).toEqual([]); + }); + + test("missing files project as keeper-not-reporting, never silence", async () => { + const dir = await fixtureDir({}); + const alerts = await readProviderAuthAlerts(providerAuthPathsIn(dir), { now: NOW }); + expect(alerts.map((a) => a.reporting)).toEqual(["missing", "missing"]); + const lines = providerAuthProblemLines(alerts); + expect(lines).toHaveLength(2); + expect(lines[0]).toContain("keeper not reporting"); + }); + + test("stale file projects as stale even when its last status was valid", async () => { + const staleMeta = { ...metaValid, checkedAt: iso(2 * 3_600_000) }; + const dir = await fixtureDir({ "opendesign-renewal.json": { ...opendesignAttention, status: "valid", alert: null, alertSince: null }, "meta-renewal.json": staleMeta }); + const alerts = await readProviderAuthAlerts(providerAuthPathsIn(dir), { now: NOW }); + expect(alerts.find((a) => a.provider === "meta")!.reporting).toBe("stale"); + expect(providerAuthProblemLines(alerts)[0]).toContain("keeper not reporting"); + }); + + test("invalid file projects as invalid, distinct from missing", async () => { + const dir = await fixtureDir({ "opendesign-renewal.json": "{not json", "meta-renewal.json": metaValid }); + const alerts = await readProviderAuthAlerts(providerAuthPathsIn(dir), { now: NOW }); + expect(alerts.find((a) => a.provider === "opendesign")!.reporting).toBe("invalid"); + }); + + test("projection whitelists fields: an extra value in the state file never rides along", async () => { + const poisoned = { ...opendesignAttention, cookie: "session-secret-value", token: "abc" }; + const dir = await fixtureDir({ "opendesign-renewal.json": poisoned, "meta-renewal.json": metaValid }); + const alerts = await readProviderAuthAlerts(providerAuthPathsIn(dir), { now: NOW }); + expect(JSON.stringify(alerts)).not.toContain("session-secret-value"); + expect(JSON.stringify(alerts)).not.toContain("abc"); + }); +}); + +describe("gather -> overlay -> board", () => { + const file = (): QuotaCurrentFile => + parseQuotaCurrent({ + version: 1, + generatedAt: NOW.toISOString(), + source: "test", + heartbeat: { tickAt: NOW.toISOString(), ok: true, durationMs: 1, perProvider: {} }, + providers: [], + providerAuth: [ + { + provider: "meta", + status: "attention", + alert: "meta session expired and exporter recovery failed", + alertSince: iso(3_600_000), + checkedAt: iso(60_000), + sessionExpiresAt: null, + horizonHours: null, + lastGoodAt: iso(86_400_000), + reporting: "attention", + }, + ], + })!; + + const view = (): QuotaView => ({ pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }); + + test("overlay carries providerAuth onto the quota view", () => { + const out = overlayQuotaCurrent(view(), file(), NOW); + expect(out.providerAuth).toHaveLength(1); + expect(out.providerAuth![0].provider).toBe("meta"); + }); + + test("board renders the attention alert with provider and alertSince", () => { + const out = overlayQuotaCurrent(view(), file(), NOW); + const html = renderQuota(out, {} as never); + expect(html).toContain("Provider auth"); + expect(html).toContain("meta session expired and exporter recovery failed"); + }); + + test("a non-array providerAuth section is isolated at parse, never throws in the overlay", () => { + const bad = parseQuotaCurrent({ + version: 1, + generatedAt: NOW.toISOString(), + source: "test", + heartbeat: { tickAt: NOW.toISOString(), ok: true, durationMs: 1, perProvider: {} }, + providers: [], + providerAuth: { provider: "meta" }, + })!; + expect(bad.providerAuth).toBeUndefined(); + expect(() => overlayQuotaCurrent(view(), bad, NOW)).not.toThrow(); + }); + + test("serve-time freshness: an ok keeper past the stale horizon reclassifies as stale", () => { + const staleFile = file(); + staleFile.providerAuth = [ + { + provider: "meta", + status: "valid", + alert: null, + alertSince: null, + checkedAt: iso(2 * 3_600_000), + sessionExpiresAt: null, + horizonHours: null, + lastGoodAt: iso(2 * 3_600_000), + reporting: "ok", + }, + ]; + const out = overlayQuotaCurrent(view(), staleFile, NOW); + expect(out.providerAuth![0].reporting).toBe("stale"); + expect(renderQuota(out, {} as never)).toContain("keeper not reporting"); + }); + + test("board renders nothing when every keeper is ok", () => { + const okFile = file(); + okFile.providerAuth = [ + { ...okFile.providerAuth![0], status: "valid", alert: null, alertSince: null, reporting: "ok" }, + ]; + const html = renderQuota(overlayQuotaCurrent(view(), okFile, NOW), {} as never); + expect(html).not.toContain("Provider auth"); + }); +});