diff --git a/pm-stack/aggregator/scripts/gather-quota.ts b/pm-stack/aggregator/scripts/gather-quota.ts index cfebb2eff7..4ae7eb8fe7 100755 --- a/pm-stack/aggregator/scripts/gather-quota.ts +++ b/pm-stack/aggregator/scripts/gather-quota.ts @@ -89,6 +89,16 @@ // the reading rows. Fail-soft on the same terms: a forecast // failure never fails the tick and the previous forecast // stands and ages. +// - quota-shadow-placement.json beside quota-current.json, plus +// one appended line per tick in +// quota-shadow-placement-history.jsonl beside it — the Stage-3 +// shadow placement record (#12697, design D3): the +// forecast-informed ordering logged beside the live ordering +// as a per-decision diff record, projected by +// src/quota-shadow-placement.ts from this tick's entries + the +// forecast product. SHADOW ONLY: no live path reads it; the +// live ordering is computed from the measured entries alone. +// Fail-soft on the same terms as the forecast. // // Fail-soft contract: if the subcommand cannot be run or its output // cannot be parsed, the tick writes a heartbeat carrying the error @@ -108,6 +118,9 @@ // cap; the subcommand self-limits per provider), // QUOTA_CURRENT_PATH, QUOTA_HEARTBEAT_PATH, QUOTA_FORECAST_PATH // (default: quota-forecast.json beside QUOTA_CURRENT_PATH), +// QUOTA_SHADOW_PLACEMENT_PATH / QUOTA_SHADOW_PLACEMENT_HISTORY_PATH +// (defaults: quota-shadow-placement.json / +// quota-shadow-placement-history.jsonl beside QUOTA_CURRENT_PATH), // QUOTA_GATHERER_STATE_PATH, QUOTA_SNAPSHOTS_DIR (./snapshots), // USAGE_SNAPSHOT_OUTBOX_PATH, // QUOTA_GATHER_CONCURRENCY (retained for interface stability; @@ -154,7 +167,8 @@ import { ensureLibDependencies } from "../src/lib-deps.ts"; import { loadOpenChamberLib, resolveLibDir as resolveOpenChamberLib } from "../src/openchamber-lib.ts"; import { readProviderAuthAlerts } from "../src/provider-auth-alerts.ts"; import { projectPoolState } from "../src/pool-state.ts"; -import { buildForecastLedgerRows, buildQuotaForecast } from "../src/quota-forecast.ts"; +import { buildForecastLedgerRows, buildQuotaForecast, type QuotaForecastFile } from "../src/quota-forecast.ts"; +import { buildShadowPlacement } from "../src/quota-shadow-placement.ts"; import { renewMetaSession } from "../src/meta-renewal.ts"; import { classEnabled, getAlertsStore } from "../src/alerts.ts"; import { sendPush, type PushTarget } from "../src/push.ts"; @@ -189,6 +203,13 @@ const poolStatePath = process.env.POOL_STATE_PATH ?? join(HOME, ".local/state/op // #12695: the Stage-3 forecast product, beside quota-current.json // (design D1: same directory, same fail-soft posture). const forecastPath = process.env.QUOTA_FORECAST_PATH ?? join(dirname(currentPath), "quota-forecast.json"); +// #12697: the Stage-3 shadow placement record (design D3), beside +// quota-current.json like the forecast: the latest diff record plus +// the append-only history the weekly review (S7) scores. +const shadowPlacementPath = + process.env.QUOTA_SHADOW_PLACEMENT_PATH ?? join(dirname(currentPath), "quota-shadow-placement.json"); +const shadowPlacementHistoryPath = + process.env.QUOTA_SHADOW_PLACEMENT_HISTORY_PATH ?? join(dirname(currentPath), "quota-shadow-placement-history.jsonl"); /** Strict millisecond parse for boot-time env (#2835 env-number contract): * digits only, 1..2^31-1, else fail naming the variable and the value * instead of coercing NaN/negative/huge values into a fetch deadline. */ @@ -1137,9 +1158,10 @@ async function main(): Promise { // write: any failure logs and the tick still succeeds; the // previous forecast stands and ages, exactly as a failed tick // leaves the previous quota-current.json standing. + let forecast: QuotaForecastFile | null = null; try { const stored = await new SnapshotStore(snapshotsDir).readAll().catch((): SnapshotRecord[] => []); - const forecast = buildQuotaForecast(file, [...stored, ...fresh], new Date(tickAt)); + forecast = buildQuotaForecast(file, [...stored, ...fresh], new Date(tickAt)); await writeAtomic(forecastPath, JSON.stringify(forecast, null, 2) + "\n"); const forecastRows = buildForecastLedgerRows(forecast, tickAt); await writeTursoForecastRecords(forecastRows, tickAt); @@ -1153,6 +1175,30 @@ async function main(): Promise { ); } + // Stage-3 S3 (#12697, design D3): the shadow placement record — + // the forecast-informed ordering logged beside the live ordering + // as a per-decision diff record (src/quota-shadow-placement.ts), + // written as the latest-state file plus one appended line per + // tick in the history JSONL the weekly review (S7) scores. + // SHADOW ONLY: no live path reads the record, and it is computed + // after every live output above is already written; a null + // forecast (the block above failed) still yields a record, with + // the shadow ordering equal to the live one. Fail-soft like the + // forecast write: any failure logs and the tick still succeeds. + try { + const shadow = buildShadowPlacement(file, forecast, new Date(tickAt)); + await writeAtomic(shadowPlacementPath, JSON.stringify(shadow, null, 2) + "\n"); + await mkdir(dirname(shadowPlacementHistoryPath), { recursive: true }); + await appendFile(shadowPlacementHistoryPath, JSON.stringify(shadow) + "\n", "utf8"); + console.log( + `quota-gatherer: shadow placement wrote ${shadow.summary.pools} pools, ${shadow.summary.demotedByForecast} forecast demotions (shadow only) -> ${shadowPlacementPath}`, + ); + } catch (err) { + console.error( + `quota-gatherer: shadow placement failed-soft: ${safeProviderReason(err instanceof Error ? err.message : String(err))}`, + ); + } + const okCount = runs.filter((r) => r.state === "ok").length; console.log( `quota-gatherer: tick ${tickAt} providers=${runs.length} ok=${okCount} records=+${fresh.length} durationMs=${heartbeat.durationMs} -> ${currentPath}`, diff --git a/pm-stack/aggregator/src/quota-shadow-placement.test.ts b/pm-stack/aggregator/src/quota-shadow-placement.test.ts new file mode 100644 index 0000000000..de7c0d1893 --- /dev/null +++ b/pm-stack/aggregator/src/quota-shadow-placement.test.ts @@ -0,0 +1,373 @@ +import { describe, expect, test } from "bun:test"; +import { buildShadowPlacement, liveOrderingFor } from "./quota-shadow-placement.ts"; +import type { QuotaForecastFile, QuotaForecastPool, QuotaForecastWindow } from "./quota-forecast.ts"; +import type { QuotaCurrentEntry, QuotaCurrentFile, QuotaCurrentWindow } from "./model.ts"; + +// Oracle: the Stage-3 design D3 (doc/2026-11-22T22-35-00Z_design_ +// quota-plane-stage-3, #12697): the forecast-informed ordering — +// burn-by-expiry adjusted so a pool projected to wall before its +// reset is demoted BEFORE it reaches the caution zone (NEAR_PCT, +// derive.ts) — is computed beside the live ordering and logged as a +// per-decision diff record. The live ordering is a function of the +// measured data (quota-current) ONLY: no forecast input, however +// alarming or however broken, may change it. S2's named findings +// bind consumption: the bare opencode-go pool's monthly forecast is +// a cross-workspace mixing artifact and is never consumed (the +// per-workspace rows are the real ones); a series the forecast +// itself marks insufficient-history is logged, never consumed. + +const NOW = new Date("2026-11-22T22:00:00.000Z"); +const NOW_MS = NOW.getTime(); +const FRESH = "2026-11-22T21:55:00.000Z"; // 5 min before NOW +const STALE = "2026-11-22T19:00:00.000Z"; // 3 h before NOW +const HOUR = 3_600_000; +const DAY = 24 * HOUR; +const iso = (ms: number) => new Date(ms).toISOString(); + +function window(pctOfLimit: number | null, over: Partial = {}): QuotaCurrentWindow { + return { + name: "weekly", + value: pctOfLimit, + pctOfLimit, + valueLabel: null, + windowSeconds: null, + resetsAt: iso(NOW_MS + 10 * HOUR), + measuredAt: FRESH, + source: "opencode-quota", + state: "ok", + ...over, + }; +} + +function entry(over: Partial = {}): QuotaCurrentEntry { + return { + providerId: "_claude", + providerName: "Claude", + serviceId: "anthropic:claude-pro", + state: "ok", + measuredAt: FRESH, + source: "opencode-quota", + windows: [window(40)], + ...over, + } as QuotaCurrentEntry; +} + +function file(providers: QuotaCurrentEntry[]): QuotaCurrentFile { + return { + version: 1, + generatedAt: FRESH, + source: "opencode-quota", + heartbeat: { tickAt: FRESH, ok: true, durationMs: 1, perProvider: {} }, + providers, + }; +} + +function forecastWindow(over: Partial = {}): QuotaForecastWindow { + return { + name: "weekly", + state: "no-wall-before-reset", + ratePtsPerHour: 1, + samples: 12, + projectedWallAt: null, + durationUntilWallMs: null, + wallsBeforeReset: false, + pctNow: 40, + measuredAt: FRESH, + resetsAt: iso(NOW_MS + 10 * HOUR), + ...over, + }; +} + +function forecastPool(providerId: string, serviceId: string, windows: QuotaForecastWindow[]): QuotaForecastPool { + return { providerId, serviceId, plan: null, windows }; +} + +function forecast(pools: QuotaForecastPool[]): QuotaForecastFile { + const byProvider: Record = {}; + for (const p of pools) (byProvider[p.providerId] ??= []).push(p); + return { version: 1, generatedAt: FRESH, source: "gather-quota", pools: byProvider }; +} + +/** The five-pool measured fixture: two open pools (B expires + * sooner), one unknown (errored read), one caution (90%), one + * walled (100%). */ +function fivePools(): QuotaCurrentFile { + return file([ + entry({ providerId: "_claude", windows: [window(40, { resetsAt: iso(NOW_MS + 10 * HOUR) })] }), + entry({ + providerId: "_openai.main", + providerName: "OpenAI", + serviceId: "_openai.main", + windows: [window(30, { resetsAt: iso(NOW_MS + 2 * HOUR) })], + }), + entry({ + providerId: "deepseek", + providerName: "DeepSeek", + serviceId: "deepseek", + state: "error", + windows: [window(10, { measuredAt: STALE })], + }), + entry({ + providerId: "cline-pass", + providerName: "Cline", + serviceId: "cline-pass", + windows: [window(90, { resetsAt: iso(NOW_MS + 30 * HOUR) })], + }), + entry({ + providerId: "opendesign", + providerName: "OpenDesign", + serviceId: "opendesign", + windows: [window(100, { resetsAt: iso(NOW_MS + 5 * HOUR) })], + }), + ]); +} + +describe("live ordering (measured data only)", () => { + test("burn-by-expiry with measured demotions: soonest reset first, caution below open, unknown above caution, walled last", () => { + const record = buildShadowPlacement(fivePools(), null, NOW); + expect(record.liveOrdering).toEqual(["_openai.main", "_claude", "deepseek", "cline-pass", "opendesign"]); + // With no forecast the shadow ordering IS the live ordering. + expect(record.shadowOrdering).toEqual(record.liveOrdering); + expect(record.summary.identical).toBe(true); + const tiers = Object.fromEntries(record.pools.map((p) => [p.providerId, p.liveTier])); + expect(tiers).toEqual({ + "_openai.main": "open", + _claude: "open", + deepseek: "unknown", + "cline-pass": "caution", + opendesign: "walled", + }); + }); + + test("liveOrderingFor is the same ordering the record carries", () => { + const current = fivePools(); + expect(liveOrderingFor(current, NOW)).toEqual(buildShadowPlacement(current, null, NOW).liveOrdering); + }); +}); + +describe("shadow ordering (forecast-adjusted, logged only)", () => { + test("a pool projected to wall before its reset is demoted before the caution zone", () => { + const current = fivePools(); + const fc = forecast([ + forecastPool( + "_claude", + "anthropic:claude-pro", + [ + forecastWindow({ + state: "projected", + wallsBeforeReset: true, + projectedWallAt: NOW_MS + 5 * HOUR, + durationUntilWallMs: 5 * HOUR, + pctNow: 40, + }), + ], + ), + ]); + const record = buildShadowPlacement(current, fc, NOW); + // Live ordering untouched by the forecast. + expect(record.liveOrdering).toEqual(["_openai.main", "_claude", "deepseek", "cline-pass", "opendesign"]); + // Shadow: _claude (40%, nowhere near the 85% caution zone) drops + // into the caution tier, ahead of cline-pass there by expiry. + expect(record.shadowOrdering).toEqual(["_openai.main", "deepseek", "_claude", "cline-pass", "opendesign"]); + const claude = record.pools.find((p) => p.providerId === "_claude")!; + expect(claude.liveTier).toBe("open"); + expect(claude.shadowTier).toBe("caution"); + expect(claude.demotedByForecast).toBe(true); + expect(claude.moved).toBe("demoted"); + expect(claude.reasons.join(" ")).toContain("weekly"); + expect(record.summary.demotedByForecast).toBe(1); + expect(record.summary.identical).toBe(false); + // deepseek only moved relatively. + const deepseek = record.pools.find((p) => p.providerId === "deepseek")!; + expect(deepseek.moved).toBe("promoted"); + expect(deepseek.demotedByForecast).toBe(false); + }); + + test("the forecast never promotes a measured demotion and never closes a pool", () => { + const current = fivePools(); + const fc = forecast([ + // cline-pass is measured-caution at 90%; a benign forecast + // must not lift it back into the open tier. + forecastPool("cline-pass", "cline-pass", [forecastWindow({ state: "no-wall-before-reset", pctNow: 90 })]), + // opendesign is measured-walled; the shadow ordering is a + // permutation of the live one — same pools, nobody removed. + forecastPool("opendesign", "opendesign", [forecastWindow({ state: "no-wall-before-reset", pctNow: 100 })]), + ]); + const record = buildShadowPlacement(current, fc, NOW); + const cline = record.pools.find((p) => p.providerId === "cline-pass")!; + expect(cline.shadowTier).toBe("caution"); + expect([...record.shadowOrdering].sort()).toEqual([...record.liveOrdering].sort()); + expect(record.shadowOrdering[record.shadowOrdering.length - 1]).toBe("opendesign"); + }); +}); + +describe("no live effect, whatever the forecast says or fails to say", () => { + const variants: [string, QuotaForecastFile | null][] = [ + ["null forecast", null], + ["empty forecast", forecast([])], + [ + "every pool projected to wall", + forecast([ + forecastPool("_claude", "anthropic:claude-pro", [ + forecastWindow({ state: "projected", wallsBeforeReset: true, projectedWallAt: NOW_MS + HOUR }), + ]), + forecastPool("_openai.main", "_openai.main", [ + forecastWindow({ state: "projected", wallsBeforeReset: true, projectedWallAt: NOW_MS + HOUR }), + ]), + forecastPool("cline-pass", "cline-pass", [ + forecastWindow({ state: "projected", wallsBeforeReset: true, projectedWallAt: NOW_MS + HOUR }), + ]), + ]), + ], + [ + "honesty rows only", + forecast([ + forecastPool("_claude", "anthropic:claude-pro", [ + forecastWindow({ + state: "insufficient-history", + ratePtsPerHour: null, + samples: 0, + wallsBeforeReset: null, + pctNow: null, + reason: "fewer than two same-period readings spanning 10 minutes", + }), + ]), + ]), + ], + [ + "stale forecast readings", + forecast([ + forecastPool("_claude", "anthropic:claude-pro", [ + forecastWindow({ + state: "projected", + wallsBeforeReset: true, + projectedWallAt: NOW_MS + HOUR, + measuredAt: STALE, + }), + ]), + ]), + ], + ]; + for (const [name, fc] of variants) { + test(`live ordering identical with ${name}`, () => { + const current = fivePools(); + const record = buildShadowPlacement(current, fc, NOW); + expect(record.liveOrdering).toEqual(liveOrderingFor(current, NOW)); + }); + } + + test("a stale forecast reading degrades to no forecast: no demotion, exclusion logged", () => { + const record = buildShadowPlacement(fivePools(), variants[4][1], NOW); + const claude = record.pools.find((p) => p.providerId === "_claude")!; + expect(claude.demotedByForecast).toBe(false); + expect(claude.shadowTier).toBe("open"); + const input = claude.forecastInputs[0]; + expect(input.consumed).toBe(false); + expect(input.exclusion).toContain("stale"); + }); + + test("an insufficient-history forecast is logged with its reason, never consumed", () => { + const record = buildShadowPlacement(fivePools(), variants[3][1], NOW); + const claude = record.pools.find((p) => p.providerId === "_claude")!; + expect(claude.demotedByForecast).toBe(false); + const input = claude.forecastInputs[0]; + expect(input.consumed).toBe(false); + expect(input.state).toBe("insufficient-history"); + expect(input.reason).toContain("fewer than two same-period readings"); + expect(record.shadowOrdering).toEqual(record.liveOrdering); + }); +}); + +describe("S2 findings bind consumption", () => { + function goPools(): QuotaCurrentFile { + return file([ + entry({ + providerId: "opencode-go", + providerName: "OpenCode Go", + serviceId: "opencode-go", + windows: [window(20, { name: "monthly", resetsAt: iso(NOW_MS + 20 * DAY) })], + }), + entry({ + providerId: "opencode-go.drewrypope", + providerName: "OpenCode Go", + serviceId: "opencode-go.drewrypope", + windows: [window(20, { name: "monthly", resetsAt: iso(NOW_MS + 20 * DAY) })], + }), + ]); + } + const monthlyWall = (pct: number) => + forecastWindow({ + name: "monthly", + state: "projected", + wallsBeforeReset: true, + projectedWallAt: NOW_MS + 5 * DAY, + durationUntilWallMs: 5 * DAY, + pctNow: pct, + resetsAt: iso(NOW_MS + 20 * DAY), + }); + + test("the bare opencode-go pool's monthly forecast is NOT consumed (cross-workspace mixing artifact)", () => { + const fc = forecast([ + forecastPool("opencode-go", "opencode-go", [monthlyWall(20)]), + forecastPool("opencode-go.drewrypope", "opencode-go.drewrypope", [monthlyWall(20)]), + ]); + const record = buildShadowPlacement(goPools(), fc, NOW); + const bare = record.pools.find((p) => p.providerId === "opencode-go")!; + expect(bare.demotedByForecast).toBe(false); + expect(bare.shadowTier).toBe("open"); + expect(bare.forecastInputs[0].consumed).toBe(false); + expect(bare.forecastInputs[0].exclusion).toContain("opencode-go"); + // The per-workspace row is the real one: consumed, demoted. + const ws = record.pools.find((p) => p.providerId === "opencode-go.drewrypope")!; + expect(ws.demotedByForecast).toBe(true); + expect(ws.shadowTier).toBe("caution"); + expect(ws.forecastInputs[0].consumed).toBe(true); + }); +}); + +describe("the diff record S7 scores", () => { + test("carries both orderings, the decision point, per-pool forecast inputs with honesty states, and ranks", () => { + const fc = forecast([ + forecastPool("_claude", "anthropic:claude-pro", [ + forecastWindow({ state: "projected", wallsBeforeReset: true, projectedWallAt: NOW_MS + 5 * HOUR }), + ]), + ]); + const record = buildShadowPlacement(fivePools(), fc, NOW); + expect(record.version).toBe(1); + expect(record.kind).toBe("quota-shadow-placement"); + expect(record.generatedAt).toBe(NOW.toISOString()); + expect(record.decisionPoint.kind).toBe("gatherer-tick"); + expect(record.decisionPoint.at).toBe(NOW.toISOString()); + expect(record.decisionPoint.forecastGeneratedAt).toBe(FRESH); + expect(record.decisionPoint.currentGeneratedAt).toBe(FRESH); + const claude = record.pools.find((p) => p.providerId === "_claude")!; + expect(claude.liveRank).toBe(2); + expect(claude.shadowRank).toBe(3); + expect(claude.measured.percent).toBe(40); + expect(claude.measured.bindingWindow).toBe("weekly"); + expect(claude.forecastInputs).toHaveLength(1); + expect(claude.forecastInputs[0].state).toBe("projected"); + expect(claude.forecastInputs[0].wallsBeforeReset).toBe(true); + expect(claude.forecastInputs[0].projectedWallAt).toBe(NOW_MS + 5 * HOUR); + expect(record.summary.pools).toBe(5); + expect(record.summary.moved).toBe(2); + }); + + test("degenerate inputs produce an empty record, never a throw", () => { + const empty = buildShadowPlacement(file([]), null, NOW); + expect(empty.liveOrdering).toEqual([]); + expect(empty.shadowOrdering).toEqual([]); + expect(empty.summary.pools).toBe(0); + const noWindows = buildShadowPlacement(file([entry({ windows: [] })]), forecast([]), NOW); + expect(noWindows.pools[0].liveTier).toBe("unknown"); + // A forecast for a pool the current read does not carry is not + // placed: placement orders pools that exist in the measured read. + const ghost = buildShadowPlacement( + fivePools(), + forecast([forecastPool("mistral", "mistral", [forecastWindow({ state: "projected", wallsBeforeReset: true })])]), + NOW, + ); + expect(ghost.liveOrdering).not.toContain("mistral"); + expect(ghost.shadowOrdering).not.toContain("mistral"); + }); +}); diff --git a/pm-stack/aggregator/src/quota-shadow-placement.ts b/pm-stack/aggregator/src/quota-shadow-placement.ts new file mode 100644 index 0000000000..7b6e1fe2e9 --- /dev/null +++ b/pm-stack/aggregator/src/quota-shadow-placement.ts @@ -0,0 +1,417 @@ +// Stage-3 shadow placement (#12697, epic #12694; design +// doc/2026-11-22T22-35-00Z_design_quota-plane-stage-3, decision +// D3): each gatherer tick, beside the forecast product, the tick +// computes the placement ordering the forecast implies and logs it +// BESIDE the live ordering as a per-decision diff record — +// quota-shadow-placement.json (latest) plus one appended line per +// tick in quota-shadow-placement-history.jsonl, the accumulating +// record the weekly review (S7) scores. SHADOW ONLY: nothing in the +// live path reads this module's output, the live ordering below is +// a function of the measured data (quota-current) alone, and the +// shadow adjustment can demote a pool in the logged ordering but +// can never promote a measured demotion, never remove a pool, and +// never close anything. Live forecast-driven admission is S4's +// decision, taken on this record's evidence after at least a week +// of shadow diffs. +// +// The orderings. Placement ranks pools (keyed by the canonical +// provider id sessions carry — the pool-state.json / forecast +// keying) for new work: +// - Live: burn-by-expiry under today's measured doctrine. Tiers by +// measured state — open (fresh ok, below the caution zone), then +// unknown (no fresh ok reading: unknown is NOT closed, the pool +// stays in the ordering, it just has no measured expiry to burn +// by), then caution (fresh max percent at/over NEAR_PCT, the +// >=85% zone derive.ts names — today's measured demotion), then +// walled (a fresh window at 100%: closed until reset by the +// standing doctrine). Within a tier: soonest window reset first +// (burn the headroom that expires first — pools should reach +// ~100% AT their reset), then fullest first, then provider id, +// so the order is total and deterministic. +// - Shadow: the same ordering with ONE adjustment, applied before +// the caution zone is reached: a pool in the open tier whose +// consumed forecast projects a wall before its reset is demoted +// into the caution tier. That is the whole forecast effect — +// demotion in a logged ordering, nothing else. +// +// Forecast consumption rules (the design's freshness contract plus +// S2's named findings, #12696): +// - A forecast window is consumed only while its underlying reading +// is fresh by quota-current.ts's overlay bounds; a stale forecast +// degrades to NO forecast for that window — logged as an +// exclusion, never silently used. (S1 only projects fresh-ok +// readings, so in the tick path this is a belt-and-braces check +// on the product's own contract.) +// - A window the forecast itself marks "insufficient-history" is +// logged with its state and reason and never consumed: the +// shadow invents no ordering from a series S2 could not score. +// - The bare opencode-go pool's MONTHLY forecast is never consumed: +// S2's backtest showed that series is a cross-workspace mixing +// artifact (the product assembles the bare pool from every +// workspace's records; its monthly row scored precision 0.054 +// against per-workspace rows at 0.93-1.0). The per-workspace +// pools (opencode-go.) consume their monthly rows +// normally. The exclusion is logged on the record, not silent. +// - Weekly-window projections run systematically late under the +// linear pace (S2's other headline finding). That is calibration +// knowledge for S7's review, not a consumption rule: v1 consumes +// the projection as published and lets the shadow record itself +// measure how the demotions fare. +// +// The record carries everything S7 needs to score shadow-vs-live +// after the fact: both orderings, the decision point's identity +// (the gatherer tick, with the current and forecast products' +// generatedAt stamps), and per pool the measured inputs, EVERY +// forecast window row considered with its honesty state and +// whether it was consumed or excluded (and why), both ranks, and +// the reasons for any movement. Pure: no I/O, no clock reads except +// through arguments — gather-quota.ts does the file IO. +import { NEAR_PCT } from "./derive.ts"; +import { QUOTA_CURRENT_FRESH_MS, QUOTA_CURRENT_FUTURE_SKEW_MS } from "./quota-current.ts"; +import type { QuotaForecastFile, QuotaForecastWindow } from "./quota-forecast.ts"; +import type { QuotaCurrentEntry, QuotaCurrentFile } from "./model.ts"; + +/** Placement tier of one pool in one ordering. */ +export type ShadowTier = "open" | "unknown" | "caution" | "walled"; + +const TIER_RANK: Record = { open: 0, unknown: 1, caution: 2, walled: 3 }; + +/** One forecast window row as the shadow considered it: the S1 + * projection fields verbatim, plus the consumption verdict. */ +export interface ShadowForecastInput { + serviceId: string; + window: string; + state: QuotaForecastWindow["state"]; + wallsBeforeReset: boolean | null; + projectedWallAt: number | null; + ratePtsPerHour: number | null; + samples: number; + pctNow: number | null; + measuredAt: string; + resetsAt: string | null; + reason?: string; + consumed: boolean; + /** Why the row was not consumed, when it was not. */ + exclusion?: string; +} + +export interface ShadowPoolRecord { + providerId: string; + serviceIds: string[]; + liveTier: ShadowTier; + shadowTier: ShadowTier; + liveRank: number; + shadowRank: number; + moved: "demoted" | "promoted" | "unchanged"; + demotedByForecast: boolean; + measured: { + /** Max pctOfLimit across fresh ok windows; null when no fresh + * ok reading exists (never a stale number republished). */ + percent: number | null; + /** The window attaining the max percent. */ + bindingWindow: string | null; + /** The binding window's reset. */ + resetsAt: string | null; + /** Soonest reset across the fresh ok percent windows — the + * burn-by-expiry key. */ + soonestResetAt: string | null; + /** pool-state.ts semantics: walled / near / healthy from a + * fresh ok entry, else the newest entry's state ("stale" for a + * stale ok). */ + state: string | null; + }; + forecastInputs: ShadowForecastInput[]; + reasons: string[]; +} + +export interface ShadowPlacementRecord { + version: 1; + kind: "quota-shadow-placement"; + /** The tick instant this record was computed at. */ + generatedAt: string; + decisionPoint: { + kind: "gatherer-tick"; + at: string; + currentGeneratedAt: string; + forecastGeneratedAt: string | null; + }; + liveOrdering: string[]; + shadowOrdering: string[]; + /** Per-pool records, in live-ordering order. */ + pools: ShadowPoolRecord[]; + summary: { + pools: number; + moved: number; + demotedByForecast: number; + identical: boolean; + }; +} + +interface PoolMeasured { + providerId: string; + serviceIds: string[]; + percent: number | null; + bindingWindow: string | null; + bindingResetsAt: string | null; + soonestResetMs: number | null; + state: string | null; + tier: ShadowTier; +} + +/** quota-current.ts's freshness test, applied to one entry + * (pool-state.ts's isFreshOk rule). */ +function isFreshOk(entry: QuotaCurrentEntry, nowMs: number): boolean { + if (entry.state !== "ok") return false; + const t = Date.parse(entry.measuredAt); + return Number.isFinite(t) && t - nowMs <= QUOTA_CURRENT_FUTURE_SKEW_MS && nowMs - t <= QUOTA_CURRENT_FRESH_MS; +} + +/** The measured half of a pool: fresh-ok windows only. A stale or + * errored entry asserts no percent and no wall (pool-state.ts's + * rule, quota-exhaustion.ts's stale_source rule). */ +function measurePool(providerId: string, entries: QuotaCurrentEntry[], nowMs: number): PoolMeasured { + const serviceIds = [...new Set(entries.map((e) => e.serviceId))].sort(); + const freshOk = entries.filter((e) => isFreshOk(e, nowMs)); + let percent: number | null = null; + let bindingWindow: string | null = null; + let bindingResetsAt: string | null = null; + let bindingResetMs = Infinity; + let soonestResetMs: number | null = null; + for (const entry of freshOk) { + for (const w of entry.windows) { + if (w.state !== "ok" || typeof w.pctOfLimit !== "number" || !Number.isFinite(w.pctOfLimit)) continue; + const resetMs = w.resetsAt ? Date.parse(w.resetsAt) : NaN; + if (Number.isFinite(resetMs) && (soonestResetMs === null || resetMs < soonestResetMs)) soonestResetMs = resetMs; + // Binding window: max percent; ties to the earliest reset, + // then the window name — order-independent. + const better = + percent === null || + w.pctOfLimit > percent || + (w.pctOfLimit === percent && + ((Number.isFinite(resetMs) ? resetMs : Infinity) < bindingResetMs || + ((Number.isFinite(resetMs) ? resetMs : Infinity) === bindingResetMs && (bindingWindow === null || w.name < bindingWindow)))); + if (better) { + percent = w.pctOfLimit; + bindingWindow = w.name; + bindingResetsAt = w.resetsAt; + bindingResetMs = Number.isFinite(resetMs) ? resetMs : Infinity; + } + } + } + if (freshOk.length > 0 && percent !== null) { + return { + providerId, + serviceIds, + percent, + bindingWindow, + bindingResetsAt, + soonestResetMs, + state: percent >= 100 ? "walled" : percent >= NEAR_PCT ? "near" : "healthy", + tier: percent >= 100 ? "walled" : percent >= NEAR_PCT ? "caution" : "open", + }; + } + // No fresh ok percent: the newest entry's state rides, with a + // stale "ok" named as what it is (pool-state.ts). + const newest = entries.reduce((a, b) => (Date.parse(b.measuredAt) > Date.parse(a.measuredAt) ? b : a)); + return { + providerId, + serviceIds, + percent: null, + bindingWindow: null, + bindingResetsAt: null, + soonestResetMs: null, + state: newest.state === "ok" ? "stale" : newest.state, + tier: "unknown", + }; +} + +function comparePools(a: PoolMeasured, tierOf: (p: PoolMeasured) => ShadowTier, b: PoolMeasured): number { + const tierDiff = TIER_RANK[tierOf(a)] - TIER_RANK[tierOf(b)]; + if (tierDiff !== 0) return tierDiff; + const expiryA = a.soonestResetMs ?? Infinity; + const expiryB = b.soonestResetMs ?? Infinity; + if (expiryA !== expiryB) return expiryA - expiryB; + const pctA = a.percent ?? -Infinity; + const pctB = b.percent ?? -Infinity; + if (pctA !== pctB) return pctB - pctA; + return a.providerId < b.providerId ? -1 : a.providerId > b.providerId ? 1 : 0; +} + +function groupByProvider(current: QuotaCurrentFile): Map { + const byProvider = new Map(); + for (const entry of current.providers) { + const list = byProvider.get(entry.providerId) ?? []; + list.push(entry); + byProvider.set(entry.providerId, list); + } + return byProvider; +} + +/** + * The live placement ordering: a function of the measured data + * alone. Exported so the no-live-effect property is directly + * testable — the shadow record's liveOrdering is this function's + * output, whatever forecast was (or was not) supplied. + */ +export function liveOrderingFor(current: QuotaCurrentFile, now = new Date()): string[] { + const nowMs = now.getTime(); + const measured = [...groupByProvider(current)].map(([providerId, entries]) => measurePool(providerId, entries, nowMs)); + return measured + .sort((a, b) => comparePools(a, (p) => p.tier, b)) + .map((p) => p.providerId); +} + +/** The S2 exclusion: the bare opencode-go pool's monthly series is + * assembled from every workspace's records — a mixing artifact, + * not a pool forecast. Per-workspace rows are unaffected. */ +function isBareOpencodeGoMonthly(serviceId: string, windowName: string): boolean { + return serviceId === "opencode-go" && windowName === "monthly"; +} + +/** Consider one provider's forecast rows: build the logged inputs + * and decide whether the forecast demotes the pool in shadow. */ +function considerForecast( + forecast: QuotaForecastFile | null, + providerId: string, + nowMs: number, +): { inputs: ShadowForecastInput[]; demote: boolean; demoteReasons: string[] } { + const inputs: ShadowForecastInput[] = []; + const demoteReasons: string[] = []; + let demote = false; + for (const pool of forecast?.pools[providerId] ?? []) { + for (const w of pool.windows) { + let consumed = true; + let exclusion: string | undefined; + if (isBareOpencodeGoMonthly(pool.serviceId, w.name)) { + consumed = false; + exclusion = + "S2 mixing artifact: the bare opencode-go pool's monthly forecast is assembled from every workspace's records and is not a pool forecast (per-workspace rows are the real ones) — never consumed"; + } else if (w.state === "insufficient-history") { + consumed = false; + exclusion = "forecast honesty state: insufficient-history — logged, never consumed"; + } else { + const measuredMs = Date.parse(w.measuredAt); + if ( + !Number.isFinite(measuredMs) || + measuredMs - nowMs > QUOTA_CURRENT_FUTURE_SKEW_MS || + nowMs - measuredMs > QUOTA_CURRENT_FRESH_MS + ) { + consumed = false; + exclusion = "stale forecast: the underlying reading is outside the quota-current freshness bound — a stale forecast degrades to no forecast"; + } + } + inputs.push({ + serviceId: pool.serviceId, + window: w.name, + state: w.state, + wallsBeforeReset: w.wallsBeforeReset, + projectedWallAt: w.projectedWallAt, + ratePtsPerHour: w.ratePtsPerHour, + samples: w.samples, + pctNow: w.pctNow, + measuredAt: w.measuredAt, + resetsAt: w.resetsAt, + ...(w.reason ? { reason: w.reason } : {}), + consumed, + ...(exclusion ? { exclusion } : {}), + }); + if (consumed && w.state === "projected" && w.wallsBeforeReset === true) { + demote = true; + demoteReasons.push( + `forecast: ${pool.serviceId} ${w.name} projected to wall at ${ + w.projectedWallAt !== null ? new Date(w.projectedWallAt).toISOString() : "?" + } before its reset ${w.resetsAt ?? "?"} — demoted in shadow before the caution zone`, + ); + } + } + } + return { inputs, demote, demoteReasons }; +} + +/** + * Build one tick's shadow-placement diff record from the tick's + * quota-current file and forecast product (null when the forecast + * failed this tick — the record still lands, with the shadow + * ordering equal to the live one and no forecast inputs). Pure: + * no I/O, no clock reads except through arguments. + */ +export function buildShadowPlacement( + current: QuotaCurrentFile, + forecast: QuotaForecastFile | null, + now = new Date(), +): ShadowPlacementRecord { + const nowMs = now.getTime(); + const byProvider = groupByProvider(current); + const measured = [...byProvider].map(([providerId, entries]) => measurePool(providerId, entries, nowMs)); + + const liveSorted = [...measured].sort((a, b) => comparePools(a, (p) => p.tier, b)); + const liveRank = new Map(liveSorted.map((p, i) => [p.providerId, i + 1])); + + const shadowTierOf = new Map(); + const perPool = new Map>(); + for (const pool of measured) { + const considered = considerForecast(forecast, pool.providerId, nowMs); + perPool.set(pool.providerId, considered); + // The whole forecast effect: an open pool projected to wall + // before its reset is demoted into the caution tier. Measured + // tiers are never lifted, unknown pools have no consumable + // forecast (S1 projects fresh-ok readings only), and no pool + // is ever removed or closed by a forecast. + shadowTierOf.set(pool.providerId, pool.tier === "open" && considered.demote ? "caution" : pool.tier); + } + const shadowSorted = [...measured].sort((a, b) => comparePools(a, (p) => shadowTierOf.get(p.providerId)!, b)); + const shadowRank = new Map(shadowSorted.map((p, i) => [p.providerId, i + 1])); + + const pools: ShadowPoolRecord[] = liveSorted.map((pool) => { + const considered = perPool.get(pool.providerId)!; + const lr = liveRank.get(pool.providerId)!; + const sr = shadowRank.get(pool.providerId)!; + const demotedByForecast = considered.demote && pool.tier === "open"; + const reasons: string[] = []; + if (demotedByForecast) reasons.push(...considered.demoteReasons); + else if (sr < lr) reasons.push("relative movement: a pool ranked above this pool in the live ordering was demoted by the forecast"); + else if (sr > lr) reasons.push("relative movement: the forecast demotions reordered the tiers around this pool"); + return { + providerId: pool.providerId, + serviceIds: pool.serviceIds, + liveTier: pool.tier, + shadowTier: shadowTierOf.get(pool.providerId)!, + liveRank: lr, + shadowRank: sr, + moved: sr > lr ? "demoted" : sr < lr ? "promoted" : "unchanged", + demotedByForecast, + measured: { + percent: pool.percent, + bindingWindow: pool.bindingWindow, + resetsAt: pool.bindingResetsAt, + soonestResetAt: pool.soonestResetMs !== null ? new Date(pool.soonestResetMs).toISOString() : null, + state: pool.state, + }, + forecastInputs: considered.inputs, + reasons, + }; + }); + + const liveOrdering = liveSorted.map((p) => p.providerId); + const shadowOrdering = shadowSorted.map((p) => p.providerId); + return { + version: 1, + kind: "quota-shadow-placement", + generatedAt: now.toISOString(), + decisionPoint: { + kind: "gatherer-tick", + at: now.toISOString(), + currentGeneratedAt: current.generatedAt, + forecastGeneratedAt: forecast?.generatedAt ?? null, + }, + liveOrdering, + shadowOrdering, + pools, + summary: { + pools: pools.length, + moved: pools.filter((p) => p.moved !== "unchanged").length, + demotedByForecast: pools.filter((p) => p.demotedByForecast).length, + identical: liveOrdering.every((id, i) => shadowOrdering[i] === id), + }, + }; +}