From 84f040396956d708b3a6a264aae77b019dff2e47 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 18:32:32 -0600 Subject: [PATCH 1/5] fix(quota-plane): render lapsed OpenCode Go workspace as lapsed, not error (#1161) A configured opencode-go result carrying 'No active OpenCode Go subscription' now maps to entry state lapsed, propagates through pool splits, survives ingest validation, and renders as a terminal non-error lapse with no stale percentages. --- pm-stack/aggregator/scripts/gather-quota.ts | 13 ++++++-- pm-stack/aggregator/src/assets/app.css | 5 ++++ .../aggregator/src/credential-lifecycle.ts | 5 +++- pm-stack/aggregator/src/digest.ts | 15 ++++++++-- pm-stack/aggregator/src/feed.ts | 4 +-- pm-stack/aggregator/src/model.ts | 14 ++++----- pm-stack/aggregator/src/notifications.ts | 3 +- pm-stack/aggregator/src/quota-current.ts | 20 +++++++++---- pm-stack/aggregator/src/quota-gather-map.ts | 29 ++++++++++++++++-- pm-stack/aggregator/src/quota-refresh.ts | 2 +- .../aggregator/test/quota-current.test.ts | 30 +++++++++++++++++++ .../aggregator/test/quota-gather-map.test.ts | 20 +++++++++++-- 12 files changed, 132 insertions(+), 28 deletions(-) diff --git a/pm-stack/aggregator/scripts/gather-quota.ts b/pm-stack/aggregator/scripts/gather-quota.ts index ecd8787351..30b49a29cd 100755 --- a/pm-stack/aggregator/scripts/gather-quota.ts +++ b/pm-stack/aggregator/scripts/gather-quota.ts @@ -342,7 +342,7 @@ async function runMetaRenewal(tickAt: string): Promise { interface ProviderRun { id: string; - state: "ok" | "error"; + state: "ok" | "error" | "lapsed"; ms: number; entries: QuotaCurrentEntry[]; error?: string; @@ -365,6 +365,8 @@ interface ProviderRun { */ function finalizeRun(id: string, entries: QuotaCurrentEntry[], t0: number): ProviderRun { const anyOk = entries.some((e) => e.state === "ok"); + const anyLapsed = entries.some((e) => e.state === "lapsed"); + const anyError = entries.some((e) => e.state === "error"); const anyMeasured = entries.some((e) => entryHasMeasuredWindow(e)); if (anyOk && !anyMeasured) { const reason = @@ -377,12 +379,17 @@ function finalizeRun(id: string, entries: QuotaCurrentEntry[], t0: number): Prov return { id, state: "error", ms: Date.now() - t0, entries, error: reason }; } const firstBad = entries.find((e) => e.state !== "ok"); + // A run whose only non-ok rows are planned lapses is terminal, not + // failed: reporting it as "error" would trip #1268 retention and + // replace the lapsed rows with last-known ok readings, hiding the + // lapse the hub must show. + const onlyLapsed = !anyOk && anyLapsed && !anyError; return { id, - state: anyOk ? "ok" : "error", + state: anyOk ? "ok" : onlyLapsed ? "lapsed" : "error", ms: Date.now() - t0, entries, - ...(!anyOk && firstBad?.error ? { error: firstBad.error } : {}), + ...(!anyOk && !onlyLapsed && firstBad?.error ? { error: firstBad.error } : {}), }; } diff --git a/pm-stack/aggregator/src/assets/app.css b/pm-stack/aggregator/src/assets/app.css index 7c013299b3..c8c941bfda 100644 --- a/pm-stack/aggregator/src/assets/app.css +++ b/pm-stack/aggregator/src/assets/app.css @@ -5124,6 +5124,11 @@ pre { border-color: #d29922; color: #e3b341; } +.badge.lapsed { + background: #6e768133; + border-color: #6e7681; + color: #8b949e; +} .badge.conflict { background: #bc8cff33; border-color: #bc8cff; diff --git a/pm-stack/aggregator/src/credential-lifecycle.ts b/pm-stack/aggregator/src/credential-lifecycle.ts index 6140932633..62ad19c274 100644 --- a/pm-stack/aggregator/src/credential-lifecycle.ts +++ b/pm-stack/aggregator/src/credential-lifecycle.ts @@ -5,6 +5,7 @@ export type CredentialLifecycleState = | "ok" | "expiring" | "expired" + | "lapsed" | "rejected" | "provider-error" | "not-configured" @@ -58,7 +59,8 @@ export function lifecycleForEntry(entry: QuotaCurrentEntry, now = new Date()): C const error = entry.error ? safeProviderReason(entry.error) : undefined; let state: CredentialLifecycleState; - if (entry.state === "unconfigured") state = "not-configured"; + if (entry.state === "lapsed") state = "lapsed"; + else if (entry.state === "unconfigured") state = "not-configured"; else if (entry.state === "error" && /\bClaude session expired\b/i.test(error ?? "")) state = "expired"; else if ( entry.state === "error" && @@ -107,6 +109,7 @@ export function isCredentialLifecycleRow(value: unknown): value is CredentialLif "ok", "expiring", "expired", + "lapsed", "rejected", "provider-error", "not-configured", diff --git a/pm-stack/aggregator/src/digest.ts b/pm-stack/aggregator/src/digest.ts index b81b5a3ab0..2d3ed7f43f 100644 --- a/pm-stack/aggregator/src/digest.ts +++ b/pm-stack/aggregator/src/digest.ts @@ -274,7 +274,12 @@ export function buildDigest(inputs: DigestInputs): Digest { } const cappedQ = cap(items); const degradedProviders = inputs.quota.pools - .filter((p) => (p.freshness?.state ?? p.state) === "error" || (p.freshness?.state ?? p.state) === "stale") + .filter( + (p) => + (p.freshness?.state ?? p.state) === "error" || + (p.freshness?.state ?? p.state) === "stale" || + (p.freshness?.state ?? p.state) === "lapsed", + ) .map((p) => p.provider); quotaSection = { id: "quota", @@ -337,15 +342,19 @@ function quotaPoolNote(pool: QuotaPool, now: Date): string | null { const worst = pool.windows.reduce((m, w) => Math.max(m, windowPercent(w)), 0); const parts: string[] = []; // Provider freshness (#5279 Codex): quota-current marks a pool - // error/stale while retaining its historical windows, but poolState() + // error/stale/lapsed while retaining its historical windows, but poolState() // derives only utilization — without this, a failed pool with low // windows would vanish from the outlook and a stale high reading // would read as a current forecast. - const degraded = pool.freshness?.state ?? (pool.state === "error" || pool.state === "stale" ? pool.state : null); + const degraded = pool.freshness?.state ?? (pool.state === "error" || pool.state === "stale" || pool.state === "lapsed" ? pool.state : null); if (degraded === "error") { parts.push( `provider read error${pool.freshness?.error ? `: ${pool.freshness.error}` : ""} — current readings unavailable; any figures below are the last successful read`, ); + } else if (degraded === "lapsed") { + parts.push( + `provider lapsed${pool.freshness?.error ? `: ${pool.freshness.error}` : ""} — plan cancelled; no current readings`, + ); } else if (degraded === "stale") { parts.push( `provider read stale${pool.freshness?.measuredAt ? ` (measured ${pool.freshness.measuredAt})` : ""} — figures are the last read, not current`, diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index f0eef08b93..77aa98a7c9 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -565,7 +565,7 @@ export function isQuotaWindow(v: unknown): v is QuotaWindow { ); } -const QUOTA_STATES = ["healthy", "near", "walled", "error", "stale"]; +const QUOTA_STATES = ["healthy", "near", "walled", "error", "stale", "lapsed"]; /** One quota pool whose own shape is safe to hand to the renderers * (#2429): an object with a `windows` ARRAY — a non-array windows value @@ -583,7 +583,7 @@ export function isQuotaPool(v: unknown): v is QuotaPool { return true; } -const QUOTA_FRESHNESS_STATES = ["ok", "stale", "error"]; +const QUOTA_FRESHNESS_STATES = ["ok", "stale", "error", "lapsed"]; function isQuotaFreshness(v: unknown): v is PoolFreshness { return ( diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index 5a731c6f72..a63c9fc4b8 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -263,7 +263,7 @@ export type ProvenanceDetail = Record; /** "error"/"stale" are gatherer-overlay states (#1151): the gatherer * could not read the pool, or its read is past the freshness bound. * They are never rendered as healthy, and never as zero usage. */ -export type QuotaState = "healthy" | "near" | "walled" | "error" | "stale"; +export type QuotaState = "healthy" | "near" | "walled" | "error" | "stale" | "lapsed"; /** One usage window a provider exposes (5-hour, weekly, monthly, ...). */ export interface QuotaWindow { @@ -322,8 +322,8 @@ export interface QuotaCredentialRow { export interface PoolFreshness { measuredAt: string; source: string; - state: "ok" | "stale" | "error"; - /** Why the gatherer could not read the pool, when state is "error". */ + state: "ok" | "stale" | "error" | "lapsed"; + /** Why the gatherer could not read the pool, when state is "error" or "lapsed". */ error?: string; } @@ -332,7 +332,7 @@ export interface GathererProviderFreshness { providerId: string; serviceId: string; credentialLabel?: string; - state: "ok" | "stale" | "error"; + state: "ok" | "stale" | "error" | "lapsed"; measuredAt: string; source: string; error?: string; @@ -1386,7 +1386,7 @@ export interface QuotaCurrentWindow { resetsAt: string | null; measuredAt: string; source: string; - state: "ok" | "error"; + state: "ok" | "error" | "lapsed"; } export interface QuotaCurrentEntry { @@ -1409,7 +1409,7 @@ export interface QuotaCurrentEntry { /** ISO time of the provider's last successful read, when the quota * module carries one; lets readers age a degraded row honestly. */ lastSuccessAt?: string; - state: "ok" | "error" | "unconfigured"; + state: "ok" | "error" | "lapsed" | "unconfigured"; measuredAt: string; /** #1268: ISO time of the tick that retained this entry from the * previous tick after the provider's run errored. The data is @@ -1430,7 +1430,7 @@ export interface QuotaGatherHeartbeat { tickAt: string; ok: boolean; durationMs: number; - perProvider: Record; + perProvider: Record; /** Set when the tick itself failed before any provider ran (import / credential store). */ error?: string; } diff --git a/pm-stack/aggregator/src/notifications.ts b/pm-stack/aggregator/src/notifications.ts index 52057a647e..52e2346af2 100644 --- a/pm-stack/aggregator/src/notifications.ts +++ b/pm-stack/aggregator/src/notifications.ts @@ -294,7 +294,8 @@ export function buildNotificationCandidates(snapshot: NotificationSnapshot, now // #7193 Codex: a pool whose quota read errored or went stale keeps its // last windows, but the measurement is marked unavailable — never // derive wall notifications from retained windows in that state. - if (pool.state === "error" || pool.state === "stale") continue; + // A lapsed pool clears its windows at overlay, but still never burns. + if (pool.state === "error" || pool.state === "stale" || pool.state === "lapsed") continue; const soleDoor = snapshot.soleDoorPoolIds?.has(pool.id) ?? false; const windows = pool.windows.filter((w) => w.limit !== null); const percentOf = (w: (typeof windows)[number]) => w.percent ?? (w.used / (w.limit || 1)) * 100; diff --git a/pm-stack/aggregator/src/quota-current.ts b/pm-stack/aggregator/src/quota-current.ts index 7f084ed620..689f49a3d3 100644 --- a/pm-stack/aggregator/src/quota-current.ts +++ b/pm-stack/aggregator/src/quota-current.ts @@ -62,7 +62,7 @@ function isQuotaCurrentWindow(value: unknown): value is QuotaCurrentFile["provid (value.resetsAt === null || isIsoDate(value.resetsAt)) && isIsoDate(value.measuredAt) && typeof value.source === "string" && - (value.state === "ok" || value.state === "error") + (value.state === "ok" || value.state === "error" || value.state === "lapsed") ); } @@ -72,7 +72,7 @@ function isQuotaCurrentEntry(value: unknown): value is QuotaCurrentEntry { typeof value.providerId === "string" && typeof value.providerName === "string" && typeof value.serviceId === "string" && - (value.state === "ok" || value.state === "error" || value.state === "unconfigured") && + (value.state === "ok" || value.state === "error" || value.state === "lapsed" || value.state === "unconfigured") && isIsoDate(value.measuredAt) && typeof value.source === "string" && (value.credentialWatch === undefined || typeof value.credentialWatch === "boolean") && @@ -138,6 +138,7 @@ export function parseQuotaCurrent(doc: unknown): QuotaCurrentFile | null { type FreshState = PoolFreshness["state"]; function entryState(entry: QuotaCurrentEntry, nowMs: number): FreshState { + if (entry.state === "lapsed") return "lapsed"; if (entry.state === "ok") { // #1268: retained last-known entries are stale by definition — // the provider's latest run failed, however recent the retained @@ -218,12 +219,21 @@ function applyEntry(pool: QuotaPool, entry: QuotaCurrentEntry, state: FreshState source: entry.source, state, }; - if (state === "error") freshness.error = errorText(entry); + if (state === "error" || state === "lapsed") freshness.error = errorText(entry); pool.freshness = freshness; if (state === "error") { pool.state = "error"; return false; } + if (state === "lapsed") { + // A known subscription lapse is not a provider failure. The dated + // quota has no current meaning, so clear it instead of leaving old + // percentages beside a terminal lapsed badge. + pool.state = "lapsed"; + pool.windows = []; + delete pool.wallLiftsAt; + return false; + } if (state === "stale") { pool.state = "stale"; return false; @@ -297,7 +307,7 @@ function credentialRows(entries: QuotaCurrentEntry[], nowMs: number): QuotaCrede const rows: QuotaCredentialRow[] = [...byCred.values()].map((e) => { const state = entryState(e, nowMs); const freshness: PoolFreshness = { measuredAt: e.measuredAt, source: e.source, state }; - if (state === "error") freshness.error = errorText(e); + if (state === "error" || state === "lapsed") freshness.error = errorText(e); return { label: e.credentialLabel ?? e.providerName ?? e.providerId, ...(e.credentialId ? { credentialId: e.credentialId } : {}), @@ -325,7 +335,7 @@ function summarize(file: QuotaCurrentFile, nowMs: number): GathererSummary { source: e.source, }; if (e.credentialLabel) s.credentialLabel = e.credentialLabel; - if (s.state === "error") s.error = errorText(e); + if (s.state === "error" || s.state === "lapsed") s.error = errorText(e); return s; }), }; diff --git a/pm-stack/aggregator/src/quota-gather-map.ts b/pm-stack/aggregator/src/quota-gather-map.ts index 735ca8e87a..55b4161b14 100644 --- a/pm-stack/aggregator/src/quota-gather-map.ts +++ b/pm-stack/aggregator/src/quota-gather-map.ts @@ -265,7 +265,9 @@ export function entriesWithPoolSplits(entries: readonly QuotaCurrentEntry[]): Qu for (const entry of entries) { if (entry.providerId === "opencode-go") { // Unconfigured rows are host state, not pool state: the pools keep - // their dated reads until a real read (ok or error) arrives. + // their dated reads until a real read (ok, error, or lapsed) arrives. + // Lapsed rows split exactly like error rows — one terminal row per + // workspace pool — so the hub names the planned lapse instead of a failure. const serviceId = goPoolServiceId(entry); if (serviceId && entry.state !== "unconfigured") out.push({ ...entry, serviceId }); } else if (entry.providerId === "antigravity" || entry.providerId === "_antigravity") { @@ -395,6 +397,21 @@ export function entryFromFileExport( return entry; } +/** + * A configured OpenCode Go result whose Console answers "no active + * subscription" is a planned lapse (#1118, Drew ruled both plans stay + * cancelled) — a terminal state of its own, never a provider failure. + */ +export function isGoLapseResult(result: QuotaProviderResult): boolean { + return ( + result.providerId === "opencode-go" && + !result.ok && + result.configured && + typeof result.error === "string" && + result.error.includes("No active OpenCode Go subscription") + ); +} + /** Map one provider result onto a quota-current entry. */ export function entryFromResult(result: QuotaProviderResult, tickIso: string): QuotaCurrentEntry { let measuredAt = tickIso; @@ -402,7 +419,13 @@ export function entryFromResult(result: QuotaProviderResult, tickIso: string): Q const fetchedDate = new Date(result.fetchedAt); if (Number.isFinite(fetchedDate.getTime())) measuredAt = fetchedDate.toISOString(); } - const state: QuotaCurrentEntry["state"] = result.ok ? "ok" : result.configured ? "error" : "unconfigured"; + const state: QuotaCurrentEntry["state"] = result.ok + ? "ok" + : isGoLapseResult(result) + ? "lapsed" + : result.configured + ? "error" + : "unconfigured"; const providerId = canonicalProviderId(result.providerId); const entry: QuotaCurrentEntry = { providerId, @@ -453,7 +476,7 @@ export function entryFromResult(result: QuotaProviderResult, tickIso: string): Q resetsAt: normalizeResetAt(raw?.resetAt), measuredAt, source: GATHERER_SOURCE, - state: result.ok ? "ok" : "error", + state: entry.state === "lapsed" ? "lapsed" : result.ok ? "ok" : "error", }); }; const usageObj = result.usage; diff --git a/pm-stack/aggregator/src/quota-refresh.ts b/pm-stack/aggregator/src/quota-refresh.ts index a586174e4b..2ea69d061b 100644 --- a/pm-stack/aggregator/src/quota-refresh.ts +++ b/pm-stack/aggregator/src/quota-refresh.ts @@ -32,7 +32,7 @@ export type RefreshTrigger = (reason: "stale" | "manual") => void | Promise { + const add = (raw: string | null | undefined, state?: "ok" | "stale" | "error" | "lapsed") => { if (!raw || state === "error") return; const t = Date.parse(raw); // Future timestamps (clock skew) count as fresh, not as very stale. diff --git a/pm-stack/aggregator/test/quota-current.test.ts b/pm-stack/aggregator/test/quota-current.test.ts index e94176d487..6f46b69fe5 100644 --- a/pm-stack/aggregator/test/quota-current.test.ts +++ b/pm-stack/aggregator/test/quota-current.test.ts @@ -349,6 +349,36 @@ describe("quota-current overlay", () => { expect(pool.freshness?.state).toBe("error"); expect(pool.windows.map((w) => w.percent)).toEqual([11]); }); + + test("a lapsed entry survives ingest as a terminal lapse, not an error and without stale percentages", () => { + const at = iso(5 * 60_000); + const doc = JSON.parse( + JSON.stringify( + file([ + entry({ + serviceId: "opencode-go", + providerId: "opencode-go", + state: "lapsed", + measuredAt: at, + error: "No active OpenCode Go subscription on the selected Console account", + windows: [{ ...win("monthly", 62, at), state: "lapsed" }], + }), + ]), + ), + ); + const parsed = parseQuotaCurrent(doc); + expect(parsed?.providers[0].state).toBe("lapsed"); + const view = baseView(); + view.pools.push(pool("opencode-go", [{ name: "monthly", unit: "other", limit: 100, used: 62, percent: 62, resetsAt: null }])); + const out = overlayQuotaCurrent(view, parsed!, NOW); + const go = out.pools.find((p) => p.id === "opencode-go")!; + expect(go.state).toBe("lapsed"); + expect(go.freshness?.state).toBe("lapsed"); + expect(go.freshness?.error).toContain("No active OpenCode Go subscription"); + // The dated percentage is not presented as a current reading. + expect(go.windows).toEqual([]); + expect(out.gatherer?.providers.find((p) => p.serviceId === "opencode-go")?.state).toBe("lapsed"); + }); }); describe("parseQuotaCurrent", () => { diff --git a/pm-stack/aggregator/test/quota-gather-map.test.ts b/pm-stack/aggregator/test/quota-gather-map.test.ts index 45b214725b..5330fc94e3 100644 --- a/pm-stack/aggregator/test/quota-gather-map.test.ts +++ b/pm-stack/aggregator/test/quota-gather-map.test.ts @@ -919,7 +919,7 @@ describe("pool splits (#1331)", () => { ]); }); - test("Go lapse: an errored drewrypope row splits as a pool error; unconfigured rows never split", () => { + test("Go lapse: a lapsed drewrypope row splits as a pool lapsed; unconfigured rows never split", () => { const lapsed: QuotaProviderResult = { providerId: "opencode-go", providerName: "OpenCode Go", @@ -944,8 +944,24 @@ describe("pool splits (#1331)", () => { const split = entriesWithPoolSplits([entryFromResult(lapsed, TICK), entryFromResult(unconfigured, TICK)]); expect(split.map((e) => e.serviceId).sort()).toEqual(["opencode-go", "opencode-go", GO_DREWRYPOPE_SERVICE_ID]); const personal = split.find((e) => e.serviceId === GO_DREWRYPOPE_SERVICE_ID)!; - expect(personal.state).toBe("error"); + expect(personal.state).toBe("lapsed"); expect(personal.error).toContain("No active OpenCode Go subscription"); + // Control: a configured Go failure without the lapse signal stays an error. + const failed = entryFromResult( + { + providerId: "opencode-go", + providerName: "OpenCode Go", + ok: false, + configured: true, + fetchedAt: Date.parse(TICK), + credentialId: "cred_personal", + credentialLabel: "drewrypope", + error: "timeout", + usage: null, + }, + TICK, + ); + expect(failed.state).toBe("error"); }); test("Go workspaces without a hub pool stay combined-only; labels match case-insensitively", () => { From a70a475ce5947cb1340c31300d1afcf32a2fa001 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 18:47:21 -0600 Subject: [PATCH 2/5] fix(quota-plane): lapsed Go rows never emit windows; retention only on errors (#1161) Follow-up hardening on the lapsed-state fix: entryFromResult returns lapsed entries windowless (old usage alongside the lapse signal stays evidence on entry.usage, never a fresh window), and finalizeRun treats only error runs as retention candidates so a mixed ok/error/lapsed provider can never be misreported as lapsed. --- pm-stack/aggregator/scripts/gather-quota.ts | 8 +- pm-stack/aggregator/src/digest.ts | 3 +- pm-stack/aggregator/src/model.ts | 3 +- pm-stack/aggregator/src/quota-gather-map.ts | 9 +- pm-stack/aggregator/test/gather-quota.test.ts | 114 ++++++++++++++++++ .../aggregator/test/quota-gather-map.test.ts | 20 ++- 6 files changed, 147 insertions(+), 10 deletions(-) diff --git a/pm-stack/aggregator/scripts/gather-quota.ts b/pm-stack/aggregator/scripts/gather-quota.ts index 30b49a29cd..c9fcee439d 100755 --- a/pm-stack/aggregator/scripts/gather-quota.ts +++ b/pm-stack/aggregator/scripts/gather-quota.ts @@ -365,8 +365,6 @@ interface ProviderRun { */ function finalizeRun(id: string, entries: QuotaCurrentEntry[], t0: number): ProviderRun { const anyOk = entries.some((e) => e.state === "ok"); - const anyLapsed = entries.some((e) => e.state === "lapsed"); - const anyError = entries.some((e) => e.state === "error"); const anyMeasured = entries.some((e) => entryHasMeasuredWindow(e)); if (anyOk && !anyMeasured) { const reason = @@ -378,18 +376,18 @@ function finalizeRun(id: string, entries: QuotaCurrentEntry[], t0: number): Prov } return { id, state: "error", ms: Date.now() - t0, entries, error: reason }; } - const firstBad = entries.find((e) => e.state !== "ok"); + const firstFailure = entries.find((e) => e.state !== "ok" && e.state !== "lapsed"); // A run whose only non-ok rows are planned lapses is terminal, not // failed: reporting it as "error" would trip #1268 retention and // replace the lapsed rows with last-known ok readings, hiding the // lapse the hub must show. - const onlyLapsed = !anyOk && anyLapsed && !anyError; + const onlyLapsed = entries.length > 0 && entries.every((e) => e.state === "lapsed"); return { id, state: anyOk ? "ok" : onlyLapsed ? "lapsed" : "error", ms: Date.now() - t0, entries, - ...(!anyOk && !onlyLapsed && firstBad?.error ? { error: firstBad.error } : {}), + ...(!anyOk && !onlyLapsed && firstFailure?.error ? { error: firstFailure.error } : {}), }; } diff --git a/pm-stack/aggregator/src/digest.ts b/pm-stack/aggregator/src/digest.ts index 2d3ed7f43f..6162b37681 100644 --- a/pm-stack/aggregator/src/digest.ts +++ b/pm-stack/aggregator/src/digest.ts @@ -277,8 +277,7 @@ export function buildDigest(inputs: DigestInputs): Digest { .filter( (p) => (p.freshness?.state ?? p.state) === "error" || - (p.freshness?.state ?? p.state) === "stale" || - (p.freshness?.state ?? p.state) === "lapsed", + (p.freshness?.state ?? p.state) === "stale", ) .map((p) => p.provider); quotaSection = { diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index a63c9fc4b8..f9e4c4b5f6 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -262,7 +262,8 @@ export type ProvenanceDetail = Record; /** "error"/"stale" are gatherer-overlay states (#1151): the gatherer * could not read the pool, or its read is past the freshness bound. - * They are never rendered as healthy, and never as zero usage. */ + * "lapsed" is a confirmed terminal subscription state, not a provider + * failure. None are rendered as healthy or as zero usage. */ export type QuotaState = "healthy" | "near" | "walled" | "error" | "stale" | "lapsed"; /** One usage window a provider exposes (5-hour, weekly, monthly, ...). */ diff --git a/pm-stack/aggregator/src/quota-gather-map.ts b/pm-stack/aggregator/src/quota-gather-map.ts index 55b4161b14..4a16047d1f 100644 --- a/pm-stack/aggregator/src/quota-gather-map.ts +++ b/pm-stack/aggregator/src/quota-gather-map.ts @@ -455,6 +455,13 @@ export function entryFromResult(result: QuotaProviderResult, tickIso: string): Q } if (result.usage != null) entry.usage = result.usage; + if (state === "lapsed") { + // The provider may leave old usage alongside its lapse signal. + // Preserve the raw response for evidence, but never publish those + // percentages as a fresh quota window. + return entry; + } + const pushWindow = (name: string, raw: RawWindow | null | undefined): void => { const pct = isFiniteNumber(raw?.usedPercent) ? raw.usedPercent : null; // Percent is bounded by the window's own 100-point limit (#2571); @@ -476,7 +483,7 @@ export function entryFromResult(result: QuotaProviderResult, tickIso: string): Q resetsAt: normalizeResetAt(raw?.resetAt), measuredAt, source: GATHERER_SOURCE, - state: entry.state === "lapsed" ? "lapsed" : result.ok ? "ok" : "error", + state: result.ok ? "ok" : "error", }); }; const usageObj = result.usage; diff --git a/pm-stack/aggregator/test/gather-quota.test.ts b/pm-stack/aggregator/test/gather-quota.test.ts index 2a4d7d6da9..bbd8adefa6 100644 --- a/pm-stack/aggregator/test/gather-quota.test.ts +++ b/pm-stack/aggregator/test/gather-quota.test.ts @@ -148,3 +148,117 @@ test("an ok-but-null provider result retains the last good quota row", async () await rm(dir, { recursive: true, force: true }); } }); + +test("a lapsed Go workspace survives ingest instead of being replaced by last-known retention", async () => { + const dir = await mkdtemp(join(tmpdir(), "gather-quota-lapsed-")); + + try { + const currentPath = join(dir, "quota-current.json"); + const heartbeatPath = join(dir, "quota-gatherer-heartbeat.json"); + const statePath = join(dir, "quota-gatherer-state.json"); + const snapshotsDir = join(dir, "snapshots"); + const outboxPath = join(dir, "snapshots.outbox.jsonl"); + const subcommandPath = join(dir, "quota-subcommand.mjs"); + const previousAt = "2026-11-06T04:00:00.000Z"; + const lapsedResult = { + providerId: "opencode-go", + providerName: "OpenCode Go", + ok: false, + configured: true, + fetchedAt: Date.parse("2026-11-06T04:30:00.000Z"), + credentialId: "cred_personal", + credentialLabel: "drewrypope", + error: "No active OpenCode Go subscription on the selected Console account", + usage: null, + }; + + // A real ok read from the previous tick would be the retention + // candidate if the lapsed run were misclassified as an error. + await writeFile( + currentPath, + `${JSON.stringify( + { + version: 1, + generatedAt: previousAt, + source: "opencode-quota", + heartbeat: { + tickAt: previousAt, + ok: true, + durationMs: 1, + perProvider: { "opencode-go": { state: "ok", ms: 1, rows: 2 } }, + }, + providers: [ + { + providerId: "opencode-go", + providerName: "OpenCode Go", + serviceId: "opencode-go", + state: "ok", + measuredAt: previousAt, + source: "opencode-quota", + windows: [ + { + name: "monthly", + value: 62, + pctOfLimit: 62, + valueLabel: null, + windowSeconds: null, + resetsAt: "2026-12-03T03:02:00.000Z", + measuredAt: previousAt, + source: "opencode-quota", + state: "ok", + }, + ], + }, + ], + }, + null, + 2, + )}\n`, + "utf8", + ); + await writeFile(subcommandPath, `console.log(${JSON.stringify(JSON.stringify([lapsedResult]))});\n`, "utf8"); + + const result = spawnSync(process.execPath, [GATHERER_SCRIPT], { + cwd: dir, + encoding: "utf8", + timeout: 30_000, + env: { + PATH: process.env.PATH ?? "", + HOME: dir, + QUOTA_CURRENT_PATH: currentPath, + QUOTA_HEARTBEAT_PATH: heartbeatPath, + QUOTA_GATHERER_STATE_PATH: statePath, + QUOTA_SNAPSHOTS_DIR: snapshotsDir, + USAGE_SNAPSHOT_OUTBOX_PATH: outboxPath, + QUOTA_SUBCOMMAND: `${process.execPath} ${subcommandPath}`, + QUOTA_SUBCOMMAND_TIMEOUT_MS: "5000", + OPENDESIGN_RENEWAL_DISABLED: "1", + META_RENEWAL_DISABLED: "1", + SUPABASE_QUOTA_SINK: "0", + TURSO_QUOTA_SINK: "0", + }, + }); + + if (result.error || result.status !== 0) { + throw new Error(`gatherer failed: ${result.error?.message ?? result.stderr}\n${result.stdout}`); + } + + const output = JSON.parse(await readFile(currentPath, "utf8")); + const goRows = output.providers.filter((entry: { serviceId: string }) => entry.serviceId.startsWith("opencode-go")); + expect(goRows.map((entry: { serviceId: string }) => entry.serviceId).sort()).toEqual([ + "opencode-go", + "opencode-go.drewrypope", + ]); + for (const row of goRows) { + expect(row.state).toBe("lapsed"); + expect(row.windows).toEqual([]); + expect(row.retainedFromFailedTick).toBeUndefined(); + expect(row.error).toContain("No active OpenCode Go subscription"); + } + expect(output.heartbeat.perProvider["opencode-go"]).toMatchObject({ state: "lapsed" }); + // No percentage may be recorded as a fresh observation. + await expect(readFile(outboxPath, "utf8")).rejects.toThrow(); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/pm-stack/aggregator/test/quota-gather-map.test.ts b/pm-stack/aggregator/test/quota-gather-map.test.ts index 5330fc94e3..ee607219a0 100644 --- a/pm-stack/aggregator/test/quota-gather-map.test.ts +++ b/pm-stack/aggregator/test/quota-gather-map.test.ts @@ -929,7 +929,9 @@ describe("pool splits (#1331)", () => { credentialId: "cred_personal", credentialLabel: "drewrypope", error: "No active OpenCode Go subscription on the selected Console account", - usage: null, + // Even if a provider includes old usage alongside the lapse error, + // it must not be published as a current quota window or snapshot. + usage: { windows: { monthly: { usedPercent: 100 } } }, }; const unconfigured: QuotaProviderResult = { providerId: "opencode-go", @@ -946,6 +948,8 @@ describe("pool splits (#1331)", () => { const personal = split.find((e) => e.serviceId === GO_DREWRYPOPE_SERVICE_ID)!; expect(personal.state).toBe("lapsed"); expect(personal.error).toContain("No active OpenCode Go subscription"); + expect(personal.windows).toEqual([]); + expect(recordsFromEntries(split, new Map(), "quota-gatherer").records).toEqual([]); // Control: a configured Go failure without the lapse signal stays an error. const failed = entryFromResult( { @@ -962,6 +966,20 @@ describe("pool splits (#1331)", () => { TICK, ); expect(failed.state).toBe("error"); + expect(failed.error).toContain("timeout"); + // The signal only maps for the opencode-go provider itself: a + // different provider with the same words still throws an error. + const sameReason = entryFromResult( + { + providerId: "claude", + ok: false, + configured: true, + error: "No active OpenCode Go subscription on the selected Console account", + usage: null, + }, + TICK, + ); + expect(sameReason.state).toBe("error"); }); test("Go workspaces without a hub pool stay combined-only; labels match case-insensitively", () => { From 9b4b6b85692ae6df21395528e87821cecd154667 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 19:40:22 -0600 Subject: [PATCH 3/5] fix(quota-plane): retain Go lapse state beside failed siblings (#1161) --- pm-stack/aggregator/scripts/gather-quota.ts | 21 ++- pm-stack/aggregator/test/gather-quota.test.ts | 138 ++++++++++++++++++ 2 files changed, 155 insertions(+), 4 deletions(-) diff --git a/pm-stack/aggregator/scripts/gather-quota.ts b/pm-stack/aggregator/scripts/gather-quota.ts index c9fcee439d..d9a010fa18 100755 --- a/pm-stack/aggregator/scripts/gather-quota.ts +++ b/pm-stack/aggregator/scripts/gather-quota.ts @@ -692,16 +692,29 @@ async function main(): Promise { // #1268: an errored run with no ok row of its own retains the // provider's last-known ok entries from the previous tick instead // of replacing them with fresh error rows (or with nothing, on a - // whole-fetch timeout). The heartbeat below still reports the run - // as an error, with its reason and the retained row count. + // whole-fetch timeout). Preserve confirmed lapse rows alongside + // retained siblings: retention must never erase a terminal state + // reported by this tick. const prevEntries = await readPreviousEntries(); if (prevEntries.length) { for (const run of runs) { if (run.state !== "error" || run.entries.some((e) => e.state === "ok")) continue; const retained = lastKnownEntries(prevEntries, run.id); if (retained.length) { - run.entries = markRetained(retained, tickAt); - run.retained = true; + const lapsed = run.entries.filter((e) => e.state === "lapsed"); + // Do not retain the previous ok reading for the same credential + // that has just reported a lapse. Other credentials in the same + // provider run may still retain their last-known readings. + const retainedSiblings = retained.filter( + (previous) => + !lapsed.some((current) => + (current.credentialId && previous.credentialId === current.credentialId) || + (current.credentialLabel && + previous.credentialLabel?.trim().toLowerCase() === current.credentialLabel.trim().toLowerCase()), + ), + ); + run.entries = [...markRetained(retainedSiblings, tickAt), ...lapsed]; + run.retained = retainedSiblings.length > 0; } } } diff --git a/pm-stack/aggregator/test/gather-quota.test.ts b/pm-stack/aggregator/test/gather-quota.test.ts index bbd8adefa6..49d1a73e79 100644 --- a/pm-stack/aggregator/test/gather-quota.test.ts +++ b/pm-stack/aggregator/test/gather-quota.test.ts @@ -262,3 +262,141 @@ test("a lapsed Go workspace survives ingest instead of being replaced by last-kn await rm(dir, { recursive: true, force: true }); } }); + +test("a lapsed Go workspace survives retention when a sibling workspace fails", async () => { + const dir = await mkdtemp(join(tmpdir(), "gather-quota-mixed-lapse-")); + + try { + const currentPath = join(dir, "quota-current.json"); + const heartbeatPath = join(dir, "quota-gatherer-heartbeat.json"); + const statePath = join(dir, "quota-gatherer-state.json"); + const snapshotsDir = join(dir, "snapshots"); + const outboxPath = join(dir, "snapshots.outbox.jsonl"); + const subcommandPath = join(dir, "quota-subcommand.mjs"); + const previousAt = "2026-11-06T04:00:00.000Z"; + const windowFor = (credentialLabel: string, credentialId: string) => ({ + providerId: "opencode-go", + providerName: "OpenCode Go", + serviceId: "opencode-go", + credentialId, + credentialLabel, + state: "ok", + measuredAt: previousAt, + source: "opencode-quota", + windows: [ + { + name: "monthly", + value: credentialLabel === "drewrypope" ? 62 : 35, + pctOfLimit: credentialLabel === "drewrypope" ? 62 : 35, + valueLabel: null, + windowSeconds: null, + resetsAt: "2026-12-03T03:02:00.000Z", + measuredAt: previousAt, + source: "opencode-quota", + state: "ok", + }, + ], + }); + const lapsed = { + providerId: "opencode-go", + providerName: "OpenCode Go", + ok: false, + configured: true, + fetchedAt: Date.parse("2026-11-06T04:30:00.000Z"), + credentialId: "cred_personal", + credentialLabel: "drewrypope", + error: "No active OpenCode Go subscription on the selected Console account", + usage: null, + }; + const failedSibling = { + providerId: "opencode-go", + providerName: "OpenCode Go", + ok: false, + configured: true, + fetchedAt: Date.parse("2026-11-06T04:30:01.000Z"), + credentialId: "cred_lab", + credentialLabel: "popesdrew", + error: "OpenCode Go request timed out", + usage: null, + }; + + await writeFile( + currentPath, + `${JSON.stringify( + { + version: 1, + generatedAt: previousAt, + source: "opencode-quota", + heartbeat: { + tickAt: previousAt, + ok: true, + durationMs: 1, + perProvider: { "opencode-go": { state: "ok", ms: 1, rows: 2 } }, + }, + providers: [windowFor("drewrypope", "cred_personal"), windowFor("popesdrew", "cred_lab")], + }, + null, + 2, + )}\n`, + "utf8", + ); + await writeFile( + subcommandPath, + `console.log(${JSON.stringify(JSON.stringify([lapsed, failedSibling]))});\n`, + "utf8", + ); + + const result = spawnSync(process.execPath, [GATHERER_SCRIPT], { + cwd: dir, + encoding: "utf8", + timeout: 30_000, + env: { + PATH: process.env.PATH ?? "", + HOME: dir, + QUOTA_CURRENT_PATH: currentPath, + QUOTA_HEARTBEAT_PATH: heartbeatPath, + QUOTA_GATHERER_STATE_PATH: statePath, + QUOTA_SNAPSHOTS_DIR: snapshotsDir, + USAGE_SNAPSHOT_OUTBOX_PATH: outboxPath, + QUOTA_SUBCOMMAND: `${process.execPath} ${subcommandPath}`, + QUOTA_SUBCOMMAND_TIMEOUT_MS: "5000", + OPENDESIGN_RENEWAL_DISABLED: "1", + META_RENEWAL_DISABLED: "1", + SUPABASE_QUOTA_SINK: "0", + TURSO_QUOTA_SINK: "0", + }, + }); + + if (result.error || result.status !== 0) { + throw new Error(`gatherer failed: ${result.error?.message ?? result.stderr}\n${result.stdout}`); + } + + const output = JSON.parse(await readFile(currentPath, "utf8")); + const personal = output.providers.filter( + (entry: { serviceId: string }) => entry.serviceId === "opencode-go.drewrypope", + ); + expect(personal).toHaveLength(1); + expect(personal[0]).toMatchObject({ state: "lapsed", windows: [] }); + expect(personal[0].error).toContain("No active OpenCode Go subscription"); + + const sibling = output.providers.find( + (entry: { serviceId: string; retainedFromFailedTick?: string }) => + entry.serviceId === "opencode-go.popesdrew" && entry.retainedFromFailedTick, + ); + expect(sibling).toMatchObject({ state: "ok", retainedFromFailedTick: output.generatedAt }); + expect(output.heartbeat.perProvider["opencode-go"]).toMatchObject({ + state: "error", + error: "OpenCode Go request timed out", + }); + // The lapsed credential contributes no newly measured percentage. + const records = (await readFile(outboxPath, "utf8")) + .trim() + .split("\n") + .map((line: string) => JSON.parse(line)); + expect(records.some((record: { serviceId: string }) => record.serviceId === "opencode-go.drewrypope")).toBe( + false, + ); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); From e572e55ce340e79f4d49cad0f4aebd7fea55dc7d Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 19:54:23 -0600 Subject: [PATCH 4/5] fix(quota-plane): invalidate choices for lapsed pools (#1161) --- pm-stack/aggregator/src/quota-current.ts | 17 +++++++++-------- pm-stack/aggregator/test/quota-current.test.ts | 9 +++++++++ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/pm-stack/aggregator/src/quota-current.ts b/pm-stack/aggregator/src/quota-current.ts index 689f49a3d3..9050a35961 100644 --- a/pm-stack/aggregator/src/quota-current.ts +++ b/pm-stack/aggregator/src/quota-current.ts @@ -213,7 +213,8 @@ function pctWindows(entry: QuotaCurrentEntry): QuotaWindow[] { } function applyEntry(pool: QuotaPool, entry: QuotaCurrentEntry, state: FreshState): boolean { - // Returns true when the pool's windows were replaced by a fresh read. + // Returns true when model-choice guidance needs recomputing: a fresh + // read replaced windows, or a terminal lapse removed the pool's windows. const freshness: PoolFreshness = { measuredAt: entry.measuredAt, source: entry.source, @@ -232,7 +233,7 @@ function applyEntry(pool: QuotaPool, entry: QuotaCurrentEntry, state: FreshState pool.state = "lapsed"; pool.windows = []; delete pool.wallLiftsAt; - return false; + return true; } if (state === "stale") { pool.state = "stale"; @@ -368,20 +369,20 @@ export function overlayQuotaCurrent(view: QuotaView, file: QuotaCurrentFile, now else byService.set(e.serviceId, [e]); } - let anyFreshWindows = false; + let recomputeChoices = false; const pools = view.pools.map((orig) => { const entries = byService.get(orig.id); if (!entries || entries.length === 0) return orig; const pool: QuotaPool = { ...orig, windows: [...orig.windows] }; const freshOk = entries.filter((e) => entryState(e, nowMs) === "ok").sort(newestFirst(nowMs)); if (freshOk.length > 0) { - if (applyEntry(pool, freshOk[0], "ok")) anyFreshWindows = true; + if (applyEntry(pool, freshOk[0], "ok")) recomputeChoices = true; const rows = credentialRows(entries, nowMs); if (rows) pool.credentials = rows; return pool; } const newest = [...entries].sort(newestFirst(nowMs))[0]; - applyEntry(pool, newest, entryState(newest, nowMs)); + if (applyEntry(pool, newest, entryState(newest, nowMs))) recomputeChoices = true; return pool; }); @@ -411,11 +412,11 @@ export function overlayQuotaCurrent(view: QuotaView, file: QuotaCurrentFile, now }; const freshOk = entries.filter((e) => entryState(e, nowMs) === "ok").sort(newestFirst(nowMs)); if (freshOk.length > 0) { - if (applyEntry(pool, freshOk[0], "ok")) anyFreshWindows = true; + if (applyEntry(pool, freshOk[0], "ok")) recomputeChoices = true; const rows = credentialRows(entries, nowMs); if (rows) pool.credentials = rows; } else { - applyEntry(pool, newest, entryState(newest, nowMs)); + if (applyEntry(pool, newest, entryState(newest, nowMs))) recomputeChoices = true; } synthesized.push(pool); } @@ -430,7 +431,7 @@ export function overlayQuotaCurrent(view: QuotaView, file: QuotaCurrentFile, now .filter((entry) => entry.credentialWatch === true) .map((entry) => lifecycleForEntry(entry, now)); if (credentialLifecycle.length) out.credentialLifecycle = credentialLifecycle; - if (anyFreshWindows) out.choices = computeChoices(allPools, nowMs); + if (recomputeChoices) out.choices = computeChoices(allPools, nowMs); return out; } diff --git a/pm-stack/aggregator/test/quota-current.test.ts b/pm-stack/aggregator/test/quota-current.test.ts index 6f46b69fe5..15b6c37680 100644 --- a/pm-stack/aggregator/test/quota-current.test.ts +++ b/pm-stack/aggregator/test/quota-current.test.ts @@ -370,6 +370,11 @@ describe("quota-current overlay", () => { expect(parsed?.providers[0].state).toBe("lapsed"); const view = baseView(); view.pools.push(pool("opencode-go", [{ name: "monthly", unit: "other", limit: 100, used: 62, percent: 62, resetsAt: null }])); + view.choices = { + hasHeadroom: ["opencode-go"], + burnBeforeReset: ["opencode-go"], + doNotStart: ["opencode-go"], + }; const out = overlayQuotaCurrent(view, parsed!, NOW); const go = out.pools.find((p) => p.id === "opencode-go")!; expect(go.state).toBe("lapsed"); @@ -377,6 +382,10 @@ describe("quota-current overlay", () => { expect(go.freshness?.error).toContain("No active OpenCode Go subscription"); // The dated percentage is not presented as a current reading. expect(go.windows).toEqual([]); + // Guidance must not continue recommending a cancelled workspace. + expect(out.choices.hasHeadroom).not.toContain("opencode-go"); + expect(out.choices.burnBeforeReset).not.toContain("opencode-go"); + expect(out.choices.doNotStart).not.toContain("opencode-go"); expect(out.gatherer?.providers.find((p) => p.serviceId === "opencode-go")?.state).toBe("lapsed"); }); }); From 912d172734b1bb21b4157ddc42b29250445d476d Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 15:19:13 -0600 Subject: [PATCH 5/5] fix(quota-plane): canonicalize provider id in Go lapse check; clarify newestMeasurement docstring (Copilot review, PR #7898) --- pm-stack/aggregator/src/quota-gather-map.ts | 2 +- pm-stack/aggregator/src/quota-refresh.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pm-stack/aggregator/src/quota-gather-map.ts b/pm-stack/aggregator/src/quota-gather-map.ts index 4a16047d1f..6297b77c4b 100644 --- a/pm-stack/aggregator/src/quota-gather-map.ts +++ b/pm-stack/aggregator/src/quota-gather-map.ts @@ -404,7 +404,7 @@ export function entryFromFileExport( */ export function isGoLapseResult(result: QuotaProviderResult): boolean { return ( - result.providerId === "opencode-go" && + canonicalProviderId(result.providerId) === "opencode-go" && !result.ok && result.configured && typeof result.error === "string" && diff --git a/pm-stack/aggregator/src/quota-refresh.ts b/pm-stack/aggregator/src/quota-refresh.ts index 2ea69d061b..2f64bf39ef 100644 --- a/pm-stack/aggregator/src/quota-refresh.ts +++ b/pm-stack/aggregator/src/quota-refresh.ts @@ -29,7 +29,7 @@ export interface RefreshStatus { export type RefreshTrigger = (reason: "stale" | "manual") => void | Promise; -/** Newest non-error provider/pool measurement in the view, in epoch ms, or null. */ +/** Newest provider/pool measurement stamp in the view, in epoch ms, or null. Error reads are excluded; a lapsed read contributes its stamp (it is a current terminal state, not a measurement of usage). */ export function newestMeasurement(view: QuotaView, nowMs = Date.now()): number | null { const times: number[] = []; const add = (raw: string | null | undefined, state?: "ok" | "stale" | "error" | "lapsed") => {