Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)), "..");
Expand Down Expand Up @@ -727,12 +728,24 @@ async function main(): Promise<number> {
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);
Expand Down
8 changes: 8 additions & 0 deletions pm-stack/aggregator/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 };
}
Expand Down
199 changes: 199 additions & 0 deletions pm-stack/aggregator/src/provider-auth-alerts.ts
Original file line number Diff line number Diff line change
@@ -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<ProviderAuthProvider, string> = {
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<string, unknown>;
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<string, unknown>;
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<string> } = {},
): Promise<ProviderAuthAlert[]> {
const readText = opts.readText ?? ((p: string) => readFile(p, "utf8"));
const one = async (provider: ProviderAuthProvider): Promise<ProviderAuthAlert> => {
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")];
}
13 changes: 13 additions & 0 deletions pm-stack/aggregator/src/quota-current.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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));
Expand Down
22 changes: 22 additions & 0 deletions pm-stack/aggregator/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2177,6 +2177,26 @@ export function renderQuota(
})
.join("")}</div>`
: "";
// #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
? `<h2>Provider auth</h2><div class="card">${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 `<div><strong>${esc(a.provider)}</strong> <span class="badge error">${esc(a.reporting)}</span> <span class="muted">${detail}</span></div>`;
})
.join("")}</div>`
: "";
const pools = view.pools
.map((p) => {
const windows = p.windows
Expand Down Expand Up @@ -2226,6 +2246,7 @@ export function renderQuota(
"Quota + throughput",
`<h1>Quota + throughput</h1><p class="muted">All pooled quotas, resets, and burn rates. Machine-first: the same data is at <a href="/api/quota.json">/api/quota.json</a>.</p>
${credentialLifecycle}
${providerAuthSection}
${quotaRefreshHtml(refresh, view.gatherer?.generatedAt ?? null)}
<h2>Pools</h2>${pools}
${burnAndChoices}`,
Expand Down Expand Up @@ -2269,6 +2290,7 @@ ${burnAndChoices}`,
`<h1>Usage &amp; billing</h1><p class="muted">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: <a href="/api/quota.json">/api/quota.json</a>.</p>
${attentionStripHtml(usage)}
${credentialLifecycle}
${providerAuthSection}
${quotaRefreshHtml(refresh, view.gatherer?.generatedAt ?? null)}
<h2>Token quotas</h2>${pools}
${paygCardHtml(usage)}
Expand Down
Loading
Loading