SAFETY-45: a price-driven charge is SIZED by the capacity guard, not switched by it
checks / unit (pull_request) Successful in 7m42s

With arbitrage armed at the shipped defaults, arbitrage and the capacity-tariff
guard drove each other in a sustained limit cycle. Re-measured on TEST-23 stage
3's closed rig against 478ba93, metrics recomputed rather than taken from the
card: `peak_cap_w` 1500 / 1200 W house -> 28 charge onsets an hour, mean period
131.1 s, the grid swinging -455.5 to +3200.0 W; at the SHIPPED
`peak_cap_w: 3500` with an 1800 W house -> 8/h, with a 3000 W house -> 32/h.
The bite rule is `load + max_w > peak_cap_w`, i.e. any house over 1500 W in the
cheapest quarter. §10.2: "an EMS that oscillates is worse than no EMS, both for
hardware wear and - per §9.1 - for the peak it is trying to avoid." And it was
losing the argument it was having: EVERY billed quarter in the three affected
configurations finished OVER the cap.

⚠️ THE CARD'S STATED MECHANISM IS WRONG AND THE CORRECTION IS ON THE RECORD.
The card, and .cache/s45.md before it, say the loop is the quarter boundary
resetting the projection and arbitrage re-arming at full power. It is not. Of
the 27 gaps between the 28 onsets, 23 are 90-120 s (mean 111.5 s) and lie
ENTIRELY INSIDE one quarter; the four long gaps - 230, 240, 250, 255 s - are
exactly the four that SPAN a boundary, so the boundary LENGTHENS the interval
rather than causing an onset. The real cycle, off the recorded fields: the trade
charges at max_w while `wanted = batt_w + excess` is negative and the guard
files NOTHING; `wanted` crosses zero; the guard engages on a floor of 5.3 W;
that flips `arbitrage.guard_state()`, which cancels the WHOLE trade; the
grid-following loop - which targets grid = 0, not grid = ceiling - takes the
actuator and discharges to +1870 W, exporting 420 W; the projection collapses;
the guard releases; the trade re-arms at max_w. A binary interlock keyed on a
continuous quantity. A fix aimed at the boundary would have removed four of
twenty-eight onsets.

THE FIX IS A SHAPE THIS ADD-ON ALREADY HAD. `control.maintenance_charge_floor()`
caps a MAINTENANCE charge at "the headroom left under the site's cap", because
"a maintenance charge is the only thing this system does that is big enough and
long enough to set that peak". ⚠️ That sentence stopped being true when OPT-04
landed. `peakguard.charge_headroom_w()` publishes the same quantity off the
MEASURED guard rather than off the optional `peak_forecast_entity` - the hole
SAFETY-25 had to close in `shaping_suspended()` - and `arbitrage.decide()` sizes
its BUY leg to it, keyword-only and with no default.

NO NEW ARITHMETIC AND NO NEW CONSTANT. The number is `wanted_w` read in the
other direction: `decide()` already computes the DISCHARGE that lands the
quarter on the ceiling, and a negative one is a permitted CHARGE of `-wanted`.
⚠️ `peakguard.decide()` IS UNCHANGED - sha256(decide) = 200090d0835a3a55, 7252 B
on this branch and on 478ba93 - so 2026-08-20's anti-bang-bang rung is exactly
where it was, and tools/replay_ac3.py reproduces 190/190 guarded quarters, 110
engaged cycles, 5 blind and 878 Wh on both trees.

TWO PROPERTIES MAKE IT SAFE TO HAND A STRATEGY, BOTH SWEPT RATHER THAN ARGUED.
It is INVARIANT IN THE BATTERY - raise the charge by dW, the meter rises by dW,
so `excess` rises by dW while `batt_w` falls by dW and `wanted` does not move:
1350.0 W at every point across batt_w -5000..+2000 W on one banked quarter,
while the `excess` those runs see takes six distinct values. It is feed-forward,
so consuming it adds no feedback path around the plant. And HOLDING IMPLIES ZERO
OR UNKNOWN: across 1080 swept combinations not one ENGAGED decision answers a
positive headroom.

AFTER, same rig, same command. 1500/1200: 28 onsets -> 1, grid swing 3655.5 ->
282.0 W, energy bought 180.0 -> 285.2 Wh (+58%, because a continuous 300 W trade
beats a 2000 W trade cancelled for 57% of the hour), billed quarters
1490/1497/1509 -> 1500.0/1500.0/1500.0. 3500/1800: 8 -> 1, 3511/3536/3559 ->
3500/3500/3500. 3500/3000: 32 -> 1, 3519/3542/3557 -> 3500/3500/3500. The two
shipped-default rows buy 2.2% and 1.6% LESS energy and in exchange the worst
quarter goes from 59 W over the cap to zero - which is the ordering §10.1 asks
for, since the capacity tariff bills the month's single worst quarter.
⚠️ AND THE NEGATIVE CONTROL: at peak_cap_w 5000 with a 1200 W house, where
`load + max_w` never reaches the cap, the two runs are BIT-IDENTICAL.

⚠️ A NEGATIVE `lo` WAS CONSIDERED AND REJECTED, AND THE REASON IS IN THE CODE.
Deleting `decide()`'s `wanted <= 0` gate and filing `lo = wanted` is the tidier
answer arithmetically. It creates a new `lo > hi` CONTRADICTION against
main.py's cheap-window maintenance shaping, which files a NEGATIVE `hi`;
arbiter.py clause 2 has no notion of one limit out-ranking another, so it
resolves to 0 W - the battery PARKED in the quarter that sets the bill - and the
only way to close that suspends the maintenance charge shaping PERMANENTLY on
every site this card is about. A backoff or cooldown in arbitrage was rejected
too: both modules' design notes say no timer is invented, and the trade now
re-arms at `ceiling - load` rather than at max_w, which is what learning from a
refusal means when the refusal is a measurement.

THE REGRESSION IS THE LOOP SETTLING, NOT A UNIT TEST ON decide().
test_arbitrage.py 3c closes the loop over the shipped guard, strategy, arbiter,
control law and QuarterAverager with a modelled plant, and asserts BOTH
directions: unsized it must run away (24 onsets, -414..+3200 W, a quarter over
the cap) and sized it must settle (1 onset, 303 W swing, three quarters at
exactly 1500.0 W). The two runs differ in one argument. A third pair asserts the
card is INERT where the defect is inert.

Evidence: 29/29 green. 14 mutations, every one RED on a named check, no
survivors; two are ZERO BYTES - `min()` -> `max()` on the sizing, and the
sized-trade sentence's two operands transposed - and both are red. M13 reverts
the 2026-08-20 rung and is red on EIGHT named checks in test_peakguard and three
in test_arbitrage. Every revert verified by a tree fingerprint AFTER the revert,
which is how a defect in the battery's own harness was found: two edits to one
file, restored in list order, left the first one on disk (MUTATION.md habit 18).
test_peakguard.py part 1 also gained a None-safe format, because the mutation it
exists to catch made it raise TypeError one line later and ABORT the file -
parts 2-13 were ungraded and M13's recorded coverage was one check instead of
eight.

Not fixed, and named: TEST-23 finding 1's export overshoot at the END of a trade
(356-938 W, ~0.37 x max_w) is a different card; a house whose load ALONE exceeds
the cap still has the trade refused outright and the loop drive to grid = 0
rather than to the ceiling, and no swept pair reaches that regime; the container
leg (hadrive.py) was not re-run because test23s3-addon is deliberately stopped
as a second writer on the setpoint entity.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
This commit is contained in:
glenn schrooyen
2026-09-14 16:10:34 +02:00
co-authored by Claude Opus 5
parent 478ba93710
commit e1b9254626
9 changed files with 1178 additions and 24 deletions
+287 -3
View File
@@ -138,8 +138,8 @@ from app.peakguard import (
BLIND_COVERAGE, BLIND_FROZEN, BLIND_NO_BLOCK, CEILING_CAP,
CEILING_MONTH_PEAK, FLOOR_AT_SOC_FLOOR, FLOOR_SOC_UNREADABLE,
PEAK_OPTION_DEFAULTS, Pack, PeakDecision, binding_soc_floor, blindness,
decide, discharge_permitted, excess_w, pack_floor_pct, pack_permissions,
quarter_ceiling_w, uncovered_s,
charge_headroom_w, decide, discharge_permitted, excess_w, pack_floor_pct,
pack_permissions, quarter_ceiling_w, uncovered_s,
)
from app.validate import validate_startup_config
from app.tariff import (
@@ -379,8 +379,17 @@ check("at the engagement boundary the excess is zero, so the floor is exactly "
released = decide(p_edge, batt_w=BATT_NOW, cap_w=CAP_W, reading=None,
achievable_w=LIVE_MAX_W, max_hold_s=MAX_HOLD_S, soc=SOC_OK, soc_floor=SOC_FLOOR)
would_release_on_excess = excess_w(p_edge, CEIL) <= 0.0
# ⚠️ `floor_w` IS FORMATTED DEFENSIVELY, AND MUTATION.md's OWN LEDGER IS WHY.
# The mutation this check exists for - reverting the `floor > 0` rung to
# `excess > 0` - makes `floor_w` None HERE, so a bare `:.0f` raises TypeError
# and ABORTS THE WHOLE FILE on the line after the check that just went red.
# Parts 2-13 are then ungraded and the recorded coverage of that mutation is
# smaller than the truth: exactly what MAINT-05's `delinquent(...)['b']`
# subscript did to test_delivery.py, and habit 5 ("a check whose failure mode
# is a hang - or a crash - needs a deadline, or a name") in the other costume.
print(f" at the boundary: excess {e_edge:.3f} W (an `excess > 0` test would "
f"RELEASE: {would_release_on_excess}), floor {released.floor_w:.0f} W "
f"RELEASE: {would_release_on_excess}), floor "
f"{'(none)' if released.floor_w is None else f'{released.floor_w:.0f} W'} "
f"(the shipped `floor > 0` test holds: {released.engaged})")
check("...and the claim is held there, not released. `excess` falls to zero as "
"soon as the battery is already taking the watts, so thresholding IT is "
@@ -5947,6 +5956,281 @@ check("...and the row is green and un-warned, which is what makes the "
"operator scrolls past", _rows38[0]["ok"] and not _rows38[0]["warn"]
and _S38_CEIL_W - _S38_PROJ.projected_w == 2713.0)
# ==============================================================================
print()
print("13. SAFETY-45 - charge_headroom_w(): the number decide() used to throw "
"away")
# ---------------------------------------------------------------------------
# `decide()` computes `wanted = batt_w + excess` - the DISCHARGE that lands the
# quarter exactly on the ceiling - and returns `engaged=False, floor_w=None`
# the moment that number is not positive. A negative `wanted` is not "nothing
# to say": it is a permitted CHARGE of `-wanted` W, and discarding it is what
# let an arbitrage charge sit at max_w against a quarter it was blowing.
#
# ⚠️ NOTHING IN decide() CHANGES IN THIS CARD, AND THAT IS THE POINT. The
# `wanted <= 0` branch is 2026-08-20's anti-bang-bang rung and part 6's replay
# is what proves it still holds; this part grades a PURE READ of the number it
# already carried. 13g asserts the branch is still there rather than trusting
# the diff.
# ---------------------------------------------------------------------------
def _proj_at(net_w, elapsed):
return PeakTracker.project(averager_at(net_w, elapsed),
B + timedelta(seconds=elapsed))
def _decide_on(projection, *, batt_w, soc=SOC_OK, cap_w=CAP_W,
achievable_w=LIVE_MAX_W, reading=None, frozen=False):
return decide(projection, batt_w=batt_w, cap_w=cap_w, reading=reading,
achievable_w=achievable_w, soc=soc, soc_floor=SOC_FLOOR,
max_hold_s=MAX_HOLD_S, frozen=frozen)
def _decide_at(net_w, elapsed, **kw):
return _decide_on(_proj_at(net_w, elapsed), **kw)
def _avg_held(base_w, elapsed, held_w, *, start=B, step=5.0):
"""`elapsed` seconds BANKED at `base_w`, then `held_w` standing at the edge.
⚠️ THE HISTORY AND THE HELD VALUE ARE SEPARATE FIXTURE AXES, and 13c is why
this helper exists rather than `averager_at(load - batt, ...)`. The averager
credits a sample from its own timestamp to the NEXT one, so the last sample
contributes ZERO accumulated seconds and only becomes `held`. That is the
real shape of a battery whose command changed a moment ago - the quarter's
banked seconds do not retroactively change - and a fixture that moved the
whole history with it would be grading a different quarter each time.
"""
a = QuarterAverager(phases=1, max_hold_s=MAX_HOLD_S)
t = 0.0
while t < elapsed:
a.add(sample(start + timedelta(seconds=t), base_w))
t += step
a.add(sample(start + timedelta(seconds=elapsed), held_w))
return a
# --- 13a. the number, and it is DERIVED rather than read back ---------------
# The house is flat at 2600 W under a 3500 W cap, the battery is idle, and 300 s
# of the block are banked. 600 s remain, so the block can still absorb
# 900 W x 900/600 = 1350 W of extra offtake and finish exactly on the ceiling.
_H45_GAP = 900.0
_H45_LOAD = CAP_W - _H45_GAP
_H45_EL, _H45_REM = 300.0, QUARTER_S - 300.0
_h45_idle = _decide_at(_H45_LOAD, _H45_EL, batt_w=0.0)
_h45_head = charge_headroom_w(_h45_idle)
# The CONSEQUENCE, computed from the fixture's own literals and not from the
# module's arithmetic: hold that charge for the rest of the block and the
# BILLED AVERAGE is the ceiling. This is the meaning of the number, which is a
# different statement from the expression that produces it (habit 2).
_H45_FINAL = (_H45_LOAD * _H45_EL
+ (_H45_LOAD + _h45_head) * _H45_REM) / QUARTER_S
print(f" house {_H45_LOAD:.0f} W under a {CAP_W:.0f} W cap, battery 0 W, "
f"{_H45_EL:.0f} s banked: engaged={_h45_idle.engaged}, "
f"wanted={_h45_idle.wanted_w:+.0f} W, headroom={_h45_head:.0f} W")
print(f" holding that charge for the remaining {_H45_REM:.0f} s bills the "
f"block at {_H45_FINAL:.1f} W against a {CAP_W:.0f} W ceiling")
check("the guard files NOTHING here - this is the shipped `wanted <= 0` branch, "
"untouched, and the state SAFETY-45 is about",
not _h45_idle.engaged and _h45_idle.floor_w is None
and _h45_idle.wanted_w is not None and _h45_idle.wanted_w < 0.0)
check(f"...and yet the quarter can afford {_h45_head:.0f} W of charging, which "
f"is the number that was being discarded. Graded by its CONSEQUENCE - "
f"the block lands on the ceiling to the watt - rather than by "
f"re-deriving -wanted_w with the module's own formula",
near(_H45_FINAL, CAP_W, 0.5))
check(f"...and it is none of the other numbers this fixture has: not the cap "
f"({CAP_W:.0f}), not max_w ({LIVE_MAX_W:.0f}), not the house "
f"({_H45_LOAD:.0f}) and not the raw gap under the ceiling "
f"({_H45_GAP:.0f}) - the 900/remaining gain is 1.5 here and a check that "
f"could not tell those apart would be decoration",
not any(near(_h45_head, v, 1.0)
for v in (CAP_W, LIVE_MAX_W, _H45_LOAD, _H45_GAP)))
# --- 13a2. AND THE IDENTITY HOLDS ACROSS THE WHOLE BLOCK --------------------
# ⚠️ THE AMPLIFICATION IS REAL AND IT IS REPORTED WITH ITS SIZE (habit 13).
# 900/remaining reaches 180 in the last five seconds, so the headroom there is
# enormous - and it is bounded in EFFECT, not in magnitude: at every elapsed,
# holding it bills the block at exactly the ceiling.
H45_ID = []
for _el in (0.0, 60.0, 300.0, 600.0, 870.0, 895.0):
_rem = QUARTER_S - _el
_hd = charge_headroom_w(_decide_at(_H45_LOAD, _el, batt_w=0.0))
H45_ID.append((_el, _hd,
(_H45_LOAD * _el + (_H45_LOAD + _hd) * _rem) / QUARTER_S))
print(" headroom across the block (elapsed, headroom W, billed W): "
+ ", ".join(f"({a:.0f}, {b:.0f}, {c:.1f})" for a, b, c in H45_ID))
check("at EVERY point in the block, holding the headroom for the rest of it "
"bills the block at exactly the ceiling - so the 162 kW answer five "
"seconds from the boundary and the 900 W answer at the top of it are the "
"same statement about the bill",
all(near(c, CAP_W, 0.5) for _, _, c in H45_ID))
check("...and the fixture SPANS the amplification rather than sitting in one "
f"corner of it: the headroom moves by a factor of "
f"{max(b for _, b, _ in H45_ID) / min(b for _, b, _ in H45_ID):.0f} "
f"across those six points",
max(b for _, b, _ in H45_ID) > 100.0 * min(b for _, b, _ in H45_ID))
# --- 13b. HOLDING implies ZERO OR UNKNOWN, swept - the family, not one case -
# ⚠️ THE PROPERTY THAT MAKES THIS SAFE TO HAND A STRATEGY. Every state that
# files a claim has `wanted > 0`, `wanted is None` or `blind`, so this function
# can never hand a caller permission the guard's own `lo` is at that instant
# refusing. Swept over the same grid part 5's no-negative-floor proof uses,
# widened with the two ways a cycle can fail to measure at all.
H45_N = H45_BAD = H45_POS = H45_NONE = H45_ZERO = 0
for _load in (0.0, CAP_W - 500.0, CAP_W, CAP_W + 300.0, CAP_W + 3000.0,
LIVE_MAX_W * 3):
for _el in (30.0, 450.0, 870.0):
for _bw in (-LIVE_MAX_W, -2000.0, 0.0, 400.0, 4000.0, None):
for _sc in (None, BMS_FLOOR, SOC_FLOOR, SOC_FLOOR + 0.5, 100.0):
for _fz in (False, True):
_d45 = _decide_at(_load, _el, batt_w=_bw, soc=_sc,
frozen=_fz)
_hr = charge_headroom_w(_d45)
H45_N += 1
if _hr is None:
H45_NONE += 1
elif _hr > 0.0:
H45_POS += 1
else:
H45_ZERO += 1
if _d45.engaged and _hr not in (None, 0.0):
H45_BAD += 1
print(f" swept {H45_N} (load x elapsed x battery x SoC x frozen) "
f"combinations: {H45_BAD} ENGAGED decisions answering a positive "
f"headroom; {H45_POS} permit charging, {H45_ZERO} answer 0 W, "
f"{H45_NONE} unmeasured")
check(f"NOT ONE of the {H45_N} combinations answers a positive headroom while "
f"the guard is ENGAGED. A decision whose `lo` is at that instant "
f"forbidding charging can never be read as permission to charge",
H45_BAD == 0 and H45_N > 800)
check("...and the sweep is vacuous in no direction: it reaches decisions that "
f"permit charging ({H45_POS}), decisions that permit none ({H45_ZERO}) "
f"and decisions nothing measured ({H45_NONE}), so all three answers are "
f"exercised", H45_POS > 0 and H45_ZERO > 0 and H45_NONE > 0)
# --- 13c. IT IS INVARIANT IN THE BATTERY, WHICH IS WHY SIZING A TRADE TO IT
# CANNOT OSCILLATE -------------------------------------------------
# Raise the charge by dW and the METER rises by dW, so `excess` rises by exactly
# dW while `batt_w` falls by dW: `wanted` does not move. The headroom is a
# FEED-FORWARD number - a function of the house, the ceiling and the seconds
# already banked - so consuming it adds no feedback path around the plant.
# Without this property the whole fix would be one loop replacing another.
H45_INV, H45_EX = [], []
for _bw in (-LIVE_MAX_W, -2000.0, -500.0, 0.0, 500.0, 2000.0):
# ONE banked history, and the battery's change visible only in the HELD
# value - which is what a command given a moment ago actually looks like.
_d = _decide_on(PeakTracker.project(
_avg_held(_H45_LOAD, _H45_EL, _H45_LOAD - _bw),
B + timedelta(seconds=_H45_EL)), batt_w=_bw)
H45_INV.append(charge_headroom_w(_d))
H45_EX.append(round(_d.excess_w, 1))
print(f" same house, same banked quarter, battery {-LIVE_MAX_W:+.0f}.."
f"{2000.0:+.0f} W: headroom {[round(v, 3) for v in H45_INV]}")
print(f" ...while the EXCESS those runs see is {H45_EX}")
check("the headroom does NOT move when the battery moves across the whole "
"range of what it can do - it is a property of the HOUSE and the "
"CEILING, not of what the battery happens to be doing, which is what "
"makes a trade sized from it feed-forward rather than a second loop "
"around the plant",
max(H45_INV) - min(H45_INV) < 1.0)
check(f"...and the fixture SEPARATES it from the two quantities it is built "
f"out of: the battery moved {LIVE_MAX_W + 2000.0:.0f} W and the excess "
f"with it, over {len(set(H45_EX))} distinct values, so an implementation "
f"answering `-batt_w` or `abs(excess)` would give six different answers "
f"here (habit 4)",
len(set(H45_EX)) == len(H45_EX)
and len(set(round(v, 3) for v in H45_INV)) == 1)
# --- 13d. AND A BOUNDARY HANDS IT BACK AT THE AFFORDABLE RATE, NOT AT max_w --
# ⚠️ SAFETY-45's SECOND HALF, AND THE CLAIM IS NOT "IT DOES NOT CHANGE".
# `project()` resets to the held level at `elapsed = 0`, and the headroom
# collapses with it - from 162 kW to 900 W here. What the card is about is WHAT
# IT COLLAPSES TO: the house and the cap, and nothing else. The behaviour being
# removed re-armed at `max_w` regardless of either.
_H45_END = charge_headroom_w(_decide_at(_H45_LOAD, 895.0, batt_w=0.0))
_H45_TOP = charge_headroom_w(_decide_at(_H45_LOAD, 0.0, batt_w=0.0))
print(f" across a boundary, same house: {_H45_END:.0f} W with 5 s of the "
f"old quarter left -> {_H45_TOP:.0f} W with the new one 0 s old, against "
f"a max_w of {LIVE_MAX_W:.0f} W")
check(f"at the top of the new quarter the headroom is exactly the ceiling less "
f"the house ({CAP_W:.0f} - {_H45_LOAD:.0f} = {_H45_GAP:.0f} W). A trade "
f"refused at 14:59 resumes at 15:00 at the rate the new quarter can "
f"afford - the projection resets, this does not reset TO max_w",
near(_H45_TOP, _H45_GAP, 1.0) and _H45_TOP < LIVE_MAX_W)
check("...and the check is not passing because nothing moved: the headroom on "
"the other side of that boundary is two orders of magnitude larger, and "
"the PROJECTION really did reset",
_H45_END > 100.0 * _H45_TOP and _proj_at(_H45_LOAD, 0.0).elapsed_s < 1.0)
# --- 13e. the unmeasured answers, and None is NOT unlimited -----------------
_h45_nobatt = _decide_at(_H45_LOAD, _H45_EL, batt_w=None)
_h45_blind = _decide_at(_H45_LOAD, _H45_EL, batt_w=0.0, frozen=True)
print(f" no battery reading: {charge_headroom_w(_h45_nobatt)}; "
f"BLIND: {charge_headroom_w(_h45_blind)}; no decision at all: "
f"{charge_headroom_w(None)}")
check("a guard that never ran answers None, not a number - `meter_source: off` "
"reaches this with no decision at all and a caller that read it as a "
"large headroom would be guard_state()'s None-is-not-False collapse one "
"layer down", charge_headroom_w(None) is None)
check("...and a cycle with NO BATTERY MEASUREMENT answers None too: there is "
"nothing to size a floor from, so there is nothing to size a trade from "
"either", charge_headroom_w(_h45_nobatt) is None
and _h45_nobatt.wanted_w is None)
check("...and BLIND answers 0.0 - a NUMBER, and the number is no charging. "
"The claim it files already says exactly that at `floor 0 W`, and this "
"agrees with it rather than restating it",
charge_headroom_w(_h45_blind) == 0.0 and _h45_blind.blind
and _h45_blind.floor_w == 0.0)
check("...and the three are TOLD APART: blind is 0.0 and the two unmeasured "
"states are None, so a caller can refuse for the reason that is true "
"rather than for whichever fired first",
charge_headroom_w(_h45_blind) is not None
and charge_headroom_w(_h45_nobatt) is None)
# --- 13f. the SoC floor does not become charging permission -----------------
# ⚠️ THE ONE ENGAGED STATE WHERE THE GUARD IS DELIBERATELY NOT DISCHARGING.
# SAFETY-24's floor-limited decision files `lo = 0.0` - "charging stays
# blocked" - on a quarter that IS over the ceiling. If that read as headroom,
# an empty pack in a blown quarter would be told to buy.
_h45_lim = _decide_at(CAP_W + 2000.0, _H45_EL, batt_w=0.0, soc=SOC_FLOOR - 1.0)
print(f" floor-limited over a blown quarter: engaged={_h45_lim.engaged}, "
f"floor_limited={_h45_lim.floor_limited}, wanted="
f"{_h45_lim.wanted_w:+.0f} W, headroom={charge_headroom_w(_h45_lim)}")
check("a FLOOR-LIMITED decision - the guard wanted a discharge and SoC refused "
"to size it - answers 0.0 headroom. The quarter is over the ceiling; the "
"pack being empty is not a reason to fill it from the grid in it",
_h45_lim.floor_limited and _h45_lim.engaged
and charge_headroom_w(_h45_lim) == 0.0)
# --- 13g. decide() ITSELF IS UNCHANGED, PINNED -----------------------------
# ⚠️ MUTATION.md habit 4, in the direction a diff cannot cover. The whole safety
# argument of this card is "the 2026-08-20 rung is still there and part 6 still
# grades it". That is a claim about the SOURCE, so it is pinned on the source -
# and on the BEHAVIOUR, because a shape pin alone would pass a rung that had
# been inverted.
_H45_SRC = (HERE / "app" / "peakguard.py").read_text(encoding="utf-8")
_H45_TREE = ast.parse(_H45_SRC)
_h45_fn = next(n for n in ast.walk(_H45_TREE)
if isinstance(n, ast.FunctionDef) and n.name == "decide")
_H45_RUNG = [n for n in ast.walk(_h45_fn) if isinstance(n, ast.If)
and ast.unparse(n.test) == "wanted <= 0.0"]
check("the `wanted <= 0.0` rung is still in decide(), spelled exactly that "
"way, on the AST rather than as a substring - it is the rung whose "
"removal put 2026-08-20's quarter 49 W over the limit after seventeen "
"engage/release cycles in 900 s", len(_H45_RUNG) == 1)
check("...and it still DISENGAGES rather than merely reporting: the fixture "
"13a is built on reaches it and files no claim, so the pin above is not "
"grading a rung that has been inverted under it",
peakguard.claim(_h45_idle) is None)
_h45_head_fn = next(n for n in _H45_TREE.body if isinstance(n, ast.FunctionDef)
and n.name == "charge_headroom_w")
check("...and charge_headroom_w() is a PURE READ of the decision - one "
"positional parameter, no projection, no clock and no options - so it "
"cannot become a second answer to the question decide() already answers",
[a.arg for a in _h45_head_fn.args.args] == ["decision"]
and not _h45_head_fn.args.kwonlyargs)
# ==============================================================================
print()
shutil.rmtree(TMP, ignore_errors=True)