Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
cf59160
feat(core,storage): battery contracts per ADR-0013 - None is the base…
claude Oct 24, 2026
65e68d9
feat(safety): battery invariants B1-B6, B9 and the battery watchdog a…
claude Oct 24, 2026
f50f5d8
feat(devices,templates): battery adapters generic, kostal_plenticore …
claude Oct 24, 2026
7ac5831
feat(safety): battery intents through the gate with the ADR-0013 inva…
claude Oct 24, 2026
75e6f8b
feat(controller): translate the plan's battery band into battery inte…
claude Oct 24, 2026
a64f1a5
feat(app,api): battery in the control stack, control state and PUT /a…
claude Oct 25, 2026
85b7c1b
test(sim): hybrid inverter model and the five battery scenarios (WP10)
claude Oct 25, 2026
d916ef5
feat(safety,devices): battery control through the gate with the ADR-0…
claude Oct 25, 2026
4e2b94c
docs: STATUS for PR 4-G WP10 (battery control), UNVERIFIED rows for K…
claude Oct 25, 2026
828d1df
fix(safety,devices): a battery release is complete only when the base…
claude Oct 26, 2026
8a6e414
fix(safety,devices): judge locks on the written state, Kostal §3.5 ba…
claude Oct 26, 2026
5811783
fix(controller,core,sim): fallback_measured is identity, only an OK S…
claude Oct 26, 2026
c37597e
docs: STATUS, plan deviations, architecture and an ADR-0013 implement…
claude Oct 26, 2026
db3635a
fix(safety,devices): never take SunCore's own late or partial battery…
claude Oct 28, 2026
59b8342
docs: STATUS, plan deviations and ADR-0013 addendum for the PR 4-G re…
claude Oct 28, 2026
6cbaa43
fix(safety): write the held battery state again when an older own sta…
claude Oct 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 66 additions & 11 deletions docs/STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
Read this first in every session, then `CLAUDE.md` (once it exists) and the
ADRs relevant to your task. Keep it short; history lives in git.

**Last update:** 2026-10-24 · **Phase:** 4 in progress – PR 4-A contracts, 4-B storage, 4-C
tariffs, 4-D PV forecast, 4-E load forecast and risk model, 4-F planner and runtime (WP8, WP9;
battery control WP10 next); Phase 3 (3-A
**Last update:** 2026-10-25 · **Phase:** 4 in progress – PR 4-A contracts, 4-B storage, 4-C
tariffs, 4-D PV forecast, 4-E load forecast and risk model, 4-F planner and runtime (WP8, WP9),
4-G battery control (WP10; UI and docs 4-H next); Phase 3 (3-A
`phase-3/a-safety`, 3-B `phase-3/b-controller`, 3-C `phase-3/c-ui`) implemented, waiting for the
maintainer's shadow test · **Branch:** `phase-4/f-planner` (stacked on `phase-4/e-load-risk`, merged
with `phase-4/c-tariff`)
maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4/f-planner`)

## Done

Expand Down Expand Up @@ -99,6 +98,57 @@ with `phase-4/c-tariff`)
- Follow-ups: the weights come from the *uncalibrated* sources' MAE (a calibrated source is
under-weighted until a calibrated accuracy is scored); no UI yet (4-H).

- **Phase 4 – PR 4-G (WP10, battery control; branch `phase-4/g-battery`, on 4-F; `control-safety`)**:
- Contracts (ADR-0013): `BatteryAction` = the full desired state, `None` = the adapter's baseline
(`core.battery.resolve_battery_action`), capabilities per field, live `BatteryRanges`, min SoC
rounded **up**; `core.identity.battery_identity(_token)` (asset id `battery`, adapter template,
role entities, the site's SoC/battery power, modbus hub + unit id);
`operation.battery_mode` (additive): a `battery`/`site` put that changes the identity drops it,
an import resets it, a restore keeps it only for the recorded identity, a full `operation` put
cannot raise it, `PUT /api/v1/operation/battery {mode, identity}` (404 observe-only, 409 stale);
`battery.modbus` (hub, unit id, byte order, heartbeat 20 s, fallback timer 60 s) and
`battery.fallback_measured` (additive).
- Adapters `suncore/devices/battery/` (only the gate calls `apply`, `release`, `arm_fallback`,
`keep_alive`; boundary tests): `generic` (number/select/switch roles), `kostal_plenticore`
(`Battery:MinSoc` only, settle 35 s for the silent REST write and the 30 s poll, no charge
set-point), `kostal_modbus` (§3.5 via `modbus.write_register` - a write of this adapter only,
never a read-only action; float32/U32 words in the configured order; refuses unless 1080 = 2;
1284/1286/1288 armed and read back before any limit; heartbeat; release writes the own limits).
Templates `generic.battery`, `kostal.plenticore`, `kostal.plenticore_g3_modbus` (`driver`,
register map, capability `hardware_fallback`; schema v1 additive) with conformance scenarios.
- Safety: the blanket `safety.battery_not_supported` stays only without a battery adapter or for
other asset ids; battery intents pass B1-B9 (`safety/battery.py`, hypothesis property tests),
mode capped at assisted while the hardware fallback is not measured, mandatory read-back, a
lease re-judged every tick by `poll()` (heartbeat only while it holds), override detection,
release check, battery watch (frozen battery power / SoC), every Phase 3 release path. All
Phase 3 safety tests unchanged and green.
- Controller: `controller/battery.py` turns the band of a fresh plan interval into intents
(grid charging, discharge lock as `max_discharge_w` 0 or a min-SoC floor, release), hysteresis,
one intent per minute, `controller.battery.grid_charge_unsupported` for Kostal REST; a held
forced grid charge is never surplus for the devices.
- App: `ControlStack` battery wiring, control state `battery`, devices' reserve guard =
`effective_reserve_pct` with a battery model; OpenAPI and frontend types regenerated, no UI.
- Simulator: `sim/inverter.py` (own control as fallback, BMS drift, REST lag and silent failures,
§3.5 fallback timer, hang); scenarios `modbus_heartbeat_lost`, `battery_reserve_drift`,
`kostal_rest_reserve`, `inverter_hang_battery`, `grid_charge_price_level` (real planner,
controller and gate in automatic mode).
- Decisions and deviations: plan §"Deviations during implementation" (PR 4-G).
- Review fixes (2026-10-26, reviewer blocker B1, M1-M3, minors 1-8): latched battery release
with read-back of the original baseline and back-off retries (also under emergency stop),
B4/B5 on the written state, Kostal §3.5 baseline = own limits and fallback confirmed against
the written values, register 5 role, lease ends on refusal / plan end, arming outside the
lock, user's select/switch restored, `fallback_measured` is identity, OK-only SoC, a more
realistic simulator (REST 30 s, modbus scan lag, stale registers, price jump). ADR-0013 got
an implementation addendum. Re-check fixes (2026-10-28): own late/partial writes are never
taken for user values (`DeviceRuntime.attempted`, per-field rule), user values found during a
release get the override hold, the generic adapter remembers user options only before its
first write attempt.
Approval follow-up: when the read-back shows an older own state instead of the held one,
the gate writes the held state again through the evaluated path (B1-B9, read-back) or
releases if that is refused. For the 4-H user docs: a user value that happens to equal a
value SunCore wrote or attempted while in control is taken for SunCore's and reset to the
baseline at release (accepted by the reviewer).

- **Phase 4 – PR 4-F, part WP8 planner (branch `phase-4/f-planner`, on 4-E merged with 4-C)**:
- `suncore/planner/` (depends on `core` only; boundary test extended; `mypy --strict`):
`inputs.py` (`build_inputs`: pure snapshot on the 15-minute grid now → +48 h from the
Expand Down Expand Up @@ -513,10 +563,12 @@ with `phase-4/c-tariff`)
(WP3) → 4-C tariffs (WP4) and 4-D PV forecast (WP5) → 4-E load + risk (WP6, WP7) → 4-F planner and
runtime (WP8, WP9) → 4-G battery control (WP10) → 4-H frontend + docs (WP11, WP13); 4-I ML load
(WP12, optional, after 4-E). Merge only after the Phase 3 acceptance.
- **ADR-0013 must be accepted before WP10** (4-G). Its contract changes `BatteryBand.grid_charge_max_w`
/ `discharge_lock` landed with WP8 (additive, planner-only, the controller ignores them);
`BatteryAction` `None` = baseline and `battery_identity` land at the start of 4-G.
- **WP9 done** (4-F, see Done); next: 4-G battery control (WP10, ADR-0013 first).
- **WP10 done** (4-G, see Done); next: 4-H UI and docs (battery card with mode, identity and the
assisted cap; wizard step for the battery adapter incl. enabling the Kostal number and the modbus
YAML; WP13 docs). ADR-0013 file still says "proposed" - record the maintainer's acceptance.
- Maintainer questions from 4-G (PR description): grid charging on the Kostal (generic
force-charge entity or a §3.4 ADR); the fallback timer measurement procedure for
`battery.fallback_measured`. Answered: no permanent reserve floor on the inverter.
- **PR 4-C (WP4, branch `phase-4/c-tariff`)**: `suncore/tariff/` - a template-driven price adapter
(`engine.py`: action or attribute source, list or mapping shape, per-MWh conversion, native grid
from `end - start` or the timestamp spacing, 15/60-minute mixes as segments, gaps `None`, DST
Expand Down Expand Up @@ -733,8 +785,11 @@ with `phase-4/c-tariff`)
| Energy-Charts and aWATTar APIs and terms (not shipped in Phase 4) | `research/integrations.md` | session with network access (Phase 6) |
| Open-Meteo azimuth convention in a live response (code: 0 = south, OpenAPI text contradicts); separate terms page (README only) | `research/integrations.md` | live request; maintainer reads the terms page |
| Kostal REST battery/grid power sign; `ActivePowerLimitation` semantics; live entity ids | `research/integrations.md` | maintainer's HA (enable the entities, compare with the inverter display) |
| Kostal Modbus external battery management not enabled on the maintainer's inverter; how it is enabled; §3.5 fallback timer behaviour | `research/kostal-plenticore-modbus.md`, ADR-0013 | maintainer enables it and measures; `kostal_modbus` capped at assisted until then |
| Creating a modbus hub from the HA UI (else YAML) | `research/ha-websocket-api.md` | maintainer's HA |
| Kostal Modbus external battery management not enabled on the maintainer's inverter; how it is enabled; §3.5 fallback timer behaviour (the `kostal_modbus` adapter and its fallback are exercised in the simulator only, scenario `modbus_heartbeat_lost`) | `research/kostal-plenticore-modbus.md`, ADR-0013, `suncore/devices/battery/kostal_modbus.py` | maintainer enables it and measures, then sets `battery.fallback_measured`; capped at assisted until then |
| Kostal Modbus U32 word order of register 1288 assumed equal to the float order (register 5); modbus sensor `scan_interval` vs the adapter's 15 s settle time; how 1076/1078 (the battery's own limits) move with temperature and SoC (the fallback gets max(model, own)) | `suncore/devices/battery/modbus_codec.py`, `templates/battery/kostal.plenticore_g3_modbus.yaml` | first Modbus write on the maintainer's inverter |
| Kostal REST: battery/grid power sign (the site's `invert_sign`), the min-SoC read-back timing after the forced refresh (35 s settle assumed), whether out-of-range values are clamped or rejected; the number is disabled by default | `suncore/devices/battery/kostal_plenticore.py`, `templates/battery/kostal.plenticore.yaml` | maintainer enables "Battery min SoC" and watches the first assisted write |
| Creating a modbus hub from the HA UI (else YAML); the hub name and unit id the user configures | `research/ha-websocket-api.md`, `battery.modbus` | maintainer's HA |
| Generic battery adapter (numbers/select/switch) and the battery watch thresholds (frozen 600 s / 50 W / grid 500 W, SoC frozen after 3 % of the capacity moved) | `suncore/devices/battery/generic.py`, `suncore/safety/battery.py` | first real battery integration; shadow run |
| Supervisor proxy passes `recorder/*` and `energy/*` commands | `research/ha-websocket-api.md` | first Phase 4 run on HA OS |
| Supervisor proxy forwards `recorder/statistics_during_period` (the 4-B rebuild logs a warning and retries) | `suncore/ha/statistics.py` | first run on HA OS |
| `change`/`sum` rows of real energy counters (the rebuild reads them as verified from source, not tested against live counters); `backup_exclude` accepts the glob `timeseries.db.corrupt*` | `suncore/ha/statistics.py`, `addon/*/config.yaml` | maintainer's HA with an energy counter; a backup on HA OS |
Expand Down
9 changes: 9 additions & 0 deletions docs/adr/0011-two-control-layers.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,15 @@ Decision:
ADR-0013 ("Battery as a controlled asset"), which must be accepted before
Phase 4 WP10 lifts the rejection.

Sign-off 2026-10-25 (`control-safety`, PR 4-G, Phase 4 WP10): the blanket rejection of
`BatteryAction` is lifted **only for intents to the configured battery adapter** that pass the
ADR-0013 invariants B1-B9 (`safety/battery.py`, property-tested; gate path
`SafetyGate._submit_battery`, lease in `poll()`; scenarios `modbus_heartbeat_lost`,
`battery_reserve_drift`, `kostal_rest_reserve`, `inverter_hang_battery`,
`grid_charge_price_level`). Without a battery adapter (observe-only, no battery model) or for any
other asset id the gate still answers `safety.battery_not_supported` and writes nothing. The
invariant table is in the PR 4-G description.

Consequence: contracts can be published ahead of their write path without
weakening the single-writer guarantee; a boundary/unit test asserts that
every `ActionKind` is either handled by the invariants or rejected with its
Expand Down
24 changes: 24 additions & 0 deletions docs/adr/0013-battery-as-controlled-asset.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,27 @@ charging is possible on the maintainer's Kostal without §3.4 (see consequences)

Accept as proposed; your input is needed on how grid charging should be executed on your
Kostal in Phase 4 (not at all, a generic force-charge entity, or a later §3.4 ADR).

## Addendum 2026-10-26: implementation notes (Phase 4 WP10, PR 4-G review)

Additive, no decision above changes:

- The battery invariants live in `safety/battery.py` (not `safety/invariants.py`, which stays the
device module); the gate's battery path is `SafetyGate._submit_battery`, the lease
`SafetyGate._battery_lease`.
- B4/B5 are judged on the **resolved state that is written** (and re-sent by the heartbeat), not
on the request: a cap or floor inherited from the baseline counts. Forced grid charging is no
discharge lock (its import is bounded by B2/B5).
- A release is complete only when the read-back shows the original baseline (or the user set a
third value). Until then the runtime keeps the original baseline, nothing else is written and
the release is retried with back-off, also during an emergency stop.
- A field is the user's third value only if it differs from the baseline **and** from every
target SunCore wrote or attempted while under control (`DeviceRuntime.attempted`); a late or
partly applied SunCore write is restored, the user's fields are kept (restore = baseline with
those fields), proven by read-back and held like any override (next 04:00).
- `kostal_modbus`: the baseline (`None` fields, release) is the battery's own limits (1076/1078);
the fallback registers get the larger of the model's and the own limits and are confirmed
against the values written; register 5 must match the configured word order.
- `battery.fallback_measured` is part of the battery identity (it lifts the assisted cap).
- Reserve (maintainer default): SunCore enforces the effective reserve in the plan and the gate
only; the user's own lower inverter floor outside a SunCore lock stays as it is.
21 changes: 21 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,27 @@ applies, settles, reads back and logs `accepted` or `failed`. The write path re-
stop, mode, watchdog and hold right before `apply()` under a per-device lock. The free surplus is
claimed per `GateInputs` snapshot, so several intents of one tick cannot together exceed it.

**The battery** (Phase 4 WP10, ADR-0013) is the asset `battery` with its own path through the
same gate. The controller turns the band of a *fresh* plan interval into a `BatteryAction`
(limits, not set-points; `None` = the adapter's baseline found at takeover): `grid_charge_max_w`
-> `grid_charge_w` where the adapter can force charging, `discharge_lock` -> `max_discharge_w`
= 0 or a min-SoC floor at the live SoC (never below `effective_reserve_pct`), nothing planned ->
`ReleaseAction`. The gate judges it with the battery invariants B1-B9 (`safety/battery.py`):
floor never below the reserve or the user's own floor, grid charging only from a fresh planned
interval inside the grid-charge policy at the **live** price and within battery, adapter, band
and import-headroom bounds, a discharge lock only when planned, the import limit for every
action that can cause import, live ranges and capabilities, write only on change, mandatory
read-back. An adapter with a hardware fallback (Kostal §3.5) gets it armed and read back before
the first limit and is capped at assisted until `battery.fallback_measured`. An accepted state is
a **lease**: `gate.poll()` re-judges it every tick and restores the baseline when the mode, the
watchdog (site or battery scope, `gate.check_battery`: frozen battery power or SoC), stale inputs
or any invariant says so (also when no fresh plan interval covers the held state, or the adapter
refuses); the adapter's heartbeat re-writes only while it holds. A battery release is complete
only when the read-back shows the original baseline; until then the release is retried with
back-off (also during an emergency stop) and nothing else is written. Devices keep the
Phase 3 rule "no SunCore-caused import" unchanged, and the charging power of a forced grid charge
is never surplus for them.

Deviation events: the controller reports when actual SoC, PV or load leave the plan's assumption
corridor; the scheduler then re-plans early (rate limited to once per 5 minutes) from Phase 4 on.

Expand Down
43 changes: 43 additions & 0 deletions docs/plans/phase-4.md
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,49 @@ shadow and assisted run is the acceptance test.
- WP9: the controller applies a plan's battery band only while an interval covers `now`, and judges
`priority_until_soc_pct` against the live SoC.

- PR 4-G (WP10, battery control; `control-safety`):
- **Battery mode** lives in `operation.battery_mode` (additive) instead of a `device_modes`
entry under the reserved id: a device may already be called `battery`, and the gate learns it
through `ModeProvider.battery_mode()`. The identity record is a separate `safety_state` key.
A configured device with the id `battery` keeps the battery observe-only (logged).
- **Heartbeat** is driven by the gate's `poll()` (every tick, timed from the write) and executed
by the adapter's `keep_alive()`, not by a timer task inside the adapter: a hung control loop
stops the heartbeat, so the inverter's own fallback takes over (ADR-0013 5B intent).
- **Discharge lock** is judged by B4 against the deficit *now*; the lease re-judges it every
tick, so a cap that becomes a lock in the evening needs the plan's `discharge_lock` then.
- **Reserve**: SunCore never holds a permanent min-SoC floor; the effective reserve is the floor
of every min SoC it writes, and B1 also forbids writing below the user's own inverter floor.
The devices' reserve guard (`GateInputs.reserve_soc_pct`) is `effective_reserve_pct` when a
battery model exists.
- **Grid charging needs an import limit** (B2: an unknown bound means no grid charging).
- Power caps are never written above the baseline (B6), so SunCore only ever restricts.
- A manual change of the held limits is an override: SunCore lets go without writing and holds
off until the default override time (next day 04:00).
- After a release of an adapter without hardware fallback the gate reads back once after the
settle time; a mismatch pauses battery control (`safety.battery_release_unconfirmed`).
- Templates gained `driver` (`generic`, `kostal_plenticore`, `kostal_modbus`), a Modbus
register map and the capability `hardware_fallback` (additive in schema v1); the adapters read
a core `BatteryAdapterSpec` (`suncore.devices` imports only `core`).
- Kostal Modbus §3.5 runs in the simulator only (external battery management is not enabled on
the maintainer's inverter); it is capped at assisted until `battery.fallback_measured`.
- Review fixes (2026-10-26): a battery release completes only on a read-back of the original
baseline (retried with back-off, latched, never adopted as a new baseline; an adapter release
to an unavailable entity fails instead of succeeding silently); B4/B5 judge the written
state; `kostal_modbus` baseline = own limits, fallback = max(model, own) confirmed against the
written values, register 5 checked; the lease ends on an adapter refusal and when no fresh
plan interval covers the held state; the settle wait after arming runs outside the gate lock
and the invariants are judged again before `apply()`; the generic release restores the user's
own select option / switch state; `fallback_measured` is identity; the controller uses only an
OK SoC; a §3.5 takeover is never skipped because the registers merely show the value.
- Re-check fixes (2026-10-28): a field counts as the user's during a release (and for the
lease's override check) only if it differs from the baseline and from every target SunCore
wrote or attempted while under control (`DeviceRuntime.attempted`); SunCore's own late or
partial values go back to the baseline and are proven by read-back, the user's fields stay
and get the override hold (next 04:00). The generic adapter remembers the user's select /
switch state only before its first write attempt.
- **Answered (maintainer default):** SunCore enforces the effective reserve in plan and gate
only, it holds no permanent min-SoC floor on the inverter.

## 7. Out of scope for Phase 4

Full plan chart with device Gantt, zoom/pan, history, savings vs baselines, what-if and
Expand Down
Loading
Loading