import { bindRawCodexDecisionResets, publishCodexDecisionQuota } from "../providers/quota-decision-publication";
import { clearDecisionAccountQuotas, decisionQuotaSinkActive } from "../lib/decision-quota-sink";
import { parseCodexCredits, type CodexCredits } from "./credits";
import { forgetMainAccountUsage, observeMainAccountUsage, type FreshWindow } from "./main-account-external-usage";
import { closeSync, constants as fsConstants, existsSync, fstatSync, openSync, readSync, unlinkSync } from "node:fs";
import { join } from "node:path";
import { atomicWriteFile, getConfigDir } from "../config";
import { withConfigDirHardeningSettled } from "../config/paths";
import { captureConfigGeneration, type GenerationContext } from "../lib/state-store-sweeper";
import { codexPlanKey, isThirtyDayOnlyCodexPlan } from "./plan";
import { stampCodexQuotaUsageObservation } from "./quota-observation-freshness";
import { observeCodexLowQuota } from "./low-quota-observer";
import { MAIN_CODEX_ACCOUNT_ID } from "./account-id";
import { getObservedMainQuotaIdentityKey, mainDecisionQuotaWriterGeneration, isMainQuotaWriterLive, type MainQuotaWriter } from "./main-account-cache";

import { CodexQuotaHistory, QUOTA_HISTORY_LIMITS, type QuotaHistoryWindow } from "./quota-history";
import { isPoolQuotaWriterLive, poolQuotaHistoryIdentity, poolQuotaHistoryIdentityOf } from "./account-store";
import type { CodexAccountCredentialRecord } from "../types";
import { detectWeeklyWindowConflicts, type WeeklyWindowConflict } from "./quota-window-conflict";
import { CODEX_EXHAUSTED_USAGE_PERCENT, MAIN_ACCOUNT_HARD_LOCK_MIN_PERCENT, hasSpendableCodexCredits, resetAtToMs } from "./quota-types";
import type { PoolQuotaWriter, StoredAccountQuota, WhamUsageResponse, WhamUsageWindow } from "./quota-types";

export type { StoredAccountQuota, WhamUsageResponse } from "./quota-types";
export { CODEX_EXHAUSTED_USAGE_PERCENT } from "./quota-types";

/** Disk snapshot: quota, private non-secret publication UUIDs and policy identity; never token-derived fingerprints. */
const QUOTA_CACHE_FILENAME = "codex-quota-cache.json";
/** Keep last-known bars across restarts; WHAM still refreshes on TTL in live/prime paths. */
const QUOTA_DISK_MAX_AGE_MS = 6 * 60 * 60_000;
const QUOTA_PERSIST_DEBOUNCE_MS = 250;
/** Match the reset ledger's maximum deferral under sustained quota observations. */
const QUOTA_PERSIST_MAX_DEFERRAL_MS = 1_000;

type QuotaDiskFile = {
  version: 1;
  quotas: Record<string, StoredAccountQuota>;
  mainPolicyQuota?: MainPolicyQuota;
  history?: ReturnType<CodexQuotaHistory["serialize"]>;
};

type MainPolicyQuota = { identityKey: string; quota: StoredAccountQuota };
/** Fresh WHAM topology proof is consumed by the merge, never retained in a cache or DTO. */
type MainPolicyQuotaObservation = Omit<StoredAccountQuota, "updatedAt"> & { shortWindowAbsent?: true; monthlyWindowAbsent?: true };
let mainPolicyQuota: MainPolicyQuota | null = null;
/**
 * When each main policy usage window was last measured in this process (#8113). A window's time
 * moves only when a write measures that window's percentage; reset metadata, credits and other
 * windows never renew it. Process-local and never persisted: a reading restored from disk has none.
 */
type PolicyUsageWindow = "shortPercent" | "weeklyPercent" | "monthlyPercent";
const POLICY_USAGE_WINDOWS: readonly PolicyUsageWindow[] = ["shortPercent", "weeklyPercent", "monthlyPercent"];
let mainPolicyUsageObservation: { identityKey: string; at: Partial<Record<PolicyUsageWindow, number>> } | undefined;
let diskHydrated = false;
let persistTimer: ReturnType<typeof setTimeout> | null = null;
let persistStartedAt: number | null = null;
/** The latest admitted snapshot write; settles even when admission times out. */
let persistWrite: Promise<void> = Promise.resolve();
/** Bumped by a full clear so a fired callback still waiting for ACL admission writes nothing. */
let persistGeneration = 0;
/** Test seam: wait for a fired persistence callback's admitted write. */
export function settleQuotaPersistenceForTests(): Promise<void> { return persistWrite; }

const MONTHLY_WINDOW_MIN_SECONDS = 28 * 24 * 60 * 60;
/**
 * Shortest window still plausibly the WEEKLY quota (#1791).
 *
 * K12 and similar plans send a 5-hour primary window plus a 7-day secondary. Folding the
 * primary into `weeklyPercent` reported the 5-hour bar as the weekly one and discarded the
 * real weekly reading entirely, so the dashboard showed a window that reset every few hours
 * and routing never saw the limit that actually gates the account.
 *
 * 24h is the discriminator: anything shorter is a burst window, not a weekly one. A window
 * with no declared duration is unchanged, because older payloads omit `limit_window_seconds`
 * and guessing there would break every legacy account.
 */
const WEEKLY_WINDOW_MIN_SECONDS = 24 * 60 * 60;
const MONTHLY_WINDOW_MIN_MINUTES = MONTHLY_WINDOW_MIN_SECONDS / 60;
// Derived, never written as a literal: the header parser and the WHAM parser must not be able
// to drift to different thresholds, which is the class of defect this pair exists to prevent.
const WEEKLY_WINDOW_MIN_MINUTES = WEEKLY_WINDOW_MIN_SECONDS / 60;
/**
 * Seconds/milliseconds split for a stored reset instant: below it the value is Unix seconds,
 * at or above it milliseconds.
 *
 * Both units reach storage — `normalizeResetAt` does not scale, and the GUI disambiguates by
 * magnitude at read time — so a comparison written against one assumption is off by 1000x
 * against the other. In the seconds-read-as-milliseconds direction every reading looks like it
 * elapsed in 1970, which is a check that passes its own test and does nothing.
 *
 * The split now lives on `./quota-types`, the leaf the dashboard can also import, because the
 * dashboard was the reader that did not have it (#5045). Re-exported here so the existing
 * callers of this module keep their import path.
 */
export { resetAtToMs };

const accountQuota = new Map<string, StoredAccountQuota>();
const quotaHistory = new CodexQuotaHistory();
let lastReconciledGeneration = 0;
let liveAccountIds = new Set<string>();

function mayCommitAccountQuota(accountId: string, writerGeneration: number): boolean {
  return writerGeneration >= lastReconciledGeneration || liveAccountIds.has(accountId);
}

// Valid upstream percentages are normalized to 0..100. Keep "unknown" outside that domain so an
// actually exhausted account is still eligible for threshold rotation.
export const CODEX_UNKNOWN_USAGE_SCORE = 101;
export function isCodexQuotaExhausted(
  quota: Pick<StoredAccountQuota, "weeklyPercent" | "monthlyPercent" | "shortPercent" | "credits"> | null,
  plan?: unknown,
  allowCredits = false,
): boolean {
  if (!quota) return false;
  if (allowCredits && hasSpendableCodexCredits(quota)) return false;
  // The burst window counts on EVERY plan. It is upstream-enforced independently, so an
  // account at 100% there is blocked regardless of which longer window governs its plan;
  // omitting it would route traffic straight into a 429 (#1791).
  const values = codexQuotaWindowForPlan(plan) === "monthly"
    ? [quota.monthlyPercent, quota.shortPercent]
    : [quota.weeklyPercent, quota.monthlyPercent, quota.shortPercent];
  return values.some(value => typeof value === "number"
    && Number.isFinite(value)
    && value >= CODEX_EXHAUSTED_USAGE_PERCENT);
}

/**
 * Which usage window a plan reports in. This is the SINGLE rule shared by quota
 * parsing, exhaustion, and recovery — they must not diverge.
 *
 * An allowlist of "known" plans was tried here and was wrong: the upstream model
 * snapshot alone carries 21 distinct plan strings (`edu_plus`, `finserv`, `k12`,
 * `quorum`, `self_serve_business_usage_based`, ...), and `CodexAccount.plan` is an
 * unrestricted string, so any list is a list of the plans someone remembered.
 * Twelve real plans would have been refused recovery and stayed cooled forever —
 * the very defect this unit exists to fix, reintroduced as a typo-shaped hole.
 *
 * The honest rule is the parser's own: Go and Free report a 30-day window,
 * everything else (including an absent plan) reports weekly. Recovery reads the
 * window the parser actually wrote rather than second-guessing it.
 */
export function codexQuotaWindowForPlan(plan?: unknown): "monthly" | "weekly" {
  return isThirtyDayOnlyCodexPlan(plan) ? "monthly" : "weekly";
}

export function isCompleteCodexQuotaRecoverySnapshot(
  quota: Pick<StoredAccountQuota, "weeklyPercent" | "monthlyPercent" | "monthlyIsPrimaryWindow" | "shortPercent" | "credits"> | null,
  plan?: unknown,
  allowCredits = false,
): boolean {
  if (!quota || isCodexQuotaExhausted(quota, plan, allowCredits)) return false;
  // Recovery still fails closed on MISSING EVIDENCE — a credits-only or windowless payload
  // carries no usage reading at all and must never clear a cooldown. What it does not do is
  // fail closed on an unfamiliar plan NAME, which only ever meant "cooled forever".
  //
  // The parser classifies windows by DURATION, not by plan name: a Team response whose
  // primary window is explicitly monthly parses to monthlyPercent only (no secondary
  // window exists), so requiring weeklyPercent because the plan is not go/free would
  // strand exactly those accounts until their predicted expiry. Accept whichever window(s)
  // the parser actually wrote; Go/Free never carry a weekly value, so monthly-only is
  // required there.
  //
  // Audit correction: "the parser wrote monthlyPercent" is NOT by itself evidence for a
  // weekly-quota plan. A tertiary-only response also writes monthlyPercent, and it says
  // nothing about the weekly quota that actually gates a Team/Plus account — accepting it
  // would clear the cooldown on a reading of a different window. Only an explicitly-monthly
  // PRIMARY window is the governing reading, which is what `monthlyIsPrimaryWindow` records.
  if (codexQuotaWindowForPlan(plan) === "monthly") {
    return finitePercent(quota.monthlyPercent);
  }
  if (finitePercent(quota.weeklyPercent)) return true;
  return quota.monthlyIsPrimaryWindow === true && finitePercent(quota.monthlyPercent);
}

function finitePercent(value: number | undefined): value is number {
  return typeof value === "number" && Number.isFinite(value);
}

function parseFiniteUsagePercent(value: unknown): number | undefined {
  const numeric = typeof value === "number"
    ? value
    : typeof value === "string" && value.trim() !== ""
      ? Number(value)
      : undefined;
  return typeof numeric === "number" && Number.isFinite(numeric) ? numeric : undefined;
}

export function normalizeUsagePercent(value: unknown): number | undefined {
  const numeric = parseFiniteUsagePercent(value);
  return numeric === undefined ? undefined : Math.max(0, Math.min(100, numeric));
}

/** Undefined marks an absent group reading. Null marks invalid evidence. */
function parseGroupUsagePercent(value: unknown): number | null | undefined {
  if (value == null) return undefined;
  const percent = parseFiniteUsagePercent(value);
  return percent === undefined || percent < 0 || percent > 100 ? null : percent;
}

/** Reject numeric policy evidence before legacy clamping can fabricate a valid reading. */
function isInvalidPolicyUsagePercent(value: unknown): boolean {
  if (typeof value === "number") return !Number.isFinite(value) || value < 0 || value > 100;
  if (typeof value !== "string" || value.trim() === "") return false;
  const numeric = Number(value);
  // Non-numeric metadata stays unknown; explicit nonfinite spellings are invalid evidence.
  if (Number.isNaN(numeric)) return /^[+-]?(?:nan|infinity)$/i.test(value.trim());
  return !Number.isFinite(numeric) || numeric < 0 || numeric > 100;
}

function normalizeResetAt(value: unknown): number | undefined {
  const numeric = typeof value === "number"
    ? value
    : typeof value === "string" && value.trim() !== ""
      ? Number(value)
      : undefined;
  if (typeof numeric !== "number" || !Number.isFinite(numeric) || numeric < 0) return undefined;
  return numeric;
}

function hasKnownQuotaValue(quota: Omit<StoredAccountQuota, "updatedAt">): boolean {
  return [quota.weeklyPercent, quota.monthlyPercent, quota.shortPercent]
    .some(value => typeof value === "number" && Number.isFinite(value))
    // Known short-window shape with unknown usage still selects that window for policy.
    || snapshotHasShort(quota)
    || !!quota.customWindows?.some(window => Number.isFinite(window.percent));
}

/** True only for a window that DECLARES a duration shorter than a day. */
function isExplicitShortWindow(window: WhamUsageWindow | null | undefined): boolean {
  const seconds = window?.limit_window_seconds;
  return typeof seconds === "number"
    && Number.isFinite(seconds)
    && seconds > 0
    && seconds < WEEKLY_WINDOW_MIN_SECONDS;
}

function isExplicitMonthlyWindow(window: WhamUsageWindow | null | undefined): boolean {
  const seconds = window?.limit_window_seconds;
  return typeof seconds === "number"
    && Number.isFinite(seconds)
    && seconds >= MONTHLY_WINDOW_MIN_SECONDS;
}

/** Same 24h short/long boundary as the parser; this includes a declared one-day window. */
function isExplicitLongWindow(window: WhamUsageWindow | null | undefined): boolean {
  const seconds = window?.limit_window_seconds;
  return typeof seconds === "number" && Number.isFinite(seconds) && seconds >= WEEKLY_WINDOW_MIN_SECONDS;
}

function isExplicitMonthlyWindowMinutes(windowMinutes: unknown): boolean {
  const minutes = windowMinutes_(windowMinutes);
  return minutes !== undefined && minutes >= MONTHLY_WINDOW_MIN_MINUTES;
}

/** The header wire reports a window duration in MINUTES; WHAM reports it in seconds. */
function windowMinutes_(value: unknown): number | undefined {
  const minutes = typeof value === "number"
    ? value
    : typeof value === "string" && value.trim() !== ""
      ? Number(value)
      : undefined;
  return typeof minutes === "number" && Number.isFinite(minutes) ? minutes : undefined;
}

/** Minutes-domain twin of isExplicitShortWindow. Same strict `<`, same 24h discriminator. */
function isExplicitShortWindowMinutes(value: unknown): boolean {
  const minutes = windowMinutes_(value);
  return minutes !== undefined && minutes > 0 && minutes < WEEKLY_WINDOW_MIN_MINUTES;
}


function snapshotHasWeekly(quota: Omit<StoredAccountQuota, "updatedAt">): boolean {
  return quota.weeklyPercent !== undefined || quota.weeklyResetAt !== undefined;
}

function snapshotHasMonthly(quota: Omit<StoredAccountQuota, "updatedAt">): boolean {
  return quota.monthlyPercent !== undefined || quota.monthlyResetAt !== undefined;
}

function snapshotHasShort(quota: Omit<StoredAccountQuota, "updatedAt">): boolean {
  return quota.shortPercent !== undefined
    || quota.shortResetAt !== undefined
    || quota.shortWindowSeconds !== undefined;
}

function shortResetHasElapsed(resetAt: number | undefined, now: number): boolean {
  if (typeof resetAt !== "number" || !Number.isFinite(resetAt) || resetAt <= 0) return false;
  return resetAtToMs(resetAt) <= now;
}

/**
 * Whether the account's reset tickets went DOWN, which means one was just redeemed.
 *
 * A manual reset zeroes the current window's usage without ending it: the deadline moves further
 * out, but the account keeps spending in what is effectively a fresh window. The percentage we
 * cached before the redemption measures the window that was thrown away, so it must not be
 * carried into the reset one — the user has, by definition, just bought themselves an empty
 * window, and reporting the old 98% keeps them locked out of the quota they paid to recover.
 *
 * Only a DECREASE counts. Upstream periodically grants new tickets (`available_count` rising),
 * which says nothing about current usage and must never invalidate a reading.
 *
 * This is the one signal that catches a redemption made outside this process — in the ChatGPT web
 * UI, or on another machine. The header stream carries no reset-ticket field at all, so it can
 * only ever be learned from the `/wham/usage` payload, and the hard lock delays that probe by
 * minutes-to-an-hour. Keeping the judgement data-driven and here means the moment any observation
 * does carry the new count, the stale percentage is retired instead of replayed.
 */
function resetTicketWasRedeemed(
  incoming: Omit<StoredAccountQuota, "updatedAt">,
  existing: StoredAccountQuota | undefined,
): boolean {
  const previousCount = existing?.resetCredits;
  const nextCount = incoming.resetCredits;
  if (typeof previousCount !== "number" || !Number.isFinite(previousCount)) return false;
  if (typeof nextCount !== "number" || !Number.isFinite(nextCount)) return false;
  return nextCount < previousCount;
}

/**
 * Whether the stored weekly reading belongs to a window that is demonstrably over.
 *
 * This is the weekly counterpart of `shortResetHasElapsed`. The short (5h) branch has always
 * expired a carried tuple whose reset had passed; the weekly branch never did, so a stale
 * weekly percentage could outlive its own deadline indefinitely as long as observations omitted
 * the weekly header. Either of these retires the reading (an observation that carries the weekly
 * window itself, including a later deadline, already replaces the tuple before this is consulted):
 *
 * 1. The stored deadline has already elapsed. Usage only accumulates inside an open window, so a
 *    percentage pinned to a closed one is history, not current state. This is exactly the rule
 *    `shortResetHasElapsed` applies to the 5h tuple and it is what lets a stuck account re-measure.
 * 2. A reset ticket was redeemed (`resetTicketWasRedeemed`) — the window's usage was zeroed on
 *    purpose, so the pre-redemption percentage describes a window nobody is spending in any more.
 *
 * Why this matters beyond a cosmetic bar: this display/rotation snapshot feeds quota exhaustion and
 * the pool rotation score. A percentage that can never expire keeps a recovered account excluded and
 * its card at "usage limit reached" while upstream shows a nearly-empty window. The main-account hard
 * lock is unaffected: it reads the separate policy snapshot, which these signals never touch.
 *
 * Policy callers must NOT use these signals. The hard lock's contract is that only an explicit
 * observation that replaces a blocking reading may release it — "a predicted reset is not
 * recovery evidence". There, a clock elapsing, an advanced deadline, and a redeemed ticket are
 * all non-events; the arriving low percentage is what releases it.
 *
 * Observed live, twice:
 * - Upstream had rolled the window over while every response carried only credits headers, so the
 *   old 98% was replayed for ~20h against a true 4%.
 * - The user then redeemed a reset ticket in the web UI. Upstream reported 0% used with a deadline
 *   4.84 days further out, but the cache still said 98%, so the hard lock kept refusing to send.
 * Both times only manual cache surgery recovered the account.
 */
function weeklyWindowRolledOver(
  incoming: Omit<StoredAccountQuota, "updatedAt">,
  existing: StoredAccountQuota | undefined,
  now: number,
): boolean {
  if (resetTicketWasRedeemed(incoming, existing)) return true;
  const previousReset = existing?.weeklyResetAt;
  if (typeof previousReset !== "number" || !Number.isFinite(previousReset) || previousReset <= 0) return false;
  return resetAtToMs(previousReset) <= now;
}

/** Display/rotation carry expires; a reset clock cannot retract blocking hard-lock evidence. */
function assignCarriedShort(
  next: StoredAccountQuota,
  existing: StoredAccountQuota | undefined,
  now: number,
  policyEvidence = false,
): void {
  if (!existing) return;
  const existingShortPercent = existing.shortPercent;
  const preserveBlockingEvidence = policyEvidence
    && finitePercent(existingShortPercent)
    && existingShortPercent >= MAIN_ACCOUNT_HARD_LOCK_MIN_PERCENT
    && existingShortPercent <= 100;
  if (!preserveBlockingEvidence && shortResetHasElapsed(existing.shortResetAt, now)) return;
  if (existing.shortPercent !== undefined) next.shortPercent = existing.shortPercent;
  if (existing.shortObservedAt !== undefined) next.shortObservedAt = existing.shortObservedAt;
  if (existing.shortResetAt !== undefined) next.shortResetAt = existing.shortResetAt;
  if (existing.shortWindowSeconds !== undefined) next.shortWindowSeconds = existing.shortWindowSeconds;
}

function snapshotHasCustom(quota: Omit<StoredAccountQuota, "updatedAt">): boolean {
  return quota.customWindows !== undefined;
}

function snapshotHasUsage(quota: Omit<StoredAccountQuota, "updatedAt">): boolean {
  return snapshotHasWeekly(quota) || snapshotHasMonthly(quota) || snapshotHasShort(quota) || snapshotHasCustom(quota);
}

function snapshotHasCredits(quota: Omit<StoredAccountQuota, "updatedAt">): boolean {
  return quota.resetCredits !== undefined || quota.credits !== undefined;
}
/**
 * Publish parsed display quota and separately validated policy evidence after writer checks.
 * A null policy observation retains only the matching main identity's previous evidence;
 * transient replacement markers are consumed during merging and never enter stored snapshots.
 */
export function setAccountQuotaFromParsed(
  accountId: string,
  quota: Omit<StoredAccountQuota, "updatedAt"> | null,
  writerGeneration = captureConfigGeneration(),
  mainWriter?: MainQuotaWriter,
  policyQuota: MainPolicyQuotaObservation | null = accountId === MAIN_CODEX_ACCOUNT_ID ? quota : null,
  historyEvidence?: QuotaObservationEvidence,
  // Pool responses carry their credential provenance separately from the optional history
  // writer: when capture failed before dispatch, an absent writer must fail closed instead
  // of reading as a writer-free legacy/login observation.
  poolRequest = false,
  decisionObservationPartial = true,
  // Advisory publication is explicit opt-in evidence: display or policy data never becomes it by default.
  decisionRaw: Omit<StoredAccountQuota, "updatedAt"> | null = null,
): void {
  quota = withoutRetiredCodexQuota(quota);
  policyQuota = withoutRetiredCodexQuota(policyQuota);
  if (!quota || (!snapshotHasUsage(quota) && !snapshotHasCredits(quota))) return;
  if (!mayCommitAccountQuota(accountId, writerGeneration)) return;
  const isMain = accountId === MAIN_CODEX_ACCOUNT_ID;
  if (isMain && mainWriter && !isMainQuotaWriterLive(mainWriter)) return;
  hydrateAccountQuotasFromDisk();
  const legacyExisting = accountQuota.get(accountId);
  const updatedAt = Date.now();
  const livePoolEvidence = historyEvidence
    ? historyEvidence.writer.accountId === accountId && isPoolQuotaWriterLive(historyEvidence.writer)
    : !poolRequest;
  if (historyEvidence && livePoolEvidence) {
    publishCodexDecisionQuota(accountId, historyEvidence.writer.credentialGeneration, historyEvidence.raw, historyEvidence.observedAt, "codex", historyEvidence.source === "response-header");
    quotaHistory.append(historyEvidence.writer, { observedAt: historyEvidence.observedAt, source: historyEvidence.source,
      credentialGeneration: historyEvidence.writer.credentialGeneration, windows: historyWindows(historyEvidence.raw),
    }, updatedAt);
  }
  // Rotation shares validated main-window retirement, but never inherits policy-only
  // evidence that outlived its disk TTL. Policy has a separate, identity-checked base.
  const mainDecisionGeneration = mainWriter && mainDecisionQuotaWriterGeneration(mainWriter);
  if (isMain && mainDecisionGeneration !== undefined && decisionRaw)
    publishCodexDecisionQuota(accountId, mainDecisionGeneration, decisionRaw, updatedAt, "codex-main", decisionObservationPartial);
  // Retiring a short tuple releases a routing block, so it needs the same writer proof as
  // history: a live main writer for main, a live captured pool writer for pool requests.
  const mayRetireShort = isMain ? mainWriter !== undefined : livePoolEvidence;
  // Monthly-window absence (#8067) comes from the same complete topology and needs the same proof.
  const displayQuota: MainPolicyQuotaObservation = {
    ...quota,
    ...(mayRetireShort && policyQuota?.shortWindowAbsent === true ? { shortWindowAbsent: true as const } : {}),
    ...(mayRetireShort && policyQuota?.monthlyWindowAbsent === true ? { monthlyWindowAbsent: true as const } : {}),
  };
  const next = mergeAccountQuota(displayQuota, legacyExisting, updatedAt);
  accountQuota.set(accountId, next);
  if (isMain) {
    if (mainWriter && policyQuota && snapshotHasUsage(policyQuota)) {
      const windows: FreshWindow[] = [];
      const add = (kind: FreshWindow["kind"], percent: number | undefined, reset: number | undefined) => {
        if (finitePercent(percent) && percent >= 0 && percent <= 100
          && typeof reset === "number" && Number.isFinite(reset) && reset > 0) {
          windows.push({ kind, percent, resetAtMs: resetAtToMs(reset) });
        }
      };
      add("short", policyQuota.shortPercent, policyQuota.shortResetAt);
      if (policyQuota.monthlyIsPrimaryWindow === true) add("long", policyQuota.monthlyPercent, policyQuota.monthlyResetAt);
      else add("long", policyQuota.weeklyPercent, policyQuota.weeklyResetAt);
      observeMainAccountUsage(mainWriter.identityKey, windows, updatedAt);
    }
    const policyExisting = mainWriter && mainPolicyQuota?.identityKey === mainWriter.identityKey
      ? mainPolicyQuota.quota
      : undefined;
    // Only a measured percentage renews its own window; anything else keeps the earlier time.
    if (mainWriter && policyQuota) {
      const at = mainPolicyUsageObservation?.identityKey === mainWriter.identityKey && policyExisting
        ? { ...mainPolicyUsageObservation.at } : {};
      for (const window of POLICY_USAGE_WINDOWS) if (finitePercent(policyQuota[window])) at[window] = updatedAt;
      mainPolicyUsageObservation = { identityKey: mainWriter.identityKey, at };
    }
    mainPolicyQuota = mainWriter && (policyQuota || policyExisting)
      ? {
        identityKey: mainWriter.identityKey,
        quota: policyQuota
          ? structuredClone(mergeAccountQuota(policyQuota, policyExisting, updatedAt, true))
          : policyExisting!,
      }
      : null;
    if (!mainPolicyQuota) mainPolicyUsageObservation = undefined;
  }
  schedulePersistAccountQuotas();
  // Credits carry the previous usage tuple; they must not refresh its observation clock.
  if (!(snapshotHasCredits(quota) && !snapshotHasUsage(quota))) {
    if (!isMain && policyQuota && livePoolEvidence) observeCodexLowQuota(accountId, policyQuota);
    notifyCodexQuotaSnapshot(accountId, next);
  }
}

/**
 * Merge a partial observation into the legacy or identity-bound policy snapshot.
 * Policy mode retains omitted blocking short usage unless this observation authorizes replacement;
 * the returned snapshot contains quota fields only, without the transient replacement marker.
 */
function mergeAccountQuota(
  quota: MainPolicyQuotaObservation,
  existing: StoredAccountQuota | undefined,
  updatedAt: number,
  policyEvidence = false,
): StoredAccountQuota {
  quota = withoutRetiredCodexQuota(quota) ?? {};
  existing = withoutRetiredCodexQuota(existing ?? null) ?? undefined;
  const next: StoredAccountQuota = { updatedAt };
  const creditsOnly = snapshotHasCredits(quota) && !snapshotHasUsage(quota);
  // An explicit empty/invalid credits summary retracts the old balance. Partial headers
  // retain the original observation clock instead of extending its spending authority.
  const creditSource = quota.credits !== undefined ? quota : existing;
  if (creditSource?.credits !== undefined) next.credits = creditSource.credits;
  if (creditSource?.credits === null && creditSource.creditObservationUnavailable === true) {
    next.creditObservationUnavailable = true;
  }

  if (creditsOnly) {
    // A credits-only refresh says nothing about usage windows, so it normally carries the known
    // ones. The exception is a weekly window upstream has already rolled over: replaying that
    // percentage would report the previous window's usage as the current one, and a
    // credits-only-only stream would keep doing so indefinitely. Policy evidence is exempt for
    // the same reason as below: only an explicit lower observation may release the hard lock.
    const weeklyRolledOver = !policyEvidence && weeklyWindowRolledOver(quota, existing, updatedAt);
    if (existing?.weeklyPercent !== undefined && !weeklyRolledOver) next.weeklyPercent = existing.weeklyPercent;
    if (existing?.weeklyResetAt !== undefined && !weeklyRolledOver) next.weeklyResetAt = existing.weeklyResetAt;
    if (existing?.monthlyPercent !== undefined) next.monthlyPercent = existing.monthlyPercent;
    if (existing?.monthlyResetAt !== undefined) next.monthlyResetAt = existing.monthlyResetAt;
    if (existing?.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
    assignCarriedShort(next, existing, updatedAt, policyEvidence);
    if (existing?.customWindows !== undefined) next.customWindows = existing.customWindows;
    if (quota.resetCredits !== undefined) next.resetCredits = quota.resetCredits;
    else if (existing?.resetCredits !== undefined) next.resetCredits = existing.resetCredits;
    return stampCodexQuotaUsageObservation(next, quota, existing);
  }

  const existingWeeklyPercent = existing?.weeklyPercent;
  // The one thing a stale reading must never survive: proof that its window is over.
  // Display only. Policy evidence obeys a stricter contract — see preserveKnownWeekly below.
  const weeklyRolledOver = weeklyWindowRolledOver(quota, existing, updatedAt);
  // A reset-only weekly observation is not a lower reading. Policy mode keeps a blocking weekly
  // tuple whole, exactly like preserveKnownShort; a governing monthly-primary observation still
  // replaces it, so that release path does not depend on this guard.
  //
  // This guard is deliberately NOT relaxed for a rolled-over or advanced window. Policy evidence
  // is the hard lock's only input, and "a predicted reset is not recovery evidence" is a pinned
  // contract: `main-account-hard-lock-policy` asserts that advancing `weeklyResetAt` from now+60s
  // to now+120s alone must NOT clear a retained 99. Releasing the lock has to stay a deliberate,
  // explicitly-observed decision, so the policy path is left exactly as upstream wrote it. The
  // display path below is where a dead reading is allowed to expire.
  const preserveKnownWeekly = policyEvidence
    && quota.weeklyPercent === undefined
    && quota.monthlyIsPrimaryWindow !== true
    && finitePercent(existingWeeklyPercent)
    && existingWeeklyPercent >= MAIN_ACCOUNT_HARD_LOCK_MIN_PERCENT
    && existingWeeklyPercent <= 100;
  if (snapshotHasWeekly(quota) && !preserveKnownWeekly) {
    if (quota.weeklyPercent !== undefined) next.weeklyPercent = quota.weeklyPercent;
    if (quota.weeklyResetAt !== undefined) next.weeklyResetAt = quota.weeklyResetAt;
  } else if (snapshotHasMonthly(quota)
    && (!policyEvidence || quota.monthlyIsPrimaryWindow === true)) {
    // Legacy monthly-only clearing is unchanged (#382). Policy needs a governing
    // monthly-primary observation: a tertiary-only header cannot retract weekly99.
  } else if (existing?.weeklyPercent !== undefined
    && (policyEvidence || !weeklyRolledOver)) {
    // Carry-forward is for windows whose deadline upstream has not moved. Once it has, the
    // percentage we hold belongs to the closed window; re-publishing it would hand the next
    // window a usage figure it never earned. Leaving the field unset is correct here — the
    // caller treats "unknown" as "needs a fresh measurement", which is exactly the state that
    // lets quota auto-refresh recover.
    //
    // Policy mode is exempt and always carries: it must only ever change through an explicit
    // observation, so it never expires on its own clock. That is the pinned contract above, and
    // admitting either signal here re-opens the "predicted reset releases the lock" hole.
    next.weeklyPercent = existing.weeklyPercent;
    if (existing.weeklyResetAt !== undefined) next.weeklyResetAt = existing.weeklyResetAt;
  }

  if (snapshotHasMonthly(quota)) {
    if (quota.monthlyPercent !== undefined) next.monthlyPercent = quota.monthlyPercent;
    if (quota.monthlyResetAt !== undefined) next.monthlyResetAt = quota.monthlyResetAt;
    // Carry the provenance with the value it describes. Recovery reads `freshQuota` directly,
    // so this is not on its path today — but a cached snapshot that kept `monthlyPercent`
    // while silently dropping `monthlyIsPrimaryWindow` would look like tertiary-only data to
    // any future reader, and that failure would be invisible.
    if (quota.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
  } else if (quota.monthlyWindowAbsent !== true
      && (snapshotHasWeekly(quota) || snapshotHasShort(quota) || snapshotHasCustom(quota))
      && existing?.monthlyPercent !== undefined) {
    // A complete topology with no monthly-length window retires the carried tuple, so a plan
    // change away from a monthly primary (Free to Pro Lite) cannot keep its old exhausted reading.
    next.monthlyPercent = existing.monthlyPercent;
    if (existing.monthlyResetAt !== undefined) next.monthlyResetAt = existing.monthlyResetAt;
    if (existing.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
  }

  const existingShortPercent = existing?.shortPercent;
  const preserveKnownShort = policyEvidence
    && quota.shortPercent === undefined
    && finitePercent(existingShortPercent)
    && existingShortPercent >= MAIN_ACCOUNT_HARD_LOCK_MIN_PERCENT
    && existingShortPercent <= 100;
  if (snapshotHasShort(quota) && !preserveKnownShort) {
    if (quota.shortPercent !== undefined) {
      next.shortPercent = quota.shortPercent;
      if (Number.isFinite(quota.shortPercent)) next.shortObservedAt = next.updatedAt;
    }
    if (quota.shortResetAt !== undefined) next.shortResetAt = quota.shortResetAt;
    if (quota.shortWindowSeconds !== undefined) next.shortWindowSeconds = quota.shortWindowSeconds;
  } else if (quota.shortWindowAbsent !== true) {
    // Unknown usage is not a lower reading. Retain the entire known tuple: pairing
    // its percentage with new metadata would silently extend or shorten its reset.
    // An elapsed reset is the exception. It describes a window that has already rolled over,
    // and carrying it republishes updatedAt, which is exactly what kept a Spark-polluted Pro
    // row alive past the six-hour disk TTL that #4122 expected to expire it.
    assignCarriedShort(next, existing, updatedAt, policyEvidence);
  }

  if (snapshotHasCustom(quota)) next.customWindows = quota.customWindows;
  // Ordinary response headers omit model-specific windows reported by WHAM.
  // Absence is a partial update; an explicit list (including []) still replaces it.
  else if (existing?.customWindows !== undefined) next.customWindows = existing.customWindows;

  if (quota.resetCredits !== undefined) next.resetCredits = quota.resetCredits;
  else if (existing?.resetCredits !== undefined) next.resetCredits = existing.resetCredits;

  return stampCodexQuotaUsageObservation(next, quota, existing);
}

/**
 * Hand a committed snapshot to the optional quota-reset observer.
 *
 * Lazy import on purpose. This file is statically reachable from
 * src/server/responses/core.ts (via codex/auth-context.ts), and
 * applyAccountQuotaFromUpstreamHeaders runs it once per pooled response. A static import
 * would load the observer, its config resolution, and its sink registry into every install,
 * including installs that never enable the feature — the same failure mode
 * tests/core-lab-boundary.test.ts exists to prevent for src/lab/.
 *
 * The previous snapshot is deliberately NOT passed. The observer keeps its own persisted
 * baseline (see swapLastObservedWindows), so every committed write must reach it — including
 * the first one, which is what establishes that baseline. An earlier version of this
 * function skipped the call when the in-map `existing` was undefined; that left the observer
 * with no baseline to compare against, so the write AFTER a rollover was silently treated as
 * the first observation and no reset ever fired.
 *
 * The snapshot is COPIED synchronously, before the import resolves. `next` is the live map
 * value and the next write mutates it, so an observation that read it after awaiting could
 * see a later snapshot than the one it was called for.
 *
 * Observations are SERIALIZED through a module-level promise chain, because the baseline
 * swap must happen in call order. An earlier version awaited two imports and then swapped,
 * and Bun does not resolve concurrent import() calls in call order: a burst of 21
 * rising-usage writes (10% -> 90%, no reset at all) arrived reordered and fired a false
 * "surprise" reset on every run. Worse, the false event CLAIMED the durable idempotence
 * key, so the genuine reset on that window was then permanently suppressed.
 *
 * `pendingObservation` is reassigned SYNCHRONOUSLY here, so each link is queued in call
 * order and only starts once the previous one has committed its baseline. A FIFO queue
 * entered after the await would not have fixed it — the enqueue itself would race.
 */
let pendingObservation: Promise<void> = Promise.resolve();

function notifyCodexQuotaSnapshot(accountId: string, next: StoredAccountQuota): void {
  // Copy before the boundary: `next` is the live map value and the following write mutates
  // it, so an observation that read it after awaiting could see a later snapshot than the
  // one it was called for.
  const retained = withoutRetiredCodexQuota(next);
  if (!retained) return;
  const snapshot = { ...retained };
  pendingObservation = pendingObservation
    .then(async () => {
      const observer = await import("../quota/reset-observer");
      if (!observer.hasQuotaResetSink()) return;
      const { codexWindowObservations } = await import("../quota/window-mapping");
      observer.observeQuotaSnapshot({
        scope: "codex",
        accountKey: accountId,
        windows: codexWindowObservations(snapshot),
        retainAbsentShortWindow: true,
      });
    })
    .catch(() => {
      // Detection is best-effort: a quota write must never fail because of it. Swallowing
      // here also keeps the chain alive — a rejected link would poison every later one.
    });
}

/** Await the observation chain. Tests only: production never needs to join it. */
export function flushQuotaObservationsForTests(): Promise<void> {
  return pendingObservation;
}

/** Exact retired model evidence, including account/provider-qualified selectors. */
export function isRetiredCodexSparkModel(modelId: string | undefined): boolean {
  return modelId?.trim().toLowerCase().split("/").at(-1) === "gpt-5.3-codex-spark";
}

/** Tombstone old cache/DTO labels without changing unrelated custom windows or stores. */
export function withoutRetiredCodexQuota<T extends Omit<StoredAccountQuota, "updatedAt"> | null>(quota: T): T | null {
  if (!quota?.customWindows?.length) return quota;
  const kept = quota.customWindows.filter(window =>
    window.label !== "GPT-5.3-Codex-Spark 5h" && window.label !== "GPT-5.3-Codex-Spark Weekly");
  if (kept.length === quota.customWindows.length) return quota;
  const next = { ...quota };
  if (kept.length > 0) next.customWindows = kept;
  else delete next.customWindows;
  return snapshotHasUsage(next) || snapshotHasCredits(next) ? next as T : null;
}

/** Parse `x-codex-*` rate-limit headers into a quota observation, binding the raw reset values so decision evidence can keep invalid resets distinct from the display fields. */
export function parseUpstreamQuotaHeaders(headers: Headers, options?: { modelId?: string }): Omit<StoredAccountQuota, "updatedAt"> | null {
  if (isRetiredCodexSparkModel(options?.modelId)) return null;
  const primaryRaw = headers.get("x-codex-primary-used-percent");
  const secondaryRaw = headers.get("x-codex-secondary-used-percent");
  const tertiaryRaw = headers.get("x-codex-tertiary-used-percent");
  const primaryResetRaw = headers.get("x-codex-primary-reset-at");
  const secondaryResetRaw = headers.get("x-codex-secondary-reset-at");
  const tertiaryResetRaw = headers.get("x-codex-tertiary-reset-at");
  const primaryWindowMinutes = headers.get("x-codex-primary-window-minutes");
  const secondaryWindowMinutes = headers.get("x-codex-secondary-window-minutes");

  const quota: Omit<StoredAccountQuota, "updatedAt"> = {};
  const primaryPercent = normalizeUsagePercent(primaryRaw);
  const secondaryPercent = normalizeUsagePercent(secondaryRaw);
  const tertiaryPercent = normalizeUsagePercent(tertiaryRaw);
  const primaryResetAt = normalizeResetAt(primaryResetRaw);
  const secondaryResetAt = normalizeResetAt(secondaryResetRaw);
  const tertiaryResetAt = normalizeResetAt(tertiaryResetRaw);
  const primaryIsMonthly = primaryRaw !== null && isExplicitMonthlyWindowMinutes(primaryWindowMinutes);
  // Codex removed the 5-hour window and has now restored it for Plus and Team (Pro stays
  // weekly-only). A primary window that DECLARES a sub-day duration is a burst window: folding
  // it into weeklyPercent both discards the real weekly reading and leaves the account looking
  // exhausted long after the burst window resets. Duration decides, exactly as parseUsageQuota
  // already does for the WHAM payload — the two parsers must not disagree about the same data.
  const primaryIsShort = isExplicitShortWindowMinutes(primaryWindowMinutes);

  if (primaryIsMonthly) {
    if (primaryPercent !== undefined) {
      quota.monthlyPercent = primaryPercent;
      if (primaryResetAt !== undefined) quota.monthlyResetAt = primaryResetAt;
      // Same provenance rule as parseUsageQuota(): this monthly value is the governing
      // primary window, not a supplementary tertiary one. Not on the recovery path today,
      // but the two parsers must agree on what a bare monthlyPercent means.
      quota.monthlyIsPrimaryWindow = true;
    }
    if (secondaryPercent !== undefined) {
      quota.weeklyPercent = secondaryPercent;
      if (secondaryResetAt !== undefined) quota.weeklyResetAt = secondaryResetAt;
    }
  } else if (primaryIsShort) {
    if (primaryPercent !== undefined) quota.shortPercent = primaryPercent;
    if (primaryResetAt !== undefined) quota.shortResetAt = primaryResetAt;
    const minutes = windowMinutes_(primaryWindowMinutes);
    if (minutes !== undefined) quota.shortWindowSeconds = Math.round(minutes * 60);
    // The burst window vacates the primary slot, so the weekly reading is the secondary — which
    // is where it was all along. Without this the true weekly value is silently dropped.
    if (secondaryPercent !== undefined) {
      quota.weeklyPercent = secondaryPercent;
      if (secondaryResetAt !== undefined) quota.weeklyResetAt = secondaryResetAt;
    }
  } else {
    const weeklyPercent = primaryPercent ?? secondaryPercent;
    const weeklyResetAt = primaryPercent !== undefined
      ? primaryResetAt
      : secondaryResetAt;
    if (weeklyPercent !== undefined) {
      quota.weeklyPercent = weeklyPercent;
      if (weeklyResetAt !== undefined) quota.weeklyResetAt = weeklyResetAt;
    }
  }

  if (tertiaryPercent !== undefined && quota.monthlyPercent === undefined) {
    quota.monthlyPercent = tertiaryPercent;
    if (tertiaryResetAt !== undefined) quota.monthlyResetAt = tertiaryResetAt;
  }

  if (decisionQuotaSinkActive()) bindRawCodexDecisionResets(quota, {
    short: primaryResetRaw,
    weekly: primaryIsMonthly || primaryIsShort || primaryPercent === undefined ? secondaryResetRaw : primaryResetRaw,
    monthly: primaryIsMonthly && primaryPercent !== undefined ? primaryResetRaw : tertiaryResetRaw,
  }, Date.now());
  return hasKnownQuotaValue(quota) ? quota : null;
}

/** Apply upstream rate-limit headers for an account: publish display and policy quota and, only for a valid observation, the advisory decision evidence. */
export function applyAccountQuotaFromUpstreamHeaders(
  accountId: string,
  headers: Headers,
  writerGeneration = captureConfigGeneration(),
  mainWriter?: MainQuotaWriter,
  options?: { modelId?: string; poolWriter?: PoolQuotaWriter; poolResponse?: boolean },
): void {
  const quota = parseUpstreamQuotaHeaders(headers, options);
  if (!quota) return;
  const policyQuota = [
    "x-codex-primary-used-percent", "x-codex-secondary-used-percent", "x-codex-tertiary-used-percent",
  ].some(name => isInvalidPolicyUsagePercent(headers.get(name))) ? null : filterMainPolicyMonthlyQuota(quota);
  const validHistory = !["x-codex-primary-used-percent", "x-codex-secondary-used-percent", "x-codex-tertiary-used-percent"]
    .some(name => isInvalidPolicyUsagePercent(headers.get(name)));
  setAccountQuotaFromParsed(accountId, quota, writerGeneration, mainWriter, policyQuota,
    options?.poolWriter && validHistory ? { writer: options.poolWriter, observedAt: Date.now(), source: "response-header", raw: quota } : undefined,
    options?.poolResponse === true, true, validHistory ? quota : null);
}

export function updateAccountQuota(
  accountId: string,
  weekly: unknown,
  weeklyResetAt?: unknown,
  monthly?: unknown,
  monthlyResetAt?: unknown,
  resetCredits?: number,
  writerGeneration = captureConfigGeneration(),
): void {
  if (!mayCommitAccountQuota(accountId, writerGeneration)) return;
  const nextWeekly = normalizeUsagePercent(weekly);
  const nextMonthly = normalizeUsagePercent(monthly);
  if (nextWeekly === undefined && nextMonthly === undefined && resetCredits === undefined) return;
  hydrateAccountQuotasFromDisk();
  const existing = accountQuota.get(accountId);
  // The WHAM/usage path carries the same staleness hazard as `mergeAccountQuota`: pre-seeding
  // from `existing` and only overwriting when a new value arrives replays an expired weekly
  // reading forever, because a caller that omits the weekly window never clears it. That is the
  // second half of the "weekly bar stuck at 98%" bug - the header path is fixed above, and
  // without this the WHAM path would keep the stale value alive on its own.
  const now = Date.now();
  const weeklyExpired = weeklyWindowRolledOver({}, existing, now);

  const quota: StoredAccountQuota = {
    ...(existing?.weeklyPercent !== undefined && !weeklyExpired ? { weeklyPercent: existing.weeklyPercent } : {}),
    ...(existing?.monthlyPercent !== undefined ? { monthlyPercent: existing.monthlyPercent } : {}),
    // Carry provenance with the value it describes. Dropping it here would downgrade a proven
    // explicit-primary reading to "unproven" on the next unrelated weekly update.
    ...(existing?.monthlyPercent !== undefined && existing.monthlyIsPrimaryWindow === true
      ? { monthlyIsPrimaryWindow: true }
      : {}),
    ...(existing?.weeklyResetAt !== undefined && !weeklyExpired ? { weeklyResetAt: existing.weeklyResetAt } : {}),
    ...(existing?.monthlyResetAt !== undefined ? { monthlyResetAt: existing.monthlyResetAt } : {}),
    ...(existing?.customWindows !== undefined ? { customWindows: existing.customWindows } : {}),
    ...(existing?.resetCredits !== undefined ? { resetCredits: existing.resetCredits } : {}),
    ...(existing?.credits !== undefined ? { credits: existing.credits } : {}),
    ...(existing?.credits === null && existing.creditObservationUnavailable === true
      ? { creditObservationUnavailable: true as const } : {}),
    updatedAt: now,
  };
  assignCarriedShort(quota, existing, quota.updatedAt);

  const nextWeeklyResetAt = normalizeResetAt(weeklyResetAt);
  const nextMonthlyResetAt = normalizeResetAt(monthlyResetAt);
  if (nextWeekly !== undefined) {
    quota.weeklyPercent = nextWeekly;
    if (nextWeeklyResetAt !== undefined) quota.weeklyResetAt = nextWeeklyResetAt;
  }
  if (nextMonthly !== undefined) {
    quota.monthlyPercent = nextMonthly;
    if (nextMonthlyResetAt !== undefined) quota.monthlyResetAt = nextMonthlyResetAt;
    // A caller-supplied monthly value arrives without window provenance, so it REPLACES the
    // proven reading and must not inherit its flag — otherwise an unproven number would be
    // treated as governing evidence.
    delete quota.monthlyIsPrimaryWindow;
  }
  if (resetCredits !== undefined) quota.resetCredits = resetCredits;

  stampCodexQuotaUsageObservation(quota, { weeklyPercent: nextWeekly, monthlyPercent: nextMonthly }, existing);
  accountQuota.set(accountId, quota);
  // This legacy writer has no physical credential provenance.
  if (accountId === MAIN_CODEX_ACCOUNT_ID) { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; }
  schedulePersistAccountQuotas();
  // Observed like the other committed write. This function has no in-repo caller today, but it
  // is re-exported as public API through src/codex/auth-api.ts, so a future caller would
  // otherwise bypass detection AND leave a stale baseline that corrupts the next real diff.
  // The credits-only path at setAccountQuotaFromParsed deliberately does not notify; this one
  // writes window percentages and deadlines, so it must.
  if (accountId !== MAIN_CODEX_ACCOUNT_ID && nextWeekly !== undefined && !isInvalidPolicyUsagePercent(weekly)) observeCodexLowQuota(accountId, {
    weeklyPercent: nextWeekly, weeklyResetAt: nextWeeklyResetAt,
  });
  notifyCodexQuotaSnapshot(accountId, quota);
}

/** Bounded, known policy fields only: disk input cannot extend a DTO or retain credentials. */
function readMainPolicyQuota(value: unknown): MainPolicyQuota | null {
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
  const entry = value as Record<string, unknown>;
  if (typeof entry.identityKey !== "string" || !/^[a-f0-9]{64}$/.test(entry.identityKey)) return null;
  if (!entry.quota || typeof entry.quota !== "object" || Array.isArray(entry.quota)) return null;
  const raw = entry.quota as Record<string, unknown>;
  if (typeof raw.updatedAt !== "number" || !Number.isFinite(raw.updatedAt) || raw.updatedAt < 0) return null;
  const quota: StoredAccountQuota = { updatedAt: raw.updatedAt };
  for (const field of ["weeklyPercent", "monthlyPercent", "shortPercent"] as const) {
    const number = raw[field];
    if (typeof number === "number" && Number.isFinite(number) && number >= 0 && number <= 100) {
      quota[field] = number;
    }
  }
  for (const field of [
    "weeklyResetAt", "monthlyResetAt", "shortResetAt", "shortObservedAt", "shortWindowSeconds", "resetCredits",
  ] as const) {
    const number = raw[field];
    if (typeof number === "number" && Number.isFinite(number) && number >= 0) quota[field] = number;
  }
  if (quota.monthlyPercent !== undefined && raw.monthlyIsPrimaryWindow === true) quota.monthlyIsPrimaryWindow = true;
  // Retain the independent credit timestamp on restart; it still expires at its original deadline.
  if (raw.credits === null) {
    quota.credits = null;
    if (raw.creditObservationUnavailable === true) quota.creditObservationUnavailable = true;
  }
  else if (raw.credits && typeof raw.credits === "object" && !Array.isArray(raw.credits)) {
    const stored = raw.credits as Record<string, unknown>;
    if (typeof stored.observedAt === "number" && Number.isFinite(stored.observedAt) && stored.observedAt >= 0) {
      quota.credits = { observedAt: stored.observedAt };
      for (const key of ["hasCredits", "unlimited", "overageLimitReached", "allowed"] as const) {
        if (typeof stored[key] === "boolean") quota.credits[key] = stored[key];
      }
      if (typeof stored.balance === "number" && Number.isFinite(stored.balance) && stored.balance >= 0) {
        quota.credits.balance = stored.balance;
      }
    }
  }
  return { identityKey: entry.identityKey, quota };
}

function hydrateAccountQuotasFromDisk(): void {
  if (diskHydrated) return;
  diskHydrated = true;
  try {
    const path = join(getConfigDir(), QUOTA_CACHE_FILENAME);
    if (!existsSync(path)) return;
    const raw = readQuotaCacheBounded(path);
    const parsed = JSON.parse(raw) as QuotaDiskFile;
    if (!parsed || parsed.version !== 1 || !parsed.quotas || typeof parsed.quotas !== "object") return;
    quotaHistory.hydrate(parsed.history);
    // Policy evidence deliberately outlives the legacy six-hour rotation-cache TTL.
    mainPolicyQuota = readMainPolicyQuota(parsed.mainPolicyQuota);
    mainPolicyUsageObservation = undefined;
    const now = Date.now();
    for (const [accountId, quota] of Object.entries(parsed.quotas)) {
      if (!quota || typeof quota !== "object" || typeof quota.updatedAt !== "number") continue;
      if (now - quota.updatedAt > QUOTA_DISK_MAX_AGE_MS) continue;
      const retained = withoutRetiredCodexQuota(quota);
      if (!retained) continue;
      if (!accountQuota.has(accountId)) accountQuota.set(accountId, retained);
    }
  } catch {
    // Corrupt/missing cache must never block routing or the dashboard.
  }
}

function schedulePersistAccountQuotas(): void {
  const now = performance.now();
  persistStartedAt ??= now;
  const delay = Math.max(0, Math.min(QUOTA_PERSIST_DEBOUNCE_MS,
    QUOTA_PERSIST_MAX_DEFERRAL_MS - (now - persistStartedAt)));
  if (persistTimer) clearTimeout(persistTimer);
  persistTimer = setTimeout(() => {
    persistTimer = null;
    persistStartedAt = null;
    // Admitted after an overlapping optional config-root ACL flight (#7815); the snapshot is
    // taken inside the callback, and a timed-out admission skips this best-effort write.
    const dir = getConfigDir();
    const generation = persistGeneration;
    persistWrite = withConfigDirHardeningSettled(dir, () => {
      if (generation !== persistGeneration) return;
      const quotas: Record<string, StoredAccountQuota> = {};
      for (const [accountId, quota] of accountQuota.entries()) {
        quotas[accountId] = quota;
      }
      const body: QuotaDiskFile = {
        version: 1,
        quotas,
        ...(mainPolicyQuota ? { mainPolicyQuota } : {}),
        history: quotaHistory.serialize(),
      };
      atomicWriteFile(join(dir, QUOTA_CACHE_FILENAME), `${JSON.stringify(body)}\n`);
    }).catch(() => {
      // Best-effort persistence only.
    });
  }, delay);
}

export function getAccountQuota(accountId: string): StoredAccountQuota | null {
  hydrateAccountQuotasFromDisk();
  return accountQuota.get(accountId) ?? null;
}

/** No physical-auth reads; unrelated legacy quota consumers cannot mutate this evidence. */
export function getMainPolicyQuota(): StoredAccountQuota | null {
  hydrateAccountQuotasFromDisk();
  if (!mainPolicyQuota || mainPolicyQuota.identityKey !== getObservedMainQuotaIdentityKey()) return null;
  return structuredClone(mainPolicyQuota.quota);
}

/**
 * The oldest measurement time among the windows the observed main identity's policy reading
 * retains, or undefined when any of them was not measured in this process (for example a reading
 * restored from disk) (#8113). Any stale retained window therefore makes the whole reading stale.
 */
export function getMainPolicyUsageObservedAt(): number | undefined {
  hydrateAccountQuotasFromDisk();
  if (!mainPolicyQuota || mainPolicyQuota.identityKey !== getObservedMainQuotaIdentityKey()) return undefined;
  const observation = mainPolicyUsageObservation?.identityKey === mainPolicyQuota.identityKey
    ? mainPolicyUsageObservation.at : undefined;
  let oldest: number | undefined;
  for (const window of POLICY_USAGE_WINDOWS) {
    if (!finitePercent(mainPolicyQuota.quota[window])) continue;
    const at = observation?.[window];
    if (at === undefined) return undefined;
    oldest = oldest === undefined ? at : Math.min(oldest, at);
  }
  return oldest;
}

/** An owned identity observation may retire legacy main quota only when its retained policy tag proves replacement. */
export function discardMismatchedMainQuota(): void {
  hydrateAccountQuotasFromDisk();
  const observedIdentity = getObservedMainQuotaIdentityKey();
  // Untagged/malformed snapshots and a matching identity retain their existing restrictions.
  if (observedIdentity !== undefined && mainPolicyQuota
    && mainPolicyQuota.identityKey !== observedIdentity) clearAccountQuota(MAIN_CODEX_ACCOUNT_ID);
}

export function listAccountQuotas(): IterableIterator<[string, StoredAccountQuota]> {
  hydrateAccountQuotasFromDisk();
  return accountQuota.entries();
}

/**
 * Tell the observer to drop the baseline for a row that was deliberately cleared.
 *
 * Queued on the same chain as observations so it cannot overtake an in-flight one and be
 * immediately re-established by it. Without this, reauth of a used account left the observer
 * holding the pre-clear percentages and the first fresh write fired a false surprise reset
 * (measured 91% -> 0%).
 */
function forgetCodexQuotaBaseline(accountId?: string): void {
  pendingObservation = pendingObservation
    .then(async () => {
      const observer = await import("../quota/reset-observer");
      observer.forgetQuotaBaseline({
        scope: "codex",
        ...(accountId !== undefined ? { accountKey: accountId } : {}),
      });
    })
    .catch(() => {
      // Best-effort; a failure can only cost a re-baseline.
    });
}

/** Clear stored quota, advisory decision evidence and history for one account, or for all accounts when no id is given. */
export function clearAccountQuota(accountId?: string): void {
  clearDecisionAccountQuotas("codex", accountId);
  if (!accountId || accountId === MAIN_CODEX_ACCOUNT_ID) clearDecisionAccountQuotas("codex-main");
  if (!accountId || accountId === MAIN_CODEX_ACCOUNT_ID) forgetMainAccountUsage();
  if (accountId) hydrateAccountQuotasFromDisk();
  quotaHistory.clear(accountId);
  if (accountId) {
    hydrateAccountQuotasFromDisk();
    accountQuota.delete(accountId);
    if (accountId === MAIN_CODEX_ACCOUNT_ID) { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; }
    schedulePersistAccountQuotas();
    forgetCodexQuotaBaseline(accountId);
    return;
  }
  accountQuota.clear();
  forgetCodexQuotaBaseline();
  { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; }
  diskHydrated = false;
  if (persistTimer) {
    clearTimeout(persistTimer);
    persistTimer = null;
  }
  persistStartedAt = null;
  persistGeneration += 1;
  try {
    const path = join(getConfigDir(), QUOTA_CACHE_FILENAME);
    if (existsSync(path)) unlinkSync(path);
  } catch {
    // Best-effort; memory is already cleared.
  }
}

export function reconcileCodexQuotaAccounts(context: GenerationContext): number {
  if (context.generation <= lastReconciledGeneration) return 0;
  hydrateAccountQuotasFromDisk();
  let removed = quotaHistory.reconcile(context.codexAccountIds);
  for (const accountId of accountQuota.keys()) {
    if (context.codexAccountIds.has(accountId)) continue;
    accountQuota.delete(accountId);
    removed += 1;
  }
  liveAccountIds = new Set(context.codexAccountIds);
  lastReconciledGeneration = context.generation;
  if (removed > 0) schedulePersistAccountQuotas();
  return removed;
}

/** Supplementary monthly bars are not governing policy evidence without plan/primary proof. */
function filterMainPolicyMonthlyQuota(
  quota: Omit<StoredAccountQuota, "updatedAt"> | null,
  monthlyOnlyPlan = false,
): Omit<StoredAccountQuota, "updatedAt"> | null {
  if (!quota || monthlyOnlyPlan || quota.monthlyIsPrimaryWindow === true) return quota;
  const filtered = { ...quota };
  delete filtered.monthlyPercent;
  delete filtered.monthlyResetAt;
  delete filtered.monthlyIsPrimaryWindow;
  // Null retains the matching prior observation; an empty object would merge away evidence.
  return hasKnownQuotaValue(filtered) || snapshotHasCredits(filtered) ? filtered : null;
}

/**
 * Parse ordinary main-policy usage, rejecting messages with invalid numeric window percentages.
 * A measured long primary, or explicitly absent primary with measured weekly secondary,
 * proves replacement with long/null topology; an allowed two-window response may omit tertiary.
 * Null supplies no usable evidence.
 */
export function parseMainPolicyUsageQuota(data: WhamUsageResponse): MainPolicyQuotaObservation | null {
  const individualLimit = extractGroupBasedSpendControlLimit(data);
  const windows = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
  if (windows.some(window => isInvalidPolicyUsagePercent(window?.used_percent))
    || parseGroupUsagePercent(individualLimit?.used_percent) === null) return null;
  const quota = filterMainPolicyMonthlyQuota(parseUsageQuota(data), isThirtyDayOnlyCodexPlan(data.plan_type));
  // #8596: a complete, allowed main read retires a carried monthly tuple under the pool proof (#8067).
  return quota ? withWhamMonthlyWindowAbsence(data, withWhamShortWindowAbsence(data, quota)) : null;
}

/** Derive absence from complete WHAM topology without changing the display quota. */
export function withWhamShortWindowAbsence(
  data: WhamUsageResponse, quota: Omit<StoredAccountQuota, "updatedAt">,
): MainPolicyQuotaObservation {
  const [primary, secondary, tertiary] = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
  // Primary and secondary must explicitly report their topology. WHAM also sends
  // two-window responses without tertiary; an explicit allowed verdict disambiguates those
  // from partial observations. A present tertiary still requires measured long/null evidence.
  // Policy trusts one complete snapshot only when every non-null window is >=24h AND
  // carries a valid usage reading: a long window without used_percent leaves that
  // window's usage unknown, and unknown usage must never release a block.
  // Headers never supply this proof, and reset time alone still cannot release a block.
  if ((isMeasuredLongWindow(primary)
      || (primary === null && isMeasuredLongWindow(secondary) && quota.weeklyPercent !== undefined))
    && (secondary === null || isMeasuredLongWindow(secondary))
    && (tertiary === null || isMeasuredLongWindow(tertiary)
      || (tertiary === undefined && data.rate_limit?.allowed === true))) {
    return { ...quota, shortWindowAbsent: true };
  }
  return quota;
}

/**
 * Policy evidence for a stored pool account's WHAM read (pool probe or re-login): null when any
 * reading is invalid. A complete long/null topology marks short-window absence (#7961) unless
 * upstream explicitly denied the account, since a denial is never evidence that a block ended.
 */
export function poolWhamPolicyObservation(
  data: WhamUsageResponse, quota: Omit<StoredAccountQuota, "updatedAt"> | null,
): MainPolicyQuotaObservation | null {
  if (!quota || !isValidWhamHistoryObservation(data)) return null;
  if (data.rate_limit?.allowed === false || hasMalformedWhamReading(data)) return quota;
  return withWhamMonthlyWindowAbsence(data, withWhamShortWindowAbsence(data, quota));
}

/** Retirement releases a block, so a present reading that does not parse is not "unknown". */
function hasMalformedWhamReading(data: WhamUsageResponse): boolean {
  const readings = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
  for (const limit of Array.isArray(data.additional_rate_limits) ? data.additional_rate_limits : []) {
    if (limit && typeof limit === "object") readings.push(limit.rate_limit?.primary_window, limit.rate_limit?.secondary_window);
  }
  return readings.some(window => window?.used_percent != null
    && normalizeUsagePercent(window.used_percent) === undefined);
}

/**
 * #8067/#8596: the complete topology that proves short-window absence also proves there is no
 * monthly window when no window declares a monthly duration and no tertiary window is present,
 * so a plan change away from a monthly primary (Free to Pro Lite) retires the carried tuple.
 * An explicit denial and invalid or unparseable readings never supply that proof.
 */
function withWhamMonthlyWindowAbsence(
  data: WhamUsageResponse, observation: MainPolicyQuotaObservation,
): MainPolicyQuotaObservation {
  if (observation.shortWindowAbsent !== true || data.rate_limit?.allowed === false) return observation;
  if (!isValidWhamHistoryObservation(data) || hasMalformedWhamReading(data)) return observation;
  const [primary, secondary, tertiary] = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
  return !isExplicitMonthlyWindow(primary) && !isExplicitMonthlyWindow(secondary) && tertiary == null
    ? { ...observation, monthlyWindowAbsent: true }
    : observation;
}

function isMeasuredLongWindow(window: WhamUsageWindow | null | undefined): boolean {
  return isExplicitLongWindow(window) && normalizeUsagePercent(window?.used_percent) !== undefined;
}

/** Absent/null controls impose no veto; a present control requires reached:false. */
function spendControlAllowsCredits(control: unknown): boolean | undefined {
  if (control === undefined || control === null) return undefined;
  return typeof control === "object" && !Array.isArray(control)
    && "reached" in control && control.reached === false;
}

/** Extract group-based individual spend limit for Business/Enterprise plans when rate_limit is absent. */
function extractGroupBasedSpendControlLimit(data: WhamUsageResponse): Record<string, unknown> | null {
  if (data.rate_limit || codexPlanKey(data.plan_type) !== "business") return null;
  const control = data.spend_control;
  if (!control || typeof control !== "object" || Array.isArray(control)) return null;
  const individualLimit = (control as Record<string, unknown>).individual_limit;
  if (!individualLimit || typeof individualLimit !== "object" || Array.isArray(individualLimit)) return null;
  const limitRecord = individualLimit as Record<string, unknown>;
  return limitRecord.source === "group_based_spend_controls" ? limitRecord : null;
}

/** Normalize WHAM credits for both the quota snapshot and the account DTO. */
export function parseWhamCredits(data: WhamUsageResponse): CodexCredits | null | undefined {
  const credits = parseCodexCredits(data.credits);
  if (!credits || (credits.balance !== undefined && Number.isFinite(Number(credits.balance)))) return credits;
  const raw = extractGroupBasedSpendControlLimit(data)?.remaining;
  const remaining = typeof raw === "number" ? raw
    : typeof raw === "string" && raw.trim() !== "" ? Number(raw) : undefined;
  if (remaining === undefined || !Number.isFinite(remaining) || remaining < 0) return credits;
  // Keep a plain decimal in the DTO and preserve the number when the snapshot parses it back.
  credits.balance = Math.abs(remaining).toLocaleString("en-US", { useGrouping: false, maximumSignificantDigits: 17 });
  return credits;
}

/**
 * Normalize WHAM windows into the display snapshot, preserving declared short-window shape.
 * Finite percentages are clamped for compatibility; policy callers must validate raw readings
 * separately. Return null when no usage window or credit observation/retraction is available.
 */
export function parseUsageQuota(data: WhamUsageResponse): Omit<StoredAccountQuota, "updatedAt"> | null {
  const resetCredits = typeof data.rate_limit_reset_credits?.available_count === "number"
    ? data.rate_limit_reset_credits.available_count
    : undefined;

  const quota: Omit<StoredAccountQuota, "updatedAt"> = {};
  const creditsAllowed = spendControlAllowsCredits(data.spend_control);
  if (resetCredits !== undefined) quota.resetCredits = resetCredits;
  if (data.credits !== undefined) {
    quota.credits = null;
    const parsed = parseWhamCredits(data);
    if (parsed) {
      const balance = parsed.balance === undefined ? undefined : Number(parsed.balance);
      quota.credits = {
        observedAt: Date.now(),
        ...(parsed.hasCredits !== undefined ? { hasCredits: parsed.hasCredits } : {}),
        ...(parsed.unlimited !== undefined ? { unlimited: parsed.unlimited } : {}),
        ...(parsed.overageLimitReached !== undefined ? { overageLimitReached: parsed.overageLimitReached } : {}),
        // Included-plan refusal is precisely when opted-in credits take over, not a credit veto.
        // A declared spending control permits credits only with an explicit unreached verdict.
        ...(creditsAllowed !== undefined ? { allowed: creditsAllowed } : {}),
        ...(balance !== undefined && Number.isFinite(balance) ? { balance } : {}),
      };
    }
  } else if (data.rate_limit?.allowed === false || creditsAllowed === false) quota.credits = null;
  // A missing/malformed summary retracts spending authority, but is re-observable.
  // Explicit spending vetoes and legacy unmarked null retain conservative retry advice.
  if (quota.credits === null && creditsAllowed !== false) quota.creditObservationUnavailable = true;
  if (!data.rate_limit) {
    const individualLimit = extractGroupBasedSpendControlLimit(data);
    if (individualLimit) {
      // An out-of-range or malformed raw reading must not be clamped into a valid-looking bar;
      // leaving the monthly tuple unset lets the merge carry the stored reading forward.
      const usedPercent = parseGroupUsagePercent(individualLimit.used_percent);
      const monthlyPercent = usedPercent === undefined && (data.spend_control as Record<string, unknown>).reached === true
        ? CODEX_EXHAUSTED_USAGE_PERCENT : usedPercent;
      if (monthlyPercent != null) {
        quota.monthlyPercent = monthlyPercent;
        const resetAt = normalizeResetAt(individualLimit.reset_at);
        if (resetAt !== undefined) quota.monthlyResetAt = resetAt;
        quota.monthlyIsPrimaryWindow = true;
      }
      if (decisionQuotaSinkActive() && quota.monthlyPercent !== undefined) {
        bindRawCodexDecisionResets(quota, {
          short: undefined,
          weekly: undefined,
          monthly: individualLimit.reset_at,
        }, Date.now());
      }
      return hasKnownQuotaValue(quota) || snapshotHasCredits(quota) ? quota : null;
    }
    return snapshotHasCredits(quota) ? quota : null;
  }
  const thirtyDayOnly = codexQuotaWindowForPlan(data.plan_type) === "monthly";
  const primaryWindow = data.rate_limit.primary_window;
  const secondaryWindow = data.rate_limit.secondary_window;
  const tertiaryWindow = data.rate_limit.tertiary_window;
  const primaryPercent = normalizeUsagePercent(primaryWindow?.used_percent);
  const secondaryPercent = normalizeUsagePercent(secondaryWindow?.used_percent);
  const tertiaryPercent = normalizeUsagePercent(tertiaryWindow?.used_percent);
  const primaryResetAt = normalizeResetAt(primaryWindow?.reset_at);
  const secondaryResetAt = normalizeResetAt(secondaryWindow?.reset_at);
  const tertiaryResetAt = normalizeResetAt(tertiaryWindow?.reset_at);
  const primaryIsMonthly = isExplicitMonthlyWindow(primaryWindow);

  // [Decision Log]
  // - 목적과 의도: distinguish weekly and roughly monthly WHAM primary windows without plan-name guesses.
  // - 기존 구현 및 제약 조건: primary meant weekly, and older responses omit limit_window_seconds.
  // - 검토한 주요 대안: exact-duration matching, plan-specific mapping, and a duration lower bound.
  // - 선택한 방식: only an explicit primary duration of at least 28 days changes it to monthly.
  // - 다른 대안 대신 이 방식을 선택한 이유: it accepts calendar-month variance and preserves legacy payloads.
  // - 장점, 단점 및 영향: Team monthly quotas classify correctly; unknown durations remain weekly by design.
  // #1791: a primary window that declares a sub-day duration is a burst window, not the
  // weekly one. Skip it so the secondary (the real 7-day window) is what lands in
  // `weeklyPercent`; without this the 5-hour bar was reported as weekly and the actual
  // weekly reading was dropped on the floor.
  const primaryIsShort = isExplicitShortWindow(primaryWindow);
  const weeklyCandidatePercent = primaryIsShort ? undefined : primaryPercent;
  const weeklyCandidateResetAt = primaryIsShort ? undefined : primaryResetAt;
  // Retain the declared burst tuple even when its usage is unknown. Its shape selects
  // the short-window policy; a missing reading is not permission to fall back to weekly.
  if (primaryIsShort) {
    if (primaryPercent !== undefined) quota.shortPercent = primaryPercent;
    if (primaryResetAt !== undefined) quota.shortResetAt = primaryResetAt;
    const seconds = primaryWindow?.limit_window_seconds;
    if (typeof seconds === "number" && Number.isFinite(seconds)) quota.shortWindowSeconds = seconds;
  }
  const weeklyPercent = primaryIsMonthly ? secondaryPercent : weeklyCandidatePercent ?? secondaryPercent;
  const weeklyResetAt = primaryIsMonthly
    ? secondaryResetAt
    : weeklyCandidatePercent !== undefined ? weeklyCandidateResetAt : secondaryResetAt;
  const monthlyPercent = primaryIsMonthly ? primaryPercent ?? tertiaryPercent : tertiaryPercent;
  const monthlyResetAt = primaryIsMonthly && primaryPercent !== undefined ? primaryResetAt : tertiaryResetAt;
  if (thirtyDayOnly) {
    if (monthlyPercent !== undefined) {
      quota.monthlyPercent = monthlyPercent;
      if (monthlyResetAt !== undefined) quota.monthlyResetAt = monthlyResetAt;
    }
  } else if (weeklyPercent !== undefined) {
    quota.weeklyPercent = weeklyPercent;
    if (weeklyResetAt !== undefined) quota.weeklyResetAt = weeklyResetAt;
  }
  if (!thirtyDayOnly && monthlyPercent !== undefined) {
    quota.monthlyPercent = monthlyPercent;
    if (monthlyResetAt !== undefined) quota.monthlyResetAt = monthlyResetAt;
  }
  // Provenance depends on the observed window, not the plan name. Go/Free need it
  // too so a real monthly-primary replacement can retire an earlier weekly policy tuple.
  // A supplementary value (including fallback from an unreadable primary) is not proof.
  if (primaryIsMonthly && primaryPercent !== undefined) quota.monthlyIsPrimaryWindow = true;

  if (resetCredits !== undefined) quota.resetCredits = resetCredits;

  if (decisionQuotaSinkActive()) bindRawCodexDecisionResets(quota, {
    short: primaryWindow?.reset_at,
    weekly: primaryIsMonthly || weeklyCandidatePercent === undefined ? secondaryWindow?.reset_at : primaryWindow?.reset_at,
    monthly: primaryIsMonthly && primaryPercent !== undefined ? primaryWindow?.reset_at : tertiaryWindow?.reset_at,
  }, Date.now());
  return hasKnownQuotaValue(quota) || snapshotHasCredits(quota) ? quota : null;
}


export interface QuotaObservationEvidence {
  writer: PoolQuotaWriter;
  observedAt: number;
  source: "wham" | "response-header";
  raw: Omit<StoredAccountQuota, "updatedAt">;
}

/** Reject raw invalid readings before the compatibility parser clamps them into valid-looking bars. */
export function isValidWhamHistoryObservation(data: WhamUsageResponse): boolean {
  const individualLimit = extractGroupBasedSpendControlLimit(data);
  if (parseGroupUsagePercent(individualLimit?.used_percent) === null) return false;
  const windows = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
  for (const limit of Array.isArray(data.additional_rate_limits) ? data.additional_rate_limits : []) {
    if (limit && typeof limit === "object") windows.push(limit.rate_limit?.primary_window, limit.rate_limit?.secondary_window);
  }
  return !windows.some(window => isInvalidPolicyUsagePercent(window?.used_percent));
}

function historyWindows(quota: Omit<StoredAccountQuota, "updatedAt">): QuotaHistoryWindow[] {
  const windows: QuotaHistoryWindow[] = [];
  for (const window of ["short", "weekly", "monthly"] as const) {
    const percent = quota[`${window}Percent`];
    const reset = quota[`${window}ResetAt`];
    if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100) continue;
    windows.push({ family: "account", window, usedPercent: percent,
      ...(typeof reset === "number" && Number.isFinite(reset) && reset >= 0 ? { resetAtMs: resetAtToMs(reset) } : {}),
      ...(window === "short" && quota.shortWindowSeconds ? { windowSeconds: quota.shortWindowSeconds } : {}),
      ...(window === "monthly" && quota.monthlyIsPrimaryWindow ? { monthlyIsPrimaryWindow: true } : {}),
    });
  }
  // No observation path emits retired Spark custom windows any more: the header parser refuses the
  // retired model and the WHAM parser no longer derives its family, so recording one here could only
  // resurrect evidence `withoutRetiredCodexQuota` tombstones on the way in. The `spark` family stays
  // in the history schema so samples already persisted by older builds still parse.
  return windows;
}

/** A cache read is bounded even if a file grows between stat and read. */
function readQuotaCacheBounded(path: string): string {
  const limit = 4 * 1024 * 1024;
  const flags = fsConstants.O_RDONLY | (process.platform === "win32" ? 0 : fsConstants.O_NONBLOCK | fsConstants.O_NOFOLLOW);
  const fd = openSync(path, flags);
  try {
    const stat = fstatSync(fd);
    if (!stat.isFile() || stat.size > limit) throw new Error("quota cache exceeds bounds");
    const chunks: Buffer[] = [];
    let total = 0;
    while (total <= limit) {
      const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, limit + 1 - total));
      const size = readSync(fd, chunk, 0, chunk.length, null);
      if (!size) return Buffer.concat(chunks, total).toString("utf8");
      chunks.push(chunk.subarray(0, size)); total += size;
    }
    throw new Error("quota cache exceeds bounds");
  } finally { closeSync(fd); }
}

/** Cached pool observations only. An unavailable identity never authorizes publication or deletion. */
export function getAccountQuotaHistory(accountId: string, limit: number = QUOTA_HISTORY_LIMITS.perAccount) {
  hydrateAccountQuotasFromDisk();
  const result = quotaHistory.read(accountId, poolQuotaHistoryIdentity(accountId), Date.now(), limit);
  return { observations: result.samples.map(({ credentialGeneration: _generation, ...sample }) => sample),
    truncated: result.truncated, retention: { maxObservations: QUOTA_HISTORY_LIMITS.perAccount, maxAgeDays: 30 } };
}

/**
 * Where the newest stored reading for a pool account came from (a WHAM usage body or upstream
 * response headers), or undefined when no current history exists. Read-only: unlike
 * `getAccountQuotaHistory` it never prunes or clears a mismatched bucket.
 */
export function latestCodexQuotaObservationSource(accountId: string): "wham" | "response-header" | undefined {
  hydrateAccountQuotasFromDisk();
  return quotaHistory.peekLatestSource(accountId, poolQuotaHistoryIdentity(accountId));
}

/**
 * Live weekly windows the current credential generation has reported in contradiction (#8574),
 * read from the cached history only. Display evidence: admission, routing and credit consent
 * never read it.
 *
 * The caller passes the account's credential record, normally one entry of a single store
 * snapshot, so a roster listing costs no store read per account. The history is peeked, never
 * pruned or cleared, because a passive read (`/api/quota-pool`) reaches this.
 */
export function getAccountWeeklyQuotaConflicts(
  accountId: string,
  record: CodexAccountCredentialRecord | null | undefined,
  now = Date.now(),
): WeeklyWindowConflict[] {
  hydrateAccountQuotasFromDisk();
  const identity = poolQuotaHistoryIdentityOf(record);
  if (!identity || !record) return [];
  return detectWeeklyWindowConflicts(quotaHistory.peekSamples(accountId, identity), record.generation, now);
}
