/** * The estimator: anchor-relative projection, correction factor, and time-to-empty. * * Three ideas carry this module. * * **The reading is an anchor, not the displayed value.** The platform reports * `total` as of `at`, but that figure only reflects usage up to `at - * settlementLagMs`. The displayed balance is therefore `total` minus what this * machine has itself observed spending since `usageClockAt`, which updates as * tokens flow instead of sitting frozen for the whole settlement lag. The same * shift makes the correction factor unbiased: `observed` and `predicted` cover the * same usage interval rather than one of them including unsettled tail usage. * * **One scalar explains almost everything.** The correction factor `k` is * `observed spend / locally predicted spend` over a window, so it absorbs a stale * price table, a missed model, and the uniform off-peak discount alike. Its * effective value is the **median** of recent candidates, not an exponential * average, so the occasional odd day — a statutory holiday the calendar does not * know yet — cannot drag it. * * **Ambiguous calendar days are probed, not trusted.** A candidate whose interval * covers a make-up workday (or an unpublished calendar year) is held out of the * main median and kept as a *probe* instead. If probes consistently disagree with * the main factor by a factor of two, the pricing period assumption is wrong and * the panel says so, with the observed ratio, rather than silently mispricing. The * configuration is never rewritten automatically. * * @module dsh-balance/estimator */ import type { BalanceBurn, BalanceProjection, CalendarHint, Currency } from './protocol.js'; import { type LedgerDrop, type LedgerReading } from './ledger.js'; import { type PriceTable, type TokenBuckets, type TokenWeights } from './pricing.js'; import type { Schedule } from './schedule.js'; /** Tokens accumulated for one minute and one provider/model route. */ export interface TokenBucketRecord { /** Minute start, epoch ms. Buckets are aligned to {@link BUCKET_MS}. */ readonly minute: number; readonly route: string; readonly tokens: TokenBuckets; } /** Width of one accumulation bucket. Fixed so persisted keys stay stable across config edits. */ export declare const BUCKET_MS = 60000; /** Why a calibration interval's calendar is not trustworthy. */ export type IntervalAmbiguity = 'none' | 'makeup' | 'unpublished'; /** Tunables the estimator reads. */ export interface EstimatorConfig { readonly settlementLagMs: number; readonly rateWindowMs: number; readonly calibrationWindowMs: number; readonly correctionSamples: number; readonly probeSamples: number; readonly minPredictedSpend: number; readonly minBurnPerHour: number; readonly etaCapMs: number; readonly etaIntegratesSchedule: boolean; } /** Everything one estimate needs. */ export interface EstimatorInput { readonly now: number; readonly currency: Currency; /** Newest successful reading for `currency`, or null before the first poll. */ readonly anchor: LedgerReading & { readonly amount: number; } | null; readonly isAvailable: boolean | null; readonly readings: readonly LedgerReading[]; readonly buckets: readonly TokenBucketRecord[]; readonly priceTable: PriceTable; readonly weights: TokenWeights; readonly schedule: Schedule; readonly config: EstimatorConfig; /** Epoch ms of the current local day's start, for the "today" total. */ readonly dayStart: number; /** Classify a usage-clock interval's calendar trustworthiness. */ readonly ambiguityOf: (fromMs: number, toMs: number) => IntervalAmbiguity; /** Routes priced by the fallback shape because no table entry matched. */ readonly unmatchedRoutes: readonly string[]; /** True when the price table's currency differs from the wallet's. */ readonly currencyMismatch: boolean; /** Format an instant as the pricing zone's `YYYY-MM-DD`, for advisory hint text. */ readonly formatDay: (ms: number) => string; } /** Estimator output, matching the wire projection plus the derived totals. */ export interface EstimatorResult { readonly projection: BalanceProjection; readonly burn: BalanceBurn; readonly spend: { readonly today: number; readonly lastHour: number; }; } /** One correction candidate, tagged with its calendar trustworthiness. */ export interface CorrectionCandidate { readonly fromUsageClockAt: number; readonly toUsageClockAt: number; readonly observed: number; readonly predicted: number; readonly ratio: number; readonly ambiguity: IntervalAmbiguity; } /** Median of a non-empty numeric list; NaN for an empty one. */ export declare function median(values: readonly number[]): number; /** * Convert decimal readings to scaled integer units, dropping unusable entries. * @param entries - `{ at, usageClockAt, total }` with the platform's decimal string. * @returns readings in scaled units, ready for the ledger. */ export declare function toLedgerReadings(entries: readonly { readonly at: number; readonly usageClockAt: number; readonly total: string; }[]): readonly LedgerReading[]; /** * Compute the correction candidates from the observed drops. * * Only drops large enough to attribute are used, and a candidate's ratio is only * meaningful when the predicted side is above the attribution threshold. * * @param usageDrops - drops classified as real usage. * @param consumedBetween - local predicted spend over a usage-clock interval. * @param minPredictedSpend - attribution threshold. * @param ambiguityOf - calendar-trust classifier. * @returns candidates in ascending time order. */ export declare function buildCandidates(usageDrops: readonly LedgerDrop[], consumedBetween: (fromMs: number, toMs: number) => number, minPredictedSpend: number, ambiguityOf: (fromMs: number, toMs: number) => IntervalAmbiguity): readonly CorrectionCandidate[]; /** * Choose the effective correction factor and the calendar hint. * * @param candidates - all candidates within the calibration window, ascending. * @param config - estimator tunables. * @returns the factor, its sample count, the probe statistics, and any hint. */ export declare function resolveCorrection(candidates: readonly CorrectionCandidate[], config: EstimatorConfig, formatDay: (ms: number) => string): { correction: number | null; samples: number; probes: { count: number; ratio: number | null; }; hint: CalendarHint | null; }; /** * Integrate time-to-empty across upcoming pricing periods. * * Dividing the remaining balance by the current rate would ignore every upcoming * period boundary: at 17:50 a peak-rate division misses the half-price period that * starts at 18:00 and understates the answer by up to 2x. This walks the segment * list instead. * * @param remaining - balance left to spend, in currency units. * @param perHourNow - rate measured in the current period. * @param now - current instant. * @param schedule - the pricing schedule. * @param capMs - clamp for the reported value. * @returns the wall-clock milliseconds to empty and whether it was clamped. */ export declare function integrateEta(remaining: number, perHourNow: number, now: number, schedule: Schedule, capMs: number): { etaMs: number; capped: boolean; }; /** * Produce one estimate. * @param input - anchor, history, tokens, pricing and schedule. * @returns projection, burn and spend totals for the wire snapshot. */ export declare function estimate(input: EstimatorInput): EstimatorResult;