Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
1136 lines
50 KiB
Markdown
1136 lines
50 KiB
Markdown
# Series-4 write path, phase 2: encoder, opcode guard, dry run — 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:** Build every Micromate write a later phase needs as an exact, reviewable **write plan**, proven byte for byte against THOR's captured frames. Make it impossible for any code path to transmit a write opcode, or `0xA2` ever, by accident. Nothing is sent to a unit.
|
||
|
||
**Architecture:**
|
||
- `micromate/framing.py`: `build_request()` gains an optional data section, using the same escape set and SUM8 it already applies.
|
||
- `micromate/opcodes.py` (new): one table of write SUBs and one of cross-series collisions (`0xA2`).
|
||
- **The send-side gate.** `MicromateProtocol._send()` now reads each outgoing frame's SUB. It refuses any write SUB the protocol object was not explicitly allowed, and always refuses a collision. No production caller allows anything in this phase.
|
||
- `micromate/writes.py` (new): pure functions that turn the unit's own reads into a `WritePlan`, i.e. the frames, in order, with expected acks. That plan is what each later write endpoint's `dry_run=true` returns.
|
||
- A bench tool, `bridges/mm_dry_run.py`, does the reads on a live unit and prints the plan, sending nothing else. It is step 1 of the spec's bench protocol for every first live write.
|
||
|
||
**Tech Stack:** Python 3, pytest. `micromate/` codec + protocol (no `sfm` imports).
|
||
|
||
**Spec:** `docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md`. The sections that apply are *The safety layer* (opcode guard), *Series-4 write path* (encoder, dry run, per-operation table, setup-push details), *Testing* (frame reproduction) and *Build phases* item 2.
|
||
|
||
## Global Constraints
|
||
|
||
- **Nothing but reads reaches a unit.** No task may construct `MicromateProtocol` / `MicromateClient` with a non-empty `allowed_writes` outside a test that uses a scripted transport. Task 5 (bench) sends reads only.
|
||
- **`0xA2` is never transmitted on Series 4.** The collision guard refuses it even when "allowed". Lifting that needs a spec change, not a parameter.
|
||
- **A call-home plan changes exactly bit 0 of content byte `[5]`.** Every other byte, including the unit-maintained `[118:120]`, is echoed from the read. Never write modem baud or modem type.
|
||
- **The setup-push read-modify-write sends back only what was read.** No field editing in this phase. Field encoding is phase 5.
|
||
- **Codec purity:** nothing in `micromate/` imports `sfm`. `micromate/` may import `minimateplus.transport` only, as today.
|
||
- **Never move, rename or delete `bridges/captures/`**, even temporarily: it holds irreplaceable research captures. Read it only.
|
||
- **Fixtures:** `tests/fixtures/` and `bridges/captures/` are gitignored. Fixtures cut from captures go in `tests/fixtures/micromate-writes/` and are **force-added** (`git add -f`). Tests that read `bridges/captures/` directly must `skipif` when it is absent.
|
||
- **The suite's 16 pre-existing failures** (test_bw_ascii_report.py 15, test_event_file_io.py 1; missing gitignored fixtures) stay exactly that set.
|
||
- **Branch `feat/series4-sfm-parity`.**
|
||
- Never commit to `main` or `dev`.
|
||
- Do not edit `CHANGELOG.md`.
|
||
- After each commit, run `git push`.
|
||
- **Hardware:** only Task 5 touches `/dev/ttyACM0` (UM20147), under `sg dialout -c "..."`. Never start a server on port 8200.
|
||
- **Every commit message ends with:**
|
||
```
|
||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
|
||
```
|
||
|
||
## Review Focus
|
||
|
||
These are the inputs most likely to bite, each with a test in the named task.
|
||
|
||
1. **A write opcode reaching the wire by any path.** This includes `_exchange`, a direct `_send`, a scratch tool calling `protocol._send`, and a frame built by hand. It must be refused with nothing written to the transport (Task 2).
|
||
2. **`0xA2` in a plan or a send.** It is refused even when explicitly allowed (Tasks 2, 4).
|
||
3. **A read whose block fails its CRC, or has a size THOR's offset was never observed at.** Building a plan from it must be refused. Otherwise it would write corruption back, or use an unverified offset (Task 4).
|
||
4. **Escape bytes inside data**, including a literal `0x10` (never captured in write data) and a checksum that lands on `02/03/04/10`. The frame must still be correct (Task 1).
|
||
5. **The call-home plan must flip exactly one bit.** Every other byte must equal the read (Task 4).
|
||
|
||
---
|
||
|
||
## File map
|
||
|
||
| file | change |
|
||
|---|---|
|
||
| `micromate/framing.py` | `build_request(..., data=b"")`; new `request_sub(frame)` |
|
||
| `micromate/opcodes.py` | **new**: `WRITE_SUBS`, `CROSS_SERIES_COLLISIONS`, `OpcodeRefused`, `check_transmit()` |
|
||
| `micromate/protocol.py` | `MicromateProtocol(allowed_writes=frozenset())`; `_send` gate; docstring |
|
||
| `micromate/client.py` | docstring only ("reads only" now enforced) |
|
||
| `micromate/writes.py` | **new**: `WriteStep`, `WritePlan`, `plan_start_monitoring`, `plan_stop_monitoring`, `plan_call_home_enabled`, `plan_setup_push` |
|
||
| `scratch/mm_write_fixtures.py` | **new**: cuts fixtures out of the captures (reproducible provenance) |
|
||
| `tests/fixtures/micromate-writes/*.json` | **new, force-added**: seven captured sessions |
|
||
| `bridges/mm_dry_run.py` | **new**: live dry run, reads only |
|
||
| tests | `test_micromate_framing.py` (+), `test_micromate_opcodes.py` (new), `test_micromate_write_fixtures.py` (new), `test_micromate_writes.py` (new) |
|
||
| docs | `docs/micromate_protocol_reference.md`, `CLAUDE.md` (Task 5) |
|
||
|
||
---
|
||
|
||
### Task 1: The encoder — a data section on `build_request`
|
||
|
||
**Files:**
|
||
- Modify: `micromate/framing.py`, `build_request` (line 129)
|
||
- Test: `tests/test_micromate_framing.py` (append)
|
||
|
||
**Interfaces:**
|
||
- Produces:
|
||
- `build_request(sub: int, offset: int = 0, params: bytes = bytes(10), data: bytes = b"") -> bytes`. The data goes after params, inside the stuffing and the checksum.
|
||
- `request_sub(frame: bytes) -> int`, the SUB of a built host→unit frame. It raises `ValueError` on anything that isn't one.
|
||
|
||
- [ ] **Step 1: Write the failing tests.** Append to `tests/test_micromate_framing.py`:
|
||
|
||
```python
|
||
# ── the data section (writes) ─────────────────────────────────────────────────
|
||
|
||
from micromate.framing import request_sub, unstuff # noqa: E402
|
||
|
||
|
||
def _destuffed_payload(frame: bytes) -> bytes:
|
||
body = unstuff(frame[2:-1])
|
||
return body[:-1] # drop the checksum byte
|
||
|
||
|
||
def test_data_goes_after_the_params_inside_the_checksum():
|
||
data = bytes(range(0x20, 0x40))
|
||
f = build_request(0x7E, 0x007E, bytes(10), data)
|
||
payload = _destuffed_payload(f)
|
||
assert payload[:6] == bytes([0x10, 0x00, 0x7E, 0x00, 0x00, 0x7E])
|
||
assert payload[6:16] == bytes(10) and payload[16:] == data
|
||
assert unstuff(f[2:-1])[-1] == sum(payload) & 0xFF
|
||
|
||
|
||
@pytest.mark.parametrize("b", [0x02, 0x03, 0x04, 0x10])
|
||
def test_every_escape_byte_in_data_is_escaped_on_the_wire(b):
|
||
f = build_request(0x71, 0x082C, bytes(10), bytes([0x55, b, 0x55]))
|
||
assert bytes([0x55, DLE, b, 0x55]) in f
|
||
assert _destuffed_payload(f)[16:] == bytes([0x55, b, 0x55])
|
||
|
||
|
||
def test_a_literal_0x10_in_data_round_trips():
|
||
# Never captured in write data; params already prove `10 10` (SUB 0x5A).
|
||
data = b"\x10\x10\x00\x10"
|
||
assert _destuffed_payload(build_request(0x71, 0x082C, bytes(10), data))[16:] == data
|
||
|
||
|
||
def test_a_checksum_that_lands_on_an_escape_byte_is_escaped():
|
||
# Pick the last data byte so SUM8 of the payload is exactly 0x03.
|
||
head = bytes([0x10, 0x00, 0x7E, 0x00, 0x00, 0x7E]) + bytes(10) + b"\x01\x02"
|
||
last = (0x03 - sum(head)) & 0xFF
|
||
f = build_request(0x7E, 0x007E, bytes(10), b"\x01\x02" + bytes([last]))
|
||
assert f[-3:] == bytes([DLE, 0x03, ETX])
|
||
|
||
|
||
def test_without_data_the_frame_is_unchanged():
|
||
assert build_request(0x5B, 0x0030) == build_request(0x5B, 0x0030, bytes(10), b"")
|
||
|
||
|
||
def test_request_sub_reads_the_sub_back_even_when_stuffed():
|
||
assert request_sub(build_request(0x96, 0xFFFF)) == 0x96
|
||
assert request_sub(build_request(0x10, 0x0000)) == 0x10 # SUB itself escaped
|
||
assert request_sub(build_request(0x71, 0x082C, bytes(10), b"\x03" * 5)) == 0x71
|
||
|
||
|
||
@pytest.mark.parametrize("junk", [b"", b"\x41\x02\x03", b"\x02\x10\x10\x00\x96\x03", b"hello"])
|
||
def test_request_sub_refuses_anything_that_is_not_a_request_frame(junk):
|
||
with pytest.raises(ValueError):
|
||
request_sub(junk)
|
||
|
||
|
||
@pytest.mark.skipif(
|
||
not _CAPTURES.is_dir(),
|
||
reason="capture directory is gitignored; present only on a dev box",
|
||
)
|
||
def test_builder_reproduces_every_captured_request_frame_including_writes():
|
||
"""251/251: the 218 reads plus the 33 data-carrying writes."""
|
||
checked = 0
|
||
for path in sorted(_CAPTURES.rglob("raw_bw_*.bin")):
|
||
blob = path.read_bytes()
|
||
i = 0
|
||
while i < len(blob):
|
||
if not (blob[i] == ACK and i + 1 < len(blob) and blob[i + 1] == STX):
|
||
i += 1
|
||
continue
|
||
j = i + 2
|
||
body = bytearray()
|
||
while j < len(blob):
|
||
if blob[j] == DLE and j + 1 < len(blob):
|
||
body.append(blob[j + 1])
|
||
j += 2
|
||
continue
|
||
if blob[j] == ETX:
|
||
break
|
||
body.append(blob[j])
|
||
j += 1
|
||
payload = bytes(body[:-1])
|
||
sub = payload[2]
|
||
offset = (payload[4] << 8) | payload[5]
|
||
assert build_request(sub, offset, payload[6:16], payload[16:]) == blob[i:j + 1], (
|
||
f"{path.name} @0x{i:04x} SUB=0x{sub:02x}"
|
||
)
|
||
checked += 1
|
||
i = j + 1
|
||
assert checked == 251, f"expected 251 request frames, checked {checked}"
|
||
```
|
||
|
||
- [ ] **Step 2: Run them, and watch them fail.**
|
||
Run: `.venv/bin/python -m pytest tests/test_micromate_framing.py -q`
|
||
Expected: FAIL with `ImportError: cannot import name 'request_sub'`.
|
||
|
||
- [ ] **Step 3: Implement.** In `micromate/framing.py`:
|
||
- Change the signature to `def build_request(sub: int, offset: int = 0, params: bytes = bytes(10), data: bytes = b"") -> bytes:`.
|
||
- Add to its docstring's Args:
|
||
|
||
```
|
||
data: the write section after params (empty for every read and for
|
||
write confirms). Escaped and checksummed exactly like the rest
|
||
of the payload -- reproduces all 33 data-carrying THOR frames.
|
||
```
|
||
|
||
- Change the `payload = ...` line to:
|
||
|
||
```python
|
||
payload = (bytes([MM_CMD, 0x00, sub, 0x00, (offset >> 8) & 0xFF, offset & 0xFF])
|
||
+ params + bytes(data))
|
||
```
|
||
|
||
- Add after `build_request`:
|
||
|
||
```python
|
||
def request_sub(frame: bytes) -> int:
|
||
"""The SUB of a built host->unit frame (`41 02 <stuffed body> 03`).
|
||
|
||
Used by the protocol's send-side opcode gate, which must see exactly what is
|
||
about to go on the wire rather than trust the caller's word for it.
|
||
"""
|
||
if len(frame) < 5 or frame[0] != ACK or frame[1] != STX or frame[-1] != ETX:
|
||
raise ValueError(f"not a host->unit request frame: {bytes(frame[:8]).hex()}")
|
||
body = unstuff(frame[2:-1])
|
||
if len(body) < 17 or body[0] != MM_CMD:
|
||
raise ValueError(f"not a host->unit request frame: {bytes(frame[:8]).hex()}")
|
||
return body[2]
|
||
```
|
||
|
||
- [ ] **Step 4: Run the tests, and watch them pass.**
|
||
Run: `.venv/bin/python -m pytest tests/test_micromate_framing.py -q`
|
||
Expected: all pass, including both capture-gated tests on this box (218 and 251).
|
||
|
||
- [ ] **Step 5: Commit and push.** Message: `feat(micromate): build_request carries a data section -- reproduces all 251 THOR request frames`.
|
||
|
||
---
|
||
|
||
### Task 2: The opcode table and the send-side gate
|
||
|
||
**Files:**
|
||
- Create: `micromate/opcodes.py`
|
||
- Modify: `micromate/protocol.py`: `MicromateProtocol.__init__` (line 241), `_send` (line 511) and the module docstring. Also `micromate/client.py`, docstring line 5.
|
||
- Test: `tests/test_micromate_opcodes.py` (new)
|
||
|
||
**Interfaces:**
|
||
- Consumes: Task 1's `request_sub`.
|
||
- Produces:
|
||
- `WRITE_SUBS: dict[int, str]`
|
||
- `CROSS_SERIES_COLLISIONS: dict[int, str]`
|
||
- `class OpcodeRefused(RuntimeError)`
|
||
- `check_transmit(sub, allowed_writes=frozenset()) -> None`
|
||
- `MicromateProtocol(transport, recv_timeout=..., strict_checksums=True, allowed_writes: frozenset = frozenset())`
|
||
|
||
- [ ] **Step 1: Write the failing tests** in `tests/test_micromate_opcodes.py`:
|
||
|
||
```python
|
||
"""The send-side gate: no write opcode reaches the wire unless allowed, and 0xA2 never."""
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import sys
|
||
|
||
import pytest
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
import micromate.protocol as mm_proto # noqa: E402
|
||
from micromate.framing import build_request # noqa: E402
|
||
from micromate.opcodes import ( # noqa: E402
|
||
CROSS_SERIES_COLLISIONS, WRITE_SUBS, OpcodeRefused, check_transmit,
|
||
)
|
||
from test_micromate_protocol import frame, proto # noqa: E402
|
||
|
||
# THOR's captured end-call-home frame -- byte-identical to Series III's CONFIRM ERASE.
|
||
A2_WIRE = bytes.fromhex("4102101000a200ffff00000000000000000000b003")
|
||
|
||
|
||
def test_no_read_command_is_classed_as_a_write():
|
||
reads = {v for k, v in vars(mm_proto).items() if k.startswith("SUB_")}
|
||
assert reads and not (reads & set(WRITE_SUBS))
|
||
|
||
|
||
def test_0xa2_is_a_collision_and_a_write():
|
||
assert 0xA2 in CROSS_SERIES_COLLISIONS and 0xA2 in WRITE_SUBS
|
||
|
||
|
||
def test_a_write_is_refused_unless_allowed():
|
||
with pytest.raises(OpcodeRefused, match="0x96"):
|
||
check_transmit(0x96)
|
||
check_transmit(0x96, frozenset({0x96}))
|
||
check_transmit(0x5B) # a read needs no permission
|
||
|
||
|
||
def test_0xa2_is_refused_even_when_allowed():
|
||
with pytest.raises(OpcodeRefused, match="ERASE"):
|
||
check_transmit(0xA2, frozenset({0xA2}))
|
||
|
||
|
||
def test_the_protocol_refuses_a_write_and_writes_nothing():
|
||
p, t = proto([])
|
||
with pytest.raises(OpcodeRefused):
|
||
p._exchange(0x96, offset=0xFFFF)
|
||
with pytest.raises(OpcodeRefused):
|
||
p._send(build_request(0x97, 0xFFFF)) # a direct _send is gated too
|
||
assert t.written == []
|
||
|
||
|
||
def test_the_protocol_refuses_the_captured_0xa2_frame_byte_for_byte():
|
||
p, t = proto([], allowed_writes=frozenset({0xA2}))
|
||
with pytest.raises(OpcodeRefused):
|
||
p._send(A2_WIRE)
|
||
assert t.written == []
|
||
|
||
|
||
def test_an_explicitly_allowed_write_goes_out_on_a_scripted_transport():
|
||
p, t = proto([frame(0x69, bytes(11))], allowed_writes=frozenset({0x96}))
|
||
p._exchange(0x96, offset=0xFFFF)
|
||
assert t.written == [build_request(0x96, 0xFFFF)]
|
||
|
||
|
||
def test_reads_are_unaffected_by_the_gate():
|
||
p, t = proto([frame(0xA4, bytes(11))])
|
||
p.poll()
|
||
assert len(t.written) == 1
|
||
|
||
|
||
def test_a_frame_that_is_not_a_request_is_refused_not_sent():
|
||
p, t = proto([])
|
||
with pytest.raises(ValueError):
|
||
p._send(b"\x41\x03")
|
||
assert t.written == []
|
||
```
|
||
|
||
Before running, check `tests/test_micromate_protocol.py`:
|
||
- Does `proto(responses, **kw)` forward `**kw` to `MicromateProtocol`?
|
||
- Is `frame(rsp_sub, data, ...)` the response builder?
|
||
- If either differs, adapt only the import lines and the call shape, and say so in the report.
|
||
|
||
Also check what POLL's response SUB is: `0xFF - 0x5B = 0xA4`.
|
||
|
||
- [ ] **Step 2: Run them, and watch them fail.**
|
||
Run: `.venv/bin/python -m pytest tests/test_micromate_opcodes.py -q`
|
||
Expected: FAIL with `ModuleNotFoundError: No module named 'micromate.opcodes'`.
|
||
|
||
- [ ] **Step 3: Implement.** Create `micromate/opcodes.py`:
|
||
|
||
```python
|
||
"""Micromate (Series IV) opcode table: which SUBs write, and which collide.
|
||
|
||
One place, as the parity spec requires. `MicromateProtocol._send` consults it
|
||
on every outgoing frame, so a write cannot reach a unit by a path nobody
|
||
thought about -- a scratch tool calling `protocol._send`, a hand-built frame, a
|
||
method added later.
|
||
|
||
Every SUB here was seen as a host->unit request in THOR's captures
|
||
(`docs/micromate_protocol_reference.md`). The table classifies REQUESTS: a few
|
||
of these values are also ACK SUBs of other commands (0x71 acks 0x8E, 0x72 acks
|
||
0x8D), which is irrelevant to a send-side check.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from typing import Dict, FrozenSet
|
||
|
||
WRITE_SUBS: Dict[int, str] = {
|
||
0x47: "scheduler enable/disable",
|
||
0x68: "setup push: preferences block (0x08)",
|
||
0x71: "setup push: setup block (0x1A)",
|
||
0x72: "setup push: setup confirm",
|
||
0x73: "setup push: preferences confirm",
|
||
0x7E: "call-home config write (0x2C)",
|
||
0x7F: "call-home config confirm",
|
||
0x82: "setup push: trigger block (0x2E)",
|
||
0x83: "setup push: trigger confirm",
|
||
0x8D: "file open for write",
|
||
0x8E: "file body write",
|
||
0x96: "start monitoring",
|
||
0x97: "stop monitoring",
|
||
0xA2: "end call-home",
|
||
0xA8: "delete one event",
|
||
0xAA: "delete-event confirm",
|
||
0xDA: "setup push: file name",
|
||
}
|
||
|
||
# Same bytes, opposite consequence on the other series. Never transmitted on
|
||
# Series IV, allowed or not: if a Series-III unit is at the address (a moved
|
||
# modem, a stale IP), it would execute the other meaning. Lifting an entry is
|
||
# a spec change, not a parameter.
|
||
CROSS_SERIES_COLLISIONS: Dict[int, str] = {
|
||
0xA2: "CONFIRM ERASE on Series III -- erases every stored event; "
|
||
"'end call-home' on Series IV",
|
||
}
|
||
|
||
|
||
class OpcodeRefused(RuntimeError):
|
||
"""A frame was stopped before it reached the wire."""
|
||
|
||
|
||
def check_transmit(sub: int, allowed_writes: FrozenSet[int] = frozenset()) -> None:
|
||
if sub in CROSS_SERIES_COLLISIONS:
|
||
raise OpcodeRefused(
|
||
f"refused to transmit SUB 0x{sub:02X}: {CROSS_SERIES_COLLISIONS[sub]}")
|
||
if sub in WRITE_SUBS and sub not in allowed_writes:
|
||
raise OpcodeRefused(
|
||
f"refused to transmit SUB 0x{sub:02X} ({WRITE_SUBS[sub]}): writes are "
|
||
"not enabled on this connection")
|
||
```
|
||
|
||
In `micromate/protocol.py`:
|
||
- Imports: extend `from .framing import ...` with `request_sub`, and add `from .opcodes import check_transmit`.
|
||
- `__init__`: add the parameter `allowed_writes: frozenset = frozenset(),` after `strict_checksums`, and set `self._allowed_writes = frozenset(allowed_writes)` with the other assignments. Add to the docstring:
|
||
|
||
```
|
||
allowed_writes: write SUBs this connection may transmit. Empty by
|
||
default -- every write opcode in `micromate.opcodes` is refused
|
||
at `_send`, and `0xA2` is refused whatever this says.
|
||
```
|
||
|
||
- `_send`:
|
||
|
||
```python
|
||
def _send(self, frame: bytes) -> None:
|
||
# The gate sees the bytes that are about to go out, not the caller's
|
||
# intent: every transmit in this package passes through here.
|
||
check_transmit(request_sub(frame), self._allowed_writes)
|
||
log.debug("TX %d bytes: %s", len(frame), frame.hex())
|
||
self._transport.write(frame)
|
||
```
|
||
|
||
- Module docstring: replace the paragraph that begins `Scope: **reads only.**` up to `...not a side effect of a client that grew a method.` with:
|
||
|
||
```
|
||
Scope: **reads only on the wire, enforced.** Every outgoing frame passes
|
||
`micromate.opcodes.check_transmit()` in `_send`: a write opcode is refused
|
||
unless this connection was constructed with it in `allowed_writes` (nothing in
|
||
the codebase does so yet), and `0xA2` -- CONFIRM ERASE on Series III -- is
|
||
refused always. No command has ever been originated against a unit by this
|
||
project; every write in ``docs/micromate_protocol_reference.md`` was performed
|
||
by THOR while we recorded. The first thing this codebase ever sends to a
|
||
customer's instrument should be a decision someone made on purpose, not a side
|
||
effect of a client that grew a method. Write frames are *built* in
|
||
``micromate.writes`` as reviewable plans; building one sends nothing.
|
||
```
|
||
|
||
In `micromate/client.py`, change the docstring line saying reads only, at line 5, to say reads only, enforced by the protocol's opcode gate (`micromate.opcodes`).
|
||
|
||
- [ ] **Step 4: Run the tests, and watch them pass.**
|
||
Run: `.venv/bin/python -m pytest tests/test_micromate_opcodes.py tests/test_micromate_protocol.py tests/test_micromate_client.py tests/test_micromate_events.py -q`
|
||
Expected: all pass, including the THOR replay tests on this box. If a replay test now raises `OpcodeRefused`, it was transmitting a captured write through the protocol. STOP and report it; do not allow writes to make it pass.
|
||
|
||
- [ ] **Step 5: Full suite.** Run `.venv/bin/python -m pytest -q 2>&1 | tail -3`. Only the 16 pre-existing failures are allowed.
|
||
|
||
- [ ] **Step 6: Commit and push.** Message: `feat(micromate): one opcode table and a send-side gate -- writes refused unless allowed, 0xA2 always`.
|
||
|
||
---
|
||
|
||
### Task 3: Fixtures cut from THOR's write captures
|
||
|
||
**Files:**
|
||
- Create: `scratch/mm_write_fixtures.py`
|
||
- Create, force-added: `tests/fixtures/micromate-writes/*.json`
|
||
- Test: `tests/test_micromate_write_fixtures.py` (new)
|
||
|
||
**Interfaces:**
|
||
- Produces: one JSON file per captured session, in this schema:
|
||
|
||
```json
|
||
{
|
||
"source": "bridges/captures/9-24-26 - micromate2/<raw_bw file name>",
|
||
"source_sha256": {"bw": "<hex>", "s3": "<hex>"},
|
||
"unit": "UM12947",
|
||
"firmware_line": "11.0CB",
|
||
"exchanges": [
|
||
{"sub": 65, "request": "<request wire hex>", "response_sub": 190, "response_data": "<response data hex>"}
|
||
]
|
||
}
|
||
```
|
||
|
||
The sessions and their slugs:
|
||
|
||
| slug | capture (under `bridges/captures/9-24-26 - micromate2/`) |
|
||
|---|---|
|
||
| `setup-push-new-test1` | `raw_{bw,s3}_20260924_181942_send_TEST1_to_unit.bin` |
|
||
| `setup-push-overwrite-test1` | `overwritetest/raw_{bw,s3}_20260924_185113_test1_overwrite_check.bin` |
|
||
| `setup-push-read-scheduler` | `raw_{bw,s3}_20260924_191835_read_scheduler.bin` |
|
||
| `setup-push-pull-schedule` | `raw_{bw,s3}_20260925_003029_pull_schedule,_turn_off_repeat_daily,_push_schedule.bin` |
|
||
| `setup-push-multiday` | `raw_{bw,s3}_20260925_011907_send_multiday_schedule.bin` |
|
||
| `call-home-enable-disable` | `raw_{bw,s3}_20260925_011620_ACH-change_1_setting.bin` |
|
||
| `monitor-start-stop` | `raw_{bw,s3}_20260924_191214_turn_on_monitormode_then_attempt_to_write_config.bin` |
|
||
|
||
- [ ] **Step 1: Write the extraction script** `scratch/mm_write_fixtures.py`:
|
||
|
||
```python
|
||
#!/usr/bin/env python3
|
||
"""Cut Micromate write-session fixtures out of THOR's captures.
|
||
|
||
bridges/captures/ is gitignored, so the reproduction tests read these instead.
|
||
Each fixture is every request (as wire bytes) and every response (as its data
|
||
section) of one captured THOR session, paired in order, with the sha256 of the
|
||
capture files it came from. Re-run to regenerate:
|
||
|
||
.venv/bin/python scratch/mm_write_fixtures.py
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
REPO = Path(__file__).resolve().parent.parent
|
||
sys.path.insert(0, str(REPO))
|
||
|
||
from micromate.framing import ACK, DLE, ETX, STX, MicromateFrameParser # noqa: E402
|
||
|
||
CAP = REPO / "bridges" / "captures" / "9-24-26 - micromate2"
|
||
OUT = REPO / "tests" / "fixtures" / "micromate-writes"
|
||
SESSIONS = {
|
||
"setup-push-new-test1": "20260924_181942_send_TEST1_to_unit",
|
||
"setup-push-overwrite-test1": "overwritetest/*20260924_185113_test1_overwrite_check",
|
||
"setup-push-read-scheduler": "20260924_191835_read_scheduler",
|
||
"setup-push-pull-schedule": "20260925_003029_pull_schedule,_turn_off_repeat_daily,_push_schedule",
|
||
"setup-push-multiday": "20260925_011907_send_multiday_schedule",
|
||
"call-home-enable-disable": "20260925_011620_ACH-change_1_setting",
|
||
"monitor-start-stop": "20260924_191214_turn_on_monitormode_then_attempt_to_write_config",
|
||
}
|
||
|
||
|
||
def _find(stem: str, kind: str) -> Path:
|
||
if "/" in stem:
|
||
sub, rest = stem.split("/", 1)
|
||
hits = sorted((CAP / sub).glob(f"raw_{kind}_{rest.lstrip('*')}.bin"))
|
||
else:
|
||
hits = sorted(CAP.glob(f"raw_{kind}_{stem}.bin"))
|
||
if len(hits) != 1:
|
||
raise SystemExit(f"expected one raw_{kind} file for {stem!r}, found {hits}")
|
||
return hits[0]
|
||
|
||
|
||
def requests(blob: bytes) -> list[bytes]:
|
||
out, i = [], 0
|
||
while i < len(blob):
|
||
if not (blob[i] == ACK and i + 1 < len(blob) and blob[i + 1] == STX):
|
||
i += 1
|
||
continue
|
||
j = i + 2
|
||
while j < len(blob):
|
||
if blob[j] == DLE and j + 1 < len(blob):
|
||
j += 2
|
||
continue
|
||
if blob[j] == ETX:
|
||
break
|
||
j += 1
|
||
out.append(blob[i:j + 1])
|
||
i = j + 1
|
||
return out
|
||
|
||
|
||
def main() -> None:
|
||
OUT.mkdir(parents=True, exist_ok=True)
|
||
for slug, stem in SESSIONS.items():
|
||
bw, s3 = _find(stem, "bw"), _find(stem, "s3")
|
||
reqs = requests(bw.read_bytes())
|
||
parser = MicromateFrameParser()
|
||
rsps = parser.feed(s3.read_bytes())
|
||
if len(reqs) != len(rsps):
|
||
raise SystemExit(f"{slug}: {len(reqs)} requests vs {len(rsps)} responses")
|
||
exchanges = []
|
||
for rq, rp in zip(reqs, rsps):
|
||
from micromate.framing import request_sub
|
||
sub = request_sub(rq)
|
||
if rp.sub != 0xFF - sub or not rp.checksum_valid:
|
||
raise SystemExit(f"{slug}: response 0x{rp.sub:02X} does not answer 0x{sub:02X}")
|
||
exchanges.append({"sub": sub, "request": rq.hex(), "response_sub": rp.sub,
|
||
"response_data": rp.data.hex()})
|
||
doc = {
|
||
"source": str(bw.relative_to(REPO)),
|
||
"source_sha256": {"bw": hashlib.sha256(bw.read_bytes()).hexdigest(),
|
||
"s3": hashlib.sha256(s3.read_bytes()).hexdigest()},
|
||
"unit": "UM12947", "firmware_line": "11.0CB",
|
||
"exchanges": exchanges,
|
||
}
|
||
(OUT / f"{slug}.json").write_text(json.dumps(doc, indent=1) + "\n")
|
||
print(f"{slug}: {len(exchanges)} exchanges")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|
||
```
|
||
|
||
Check two things before running:
|
||
- `MicromateFrameParser().feed()` returns a list of `MicromateFrame` with `.sub`, `.data` and `.checksum_valid` (micromate/framing.py).
|
||
- Responses index-align with requests. The survey measured equal counts in every pair; the script refuses otherwise.
|
||
|
||
Move the `request_sub` import to the top imports. It is shown inline above only for clarity.
|
||
|
||
- [ ] **Step 2: Run it.** `.venv/bin/python scratch/mm_write_fixtures.py`. Expect 7 lines, one per slug. Check the count for each kind of session:
|
||
- **setup push:** 12 to 25 exchanges;
|
||
- **call-home:** 14;
|
||
- **start/stop:** about 40.
|
||
|
||
If any session fails alignment, STOP and report it.
|
||
|
||
- [ ] **Step 3: Write the tests** in `tests/test_micromate_write_fixtures.py`:
|
||
|
||
```python
|
||
"""The write-session fixtures are what they claim to be: THOR's own frames, paired."""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
from micromate.framing import request_sub, unstuff # noqa: E402
|
||
|
||
FIX = Path(__file__).parent / "fixtures" / "micromate-writes"
|
||
ALL = sorted(FIX.glob("*.json"))
|
||
|
||
|
||
def test_all_seven_sessions_are_present():
|
||
assert {p.stem for p in ALL} == {
|
||
"setup-push-new-test1", "setup-push-overwrite-test1", "setup-push-read-scheduler",
|
||
"setup-push-pull-schedule", "setup-push-multiday", "call-home-enable-disable",
|
||
"monitor-start-stop"}
|
||
|
||
|
||
@pytest.mark.parametrize("path", ALL, ids=lambda p: p.stem)
|
||
def test_every_request_is_a_valid_frame_and_every_response_answers_it(path):
|
||
doc = json.loads(path.read_text())
|
||
assert doc["source_sha256"]["bw"] and doc["exchanges"]
|
||
for ex in doc["exchanges"]:
|
||
wire = bytes.fromhex(ex["request"])
|
||
assert request_sub(wire) == ex["sub"]
|
||
body = unstuff(wire[2:-1])
|
||
assert body[-1] == sum(body[:-1]) & 0xFF # plain SUM8
|
||
assert ex["response_sub"] == 0xFF - ex["sub"]
|
||
|
||
|
||
@pytest.mark.parametrize("slug,subs", [
|
||
("setup-push-new-test1", [0x41, 0x08, 0x2E, 0x1A, 0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72]),
|
||
("call-home-enable-disable", [0x2C, 0x7E, 0x7F]),
|
||
("monitor-start-stop", [0x96, 0x97]),
|
||
])
|
||
def test_each_session_holds_the_frames_its_tests_need(slug, subs):
|
||
seen = [ex["sub"] for ex in json.loads((FIX / f"{slug}.json").read_text())["exchanges"]]
|
||
for s in subs:
|
||
assert s in seen, f"{slug}: no SUB 0x{s:02X}"
|
||
```
|
||
|
||
- [ ] **Step 4: Run the tests and watch them pass.**
|
||
Run: `.venv/bin/python -m pytest tests/test_micromate_write_fixtures.py -q`.
|
||
To show the fixtures stand alone, check that neither the fixture tests nor Task 4's tests reference the capture directory:
|
||
`grep -n "captures" tests/test_micromate_write_fixtures.py` must print nothing.
|
||
⚠ **Never move, rename or delete `bridges/captures/`**, not even temporarily. It holds irreplaceable research captures.
|
||
|
||
- [ ] **Step 5: Commit and push.** Use `git add -f tests/fixtures/micromate-writes/*.json` and `git add scratch/mm_write_fixtures.py tests/test_micromate_write_fixtures.py`. Message: `test(micromate): THOR's write sessions as fixtures -- seven captures, paired, with provenance`.
|
||
|
||
---
|
||
|
||
### Task 4: Write plans, reproduced byte for byte
|
||
|
||
**Files:**
|
||
- Create: `micromate/writes.py`
|
||
- Test: `tests/test_micromate_writes.py` (new)
|
||
|
||
**Interfaces:**
|
||
- Consumes:
|
||
- Task 1's `build_request(data=)`;
|
||
- Task 2's `WRITE_SUBS`, `CROSS_SERIES_COLLISIONS` and `OpcodeRefused`;
|
||
- `micromate.setup_block.crc_ok`;
|
||
- Task 3's fixtures.
|
||
- Produces:
|
||
- `WriteStep(sub, offset, data=b"", params=bytes(10), what="")` with `.ack_sub`, `.frame` and `.describe()`;
|
||
- `WritePlan(action, steps)` with `.subs`, `.frames()` and `.describe()`;
|
||
- `plan_start_monitoring()`, `plan_stop_monitoring()`;
|
||
- `plan_call_home_enabled(call_home: bytes, enabled: bool)`;
|
||
- `plan_setup_push(prefs: bytes, trigger: bytes, setup: bytes, name: str)`.
|
||
|
||
All inputs are block **content**: response data `[11:]`.
|
||
|
||
- [ ] **Step 1: Write the failing tests** in `tests/test_micromate_writes.py`:
|
||
|
||
```python
|
||
"""Write plans: built from the unit's own reads, equal to THOR's frames byte for byte."""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
from micromate.opcodes import OpcodeRefused # noqa: E402
|
||
from micromate.writes import ( # noqa: E402
|
||
WritePlan, WriteStep, plan_call_home_enabled, plan_setup_push,
|
||
plan_start_monitoring, plan_stop_monitoring,
|
||
)
|
||
|
||
FIX = Path(__file__).parent / "fixtures" / "micromate-writes"
|
||
PUSHES = ["setup-push-new-test1", "setup-push-overwrite-test1", "setup-push-read-scheduler",
|
||
"setup-push-pull-schedule", "setup-push-multiday"]
|
||
NO_EDIT_PUSHES = ["setup-push-read-scheduler", "setup-push-pull-schedule", "setup-push-multiday"]
|
||
|
||
|
||
def _session(slug):
|
||
return json.loads((FIX / f"{slug}.json").read_text())["exchanges"]
|
||
|
||
|
||
def _content(ex):
|
||
return bytes.fromhex(ex["response_data"])[11:]
|
||
|
||
|
||
def _first_push(slug):
|
||
"""The reads (by SUB) and THOR's writes (by SUB) of the session's first push."""
|
||
ex = _session(slug)
|
||
start = next(i for i, e in enumerate(ex) if e["sub"] == 0xDA)
|
||
reads = {}
|
||
for e in ex[:start]:
|
||
reads[e["sub"]] = _content(e) # the LAST read of each SUB before the push
|
||
writes = {}
|
||
for e in ex[start:]:
|
||
if e["sub"] in writes:
|
||
break
|
||
writes[e["sub"]] = bytes.fromhex(e["request"])
|
||
if e["sub"] == 0x72:
|
||
break
|
||
return reads, writes
|
||
|
||
|
||
def _name_from_active(content):
|
||
# Mirror how MicromateClient.get_active_setup() extracts the name from the
|
||
# 0x41 content -- check it and copy its slicing if the name does not start
|
||
# at content[0].
|
||
return content.split(b"\x00", 1)[0].decode("ascii")
|
||
|
||
|
||
# ── start / stop ──────────────────────────────────────────────────────────────
|
||
|
||
def test_start_and_stop_equal_thors_frames():
|
||
thor = {e["sub"]: bytes.fromhex(e["request"]) for e in _session("monitor-start-stop")
|
||
if e["sub"] in (0x96, 0x97)}
|
||
assert plan_start_monitoring().frames() == [thor[0x96]]
|
||
assert plan_stop_monitoring().frames() == [thor[0x97]]
|
||
assert thor[0x96].hex() == "41021010009600ffff00000000000000000000a403"
|
||
|
||
|
||
# ── call-home ─────────────────────────────────────────────────────────────────
|
||
|
||
def test_call_home_enable_then_disable_equal_thors_frames():
|
||
ex = _session("call-home-enable-disable")
|
||
pairs, last_read = [], None
|
||
for e in ex:
|
||
if e["sub"] == 0x2C:
|
||
last_read = _content(e)
|
||
elif e["sub"] == 0x7E:
|
||
pairs.append((last_read, bytes.fromhex(e["request"])))
|
||
confirms = [bytes.fromhex(e["request"]) for e in ex if e["sub"] == 0x7F]
|
||
assert len(pairs) == 2 and len(confirms) == 2
|
||
(r1, w1), (r2, w2) = pairs
|
||
on, off = plan_call_home_enabled(r1, True), plan_call_home_enabled(r2, False)
|
||
assert on.frames() == [w1, confirms[0]]
|
||
assert off.frames() == [w2, confirms[1]]
|
||
|
||
|
||
def test_call_home_flips_exactly_one_bit_and_echoes_everything_else():
|
||
r1 = next(_content(e) for e in _session("call-home-enable-disable") if e["sub"] == 0x2C)
|
||
for enabled in (True, False):
|
||
data = plan_call_home_enabled(r1, enabled).steps[0].data
|
||
diff = [i for i in range(len(r1)) if data[i] != r1[i]]
|
||
assert set(diff) <= {5}
|
||
assert data[5] & 0x01 == (1 if enabled else 0)
|
||
assert data[5] & 0xFE == r1[5] & 0xFE
|
||
assert data[118:120] == r1[118:120]
|
||
|
||
|
||
def test_call_home_refuses_an_unobserved_size():
|
||
with pytest.raises(ValueError, match="126"):
|
||
plan_call_home_enabled(bytes(125), True)
|
||
|
||
|
||
# ── setup push ────────────────────────────────────────────────────────────────
|
||
|
||
@pytest.mark.parametrize("slug", PUSHES)
|
||
def test_setup_push_name_prefs_trigger_and_confirms_equal_thors_frames(slug):
|
||
reads, thor = _first_push(slug)
|
||
name = ("TEST1.mmb" if slug == "setup-push-new-test1"
|
||
else _name_from_active(reads[0x41]))
|
||
plan = plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], name)
|
||
ours = {s.sub: s.frame for s in plan.steps}
|
||
for sub in (0xDA, 0x68, 0x73, 0x82, 0x83, 0x72):
|
||
assert ours[sub] == thor[sub], f"{slug}: SUB 0x{sub:02X}"
|
||
assert [s.sub for s in plan.steps] == [0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72]
|
||
|
||
|
||
@pytest.mark.parametrize("slug", NO_EDIT_PUSHES)
|
||
def test_a_no_edit_push_reproduces_thors_setup_block_frame(slug):
|
||
reads, thor = _first_push(slug)
|
||
plan = plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], _name_from_active(reads[0x41]))
|
||
assert next(s.frame for s in plan.steps if s.sub == 0x71) == thor[0x71]
|
||
|
||
|
||
def test_setup_push_refuses_a_read_that_fails_its_checksum():
|
||
reads, _ = _first_push("setup-push-multiday")
|
||
bad = bytearray(reads[0x1A])
|
||
bad[100] ^= 0xFF
|
||
with pytest.raises(ValueError, match="checksum"):
|
||
plan_setup_push(reads[0x08], reads[0x2E], bytes(bad), "x.mmb")
|
||
|
||
|
||
@pytest.mark.parametrize("which", ["prefs", "trigger", "setup"])
|
||
def test_setup_push_refuses_an_unobserved_block_size(which):
|
||
reads, _ = _first_push("setup-push-multiday")
|
||
args = {"prefs": reads[0x08], "trigger": reads[0x2E], "setup": reads[0x1A]}
|
||
args[which] = args[which] + b"\x00\x00"
|
||
with pytest.raises(ValueError, match="size"):
|
||
plan_setup_push(args["prefs"], args["trigger"], args["setup"], "x.mmb")
|
||
|
||
|
||
@pytest.mark.parametrize("name", ["", "a\x00b", "é.mmb", "x" * 256])
|
||
def test_setup_push_refuses_a_bad_name(name):
|
||
reads, _ = _first_push("setup-push-multiday")
|
||
with pytest.raises(ValueError):
|
||
plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], name)
|
||
|
||
|
||
# ── the plan object ───────────────────────────────────────────────────────────
|
||
|
||
def test_a_plan_cannot_hold_a_collision_opcode():
|
||
with pytest.raises(OpcodeRefused):
|
||
WritePlan("end call-home", (WriteStep(0xA2, 0xFFFF),))
|
||
|
||
|
||
def test_a_plan_cannot_hold_a_read():
|
||
with pytest.raises(ValueError):
|
||
WritePlan("poll", (WriteStep(0x5B, 0x0030),))
|
||
|
||
|
||
def test_describe_is_the_dry_run_shape():
|
||
d = plan_stop_monitoring().describe()
|
||
assert d["action"] == "stop monitoring" and d["sends_nothing"] is True
|
||
step = d["steps"][0]
|
||
assert step == {"sub": "0x97", "what": "stop monitoring", "offset": "0xFFFF",
|
||
"data_len": 0, "expect_ack": "0x68",
|
||
"frame": "41021010009700ffff00000000000000000000a503"}
|
||
```
|
||
|
||
- [ ] **Step 2: Run them, and watch them fail.**
|
||
Run: `.venv/bin/python -m pytest tests/test_micromate_writes.py -q`
|
||
Expected: FAIL with `ModuleNotFoundError: No module named 'micromate.writes'`.
|
||
|
||
- [ ] **Step 3: Implement** `micromate/writes.py`:
|
||
|
||
```python
|
||
"""Write plans for a Micromate: the exact frames a write would send, in order.
|
||
|
||
A plan is what a dry run returns. Building one sends nothing; transmitting it
|
||
also needs a protocol constructed with those SUBs in `allowed_writes`, which no
|
||
code does yet (see `micromate.opcodes`).
|
||
|
||
Every input is the unit's OWN read of the block being written (content, i.e.
|
||
response data[11:]), and every plan sends back exactly what was read except
|
||
the one thing the operation changes. THOR works the same way, and the
|
||
reproduction tests hold the plans to THOR's frames byte for byte.
|
||
|
||
Offsets are THOR's observed constants. 🔶 Each was seen at one block size
|
||
only, so a plan refuses a block of any other size rather than guess.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass, field
|
||
from typing import FrozenSet, List, Tuple
|
||
|
||
from .framing import build_request
|
||
from .opcodes import CROSS_SERIES_COLLISIONS, WRITE_SUBS, OpcodeRefused
|
||
from .setup_block import crc_ok
|
||
|
||
_CONFIRM = 0xFFFF
|
||
|
||
# block content sizes THOR's offsets were observed at (all on UM12947 / 11.0CB)
|
||
_PREFS_LEN, _TRIGGER_LEN, _SETUP_LEN, _CALL_HOME_LEN = 90, 28, 2092, 126
|
||
_NAME_FIELD = 256
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class WriteStep:
|
||
sub: int
|
||
offset: int
|
||
data: bytes = b""
|
||
params: bytes = field(default=bytes(10))
|
||
what: str = ""
|
||
|
||
@property
|
||
def ack_sub(self) -> int:
|
||
return 0xFF - self.sub
|
||
|
||
@property
|
||
def frame(self) -> bytes:
|
||
return build_request(self.sub, self.offset, self.params, self.data)
|
||
|
||
def describe(self) -> dict:
|
||
return {"sub": f"0x{self.sub:02X}", "what": self.what,
|
||
"offset": f"0x{self.offset:04X}", "data_len": len(self.data),
|
||
"expect_ack": f"0x{self.ack_sub:02X}", "frame": self.frame.hex()}
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class WritePlan:
|
||
action: str
|
||
steps: Tuple[WriteStep, ...]
|
||
|
||
def __post_init__(self) -> None:
|
||
for s in self.steps:
|
||
if s.sub in CROSS_SERIES_COLLISIONS:
|
||
raise OpcodeRefused(
|
||
f"a plan cannot hold SUB 0x{s.sub:02X}: {CROSS_SERIES_COLLISIONS[s.sub]}")
|
||
if s.sub not in WRITE_SUBS:
|
||
raise ValueError(f"SUB 0x{s.sub:02X} is not a write opcode")
|
||
|
||
@property
|
||
def subs(self) -> FrozenSet[int]:
|
||
return frozenset(s.sub for s in self.steps)
|
||
|
||
def frames(self) -> List[bytes]:
|
||
return [s.frame for s in self.steps]
|
||
|
||
def describe(self) -> dict:
|
||
return {"action": self.action, "sends_nothing": True,
|
||
"steps": [s.describe() for s in self.steps]}
|
||
|
||
|
||
def plan_start_monitoring() -> WritePlan:
|
||
return WritePlan("start monitoring", (WriteStep(0x96, _CONFIRM, what="start monitoring"),))
|
||
|
||
|
||
def plan_stop_monitoring() -> WritePlan:
|
||
return WritePlan("stop monitoring", (WriteStep(0x97, _CONFIRM, what="stop monitoring"),))
|
||
|
||
|
||
def plan_call_home_enabled(call_home: bytes, enabled: bool) -> WritePlan:
|
||
"""Read `0x2C`, flip bit 0 of content[5], send the rest back byte for byte.
|
||
|
||
`[5]` reads 0x05 enabled / 0x04 disabled; bit 2 is set in both, so only
|
||
bit 0 is the enable. `[118:120]` is unit-maintained and THOR echoes it.
|
||
"""
|
||
if len(call_home) != _CALL_HOME_LEN:
|
||
raise ValueError(f"call-home content must be {_CALL_HOME_LEN} B "
|
||
f"(the size THOR's offset was seen at), got {len(call_home)}")
|
||
b5 = (call_home[5] | 0x01) if enabled else (call_home[5] & 0xFE)
|
||
data = call_home[:5] + bytes([b5]) + call_home[6:]
|
||
what = "call-home " + ("enable" if enabled else "disable")
|
||
return WritePlan(what, (
|
||
WriteStep(0x7E, 0x007E, data, what="call-home config write"),
|
||
WriteStep(0x7F, _CONFIRM, what="call-home config confirm"),
|
||
))
|
||
|
||
|
||
def _checked(block: bytes, size: int, label: str) -> bytes:
|
||
if len(block) != size:
|
||
raise ValueError(f"{label} block size {len(block)} B is not the {size} B "
|
||
"THOR's offset was observed at -- refusing to guess")
|
||
if not crc_ok(block):
|
||
raise ValueError(f"{label} block failed its checksum -- refusing to write a "
|
||
"corrupt read back to the unit")
|
||
return block
|
||
|
||
|
||
def plan_setup_push(prefs: bytes, trigger: bytes, setup: bytes, name: str) -> WritePlan:
|
||
"""Rewrite a setup as THOR does: read 0x08, 0x2E, 0x1A, send each back.
|
||
|
||
No field editing here (phase 5). Each block goes back with its length echo
|
||
[0:3] zeroed; the unit recomputes the CRCs, so 0x68 and 0x71 drop the CRC
|
||
slot and 0x82 sends it zeroed -- exactly THOR's frames.
|
||
"""
|
||
_checked(prefs, _PREFS_LEN, "preferences (0x08)")
|
||
_checked(trigger, _TRIGGER_LEN, "trigger (0x2E)")
|
||
_checked(setup, _SETUP_LEN, "setup (0x1A)")
|
||
try:
|
||
raw = name.encode("ascii")
|
||
except UnicodeEncodeError:
|
||
raise ValueError(f"setup name must be ASCII: {name!r}") from None
|
||
if not raw or b"\x00" in raw or len(raw) >= _NAME_FIELD:
|
||
raise ValueError(f"setup name must be 1-{_NAME_FIELD - 1} ASCII bytes "
|
||
f"with no NUL: {name!r}")
|
||
return WritePlan(f"setup push: {name}", (
|
||
WriteStep(0xDA, 0x0100, raw.ljust(_NAME_FIELD, b"\x00"), what="setup file name"),
|
||
WriteStep(0x68, 0x005A, bytes(3) + prefs[3:88], what="preferences block"),
|
||
WriteStep(0x73, _CONFIRM, what="preferences confirm"),
|
||
WriteStep(0x82, 0x001C, bytes(3) + trigger[3:26] + bytes(2), what="trigger block"),
|
||
WriteStep(0x83, _CONFIRM, what="trigger confirm"),
|
||
WriteStep(0x71, 0x082C, bytes(3) + setup[3:2090], what="setup block"),
|
||
WriteStep(0x72, _CONFIRM, what="setup confirm"),
|
||
))
|
||
```
|
||
|
||
If a reproduction assertion fails, do NOT adjust the builder to match one capture. Report the exact byte difference. The builder rules come from the survey's measured diffs (`0x68` = `0x08` content[0:88] with [0:3] zeroed; `0x82` = `0x2E` content[0:28] with [0:3] and [26:28] zeroed; `0x71` = `0x1A` content[0:2090] with [0:3] zeroed; `0xDA` = the name, null-padded to 256). A mismatch means a rule is wrong, and that is a finding.
|
||
|
||
- [ ] **Step 4: Run the tests, and watch them pass.**
|
||
Run: `.venv/bin/python -m pytest tests/test_micromate_writes.py -q`
|
||
Expected: all pass.
|
||
|
||
- [ ] **Step 5: Run the full suite.** Only the 16 pre-existing failures are allowed.
|
||
|
||
- [ ] **Step 6: Commit and push.** Message: `feat(micromate): write plans for start/stop, call-home and setup push -- THOR's frames byte for byte`.
|
||
|
||
---
|
||
|
||
### Task 5: The dry-run bench tool, run on UM20147
|
||
|
||
**Files:**
|
||
- Create: `bridges/mm_dry_run.py`
|
||
- Modify: `docs/micromate_protocol_reference.md`, `CLAUDE.md`
|
||
|
||
Read-only on the unit. UM20147 is on `/dev/ttyACM0`, which needs `sg dialout -c "..."`.
|
||
|
||
- [ ] **Step 1: Write the tool** `bridges/mm_dry_run.py`:
|
||
|
||
```python
|
||
#!/usr/bin/env python3
|
||
"""Dry run a Micromate write against a live unit: do the reads, print the plan.
|
||
|
||
Sends READS only. The write frames are built from the unit's own blocks and
|
||
printed for review -- step 1 of the bench protocol for every first live write
|
||
(parity spec, Testing). The protocol's opcode gate refuses every write SUB on
|
||
this connection, so nothing else can go out even by mistake.
|
||
|
||
sg dialout -c ".venv/bin/python bridges/mm_dry_run.py /dev/ttyACM0 call-home-off"
|
||
.venv/bin/python bridges/mm_dry_run.py --host 10.0.0.5 --tcp-port 9034 setup-rewrite
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||
|
||
from micromate.client import MicromateClient # noqa: E402
|
||
from micromate.writes import ( # noqa: E402
|
||
plan_call_home_enabled, plan_setup_push, plan_start_monitoring, plan_stop_monitoring,
|
||
)
|
||
from minimateplus.transport import SerialTransport, TcpTransport # noqa: E402
|
||
|
||
ACTIONS = ("start", "stop", "call-home-on", "call-home-off", "setup-rewrite")
|
||
|
||
|
||
def _content(data: bytes) -> bytes:
|
||
return bytes(data)[11:]
|
||
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||
ap.add_argument("port", nargs="?", help="serial port, e.g. /dev/ttyACM0")
|
||
ap.add_argument("action", choices=ACTIONS)
|
||
ap.add_argument("--host")
|
||
ap.add_argument("--tcp-port", type=int, default=9034)
|
||
ap.add_argument("--baud", type=int, default=115200)
|
||
a = ap.parse_args()
|
||
if not (a.port or a.host):
|
||
ap.error("give a serial port or --host")
|
||
transport = TcpTransport(a.host, port=a.tcp_port) if a.host else SerialTransport(a.port, a.baud)
|
||
mm = MicromateClient(transport)
|
||
mm.open()
|
||
try:
|
||
info = mm.connect()
|
||
p = mm.protocol
|
||
if a.action == "start":
|
||
plan = plan_start_monitoring()
|
||
elif a.action == "stop":
|
||
plan = plan_stop_monitoring()
|
||
elif a.action.startswith("call-home"):
|
||
plan = plan_call_home_enabled(_content(p.read_call_home_config()),
|
||
a.action == "call-home-on")
|
||
else:
|
||
name = mm.get_active_setup()
|
||
plan = plan_setup_push(_content(p.read_event_index()), _content(p.read_trigger_config()),
|
||
_content(p.read_compliance_config()), name)
|
||
out = plan.describe()
|
||
out["unit"] = {"serial": info.serial, "firmware_line": info.firmware_line}
|
||
print(json.dumps(out, indent=1))
|
||
finally:
|
||
mm.close()
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|
||
```
|
||
|
||
Before running, check the real names and return types of these:
|
||
- `MicromateProtocol.read_call_home_config`, `read_event_index` (the `0x08` preferences block), `read_trigger_config` and `read_compliance_config`. Do they return the response data or a frame?
|
||
- `MicromateClient.get_active_setup()`. Does it return the file name string, e.g. `"test2.MMB"`?
|
||
|
||
Adapt `_content()` and the calls to the real API. Mention any adaptation in the report.
|
||
|
||
- [ ] **Step 2: Run it on UM20147, one action at a time.** Run each as its own command, under `sg dialout`:
|
||
- `start`
|
||
- `stop`
|
||
- `call-home-on`
|
||
- `call-home-off`
|
||
- `setup-rewrite`
|
||
|
||
Save each output to `<scratchpad>/dryrun/<action>.json`. The scratchpad is `/tmp/claude-1000/-home-serversdown-seismo-relay/fc1049ca-ccbd-41ba-ac35-6b7c3996ffcd/scratchpad`.
|
||
|
||
Expected for every action:
|
||
- JSON with `sends_nothing: true` and the planned frames.
|
||
- No `OpcodeRefused` traceback. The tool only calls reads; a traceback would mean a write was attempted, which is a bug to report.
|
||
|
||
If a setup or call-home block is not the observed size on this unit's firmware (11.0BD), the plan is refused with a size error. Record that. It is a finding: THOR's offsets would then be unverified on this firmware. Do not change the size table.
|
||
|
||
- [ ] **Step 3: Compare with THOR's frames** (UM12947, 11.0CB, from the fixtures). For each action, tabulate SUB order, offsets and data lengths, ours against THOR's. They should match exactly; only data content differs, since it is the unit's own blocks.
|
||
- Also confirm the `setup-rewrite` plan's `0x71` data equals the unit's `0x1A` content [3:2090] with three zero bytes in front. That is a no-edit rewrite.
|
||
- For `call-home-off` / `call-home-on`, also confirm exactly one byte ([5]) differs between the two plans' `0x7E` data.
|
||
|
||
- [ ] **Step 4: Record.**
|
||
- In `docs/micromate_protocol_reference.md`, near the setup-push and call-home write sections, add a **dated, graded** line: "2026-10-22 — UM20147 (11.0BD) block sizes equal UM12947's (11.0CB): …; so THOR's write offsets apply to both firmware lines **as far as size goes** (measured, one unit each; nothing sent)". Use whatever was actually measured.
|
||
- In `CLAUDE.md`, add a sentence in the Series-4 "Where things stand" area:
|
||
- Phase 2 is done: the write encoder, the opcode gate and write plans.
|
||
- It covers start/stop, call-home and the setup rewrite, reproduced byte for byte against THOR (counts).
|
||
- `bridges/mm_dry_run.py` prints a write's planned frames from a live unit's reads.
|
||
- The protocol's `_send` gate refuses every write opcode unless explicitly allowed, and `0xA2` always.
|
||
- "**No command has ever been originated against a unit by this project**" is still true, and is now enforced in code.
|
||
|
||
- [ ] **Step 5: Commit and push** the tool and both docs. Message: `feat(bridges): mm_dry_run -- a write's planned frames from a live unit's reads; bench-checked on UM20147`.
|
||
|
||
---
|
||
|
||
## Self-review notes
|
||
|
||
- **Spec coverage:**
|
||
- Encoder: Task 1.
|
||
- Opcode guard (one table; `0xA2`): Task 2.
|
||
- Dry run: Task 4 (`WritePlan.describe()`) and Task 5 (live). The write endpoints' `dry_run=true` parameter arrives with each write in phases 3–5 and returns `describe()`.
|
||
- Frame reproduction for `0x96`/`0x97`, `0x7E`/`0x7F` and the full setup push: Tasks 1, 3 and 4. The `0x71` edit pushes reproduce everything but `0x71`, because field editing is phase 5.
|
||
- Fixtures force-added: Task 3.
|
||
- **Not in phase 2:**
|
||
- Any transmit of a write.
|
||
- The identity check, audit table and read-back framework (phase 3).
|
||
- Field encoding (phase 5).
|
||
- Per-event delete. It is destructive tier; its SUBs are in the opcode table only.
|
||
- Scheduler `0x47` and file `0x8D`/`0x8E` (table only).
|
||
- **Never captured, and so only synthetic:**
|
||
- A checksum on an escape byte.
|
||
- A literal `0x10` in data.
|
||
- Start or stop when the unit is already in that state.
|
||
- Any write on 11.0BD.
|