import { Decimal } from './decimal.js' import type { LedgerView, PositionBounds, PositionEntry, PositionUpdate, Timescale } from '@vpp/domain' import { PositionUpdate as PositionUpdateSchema } from '@vpp/domain' export class LedgerConcurrencyError extends Error { constructor(expected: number, actual: number) { super(`ledger version mismatch: update expected ${expected}, current is ${actual}`) this.name = 'LedgerConcurrencyError' } } export class CascadeViolation extends Error { constructor(message: string) { super(message) this.name = 'CascadeViolation' } } export interface LedgerConfig { /** * Allowed relative deviation of a day-ahead bid's daily energy from the * pro-rata daily share of the monthly contracted position. * OPEN-QUESTION A5: the real Hubei decomposition-band rule may differ in * shape (cumulative month-to-date band? asymmetric?) — see docs/open-questions.md. */ daMonthlyDeviationBand: string // e.g. "0.05" = ±5% clock?: () => string } /** * Position ledger v1 (docs/00 §4, P7): in-memory, optimistic concurrency, * per-timescale views, and the constraint cascade — upper-timescale positions * bound lower-timescale writes. Storage adapter (Postgres) arrives with M3. */ export class LedgerService { private version = 0 private entries: PositionEntry[] = [] constructor(private readonly cfg: LedgerConfig) {} read(): LedgerView { return { version: this.version, entries: [...this.entries] } } viewByTimescale(timescale: Timescale): PositionEntry[] { return this.entries.filter((e) => e.timescale === timescale) } /** * Daily energy bounds for a day-ahead bid on `date`, derived from the * MONTHLY CONTRACT position (the same rule checkCascade enforces). Handed * to the bid-optimization skill as hard constraints so the optimizer can * never produce a bid the ledger would then reject. Throws when there is * no monthly anchor — same policy as append. */ dayAheadBounds(date: string): PositionBounds { const { min, max } = this.cascadeBand(date) return { ledger_version: this.version, daily_energy_min_mwh: min.toString(), daily_energy_max_mwh: max.toString(), } } append(update: PositionUpdate): LedgerView { PositionUpdateSchema.parse(update) if (update.expected_version !== this.version) { throw new LedgerConcurrencyError(update.expected_version, this.version) } this.checkCascade(update) const { expected_version: _ignored, ...rest } = update const entry: PositionEntry = { ...rest, recorded_at: this.cfg.clock?.() ?? new Date().toISOString(), } this.entries.push(entry) this.version += 1 return this.read() } /** * Constraint cascade (P7): a DAY_AHEAD bid submission must stay within the * band around the pro-rata daily share of the MONTHLY contracted position. * No monthly position for the month → nothing to cascade from → reject * (bidding without a position of record is a lineage failure, not a default-allow). */ private checkCascade(update: PositionUpdate): void { if (update.kind !== 'BID_SUBMITTED' || update.timescale !== 'DAY_AHEAD') return const { min, max, contracted, daysInMonth, band } = this.cascadeBand(update.period) const bid = new Decimal(update.energy_mwh) if (bid.lt(min) || bid.gt(max)) { throw new CascadeViolation( `day-ahead bid ${bid.toString()} MWh outside monthly cascade band ` + `[${min.toString()}, ${max.toString()}] (contracted ${contracted.toString()} MWh / ${daysInMonth} days ± ${band.mul(100).toString()}%)`, ) } } private cascadeBand(date: string) { const month = date.slice(0, 7) const monthly = this.entries.filter( (e) => e.timescale === 'MONTHLY' && e.kind === 'CONTRACT' && e.period === month, ) if (monthly.length === 0) { throw new CascadeViolation( `no MONTHLY CONTRACT position recorded for ${month}; day-ahead bid has no cascade anchor`, ) } const contracted = monthly.reduce((sum, e) => sum.add(new Decimal(e.energy_mwh)), new Decimal(0)) const daysInMonth = new Date( Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5, 7)), 0), ).getUTCDate() const dailyShare = contracted.div(daysInMonth) const band = new Decimal(this.cfg.daMonthlyDeviationBand) return { min: dailyShare.mul(new Decimal(1).sub(band)), max: dailyShare.mul(new Decimal(1).add(band)), contracted, daysInMonth, band, } } }