diff --git a/docs/superpowers/plans/2026-11-03-sfm-phase5-settings.md b/docs/superpowers/plans/2026-11-03-sfm-phase5-settings.md new file mode 100644 index 0000000..c1a0066 --- /dev/null +++ b/docs/superpowers/plans/2026-11-03-sfm-phase5-settings.md @@ -0,0 +1,519 @@ +# Phase 5: Changing a Unit's Settings by Serial — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** An operator edits a unit's live settings in SFM, by serial, on either series: preview old → new, send once (audited), and see what the unit now holds. + +**Architecture:** +- **One pure settings codec for both series** (`micromate/setup_fields.py`), on the measured shared 2,090-byte layout. +- **Each series' adapter supplies reads, the plan and the send** to the existing `run_change` core, unchanged. + - Its "state" is a read-back verdict: `as asked` / `unchanged` / `differs`. + - Series 3 sends through `push_config_raw`; Series 4 through `plan_setup_push`. + - Series 4 also reads the unit's schedule, read-only, to refuse a change that a scheduled start would undo. +- **One audited route**, `POST /device/settings/change`. The legacy by-host write is retired. + +**Tech Stack:** Python 3 (FastAPI, pytest), vanilla JS tested in Node (`tests/test_webapp_device_routing.py`). + +**Spec:** `docs/superpowers/specs/2026-11-03-sfm-phase5-settings-design.md` (approved by Brian 2026-11-03). Parent spec: `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md`. + +## Global Constraints + +- **Worktree and branch:** work in `~/seismo-relay-parity` on `feat/series4-sfm-parity`. Check `git branch --show-current` before every commit; never commit to `main`; push every commit. +- **Python:** `/home/serversdown/seismo-relay/.venv/bin/python -m pytest …` from the worktree root. +- **The suite has 16 known failures.** + - Run the full suite once before Task 1 and save the failure list in the plan workspace as `baseline-failures.txt`. + - Before every commit, run the suite, read the failure list, and confirm it equals the baseline. + - Commit in a separate call, never chained to the test run. +- **No live device traffic** in any task. The bench is after the final review, with Brian's explicit go per send. + - Never port 8200. + - Never write modem baud or modem type. + - Never send `0xA2`. +- **`CHANGELOG.md` is not touched** on this branch; it is written on `dev` at the merge. +- **No inline JavaScript.** New page logic goes in `sfm/static/device_routing.js` (DOM-free, Node-tested); glue goes in `sfm/static/sfm_webapp.js`. +- **`docs/instantel_protocol_reference.md` is CRLF.** Edit it only with the Edit tool. Keep its rows in date order. +- **Off-limits (the checker session's files):** `minimateplus/event_file_io.py`, `histogram_codec.py`, `waveform_codec.py`, `bw_xml_report.py`, `decode_check*.py`. +- **`TOOL_VERSION` is unchanged:** nothing here changes event decoding. Operational consequence: none; no migration, no backfill. +- **Grade every protocol claim** in comments and docs as measured or inferred. +- **Mutation checks:** after a mutate/restore, delete the module's `__pycache__/*.pyc` before the confirming run. + +## Review Focus + +1. **A Micromate with no schedule file, or a schedule read that fails.** + - A body with no records means no conflict, and the change proceeds. + - A read that raises refuses the change in plain words. + - Owner: Task 4; tests `test_no_schedule_records_is_no_conflict` and `test_an_unreadable_schedule_refuses`. +2. **A float that is stored as f32.** 0.3 reads back as 0.30000001192. + - The verdict compares bytes with the image written, never floats, so it reads `as asked`. + - Owner: Task 2; test `test_f32_values_read_back_as_asked`. +3. **A stale or foreign revision** after a keypad edit, or a preview of another unit. + - The send is refused with 409, nothing is sent, and no audit row is written. + - Owner: Tasks 4 and 5; tests `test_s4_stale_revision_sends_nothing` and `test_s3_stale_revision_sends_nothing`. +4. **Range and trigger changed in one request.** The trigger is checked against the **new** range. + - Owner: Task 2; test `test_trigger_checked_against_the_new_range`. +5. **Notes at the edges.** + - `""` clears a note. + - 41 bytes is accepted; 42 is refused; non-ASCII is refused. + - Labels are never written. + - Owner: Task 2; tests `test_note_edges` and `test_note_labels_are_never_written`. + +--- + +## File Structure + +| file | responsibility | +|---|---| +| `minimateplus/protocol.py` | **Series 3 assembly:** `assemble_compliance_content`, `is_compliance_content`, `MiniMateProtocol.read_compliance_content`. **Writes:** `push_config_raw`'s pre-check raises `ImageRefused`. | +| `minimateplus/client.py` | **Added:** `read_compliance_content()` and `read_settings_blocks()`. **Deleted:** `apply_config`, `set_project_info`, `_encode_compliance_config`. | +| `micromate/setup_block.py` | **Added:** `with_crc(content)`. | +| `micromate/setup_fields.py` (new) | **The shared, pure settings codec:** field registry, `editable_fields`, `check_changes`, `encode_setup`, `field_values`, `settings_state`, `revision`. | +| `micromate/schedule.py` (new) | **Pure:** `parse_schedule`, `ScheduleEntry`, `schedule_conflicts`. | +| `micromate/protocol.py` | **Added:** `read_file(path)`, using `0x94` then `0x48` pages. | +| `micromate/client.py` | **Added:** `read_schedule()`, `get_active_setup_raw()`, `get_prefs_content()`, `get_trigger_content()`, `get_setup_content()`. | +| `micromate/opcodes.py` | `ENABLEABLE_WRITES` gains the setup-push SUBs. | +| `sfm/device_access/errors.py` | **Added:** `SettingsChanged` and `ChangeRefused`, both 409. | +| `sfm/device_access/change.py` | **Added:** `settings_change()`. | +| `sfm/device_access/s4.py` | `s4_settings` moves onto the codec. **Added:** `s4_change_settings`. | +| `sfm/device_access/s3.py` | `Series3Adapter.settings` moves onto the codec. **Added:** `Series3Adapter.change_settings`. | +| `sfm/device_access/access.py` | **Added:** `DeviceAccess.change_settings`. | +| `sfm/server.py` | **Added:** `POST /device/settings/change`. `/device/config` and `/device/config/project` return 410. | +| `sfm/static/device_routing.js`, `sfm/static/sfm_webapp.js`, `sfm/sfm_webapp.html` | The edit form. | +| `tests/device_access_fakes.py` | The fakes gain settings blocks, a schedule, and writes. | + +--- + +### Task 1: Series 3 — assemble a settings read into the logical block + +**Measured basis (spec, 2026-11-03):** unescape each `1A` data frame and take `data[11:]`. Every frame but the last starts with one non-content `00` byte; drop it. The result is 2,090 bytes with `N = 2090` at `[0:2]`. + +**Files:** +- Modify: `minimateplus/protocol.py`, near `read_compliance_config` (≈ line 913) +- Modify: `minimateplus/client.py` +- Modify: `docs/instantel_protocol_reference.md` (one dated row, 2026-11-03) +- Test: `tests/test_s3_settings_read.py` (new) + +**Interfaces:** +- Produces: + - `assemble_compliance_content(frames: list[bytes]) -> bytes`. `frames` is each data reply's `frame.data`, escapes kept, in order. + - `is_compliance_content(block: bytes) -> bool`: `len == 2090` and `int.from_bytes(block[0:2], "big") == 2090`. + - `COMPLIANCE_CONTENT_LEN = 2090`. + - `MiniMateProtocol.read_compliance_content() -> bytes`: + - sends the same probe and B/C/D requests as `read_compliance_config`; + - a missing data frame raises `ProtocolError` (no `continue`); + - returns the assembled bytes **without** judging them, so a monitoring unit's device-info answer comes back for the caller to recognise. + - `MiniMateClient.read_compliance_content() -> bytes`. + - `MiniMateClient.read_settings_blocks() -> dict` with keys `event_index`, `compliance`, `trigger` and `waveform`. Each value is the bytes its existing read returns: + - `event_index`: `proto.read_event_index()` + - `compliance`: `read_compliance_content()` + - `trigger`: `proto.read_trigger_config()` + - `waveform`: `proto.read_waveform_data_raw()` + +- [ ] **Step 1: Write the failing tests** in `tests/test_s3_settings_read.py`. Use `tests/fixtures/minimate-bench-10-26-26-histogram` (`unit_replies.bin` parsed with `S3FrameParser`). Group the `0xE5` frames into reads: a frame with `len(data) == 11` starts each read. Take the write images from `tests/test_minimate_write_frames.py` (`WRITES[0:13]`, `WRITES[13:26]`; the `0x71` payloads `[16:]` joined). + +```python +def test_reads_assemble_to_2090_bytes(): # all 12 reads, both frame patterns (5 and 3 frames) + assert all(len(assemble_compliance_content(r)) == 2090 for r in READS) + +def test_a_read_after_a_blastware_write_equals_the_write(): + assert assemble_compliance_content(READS[1]) == IMAGES[0][:2090] + assert assemble_compliance_content(READS[2]) == IMAGES[1][:2090] + +def test_a_monitoring_units_answer_is_not_settings(): # READS[3:8] start 0e 'BE9441' + assert [is_compliance_content(assemble_compliance_content(r)) for r in READS[3:8]] == [False] * 5 + assert all(is_compliance_content(assemble_compliance_content(r)) for r in READS[:3] + READS[8:]) + +def test_read_compliance_content_refuses_a_missing_frame(): + ... # a fake transport that answers the probe and frame B, then times out: ProtocolError, nothing assembled +``` + +- [ ] **Step 2: Run them.** `…pytest tests/test_s3_settings_read.py -q`. Expected: FAIL (ImportError: `assemble_compliance_content`). +- [ ] **Step 3: Implement** the Produces block in `protocol.py` and `client.py`. Use `unescape_reply` from `minimateplus.framing`. The docstring cites the measurement and its fixture. +- [ ] **Step 4: Run them.** Expected: PASS (4 passed). +- [ ] **Step 5: Add a reference row** to `docs/instantel_protocol_reference.md` (Edit tool; CRLF), dated 2026-11-03, measured. Cover: + - the assembly rule; + - the round trip (2 of 2); + - `[26:28]`: Blastware writes `00 00` (11 of 11), and the unit sets `01 7f` after monitoring; + - the trailing two bytes: a per-unit Blastware constant (`7c ea` BE11529 ×9, `0c e9` BE9441 ×2), not the CRC, and never in a reply; + - `0x09 [200:202]`: echoed 9 of 9 in April; changed on 10-26 (`17 17` → `78 76`). +- [ ] **Step 6: Run the full suite** and compare the failure list with the baseline. **Then commit** (separate call): `feat(s3): assemble a settings read into the 2,090-byte block`. + +--- + +### Task 2: The shared settings codec + +**Files:** +- Create: `micromate/setup_fields.py` +- Modify: `micromate/setup_block.py`: add `with_crc(content: bytes) -> bytes`, which returns the content with `CRC-16/AUG-CCITT` over `[0:N-2]` written BE at `[N:N+2]`. +- Test: `tests/test_setup_fields.py` (new) + +**Interfaces:** +- Consumes: Task 1's `assemble_compliance_content`, used in tests only. The codec itself imports nothing from `minimateplus` and nothing from `sfm`. +- Produces (all pure). Each `content` is the 2,090-byte (Series 3) or 2,092-byte (Series 4) block. + - `editable_fields(content: bytes, series: int) -> list[dict]`. Each dict has `field`, `label`, `kind` (`"number"`, `"choice"`, `"text"` or `"bool"`) and `value`, plus as relevant `unit`, `min`, `max`, `choices` (a list of `{value, label}`) and `maxlength`. + - `field_values(content: bytes, series: int) -> dict[str, Any]`: the same fields, values only. + - `check_changes(content: bytes, series: int, changes: dict) -> dict`: returns the normalised changes, or raises `SettingsValueError(ValueError)` with a plain sentence. It has two kinds of check: static (names, types, choices, spans) and content-dependent (unit strings, the trigger against the range). + - `encode_setup(content: bytes, series: int, changes: dict) -> bytes`: + - same length as `content`; + - only the changed fields' bytes move; + - bit fields are patched bit by bit; + - Series 3 also sets `[26:28] = 00 00` (`S3_BLASTWARE_FIXED`); + - Series 4 returns `with_crc(...)`. + - `settings_state(before: bytes, written: bytes, now: bytes, *, series: int) -> str`. It compares `[0:2090]`: + - `"as asked"` if `now` equals `written` (Series 4 also needs `crc_ok(now)`); + - else `"unchanged"` if `now` equals `before`; + - else `"differs"`. + - `revision(blocks: list[bytes]) -> str` = `hashlib.sha256(b"".join(blocks)).hexdigest()[:16]`. + - `S3_ALARM_WRITE_MEASURED = False`. While False, `geo_alarm_ips` is shown (read-only, `kind` plus `"readonly": True`) and refused in `check_changes`. + +**The field registry** (content offsets; channel `k` = `1708 + 48·k`, `k` = 0, 1, 2 for the geophones): + +| field | series | bytes | values (exact) | +|---|---|---|---| +| `record_mode` | 3 | `[5]` | `single_shot`=0, `continuous`=1, `histogram`=3, `histogram_continuous`=4 | +| `record_mode` | 4 | `[5]` | `waveform`=1, `manual`=2, `histogram`=3, `combo`=4 | +| `sample_rate` | 3, 4 | `[6:8]` u16 BE | {1024, 2048, 4096} | +| `histogram_interval_s` | 3, 4 | `[8:10]` u16 BE | {2, 5, 15, 60, 300, 900} | +| `record_time_s` | 3, 4 | `[18:22]` f32 BE | 1.0 ≤ v ≤ 20.0 | +| `geo_trigger_ips` | 3, 4 | ch k `+30` f32 BE, all three | 0.005 ≤ v ≤ 0.6, and ≤ the (new) range's full scale (10.0 / 1.25) | +| `geo_range` | 3 | ch k `+29` u8, all three | `normal`=0, `sensitive`=1 | +| `geo_alarm_ips` | 3 (gated) | ch k `+38` f32 BE, all three | 0.005 ≤ v ≤ full scale | +| `job_number` | 3, 4 | `[40:42]` u16 BE | 0 ≤ v ≤ 65535 | +| `job_number_shown` | 3, 4 | `[39]` bit `0x02` | bool | +| `note_1` … `note_4` | 3, 4 | value `[144+64n : 186+64n]`; label `[122+64n : 144+64n]` read only | printable ASCII 0x20–0x7E, ≤ 41 bytes, zero-filled to 42 | + +Where the spans come from, recorded in the module as comments: +- **Trigger and record time:** 75,958 Blastware reports, 2016–2026, scanned 2026-11-03. 7,586 print a trigger: 0.005–0.500 in/s, 20 values, all in/s. 7,631 print a record time: 1.0–10.0 s. +- **The tops of the spans:** BE11529's 2026-04-20 writes and the UM20147 fixtures (trigger 0.6, record time 11), and BE9441's 10-26 setup (record time 20). +- **Job number:** bounded by its encoding (UM20147 keypad 0 → 1 → 1234). The read-back verifies it. + +**A level write is refused** unless all three geophone channels' unit string, `ch +34:+38` with NULs and `.` stripped, equals `in`. Measured: `in.` and `in` both occur on UM20147. A unit set to Metric is unmeasured. + +- [ ] **Step 1: Write the failing tests** in `tests/test_setup_fields.py`: + +```python +def test_s3_reproduces_every_blastware_write(): + # BE11529's 9 April images (bridges/captures/4-20-26/**/raw_bw_*.bin), in time order (the HHMMSS in + # the name): before = the previous image; the first (151921) uses the assembled 1A read in its own + # raw_s3 capture if that read is whole, else it is skipped (say so in the test). BE9441's 2 images: + # before = the assembled READS[0], then image 1. changes = field_values(after) for every field whose + # value differs. Assert encode_setup(before, 3, changes)[:2090] == after[:2090]. + # The 16:26 write also moves [25] (mic on): include `_sensors_mic` as a test-only patch helper, + # not a registry field. + +def test_s4_fixture_pairs_reproduce(): + # for every ordered pair (a, b) of tests/fixtures/micromate-setup/*.bin whose differing bytes outside + # [2090:2092] all lie inside registry fields: encode_setup(a, 4, {f: field_values(b)[f] for differing f}) == b + +def test_trigger_checked_against_the_new_range(): ... # Series 3: {"geo_range": "sensitive", "geo_trigger_ips": 0.6} passes; a fake full scale below 0.6 refuses +def test_spans_refuse_outside_values(): ... # 0.004 and 0.61 in/s; 0.9 and 20.1 s; sample rate 8192; interval 30 +def test_field_not_offered_for_the_series(): ... # geo_range on series 4 -> SettingsValueError naming the series +def test_alarm_is_read_only_until_measured(): ... # Series 3 geo_alarm_ips -> SettingsValueError while S3_ALARM_WRITE_MEASURED is False +def test_metric_unit_string_refuses_level_writes(): ... # ch +34 = b"mm\x00\x00" -> SettingsValueError; b"in.\x00" and b"in\x00\x00" pass +def test_note_edges(): ... # "" clears; 41 bytes ok; 42 refused; "café" refused +def test_note_labels_are_never_written(): ... # changing note_2 moves only [208:250] +def test_bit_fields_keep_unknown_bits(): ... # [39] = 0x81: job_number_shown True -> 0x83, False -> 0x81 +def test_s3_fixed_bytes(): ... # any S3 encode sets [26:28] = 00 00 +def test_s4_encode_recomputes_the_crc(): ... # crc_ok(encode_setup(fixture, 4, {"job_number": 7})) +def test_f32_values_read_back_as_asked(): ... # written = encode(0.3); settings_state(before, written, written) == "as asked" +def test_settings_state(): ... # "as asked" / "unchanged" / "differs"; S4 with a bad CRC -> "differs" +def test_revision_is_stable_and_content_sensitive(): ... +``` + +- [ ] **Step 2: Run them.** Expected: FAIL (ModuleNotFoundError: `micromate.setup_fields`). +- [ ] **Step 3: Implement** `micromate/setup_fields.py` and `with_crc`. Decode via the registry (not via `decode_setup`, whose notes are keyed by label). Note labels come from the unit and are display only. +- [ ] **Step 4: Run them.** Expected: PASS. Then mutation-check `S3_BLASTWARE_FIXED` (remove it: the Blastware-write test fails), delete the `.pyc`, and restore. +- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(codec): one settings codec for both series, on the shared layout`. + +--- + +### Task 3: Micromate — read the schedule file + +**Measured basis:** reference *The scheduler, and a generic file transfer* and *The schedule record format*. +- `0x94 ` opens a file for read; `offset` = the path's length, and the payload is the path, unpadded. +- `0x48` reads the next page, repeated until an all-zero 11-byte response. +- The file is 260-byte records. `[4]` is the half-hour slot. `[6]` is the action bitmask: 2 start-with-setup, 4 stop, 8 self-check, 16 ACH. `[7]` is the name length; `[8:260]` is the name. + +**Files:** +- Create: `micromate/schedule.py` +- Modify: `micromate/protocol.py` (`read_file`), `micromate/client.py` +- Modify: `docs/micromate_protocol_reference.md`: one line under the scheduler section saying SFM reads it (read-only) from 2026-11-03. +- Test: `tests/test_micromate_schedule.py` (new) + +**Interfaces:** +- Produces: + - `SCHEDULE_PATH = "\\system\\schedule\\schedule.dat"`. + - `MicromateProtocol.read_file(path: str) -> bytes`: the concatenated content of each `0x48` page after the page-0 descriptor, stopping at the all-zero response; at most 64 pages, else `ProtocolError`. + - `MicromateClient.read_schedule() -> bytes`. + - `MicromateClient.get_active_setup_raw() -> str`: the `0x41` name up to its NUL, **not** stripped. + - `MicromateClient.get_prefs_content() -> bytes` (`0x08`), `get_trigger_content() -> bytes` (`0x2E`) and `get_setup_content() -> bytes` (`0x1A`), each `_content(...)` of its read. + - `@dataclass(frozen=True) class ScheduleEntry`: `index: int`, `time: str` (`"HH:MM"`), `day: int`, `action_bits: int`, `actions: tuple[str, ...]`, `setup: str`. + - `parse_schedule(body: bytes) -> list[ScheduleEntry]`: 260-byte records; a record with `[4:8]` all zero and no name ends the list. `actions` names the bits 2/4/8/16 as `start_with_setup`, `stop`, `self_check` and `call_home`; any other bit becomes `unknown(0xNN)`. + - `schedule_conflicts(entries, active_setup: str) -> list[ScheduleEntry]`: start entries whose setup, compared case-insensitively after `strip()`, is not the active setup. + +- [ ] **Step 1: Write the failing tests.** Parse the bodies from `bridges/captures/9-24-26 - micromate2/raw_s3_20260924_191835_read_scheduler.bin` (frames 0–4), and from the two `raw_*_20260925_*` captures, with `MicromateFrameParser`. + +```python +def test_the_read_capture_parses(): # 2 records: start-with-setup 07:30 (40-char name), call_home 19:30 (no name) +def test_the_five_entry_schedule_parses(): # 07:30 start TEST1.mmb, 08:00 stop, 08:30 self_check, 09:00 start test2.mmb, 19:30 call_home +def test_conflicts_are_case_insensitive(): # active "test1.MMB" -> only the test2.mmb start conflicts +def test_no_schedule_records_is_no_conflict(): assert schedule_conflicts(parse_schedule(bytes(524)), "x.mmb") == [] +def test_read_file_sends_the_path_unpadded_and_stops_at_zeros(): ... # a fake protocol: 0x94 offset 0x001D, then 0x48 until all-zero +def test_get_active_setup_raw_keeps_spaces(): ... # " LOC 4 .mmb " survives +``` + +- [ ] **Step 2: Run them.** Expected: FAIL (ModuleNotFoundError: `micromate.schedule`). +- [ ] **Step 3: Implement** the Produces block. `read_file` builds `0x94` with `build_request(0x94, len(path), bytes(10), path.encode("ascii"))`. Both SUBs are already in `READ_SUBS`. +- [ ] **Step 4: Run them.** Expected: PASS. +- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(micromate): read the schedule file (read-only)`. + +--- + +### Task 4: Change-path pieces and the Series 4 settings change + +**Files:** +- Modify: `sfm/device_access/errors.py`, `sfm/device_access/change.py`, `micromate/opcodes.py`, `sfm/device_access/s4.py`, `tests/device_access_fakes.py` +- Modify: `tests/test_micromate_execute.py`, `tests/test_micromate_opcodes.py`. Their over-ceiling example `0x71` becomes enableable here; use `0xA8` (delete one event) instead. +- Test: `tests/test_device_access_s4_settings.py` (new) + +**Interfaces:** +- Consumes: + - Task 2: `editable_fields`, `field_values`, `check_changes`, `encode_setup`, `settings_state`, `revision`. + - Task 3: `read_schedule`, `parse_schedule`, `schedule_conflicts`, `get_active_setup_raw`, and the content getters. + - `micromate.writes.plan_setup_push(prefs, trigger, setup, name)`. +- Produces: + - `class SettingsChanged(DeviceError)`, `http_status = 409`. + - `class ChangeRefused(DeviceError)`, `http_status = 409`. + - `settings_change() -> ChangeKind("change settings", "as asked", "applied")`. + - `ENABLEABLE_WRITES = frozenset({0x96, 0x97, 0x7E, 0x7F, 0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72})`. + - `s4_settings(client, serial) -> UnitSettings`. It keeps every current field, plus `detail["editable"] = editable_fields(setup, 4)`. The revision comes only from a preview (dry run), never from this read. + - `s4_change_settings(client, serial, *, changes: dict, revision: Optional[str], dry_run: bool, audit, address, caller, sleep, verify_timeout_s, verify_interval_s) -> ChangeResult`. + +**`s4_change_settings` behaviour**, through `run_change` (`even_if_already=False`): + +- **`read_state`, first call:** + - Read the run state. + - `calling_home` and `unknown*` are returned as they are. + - `monitoring` raises `UnitStateUnknown(f"{serial} is monitoring -- stop it first (a stop makes it call in if call-home is on) -- nothing sent")`. + - Read the name (raw), prefs, trigger and setup. + - `check_changes` (a `SettingsValueError` becomes `BadRequest`). + - When live, `revision([name.encode("ascii"), prefs, trigger, setup])` must equal the request's. Otherwise raise `SettingsChanged("the unit's settings changed since the preview -- preview again; nothing sent")`. + - `image = encode_setup(setup, 4, changes)`. + - Read the schedule; a read error is kept as a blocking reason. + - Return `settings_state(setup, image, setup, series=4)`. +- **Later calls:** read the setup and return `settings_state(before, image, now, series=4)`. +- **`describe_plan`:** + - `plan_setup_push(prefs, trigger, image, name).describe()`, plus `fields` = `{f: {label, old, new}}` for the changed fields, `revision`, `warnings` and `blocked`. + - `warnings` always includes: "this reads the unit's keypad edit buffer: if someone is in its menu, their unsaved edits are sent too". + - `blocked`: + - the name is `factory.MMB` (case-insensitive): "this unit is running its factory setup; load any other setup on its keypad, then try again"; + - each schedule conflict: "this unit's schedule loads at , which would replace this change"; + - a schedule read error: "could not read this unit's schedule () -- SFM will not change a unit whose schedule it cannot check"; + - `plan_setup_push` raising `ValueError` (a block size or header THOR's offsets were never seen at, or a failed checksum): "this unit's -- SFM has not seen a block like it". + - When `blocked` is non-empty, `steps` is `[]`, and a live call raises `ChangeRefused("; ".join(blocked) + " -- nothing sent")`. + - When the schedule names the active setup, `warnings` adds: "the unit's schedule loads this setup at ; the change survives it". +- **`send`:** `client.protocol.execute(plan)`, as `s4_change_call_home` does. +- **`snapshot`:** + - `fields`: `{f: {label, old, new, now}}`; + - `before` / `after` hex of the setup; + - `changed_offsets`; + - `prefs` and `trigger`: before hex only. +- **`is_refusal`**, **`is_ring`** and **`pre_send`**: as in `s4_change_call_home`. + +**Validation order:** a live call without `revision` is refused before any I/O, in Task 6's `DeviceAccess` (not here). + +- [ ] **Step 1: Write the failing tests.** Extend `FakeMicromateClient` with: + - `setup` (default: `tests/fixtures/micromate-setup/um20147_baseline.bin`'s last 2,092 bytes); + - `prefs`, `trigger` and `active_name` (default `"test2.mmb"`); + - `schedule_body` (default `bytes(524)`) and `schedule_error`; + - `execute` applies a setup-push plan's `0x71` data to `self.setup` (re-adding the CRC with `with_crc`), so a read-back sees it. + +```python +def test_s4_dry_run_previews_old_to_new_and_sends_nothing(): # fields == {"geo_trigger_ips": {"label": ..., "old": 0.5, "new": 0.3}}; revision present; fake.executed == [] +def test_s4_trigger_change_sends_the_push_and_verifies(): # subs [0xDA,0x68,0x73,0x82,0x83,0x71,0x72]; outcome sent/ok; state_after "as asked" +def test_s4_stale_revision_sends_nothing(): # SettingsChanged; fake.executed == []; audit has no rows +def test_s4_already_as_asked_is_skipped(): # outcome skipped, nothing executed +def test_s4_monitoring_is_refused(dry_run in (True, False)): # "stop it first" and "nothing sent" +def test_s4_factory_setup_is_refused_live_and_shown_in_preview(): +def test_s4_schedule_conflict_blocks(): # schedule starts "other.mmb" at 07:00 -> ChangeRefused naming other.mmb and 07:00 +def test_s4_schedule_on_the_active_setup_warns_only(): +def test_an_unreadable_schedule_refuses(): +def test_no_schedule_records_is_no_conflict(): # bytes(524) -> sent +def test_s4_a_lost_ack_records_what_the_unit_holds(): # execute_error -> outcome failed, sent True, snapshot present +def test_s4_unseen_block_size_is_blocked(): # prefs 91 B -> preview blocked; live ChangeRefused; nothing executed +def test_setup_push_subs_are_now_enableable(): +``` + +- [ ] **Step 2: Run them.** Expected: FAIL (ImportError: `s4_change_settings`). +- [ ] **Step 3: Implement** the Produces block and update `s4_settings`. In the two opcode tests, swap the over-ceiling example to `0xA8`. +- [ ] **Step 4: Run them**, plus `tests/test_micromate_execute.py`, `tests/test_micromate_opcodes.py`, `tests/test_micromate_writes.py` (THOR's setup-push frames still reproduce) and `tests/test_device_access_s4_call_home.py`. Expected: PASS. +- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(s4): change a Micromate's settings by serial, audited, schedule-checked`. + +--- + +### Task 5: The Series 3 settings change + +**Files:** +- Modify: `sfm/device_access/s3.py`, `minimateplus/client.py` (`push_config_raw` pre-check), `tests/device_access_fakes.py` +- Test: `tests/test_device_access_s3_settings.py` (new) + +**Interfaces:** +- Consumes: + - Task 1: `read_compliance_content`, `read_settings_blocks`, `is_compliance_content`. + - Task 2: the codec. + - Task 4: `settings_change`, `SettingsChanged`, `ChangeRefused`. + - `MiniMateClient.push_config_raw(event_index, compliance, trigger, waveform)`. +- Produces: + - `push_config_raw` raises `ImageRefused` (from `minimateplus.protocol`) when its pre-check refuses a block, before any frame. + - `Series3Adapter.settings(address, serial) -> UnitSettings`. It is built on `read_compliance_content` and the codec, with the same top-level fields as today, plus `detail["editable"]`. A non-settings answer raises `UnitStateUnknown(S3_SETTINGS_WHILE_MONITORING)`. + - `S3_SETTINGS_WHILE_MONITORING = "did not return its settings -- a MiniMate answers this way while monitoring; stop monitoring first"`. + - `Series3Adapter.change_settings(address, serial, *, changes, revision, dry_run, audit, caller, sleep, verify_timeout_s, verify_interval_s) -> ChangeResult`, through `run_change` and `self._run(address, op, retry=False)`: + - `read_serial`: `client.connect().serial`. + - **`read_state`, first call:** + - Wake, then `read_settings_blocks()`. + - A non-settings `compliance` raises `UnitStateUnknown(f"{serial} {S3_SETTINGS_WHILE_MONITORING} -- nothing sent")`. + - `check_changes`, and the live revision check over `[event_index, compliance, trigger, waveform]`. + - Compute `image = encode_setup(...)` and return `settings_state(...)`. + - **Later calls:** wake, `read_compliance_content()`, then the verdict. + - **`describe_plan`:** + - `steps` in Blastware's order: 68 (event index, as read), 73, 71 (settings block, 2,092 B), 72, 82 (trigger, as read), 83, 69 (waveform data, as read), 74, 72. Each step has `sub`, `what` and `data_len`. + - `fields`, `revision` and `warnings` as Series 4. The warning: "the two bytes after the settings block go out as 00 00 (Blastware sends its own constant; effect unmeasured)". + - **`send`:** `client.push_config_raw(event_index, image, trigger, waveform)`. + - **`is_refusal`:** `isinstance(e, ImageRefused)`. + - **`snapshot`:** as Series 4, without prefs and trigger. + +- [ ] **Step 1: Write the failing tests.** Extend `FakeMiniMateClient` with: + - `settings_blocks`: the default compliance is BE9441's assembled 10-26 read 2; `event_index`, `trigger` and `waveform` are the `0x68`, `0x82` and `0x69` payloads (`[16:]`) of `WRITES[13:26]` in `tests/test_minimate_write_frames.py`, each minus its two trailing bytes (a write is the read plus two); + - `push_config_raw` records its four arguments and makes the compliance the new `read_compliance_content`; + - `monitoring_settings=True` returns a device-info-shaped block. + +```python +def test_s3_settings_read_uses_the_codec(): # editable includes geo_range; record_mode "histogram"; notes by slot with unit labels +def test_s3_dry_run_previews_and_sends_nothing(): +def test_s3_trigger_change_sends_the_units_own_blocks(): # push args: event_index/trigger/waveform == the read blocks; compliance == encode_setup(...) +def test_s3_change_verifies_by_read_back(): # outcome sent/ok, state_after "as asked", snapshot fields old/new/now +def test_s3_stale_revision_sends_nothing(): +def test_s3_monitoring_is_refused(dry_run in (True, False)): +def test_s3_a_refused_image_is_audited_as_nothing_sent(): # push_config_raw raises ImageRefused -> row sent 0, "refused before sending" +def test_push_config_raw_precheck_raises_image_refused(): # a 2,089-byte compliance block -> ImageRefused, no frame written +``` + +- [ ] **Step 2: Run them.** Expected: FAIL (AttributeError: `change_settings`). +- [ ] **Step 3: Implement** the Produces block. +- [ ] **Step 4: Run them**, plus `tests/test_s3_call_home.py`, `tests/test_minimate_write_frames.py` and `tests/test_device_access_*`. Expected: PASS, except the tests Task 6 deletes or rewrites. If one fails here only because it pins `apply_config`, leave it for Task 6 and note that in the ledger. +- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(s3): change a MiniMate's settings by serial on the shared codec`. + +--- + +### Task 6: Device access, the route, and retiring the legacy write + +**Files:** +- Modify: `sfm/device_access/access.py`, `sfm/server.py`, `minimateplus/client.py` +- Delete: `poc_set_project.py`. Remove `exp_compliance_only` (and its registration) from `experiments.py`. + - **Ruling (spec: "the legacy write is retired"):** both write a live unit through the retired encoder, which #46 found wrong. Git keeps them. +- Modify tests: + - `tests/test_s3_compliance_anchor_fields.py`: remove its write-side tests (the encoder is gone). + - `tests/test_minimate_write_frames.py`: `test_apply_config_writes_the_units_own_trigger_block` moves to Task 5's `test_s3_trigger_change_sends_the_units_own_blocks`; delete it here. + - `tests/test_server_series3_guard.py`: drop `apply_config` from `WRITES` and its fake method. + - `tests/test_server_device_access.py`: `/device/config` now 410. +- Test: `tests/test_device_access_settings.py` (new), `tests/test_server_settings_change.py` (new) + +**Interfaces:** +- Consumes: Task 4's `s4_change_settings` and Task 5's `Series3Adapter.change_settings`. +- Produces: + - `DeviceAccess.change_settings(address, serial, *, changes: dict, revision: Optional[str], dry_run: bool = False, caller: str = "api") -> ChangeResult`: + - `normalise_serial`, then `series_for_serial`; + - `changes` must be a non-empty dict, else `BadRequest`; + - a live call without `revision` raises `BadRequest("preview first: a live change needs the revision from its preview -- nothing sent")`; + - a live call with no audit log raises `NotSupported` (as `set_call_home`); + - `_dispatch(..., change=True)` with `verify_timeout_s=_SETTINGS_VERIFY_TIMEOUT_S = 2.0` and `verify_interval_s=_SETTINGS_VERIFY_INTERVAL_S = 1.0`. + - `POST /device/settings/change`: + - query: `serial` (required), `host`, `tcp_port`, `port`, `baud`, `dry_run`, `caller`; + - JSON body `{"changes": {...}, "revision": "..."}`; + - returns `_change_response(...)`; + - added to `_SERIAL_AWARE_PATHS`. + - `POST /device/config` and `POST /device/config/project` return **410** with `{"detail": "retired: change a unit's settings by serial with POST /device/settings/change (audited, previewed, read back)"}`. Remove the cache-dirty hooks that only these routes called; keep the read routes. + - Delete `MiniMateClient.apply_config`, `set_project_info` and `_encode_compliance_config`, and any import left orphaned. + +- [ ] **Step 1: Write the failing tests:** + +```python +def test_live_change_without_revision_is_refused_before_io(): # factory never called +def test_empty_changes_is_a_bad_request(): +def test_change_settings_dispatches_by_series_with_change_true(): +def test_route_dry_run_returns_fields_and_revision(): # 200, body.plan.fields, body.plan.revision +def test_route_verified_change_is_200_and_mismatch_409(): +def test_route_unconfirmed_carries_sent_and_audit_id(): +def test_route_refusal_is_409_with_reason(): # ChangeRefused / SettingsChanged / monitoring +def test_legacy_config_routes_are_gone(): # both 410, nothing reaches a client factory +def test_settings_change_is_serial_aware(): # in _SERIAL_AWARE_PATHS; a UM serial goes to the Series-4 path +``` + +- [ ] **Step 2: Run them.** Expected: FAIL (404 / AttributeError). +- [ ] **Step 3: Implement** the Produces block, the deletions, and the test updates listed under Files. +- [ ] **Step 4: Run them**, plus `tests/test_server_*.py`. Expected: PASS. Check that `grep -rn "apply_config\|set_project_info\|_encode_compliance_config" --include=*.py .` finds only comments and history. +- [ ] **Step 5: Run the full suite** and compare with the baseline. **Commit:** `feat(sfm): POST /device/settings/change; retire the legacy config write`. + +--- + +### Task 7: The page — edit, preview, send, "the unit now holds" + +**Files:** +- Modify: `sfm/static/device_routing.js`, `sfm/static/sfm_webapp.js`, `sfm/sfm_webapp.html` +- Modify: `CLAUDE.md` (the "Where things stand" Series-4 parity line: phase 5 built, bench pending), and the spec's status line ("Built 2026-11-xx; bench pending"). +- Test: `tests/test_webapp_device_routing.py` (extend `EXPORTS` and cases), `tests/test_webapp_static.py` + +**Interfaces:** +- Consumes: `UnitSettings.detail.editable` / `.revision`, and the `ChangeResult` shapes from Tasks 4–6. +- Produces (DOM-free, in `device_routing.js`): + - `DEVICE_ROUTES.settings_change = ['POST', '/device/settings/change', true]`; remove `config_write`. + - `controlsFor(unit)`: `configWrite: serialMode && (series === 3 || series === 4)`; `reasons.configWrite: 'By serial only: Preview, then Send (audited).'` + - `settingsFormFields(st) -> Array<{field, label, kind, value, unit?, min?, max?, choices?, maxlength?, readonly?}>`: from `st.detail.editable`, in that order. + - `settingsChanges(fields, edited) -> object`: only fields whose edited value differs. Numbers compare as numbers; read-only fields are ignored. + - `settingsPreviewRows(body) -> Array<[label, old, new]>`, from `body.plan.fields`. + - `settingsBlockedText(body) -> string`: `body.plan.blocked` joined; `''` if none. + - `settingsResultRows(body) -> Array<[label, old, new, now]>`, from `body.detail.snapshot.fields`. +- **Page behaviour** (`sfm_webapp.js` glue; HTML ids `cfg-edit`, `cfg-preview-btn`, `cfg-send-btn`, `cfg-preview`, `cfg-result`): + - The serial-mode Config pane heading reads **"On the unit — read "**. + - The form is built from `settingsFormFields`. + - **Preview** POSTs a dry run and shows old → new, warnings and blocked reasons. It keeps `revision` and enables **Send** only when nothing is blocked and something changes. + - **Send** asks `confirm()` naming the serial and the fields, then POSTs live with the kept revision and shows "the unit now holds" rows. Errors go through `changeErrorText`. + - Editing any field after a preview disables **Send** until the next preview. + - The by-host legacy form loses its write button. Its read stays. + - No inline script; listeners via `addEventListener`. + +- [ ] **Step 1: Write the failing Node-run cases** in `tests/test_webapp_device_routing.py`: + - `controlsFor` gives `configWrite` true by serial for both series, and false by host; + - `settingsChanges` returns only differing fields and compares `0.30` with `0.3` as equal; + - `settingsPreviewRows` / `settingsResultRows` / `settingsBlockedText` on bodies shaped as Task 6 returns them; + - `deviceUrl('settings_change', unit)` → `/device/settings/change?serial=…`; + - `config_write` is no longer a route. + + In `tests/test_webapp_static.py`, assert the page has no inline `