diff --git a/README.md b/README.md index 51a0e654..cc8c271b 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ Energy Dashboard), and opt-in **Home Assistant notifications** with companion-ap Every change ships through the test suite, and a guard that a plausible refactor could silently disarm is held by a committed mutation harness: **158 harnesses** holding -**6720 anchor-asserted mutants**. The harness, mutant, test and reference counts, the engine +**6763 anchor-asserted mutants**. The harness, mutant, test and reference counts, the engine floor and group counts, and every engine-index row's code anchor are checked against the tree in CI ([Quality & accuracy](#quality--accuracy)). @@ -449,7 +449,7 @@ want to do, and the add-on's Configuration tab shows each one's help text. ## Development ```bash -cd server && npm install && npm test # 7,160 tests +cd server && npm install && npm test # 7,207 tests cd server && ./node_modules/.bin/tsc --noEmit -p tsconfig.json # src cd server && ./node_modules/.bin/tsc --noEmit -p tsconfig.test.json # src + tests cd web && npm install && npm run build diff --git a/docs/reference/15-2-night-charge-writes.md b/docs/reference/15-2-night-charge-writes.md index 48f0e1db..b6fff89d 100644 --- a/docs/reference/15-2-night-charge-writes.md +++ b/docs/reference/15-2-night-charge-writes.md @@ -810,7 +810,7 @@ Until the mid-day switch the add-on arms the overnight cycle only, and computes - **When.** A minute tick (`runMiddayShadowTick`, single-flight) runs once the evening job has latched the day, inside the evening job's window (21:30–23:00 on the preset). It asks the chooser with the mid-day window and the configured objective and cost ceiling (`shadowCycleConfig`). A cycle that is not mid-day — Friday, Saturday, a holiday eve, summer, the season grace, a configuration without a cost objective or with `ARB_COST_MAX_SOC_PCT` at or below 50 — is recorded with its reason and nothing is sized. - **The legs** (`runMiddayShadowEvening`). The backup leg is sized first on option A (`backupLegSizing`): its walk runs from its close to the next overnight open, and it arms when that walk dips under reserve + cushion (chapter 15 part 1, "The leg"). The cost leg is then sized from the pool the backup protects — the backup's hold only when the backup would arm — with C_mid under the Cores' charge taper and its PV surplus from the close to the on-peak start (`costLegSizing`). Both use the planner the live plan uses (`recomputeNightChargePlan` with a shadow leg), which for a shadow leg returns the plan only: it sets no plan holder, writes no plan snapshot and logs no calibration change, so the night-charge entities, the card and the status keep the live overnight plan. -- **The solar basis** (`panelPvSelection.ts shadowPvBasis`, opted into by `sizeShadowLeg` alone). Each leg the shadow sizes (both evening legs, option B, the morning refresh) selects its own band as the evening job's own call does: the Cores' band when it passes and covers every connected slot; else the panel-measured band as of the evening that owns the leg's window, when every clause holds; else the Cores' band, refused where it leaves a slot out (M2). It reads no latch and not the live night's cancel, and takes the install's write mode whatever the leg's role (a backup leg in a write mode is no advisory leg). One rule of its own, for the daylight the mid-day legs read: a band hour is a fitted solar figure only where it is modelled (the slope of its clock hour, fitted on at least two daylight pairs, times the forecast GHI); the typical-day fallback while the sun may be up (GHI unknown or above 20 W/m², `unfittedDaylightHourTs`) is not, and reads 0 W on a clock hour with no rows. A leg takes the panel band only when no hour from the plan instant to its horizon end falls on a clock hour the band lacks or reads that way (an hour past the 24-hour band is judged by the band hour of its clock hour: the slope is per clock hour). A refusal is said in the leg's disposition after the gate's own words ("…; the panel's own solar readings are not used: …"), and the leg sizes nothing; a leg the panel band sized says so on the row (chapter 15 part 3). A transient report, a report that does not list its unfitted hours, a span of hours that is not finite or ends at or before the plan instant, or the Cores' band passing, leaves the leg exactly as before. The live morning refresh selects nothing and stays on the published band. +- **The solar basis** (`panelPvSelection.ts shadowPvBasis`, opted into by `sizeShadowLeg` alone). Each leg the shadow sizes (both evening legs, option B, the morning refresh) selects its own band as the evening job's own call does: the Cores' band when it passes and covers every connected slot; else the panel-measured band as of the evening that owns the leg's window, when every clause holds; else the Cores' band, refused where it leaves a slot out (M2). It reads no latch and not the live night's cancel, and takes the install's write mode whatever the leg's role (a backup leg in a write mode is no advisory leg). One rule of its own, for the daylight the mid-day legs read: a band hour is a fitted solar figure only where it is modelled (the slope of its clock hour, fitted on at least two daylight pairs, times the forecast GHI); the typical-day fallback while the sun may be up (GHI unknown or above 20 W/m², `unfittedDaylightHourTs`) is not, and reads 0 W on a clock hour with no rows. A leg takes the panel band only when no hour from the plan instant to its horizon end falls on a clock hour the band lacks or reads that way (an hour past the 24-hour band is judged by the band hour of its clock hour: the slope is per clock hour). A refusal is said in the leg's disposition after the gate's own words ("…; the panel's own solar readings are not used: …"), and the leg sizes nothing; a leg the panel band sized says so on the row, and on a row planned on the panel basis the capture measures the cost leg's window on the panel's own per-slot readings, through the same 7-day energy balance as the row's own PV actual (chapter 15 part 3, "Held telemetry"). A transient report, a report that does not list its unfitted hours, a span of hours that is not finite or ends at or before the plan instant, or the Cores' band passing, leaves the leg exactly as before. The live morning refresh selects nothing and stays on the published band. - **Would it arm** (`shadowArmProbe`): `armCycle` against the cycle record in place, on the backup alone and then on both legs, the way the evening job would arm them. `armCycle` is pure and its cycle is dropped; only the verdict leaves (which legs armed, and the refusal words of those that did not). In `advisory` mode nothing is armed, and the record says so. A cost leg the planner held on the re-entry line (chapter 15 part 1, "The leg") is recorded as held for it, with its level and the line. - **What a held reserve sends to the grid** (v1.192.0, `heldImportEstimate`). The SHP2 does not discharge the pool below its backup reserve, so while a leg's write holds it — from the write at the window open to the restore (`heldSpan`: the close, or the on-peak guard when that is sooner) — house load the pool would have carried down to the owner's reserve comes from the grid, at that hour's rate. Each sized leg is walked twice over its hold on the median load and PV of the band it was planned on, the way the planner's grid-present carry walks the pool (PV into the pack, load out of it over the discharge efficiency, clamped to the floor and to full): once held at the reserve it would write (lifted to it at the open), once at the owner's reserve, from the pool expected at the open. The load the held pool's floor turns away beyond the other's is the held import, in house kWh; the lift itself is the leg's own draw and is not in it. It is priced hour by hour at the tariff's rates, and credited with what the next charge no longer buys: the energy the pool kept (not what a full pool spilled), over the charge leg's efficiency, at the cycle's cost window rate. Their difference is what the hold adds to the bill. On the overnight-only cycle the hold and the charge share one cheap window and the difference is small; on the mid-day cycle option A's backup (written 50, held 23:00–05:00) puts house load on the 12.59¢ overnight rate that the 8.2¢ mid-day charge would otherwise have bought back — on the 2026-10-14 fixture about 9.3 kWh and $0.30 a weeknight, against about 0.6 kWh and $0.02 for option B (written 40), while the mid-day leg's own hold under the sun sends nothing. The figure is an estimate on the median forecast and nothing measures it yet: on a shadow night no hold is written (the live overnight leg runs instead), so the night's metered import cannot grade it until a hold is actually written. A leg that writes nothing, or a hold the band does not cover hour for hour, has none, and with rates not confirmed the energy is stated and nothing is priced. - **Option B beside A** (v1.192.0): the backup is sized a second time on option B (`backupLegSizing` with the cost window's open as its horizon), after both legs, so the backup-horizon choice is made on real nights: its reserve, its draw, its walk and its held import. It is never probed, armed or announced, it anchors nothing (the cost leg is sized from option A's hold), and a planner that has nothing for it leaves it null rather than deferring the evening. diff --git a/docs/reference/15-3-night-charge-ledger-and-scoring.md b/docs/reference/15-3-night-charge-ledger-and-scoring.md index a06176c9..07cff9c2 100644 --- a/docs/reference/15-3-night-charge-ledger-and-scoring.md +++ b/docs/reference/15-3-night-charge-ledger-and-scoring.md @@ -20,7 +20,7 @@ One durable row per `plan_date` (`YYYY-MM-DD` in site time; primary key), in thr - `force_charge_on_retries` (INTEGER) — the ON re-issues the record counts (`forceChargeOnRetries`). 0 is written at the ON, so a number is the mark that the fate was recorded. NULL: not recorded (no ON, or a row older than the columns), never "not confirmed". - `force_charge_on_slots` (TEXT) — the slots the ON was sent to (`forceChargeSlots`). NULL: no ON was recorded, or the record held no slot list. - `force_charge_on_verified_at_ms` (INTEGER, ms epoch) — when a readback showed the ON applied (`forceChargeOnVerifiedAtMs`): every slot it was sent to reading ON or excused, and at least one slot in the pool reading ON (a slot the check takes as out of the pool does not count, whatever it reads). NULL: no readback showed it. -- **THE MID-DAY CYCLE IN SHADOW.** Until the switch, each evening's row also records what the mid-day cycle would have done (chapter 15 part 2, "The mid-day cycle in shadow"), in its own columns, so no live column ever holds a shadow figure: `shadow_cycle_why` (the chooser's reason; `midday` when both legs were sized) and `shadow_computed_at_ms`; the backup leg's `shadow_backup_window_start_ms` / `_end_ms`, `shadow_backup_arms`, `shadow_backup_setpoint_pct`, `shadow_backup_buy_kwh`, `shadow_backup_expected_buy_kwh` and its walk's `shadow_backup_cushion_trough_soc_pct` / `_line_soc_pct`; the cost leg's `shadow_cost_window_start_ms` / `_end_ms`, `shadow_cost_arms`, `shadow_cost_reserve_pct` (T_mid) with `shadow_cost_reserve_basis`, `shadow_cost_level_pct`, `shadow_cost_ceiling_soc_pct` (C_mid), `shadow_cost_buy_kwh`, `shadow_cost_expected_buy_kwh` and `shadow_cost_expected_start_soc_pct`; `shadow_arm_disposition` (why a leg would or would not arm, and "(on the panel-measured planning band as of )" after a leg the panel-measured band sized, option B in a part of its own); the morning refresh's `shadow_refreshed_at_ms`, `shadow_refresh_disposition`, `shadow_refreshed_level_pct`, `shadow_refreshed_reserve_pct`, `shadow_refreshed_buy_kwh` and `shadow_refreshed_expected_buy_kwh`, and how old the weather it was sized on was, `shadow_refresh_weather_age_s`. Not every row's four refreshed figures (level, reserve, worst-case and expected buy) are a re-plan's, so they are read with `shadow_refresh_disposition`: a `stood` row carries the evening's figures (no refresh finished in time, or the re-plan had no inputs or an incomplete basis), a `capped` row the announced level, reserve and worst case, with the expected buy NULL (the re-plan asked for more than was announced, and was sized on values that are not written), a `not-armed` row (since v1.205.1) the evening's figures of a cycle that was not armed (nothing was re-sized, and no charge or refresh followed), and a `not-comparable` row leaves all four NULL; no scorer reads these columns (the de-bias learner reads the live `refreshed_buy_kwh` only). `shadow_window_pv_p50_kwh` / `shadow_window_load_p50_kwh` are the PV and house load the mid-day leg was planned on over its window, and the row's capture measures the same window into `shadow_window_pv_kwh` / `shadow_window_load_kwh` (`shadowWindowActuals`: the home Cores' PV and the panel's load, each at least 90% covered, else NULL; and NULL for a side held an hour or more of the window, "Held telemetry" below) — forecast skill for the hours a mid-day charge would run in, not a validation of the sizing model. Since v1.192.0 the row also records what each leg's hold sends to the grid (chapter 15 part 2, "What a held reserve sends to the grid"): `shadow_backup_held_import_kwh` / `shadow_backup_held_net_usd` and `shadow_cost_held_import_kwh` / `shadow_cost_held_net_usd` (the house energy, kWh, and what it adds to the bill against buying it back in the mid-day window, $, negative when it saves), and the backup sized on option B beside option A — `shadow_backup_b_setpoint_pct`, `shadow_backup_b_expected_buy_kwh`, `shadow_backup_b_held_import_kwh` and `shadow_backup_b_held_net_usd`, never armed. One list (`MIDDAY_SHADOW_LEDGER_SCHEMA`) feeds the allowlist and the column-add pass. +- **THE MID-DAY CYCLE IN SHADOW.** Until the switch, each evening's row also records what the mid-day cycle would have done (chapter 15 part 2, "The mid-day cycle in shadow"), in its own columns, so no live column ever holds a shadow figure: `shadow_cycle_why` (the chooser's reason; `midday` when both legs were sized) and `shadow_computed_at_ms`; the backup leg's `shadow_backup_window_start_ms` / `_end_ms`, `shadow_backup_arms`, `shadow_backup_setpoint_pct`, `shadow_backup_buy_kwh`, `shadow_backup_expected_buy_kwh` and its walk's `shadow_backup_cushion_trough_soc_pct` / `_line_soc_pct`; the cost leg's `shadow_cost_window_start_ms` / `_end_ms`, `shadow_cost_arms`, `shadow_cost_reserve_pct` (T_mid) with `shadow_cost_reserve_basis`, `shadow_cost_level_pct`, `shadow_cost_ceiling_soc_pct` (C_mid), `shadow_cost_buy_kwh`, `shadow_cost_expected_buy_kwh` and `shadow_cost_expected_start_soc_pct`; `shadow_arm_disposition` (why a leg would or would not arm, and "(on the panel-measured planning band as of )" after a leg the panel-measured band sized, option B in a part of its own); the morning refresh's `shadow_refreshed_at_ms`, `shadow_refresh_disposition`, `shadow_refreshed_level_pct`, `shadow_refreshed_reserve_pct`, `shadow_refreshed_buy_kwh` and `shadow_refreshed_expected_buy_kwh`, and how old the weather it was sized on was, `shadow_refresh_weather_age_s`. Not every row's four refreshed figures (level, reserve, worst-case and expected buy) are a re-plan's, so they are read with `shadow_refresh_disposition`: a `stood` row carries the evening's figures (no refresh finished in time, or the re-plan had no inputs or an incomplete basis), a `capped` row the announced level, reserve and worst case, with the expected buy NULL (the re-plan asked for more than was announced, and was sized on values that are not written), a `not-armed` row (since v1.205.1) the evening's figures of a cycle that was not armed (nothing was re-sized, and no charge or refresh followed), and a `not-comparable` row leaves all four NULL; no scorer reads these columns (the de-bias learner reads the live `refreshed_buy_kwh` only). `shadow_window_pv_p50_kwh` / `shadow_window_load_p50_kwh` are the PV and house load the mid-day leg was planned on over its window, and the row's capture measures the same window into `shadow_window_pv_kwh` / `shadow_window_load_kwh` (`shadowWindowActuals`: the home Cores' PV and the panel's load, each at least 90% covered, else NULL; and NULL for a side held an hour or more of the window, "Held telemetry" below; on a row planned on the panel basis whose cost leg the panel-measured band of the row's own evening sized, the PV is the panel's own per-slot reading over the window, admitted by the 7-day energy balance as the row's own PV actual is, also below) — forecast skill for the hours a mid-day charge would run in, not a validation of the sizing model. Since v1.192.0 the row also records what each leg's hold sends to the grid (chapter 15 part 2, "What a held reserve sends to the grid"): `shadow_backup_held_import_kwh` / `shadow_backup_held_net_usd` and `shadow_cost_held_import_kwh` / `shadow_cost_held_net_usd` (the house energy, kWh, and what it adds to the bill against buying it back in the mid-day window, $, negative when it saves), and the backup sized on option B beside option A — `shadow_backup_b_setpoint_pct`, `shadow_backup_b_expected_buy_kwh`, `shadow_backup_b_held_import_kwh` and `shadow_backup_b_held_net_usd`, never armed. One list (`MIDDAY_SHADOW_LEDGER_SCHEMA`) feeds the allowlist and the column-add pass. - **SCORE** (NULL until scored): `pv_err_frac`, `pv_in_band`, `load_err_frac`, `load_in_band`, `buy_err_kwh` (signed, + = over-bought), `soc_min_err_pct`. - **DISPOSITION** (v1.132.0, both NULL on rows written before it): - `arm_disposition` — why an armed night never became an actuation. `actuated` alone is over-loaded: `NULL` covers at least five dispositions (superseded by a later plan, held below the minimum buy, no window resolved, advisory mode, apply guards refused). The 2026-08-29 row sat at `actuated=NULL` with `buy_kwh=36` and read like a failed 36 kWh buy when it was a routine Sat/Sun shared-window supersede — a log line recorded it, the ledger did not. @@ -113,7 +113,7 @@ Runs on the 30-min tick, the evening job, and the boot warm-up. Sweeps the last - **What delivered energy measures** (v1.187.3, `deliveredIntoCores`): the energy into the home Cores — the charging part (> 0) of the house panel's source channels (`src{n}_w`, from `backupInfo.chWatt`; positive = the panel charging that Core, negative = the Core carrying the house), integrated over the hold span and summed. **The channels come from the hold:** every source channel (`SOURCE_CHANNEL_SLOTS`, slots 1–3) with at least one recorded sample inside the hold, plus every slot the house panel reports connected at capture (`houseConnectedSlots` → `connectedSourceSlots`: connected and carrying a serial — the live rule of `panelRoster`, without its persisted `lastRoster` fallback). Capture runs ~16 h after the close, so membership at that moment is not the night's: a Core unplugged or in service by then, or a `/quota/all` that came back without the `pd303_mc` sources subtree that minute, would otherwise drop a channel that charged all night (or every channel) from a column written once. The recorder writes `src{n}_w` for every `chWatt` entry whether or not the slot is connected, so an empty slot reads zeros and adds nothing, and the slot ↔ `chWatt` index mapping does not affect the total. A slot connected at capture whose channel recorded nothing over the hold is still read, as a dark channel, so the coverage gate below withholds the night. Until v1.187.3 the column was window grid import minus the concurrent house load (`actuatedDeliveredKwh`, removed), which assumed the house ran on the grid for the whole hold; when the SHP2 carries the house from the pack — above its reserve before a just-in-time force-charge, and after the force-charge's OFF — the subtraction removed load the grid never carried. 2026-09-30: import 23.38 − load 18.67 = 4.71 kWh, against 20.34 kWh on the source channels (the Cores' own AC input 20.25, the pool 55→76%). On nights the house rode the grid all window the two agree to within ~3% on 09-24 (23.64 vs 24.26 kWh) and 09-28 (46.26 vs 47.41) and ~10% on the small 09-29 night (7.23 vs 7.93). A channel carrying the house reads negative and adds nothing, so hours on the pack cost nothing and hours on the grid count only what reached the Cores. NULL, with a `Delivered:` clause in `score_notes`, when no channel recorded anything over the hold and no connected Core is known; when any channel covers less than `LEDGER_SPAN_MIN_COVERAGE` (0.9) of the hold — the minimum over channels, as `actual_pv_kwh`'s per-core gate, since one dark channel in three averages to a healthy 0.67 while the total is a third short; or when the total exceeds the metered `grid_home_w` import over the hold (when that is itself ≥ 0.9 covered) by more than `DELIVERED_IMPORT_SLACK_FRAC` (5%) + `DELIVERED_IMPORT_SLACK_KWH` (0.5 kWh) — overnight the grid is the only source that can charge the Cores, so more than that is a channel read with the wrong sign or meaning. `HOLD_TAIL_MAX_MS` is unchanged; the morning bias it was sized against was import − load's. - **Coverage**: fraction of 5-min buckets in the window with ≥ 1 sample; `< 0.9` ⇒ `scored=0` ("MNAR-excluded"). - **PV/load actuals** are integrated over `[issued_at_ms, +24 h]` — the same horizon the frozen P50 forecast covered, so `pv_err_frac`/`load_err_frac` are like-for-like. Actual PV = Σ `pv_total` over the SHP2-connected home DPUs (the same basis the forecast is built from); actual load = SHP2 `panel_load`. v1.187.10: the span is whole at capture (the forecast-span gate above); before it a row captured earlier integrated only to the capture instant. -- **A panel row's PV actual** (v1.204.0, `panelRowPvActual`, `panelPvAdmission`): per slot of its `pv_basis_slots`, the panel's own reading (`src{n}_pv_w`) for a P slot and the slot's Core's `pv_total` for a C slot, over the same `[issued_at_ms, +24 h]`, each slot at the Cores' coverage minimum, withheld on held telemetry. A P slot's day reaches the column only if the 7-day energy balance admitted it, as of an evening after the span (the one predicate the planning fit, bias and skill read). The span's last day is the day after the plan's evening, which no balance can judge before the next evening's report, built after that day's daily total from the panel's own ledger comes in (06:35–09:00): until the main thread has read such a report (`panelAdmissionMem`, the newest read, never an earlier evening's), the row is captured at the usual time with its PV actual **pending** — the cushion verdict and the strikes as usual, the PV-dependent columns empty, the note marked "PV actual pending the energy balance" — and `repairPendingPanelPv` resets it for re-capture once the report is in (inside the re-capture horizon). Then the actual is written, or **withheld** with the slot-day the balance did not pass. The note names the sources and the evening the balance passed the span's days as of, with the plan's own stored ratio as of its evening: "PV actual is the panel's own per-slot reading for slots 1, 2 and 3, on days the 7-day energy balance passed as of `` (the newest evening it had judged as of when the row was captured). The plan's own 7-day energy balance read `` as of ``, the evening it was made. The row is kept apart from the readiness gate's sizing figures." A pending row whose next report never comes (the mode set to advisory, which asks for none) keeps its note and an empty PV actual. +- **A panel row's PV actual** (v1.204.0, `panelRowPvActual`, `panelPvAdmission`): per slot of its `pv_basis_slots`, the panel's own reading (`src{n}_pv_w`) for a P slot and the slot's Core's `pv_total` for a C slot, over the same `[issued_at_ms, +24 h]`, each slot at the Cores' coverage minimum, withheld on held telemetry. A P slot's day reaches the column only if the 7-day energy balance admitted it, as of an evening after the span (the one predicate the planning fit, bias and skill read). The span's last day is the day after the plan's evening, which no balance can judge before the next evening's report, built after that day's daily total from the panel's own ledger comes in (06:35–09:00): until the main thread has read such a report (`panelAdmissionMem`, the newest read, never an earlier evening's), the row is captured at the usual time with its PV actual **pending** — the cushion verdict and the strikes as usual, the PV-dependent columns empty, the note marked "PV actual pending the energy balance" — and `repairPendingPanelPv` resets it for re-capture once the report is in (inside the re-capture horizon). Then the actual is written, or **withheld** with the slot-day the balance did not pass. The note names the sources and the evening the balance passed the span's days as of, with the plan's own stored ratio as of its evening: "PV actual is the panel's own per-slot reading for slots 1, 2 and 3, on days the 7-day energy balance passed as of `` (the newest evening it had judged as of when the row was captured). The plan's own 7-day energy balance read `` as of ``, the evening it was made. The row is kept apart from the readiness gate's sizing figures." A pending row whose next report never comes (the mode set to advisory, which asks for none) keeps its note and an empty PV actual. The capture's log states the same outcome, once, in the note's precedence (`panelPvActualLogLine`): a warning "actual_pv_kwh WITHHELD for `` (actual_pv_basis ``) — ``" where the resolver, held telemetry (with the held devices) or the energy balance withholds it, an info line "actual_pv_kwh for `` pending the 7-day energy balance (actual_pv_basis ``) — …" where it is pending, and nothing where it is written. The Cores' per-Core coverage warning ("actual_pv_kwh WITHHELD — worst per-core PV coverage …") and their held-telemetry line are not logged on such a row, since its figure is not the Cores' sum; on every other row both are logged as before. - **Minimum SoC** over the score span passes through `medianFilter3` (3-sample median; endpoints pass through) *before* the min-scan: the documented SHP2 cloud-reconnect artifact emits a single transient `backupBatPercent=0` sample, and an unfiltered min-scan latches it — fabricating a realized need equal to the full floor+cushion and a false HARD under-buy in the gate's evidence. A genuine sustained low has agreeing neighbors and passes. - **Realized-need buy** — the hindsight counterfactual `buy_err_kwh` is scored against — is defensible **only on a clean night**: in advisory phase the home runs *without* the buy, and on a grid-tied home its own overnight import props the SoC. `scored=1` requires: plan had a trajectory (`min_proj_soc_pct` non-null) ∧ coverage ≥ 0.9 ∧ a min-SoC read exists ∧ window import ≤ `ARB_MIN_BUY_KWH` (near-zero — "clean islanded baseline"). Then `realizedNeedBuyKwh = max(0, targetFloorKwh − actualMinPackKwh)/legEff`. Every other case records `scored=0` with an explicit `score_notes` reason. - **The floor verdict is the plan trajectory, never baseline telemetry** (design §3.3): `plan_traj_floor_breached` = the plan's own sized trough below its own line — v1.186.0: `cushionTroughSocPct < cushionLineSocPct` (the trough that set `cushionShortfall`, and reserve floor + the cushion applied; `legacy-pct` keeps the whole-house `minProjSocPct` against floor + `cushionPct`; no recorded trough ⇒ null). Before v1.186.0 it compared the whole-house disclosure trough, which reads 0% on every cost-mode night, so the gate counted every such night as a strike; a pre-v1.186 row with `cushion_shortfall` 0 and no trough is set aside by `nightChargeGate`. In advisory phase raw min-SoC telemetry measures the un-actuated baseline, not the plan's line. Raw telemetry feeds only `soc_min_err_pct` (plan minus actual) and the separate `cushion_breached` observation. v1.196.0 — `cushion_breached` is graded on the claim the plan made (`realizedCushionBreach`). Where the cushion is an outage starting at the close (an overnight row whose `cushion_line_soc_pct` is not `reserve_floor_pct + cushion_pct`), it is the pool at the close (`window_close_soc_pct`) under the line, less 0.05 points. Without that reading it is 0 when the lowest pool after the close holds the line, and NULL otherwise. Elsewhere it is, as before, the lowest pool over the scored span under `reserve_floor_pct + cushion_pct`. `score_notes` states the reading against the line. Chapter 15 part 2 has the gate's rule. `pv_in_band`/`load_in_band` check the actual against the frozen `[P10, P90]`; `onpeak_import_occurred` uses a 0.05 kWh threshold. @@ -138,7 +138,9 @@ The recorder no longer writes held readings and moves the ones it had written ou **A cushion-only row (v1.203.0)** is never scored, in any outcome, the Cores' actuals covered included: its buy was sized on the outage cushion with no solar credited, so the planner-sizing metric (the buy against the solar and load forecast) has no solar forecast to grade, and a `buy_err_kwh` of plan + (0 − actual PV) ÷ 0.927 would read as a large over-buy. The branch (`cushionOnlyNote`) comes right after the incomplete-basis one and before the held, coverage and actuals branches: "not scored — a cushion-only plan (no solar basis: …): its buy was sized on the outage cushion at the window close with no solar credited, so the planner-sizing metric has no solar forecast to grade.", with the held verdict and its marker after it where there is one. `realized_need_buy_kwh` and `buy_err_kwh` stay NULL. It teaches nothing of the solar model (the band calibration reads recorded PV, never the ledger), the buy de-bias (it needs `scored = 1`), the under-buy pool or graduation (both `actuated && scored`). It still teaches the load: `load_err_frac` and `load_in_band` are recorded against the published load forecast, which is real. Its realized verdict stands: the pool at the close against its line (`window_close_soc_pct`, `cushion_breached`), so an actuated cushion-only night (or one that stood, or never held its write) that closes under its line less 0.05 is a realized strike, and a line night armed and never switched on is struck by `armedNeverRanUnder`. **The asymmetry:** such a night can add a strike and cannot clear one, since the 14-night streak counts only `actuated && scored` nights — fail-closed; the gate was already BLOCKED and auto already runs as supervised while the Cores are dark, so no write changes. With the panel's point (v1.203.0, part 1) the pool the panel holds under the write is the line's whole percent, so a reserve-held night closes at or above its line. -The mid-day shadow's measured window (`shadow_window_pv_kwh` / `_load_kwh`, v1.189.0) takes the same verdict over the window itself (`shadowWindowActuals`, given `recorder.heldSpans` and the house panel): a home Core held for an hour or more of the 10:00-15:00 window leaves the PV figure NULL, the panel held that long the load figure. The window's 90% coverage already refuses such an hour, since the held readings are not in `samples` and an hour is a fifth of the window; the verdict states the refusal on the scorer's own rule, whatever the window's length. The reset below clears both figures with the outcome columns (`forecastSpanResetColumns`), and the re-capture measures the window again; the shadow's other columns, what the evening computed, are not outcome columns and are kept. A tagged row keeps them as captured, with the row. A row whose PV verdict is set aside for a Core-set mismatch (`pv_verdict_set_aside`: `pvVerdictSetAside` or the known-row list) leaves the PV figure NULL too (v1.189.0 review; the scorer passes `cols.pvSetAside`): the shadow's window P50 is planned the same evening (on the band its own selection took, the row's where the two select alike), so its measured PV is no forecast-skill evidence either. The load figure is kept. +The mid-day shadow's measured window (`shadow_window_pv_kwh` / `_load_kwh`, v1.189.0) takes the same verdict over the window itself (`shadowWindowActuals`, given `recorder.heldSpans` and the house panel): a home Core held for an hour or more of the 10:00-15:00 window leaves the PV figure NULL, the panel held that long the load figure. The window's 90% coverage already refuses such an hour, since the held readings are not in `samples` and an hour is a fifth of the window; the verdict states the refusal on the scorer's own rule, whatever the window's length. The reset below clears both figures with the outcome columns (`forecastSpanResetColumns`), and the re-capture measures the window again; the shadow's other columns, what the evening computed, are not outcome columns and are kept. A tagged row keeps them as captured, with the row. A row whose PV verdict is set aside (`pv_verdict_set_aside`: `pvVerdictSetAside` or the known-row list) leaves the PV figure NULL too (v1.189.0 review; the scorer passes `cols.pvSetAside`): the shadow's window P50 is planned the same evening, so its measured PV is no forecast-skill evidence either. The load figure is kept. + +The shadow's window on the panel band (v1.210.1). A row planned on the panel basis (`isPanelBasisRow`) whose cost leg was sized on the panel-measured band as of the row's own evening has its window's PV measured by the rule of the row's own PV actual: that band is taken where the Cores' own band cannot be used, so the Cores' meter is no measure of its window. The band is read back from the row: the evening `shadow_arm_disposition` names after the cost leg's own disposition (`shadowCostPanelPvAsOfDay`), never the backup's or option B's, which can take the panel band while the daylight rule keeps the cost leg on the Cores' band. The figure is the per-slot resolver (`panelRowPvActual`) over the row's `pv_basis_slots` on the window, which are that evening's verdict, the one both selections read: the panel's own reading for a P slot and the slot's Core's `pv_total` for a C slot, each at least 90% covered, else NULL. It is NULL when either side was held an hour or more of the window (the row's own rule), and NULL until the 7-day energy balance has judged the window's day (`panelPvAdmission` over the window): pending, where the window's day is the row's own last day, which the row's usual capture comes before; withheld, where the balance did not pass that day. A row captured with its own PV actual pending is re-captured once that day is judged, and the re-capture, which clears the figure with the outcome columns, measures the window again on the newer judgement. A row whose own actual was settled at that capture (withheld by its resolver or by held telemetry over the span) is never re-captured, so the backfill sweep measures its window alone (`remeasurePendingShadowPv`, after both repairs and before the capture loop): it is due (`shadowPanelPvRemeasureDue`) when the row carries no pending marker, its window's PV is NULL, its cost leg is on the panel band of its own evening, it is inside the re-capture horizon, it was captured before 09:00 the morning after the window's day (so its capture could not have judged it), and the newest report read now judges that day. The sweep takes the capture's rule on the capture's inputs (`shadowWindowHeld`, `shadowWindowPanelPv`), writes `shadow_window_pv_kwh` only and only with a figure, logs the figure at info and the reason a window stays NULL at debug, and measures a row once per boot, so a window that stays NULL is not read on every tick. A row first captured at or after that hour keeps what its capture measured. The row's set-aside, on such a row the panel's own, does not empty it, as it does not empty the row's `actual_pv_kwh`. Every other row is measured as above: a cost leg on the Cores' band, a band of another evening, a row not on the panel basis, or one whose slots are absent or unreadable. A cost leg sized on the panel band on an evening the row itself was not on it keeps the Cores' meter: the row records no slot list for it, and no re-capture follows its pending state. **Repair.** The sweep first resets any captured row whose PV/load span, as captured (`[issued_at_ms, min(capture, issue + 24 h)]`), overlaps such a hold and whose notes do not already state that side as `telemetry held` (`heldLedgerRepair`; per side, below), with the same Cores and panel it then captures with. Inside the forecast-span repair's horizon, and re-capturable on today's devices (`forecastSpanRecapturable`), the outcome columns are reset (`heldResetColumns`: the forecast-span reset's columns, its own note) and the row is re-captured; otherwise `score_notes` gains a `Telemetry held:` clause and the row is kept as captured. Both write the marker, so the repair is idempotent. Rows are corrected in place, never deleted. The reset note and its log line name only the actuals that were integrated over the hold (`heldIntegratedActuals`: PV when a home Core was held, `actual_pv_kwh` was captured non-null and a held `pv_total` row of a held Core lies inside the span as captured; load likewise, with the panel's `panel_load`); the held rows are looked up in `held_samples` (`recorder.heldRowsWithin`). A frozen span runs from the last change before a silence of more than an hour, so a row whose span overlaps only that silence is held by the verdict and integrated no held reading: its note says the actual was integrated over hours with no readings at all and that no held reading lay inside its span. A held side captured empty is said to have been captured empty, so nothing had been integrated. The tag says the span had no fresh readings, "held or missing", and does not claim the actuals were integrated from held readings: a hold can cover hours in which the device wrote no rows at all, and past the horizon the raw telemetry that would tell the two apart is gone. **Per side (v1.188.1, fifth review).** The marker is read per side (`heldSidesNoted`: the `PV — …` and `load — …` parts of every held clause in the notes) and compared with the sides the spans hold now (`heldSides`, the same test the scorer withholds each actual by). A side held but not stated is repaired as above (the hourly scan can find a replayed Core after the capture, which stated only the panel; with one marker for the row, its PV actual stayed integrated from the replay), the tag naming only that side. A side stated but no longer held, with a restored span of one of its devices overlapping the row's span (architecture chapter, section 4.4; `recorder.restoredHeldSpans`; the incident's hold began the day before the 10-15 row's issue and ran past its end), is re-captured from the readings moved back, with a note saying so; past the horizon it is kept as captured. A side still held by another of its devices is not restored: with one of two held Cores restored, the row stays refused and is not reset (a rule reading the restore alone would reset and re-capture it on every sweep, each re-capture stating PV held again). A Core's side is never restored by the panel's restored span. A side no longer held with no restore behind it (a Core no longer on the panel is not held by today's roster either) is left as it is. A side changes at most twice (a span only grows, and a restored span is never held again), so a row is reset at most a few times. The write is one call for both actions (`heldRepairColumns`); the sweep reads the spans over its rows' days even when none is left, and after a reset it reads the ledger again before it captures, so the reset row is re-captured by the same sweep. diff --git a/ecoflow_panel/CHANGELOG.md b/ecoflow_panel/CHANGELOG.md index a4e45de1..1baf9b36 100644 --- a/ecoflow_panel/CHANGELOG.md +++ b/ecoflow_panel/CHANGELOG.md @@ -1,3 +1,18 @@ +## 1.210.1 + +### The ledger's solar on the panel's own readings: logged as it is, and the mid-day shadow graded on it + +- **What was wrong.** With the Cores dark, every ledger capture of a row planned on the panel basis logged "night-charge ledger: actual_pv_kwh WITHHELD — worst per-core PV coverage 0.00 < 0.9 over the scored span; …", while the row's PV actual is not the Cores' sum: since 1.204.0 it is the panel's own per-slot reading, admitted by the 7-day energy balance, and the rows hold it. And the winter mid-day shadow, which since 1.210.0 sizes on the panel-measured band, still measured its window's solar on the Cores' meter under the row's set-aside, so a sized shadow row had no measured PV to grade it against. +- **The log line.** On a row planned on the panel basis the Cores' per-Core coverage warning and their held-telemetry line are not logged. The panel path states its own outcome, once, in the order the row's note does: a warning "actual_pv_kwh WITHHELD for" the plan date, with the row's slot sources and the reason (per-slot coverage, held telemetry with the held devices, or a day the energy balance did not pass); an info line "pending the 7-day energy balance" while the balance has not judged the span's last day; nothing where the figure is written. +- **The shadow's window.** A cost leg sized on the panel-measured band of the row's own evening, on a row planned on the panel basis, has its window's solar measured by the row's own rule: the panel's per-slot reading over the window on the row's slot sources (a Core's own meter for a slot on its Core), at least 90 % covered, NULL on held telemetry, NULL until the energy balance has judged the window's day, and NULL where the balance did not pass that day. The band is read back from `shadow_arm_disposition`, from the cost leg's part only. +- **The window's way out of pending.** The row's usual capture, the evening after its span, comes before the energy balance can judge the window's day. A row captured with its own PV actual pending is re-captured once that judgement is read, and its window is measured again then. A row whose own actual was settled at that capture (withheld for a slot thin, unsourced or without its Core, or for the panel or a Core held, over the night) is never re-captured: the backfill sweep measures its window alone once a report that judges the day is read, inside the re-capture horizon, on the capture's own rule and inputs, and writes `shadow_window_pv_kwh` only, and only with a figure. It logs the figure at info and the reason a window stays NULL at debug, once per row per boot. A row first captured at or after 09:00 the morning after the window's day keeps what that capture measured. +- **What does not change.** A row on the Cores' basis: its coverage gate, its figures and both log lines, to the letter. Every column and value of the live overnight row. A cost leg on the Cores' band, a band of another evening, a row with no readable slot sources, and a panel-band leg on an evening the row itself was not on the panel basis are measured as before. No device write, push or announcement is added, and nothing arms a mid-day leg. +- **Detail.** Chapter 15 parts 2 and 3 of the reference. + +### Verification + +7,207 server tests pass on CI; four more need pandoc or LibreOffice and run where those are installed. Two new test files: one (11 tests) runs the scorer's solar block as `index.ts` writes it beside the 1.210.0 block on the same inputs: every Cores-basis case scores and logs alike, every panel-basis case scores alike and logs only the panel path's line; the other (36 tests) compiles the whole scorer and the sweep as `index.ts` writes them and runs them on stub telemetry with the Cores dark, the sweep's figure checked against a capture's on the same judgement and nothing read for a row the sweep does not own. `mutate-panel-pv-basis.mjs` gains 46 mutants (37 in group N and nine in group L), every mutant killed in a full run; 6,763 anchors resolve across 158 harnesses. + ## 1.210.0 ### The winter mid-day shadow sizes on the panel's own solar readings while the Cores are dark diff --git a/ecoflow_panel/config.yaml b/ecoflow_panel/config.yaml index a84d23e3..1f6b6b39 100644 --- a/ecoflow_panel/config.yaml +++ b/ecoflow_panel/config.yaml @@ -1,5 +1,5 @@ name: Power -version: "1.210.0" +version: "1.210.1" slug: ecoflow_panel description: >- Independent, open-source time-of-use arbitrage planning, forecasting and diff --git a/scripts/mutate-panel-pv-basis.mjs b/scripts/mutate-panel-pv-basis.mjs index 32bdb2ce..37a72e5c 100644 --- a/scripts/mutate-panel-pv-basis.mjs +++ b/scripts/mutate-panel-pv-basis.mjs @@ -13,9 +13,13 @@ * the caches per E, the runway untouched, the planning skill a realized-GHI reader. (S) THE SELECTION: (a)/(b)/(c) with M2, the * clauses of (b) in L1's precedence, the transient class, the latch (M1, L2), the live selection never a shadow leg's. (M) THE MID-DAY * SHADOW'S OWN SELECTION (v1.210.0): opted into by the shadow's sizer alone, no latch, no live cancel, the install's mode, the band - * following it, its refusal in the leg's row, the daylight rule, unknown as before, the basis named on the row. (T) THE WORDS: figures only (M3), - * every hold's end, G4's grid input and force-charge, en and es, the push, the card. (H) HOME ASSISTANT (L6). (L) THE LEDGER (L5) - * and (G) THE GATE. (O) THE OWNER'S DECISIONS: the haircut 1.00, every connected slot resolves, the runway at zero sun, 1.05 strict. + * following it, its refusal in the leg's row, the daylight rule, unknown as before, the basis named on the row. (N) THE SHADOW'S MEASURED + * WINDOW (v1.210.1): a cost leg the panel band of the row's own evening sized, on a panel row, graded on the panel's per-slot readings + * through the same admission and held rule; the band read back from the row (the cost leg's, never option B's); every other row as + * before; on a panel row whose own actual was settled at its capture, the window measured alone once the balance judged its day (the + * sweep: its own column only, once per boot, nothing read for a row it does not own). (T) THE WORDS: figures only (M3), + * every hold's end, G4's grid input and force-charge, en and es, the push, the card. (H) HOME ASSISTANT (L6). (L) THE LEDGER (L5; + * v1.210.1: a panel row's log line is the panel path's own outcome, never the Cores' coverage warning) and (G) THE GATE. (O) THE OWNER'S DECISIONS: the haircut 1.00, every connected slot resolves, the runway at zero sun, 1.05 strict. * * node scripts/mutate-panel-pv-basis.mjs [--only ] * @@ -54,6 +58,8 @@ const T_GOLD = 'test/legacyIdentity.test.ts'; const T_MQTT = 'test/mqttDiscovery.test.ts'; const T_MSB = 'test/middayShadowPanelBasis.test.ts'; const T_MSI = 'test/middayShadowBasisIndependent.test.ts'; +const T_GRADE = 'test/ledgerPanelPvGrading.test.ts'; +const T_IND = 'test/panelPvGradingIndependent.test.ts'; const MUTANTS = [ /* ── R: the resolver ── */ @@ -1233,6 +1239,333 @@ const MUTANTS = [ to: ' windowPvP50Kwh: fin(sized?.windowPvP50Kwh), /* MUTANT */', why: 'The refresh push would state a window PV the evening plan was not sized on.', }, + /* ── L (v1.210.1): a panel row's PV actual, said in the log by the panel path ── */ + { + id: 'PB-L-ix. ★★★ (exemplar) the Cores\' coverage warning logged on a panel row', + file: IDX, tests: [T_GRADE], + find: ' if (!panelRow) {\n if (pvHeld && heldVerdict != null) {', + to: ' if (true as boolean) { /* MUTANT */\n if (pvHeld && heldVerdict != null) {', + why: 'Every night the Cores are dark the log says the PV actual was withheld while the row holds the panel\'s figure.', + }, + { + id: 'PB-L-x. ★★★ the Cores\' lines dropped on a Cores row', + file: IDX, tests: [T_GRADE], + find: ' if (!panelRow) {\n if (pvHeld && heldVerdict != null) {', + to: ' if (panelRow) { /* MUTANT */\n if (pvHeld && heldVerdict != null) {', + why: 'A sum across a dark Core (the August case) is withheld in silence.', + }, + { + id: 'PB-L-xi. ★★★ the panel path\'s outcome never logged', + file: IDX, tests: [T_GRADE], + find: ' if (pvLog != null) app.log[pvLog.level](pvLog.text);', + to: ' /* MUTANT */', + why: 'A panel row withheld or pending says nothing in the log.', + }, + { + id: 'PB-L-xii. ★★★ the log reads the admission past a reason', + file: IDX, tests: [T_GRADE], + find: ' const pvLog = panelPvActualLogLine(yDate, panelPv.basis, why, why != null ? null : panelAdmission, heldParts);', + to: ' const pvLog = panelPvActualLogLine(yDate, panelPv.basis, why, panelAdmission, heldParts); /* MUTANT */', + why: 'A row withheld for thin readings is logged as pending a re-capture that never comes.', + }, + { + id: 'PB-L-xiii. ★★ the held panel left unnamed', + file: IDX, tests: [T_GRADE], + find: ' ? [...heldVerdict.pv, ...heldVerdict.load].map(', + to: ' ? [...heldVerdict.pv].map( /* MUTANT */', + why: 'A row withheld because the panel was held names no device.', + }, + { + id: 'PB-L-xiv. ★★★ a pending actual logged as nothing', + file: NLS, tests: [T_GRADE], + find: " if (admission?.state === 'pending') {\n return {\n level: 'info',", + to: " if ((false as boolean) && admission?.state === 'pending') { /* MUTANT */\n return {\n level: 'info',", + why: 'The first capture of every panel row says nothing of the figure it left empty.', + }, + { + id: 'PB-L-xv. ★★★ a balance withholding logged as nothing', + file: NLS, tests: [T_GRADE], + find: " if (admission?.state === 'withheld') {\n return {", + to: " if ((false as boolean) && admission?.state === 'withheld') { /* MUTANT */\n return {", + why: 'A day the balance refused leaves the PV actual empty with no line.', + }, + { + id: 'PB-L-xvi. ★★★ a written actual logged as withheld', + file: NLS, tests: [T_GRADE], + find: ' if (withheldWhy == null) return null;\n const held = heldParts', + to: ' /* MUTANT */\n const held = heldParts', + why: 'The log says WITHHELD on the nights the panel\'s figure is written.', + }, + { + id: 'PB-L-xvii. ★★ the pending line is a warning', + file: NLS, tests: [T_GRADE], + find: " level: 'info',", + to: " level: 'warn', /* MUTANT */", + why: 'Every panel row\'s first capture raises a warning for the expected wait.', + }, + + /* ── N (v1.210.1): the shadow's measured window on the panel band ── */ + { + id: 'PB-N-i. ★★★ (exemplar) the capture never passes the band: the shadow stays on the Cores\' dark meter', + file: IDX, tests: [T_GRADE], + find: ' bandAsOfDay: shadowCostPanelPvAsOfDay(y.shadow_arm_disposition), panelSn: shp2Sn,', + to: ' bandAsOfDay: null, panelSn: shp2Sn, /* MUTANT */', + why: 'Every sized shadow row keeps no measured window PV while the Cores are dark.', + }, + { + id: 'PB-N-ii. ★★★ the capture\'s panel path reads no admission', + file: IDX, tests: [T_GRADE], + find: ' admission: panelAdmissionMem,\n },\n });', + to: ' admission: null, /* MUTANT */\n },\n });', + why: 'The window stays pending for good.', + }, + { + id: 'PB-N-iii. ★★★ the capture\'s panel path reads nothing', + file: IDX, tests: [T_GRADE], + find: ' query: (sn, metric, a, b) => recorder.query(sn, metric, a, b),\n admission: panelAdmissionMem,', + to: ' query: () => [], /* MUTANT */\n admission: panelAdmissionMem,', + why: 'The panel path withholds every window.', + }, + { + id: 'PB-N-iv. ★★ a C slot resolves to a Core that is not connected', + file: IDX, tests: [T_GRADE], + find: " .find((x) => x.slot === slot && x.isConnected === true && typeof x.sn === 'string')?.sn ?? null,", + to: " .find((x) => x.slot === slot && typeof x.sn === 'string')?.sn ?? null, /* MUTANT */", + why: 'A mixed band\'s Core slot is graded on a Core the panel no longer connects.', + }, + { + id: 'PB-N-v. ★★★ another evening\'s band graded on this evening\'s slots', + file: NLS, tests: [T_GRADE], + find: ' const panelPv = p != null && p.bandAsOfDay != null && p.bandAsOfDay === i.row.plan_date\n', + to: ' const panelPv = p != null && p.bandAsOfDay != null /* MUTANT */\n', + why: 'A leg sized on another evening\'s verdict is measured on slots it was not sized on.', + }, + { + id: 'PB-N-vi. ★★★ a row on the Cores\' basis graded on the panel', + file: NLS, tests: [T_GRADE], + find: ' && isPanelBasisRow({ pv_basis: i.row.pv_basis ?? null, actual_pv_basis: i.row.actual_pv_basis })\n', + to: ' && (true as boolean) /* MUTANT */\n', + why: 'A Cores row\'s window is measured on slots its row never recorded, pending a re-capture that never comes.', + }, + { + id: 'PB-N-vii. ★★★ an unadmitted panel reading graded', + file: NLS, tests: [T_GRADE], + find: " const pvKwh = held.pv || held.load || admission.state !== 'admitted' ? null : panelPv.kwh;", + to: ' const pvKwh = held.pv || held.load ? null : panelPv.kwh; /* MUTANT */', + why: 'A x1.25 fault\'s first day is graded as forecast skill before the balance has judged it.', + }, + { + id: 'PB-N-viii. ★★★ the held panel\'s readings graded', + file: NLS, tests: [T_GRADE], + find: " const pvKwh = held.pv || held.load || admission.state !== 'admitted' ? null : panelPv.kwh;", + to: " const pvKwh = held.pv || admission.state !== 'admitted' ? null : panelPv.kwh; /* MUTANT */", + why: 'A restated reading from a panel offline in the cloud is summed as the window\'s solar.', + }, + { + id: 'PB-N-ix. ★★ a held Core leaves the panel\'s figure', + file: NLS, tests: [T_GRADE], + find: " const pvKwh = held.pv || held.load || admission.state !== 'admitted' ? null : panelPv.kwh;", + to: " const pvKwh = held.load || admission.state !== 'admitted' ? null : panelPv.kwh; /* MUTANT */", + why: 'The window is graded on a rule the live row of the same night does not follow.', + }, + { + id: 'PB-N-x. ★★★ a thin panel reading summed', + file: NLS, tests: [T_GRADE], + find: ' minCoverage: LEDGER_SPAN_MIN_COVERAGE,\n })\n : null;', + to: ' minCoverage: 0, /* MUTANT */\n })\n : null;', + why: 'An hour of readings is recorded as a five-hour window\'s solar: a partial sum.', + }, + { + id: 'PB-N-xi. ★★ the window judged on the plan\'s evening too', + file: NLS, tests: [T_GRADE], + find: ' const admission = panelPvAdmission({ basis: panelPv.basis, span: { startMs: a, endMs: b }, admission: p.admission });', + to: ' const admission = panelPvAdmission({ basis: panelPv.basis, span: { startMs: a - 24 * HOUR_MS, endMs: b }, admission: p.admission }); /* MUTANT */', + why: 'A window the balance passed is withheld for a day it does not touch.', + }, + { + id: 'PB-N-xii. ★★★ the panel figure never replaces the Cores\' meter', + file: NLS, tests: [T_GRADE], + find: ' if (p != null && panelPv != null && panelPv.basis != null) {', + to: ' if ((false as boolean) && p != null && panelPv != null && panelPv.basis != null) { /* MUTANT */', + why: 'The pure core is wired and never changes a figure.', + }, + { + id: 'PB-N-xiii. ★★ unreadable slots replace today\'s figure', + file: NLS, tests: [T_GRADE], + find: ' if (p != null && panelPv != null && panelPv.basis != null) {', + to: ' if (p != null && panelPv != null) { /* MUTANT */', + why: 'A row with no readable sources loses the Cores\' figure it had.', + }, + { + id: 'PB-N-xiv. ★★★ option B\'s band read as the cost leg\'s', + file: MSH, tests: [T_GRADE], + find: String.raw`cost: (?:(?!; backup option B:)[\s\S])*? \(on the panel-measured`, + to: String.raw`cost: [\s\S]*? \(on the panel-measured`, + why: 'A cost leg the daylight rule kept on the Cores\' band is graded on the panel because the backup took it.', + }, + { + id: 'PB-N-xv. ★★★ the band read from any part of the row', + file: MSH, tests: [T_GRADE], + find: String.raw`/(?:^|; )cost: (?:(?!; backup option B:)`, + to: String.raw`/(?:(?!; backup option B:)`, + why: 'Option B\'s note alone grades a Cores-band cost leg on the panel.', + }, + { + id: 'PB-N-xvi. ★★ a malformed evening read as a band', + file: MSH, tests: [T_GRADE], + find: String.raw`as of (\d{4}-\d{2}-\d{2})\)(?:; backup option B:`, + to: String.raw`as of ([^)]*)\)(?:; backup option B:`, + why: 'A hand-edited row grades on a band of no evening.', + }, + { + id: 'PB-N-xvii. ★★★ the figure the panel path gives never reaches the window', + file: NLS, tests: [T_GRADE, T_IND], + find: ' if (panelPv != null) pvKwh = panelPv.pvKwh;', + to: ' /* MUTANT */', + why: 'The shadow stays on the Cores\' dark meter while the pure core measures the panel.', + }, + + /* ── N (v1.210.1): the shadow's own way out of pending, on a row no re-capture revisits ── */ + { + id: 'PB-N-xviii. ★★★ (exemplar) the sweep never runs', + file: IDX, tests: [T_IND], + find: '\n remeasurePendingShadowPv(rows, shp2Sn, nowMs);\n', + to: '\n /* MUTANT */\n', + why: 'A panel row withheld for a thin night keeps its window ungraded for good.', + }, + { + id: 'PB-N-xix. ★★★ a row its own re-capture revisits measured by the sweep too', + file: NLS, tests: [T_IND], + find: " if (String(row.score_notes ?? '').includes(PANEL_PV_PENDING_MARKER)) return false;\n if (row.shadow_window_pv_kwh != null) return false;", + to: " /* MUTANT */\n if (row.shadow_window_pv_kwh != null) return false;", + why: 'Two paths write one figure, on two judgements.', + }, + { + id: 'PB-N-xx. ★★★ a written window measured again', + file: NLS, tests: [T_IND], + find: ' if (row.shadow_window_pv_kwh != null) return false;\n if (bandAsOfDay == null', + to: ' /* MUTANT */\n if (bandAsOfDay == null', + why: 'Every restart re-reads and re-writes a graded window.', + }, + { + id: 'PB-N-xxi. ★★★ the sweep grades a leg sized on the Cores\' band', + file: NLS, tests: [T_IND], + find: ' if (bandAsOfDay == null || bandAsOfDay !== row.plan_date) return false;', + to: ' if (bandAsOfDay == null) return false; /* MUTANT */', + why: 'A leg sized on another evening\'s verdict is graded on slots it was not sized on.', + }, + { + id: 'PB-N-xxii. ★★ the sweep reads a leg with no band', + file: NLS, tests: [T_IND], + find: ' if (bandAsOfDay == null || bandAsOfDay !== row.plan_date) return false;', + to: ' if (bandAsOfDay != null && bandAsOfDay !== row.plan_date) return false; /* MUTANT */', + why: 'A Cores-band leg is read for nothing on every boot.', + }, + { + id: 'PB-N-xxiii. ★★★ the sweep reads past the re-capture horizon', + file: NLS, tests: [T_IND], + find: " if (typeof row.issued_at_ms !== 'number' || !Number.isFinite(row.issued_at_ms) || nowMs - row.issued_at_ms > horizonMs) return false;\n const unjudged", + to: " if (typeof row.issued_at_ms !== 'number' || !Number.isFinite(row.issued_at_ms)) return false; /* MUTANT */\n const unjudged", + why: 'A window is graded on telemetry the recorder may have thinned or pruned.', + }, + { + id: 'PB-N-xxiv. ★★★ a window the capture judged is judged again', + file: NLS, tests: [T_IND], + find: " if (unjudged.state !== 'pending' || !(capturedAt < unjudged.judgeFromMs)) return false;", + to: " if (unjudged.state !== 'pending') return false; /* MUTANT */", + why: 'A day the balance refused at the capture is graded on a later evening\'s report.', + }, + { + id: 'PB-N-xxv. ★★ a capture at the judging hour counted as unjudged', + file: NLS, tests: [T_IND], + find: " if (unjudged.state !== 'pending' || !(capturedAt < unjudged.judgeFromMs)) return false;", + to: " if (unjudged.state !== 'pending' || !(capturedAt <= unjudged.judgeFromMs)) return false; /* MUTANT */", + why: 'The boundary of the judging hour moves by one instant.', + }, + { + id: 'PB-N-xxvi. ★★★ the sweep measures before the day is judged', + file: NLS, tests: [T_IND], + find: " return panelPvAdmission({ basis: row.actual_pv_basis, span: { startMs: a, endMs: b }, admission }).state !== 'pending';", + to: ' return true; /* MUTANT */', + why: 'Every unjudged window is read on every boot and spends its one measurement on a pending answer.', + }, + { + id: 'PB-N-xxvii. ★★★ the sweep\'s unjudged test reads the report', + file: NLS, tests: [T_IND], + find: ' const unjudged = panelPvAdmission({ basis: row.actual_pv_basis, span: { startMs: a, endMs: b }, admission: null });', + to: ' const unjudged = panelPvAdmission({ basis: row.actual_pv_basis, span: { startMs: a, endMs: b }, admission }); /* MUTANT */', + why: 'Once a report judges the day the row is never due: the sweep never grades.', + }, + { + id: 'PB-N-xxviii. ★★★ the sweep measures again on every tick', + file: IDX, tests: [T_IND], + find: ' if (shadowPvRemeasuredThisBoot.has(day) || !shadowPanelPvRemeasureDue(', + to: ' if (!shadowPanelPvRemeasureDue( /* MUTANT */', + why: 'A window that stays NULL is read and logged every thirty minutes.', + }, + { + id: 'PB-N-xxix. ★★ the sweep remembers nothing', + file: IDX, tests: [T_IND], + find: ' shadowPvRemeasuredThisBoot.add(day);', + to: ' /* MUTANT */', + why: 'A window that stays NULL is read and logged every thirty minutes.', + }, + { + id: 'PB-N-xxx. ★★★ the sweep ignores held telemetry', + file: IDX, tests: [T_IND], + find: ' held: { spans: (from, to) => recorder.heldSpans?.(from, to) ?? [], panelSn: shp2Sn },', + to: ' held: null, /* MUTANT */', + why: 'A restated reading from a panel offline in the cloud is summed as the window\'s solar.', + }, + { + id: 'PB-N-xxxi. ★★ the sweep\'s C slot resolves to a Core off the panel', + file: IDX, tests: [T_IND], + find: " coreOfSlot: (slot) => houseSlots.find((x) => x.slot === slot && x.isConnected === true && typeof x.sn === 'string')?.sn ?? null,", + to: " coreOfSlot: (slot) => houseSlots.find((x) => x.slot === slot && typeof x.sn === 'string')?.sn ?? null, /* MUTANT */", + why: 'A mixed band\'s Core slot is graded on a Core the panel no longer connects.', + }, + { + id: 'PB-N-xxxii. ★★★ the sweep reads no admission', + file: IDX, tests: [T_IND], + find: ' admission: panelAdmissionMem,\n },\n });', + to: ' admission: null, /* MUTANT */\n },\n });', + why: 'Every window the sweep reads stays pending.', + }, + { + id: 'PB-N-xxxiii. ★★★ the sweep measures on no band', + file: IDX, tests: [T_IND], + find: ' bandAsOfDay: band, panelSn: shp2Sn,', + to: ' bandAsOfDay: null, panelSn: shp2Sn, /* MUTANT */', + why: 'The sweep reads and never grades.', + }, + { + id: 'PB-N-xxxiv. ★★★ the sweep never writes its figure', + file: IDX, tests: [T_IND], + find: ' if (m.pvKwh != null) recorder.recordNightOutcome(day, { shadow_window_pv_kwh: m.pvKwh });', + to: ' /* MUTANT */', + why: 'The log says the window was measured while the row keeps NULL.', + }, + { + id: 'PB-N-xxxv. ★★ the sweep says nothing', + file: IDX, tests: [T_IND], + find: ' app.log[line.level](line.text);\n }\n } catch', + to: ' /* MUTANT */\n }\n } catch', + why: 'A shadow column changes after its capture with no line to say when or why.', + }, + { + id: 'PB-N-xxxvi. ★★ the sweep\'s NULL said at the info level', + file: NLS, tests: [T_IND], + find: " return { level: 'debug', text: `night-charge ledger: shadow_window_pv_kwh for ${planDate} stays NULL", + to: " return { /* MUTANT */ level: 'info', text: `night-charge ledger: shadow_window_pv_kwh for ${planDate} stays NULL", + why: 'Every boot repeats an info line for each window that stays NULL.', + }, + { + id: 'PB-N-xxxvii. ★★ a held window\'s NULL given the resolver\'s reason', + file: NLS, tests: [T_IND], + find: " const why = held.pv || held.load ? 'held telemetry over the window'", + to: " const why = (false as boolean) ? 'held telemetry over the window' /* MUTANT */", + why: 'A window withheld for held telemetry is said to be pending the balance.', + }, ]; // Mutants run in parallel, each in its own copy of the tree (scripts/lib/mutateParallel.mjs). diff --git a/server/src/index.ts b/server/src/index.ts index 06cf70d6..9cf5317d 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -341,6 +341,8 @@ import { runMiddayShadowEvening, shadowCycleConfig, shadowRefreshDue, standingRefresh, refreshFromSized, refreshSizing, liveOvernightWrote, notComparableRefresh, notArmedRefresh, middayShadowLedgerColumns, middayShadowRefreshLedgerColumns, middayShadowLogLines, middayShadowRefreshLogLine, + // ★★★ v1.210.1 — the band the shadow's cost leg was sized on, read back from its row (the capture grades its window on it). + shadowCostPanelPvAsOfDay, coerceMiddayShadowRecord, getMiddayShadow, setMiddayShadow, middayChargeStateFields, shadowServed, windowP50Kwh, MIDDAY_SHADOW_LOG_TAG, heldImportEstimate, heldSpan, type HeldImport, middayShadowPreview, middayShadowPreviewLogLines, middayShadowRefreshPreviewLogLine, weatherAgeSeconds, @@ -386,8 +388,12 @@ import { heldLedgerVerdict, heldLedgerNote, heldLedgerRepair, heldRepairColumns, heldRepairClause, heldSides, basisIncompleteNote, cushionOnlyNote, // v1.204.0 — a row planned on the panel's own readings: its PV actual from the per-slot sources, and its note. isPanelBasisRow, panelRowPvActual, panelPvActualNote, + // ★★★ v1.210.1 — a panel row's PV actual, said in the log by the panel path itself (the Cores' gate says nothing on it). + panelPvActualLogLine, // v1.204.0 (L5) — a panel row's PV actual only on slot-days the 7-day energy balance admitted, judged after its span. panelPvAdmission, panelPvRecaptureDue, panelPvRecaptureColumns, type PanelAdmission, + // ★★★ v1.210.1 — the shadow's window on the panel band, measured alone on a row whose own PV actual no re-capture revisits. + shadowWindowHeld, shadowWindowPanelPv, shadowPanelPvRemeasureDue, shadowPanelPvRemeasureLogLine, // v1.196.0 — the saturation that censors a row's PV for the cost ceiling's PV factor. pvSaturationColumns, } from './nightLedgerScoring.js'; @@ -4918,6 +4924,9 @@ function scoreCompletedNights(nowMs: number): void { if (repairHeldNightOutcomes(rows, shp2Sn, nowMs)) rows = recorder.readNightLedger(LEDGER_BACKFILL_SWEEP_DAYS); // v1.204.0 (L5) — and a panel row captured with its PV actual pending, once the energy balance has judged its span's days. if (repairPendingPanelPv(rows, nowMs)) rows = recorder.readNightLedger(LEDGER_BACKFILL_SWEEP_DAYS); + // ★★★ v1.210.1 — and the mid-day shadow's window on the panel band, on a panel row whose own PV actual was settled at its capture + // while the window's day was unjudged: measured alone once the energy balance has judged that day (its shadow column only). + remeasurePendingShadowPv(rows, shp2Sn, nowMs); // ★ THE v1.39.0 COMPLETION GATE (review HIGH ×2): a night may be captured // only once its FULL scored span has elapsed — 16 h past its REAL window // close. The pre-fix midnight tick captured yesterday's row while its @@ -5047,6 +5056,9 @@ function scoreNightRow( // v1.188.1 (review 5) — each actual is withheld on its own side only (nightLedgerScoring.heldSides). const heldSide = heldSides(heldVerdict); const deviceNameOf = (sn: string) => store.get().devices[sn]?.deviceName ?? sn; + // ★★★ v1.210.1 — read here (it was read after the gate): on a panel row the gate's figure is replaced below, and its log line is the + // panel path's (panelPvActualLogLine), not the Cores'. + const panelRow = isPanelBasisRow(y); let actualPvKwh: number | null = null; let actualPvCoverage: number | null = null; if (homeSns.size) { @@ -5063,17 +5075,18 @@ function scoreNightRow( actualPvCoverage = round2(worstCov); const pvHeld = heldSide.pv; actualPvKwh = worstCov >= PV_LEDGER_MIN_CORE_COVERAGE && !pvHeld ? round2(pvWh / 1000) : null; - if (pvHeld && heldVerdict != null) { - app.log.warn(`night-charge ledger: actual_pv_kwh WITHHELD for ${yDate} — ${heldVerdict.pv.map((p) => `${deviceNameOf(p.sn)} ${(p.heldMs / 3_600_000).toFixed(1)} h`).join(', ')} of the span had no fresh readings (held telemetry)`); - } else if (actualPvKwh == null) { - app.log.warn(`night-charge ledger: actual_pv_kwh WITHHELD — worst per-core PV coverage ${worstCov.toFixed(2)} < ${PV_LEDGER_MIN_CORE_COVERAGE} over the scored span; a fleet sum across a dark core under-counts and this column is durable`); + if (!panelRow) { + if (pvHeld && heldVerdict != null) { + app.log.warn(`night-charge ledger: actual_pv_kwh WITHHELD for ${yDate} — ${heldVerdict.pv.map((p) => `${deviceNameOf(p.sn)} ${(p.heldMs / 3_600_000).toFixed(1)} h`).join(', ')} of the span had no fresh readings (held telemetry)`); + } else if (actualPvKwh == null) { + app.log.warn(`night-charge ledger: actual_pv_kwh WITHHELD — worst per-core PV coverage ${worstCov.toFixed(2)} < ${PV_LEDGER_MIN_CORE_COVERAGE} over the scored span; a fleet sum across a dark core under-counts and this column is durable`); + } } } // ★★★ v1.204.0 — a row planned on the panel's own per-slot readings ('panel' / 'mixed'): its PV actual is the per-slot resolver over // the same span — the panel's reading (src{n}_pv_w) for a slot that took it, the slot's Core's pv_total for one that did not // (panelRowPvActual) — each slot at the Cores' coverage minimum, and withheld when the panel or a Core read held telemetry. The // sources go to actual_pv_basis; the note (panelPvActualNote) says what it is and that the row is kept apart. - const panelRow = isPanelBasisRow(y); let panelPv: ReturnType | null = null; let panelAdmission: ReturnType | null = null; if (panelRow) { @@ -5228,6 +5241,11 @@ function scoreNightRow( if (panelRow && panelPv != null) { const why = panelPv.why != null ? panelPv.why : panelPv.kwh == null && panelAdmission?.state === 'admitted' ? 'withheld' : null; scoreNotes += panelPvActualNote(y, panelPv.basis, why, why != null ? null : panelAdmission); + // ★★★ v1.210.1 — and the log says the same, once: withheld (why), pending or withheld by the balance; nothing when written. + const heldParts = heldVerdict != null && (heldSide.pv || heldSide.load) + ? [...heldVerdict.pv, ...heldVerdict.load].map((p) => `${deviceNameOf(p.sn)} ${(p.heldMs / 3_600_000).toFixed(1)} h`).join(', ') : null; + const pvLog = panelPvActualLogLine(yDate, panelPv.basis, why, why != null ? null : panelAdmission, heldParts); + if (pvLog != null) app.log[pvLog.level](pvLog.text); } scoreNotes += expectedBuyScoreNote({ expectedBuyKwh: y.expected_buy_kwh ?? null, @@ -5356,6 +5374,15 @@ function scoreNightRow( held: { spans: (a, b) => recorder.heldSpans?.(a, b) ?? [], panelSn: shp2Sn }, // v1.189.0 (review) — the shadow's window P50 is from the row's own band: set aside with it. pvSetAside: cols.pvSetAside, + // ★★★ v1.210.1 — a cost leg the panel-measured band of the row's own evening sized, on a panel row: its window's PV is the panel + // path's (the row's per-slot sources on the window, through the same admission), not the Cores' meter. + panel: { + bandAsOfDay: shadowCostPanelPvAsOfDay(y.shadow_arm_disposition), panelSn: shp2Sn, + coreOfSlot: (slot) => ((findShp2(store.get().devices)?.projection?.sources ?? []) as Array<{ slot?: number; sn?: string; isConnected?: boolean }>) + .find((x) => x.slot === slot && x.isConnected === true && typeof x.sn === 'string')?.sn ?? null, + query: (sn, metric, a, b) => recorder.query(sn, metric, a, b), + admission: panelAdmissionMem, + }, }); if (shadowActuals != null) { recorder.recordNightOutcome(yDate, { shadow_window_pv_kwh: shadowActuals.pvKwh, shadow_window_load_kwh: shadowActuals.loadKwh }); @@ -5972,6 +5999,48 @@ function repairPendingPanelPv(rows: NightLedgerRow[], nowMs: number): boolean { return reset; } +/** ★★★ v1.210.1 — the mid-day shadow's window on the panel band, on a 'panel' / 'mixed' row whose own PV actual was settled at its + * capture (withheld for thin, unsourced or held readings over the span) while the window's day was still unjudged: no re-capture + * follows such a row, so the window's PV is measured alone once the main thread has read a report that judges that day + * (nightLedgerScoring.shadowPanelPvRemeasureDue), by the capture's own rule and inputs (shadowWindowHeld, shadowWindowPanelPv: the + * row's slot sources on the window, at least 90 % covered, NULL on held telemetry, only on an admitted day). Only + * shadow_window_pv_kwh is written, and only with a figure: no other column of the row changes. Once per row per boot: a window that + * stays NULL (thin or held readings over it, or a day the balance did not pass) is not measured again on every tick. */ +const shadowPvRemeasuredThisBoot = new Set(); +function remeasurePendingShadowPv(rows: NightLedgerRow[], shp2Sn: string, nowMs: number): void { + try { + const horizonMs = forecastSpanRecaptureHorizonMs(config.retentionDays, LEDGER_BACKFILL_SWEEP_DAYS); + for (const y of rows) { + const day = String(y.plan_date); + const band = shadowCostPanelPvAsOfDay(y.shadow_arm_disposition); + if (shadowPvRemeasuredThisBoot.has(day) || !shadowPanelPvRemeasureDue(y, band, panelAdmissionMem, nowMs, horizonMs)) continue; + shadowPvRemeasuredThisBoot.add(day); + const a = Number(y.shadow_cost_window_start_ms); + const b = Number(y.shadow_cost_window_end_ms); + const houseSlots = (findShp2(store.get().devices)?.projection?.sources ?? []) as Array<{ slot?: number; sn?: string; isConnected?: boolean }>; + const held = shadowWindowHeld({ + homeSns: [...shp2ConnectedDpuSns(store.get().devices)], + held: { spans: (from, to) => recorder.heldSpans?.(from, to) ?? [], panelSn: shp2Sn }, + }, a, b); + const m = shadowWindowPanelPv({ + row: y, a, b, held, + panel: { + bandAsOfDay: band, panelSn: shp2Sn, + coreOfSlot: (slot) => houseSlots.find((x) => x.slot === slot && x.isConnected === true && typeof x.sn === 'string')?.sn ?? null, + query: (sn, metric, from, to) => recorder.query(sn, metric, from, to), + admission: panelAdmissionMem, + }, + }); + if (m == null) continue; + if (m.pvKwh != null) recorder.recordNightOutcome(day, { shadow_window_pv_kwh: m.pvKwh }); + const line = shadowPanelPvRemeasureLogLine(day, m); + app.log[line.level](line.text); + } + } catch (e: any) { + app.log.debug(`night-charge: shadow window PV re-measure skipped (${e?.message ?? e})`); + } +} + function repairHeldNightOutcomes(rows: NightLedgerRow[], shp2Sn: string, nowMs: number): boolean { let reset = false; try { diff --git a/server/src/middayShadow.ts b/server/src/middayShadow.ts index 4f6f84e4..316ba909 100644 --- a/server/src/middayShadow.ts +++ b/server/src/middayShadow.ts @@ -467,6 +467,18 @@ export function panelPvBasisNote(asOfDay: string | undefined): string { return asOfDay != null ? ` (on the panel-measured planning band as of ${asOfDay})` : ''; } +/** ★★★ v1.210.1 — E of the panel-measured band the COST leg was sized on, read back from a row's shadow_arm_disposition (written by + * middayShadowLedgerColumns: "cost: (on the panel-measured planning band as of E)", then option B's part, if any): the + * capture grades the cost leg's window on the band it was sized on (nightLedgerScoring.shadowWindowActuals). Null on a cost leg + * sized on the Cores' band, a row with no cost leg or only a note, and a row stamped before v1.210.0. PURE. */ +export function shadowCostPanelPvAsOfDay(disposition: string | null | undefined): string | null { + // The cost part ends at option B's part or at the end; option B's own note (a backup re-sized, which may take the panel band while + // the cost leg's daylight hours refuse it) is never the cost leg's. + const m = /(?:^|; )cost: (?:(?!; backup option B:)[\s\S])*? \(on the panel-measured planning band as of (\d{4}-\d{2}-\d{2})\)(?:; backup option B: \(on the panel-measured planning band as of \d{4}-\d{2}-\d{2}\))?$/ + .exec(String(disposition ?? '')); + return m != null ? m[1] : null; +} + /** The solar band a leg was sized on, in words (the refresh's reason). PURE. */ function solarBandWords(asOfDay: string | null): string { return asOfDay != null ? `the panel-measured planning band as of ${asOfDay}` : "the Cores' band"; diff --git a/server/src/nightLedgerScoring.ts b/server/src/nightLedgerScoring.ts index 4e9e6893..9016998a 100644 --- a/server/src/nightLedgerScoring.ts +++ b/server/src/nightLedgerScoring.ts @@ -249,9 +249,24 @@ export function minOverSpans( * same evening (panelPvSelection.shadowPvBasis), the row's band on the evenings the two select alike. * The set-aside is the row's: a band built on a solar model fitted on other Cores than the actuals * says nothing about forecast skill over the window either. The load is not a Core-set figure and - * is kept. */ + * is kept. + * + * ★★★ v1.210.1 — THE PANEL PATH (`panel`): on a row planned on the panel basis (isPanelBasisRow, the + * live row's own predicate) whose cost leg was sized on the panel-measured band as of the row's own + * evening (`panel.bandAsOfDay`, read back from shadow_arm_disposition, equal to plan_date: the + * row's pv_basis_slots are that evening's verdict, the one report both selections read), the + * window's PV is the live row's rule over the window: the per-slot resolver over pv_basis_slots + * (panelRowPvActual: the panel's own reading for a P slot, the slot's Core's meter for a C slot, + * each at the same 90 % coverage), null when either side was held over the window (the live panel + * row's rule), and null unless the 7-day energy balance admitted the window's day + * (panelPvAdmission: pending until it is judged, withheld where it did not pass). The row's PV + * set-aside does not null it: on a panel row it is the panel's own ("no independent meter"), the + * rule the row's actual_pv_kwh is written under too. A row the panel path does not cover — the + * Cores' band, another evening's band, no readable slots, no `panel` given — is measured as before, + * to the letter. The load is computed the same way on every row. */ export function shadowWindowActuals(i: { - row: Partial>; + row: Partial>; nowMs: number; homeSns: readonly string[]; queryPv: (sn: string, startMs: number, endMs: number) => ReadonlyArray; @@ -262,13 +277,13 @@ export function shadowWindowActuals(i: { /** The row's PV set-aside reason (NightLedgerColumns.pvSetAside); null or absent: the band is * evidence and the PV is measured. */ pvSetAside?: string | null; + /** ★★★ v1.210.1 — the panel path's inputs (above). Absent or null: the Cores' meter, as before. */ + panel?: ShadowWindowPanelInput | null; }): { pvKwh: number | null; loadKwh: number | null } | null { const a = i.row.shadow_cost_window_start_ms; const b = i.row.shadow_cost_window_end_ms; if (typeof a !== 'number' || typeof b !== 'number' || !(b > a) || i.nowMs < b) return null; - const held = i.held == null ? { pv: false, load: false } : heldSides(heldLedgerVerdict({ - spans: i.held.spans(a, b), coreSns: i.homeSns, panelSn: i.held.panelSn, span: { startMs: a, endMs: b }, - })); + const held = shadowWindowHeld(i, a, b); let pvKwh: number | null = null; if (i.homeSns.length > 0) { let pvEnergyWh = 0; @@ -282,12 +297,121 @@ export function shadowWindowActuals(i: { if (held.pv) pvKwh = null; } if (i.pvSetAside != null) pvKwh = null; + // ★★★ v1.210.1 — the panel path (above) REPLACES the figure, as the live row's panel block does: the resolver over the row's + // slots on the window, null on either side held, and only once the energy balance admitted the window's day. + const panelPv = shadowWindowPanelPv({ row: i.row, a, b, held, panel: i.panel }); + if (panelPv != null) pvKwh = panelPv.pvKwh; const load = i.queryLoad(a, b); const loadKwh = !held.load && load.length > 0 && coverageFrac(load, a, b) >= LEDGER_SPAN_MIN_COVERAGE ? round2(integrateWh(load, false) / 1000) : null; return { pvKwh, loadKwh }; } +/** ★★★ v1.210.1 — the panel path's inputs (shadowWindowActuals' `panel`, the sweep's too: index.ts remeasurePendingShadowPv). */ +export interface ShadowWindowPanelInput { + /** E of the panel-measured band the cost leg was sized on (middayShadow.shadowCostPanelPvAsOfDay); null: the Cores' band. */ + bandAsOfDay: string | null; + panelSn: string; + coreOfSlot: (slot: number) => string | null; + query: (sn: string, metric: string, fromMs: number, toMs: number) => ReadonlyArray; + /** The newest planning report's admitted slot-days the main thread has read (index.ts panelAdmissionMem). */ + admission: PanelAdmission | null | undefined; +} + +/** The held sides over the shadow's window [a, b]: heldLedgerVerdict over the window itself, the home Cores and the house panel + * (shadowWindowActuals; the sweep's too). No `held` given: no side is held. PURE. */ +export function shadowWindowHeld( + i: { homeSns: readonly string[]; held?: { spans: (startMs: number, endMs: number) => ReadonlyArray; panelSn: string } | null }, + a: number, + b: number, +): HeldSides { + return i.held == null ? { pv: false, load: false } : heldSides(heldLedgerVerdict({ + spans: i.held.spans(a, b), coreSns: i.homeSns, panelSn: i.held.panelSn, span: { startMs: a, endMs: b }, + })); +} + +/** ★★★ v1.210.1 — THE PANEL PATH of the shadow's window PV (shadowWindowActuals, above), over the closed window [a, b] on the held + * sides over it: null where the path does not apply (the figure is then the Cores' meter's, as before); else the per-slot resolver's + * figure, null on either side held and unless the 7-day energy balance admitted the window's day, with the sources (`basis`, the + * row's actual_pv_basis form), the admission it was read through, and why it is null (null when it is a figure). PURE. */ +export function shadowWindowPanelPv(i: { + row: Partial>; + a: number; + b: number; + held: HeldSides; + panel: ShadowWindowPanelInput | null | undefined; +}): { pvKwh: number | null; basis: string | null; admission: PanelPvAdmission; why: string | null } | null { + const { a, b, held } = i; + const p = i.panel; + const panelPv = p != null && p.bandAsOfDay != null && p.bandAsOfDay === i.row.plan_date + && isPanelBasisRow({ pv_basis: i.row.pv_basis ?? null, actual_pv_basis: i.row.actual_pv_basis }) + ? panelRowPvActual({ + slots: i.row.pv_basis_slots, span: { startMs: a, endMs: b }, panelSn: p.panelSn, coreOfSlot: p.coreOfSlot, query: p.query, + minCoverage: LEDGER_SPAN_MIN_COVERAGE, + }) + : null; + if (p != null && panelPv != null && panelPv.basis != null) { + const admission = panelPvAdmission({ basis: panelPv.basis, span: { startMs: a, endMs: b }, admission: p.admission }); + const pvKwh = held.pv || held.load || admission.state !== 'admitted' ? null : panelPv.kwh; + const why = held.pv || held.load ? 'held telemetry over the window' + : panelPv.why != null ? panelPv.why + : admission.state === 'pending' ? `pending the 7-day energy balance (${admission.lastDay} not yet judged)` + : admission.state === 'withheld' ? `slot ${admission.slot}'s ${admission.day} was not passed by the 7-day energy balance as of ${admission.asOfDay}` + : null; + return { pvKwh, basis: panelPv.basis, admission, why: pvKwh == null ? why : null }; + } + return null; +} + +/** ★★★ v1.210.1 — THE SHADOW'S WINDOW, ON ITS OWN WAY OUT OF PENDING. On a row the panel path covers (shadowWindowPanelPv), the + * window's PV is pending at the row's usual capture: the window lies on the span's last day, which no report the main thread can + * have read by then has judged. A row captured with its own PV actual pending (PANEL_PV_PENDING_MARKER) is re-captured whole once + * that day is judged (panelPvRecaptureDue), and its window is measured again then. A row whose own actual was settled at that + * capture — withheld by its resolver (a slot thin, unsourced or without its Core over the span) or by held telemetry over the span — + * is never re-captured, so its window is measured alone (index.ts remeasurePendingShadowPv). Due when: the row is captured, on the + * panel basis, without the pending marker; its window's PV is NULL; its cost leg's band (`bandAsOfDay`, as the capture reads it) is + * the panel band of the row's own evening; the window has closed; the row is inside the re-capture horizon; it was captured before + * the window's day could be judged (before 09:00 the morning after it, panelPvAdmission over the window on its recorded sources, + * actual_pv_basis), so the capture could not have judged it; and the newest report read (`admission`) now judges that day. A row + * with no P slot on record never pends and is never due. PURE. */ +export function shadowPanelPvRemeasureDue( + row: Pick & Partial>, + bandAsOfDay: string | null, + admission: PanelAdmission | null | undefined, + nowMs: number, + horizonMs: number, +): boolean { + const capturedAt = row.outcome_captured_at_ms; + if (typeof capturedAt !== 'number' || !Number.isFinite(capturedAt) || !isPanelBasisRow(row)) return false; + if (String(row.score_notes ?? '').includes(PANEL_PV_PENDING_MARKER)) return false; + if (row.shadow_window_pv_kwh != null) return false; + if (bandAsOfDay == null || bandAsOfDay !== row.plan_date) return false; + const a = row.shadow_cost_window_start_ms; + const b = row.shadow_cost_window_end_ms; + if (typeof a !== 'number' || typeof b !== 'number' || !(b > a) || nowMs < b) return false; + if (typeof row.issued_at_ms !== 'number' || !Number.isFinite(row.issued_at_ms) || nowMs - row.issued_at_ms > horizonMs) return false; + const unjudged = panelPvAdmission({ basis: row.actual_pv_basis, span: { startMs: a, endMs: b }, admission: null }); + if (unjudged.state !== 'pending' || !(capturedAt < unjudged.judgeFromMs)) return false; + return panelPvAdmission({ basis: row.actual_pv_basis, span: { startMs: a, endMs: b }, admission }).state !== 'pending'; +} + +/** ★★★ v1.210.1 — the sweep's log line for a shadow window it measured alone (index.ts remeasurePendingShadowPv): info with the + * figure where it wrote one; debug with the reason where the window stays NULL (nothing is written then). PURE. */ +export function shadowPanelPvRemeasureLogLine( + planDate: string, + m: NonNullable>, +): { level: 'info' | 'debug'; text: string } { + const src = m.basis != null ? ` (actual_pv_basis ${m.basis})` : ''; + if (m.pvKwh != null) { + const asOf = m.admission.state === 'admitted' && m.admission.asOfDay != null ? ` as of ${m.admission.asOfDay}` : ''; + const text = `night-charge ledger: shadow_window_pv_kwh for ${planDate} measured on the panel's own readings${src} — ${m.pvKwh} kWh, ` + + `the window's day judged by the 7-day energy balance${asOf}; the row's own columns are kept as captured`; + return { level: 'info', text }; + } + return { level: 'debug', text: `night-charge ledger: shadow_window_pv_kwh for ${planDate} stays NULL${src} — ${m.why ?? 'no figure'}` }; +} + /* ═══════════════════════════════════════════════════════════════════════════ * R4 (v1.189.0) — plan §4 item 9, the accounting part: the hours a mid-day charge of OURS held the * pool are not evidence about the arrays. A grid charge beside the sun takes acceptance the PV would @@ -647,6 +771,37 @@ export function panelPvActualNote( return `${head}${ratio} The row is kept apart from the readiness gate's sizing figures.`; } +/** ★★★ v1.210.1 — the capture's log line for a 'panel' / 'mixed' row's PV actual: the panel path's own outcome, from the note's own + * arguments and in its precedence (panelPvActualNote) — withheld with the resolver's or the held telemetry's reason (`heldParts`: the + * held devices, named), pending the 7-day energy balance, or withheld by it; null when the actual is written. On such a row the Cores' + * per-Core coverage gate logs nothing (index.ts scoreNightRow): the figure is not theirs. One line at most per capture. PURE. */ +export function panelPvActualLogLine( + planDate: string, + basis: string | null, + withheldWhy: string | null, + admission: PanelPvAdmission | null, + heldParts: string | null = null, +): { level: 'info' | 'warn'; text: string } | null { + const src = basis != null ? ` (actual_pv_basis ${basis})` : ''; + if (admission?.state === 'pending') { + return { + level: 'info', + text: `night-charge ledger: actual_pv_kwh for ${planDate} pending the 7-day energy balance${src} — ${admission.lastDay} is judged no ` + + `earlier than ${PANEL_PV_JUDGE_HOUR}:00 the next morning, and the row is re-captured once the night planner has read that judgement`, + }; + } + if (admission?.state === 'withheld') { + return { + level: 'warn', + text: `night-charge ledger: actual_pv_kwh WITHHELD for ${planDate}${src} — slot ${admission.slot}'s ${admission.day} was not passed by ` + + `the 7-day energy balance as of ${admission.asOfDay}`, + }; + } + if (withheldWhy == null) return null; + const held = heldParts != null && heldParts !== '' ? ` (${heldParts} with no fresh readings)` : ''; + return { level: 'warn', text: `night-charge ledger: actual_pv_kwh WITHHELD for ${planDate}${src} — ${withheldWhy}${held}` }; +} + /** * v1.187.0 — rows recorded BEFORE `pv_model_sns` existed whose PV band is established * to come from a model fitted on other Cores than the actuals. Identified by the exact diff --git a/server/test/ledgerPanelPvGrading.test.ts b/server/test/ledgerPanelPvGrading.test.ts new file mode 100644 index 00000000..527a0386 --- /dev/null +++ b/server/test/ledgerPanelPvGrading.test.ts @@ -0,0 +1,490 @@ +/** + * ledgerPanelPvGrading.test.ts — ★★★ v1.210.1: the ledger's solar on the panel's own readings, said and graded, with the Cores dark. + * + * 1. THE CAPTURE'S LOG LINE. On a row planned on the panel basis (isPanelBasisRow) the PV actual is the panel path's (the per-slot + * resolver through the 7-day energy balance), so the Cores' per-Core coverage gate no longer logs its "WITHHELD — worst per-core + * PV coverage" line there: the panel path states its own outcome, once (withheld, pending, withheld by the balance; nothing when + * written). On a row on the Cores' basis the gate and its lines are the v1.210.0 lines to the letter: scoreNightRow's PV block, as + * written in index.ts, runs beside the v1.210.0 block (kept below verbatim) on the same inputs, and every output and every log + * call is compared. + * 2. THE SHADOW'S MEASURED WINDOW. A cost leg the panel-measured band of the row's own evening sized, on a panel row, has its window's + * PV measured by the same rule as the live row (the per-slot resolver on the window, held telemetry, the same admission: pending, + * withheld, admitted); a leg on the Cores' band, and every case the panel path does not cover, is measured as before. + */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { transformSync } from 'esbuild'; +import { + shadowWindowActuals, panelPvActualLogLine, panelPvActualNote, panelRowPvActual, panelPvAdmission, isPanelBasisRow, + integrateWh, coverageFrac, panelPvVerdictSetAside, forecastSpanResetColumns, heldSides, + PANEL_PV_PENDING_MARKER, FORECAST_SPAN_MS, + type PanelAdmission, type PanelPvAdmission, type HeldLedgerVerdict, type LedgerHeldSpan, +} from '../src/nightLedgerScoring.js'; +import { shadowCostPanelPvAsOfDay, middayShadowLedgerColumns, panelPvBasisNote, type MiddayShadowRecord, type ShadowLegSummary } from '../src/middayShadow.js'; +import { siteDayStartMs, addDaysYmd } from '../src/siteTime.js'; +import type { NightLedgerRow } from '../src/recorder.js'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +type Any = any; +const HERE = dirname(fileURLToPath(import.meta.url)); +const INDEX = readFileSync(resolve(HERE, '../src/index.ts'), 'utf8'); +const SCORE_AT = INDEX.indexOf('function scoreNightRow('); +const SCORE = INDEX.slice(SCORE_AT, INDEX.indexOf('\nfunction ', SCORE_AT + 10)); +const H = 3_600_000; +const D = '2026-11-25'; +const D1 = addDaysYmd(D, 1); +const D2 = addDaysYmd(D, 2); +const ISSUED = siteDayStartMs(D) + (21 * 60 + 30) * 60_000; +const SPAN = { startMs: ISSUED, endMs: ISSUED + FORECAST_SPAN_MS }; +const PANEL = 'PANEL'; +const CORES = ['CORE1', 'CORE2', 'CORE3']; +const SOURCES = CORES.map((sn, k) => ({ slot: k + 1, sn, isConnected: true })); +/** 5-minute samples of a constant power over [from, to]. */ +const flat = (w: number, from: number, to: number) => { + const out: Array<{ ts: number; value: number }> = []; + for (let t = from; t <= to; t += 300_000) out.push({ ts: t, value: w }); + return out; +}; +/** A planning report as of an evening after `lastDay`, built at 09:00 the morning after it, admitting `days` on every slot. */ +const judged = (lastDay: string, days: string[], o: Partial> = {}): PanelAdmission => ({ + asOfDay: addDaysYmd(lastDay, 1), builtAtMs: siteDayStartMs(addDaysYmd(lastDay, 1)) + 9 * H, + slotDays: { 1: o[1] ?? days, 2: o[2] ?? days, 3: o[3] ?? days }, +}); + +/* ══ 1. the log line, pure ═════════════════════════════════════════════════════════════════════════════════════════════════════ */ + +test('★★★ panelPvActualLogLine: the panel path\'s own outcome, one line — pending (info), withheld by the balance or with its reason (warn), nothing when written', () => { + const pending: PanelPvAdmission = { state: 'pending', lastDay: D1, judgeFromMs: siteDayStartMs(D2) + 9 * H }; + assert.deepEqual(panelPvActualLogLine(D, '1:P,2:P,3:P', null, pending), { + level: 'info', + text: `night-charge ledger: actual_pv_kwh for ${D} pending the 7-day energy balance (actual_pv_basis 1:P,2:P,3:P) — ${D1} is judged no earlier than 9:00 the next morning, and the row is re-captured once the night planner has read that judgement`, + }); + assert.deepEqual(panelPvActualLogLine(D, '1:P,2:P,3:P', null, { state: 'withheld', asOfDay: D2, slot: 2, day: D1 }), { + level: 'warn', + text: `night-charge ledger: actual_pv_kwh WITHHELD for ${D} (actual_pv_basis 1:P,2:P,3:P) — slot 2's ${D1} was not passed by the 7-day energy balance as of ${D2}`, + }); + assert.deepEqual(panelPvActualLogLine(D, '1:P,2:P', 'worst per-slot PV coverage 0.42 < 0.9', null), { + level: 'warn', text: `night-charge ledger: actual_pv_kwh WITHHELD for ${D} (actual_pv_basis 1:P,2:P) — worst per-slot PV coverage 0.42 < 0.9`, + }); + assert.deepEqual(panelPvActualLogLine(D, '1:P,2:P,3:P', 'held telemetry over the span', null, 'Panel 2.0 h, Core one 1.5 h'), { + level: 'warn', + text: `night-charge ledger: actual_pv_kwh WITHHELD for ${D} (actual_pv_basis 1:P,2:P,3:P) — held telemetry over the span (Panel 2.0 h, Core one 1.5 h with no fresh readings)`, + }); + assert.equal(panelPvActualLogLine(D, null, 'no per-slot sources recorded', null)!.text, + `night-charge ledger: actual_pv_kwh WITHHELD for ${D} — no per-slot sources recorded`, 'no sources: no basis clause'); + assert.equal(panelPvActualLogLine(D, '1:P,2:P,3:P', null, { state: 'admitted', asOfDay: D2 }), null, 'written: no line'); + assert.equal(panelPvActualLogLine(D, '1:P,2:P,3:P', null, null), null); + for (const l of [panelPvActualLogLine(D, '1:P', 'x', null), panelPvActualLogLine(D, '1:P', null, pending)]) { + assert.doesNotMatch(l!.text, /per-core|dark core/, 'never the Cores\' words'); + } +}); + +test('★★★ panelPvActualLogLine follows the note\'s precedence: a line exactly where the note says pending or withheld, of the same kind', () => { + const r = { plan_date: D, pv_upper_ratio: 1.0123 }; + const pending: PanelPvAdmission = { state: 'pending', lastDay: D1, judgeFromMs: 0 }; + const withheld: PanelPvAdmission = { state: 'withheld', asOfDay: D2, slot: 3, day: D }; + const admitted: PanelPvAdmission = { state: 'admitted', asOfDay: D2 }; + for (const why of [null, 'held telemetry over the span', 'slot 2 had no source'] as Array) { + for (const adm of [null, pending, withheld, admitted] as Array) { + // index.ts passes the note's own arguments: the admission only where no reason withholds it. + const a = why != null ? null : adm; + const note = panelPvActualNote(r, '1:P,2:P,3:P', why, a); + const line = panelPvActualLogLine(D, '1:P,2:P,3:P', why, a); + const tag: string = `${why} / ${adm?.state}`; + if (note.startsWith(' PV actual is ')) assert.equal(line, null, tag); + else if (note.includes(PANEL_PV_PENDING_MARKER)) assert.equal(line?.level, 'info', tag); + else { + assert.ok(note.startsWith(' PV actual withheld'), tag); + assert.equal(line?.level, 'warn', tag); + assert.match(line!.text, /actual_pv_kwh WITHHELD for /, tag); + } + } + } +}); + +/* ══ 1. scoreNightRow's PV block, as written, against v1.210.0's ═══════════════════════════════════════════════════════════════ */ + +// The v1.210.0 block (index.ts scoreNightRow, from the PV actual's declaration to the end of the panel row's block, and the panel +// row's note), verbatim: the golden the new block is held to. +const V1210_PV_BLOCK = [ + " let actualPvKwh: number | null = null;", + " let actualPvCoverage: number | null = null;", + " if (homeSns.size) {", + " let pvWh = 0;", + " let worstCov = 1;", + " for (const sn of homeSns) {", + " const pts = recorder.query(sn, 'pv_total', fcSpanStart, fcSpanEnd);", + " pvWh += integrateWh(pts, true);", + " // Per-core, not fleet-averaged: one dark core in three averages to a", + " // healthy-looking 0.67 while the total is a third short. The MINIMUM is", + " // the only summary that cannot hide a single dark member.", + " worstCov = Math.min(worstCov, coverageFrac(pts, fcSpanStart, fcSpanEnd));", + " }", + " actualPvCoverage = round2(worstCov);", + " const pvHeld = heldSide.pv;", + " actualPvKwh = worstCov >= PV_LEDGER_MIN_CORE_COVERAGE && !pvHeld ? round2(pvWh / 1000) : null;", + " if (pvHeld && heldVerdict != null) {", + " app.log.warn(`night-charge ledger: actual_pv_kwh WITHHELD for ${yDate} — ${heldVerdict.pv.map((p) => `${deviceNameOf(p.sn)} ${(p.heldMs / 3_600_000).toFixed(1)} h`).join(', ')} of the span had no fresh readings (held telemetry)`);", + " } else if (actualPvKwh == null) {", + " app.log.warn(`night-charge ledger: actual_pv_kwh WITHHELD — worst per-core PV coverage ${worstCov.toFixed(2)} < ${PV_LEDGER_MIN_CORE_COVERAGE} over the scored span; a fleet sum across a dark core under-counts and this column is durable`);", + " }", + " }", + " // ★★★ v1.204.0 — a row planned on the panel's own per-slot readings ('panel' / 'mixed'): its PV actual is the per-slot resolver over", + " // the same span — the panel's reading (src{n}_pv_w) for a slot that took it, the slot's Core's pv_total for one that did not", + " // (panelRowPvActual) — each slot at the Cores' coverage minimum, and withheld when the panel or a Core read held telemetry. The", + " // sources go to actual_pv_basis; the note (panelPvActualNote) says what it is and that the row is kept apart.", + " const panelRow = isPanelBasisRow(y);", + " let panelPv: ReturnType | null = null;", + " let panelAdmission: ReturnType | null = null;", + " if (panelRow) {", + " const houseSrc = (findShp2(store.get().devices)?.projection?.sources ?? []) as Array<{ slot?: number; sn?: string; isConnected?: boolean }>;", + " panelPv = panelRowPvActual({", + " slots: y.pv_basis_slots, span: { startMs: fcSpanStart, endMs: fcSpanEnd }, panelSn: shp2Sn,", + " coreOfSlot: (slot) => houseSrc.find((x) => x.slot === slot && x.isConnected === true && typeof x.sn === 'string')?.sn ?? null,", + " query: (sn, metric, a, b) => recorder.query(sn, metric, a, b),", + " minCoverage: PV_LEDGER_MIN_CORE_COVERAGE,", + " });", + " const held = heldSide.pv || heldSide.load;", + " // v1.204.0 (L5) — and only on slot-days the 7-day energy balance admitted, as of an evening after the span, read after the", + " // morning its last day's daily total comes in (panelPvAdmission): pending until then (re-captured: repairPendingPanelPv), withheld", + " // where a span day was not passed. The PV-independent columns are captured now either way.", + " panelAdmission = panelPvAdmission({ basis: panelPv.basis, span: { startMs: fcSpanStart, endMs: fcSpanEnd }, admission: panelAdmissionMem });", + " actualPvKwh = held || panelAdmission.state !== 'admitted' ? null : panelPv.kwh;", + " actualPvCoverage = panelPv.worstCoverage;", + " if (held) panelPv = { ...panelPv, kwh: null, why: 'held telemetry over the span' };", + " else if (panelAdmission.state !== 'admitted') panelPv = { ...panelPv, kwh: null };", + " }", +].join('\n'); +const V1210_NOTE_BLOCK = [ + " if (panelRow && panelPv != null) {", + " const why = panelPv.why != null ? panelPv.why : panelPv.kwh == null && panelAdmission?.state === 'admitted' ? 'withheld' : null;", + " scoreNotes += panelPvActualNote(y, panelPv.basis, why, why != null ? null : panelAdmission);", + " }", +].join('\n'); + +/** A part of scoreNightRow as written: from `head` (found once) to the end of the first `tail` after it. */ +function part(headText: string, tail: string): string { + const at = SCORE.indexOf(headText); + assert.ok(at > 0 && SCORE.indexOf(headText, at + 1) < 0, headText); + const end = SCORE.indexOf(tail, at); + assert.ok(end > at, tail); + return SCORE.slice(at, end + tail.length); +} +const PV_BLOCK = part(' const panelRow = isPanelBasisRow(y);\n', " else if (panelAdmission.state !== 'admitted') panelPv = { ...panelPv, kwh: null };\n }\n"); +const NOTE_BLOCK = part(' if (panelRow && panelPv != null) {\n', ' if (pvLog != null) app.log[pvLog.level](pvLog.text);\n }\n'); + +interface BlockOut { actualPvKwh: number | null; actualPvCoverage: number | null; panelPv: Any; panelAdmission: Any; scoreNotes: string } +const compile = (body: string): ((env: Any) => BlockOut) => new Function(`${transformSync(`function __run(env: any) { +const { y, homeSns, recorder, heldSide, heldVerdict, deviceNameOf, app, yDate, fcSpanStart, fcSpanEnd, shp2Sn, store, findShp2, + panelAdmissionMem, isPanelBasisRow, panelRowPvActual, panelPvAdmission, panelPvActualNote, panelPvActualLogLine, integrateWh, + coverageFrac, round2, PV_LEDGER_MIN_CORE_COVERAGE } = env; +let scoreNotes = ''; +${body} +return { actualPvKwh, actualPvCoverage, panelPv, panelAdmission, scoreNotes }; +}`, { loader: 'ts' }).code}\nreturn __run;`)(); +const RUN_NOW = compile(`${PV_BLOCK}${NOTE_BLOCK}`); +const RUN_V1210 = compile(`${V1210_PV_BLOCK}\n${V1210_NOTE_BLOCK}\n`); + +interface BlockCase { + name: string; + row: Partial; + /** Each Core's pv_total (W), absent: dark (no samples). `thin`: the Cores with only a third of the span. */ + coreW?: Partial>; + thin?: string[]; + /** The panel's per-slot reading (W) on every slot, absent: none; `panelThin`: two hours of it. */ + panelW?: number; + panelThin?: boolean; + held?: HeldLedgerVerdict | null; + admission?: PanelAdmission | null; + homeSns?: string[]; +} +function runBlock(run: (env: Any) => BlockOut, c: BlockCase): BlockOut & { logs: Array<{ level: string; text: string }> } { + const logs: Array<{ level: string; text: string }> = []; + const query = (sn: string, metric: string, a: number, b: number) => { + if (sn === PANEL) return /^src\d_pv_w$/.test(metric) && c.panelW != null ? flat(c.panelW, a, c.panelThin ? a + 2 * H : b) : []; + const w = metric === 'pv_total' ? c.coreW?.[sn] : undefined; + return w == null ? [] : flat(w, a, c.thin?.includes(sn) ? a + 8 * H : b); + }; + const heldVerdict = c.held ?? null; + const out = run({ + y: { plan_date: D, issued_at_ms: ISSUED, pv_upper_ratio: 1.0123, ...c.row }, homeSns: new Set(c.homeSns ?? CORES), + recorder: { query }, heldSide: heldSides(heldVerdict), heldVerdict, deviceNameOf: (sn: string) => `Device ${sn}`, + app: { log: { warn: (text: string) => logs.push({ level: 'warn', text }), info: (text: string) => logs.push({ level: 'info', text }) } }, + yDate: D, fcSpanStart: SPAN.startMs, fcSpanEnd: SPAN.endMs, shp2Sn: PANEL, + store: { get: () => ({ devices: {} }) }, findShp2: () => ({ projection: { sources: SOURCES } }), + panelAdmissionMem: c.admission ?? null, + isPanelBasisRow, panelRowPvActual, panelPvAdmission, panelPvActualNote, panelPvActualLogLine, integrateWh, coverageFrac, + round2: (n: number) => Math.round(n * 100) / 100, PV_LEDGER_MIN_CORE_COVERAGE: 0.9, + }); + return { ...out, logs }; +} +const ALL_ON = { CORE1: 1000, CORE2: 1000, CORE3: 1000 }; +const STALE = `night-charge ledger: actual_pv_kwh WITHHELD — worst per-core PV coverage 0.00 < 0.9 over the scored span; a fleet sum across a dark core under-counts and this column is durable`; + +test('★★★ SOURCE PIN: the stubs are the scorer\'s own: the coverage minimum, round2, the slot lookup', () => { + assert.match(INDEX, /\nexport const PV_LEDGER_MIN_CORE_COVERAGE = 0\.9;\n/); + assert.match(INDEX, /\nfunction round2\(n: number\): number \{ return Math\.round\(n \* 100\) \/ 100; \}\n/); + assert.ok(PV_BLOCK.includes('const houseSrc = (findShp2(store.get().devices)?.projection?.sources ?? [])')); + // The block reads nothing the stubs do not give: every free name it uses is in the destructuring above. + assert.ok(!/\bnowMs\b|\bcols\b/.test(PV_BLOCK + NOTE_BLOCK)); +}); + +test('★★★ a row on the Cores\' basis is scored and logged exactly as v1.210.0: every figure, the note and every log line, held and dark Cores included', () => { + const cores: BlockCase[] = [ + { name: 'all three Cores reporting', row: { pv_basis: 'cores' }, coreW: ALL_ON }, + { name: 'one Core dark (the August case)', row: { pv_basis: 'cores' }, coreW: { CORE1: 1000, CORE2: 1000 } }, + { name: 'one Core thin', row: { pv_basis: 'cores' }, coreW: ALL_ON, thin: ['CORE2'] }, + { name: 'every Core dark', row: { pv_basis: 'cores' } }, + { name: 'a row from before the panel basis (pv_basis null)', row: { pv_basis: null } }, + { name: 'a Core held', row: { pv_basis: 'cores' }, coreW: ALL_ON, held: { pv: [{ sn: 'CORE2', heldMs: 2 * H }], load: [] } }, + { name: 'the panel held (load side only)', row: { pv_basis: 'cores' }, coreW: ALL_ON, held: { pv: [], load: [{ sn: PANEL, heldMs: 3 * H }] } }, + { name: 'no home Cores', row: { pv_basis: 'cores' }, homeSns: [] }, + { name: 'the panel reading present on a Cores row', row: { pv_basis: 'cores', pv_basis_slots: '1:P,2:P,3:P' }, panelW: 900, admission: judged(D1, [D, D1]) }, + ]; + for (const c of cores) { + assert.equal(isPanelBasisRow({ pv_basis: c.row.pv_basis ?? null }), false, c.name); + const now = runBlock(RUN_NOW, c); + const was = runBlock(RUN_V1210, c); + assert.deepEqual(now, was, c.name); + } + // The lines themselves, as v1.210.0 wrote them. + assert.deepEqual(runBlock(RUN_NOW, cores[3]).logs, [{ level: 'warn', text: STALE }]); + assert.deepEqual(runBlock(RUN_NOW, cores[1]).logs.map((l) => l.text), + ['night-charge ledger: actual_pv_kwh WITHHELD — worst per-core PV coverage 0.00 < 0.9 over the scored span; a fleet sum across a dark core under-counts and this column is durable']); + assert.deepEqual(runBlock(RUN_NOW, cores[5]).logs.map((l) => l.text), + [`night-charge ledger: actual_pv_kwh WITHHELD for ${D} — Device CORE2 2.0 h of the span had no fresh readings (held telemetry)`]); + assert.equal(runBlock(RUN_NOW, cores[0]).actualPvKwh, 72, 'three Cores at 1 kW over 24 h'); + assert.equal(runBlock(RUN_NOW, cores[1]).actualPvKwh, null, 'the gate still withholds a sum across a dark Core'); + assert.deepEqual(runBlock(RUN_NOW, cores[0]).logs, []); +}); + +test('★★★ a panel-basis row no longer logs the Cores-only warning: its figure and note are v1.210.0\'s, and its one log line is the panel path\'s own outcome', () => { + const P = { pv_basis: 'panel', pv_basis_slots: '1:P,2:P,3:P' } as Partial; + const days = [D, D1]; + const panel: Array = [ + // The live 11-18..11-25 shape: Cores dark, the panel's readings admitted. v1.210.0 logged the stale warning here, daily. + { name: 'Cores dark, admitted', row: P, panelW: 1000, admission: judged(D1, days), line: null }, + { name: 'Cores dark, pending (first capture)', row: P, panelW: 1000, admission: null, + line: { level: 'info', text: `night-charge ledger: actual_pv_kwh for ${D} pending the 7-day energy balance (actual_pv_basis 1:P,2:P,3:P) — ${D1} is judged no earlier than 9:00 the next morning, and the row is re-captured once the night planner has read that judgement` } }, + { name: 'Cores dark, a report as of the plan\'s own next evening (still pending)', row: P, panelW: 1000, admission: { ...judged(D1, days), asOfDay: D1 }, + line: { level: 'info', text: `night-charge ledger: actual_pv_kwh for ${D} pending the 7-day energy balance (actual_pv_basis 1:P,2:P,3:P) — ${D1} is judged no earlier than 9:00 the next morning, and the row is re-captured once the night planner has read that judgement` } }, + { name: 'Cores dark, withheld by the balance', row: P, panelW: 1000, admission: judged(D1, days, { 2: [D] }), + line: { level: 'warn', text: `night-charge ledger: actual_pv_kwh WITHHELD for ${D} (actual_pv_basis 1:P,2:P,3:P) — slot 2's ${D1} was not passed by the 7-day energy balance as of ${D2}` } }, + { name: 'Cores dark, the panel\'s reading thin', row: P, panelW: 1000, panelThin: true, admission: judged(D1, days), + line: { level: 'warn', text: `night-charge ledger: actual_pv_kwh WITHHELD for ${D} (actual_pv_basis 1:P,2:P,3:P) — worst per-slot PV coverage 0.09 < 0.9` } }, + // A reason withholds it even while the balance has not judged the span: the note says withheld (no re-capture), and so does the log. + { name: 'Cores dark, the panel\'s reading thin, pending', row: P, panelW: 1000, panelThin: true, admission: null, + line: { level: 'warn', text: `night-charge ledger: actual_pv_kwh WITHHELD for ${D} (actual_pv_basis 1:P,2:P,3:P) — worst per-slot PV coverage 0.09 < 0.9` } }, + { name: 'Cores dark, the panel held', row: P, panelW: 1000, admission: judged(D1, days), held: { pv: [], load: [{ sn: PANEL, heldMs: 2 * H }] }, + line: { level: 'warn', text: `night-charge ledger: actual_pv_kwh WITHHELD for ${D} (actual_pv_basis 1:P,2:P,3:P) — held telemetry over the span (Device PANEL 2.0 h with no fresh readings)` } }, + { name: 'a Core held', row: P, panelW: 1000, coreW: ALL_ON, admission: judged(D1, days), held: { pv: [{ sn: 'CORE1', heldMs: 1.5 * H }], load: [] }, + line: { level: 'warn', text: `night-charge ledger: actual_pv_kwh WITHHELD for ${D} (actual_pv_basis 1:P,2:P,3:P) — held telemetry over the span (Device CORE1 1.5 h with no fresh readings)` } }, + { name: 'mixed, its Core slot dark', row: { pv_basis: 'mixed', pv_basis_slots: '1:P,2:P,3:C' }, panelW: 1000, admission: judged(D1, days), + line: { level: 'warn', text: `night-charge ledger: actual_pv_kwh WITHHELD for ${D} (actual_pv_basis 1:P,2:P,3:C) — worst per-slot PV coverage 0.00 < 0.9` } }, + { name: 'mixed, its Core slot reporting', row: { pv_basis: 'mixed', pv_basis_slots: '1:P,2:P,3:C' }, panelW: 1000, coreW: { CORE3: 500 }, admission: judged(D1, days), line: null }, + { name: 'no slots recorded', row: { pv_basis: 'panel', pv_basis_slots: null }, panelW: 1000, admission: judged(D1, days), + line: { level: 'warn', text: `night-charge ledger: actual_pv_kwh WITHHELD for ${D} — no per-slot sources recorded` } }, + { name: 'the Cores reporting, admitted', row: P, panelW: 1000, coreW: ALL_ON, admission: judged(D1, days), line: null }, + { name: 'the Cores reporting, pending', row: P, panelW: 1000, coreW: ALL_ON, admission: null, + line: { level: 'info', text: `night-charge ledger: actual_pv_kwh for ${D} pending the 7-day energy balance (actual_pv_basis 1:P,2:P,3:P) — ${D1} is judged no earlier than 9:00 the next morning, and the row is re-captured once the night planner has read that judgement` } }, + { name: 'captured before as a panel row (actual_pv_basis)', row: { pv_basis: null, pv_basis_slots: '1:P,2:P,3:P', actual_pv_basis: '1:P,2:P,3:P' }, panelW: 1000, admission: judged(D1, days), line: null }, + ]; + for (const c of panel) { + const now = runBlock(RUN_NOW, c); + const was = runBlock(RUN_V1210, c); + const { logs: nowLogs, ...nowCols } = now; + const { logs: _wasLogs, ...wasCols } = was; + assert.deepEqual(nowCols, wasCols, `${c.name}: the figure, coverage, sources, admission and note are v1.210.0's`); + assert.deepEqual(nowLogs, c.line == null ? [] : [c.line], c.name); + assert.ok(nowLogs.every((l) => !/per-core PV coverage|dark core/.test(l.text)), `${c.name}: never the Cores-only warning`); + } + // v1.210.0 logged the stale warning on the live shape while it wrote the panel's figure: the defect this release removes. + const live = runBlock(RUN_V1210, panel[0]); + assert.equal(live.actualPvKwh, 72); + assert.deepEqual(live.logs, [{ level: 'warn', text: STALE }]); + assert.equal(runBlock(RUN_NOW, panel[0]).actualPvKwh, 72); +}); + +/* ══ 2. the cost leg's band, read back from the row ════════════════════════════════════════════════════════════════════════════ */ + +const leg = (role: 'backup' | 'cost', disposition: string, panelPvAsOfDay?: string): ShadowLegSummary => ({ + role, kind: role === 'cost' ? 'super_off_peak' : 'overnight', windowStartMs: 0, windowEndMs: 1, basisComplete: true, chargeTonight: true, + reservePct: 50, reserveBasis: null, levelPct: 60, costCeilingSocPct: null, buyKwh: 5, expectedBuyKwh: 4, expectedStartSocPct: 30, + cushionTroughSocPct: null, cushionLineSocPct: null, wouldArm: true, disposition, windowPvP50Kwh: 20, windowLoadP50Kwh: 10, + ...(panelPvAsOfDay != null ? { panelPvAsOfDay } : {}), +} as ShadowLegSummary); +const record = (o: Partial): MiddayShadowRecord => ({ + version: 1, day: D, computedAtMs: 0, why: 'midday', mode: 'supervised', backup: null, cost: null, refresh: null, note: null, ...o, +} as MiddayShadowRecord); +const dispOf = (o: Partial): string | null | undefined => middayShadowLedgerColumns(record(o)).shadow_arm_disposition; +const REFUSED = 'not armed — the plan basis is incomplete (only 0 scored calibration day(s), need 4; the panel\'s own solar readings are not used: the panel-measured band has no fitted solar response for the daylight hour from 11:00 AM)'; + +test('★★★ shadowCostPanelPvAsOfDay reads back what middayShadowLedgerColumns wrote: the COST leg\'s band only, never the backup\'s or option B\'s', () => { + // The cost leg on the panel band (with and without the backup and option B on it): its evening. + assert.equal(shadowCostPanelPvAsOfDay(dispOf({ backup: leg('backup', 'would arm', D), cost: leg('cost', 'would arm', D), backupB: leg('backup', 'x', D) })), D); + assert.equal(shadowCostPanelPvAsOfDay(dispOf({ backup: leg('backup', 'would arm'), cost: leg('cost', 'would arm', D) })), D); + assert.equal(shadowCostPanelPvAsOfDay(dispOf({ cost: leg('cost', 'would arm', D) })), D, 'no backup leg'); + // A cost disposition with its own semicolons and parentheses. + assert.equal(shadowCostPanelPvAsOfDay(dispOf({ backup: leg('backup', REFUSED), cost: leg('cost', 'held on the re-entry line (31.3%; level 60%)', D1) })), D1); + // The cost leg on the Cores' band while the backup and option B took the panel band (the daylight rule refuses only the cost + // leg's hours): not the cost leg's. + const split = dispOf({ backup: leg('backup', 'would arm', D), cost: leg('cost', REFUSED), backupB: leg('backup', 'x', D) }); + assert.ok(split!.includes(panelPvBasisNote(D)), split!); + assert.equal(shadowCostPanelPvAsOfDay(split), null); + assert.equal(shadowCostPanelPvAsOfDay(dispOf({ backup: leg('backup', 'would arm', D), cost: leg('cost', 'would arm') })), null); + // Nothing to read: no cost leg, a note-only row, a row from before v1.210.0, no value. + assert.equal(shadowCostPanelPvAsOfDay(dispOf({ backup: leg('backup', 'would arm', D) })), null); + assert.equal(shadowCostPanelPvAsOfDay(dispOf({ why: 'friday' as Any, note: 'not a mid-day cycle: Friday' })), null); + assert.equal(shadowCostPanelPvAsOfDay(`backup: would arm; cost: would arm`), null); + assert.equal(shadowCostPanelPvAsOfDay(null), null); + assert.equal(shadowCostPanelPvAsOfDay(undefined), null); + assert.equal(shadowCostPanelPvAsOfDay(`cost: would arm (on the panel-measured planning band as of yesterday)`), null, 'a malformed evening is no band'); +}); + +/* ══ 2. the shadow's measured window ═══════════════════════════════════════════════════════════════════════════════════════════ */ + +const WA = siteDayStartMs(D1) + 10 * H; +const WB = siteDayStartMs(D1) + 15 * H; +const AFTER = WB + 7 * H; +const PANEL_ROW = { shadow_cost_window_start_ms: WA, shadow_cost_window_end_ms: WB, plan_date: D, pv_basis: 'panel', pv_basis_slots: '1:P,2:P,3:P' } as Partial; +interface WinCase { coreW?: Partial>; panelW?: number; panelThin?: boolean; loadW?: number; held?: LedgerHeldSpan[] } +const winQuery = (c: WinCase) => ({ + queryPv: (sn: string, a: number, b: number) => (c.coreW?.[sn] == null ? [] : flat(c.coreW[sn]!, a, b)), + queryLoad: (a: number, b: number) => flat(c.loadW ?? 3000, a, b), + query: (sn: string, metric: string, a: number, b: number) => (sn === PANEL && /^src\d_pv_w$/.test(metric) && c.panelW != null + ? flat(c.panelW, a, c.panelThin ? a + H : b) + : metric === 'pv_total' && c.coreW?.[sn] != null ? flat(c.coreW[sn]!, a, b) : []), +}); +/** The capture's call: today's arguments, and the panel path's when `band` is given. */ +const measure = (row: Partial, c: WinCase, o: { band?: string | null; admission?: PanelAdmission | null; pvSetAside?: string | null; panel?: boolean } = {}) => { + const q = winQuery(c); + return shadowWindowActuals({ + row, nowMs: AFTER, homeSns: CORES, queryPv: q.queryPv, queryLoad: q.queryLoad, + held: { spans: () => c.held ?? [], panelSn: PANEL }, pvSetAside: o.pvSetAside === undefined ? panelPvVerdictSetAside(String(row.pv_basis)) : o.pvSetAside, + ...(o.panel === false ? {} : { + panel: { + bandAsOfDay: o.band === undefined ? D : o.band, panelSn: PANEL, coreOfSlot: (slot: number) => SOURCES.find((s) => s.slot === slot)?.sn ?? null, + query: q.query, admission: o.admission === undefined ? judged(D1, [D1]) : o.admission, + }, + }), + }); +}; +const today = (row: Partial, c: WinCase, pvSetAside?: string | null) => measure(row, c, { panel: false, pvSetAside }); + +test('★★★ the shadow\'s window PV on the panel band is the panel\'s own per-slot reading, admitted — with the Cores dark', () => { + // 3 slots × 2 kW × 5 h; the load (3 kW × 5 h) as before. + assert.deepEqual(measure(PANEL_ROW, { panelW: 2000 }), { pvKwh: 30, loadKwh: 15 }); + // v1.210.0 on the same row: NULL (the Cores dark, and the row's set-aside). + assert.deepEqual(today(PANEL_ROW, { panelW: 2000 }), { pvKwh: null, loadKwh: 15 }); + // The row's set-aside (the panel's own: no independent meter) does not null it, nor does no set-aside. + assert.equal(panelPvVerdictSetAside('panel') != null, true); + assert.deepEqual(measure(PANEL_ROW, { panelW: 2000 }, { pvSetAside: null }), { pvKwh: 30, loadKwh: 15 }); + // A mixed band: the panel's slots and the Core's own meter for its C slot (no admission needed for it). + const mixed = { ...PANEL_ROW, pv_basis: 'mixed', pv_basis_slots: '1:P,2:P,3:C' } as Partial; + assert.deepEqual(measure(mixed, { panelW: 2000, coreW: { CORE3: 1000 } }, { admission: judged(D1, [D1], { 3: [] }) }), { pvKwh: 25, loadKwh: 15 }); + assert.deepEqual(measure(mixed, { panelW: 2000 }), { pvKwh: null, loadKwh: 15 }, 'its Core dark: withheld, never a partial sum'); + // A row captured before as a panel row (actual_pv_basis) is a panel row. + assert.deepEqual(measure({ ...PANEL_ROW, pv_basis: null, actual_pv_basis: '1:P,2:P,3:P' }, { panelW: 2000 }), { pvKwh: 30, loadKwh: 15 }); +}); + +test('★★★ pending until the energy balance judges the window\'s day, withheld where it did not pass, NULL on held telemetry or thin readings', () => { + const c = { panelW: 2000 }; + // Pending: no report read; one as of the plan's own next evening (the window's day is not judged); one built before 09:00. + assert.deepEqual(measure(PANEL_ROW, c, { admission: null }), { pvKwh: null, loadKwh: 15 }); + assert.deepEqual(measure(PANEL_ROW, c, { admission: { ...judged(D1, [D1]), asOfDay: D1 } }), { pvKwh: null, loadKwh: 15 }); + assert.deepEqual(measure(PANEL_ROW, c, { admission: { ...judged(D1, [D1]), builtAtMs: siteDayStartMs(D2) + 9 * H - 1 } }), { pvKwh: null, loadKwh: 15 }); + assert.deepEqual(measure(PANEL_ROW, c, { admission: { ...judged(D1, [D1]), builtAtMs: siteDayStartMs(D2) + 9 * H } }), { pvKwh: 30, loadKwh: 15 }); + // Withheld: a slot whose window day the balance did not pass. The plan's own evening is not the window's day. + assert.deepEqual(measure(PANEL_ROW, c, { admission: judged(D1, [D1], { 2: [D] }) }), { pvKwh: null, loadKwh: 15 }); + assert.deepEqual(measure(PANEL_ROW, c, { admission: judged(D1, [D1], { 1: [D1], 2: [D1], 3: [D1] }) }), { pvKwh: 30, loadKwh: 15 }); + // Held over the window, either side (the live panel row's rule): the panel held leaves both figures empty, a Core held the PV. + assert.deepEqual(measure(PANEL_ROW, { ...c, held: [{ sn: PANEL, startMs: WA, endMs: WA + 2 * H }] }), { pvKwh: null, loadKwh: null }); + assert.deepEqual(measure(PANEL_ROW, { ...c, held: [{ sn: 'CORE2', startMs: WA, endMs: WA + 2 * H }] }), { pvKwh: null, loadKwh: 15 }); + assert.deepEqual(measure(PANEL_ROW, { ...c, held: [{ sn: PANEL, startMs: WA, endMs: WA + 30 * 60_000 }] }), { pvKwh: 30, loadKwh: 15 }, 'under an hour: not held'); + // Thin panel readings (an hour of the five), or a slot with no source: withheld, never a partial sum. + assert.deepEqual(measure(PANEL_ROW, { panelW: 2000, panelThin: true }), { pvKwh: null, loadKwh: 15 }); + assert.deepEqual(measure({ ...PANEL_ROW, pv_basis_slots: '1:P,2:N' }, c), { pvKwh: null, loadKwh: 15 }); + // The window not closed yet: nothing measured, as before. + assert.equal(shadowWindowActuals({ row: PANEL_ROW, nowMs: WB - 1, homeSns: CORES, queryPv: () => [], queryLoad: () => [], + panel: { bandAsOfDay: D, panelSn: PANEL, coreOfSlot: () => null, query: () => flat(2000, WA, WB), admission: judged(D1, [D1]) } }), null); +}); + +test('★★★ the shadow is pending exactly when the live row is (the window\'s day is the span\'s last), and the live row\'s re-capture clears its figure for the newer judgement', () => { + const reports: Array = [ + null, { ...judged(D1, [D, D1]), asOfDay: D1 }, { ...judged(D1, [D, D1]), builtAtMs: siteDayStartMs(D2) + 8 * H }, judged(D1, [D, D1]), + judged(D1, [D1]), judged(addDaysYmd(D1, 1), [D, D1]), + ]; + for (const a of reports) { + const live = panelPvAdmission({ basis: '1:P,2:P,3:P', span: SPAN, admission: a }).state; + const win = panelPvAdmission({ basis: '1:P,2:P,3:P', span: { startMs: WA, endMs: WB }, admission: a }).state; + assert.equal(win === 'pending', live === 'pending', JSON.stringify(a)); + } + const reset = forecastSpanResetColumns(0); + assert.equal(reset.shadow_window_pv_kwh, null); + assert.ok('shadow_window_pv_kwh' in reset); +}); + +test('★★★ unknown equals today: a Cores-band leg, another evening\'s band, a row not on the panel basis, no slots — each measured exactly as v1.210.0', () => { + const cases: Array<{ name: string; row: Partial; c: WinCase; band: string | null }> = [ + { name: 'the cost leg on the Cores\' band, the Cores dark', row: PANEL_ROW, c: { panelW: 2000 }, band: null }, + { name: 'the cost leg on the Cores\' band, the Cores reporting', row: PANEL_ROW, c: { panelW: 2000, coreW: { CORE1: 2000, CORE2: 2000, CORE3: 2000 } }, band: null }, + { name: 'a band of another evening', row: PANEL_ROW, c: { panelW: 2000 }, band: D1 }, + { name: 'a row on the Cores\' basis (the Cores reporting)', row: { ...PANEL_ROW, pv_basis: 'cores' }, c: { panelW: 2000, coreW: { CORE1: 2000, CORE2: 2000, CORE3: 2000 } }, band: D }, + { name: 'a row on the Cores\' basis (the Cores dark)', row: { ...PANEL_ROW, pv_basis: 'cores' }, c: { panelW: 2000 }, band: D }, + { name: 'a row before the panel basis', row: { ...PANEL_ROW, pv_basis: null, pv_basis_slots: null }, c: { coreW: { CORE1: 1000, CORE2: 1000, CORE3: 1000 } }, band: D }, + { name: 'a panel row with no slots recorded', row: { ...PANEL_ROW, pv_basis_slots: null }, c: { panelW: 2000, coreW: { CORE1: 2000, CORE2: 2000, CORE3: 2000 } }, band: D }, + { name: 'a panel row with unreadable slots', row: { ...PANEL_ROW, pv_basis_slots: '1:X' }, c: { panelW: 2000, coreW: { CORE1: 2000, CORE2: 2000, CORE3: 2000 } }, band: D }, + { name: 'a panel row with unreadable slots, the Cores dark', row: { ...PANEL_ROW, pv_basis_slots: '1:P,x' }, c: { panelW: 2000 }, band: D }, + { name: 'no shadow window', row: { ...PANEL_ROW, shadow_cost_window_start_ms: null, shadow_cost_window_end_ms: null }, c: { panelW: 2000 }, band: D }, + ]; + for (const k of cases) { + for (const aside of [undefined, null]) { + const sa = aside === undefined ? panelPvVerdictSetAside(String(k.row.pv_basis)) : null; + assert.deepEqual(measure(k.row, k.c, { band: k.band, pvSetAside: sa }), today(k.row, k.c, sa), `${k.name} (set-aside ${sa != null})`); + } + } + // Where the Cores report and no set-aside applies, today's figure is the Cores' meter, and the panel path never replaces it. + assert.deepEqual(measure({ ...PANEL_ROW, pv_basis_slots: '1:X' }, { panelW: 9000, coreW: { CORE1: 2000, CORE2: 2000, CORE3: 2000 } }, { pvSetAside: null }), + { pvKwh: 30, loadKwh: 15 }); + // The Cores' meter where the leg was sized on the Cores' band: on a Cores row, the Cores' figure. + assert.deepEqual(measure({ ...PANEL_ROW, pv_basis: 'cores' }, { panelW: 9000, coreW: { CORE1: 2000, CORE2: 2000, CORE3: 2000 } }, { band: null, pvSetAside: null }), + { pvKwh: 30, loadKwh: 15 }); +}); + +/* ══ 2. index.ts: the capture's call, as written ═══════════════════════════════════════════════════════════════════════════════ */ + +test('★★★ the capture passes the panel path the row\'s own band, the house panel, the live block\'s slot lookup, the recorder and the newest admission', () => { + const at = SCORE.indexOf(' const shadowActuals = shadowWindowActuals({'); + const call = SCORE.slice(at, SCORE.indexOf('\n });\n', at) + '\n });\n'.length); + assert.ok(call.includes(' pvSetAside: cols.pvSetAside,\n'), 'the set-aside still passed: today\'s rule off the panel path'); + const run = new Function(`${transformSync(`function __run(env: any) { +const { y, nowMs, homeSns, recorder, shp2Sn, cols, findShp2, store, panelAdmissionMem, shadowWindowActuals, shadowCostPanelPvAsOfDay } = env; +${call} +return shadowActuals; +}`, { loader: 'ts' }).code}\nreturn __run;`)() as (env: Any) => { pvKwh: number | null; loadKwh: number | null } | null; + const recorder = { + query: (sn: string, metric: string, a: number, b: number) => (sn === PANEL + ? (metric === 'panel_load' ? flat(3000, a, b) : /^src\d_pv_w$/.test(metric) ? flat(2000, a, b) : []) + : []), + heldSpans: () => [], + }; + const disposition = middayShadowLedgerColumns(record({ backup: leg('backup', 'would arm', D), cost: leg('cost', 'would arm', D) })).shadow_arm_disposition; + const env = (o: Partial<{ y: Any; admission: PanelAdmission | null }>) => ({ + y: { ...PANEL_ROW, shadow_arm_disposition: disposition, ...o.y }, nowMs: AFTER, homeSns: new Set(CORES), recorder, shp2Sn: PANEL, + cols: { pvSetAside: panelPvVerdictSetAside('panel') }, findShp2: () => ({ projection: { sources: SOURCES } }), store: { get: () => ({ devices: {} }) }, + panelAdmissionMem: o.admission === undefined ? judged(D1, [D1]) : o.admission, shadowWindowActuals, shadowCostPanelPvAsOfDay, + }); + assert.deepEqual(run(env({})), { pvKwh: 30, loadKwh: 15 }); + assert.deepEqual(run(env({ admission: null })), { pvKwh: null, loadKwh: 15 }, 'pending'); + // The mixed band's C slot resolves through the house panel's connected sources, as the live block's lookup does. + const mixedRec = { ...recorder, query: (sn: string, metric: string, a: number, b: number) => (sn === 'CORE3' && metric === 'pv_total' ? flat(1000, a, b) : recorder.query(sn, metric, a, b)) }; + assert.deepEqual(run({ ...env({ y: { pv_basis: 'mixed', pv_basis_slots: '1:P,2:P,3:C' }, admission: judged(D1, [D1], { 3: [] }) }), recorder: mixedRec }), { pvKwh: 25, loadKwh: 15 }); + assert.deepEqual(run({ ...env({ y: { pv_basis: 'mixed', pv_basis_slots: '1:P,2:P,3:C' } }), findShp2: () => ({ projection: { sources: SOURCES.map((s) => ({ ...s, isConnected: s.slot !== 3 })) } }), recorder: mixedRec }), + { pvKwh: null, loadKwh: 15 }, 'its Core not connected: withheld'); + // The cost leg on the Cores' band: today's (the Cores dark under the row's set-aside). + const cores = middayShadowLedgerColumns(record({ backup: leg('backup', 'would arm', D), cost: leg('cost', 'would arm') })).shadow_arm_disposition; + assert.deepEqual(run(env({ y: { shadow_arm_disposition: cores } })), { pvKwh: null, loadKwh: 15 }); +}); diff --git a/server/test/panelPvGradingIndependent.test.ts b/server/test/panelPvGradingIndependent.test.ts new file mode 100644 index 00000000..c21cd98a --- /dev/null +++ b/server/test/panelPvGradingIndependent.test.ts @@ -0,0 +1,838 @@ +/** + * panelPvGradingIndependent.test.ts — an independent check of the night-charge ledger's solar on a row planned on the panel's own + * readings, with the Cores dark. + * + * The whole scorer (index.ts scoreNightRow, as the file writes it) is compiled and run here on stub telemetry, with every other name + * it reads resolved from the modules index.ts itself imports it from. Only the recorder, the device store and the log are stubs. + * + * What is held: + * - A row on the Cores' basis: its figure and both of the Cores' warnings, to the letter (the per-Core coverage gate is a safety + * rule: one Core silent for days makes the fleet sum a fraction of true production). + * - A row on the panel basis: the same figure as the panel path gives, and never the Cores-only warning; the panel path's own + * outcome is said once where it withholds the figure or leaves it pending, and nothing is said where it is written. + * - The mid-day shadow's measured window solar: the panel's per-slot readings where the cost leg was sized on the panel band of the + * row's own evening, only once the 7-day energy balance admitted the window's day, NULL on held telemetry and NULL rather than a + * partial sum; the Cores' meter where it was sized on the Cores' band; and today's output wherever the panel path cannot produce a + * figure (no slot list, another evening's band, a row not on the panel basis). + * - The shadow's own way out of pending: on a panel row whose own PV actual was settled at its capture (withheld for readings thin + * or held over the night) while the window's day was unjudged, no re-capture follows, so the backfill sweep measures the window + * alone once the balance has judged that day (index.ts remeasurePendingShadowPv, compiled here as the file writes it): the figure a + * re-capture would give, written to the shadow's column only; NULL and nothing written wherever the capture's rule gives NULL; and + * nothing read for a row the sweep does not own. + */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { transformSync } from 'esbuild'; +import { siteTimeZone, zonedWallTimeMs, addDaysYmd } from '../src/siteTime.js'; +import { + shadowWindowActuals, panelPvRecaptureDue, panelPvRecaptureColumns, shadowPanelPvRemeasureDue, forecastSpanRecaptureHorizonMs, + type PanelAdmission, +} from '../src/nightLedgerScoring.js'; +import { middayShadowLedgerColumns, shadowCostPanelPvAsOfDay, type MiddayShadowRecord, type ShadowLegSummary } from '../src/middayShadow.js'; +import type { NightLedgerRow } from '../src/recorder.js'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +/* ─── the scorer, as index.ts writes it ────────────────────────────────────────────────────────── */ + +const srcUrl = (rel: string): URL => new URL(`../src/${rel}`, import.meta.url); +const INDEX = readFileSync(srcUrl('index.ts'), 'utf8'); + +/** A top-level function of index.ts, from its head to its closing brace at column zero. */ +function topLevelFunction(head: string): string { + const at = INDEX.indexOf(`\n${head}`); + assert.ok(at >= 0, `index.ts has ${head}`); + assert.equal(INDEX.indexOf(`\n${head}`, at + 1), -1, `${head} is unique in index.ts`); + const end = INDEX.indexOf('\n}\n', at); + assert.ok(end > at); + return INDEX.slice(at + 1, end + 2); +} + +/** One-line local helper of index.ts (round2, round1). */ +function oneLineFunction(name: string): string { + const m = new RegExp(`^function ${name}\\(.*\\}$`, 'm').exec(INDEX); + assert.ok(m != null, `index.ts has its own ${name}`); + return m[0]; +} + +/** index.ts's named value imports: local name → { module, exported name }. */ +function indexImports(): Map { + const out = new Map(); + for (const m of INDEX.matchAll(/^import\s+(type\s+)?\{([\s\S]*?)\}\s+from\s+'([^']+)';/gm)) { + if (m[1] != null) continue; + for (const raw of m[2].replace(/\/\/[^\n]*/g, '').split(',')) { + const part = raw.trim(); + if (part === '' || part.startsWith('type ')) continue; + const mm = /^(\w+)(?:\s+as\s+(\w+))?$/.exec(part); + assert.ok(mm != null, `an import part index.ts writes: ${part}`); + out.set(mm[2] ?? mm[1], { mod: m[3], name: mm[1] }); + } + } + return out; +} + +const SCORER = topLevelFunction('function scoreNightRow('); +const SCORER_WORDS = new Set(SCORER.match(/\b[A-Za-z_$][\w$]*\b/g) ?? []); +const IMPORTS = indexImports(); +/** Every imported name the scorer reads, with the module index.ts takes it from. */ +const SCORER_IMPORTS = [...IMPORTS].filter(([local]) => SCORER_WORDS.has(local)); + +const resolved: Record = {}; +for (const [local, { mod, name }] of SCORER_IMPORTS) { + assert.ok(mod.startsWith('./') && mod.endsWith('.js'), `a module of the add-on: ${mod}`); + const ns: Record = await import(srcUrl(`${mod.slice(2, -3)}.ts`).href); + assert.ok(name in ns, `${mod} exports ${name}`); + resolved[local] = ns[name]; +} + +const PV_LEDGER_MIN_CORE_COVERAGE = Number(/^export const PV_LEDGER_MIN_CORE_COVERAGE = ([\d.]+);$/m.exec(INDEX)?.[1]); + +type Sample = { ts: number; value: number }; +type LogCall = { level: string; text: string }; +type HeldSpan = { sn: string; startMs: number; endMs: number }; +interface World { + devices: Record; + /** `${sn}|${metric}` → the watts at an instant, or null for no sample there. */ + series: Map number | null>; + held: HeldSpan[]; + admission: PanelAdmission | null; +} +interface Run { logs: LogCall[]; writes: Array<{ day: string; cols: Record }>; row: Record; recorderCalls: Set } + +const FIVE_MIN = 5 * 60_000; +let world: World | null = null; +let current: Run | null = null; + +const recorder = new Proxy({}, { + get(_t, prop: string) { + current!.recorderCalls.add(prop); + if (prop === 'query') { + return (sn: string, metric: string, a: number, b: number): Sample[] => { + const f = world!.series.get(`${sn}|${metric}`); + if (f == null) return []; + const out: Sample[] = []; + for (let ts = a; ts < b; ts += FIVE_MIN) { const v = f(ts); if (v != null) out.push({ ts, value: v }); } + return out; + }; + } + if (prop === 'heldSpans') { + return (a: number, b: number): HeldSpan[] => world!.held + .filter((h) => h.endMs > a && h.startMs < b).map((h) => ({ ...h, startMs: Math.max(h.startMs, a), endMs: Math.min(h.endMs, b) })); + } + if (prop === 'recordNightOutcome') { + return (day: string, cols: Record): void => { + current!.writes.push({ day, cols }); + Object.assign(current!.row, cols); + }; + } + return undefined; + }, +}); +const logger = (level: string) => (text: string): void => { current!.logs.push({ level, text }); }; +const app = { log: { warn: logger('warn'), info: logger('info'), error: logger('error'), debug: logger('debug'), trace: logger('trace'), fatal: logger('fatal') } }; +const store = { get: () => ({ devices: world!.devices }) }; + +const scope: Record = { + ...resolved, recorder, app, store, PV_LEDGER_MIN_CORE_COVERAGE, + homeChgMaxSocPcts: (): Array => [], +}; +Object.defineProperty(scope, 'panelAdmissionMem', { get: () => world!.admission, enumerable: true }); +const scopeProxy = new Proxy(scope, { has: (t, k) => typeof k === 'string' && k in t }); +const compiled = transformSync(`${oneLineFunction('round2')}\n${oneLineFunction('round1')}\n${SCORER}`, { loader: 'ts' }).code; +type ScoreNightRow = (y: NightLedgerRow, s: unknown, shp2Sn: string, nowMs: number, supersededBy?: string | null) => void; +// eslint-disable-next-line no-new-func +const scoreNightRow = new Function('__scope', `with (__scope) { return (function () {\n${compiled}\nreturn scoreNightRow;\n})(); }`)(scopeProxy) as ScoreNightRow; + +/* ─── the site, the night, the stubs ───────────────────────────────────────────────────────────── */ + +const TZ = siteTimeZone(); +const D = '2026-11-24'; +const D_PREV = addDaysYmd(D, -1); +const D1 = addDaysYmd(D, 1); +const D2 = addDaysYmd(D, 2); +const at = (ymd: string, h: number, m = 0): number => zonedWallTimeMs(ymd, h, m, TZ); +const ISSUED = at(D, 21, 30); +const WIN_START = at(D, 23); +const WIN_END = at(D1, 5); +const SHADOW_START = at(D1, 10); +const SHADOW_END = at(D1, 15); +const NOW = at(D2, 10); +const HOUR = 3_600_000; + +const PANEL = 'PANEL-A'; +const CORES = ['CORE-1', 'CORE-2', 'CORE-3']; +const devices = (): Record => ({ + [PANEL]: { + sn: PANEL, deviceName: 'House panel', housePanel: true, + projection: { kind: 'shp2', sources: CORES.map((sn, i) => ({ slot: i + 1, sn, isConnected: true })) }, + }, + ...Object.fromEntries(CORES.map((sn, i) => [sn, { sn, deviceName: `Core ${i + 1}` }])), +}); + +/** The watts each stub series reads (constant, a sample every five minutes). */ +const W = { p1: 1000, p2: 500, p3: 250, c1: 600, c2: 400, c3: 200, load: 800 }; +/** A constant series' energy over [a, b) on five-minute samples from a (the trapezoid has (n − 1) steps), kWh. */ +const kwhOver = (watts: number, a: number, b: number): number => (watts * ((Math.ceil((b - a) / FIVE_MIN) - 1) * FIVE_MIN)) / HOUR / 1000; +const r2 = (x: number): number => Math.round(x * 100) / 100; + +const SPAN_END = ISSUED + 24 * HOUR; +const PANEL_SPAN_KWH = r2(kwhOver(W.p1 + W.p2 + W.p3, ISSUED, SPAN_END)); +const CORES_SPAN_KWH = r2(kwhOver(W.c1 + W.c2 + W.c3, ISSUED, SPAN_END)); +const PANEL_WINDOW_KWH = r2(kwhOver(W.p1 + W.p2 + W.p3, SHADOW_START, SHADOW_END)); +const CORES_WINDOW_KWH = r2(kwhOver(W.c1 + W.c2 + W.c3, SHADOW_START, SHADOW_END)); +const LOAD_WINDOW_KWH = r2(kwhOver(W.load, SHADOW_START, SHADOW_END)); + +/** The panel's own per-slot readings, its load, SoC and grid meter: present over the whole night and day. */ +function panelSeries(m: Map number | null>): void { + m.set(`${PANEL}|src1_pv_w`, () => W.p1); + m.set(`${PANEL}|src2_pv_w`, () => W.p2); + m.set(`${PANEL}|src3_pv_w`, () => W.p3); + m.set(`${PANEL}|panel_load`, () => W.load); + m.set(`${PANEL}|backup_pct`, () => 60); + m.set(`${PANEL}|grid_home_w`, () => 0); +} +function coreSeries(m: Map number | null>, which: number[] = [1, 2, 3]): void { + const w = [W.c1, W.c2, W.c3]; + for (const n of which) m.set(`${CORES[n - 1]}|pv_total`, () => w[n - 1]); +} + +const ADMIT_ALL: PanelAdmission = { asOfDay: D2, builtAtMs: at(D2, 9, 30), slotDays: { 1: [D, D1], 2: [D, D1], 3: [D, D1] } }; + +/* ─── the shadow's row columns, as the shadow writes them ──────────────────────────────────────── */ + +const COST_DISP = 'not armed — the plan basis is incomplete (only 0 scored calibration day(s), need 4 (a provisional plan on a widened solar band from 4; the full band from 14))'; +const BACKUP_DISP = 'not armed — the cushion asks for nothing over the backup window'; + +function leg(role: 'backup' | 'cost', disposition: string, panelPvAsOfDay?: string): ShadowLegSummary { + const start = role === 'cost' ? SHADOW_START : at(D, 23); + const end = role === 'cost' ? SHADOW_END : at(D1, 5); + return { + role, kind: role === 'cost' ? 'midday' : 'overnight', windowStartMs: start, windowEndMs: end, basisComplete: false, chargeTonight: false, + reservePct: null, reserveBasis: null, levelPct: null, buyKwh: null, expectedBuyKwh: null, wouldArm: false, disposition, + windowPvP50Kwh: 9.1, windowLoadP50Kwh: 4.2, + ...(panelPvAsOfDay != null ? { panelPvAsOfDay } : {}), + } as unknown as ShadowLegSummary; +} +function shadowCols(o: { backupBand?: string; costBand?: string; optionBBand?: string; noCost?: boolean; note?: string }): Partial { + const rec = { + version: 1, day: D, computedAtMs: at(D, 21, 40), why: 'midday', mode: 'advisory', + backup: o.note != null ? null : leg('backup', BACKUP_DISP, o.backupBand), + backupB: o.optionBBand != null ? leg('backup', 'option B', o.optionBBand) : null, + cost: o.note != null || o.noCost === true ? null : leg('cost', COST_DISP, o.costBand), + refresh: null, note: o.note ?? null, + } as unknown as MiddayShadowRecord; + return middayShadowLedgerColumns(rec); +} + +/* ─── one capture ──────────────────────────────────────────────────────────────────────────────── */ + +type Basis = { pv_basis: string | null; pv_basis_slots: string | null }; +const CORES_BASIS: Basis = { pv_basis: 'cores', pv_basis_slots: null }; +const PANEL_BASIS: Basis = { pv_basis: 'panel', pv_basis_slots: '1:P,2:P,3:P' }; + +interface Telemetry { + cores?: number[]; + coreSeriesOverride?: Array<[number, (ts: number) => number | null]>; + panelOverride?: Array<[string, (ts: number) => number | null]>; + held?: HeldSpan[]; + /** The house panel's view of a Core's link (slot → isConnected), where it is not the default (every Core connected). */ + connected?: Partial>; +} +/** The world a capture or a sweep reads: the telemetry, the held spans, the store and the newest admission read. */ +function worldOf(o: Telemetry, admission: PanelAdmission | null): World { + const series = new Map number | null>(); + panelSeries(series); + coreSeries(series, o.cores ?? []); + for (const [n, f] of o.coreSeriesOverride ?? []) series.set(`${CORES[n - 1]}|pv_total`, f); + for (const [metric, f] of o.panelOverride ?? []) series.set(`${PANEL}|${metric}`, f); + const devs = devices() as Record; + for (const [slot, c] of Object.entries(o.connected ?? {})) devs[PANEL].projection.sources[Number(slot) - 1].isConnected = c; + return { devices: devs, series, held: o.held ?? [], admission }; +} + +function capture(o: Telemetry & { + basis: Basis; + admission?: PanelAdmission | null; + shadow?: Partial; + nowMs?: number; +}): Run { + world = worldOf(o, o.admission === undefined ? ADMIT_ALL : o.admission); + const y = { + plan_date: D, issued_at_ms: ISSUED, algo_version: 3, objective: 'cost', confidence_tier: 'normal', + window_start_ms: WIN_START, window_end_ms: WIN_END, + min_proj_soc_pct: 35, target_soc_pct: 60, buy_kwh: 0, required_extra_kwh: 0, + pv_p10_kwh: 20, pv_p50_kwh: 30, pv_p90_kwh: 45, load_p10_kwh: 15, load_p50_kwh: 19, load_p90_kwh: 25, + reserve_floor_pct: 10, cushion_pct: 10, rationale: '', + pv_model_sns: [...CORES].sort().join(','), pv_upper_ratio: 0.97, actual_pv_basis: null, + ...o.basis, + ...(o.shadow ?? shadowCols({ costBand: o.basis.pv_basis === 'panel' || o.basis.pv_basis === 'mixed' ? D : undefined })), + } as unknown as NightLedgerRow; + current = { logs: [], writes: [], row: {}, recorderCalls: new Set() }; + const spans = { windowStart: WIN_START, windowEnd: WIN_END, onpeak: null, scoreSpanEnd: WIN_END + 16 * HOUR, completeMs: WIN_END + 16 * HOUR, windowKnown: true }; + scoreNightRow(y, spans, PANEL, o.nowMs ?? NOW, null); + const run = current; + current = null; + return run; +} +const pvLogs = (r: Run): LogCall[] => r.logs.filter((l) => /actual_pv_kwh/.test(l.text)); +const CORES_COVERAGE_WARNING = (cov: string): string => + `night-charge ledger: actual_pv_kwh WITHHELD — worst per-core PV coverage ${cov} < 0.9 over the scored span; a fleet sum across a dark core under-counts and this column is durable`; +const isCoresOnlyLine = (t: string): boolean => /worst per-core PV coverage|a fleet sum across a dark core|of the span had no fresh readings \(held telemetry\)/.test(t); + +/* ─── the harness itself ───────────────────────────────────────────────────────────────────────── */ + +test('the scorer is the one index.ts writes: it reads only scoring modules, the recorder, the store and the log', () => { + assert.equal(PV_LEDGER_MIN_CORE_COVERAGE, 0.9); + const mods = [...new Set(SCORER_IMPORTS.map(([, v]) => v.mod))].sort(); + assert.deepEqual(mods, [ + './analytics.js', './limits.js', './middayShadow.js', './nightChargeAdvisor.js', './nightChargeGate.js', './nightLedgerScoring.js', + './shp2Membership.js', './tariff.js', + ]); + // No device write, push or announcement is reachable from the capture. + for (const [local] of SCORER_IMPORTS) { + assert.doesNotMatch(local, /^(set|send|push|publish|announce|write|arm|apply|force)/i, `${local} is not a write`); + } + const r = capture({ basis: PANEL_BASIS }); + assert.deepEqual([...r.recorderCalls].sort(), ['heldSpans', 'query', 'recordNightOutcome']); + assert.ok(r.writes.every((w) => w.day === D)); +}); + +/* ─── 1. a row on the Cores' basis: to the letter ──────────────────────────────────────────────── */ + +test('Cores basis, every Core reporting: the Cores\' sum, no PV line, and the shadow on the Cores\' meter', () => { + const r = capture({ basis: CORES_BASIS, cores: [1, 2, 3] }); + assert.equal(r.row.actual_pv_kwh, CORES_SPAN_KWH); + assert.equal(r.row.actual_pv_kwh, 28.7); + assert.equal(r.row.actual_pv_basis, null); + assert.deepEqual(pvLogs(r), []); + assert.equal(r.row.shadow_window_pv_kwh, CORES_WINDOW_KWH); + assert.equal(r.row.shadow_window_load_kwh, LOAD_WINDOW_KWH); +}); + +test('Cores basis, every Core dark: NULL, and the Cores\' coverage warning, word for word, once', () => { + const r = capture({ basis: CORES_BASIS, cores: [] }); + assert.equal(r.row.actual_pv_kwh, null); + assert.equal(r.row.actual_pv_basis, null); + assert.deepEqual(r.logs, [{ level: 'warn', text: CORES_COVERAGE_WARNING('0.00') }]); + // The panel's readings are present and are not used on this row, for the live figure or the shadow's (Cores' band). + assert.equal(r.row.shadow_window_pv_kwh, null); + assert.equal(r.row.shadow_window_load_kwh, LOAD_WINDOW_KWH); +}); + +test('Cores basis, one Core dark: NULL (never the two-Core sum), and the warning at 0.00', () => { + const r = capture({ basis: CORES_BASIS, cores: [1, 3] }); + assert.equal(r.row.actual_pv_kwh, null); + assert.deepEqual(r.logs, [{ level: 'warn', text: CORES_COVERAGE_WARNING('0.00') }]); + assert.equal(r.row.shadow_window_pv_kwh, null); +}); + +test('Cores basis, one Core thin (85 % covered): NULL, and the warning states that Core\'s coverage', () => { + const cutoff = ISSUED + 245 * FIVE_MIN; // 245 of 288 five-minute buckets + const r = capture({ basis: CORES_BASIS, cores: [1, 3], coreSeriesOverride: [[2, (ts) => (ts < cutoff ? W.c2 : null)]] }); + assert.equal(r.row.actual_pv_kwh, null); + assert.deepEqual(r.logs, [{ level: 'warn', text: CORES_COVERAGE_WARNING('0.85') }]); +}); + +test('Cores basis, a Core held two hours: NULL, and the Cores\' held line, word for word', () => { + const r = capture({ basis: CORES_BASIS, cores: [1, 2, 3], held: [{ sn: 'CORE-2', startMs: ISSUED + HOUR, endMs: ISSUED + 3 * HOUR }] }); + assert.equal(r.row.actual_pv_kwh, null); + assert.deepEqual(r.logs, [{ + level: 'warn', + text: `night-charge ledger: actual_pv_kwh WITHHELD for ${D} — Core 2 2.0 h of the span had no fresh readings (held telemetry)`, + }]); +}); + +test('a row with no solar basis (pv_basis NULL) is a Cores row, even with the panel\'s slot verdict recorded', () => { + const r = capture({ basis: { pv_basis: null, pv_basis_slots: '1:P,2:P,3:P' }, cores: [] }); + assert.equal(r.row.actual_pv_kwh, null); + assert.equal(r.row.actual_pv_basis, null); + assert.deepEqual(r.logs, [{ level: 'warn', text: CORES_COVERAGE_WARNING('0.00') }]); + const up = capture({ basis: { pv_basis: null, pv_basis_slots: '1:P,2:P,3:P' }, cores: [1, 2, 3] }); + assert.equal(up.row.actual_pv_kwh, CORES_SPAN_KWH); + assert.deepEqual(pvLogs(up), []); +}); + +/* ─── 2. a row on the panel basis: the panel path's figure, never the Cores-only warning ────────── */ + +test('panel basis, Cores dark, admitted: the panel\'s own figure is written and nothing is logged about it', () => { + const r = capture({ basis: PANEL_BASIS, cores: [] }); + assert.equal(r.row.actual_pv_kwh, PANEL_SPAN_KWH); + assert.equal(r.row.actual_pv_kwh, 41.85); + assert.equal(r.row.actual_pv_basis, '1:P,2:P,3:P'); + assert.deepEqual(r.logs, [], 'no line: the figure is written, and the Cores\' gate is not this row\'s'); +}); + +test('panel basis, Cores reporting too: the panel path\'s figure, not the Cores\' sum, and no line', () => { + const r = capture({ basis: PANEL_BASIS, cores: [1, 2, 3] }); + assert.equal(r.row.actual_pv_kwh, PANEL_SPAN_KWH); + assert.deepEqual(r.logs, []); +}); + +test('panel basis, pending the energy balance: NULL, pending in the note, one line that says pending (never the Cores\')', () => { + for (const admission of [null, { ...ADMIT_ALL, asOfDay: D1 }, { ...ADMIT_ALL, builtAtMs: at(D2, 8, 59) }]) { + const r = capture({ basis: PANEL_BASIS, cores: [], admission }); + assert.equal(r.row.actual_pv_kwh, null); + assert.match(String(r.row.score_notes), /PV actual pending the energy balance/); + const lines = pvLogs(r); + assert.equal(lines.length, 1, JSON.stringify(r.logs)); + assert.ok(!isCoresOnlyLine(lines[0].text), lines[0].text); + assert.match(lines[0].text, new RegExp(`${D}.*pending|pending.*${D}`)); + assert.doesNotMatch(lines[0].text, /WITHHELD/, 'pending is not a withholding'); + assert.equal(r.logs.length, 1); + } +}); + +test('panel basis, a span day the balance did not pass: NULL, one WITHHELD line naming the slot and day', () => { + const r = capture({ basis: PANEL_BASIS, cores: [], admission: { ...ADMIT_ALL, slotDays: { ...ADMIT_ALL.slotDays, 2: [D] } } }); + assert.equal(r.row.actual_pv_kwh, null); + const lines = pvLogs(r); + assert.equal(r.logs.length, 1, JSON.stringify(r.logs)); + assert.equal(lines.length, 1); + assert.equal(lines[0].level, 'warn'); + assert.ok(!isCoresOnlyLine(lines[0].text), lines[0].text); + assert.match(lines[0].text, /WITHHELD/); + assert.match(lines[0].text, new RegExp(D)); + assert.match(lines[0].text, /slot 2/); + assert.match(lines[0].text, new RegExp(D1)); +}); + +test('panel basis, the panel held two hours: NULL, one WITHHELD line for held telemetry, not the Cores\' held line', () => { + const r = capture({ basis: PANEL_BASIS, cores: [], held: [{ sn: PANEL, startMs: ISSUED + HOUR, endMs: ISSUED + 3 * HOUR }] }); + assert.equal(r.row.actual_pv_kwh, null); + assert.equal(r.logs.length, 1, JSON.stringify(r.logs)); + assert.equal(r.logs[0].level, 'warn'); + assert.ok(!isCoresOnlyLine(r.logs[0].text), r.logs[0].text); + assert.match(r.logs[0].text, /WITHHELD/); + assert.match(r.logs[0].text, /held/); +}); + +test('panel basis, a Core held two hours: NULL (the live row\'s rule), one line, and it is not the Cores\' held line', () => { + const r = capture({ basis: PANEL_BASIS, cores: [], held: [{ sn: 'CORE-2', startMs: ISSUED + HOUR, endMs: ISSUED + 3 * HOUR }] }); + assert.equal(r.row.actual_pv_kwh, null); + assert.equal(r.logs.length, 1, JSON.stringify(r.logs)); + assert.ok(!isCoresOnlyLine(r.logs[0].text), r.logs[0].text); + assert.match(r.logs[0].text, /WITHHELD/); +}); + +test('panel basis, a slot thin over the span: NULL, never the sum of the other slots, and one line', () => { + const cutoff = ISSUED + 200 * FIVE_MIN; + const r = capture({ basis: PANEL_BASIS, cores: [], panelOverride: [['src3_pv_w', (ts) => (ts < cutoff ? W.p3 : null)]] }); + assert.equal(r.row.actual_pv_kwh, null); + assert.equal(r.logs.length, 1, JSON.stringify(r.logs)); + assert.ok(!isCoresOnlyLine(r.logs[0].text), r.logs[0].text); + assert.match(r.logs[0].text, /WITHHELD/); +}); + +test('mixed basis: the panel for P slots and the slot\'s Core for its C slot; no Cores-only warning with two Cores dark', () => { + const MIXED: Basis = { pv_basis: 'mixed', pv_basis_slots: '1:P,2:P,3:C' }; + const r = capture({ basis: MIXED, cores: [3] }); + assert.equal(r.row.actual_pv_kwh, r2(kwhOver(W.p1 + W.p2 + W.c3, ISSUED, SPAN_END))); + assert.equal(r.row.actual_pv_basis, '1:P,2:P,3:C'); + assert.deepEqual(r.logs, []); + // Its Core dark too: NULL, and the panel path's own line. + const dark = capture({ basis: MIXED, cores: [] }); + assert.equal(dark.row.actual_pv_kwh, null); + assert.equal(dark.logs.length, 1, JSON.stringify(dark.logs)); + assert.ok(!isCoresOnlyLine(dark.logs[0].text), dark.logs[0].text); + assert.match(dark.logs[0].text, /WITHHELD/); +}); + +test('panel basis with no slot list: NULL, one WITHHELD line, never the Cores\' warning', () => { + const r = capture({ basis: { pv_basis: 'panel', pv_basis_slots: null }, cores: [] }); + assert.equal(r.row.actual_pv_kwh, null); + assert.match(String(r.row.score_notes), /PV actual withheld \(no per-slot sources recorded\)/); + assert.equal(r.logs.length, 1, JSON.stringify(r.logs)); + assert.ok(!isCoresOnlyLine(r.logs[0].text), r.logs[0].text); + assert.match(r.logs[0].text, /WITHHELD/); + // The shadow cannot be measured on the panel without the slots: today's output (the Cores' meter, set aside on a panel row). + assert.equal(r.row.shadow_window_pv_kwh, null); + assert.equal(r.row.shadow_window_load_kwh, LOAD_WINDOW_KWH); +}); + +test('every PV line on a panel row agrees with what the row holds: WITHHELD ⇒ NULL, pending ⇒ the pending note, none ⇒ a figure', () => { + const cases = [ + capture({ basis: PANEL_BASIS, cores: [] }), + capture({ basis: PANEL_BASIS, cores: [], admission: null }), + capture({ basis: PANEL_BASIS, cores: [], admission: { ...ADMIT_ALL, slotDays: { 1: [D, D1], 2: [D, D1], 3: [D1] } } }), + capture({ basis: PANEL_BASIS, cores: [], held: [{ sn: PANEL, startMs: ISSUED, endMs: ISSUED + 2 * HOUR }] }), + capture({ basis: { pv_basis: 'mixed', pv_basis_slots: '1:P,2:N,3:P' }, cores: [] }), + ]; + for (const r of cases) { + const lines = pvLogs(r); + assert.ok(lines.length <= 1, JSON.stringify(r.logs)); + if (lines.length === 0) assert.equal(typeof r.row.actual_pv_kwh, 'number'); + else if (/WITHHELD/.test(lines[0].text)) assert.equal(r.row.actual_pv_kwh, null); + else { + assert.match(lines[0].text, /pending/); + assert.equal(r.row.actual_pv_kwh, null); + assert.match(String(r.row.score_notes), /pending the energy balance/); + } + } +}); + +/* ─── 3. the shadow's measured window solar ────────────────────────────────────────────────────── */ + +test('the shadow\'s cost leg on the panel band of the row\'s evening: the panel\'s per-slot reading over the window, Cores dark', () => { + const r = capture({ basis: PANEL_BASIS, cores: [], shadow: shadowCols({ costBand: D }) }); + assert.equal(r.row.shadow_window_pv_kwh, PANEL_WINDOW_KWH); + assert.equal(r.row.shadow_window_pv_kwh, 8.6); + assert.equal(r.row.shadow_window_load_kwh, LOAD_WINDOW_KWH); + // With the Cores reporting it is still the panel's (the band the leg was sized on), never the Cores' meter. + const up = capture({ basis: PANEL_BASIS, cores: [1, 2, 3], shadow: shadowCols({ costBand: D }) }); + assert.equal(up.row.shadow_window_pv_kwh, PANEL_WINDOW_KWH); +}); + +test('the shadow on the panel band with the backup and option B on it too: the cost leg\'s band decides', () => { + const r = capture({ basis: PANEL_BASIS, cores: [], shadow: shadowCols({ backupBand: D, costBand: D, optionBBand: D }) }); + assert.equal(r.row.shadow_window_pv_kwh, PANEL_WINDOW_KWH); +}); + +test('the shadow is never graded on an unadmitted panel reading: NULL while pending and where the window\'s day did not pass', () => { + for (const admission of [null, { ...ADMIT_ALL, asOfDay: D1 }, { ...ADMIT_ALL, builtAtMs: at(D2, 8, 59) }, + { ...ADMIT_ALL, slotDays: { 1: [D, D1], 2: [D], 3: [D, D1] } }, { ...ADMIT_ALL, slotDays: {} }]) { + const r = capture({ basis: PANEL_BASIS, cores: [], admission, shadow: shadowCols({ costBand: D }) }); + assert.equal(r.row.shadow_window_pv_kwh, null, JSON.stringify(admission)); + assert.equal(r.row.shadow_window_load_kwh, LOAD_WINDOW_KWH); + } +}); + +test('the shadow is graded on its own window\'s day: a plan-evening day the balance did not pass does not withhold the window', () => { + const r = capture({ basis: PANEL_BASIS, cores: [], admission: { ...ADMIT_ALL, slotDays: { 1: [D, D1], 2: [D1], 3: [D, D1] } }, shadow: shadowCols({ costBand: D }) }); + assert.equal(r.row.actual_pv_kwh, null, 'the live row: its span day D was not passed for slot 2'); + assert.equal(r.row.shadow_window_pv_kwh, PANEL_WINDOW_KWH, 'the window is on D+1, which passed'); +}); + +test('the shadow: NULL on held telemetry inside the window (the panel or a Core), measured where the hold was outside it', () => { + const inside = (sn: string): HeldSpan => ({ sn, startMs: SHADOW_START + HOUR, endMs: SHADOW_START + 3 * HOUR }); + const panelHeld = capture({ basis: PANEL_BASIS, cores: [], held: [inside(PANEL)], shadow: shadowCols({ costBand: D }) }); + assert.equal(panelHeld.row.shadow_window_pv_kwh, null); + assert.equal(panelHeld.row.shadow_window_load_kwh, null); + const coreHeld = capture({ basis: PANEL_BASIS, cores: [], held: [inside('CORE-1')], shadow: shadowCols({ costBand: D }) }); + assert.equal(coreHeld.row.shadow_window_pv_kwh, null); + assert.equal(coreHeld.row.shadow_window_load_kwh, LOAD_WINDOW_KWH); + const outside = capture({ basis: PANEL_BASIS, cores: [], held: [{ sn: PANEL, startMs: ISSUED, endMs: ISSUED + 2 * HOUR }], shadow: shadowCols({ costBand: D }) }); + assert.equal(outside.row.actual_pv_kwh, null, 'the live row is withheld over its own span'); + assert.equal(outside.row.shadow_window_pv_kwh, PANEL_WINDOW_KWH); +}); + +test('the shadow: NULL rather than a partial sum where one slot\'s readings are thin inside the window', () => { + const thin = (ts: number): number | null => (ts >= SHADOW_START && ts < SHADOW_START + HOUR ? null : W.p3); + const r = capture({ basis: PANEL_BASIS, cores: [], panelOverride: [['src3_pv_w', thin]], shadow: shadowCols({ costBand: D }) }); + assert.equal(r.row.shadow_window_pv_kwh, null); + // An N slot, and a missing slot list: no figure from the panel either. + const n = capture({ basis: { pv_basis: 'mixed', pv_basis_slots: '1:P,2:N,3:P' }, cores: [], shadow: shadowCols({ costBand: D }) }); + assert.equal(n.row.shadow_window_pv_kwh, null); +}); + +test('the shadow on a mixed row: the panel for P slots and the slot\'s Core for its C slot, NULL with that Core dark', () => { + const MIXED: Basis = { pv_basis: 'mixed', pv_basis_slots: '1:P,2:P,3:C' }; + const r = capture({ basis: MIXED, cores: [3], shadow: shadowCols({ costBand: D }) }); + assert.equal(r.row.shadow_window_pv_kwh, r2(kwhOver(W.p1 + W.p2 + W.c3, SHADOW_START, SHADOW_END))); + const dark = capture({ basis: MIXED, cores: [], shadow: shadowCols({ costBand: D }) }); + assert.equal(dark.row.shadow_window_pv_kwh, null); +}); + +test('the shadow\'s cost leg on the Cores\' band: the Cores\' meter, as today', () => { + // On a row on the Cores' basis: the Cores' meter, the Cores reporting. + const r = capture({ basis: CORES_BASIS, cores: [1, 2, 3], shadow: shadowCols({}) }); + assert.equal(r.row.shadow_window_pv_kwh, CORES_WINDOW_KWH); + // One Core thin inside the window: NULL (the per-Core rule), never the panel. + const thin = capture({ basis: CORES_BASIS, cores: [1, 3], coreSeriesOverride: [[2, (ts) => (ts >= SHADOW_START && ts < SHADOW_START + HOUR ? null : W.c2)]], shadow: shadowCols({}) }); + assert.equal(thin.row.shadow_window_pv_kwh, null); + // On a row on the panel basis: today's output, the Cores' meter under the row's own PV set-aside (NULL). + for (const shadow of [shadowCols({}), shadowCols({ backupBand: D }), shadowCols({ optionBBand: D }), shadowCols({ backupBand: D, optionBBand: D })]) { + const p = capture({ basis: PANEL_BASIS, cores: [1, 2, 3], shadow }); + assert.equal(p.row.shadow_window_pv_kwh, null, String(shadow.shadow_arm_disposition)); + assert.equal(p.row.shadow_window_load_kwh, LOAD_WINDOW_KWH); + } +}); + +test('unknown equals today: another evening\'s band, a row not on the panel basis, a window not closed', () => { + // A band as of another evening than the row's: the panel path does not apply (today: the Cores' meter, set aside on a panel row). + const other = capture({ basis: PANEL_BASIS, cores: [], shadow: shadowCols({ costBand: D_PREV }) }); + assert.equal(other.row.shadow_window_pv_kwh, null); + // A row on the Cores' basis whose cost leg was sized on the panel band: no slot list to measure it by, so the Cores' meter. + const coresRow = capture({ basis: CORES_BASIS, cores: [1, 2, 3], shadow: shadowCols({ costBand: D }) }); + assert.equal(coresRow.row.shadow_window_pv_kwh, CORES_WINDOW_KWH); + const coresRowDark = capture({ basis: CORES_BASIS, cores: [], shadow: shadowCols({ costBand: D }) }); + assert.equal(coresRowDark.row.shadow_window_pv_kwh, null); + // A row with no solar basis that still records the evening's slot verdict: not a panel row, so the Cores' meter too. + const noBasis: Basis = { pv_basis: null, pv_basis_slots: '1:P,2:P,3:P' }; + assert.equal(capture({ basis: noBasis, cores: [1, 2, 3], shadow: shadowCols({ costBand: D }) }).row.shadow_window_pv_kwh, CORES_WINDOW_KWH); + assert.equal(capture({ basis: noBasis, cores: [], shadow: shadowCols({ costBand: D }) }).row.shadow_window_pv_kwh, null); + // The window not closed yet: no shadow columns are written at all. + const open = capture({ basis: PANEL_BASIS, cores: [], shadow: shadowCols({ costBand: D }), nowMs: SHADOW_END - 1 }); + assert.ok(open.writes.every((w) => !('shadow_window_pv_kwh' in w.cols))); + // A row with no shadow leg: no shadow columns either. + const none = capture({ basis: PANEL_BASIS, cores: [], shadow: shadowCols({ note: 'the cycle is overnight: Friday' }) }); + assert.ok(none.writes.every((w) => !('shadow_window_pv_kwh' in w.cols))); +}); + +test('captured pending, then re-captured: the row and its shadow are measured on the newer judgement, each line said once', () => { + // The first capture runs the evening after the span: the newest report is as of that evening, which cannot judge its own day. + const early: PanelAdmission = { asOfDay: D1, builtAtMs: at(D1, 21, 35), slotDays: { 1: [D_PREV, D], 2: [D_PREV, D], 3: [D_PREV, D] } }; + const first = capture({ basis: PANEL_BASIS, cores: [], admission: early, nowMs: at(D1, 22), shadow: shadowCols({ costBand: D }) }); + assert.equal(first.row.actual_pv_kwh, null); + assert.equal(first.row.shadow_window_pv_kwh, null); + assert.equal(first.logs.length, 1); + assert.match(first.logs[0].text, /pending/); + const captured = { plan_date: D, issued_at_ms: ISSUED, ...PANEL_BASIS, ...shadowCols({ costBand: D }), ...first.row } as unknown as NightLedgerRow; + assert.equal(panelPvRecaptureDue(captured, ADMIT_ALL, NOW, 30 * 86_400_000), true, 'the judged report makes the row due'); + const reset = panelPvRecaptureColumns(D2); + assert.ok('shadow_window_pv_kwh' in reset && reset.shadow_window_pv_kwh === null, 'the reset clears the shadow figure with the outcome'); + const second = capture({ basis: PANEL_BASIS, cores: [], admission: ADMIT_ALL, shadow: shadowCols({ costBand: D }) }); + assert.equal(second.row.actual_pv_kwh, PANEL_SPAN_KWH); + assert.equal(second.row.shadow_window_pv_kwh, PANEL_WINDOW_KWH); + assert.deepEqual(second.logs, []); +}); + +test('the shadow\'s figure never changes a column of the live row: the outcome write is the same with the shadow on either band', () => { + const onPanel = capture({ basis: PANEL_BASIS, cores: [], shadow: shadowCols({ costBand: D }) }); + const onCores = capture({ basis: PANEL_BASIS, cores: [], shadow: shadowCols({}) }); + const outcome = (r: Run): Record => { + const w = r.writes.find((x) => 'outcome_captured_at_ms' in x.cols); + assert.ok(w != null); + return w.cols; + }; + assert.deepEqual(outcome(onPanel), outcome(onCores)); + assert.deepEqual(onPanel.logs, onCores.logs); +}); + +/* ─── 4. the band, read back from the row ──────────────────────────────────────────────────────── */ + +test('the cost leg\'s band, read back from what the shadow writes: the cost leg\'s only', () => { + const read = (o: Parameters[0]): string | null => shadowCostPanelPvAsOfDay(shadowCols(o).shadow_arm_disposition); + assert.equal(read({ costBand: D }), D); + assert.equal(read({ backupBand: D, costBand: D }), D); + assert.equal(read({ backupBand: D, costBand: D, optionBBand: D }), D); + assert.equal(read({ costBand: D, optionBBand: D_PREV }), D); + assert.equal(read({ backupBand: D_PREV, costBand: D }), D); + assert.equal(read({}), null); + assert.equal(read({ backupBand: D }), null); + assert.equal(read({ optionBBand: D }), null); + assert.equal(read({ backupBand: D, optionBBand: D }), null); + assert.equal(read({ backupBand: D, noCost: true }), null); + assert.equal(read({ note: 'the cycle is overnight: Friday' }), null); + assert.equal(shadowCostPanelPvAsOfDay(null), null); + assert.equal(shadowCostPanelPvAsOfDay(undefined), null); + assert.equal(shadowCostPanelPvAsOfDay(''), null); +}); + +/* ─── 5. the pure measure, called without the panel path: as before ────────────────────────────── */ + +test('shadowWindowActuals without its panel input measures the Cores\' meter, as before', () => { + const q = (w: number) => (_sn: string, a: number, b: number): Sample[] => { + const out: Sample[] = []; + for (let ts = a; ts < b; ts += FIVE_MIN) out.push({ ts, value: w }); + return out; + }; + const row = { + shadow_cost_window_start_ms: SHADOW_START, shadow_cost_window_end_ms: SHADOW_END, plan_date: D, ...PANEL_BASIS, actual_pv_basis: null, + } as Partial; + const base = { row, nowMs: NOW, homeSns: CORES, queryPv: q(400), queryLoad: (a: number, b: number) => q(W.load)('', a, b) }; + assert.deepEqual(shadowWindowActuals(base), { pvKwh: r2(kwhOver(1200, SHADOW_START, SHADOW_END)), loadKwh: LOAD_WINDOW_KWH }); + assert.deepEqual(shadowWindowActuals({ ...base, panel: null }), { pvKwh: r2(kwhOver(1200, SHADOW_START, SHADOW_END)), loadKwh: LOAD_WINDOW_KWH }); + assert.deepEqual(shadowWindowActuals({ ...base, pvSetAside: 'set aside' }), { pvKwh: null, loadKwh: LOAD_WINDOW_KWH }); + // Given the panel input on a panel row on the panel band of its own evening, but with no readable slot list: the panel path + // cannot produce a figure, and the output is the one it gives without the panel input. + const panel = { + bandAsOfDay: D, panelSn: PANEL, coreOfSlot: (n: number) => CORES[n - 1] ?? null, admission: ADMIT_ALL, + query: (_sn: string, _m: string, a: number, b: number) => q(700)('', a, b), + }; + for (const slots of [null, '', 'garbled', '1:P,2:X']) { + const r = { ...row, pv_basis_slots: slots }; + assert.deepEqual(shadowWindowActuals({ ...base, row: r, panel }), shadowWindowActuals({ ...base, row: r }), String(slots)); + } + // With the slots readable, the panel path measures (three P slots at 700 W each), and the Cores' 400 W do not enter. + assert.deepEqual(shadowWindowActuals({ ...base, panel }), { pvKwh: r2(kwhOver(2100, SHADOW_START, SHADOW_END)), loadKwh: LOAD_WINDOW_KWH }); +}); + +/* ─── 6. the shadow's own way out of pending: the sweep, as index.ts writes it ─────────────────── */ + +const SWEEP = topLevelFunction('function remeasurePendingShadowPv('); +const SWEEP_WORDS = new Set(SWEEP.match(/\b[A-Za-z_$][\w$]*\b/g) ?? []); +/** Every imported name the sweep reads, with the module index.ts takes it from (the configuration is the stub below). */ +const SWEEP_IMPORTS = [...IMPORTS].filter(([local]) => SWEEP_WORDS.has(local)); +const sweepResolved: Record = {}; +for (const [local, { mod, name }] of SWEEP_IMPORTS) { + if (local === 'config') continue; + const ns: Record = await import(srcUrl(`${mod.slice(2, -3)}.ts`).href); + assert.ok(name in ns, `${mod} exports ${name}`); + sweepResolved[local] = ns[name]; +} +const SWEEP_DAYS = Number(/^const LEDGER_BACKFILL_SWEEP_DAYS = (\d+);$/m.exec(INDEX)?.[1]); +const RETENTION_DAYS = 30; +const HORIZON_MS = forecastSpanRecaptureHorizonMs(RETENTION_DAYS, SWEEP_DAYS); +/** The sweep's once-per-boot memory (index.ts shadowPvRemeasuredThisBoot): a new Set is a new boot. */ +let bootMemo = new Set(); +const sweepScope: Record = { + ...sweepResolved, recorder, app, store, config: { retentionDays: RETENTION_DAYS }, LEDGER_BACKFILL_SWEEP_DAYS: SWEEP_DAYS, +}; +Object.defineProperty(sweepScope, 'panelAdmissionMem', { get: () => world!.admission, enumerable: true }); +Object.defineProperty(sweepScope, 'shadowPvRemeasuredThisBoot', { get: () => bootMemo, enumerable: true }); +const sweepProxy = new Proxy(sweepScope, { has: (t, k) => typeof k === 'string' && k in t }); +type Sweep = (rows: NightLedgerRow[], shp2Sn: string, nowMs: number) => void; +// eslint-disable-next-line no-new-func +const remeasurePendingShadowPv = new Function('__scope', `with (__scope) { return (function () {\n${transformSync(SWEEP, { loader: 'ts' }).code}\nreturn remeasurePendingShadowPv;\n})(); }`)(sweepProxy) as Sweep; + +/** The first capture's report: as of the evening after the span, which cannot judge its own day. */ +const EARLY: PanelAdmission = { asOfDay: D1, builtAtMs: at(D1, 21, 35), slotDays: { 1: [D_PREV, D], 2: [D_PREV, D], 3: [D_PREV, D] } }; +/** The row as the ledger holds it after its capture (by default the usual one: the evening after the span, on that evening's report). */ +function captured(o: Telemetry & { basis: Basis; shadow?: Partial; admission?: PanelAdmission | null; nowMs?: number }): { first: Run; row: NightLedgerRow } { + const shadow = o.shadow ?? shadowCols({ costBand: D }); + const first = capture({ ...o, shadow, admission: o.admission === undefined ? EARLY : o.admission, nowMs: o.nowMs ?? at(D1, 22) }); + return { first, row: { plan_date: D, issued_at_ms: ISSUED, ...o.basis, ...shadow, ...first.row } as unknown as NightLedgerRow }; +} +/** One pass of the sweep over `rows` on the same telemetry, with `admission` the newest report read. */ +function sweepOnce(rows: NightLedgerRow[], o: Telemetry & { admission: PanelAdmission | null; nowMs?: number }): Run { + world = worldOf(o, o.admission); + current = { logs: [], writes: [], row: {}, recorderCalls: new Set() }; + remeasurePendingShadowPv(rows, PANEL, o.nowMs ?? NOW); + const run = current; + current = null; + return run; +} +const nothing = (r: Run, label: string): void => { + assert.deepEqual(r.writes, [], `${label}: nothing written`); + assert.deepEqual(r.logs, [], `${label}: nothing said`); + assert.deepEqual([...r.recorderCalls], [], `${label}: nothing read`); +}; + +const SLOT3_THIN_AT_NIGHT: Telemetry = { cores: [], panelOverride: [['src3_pv_w', (ts) => (ts < ISSUED + 40 * FIVE_MIN ? null : W.p3)]] }; +const PANEL_HELD_AT_NIGHT: Telemetry = { cores: [], held: [{ sn: PANEL, startMs: ISSUED, endMs: ISSUED + 2 * HOUR }] }; +const NOT_PASSED_D1_SLOT2: PanelAdmission = { ...ADMIT_ALL, slotDays: { ...ADMIT_ALL.slotDays, 2: [D] } }; + +test('the sweep runs on every pass of the backfill sweep, after both repairs and before the capture loop; it reads only scoring modules, the recorder, the store and the log', () => { + const pass = topLevelFunction('function scoreCompletedNights('); + const repaired = pass.indexOf(' if (repairPendingPanelPv(rows, nowMs)) rows = recorder.readNightLedger(LEDGER_BACKFILL_SWEEP_DAYS);'); + const swept = pass.indexOf('\n remeasurePendingShadowPv(rows, shp2Sn, nowMs);\n'); + const loop = pass.indexOf('for (const { row: y, spans: s } of ledgerRowsDueForCapture(rows, nowMs, nightSpansForRow))'); + assert.ok(repaired > 0 && swept > repaired && loop > swept, 'repairs, then the sweep, then the capture loop'); + assert.deepEqual([...new Set(SWEEP_IMPORTS.map(([, v]) => v.mod))].sort(), ['./config.js', './middayShadow.js', './nightLedgerScoring.js', './shp2Membership.js']); + for (const [local] of SWEEP_IMPORTS) assert.doesNotMatch(local, /^(set|send|push|publish|announce|write|arm|apply|force)/i, `${local} is not a write`); + const { row } = captured({ basis: PANEL_BASIS, ...SLOT3_THIN_AT_NIGHT }); + bootMemo = new Set(); + const r = sweepOnce([row], { ...SLOT3_THIN_AT_NIGHT, admission: ADMIT_ALL }); + assert.deepEqual([...r.recorderCalls].sort(), ['heldSpans', 'query', 'recordNightOutcome']); +}); + +test('★★★ a panel row withheld at its capture (a slot thin, or the panel held, over the night) is never re-captured: the sweep grades its window alone once the balance has judged the window\'s day', () => { + for (const [label, t] of [['slot 3 thin at night', SLOT3_THIN_AT_NIGHT], ['the panel held at night', PANEL_HELD_AT_NIGHT]] as const) { + const { first, row } = captured({ basis: PANEL_BASIS, ...t }); + assert.equal(first.row.actual_pv_kwh, null, label); + assert.equal(first.row.shadow_window_pv_kwh, null, `${label}: pending at the capture`); + assert.doesNotMatch(String(first.row.score_notes), /PV actual pending the energy balance/, `${label}: the row's own actual is settled`); + assert.equal(panelPvRecaptureDue(row, ADMIT_ALL, NOW, HORIZON_MS), false, `${label}: no re-capture follows`); + // The evening of the capture: the window's day is not judged yet. Nothing is read. + bootMemo = new Set(); + nothing(sweepOnce([row], { ...t, admission: EARLY, nowMs: at(D1, 23) }), `${label}, unjudged`); + // The morning after the window's day, the judging report read: the window's PV, and only that column. + const judged = sweepOnce([row], { ...t, admission: ADMIT_ALL }); + assert.deepEqual(judged.writes, [{ day: D, cols: { shadow_window_pv_kwh: PANEL_WINDOW_KWH } }], label); + assert.deepEqual(judged.logs, [{ + level: 'info', + text: `night-charge ledger: shadow_window_pv_kwh for ${D} measured on the panel's own readings (actual_pv_basis 1:P,2:P,3:P) — ${PANEL_WINDOW_KWH} kWh, the window's day judged by the 7-day energy balance as of ${D2}; the row's own columns are kept as captured`, + }], label); + // The figure a capture on that judgement grades. + assert.equal(capture({ basis: PANEL_BASIS, ...t, shadow: shadowCols({ costBand: D }), admission: ADMIT_ALL }).row.shadow_window_pv_kwh, PANEL_WINDOW_KWH); + assert.equal(PANEL_WINDOW_KWH, 8.6); + // Written, it is not measured again, this boot or the next. + nothing(sweepOnce([row], { ...t, admission: ADMIT_ALL }), `${label}, again`); + bootMemo = new Set(); + nothing(sweepOnce([{ ...row, shadow_window_pv_kwh: PANEL_WINDOW_KWH } as NightLedgerRow], { ...t, admission: ADMIT_ALL }), `${label}, written`); + } +}); + +test('★★★ the sweep grades nothing the capture would not: NULL and nothing written where the window\'s day was not passed, a side was held or a slot was thin inside the window; said once per boot', () => { + const inWindow = (h: number): { startMs: number; endMs: number } => ({ startMs: SHADOW_START + HOUR, endMs: SHADOW_START + (1 + h) * HOUR }); + const cases: Array<[string, Telemetry, PanelAdmission, string]> = [ + ['the window\'s day not passed', SLOT3_THIN_AT_NIGHT, NOT_PASSED_D1_SLOT2, `slot 2's ${D1} was not passed by the 7-day energy balance as of ${D2}`], + ['the panel held inside the window', { ...SLOT3_THIN_AT_NIGHT, held: [{ sn: PANEL, ...inWindow(2) }] }, ADMIT_ALL, 'held telemetry over the window'], + ['a Core held inside the window', { ...SLOT3_THIN_AT_NIGHT, held: [{ sn: 'CORE-2', ...inWindow(2) }] }, ADMIT_ALL, 'held telemetry over the window'], + ['slot 1 thin inside the window', { + cores: [], panelOverride: [ + ['src3_pv_w', (ts) => (ts < ISSUED + 40 * FIVE_MIN ? null : W.p3)], + ['src1_pv_w', (ts) => (ts >= SHADOW_START && ts < SHADOW_START + HOUR ? null : W.p1)], + ], + }, ADMIT_ALL, 'worst per-slot PV coverage 0.80 < 0.9'], + ]; + for (const [label, t, admission, why] of cases) { + const { first, row } = captured({ basis: PANEL_BASIS, ...t }); + assert.equal(first.row.actual_pv_kwh, null, label); + assert.equal(first.row.shadow_window_pv_kwh, null, label); + // The capture on the same judgement gives NULL too. + assert.equal(capture({ basis: PANEL_BASIS, ...t, shadow: shadowCols({ costBand: D }), admission }).row.shadow_window_pv_kwh, null, label); + bootMemo = new Set(); + const r = sweepOnce([row], { ...t, admission }); + assert.deepEqual(r.writes, [], `${label}: nothing written`); + assert.deepEqual(r.logs, [{ level: 'debug', text: `night-charge ledger: shadow_window_pv_kwh for ${D} stays NULL (actual_pv_basis 1:P,2:P,3:P) — ${why}` }], label); + nothing(sweepOnce([row], { ...t, admission }), `${label}, the same boot`); + bootMemo = new Set(); + assert.equal(sweepOnce([row], { ...t, admission }).logs.length, 1, `${label}: once in the next boot`); + } +}); + +test('★★★ not the sweep\'s, and nothing is read: a row its own re-capture revisits, a Cores row, a Cores-band leg, another evening\'s band, a row the capture judged, past the horizon, the day still unjudged', () => { + const none = (row: NightLedgerRow, t: Telemetry, admission: PanelAdmission | null, label: string, nowMs = NOW): void => { + bootMemo = new Set(); + nothing(sweepOnce([row], { ...t, admission, nowMs }), label); + }; + // Captured pending: the row's own re-capture measures the window (and clears it first). + const pend = captured({ basis: PANEL_BASIS, cores: [] }); + assert.match(String(pend.row.score_notes), /PV actual pending the energy balance/); + assert.equal(panelPvRecaptureDue(pend.row, ADMIT_ALL, NOW, HORIZON_MS), true); + none(pend.row, { cores: [] }, ADMIT_ALL, 'pending row'); + // A row on the Cores' basis, its shadow on the panel band: the Cores' meter at its capture, as before. + none(captured({ basis: CORES_BASIS, cores: [], shadow: shadowCols({ costBand: D }) }).row, { cores: [] }, ADMIT_ALL, 'Cores row'); + // A panel row withheld at its capture whose cost leg was on the Cores' band, or on another evening's band. + none(captured({ basis: PANEL_BASIS, ...SLOT3_THIN_AT_NIGHT, shadow: shadowCols({}) }).row, SLOT3_THIN_AT_NIGHT, ADMIT_ALL, 'Cores band'); + none(captured({ basis: PANEL_BASIS, ...SLOT3_THIN_AT_NIGHT, shadow: shadowCols({ costBand: D_PREV }) }).row, SLOT3_THIN_AT_NIGHT, ADMIT_ALL, 'another evening'); + // Captured once the window's day could be judged: the capture judged it (here, not passed), and a later report does not re-judge it. + const D3 = addDaysYmd(D, 3); + const late = captured({ basis: PANEL_BASIS, ...SLOT3_THIN_AT_NIGHT, admission: NOT_PASSED_D1_SLOT2, nowMs: at(D2, 10) }); + assert.equal(late.row.shadow_window_pv_kwh, null); + none(late.row, SLOT3_THIN_AT_NIGHT, { asOfDay: D3, builtAtMs: at(D3, 9, 30), slotDays: ADMIT_ALL.slotDays }, 'judged at its capture', at(D3, 10)); + // Past the re-capture horizon (the raw telemetry it would read), and the day still unjudged. + const thin = captured({ basis: PANEL_BASIS, ...SLOT3_THIN_AT_NIGHT }).row; + none(thin, SLOT3_THIN_AT_NIGHT, ADMIT_ALL, 'past the horizon', ISSUED + HORIZON_MS + 1); + none(thin, SLOT3_THIN_AT_NIGHT, null, 'no report read'); + none(thin, SLOT3_THIN_AT_NIGHT, { ...ADMIT_ALL, builtAtMs: at(D2, 8, 59) }, 'built before the day\'s total is in'); + none(thin, SLOT3_THIN_AT_NIGHT, { ...ADMIT_ALL, asOfDay: D1 }, 'as of the window\'s own day'); +}); + +test('shadowPanelPvRemeasureDue: captured before 09:00 the morning after the window\'s day, never at it; inside the horizon to its edge; a row with no P slot on record never pends', () => { + const { row } = captured({ basis: PANEL_BASIS, ...SLOT3_THIN_AT_NIGHT }); + const band = shadowCostPanelPvAsOfDay(row.shadow_arm_disposition); + assert.equal(band, D); + const judgeFrom = at(D2, 9); + const due = (r: Partial, nowMs = NOW, admission: PanelAdmission | null = ADMIT_ALL): boolean => + shadowPanelPvRemeasureDue({ ...row, ...r } as NightLedgerRow, band, admission, nowMs, HORIZON_MS); + assert.equal(due({}), true); + assert.equal(due({ outcome_captured_at_ms: judgeFrom - 1 }), true); + assert.equal(due({ outcome_captured_at_ms: judgeFrom }), false); + assert.equal(due({ outcome_captured_at_ms: null }), false, 'not captured'); + assert.equal(due({}, ISSUED + HORIZON_MS), true); + assert.equal(due({}, ISSUED + HORIZON_MS + 1), false); + assert.equal(due({ actual_pv_basis: '1:C,2:C,3:C' }), false, 'no P slot: never pending'); + assert.equal(due({ actual_pv_basis: null }), false, 'no sources recorded'); + assert.equal(due({ shadow_window_pv_kwh: 0 }), false, 'a figure, zero included'); + assert.equal(due({ shadow_cost_window_start_ms: null }), false, 'no window'); + assert.equal(shadowPanelPvRemeasureDue(row, null, ADMIT_ALL, NOW, HORIZON_MS), false, 'the Cores\' band'); + assert.equal(shadowPanelPvRemeasureDue(row, D_PREV, ADMIT_ALL, NOW, HORIZON_MS), false, 'another evening\'s band'); +}); + +test('the sweep on a mixed row: the panel for P slots and the slot\'s connected Core for its C slot; NULL with that Core off the panel', () => { + const MIXED: Basis = { pv_basis: 'mixed', pv_basis_slots: '1:P,2:P,3:C' }; + const t: Telemetry = { cores: [3], panelOverride: [['src1_pv_w', (ts) => (ts < ISSUED + 40 * FIVE_MIN ? null : W.p1)]] }; + const { first, row } = captured({ basis: MIXED, ...t }); + assert.equal(first.row.actual_pv_kwh, null); + assert.equal(first.row.actual_pv_basis, '1:P,2:P,3:C'); + bootMemo = new Set(); + assert.deepEqual(sweepOnce([row], { ...t, admission: ADMIT_ALL }).writes, + [{ day: D, cols: { shadow_window_pv_kwh: r2(kwhOver(W.p1 + W.p2 + W.c3, SHADOW_START, SHADOW_END)) } }]); + bootMemo = new Set(); + const off = sweepOnce([row], { ...t, connected: { 3: false }, admission: ADMIT_ALL }); + assert.deepEqual(off.writes, []); + assert.deepEqual(off.logs, [{ level: 'debug', text: `night-charge ledger: shadow_window_pv_kwh for ${D} stays NULL (actual_pv_basis 1:P,2:P,3:C) — slot 3's Core is not connected` }]); +});