Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
47 KiB
Phase 3: start / stop monitoring, the first live write — 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. Task 7 is not for a subagent: the controller runs it at the bench, with Brian approving the send.
Goal: Start and stop monitoring by serial, for both series, through the safety layer. The layer covers:
- an identity check right before the write;
- the unit's state, read first;
- a dry run that returns the exact frames;
- an audit row for every attempt;
- a read-back that decides success;
- never a retried write.
Then make the project's first live send to a unit (UM20147), with Brian approving it at the bench.
Architecture:
-
Series 4.
MicromateProtocol.execute(plan)becomes the only write path.- It transmits exactly a
WritePlan's frames, granting permission for that call alone. - It refuses any plan beyond a code-reviewed ceiling,
ENABLEABLE_WRITES = {0x96, 0x97}. - It refuses on a connection whose replies did not carry Micromate flags.
- It transmits exactly a
-
The change operation, one per series:
- re-reads the serial;
- reads the run state,
0x49on Series 4 and0x1Con Series 3; - skips or refuses as appropriate;
- audits the attempt;
- sends;
- polls the state until it matches or a window expires;
- audits the result.
It returns a
ChangeResult. -
No retry.
DeviceAccessruns change operations with no retry of any kind. -
Audit. The table lives in SDM (
device_commandsin SeismoDb). The device side writes to it through an injected sink, sosfm/device_access/still imports no DB. -
Endpoints. The existing
POST /device/monitor/startand/stopgainserial,dry_run,even_if_alreadyandcaller. Withoutserialthey behave exactly as today.
Tech Stack: Python 3, FastAPI, pytest, SQLite.
Spec: docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md, in particular:
- The safety layer (tiers, identity, read-back, audit table);
- Series-4 write path (dry run, start/stop row);
- Testing → Bench (the first-live-send protocol);
- Build phases item 3, including its "Preconditions from the phase-2 final review" block, which is binding.
Global Constraints
- Writes. The only writes are
0x96/0x97.- On Series 4 they go through
MicromateProtocol.execute(plan)only. - On Series 3 they go through
MiniMateClient.start_monitoring()/stop_monitoring(), which are unchanged. - Nothing else may be transmitted that changes a unit.
- Tests use fakes and scripted transports only. No task but Task 7 touches hardware, and Task 7 sends only with Brian's explicit go-ahead in the conversation.
- On Series 4 they go through
- A write is never retried.
- This covers the retry-once in
DeviceAccess._dispatch, the TCP retry inSeries3Adapter._run, and any loop. - The structure must make retry impossible for a change operation. A comment saying so is not enough.
- This covers the retry-once in
- Identity before any write.
- The serial is read from the unit immediately before the write:
0x15on Series 4,connect()on Series 3. - A mismatch means 409 and nothing is sent.
- The serial is read from the unit immediately before the write:
- 0xA2 is never sent.
- The ceiling is
{0x96, 0x97}. - Raising it is a spec change.
- The ceiling is
- The audit is mandatory.
- A live change without an audit sink is refused (501), with nothing sent.
- Every live attempt, including a skip, gets one row.
- Dry runs are not audited: they send nothing.
- Legacy routes are unchanged without
serial.- The only permitted change:
baudbecomesOptional[int] = Query(None)with 38400 applied at the top of the legacy path.
- The only permitted change:
- Schema. The
device_commandstable is additive (CREATE TABLE IF NOT EXISTS). At merge, the changelog must say "schema: new table, no migration, no backfill". - Tiers.
sfm/device_access/must not importsfm.database,sfm.waveform_storeorsfm.server. - The suite. Its 16 pre-existing failures stay exactly that set.
- Branch. Work on
feat/series4-sfm-parity. Never commit tomainordev, do not editCHANGELOG.md, and rungit pushafter each commit. - Never move or modify
bridges/captures/. Port 8200 is another SFM. - Trailers. 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 five things most likely to bite, each with the task that tests it:
- A lost ack. It must never cause a second send, whether through the held-line retry, the Series-3 cold-boot retry, or anything else (Tasks 4, 5).
- A different unit at the address, for example after a modem moved. It must be refused before any write, on a fresh serial read rather than the call-up's cached serial (Tasks 4, 5).
- A unit that is calling home (
0x49=0x03). It is refused, with nothing sent (Task 4). - A clean ack where the state never changes. This also covers a sensor check that delays the change. It is reported as a failed change after the verify window, audited as
mismatch, with every state value seen recorded (Tasks 4, 5). - Write permission leaking.
- After
execute(), the same connection cannot send0x96again without anotherexecute(). - A plan holding
0x7E(call-home) is refused by the ceiling. - A connection that has seen no Micromate-flagged reply cannot execute anything (Task 1).
- After
File map
| file | change |
|---|---|
micromate/opcodes.py |
ENABLEABLE_WRITES |
micromate/protocol.py |
execute(plan); _send(frame, *, permit=); _validate records last_flags |
micromate/models.py |
MicromateRunState |
micromate/client.py |
serial(refresh=); read_run_state() |
sfm/database.py |
device_commands table; begin_device_command, finish_device_command, query_device_commands |
sfm/audit.py |
new: DbAudit, the SDM sink |
sfm/device_access/models.py |
ChangeResult |
sfm/device_access/s4.py |
s4_change_monitoring |
sfm/device_access/s3.py |
Series3Adapter.change_monitoring; _run(retry=) |
sfm/device_access/access.py |
start_monitoring/stop_monitoring; _dispatch(change=); audit=, sleep=, verify_* |
sfm/server.py |
serial branch on /device/monitor/start and /stop; guard paths; GET /db/device_commands; audit wiring |
tests/device_access_fakes.py |
run states, execute, Series-3 start/stop |
| tests | test_micromate_execute.py, test_device_commands.py, test_device_access_change.py, plus additions to test_micromate_client.py and test_server_device_access.py |
Task 1: execute(plan), the ceiling and the flags check
Files:
- Modify:
micromate/opcodes.py - Modify:
micromate/protocol.py(__init__,_validate,_send, newexecute, module docstring) - Test:
tests/test_micromate_execute.py(new)
Interfaces:
-
Produces:
ENABLEABLE_WRITES: frozensetMicromateProtocol.execute(plan: WritePlan) -> list[MicromateFrame], returning the ack framesMicromateProtocol.last_flags: Optional[int]
-
Step 1: Write the failing tests. Create
tests/test_micromate_execute.py:
"""execute(plan): the only write path -- exact frames, one call's permission, a ceiling."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from micromate.framing import FLAGS_THOR, build_request # noqa: E402
from micromate.opcodes import ENABLEABLE_WRITES, OpcodeRefused # noqa: E402
from micromate.protocol import ACK_DATA_LEN, UnexpectedResponse # noqa: E402
from micromate.writes import ( # noqa: E402
plan_call_home_enabled, plan_start_monitoring, plan_stop_monitoring,
)
from test_micromate_protocol import frame, proto # noqa: E402
ACK_START = frame(0x69, bytes(ACK_DATA_LEN))
POLL_RSP = frame(0xA4, bytes(48))
def _ready(responses):
"""A protocol that has already seen one Micromate-flagged reply (a POLL)."""
p, t = proto([POLL_RSP] + responses)
p.poll()
t.written.clear()
return p, t
def test_the_ceiling_is_start_and_stop_only():
assert ENABLEABLE_WRITES == frozenset({0x96, 0x97})
def test_execute_sends_exactly_the_plans_frame_and_returns_the_ack():
p, t = _ready([ACK_START])
acks = p.execute(plan_start_monitoring())
assert t.written == [build_request(0x96, 0xFFFF)]
assert [a.sub for a in acks] == [0x69]
def test_permission_ends_with_the_call():
p, t = _ready([ACK_START])
p.execute(plan_start_monitoring())
with pytest.raises(OpcodeRefused):
p._send(build_request(0x96, 0xFFFF))
assert len(t.written) == 1
def test_a_plan_beyond_the_ceiling_is_refused_and_nothing_is_sent():
content = bytes(5) + b"\x05" + bytes(120)
p, t = _ready([])
with pytest.raises(OpcodeRefused, match="ceiling"):
p.execute(plan_call_home_enabled(content, False))
assert t.written == []
def test_execute_refuses_before_any_micromate_reply_has_been_seen():
p, t = proto([ACK_START])
with pytest.raises(OpcodeRefused, match="Micromate"):
p.execute(plan_start_monitoring())
assert t.written == []
def test_execute_refuses_after_a_non_micromate_flags_reply():
p, t = proto([frame(0xA4, bytes(48), flags=0x10), ACK_START], strict_checksums=False)
p.poll()
t.written.clear()
with pytest.raises(OpcodeRefused):
p.execute(plan_stop_monitoring())
assert t.written == []
def test_a_wrong_ack_sub_raises_after_one_send():
p, t = _ready([frame(0x68, bytes(ACK_DATA_LEN))]) # stop's ack, for a start
with pytest.raises(UnexpectedResponse):
p.execute(plan_start_monitoring())
assert len(t.written) == 1
def test_thor_flags_are_accepted_too():
p, t = proto([frame(0xA4, bytes(48), flags=FLAGS_THOR), frame(0x68, bytes(ACK_DATA_LEN))])
p.poll()
p.execute(plan_stop_monitoring())
assert t.written[-1] == build_request(0x97, 0xFFFF)
Before you write any code, make two checks:
- In
tests/test_micromate_protocol.py, check thatScriptedTransportexposes.writtenas a list you can.clear(), and thatframe(..., flags=)exists. - Check that
micromate.framingexportsFLAGS_THORandFLAGS_BLASTWARE.
If either differs, adapt the helper calls only, and say so.
-
Step 2: Run the tests and watch them fail. Run:
.venv/bin/python -m pytest tests/test_micromate_execute.py -qExpected: an ImportError onENABLEABLE_WRITES. -
Step 3: Implement.
In
micromate/opcodes.py, add after the tables:
# The write SUBs any code may transmit at all -- through MicromateProtocol.execute,
# one call at a time. Raising this is a spec change, reviewed like one: delete
# (0xA8/0xAA), raw file writes (0x8D/0x8E -- they could reach the modem
# settings) and 0xA2 never belong here without one.
ENABLEABLE_WRITES = frozenset({0x96, 0x97})
In micromate/protocol.py:
- Imports: add
FLAGS_BLASTWAREandFLAGS_THORto thefrom .framing import ...line. AddENABLEABLE_WRITESandOpcodeRefusedto the.opcodesimport. - In
__init__, addself.last_flags: Optional[int] = None. - In
_validate, beforereturn frame, addself.last_flags = frame.flags. - Replace
_sendwith:
def _send(self, frame: bytes, *, permit: frozenset = frozenset()) -> None:
# The gate sees the bytes about to go out, not the caller's intent.
# `permit` is passed only by execute(), for exactly one step.
frame = bytes(frame)
check_transmit(request_sub(frame), self._allowed_writes | permit)
log.debug("TX %d bytes: %s", len(frame), frame.hex())
self._transport.write(frame)
- Add after
_exchange:
def execute(self, plan) -> list:
"""Transmit a `micromate.writes.WritePlan` -- the only write path.
Permission is granted for this call alone, one step at a time, and only
for SUBs under `ENABLEABLE_WRITES`. Refuses unless the last reply on
this connection carried Micromate flags (0xC5 / 0x03). Each step's ack
is awaited before the next is sent. Never retries: a timeout raises,
and what happened is the caller's to find out by reading the unit back.
"""
beyond = plan.subs - ENABLEABLE_WRITES
if beyond:
raise OpcodeRefused(
"plan holds SUB(s) above the write ceiling: "
+ ", ".join(f"0x{s:02X}" for s in sorted(beyond)))
if self.last_flags not in (FLAGS_BLASTWARE, FLAGS_THOR):
raise OpcodeRefused(
"no Micromate-flagged reply seen on this connection -- "
"refusing to write")
acks = []
for step in plan.steps:
self._parser.reset()
self._pending.clear()
self._send(step.frame, permit=frozenset({step.sub}))
acks.append(self._recv_one(expected_sub=step.ack_sub, reset_parser=False))
return acks
-
Module docstring: in the scope paragraph, add one sentence.
execute(plan)is the only write path: one call's permission, at mostENABLEABLE_WRITES, and only on a connection that has had Micromate-flagged replies. -
Step 4: Run the tests and watch them pass. Run:
.venv/bin/python -m pytest tests/test_micromate_execute.py tests/test_micromate_opcodes.py tests/test_micromate_protocol.py -qExpected: all pass. -
Step 5: Full suite, then commit and push. Message:
feat(micromate): execute(plan) -- the only write path, one call's permission, a start/stop ceiling.
Task 2: The unit's run state and a fresh serial
Files:
- Modify:
micromate/models.py,micromate/client.py - Test:
tests/test_micromate_client.py(append)
Interfaces:
-
Produces:
MicromateRunState(code: int, name: str), wherenameis one of"idle"/"monitoring"/"calling_home"/"unknown(0xNN)".MicromateClient.read_run_state() -> MicromateRunStateMicromateClient.serial(*, refresh: bool = False) -> str
-
Step 1: Write the failing tests. Append to
tests/test_micromate_client.py:
# ── run state (0x49) and a fresh serial ───────────────────────────────────────
import json as _json # noqa: E402
_WRITES = Path(__file__).parent / "fixtures" / "micromate-writes"
def _captured_0x49():
ex = _json.loads((_WRITES / "monitor-start-stop.json").read_text())["exchanges"]
return [bytes.fromhex(e["response_data"]) for e in ex if e["sub"] == 0x49]
def test_run_state_names_thors_captured_states():
datas = _captured_0x49()
names = []
for d in datas:
mm, _t = client([frame(0xB6, d)])
names.append(mm.read_run_state().name)
assert "idle" in names and "monitoring" in names
@pytest.mark.parametrize("code,name", [(0x00, "idle"), (0x02, "monitoring"),
(0x03, "calling_home"), (0x07, "unknown(0x07)")])
def test_run_state_names_every_value(code, name):
data = bytes(11) + bytes([code]) + bytes(4)
mm, _t = client([frame(0xB6, data)])
st = mm.read_run_state()
assert (st.code, st.name) == (code, name)
def test_serial_refresh_reads_the_unit_again():
mm, t = client([frame(0xEA, bytes(11) + b"UM20147\x00\x00\x00")])
mm._serial = "UM99999" # a stale cached serial
assert mm.serial(refresh=True) == "UM20147"
assert len(t.written) == 1
Before running, check two things:
-
client()andframe()exist in this file with those shapes. If they differ, adapt the calls. -
The response SUBs:
0x49gives0xFF-0x49 = 0xB6, and0x15gives0xEA. -
Step 2: Run the tests and watch them fail. Run:
.venv/bin/python -m pytest tests/test_micromate_client.py -q -k "run_state or refresh"Expected:AttributeError: ... 'read_run_state'. -
Step 3: Implement.
In
micromate/models.py, add:
@dataclass(frozen=True)
class MicromateRunState:
"""`SUB 0x49` content[0]. 0x00 idle, 0x02 monitoring, 0x03 calling home
(ten of ten in the 10-14 ACH session); anything else is named, not guessed."""
code: int
name: str
In micromate/client.py:
- Import
MicromateRunState. - Change
serialtodef serial(self, *, refresh: bool = False) -> str:, with the conditionif refresh or self._serial is None:. Document that a change operation refreshes it right before writing. - Add after
serial:
_RUN_STATES = {0x00: "idle", 0x02: "monitoring", 0x03: "calling_home"}
def read_run_state(self) -> MicromateRunState:
"""`SUB 0x49` -> the unit's run state, with the in-call-home value kept
(connect()'s `monitoring` bool flattens 0x03 into True)."""
c = _content(self._proto.read_state())
if not c:
raise ProtocolError("0x49 state reply has no content")
code = c[_STATE_FLAG]
return MicromateRunState(code, self._RUN_STATES.get(code, f"unknown(0x{code:02X})"))
- Step 4: Run the tests and watch them pass. Then run the full suite, commit and push.
Message:
feat(micromate): read the unit's run state and refresh its serial on demand.
Task 3: The audit table and its sink
Files:
- Modify:
sfm/database.py. Add to_SCHEMA, plus three methods. - Create:
sfm/audit.py - Modify:
sfm/server.py, forGET /db/device_commands - Test:
tests/test_device_commands.py(new)
Interfaces:
-
Produces:
SeismoDb.begin_device_command(*, serial, series, address, action, tier, request: dict, caller: str) -> strSeismoDb.finish_device_command(command_id, *, outcome, verified, ack: Optional[dict], error: Optional[str]) -> NoneSeismoDb.query_device_commands(serial=None, limit=100) -> list[dict], newest first, withrequestandackparsed back from JSON.DbAudit(get_db: Callable[[], SeismoDb])withbegin(**fields) -> strandfinish(command_id, **fields).
-
Step 1: Write the failing tests in
tests/test_device_commands.py:
"""The device_commands audit table: one row per change attempt, pending -> result."""
from __future__ import annotations
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sfm.audit import DbAudit # noqa: E402
from sfm.database import SeismoDb # noqa: E402
ROW = dict(serial="UM20147", series=4, address="serial:/dev/ttyACM0",
action="start monitoring", tier="change",
request={"plan": {"steps": [{"sub": "0x96"}]}}, caller="test")
def test_a_command_is_pending_until_finished(tmp_path):
db = SeismoDb(tmp_path / "s.db")
cid = db.begin_device_command(**ROW)
row = db.query_device_commands(serial="UM20147")[0]
assert (row["id"], row["outcome"], row["verified"]) == (cid, "pending", None)
assert row["request"]["plan"]["steps"][0]["sub"] == "0x96"
db.finish_device_command(cid, outcome="sent", verified="ok",
ack={"subs": ["0x69"]}, error=None)
row = db.query_device_commands(serial="UM20147")[0]
assert (row["outcome"], row["verified"], row["ack"]) == ("sent", "ok", {"subs": ["0x69"]})
assert row["finished_ts"]
def test_the_table_survives_reopening(tmp_path):
SeismoDb(tmp_path / "s.db").begin_device_command(**ROW)
assert len(SeismoDb(tmp_path / "s.db").query_device_commands()) == 1
def test_db_audit_is_a_thin_sink(tmp_path):
db = SeismoDb(tmp_path / "s.db")
audit = DbAudit(lambda: db)
cid = audit.begin(**ROW)
audit.finish(cid, outcome="failed", verified="mismatch", ack=None, error="unit reads idle")
row = db.query_device_commands()[0]
assert (row["outcome"], row["verified"], row["error"]) == ("failed", "mismatch", "unit reads idle")
-
Step 2: Run them, and watch them fail (ImportError).
-
Step 3: Implement.
- Append to
_SCHEMAinsfm/database.py:
- Append to
CREATE TABLE IF NOT EXISTS device_commands (
id TEXT PRIMARY KEY,
ts TEXT NOT NULL, -- when the attempt began (UTC ISO)
finished_ts TEXT,
serial TEXT NOT NULL,
series INTEGER NOT NULL,
address TEXT NOT NULL,
action TEXT NOT NULL, -- e.g. "start monitoring"
tier TEXT NOT NULL, -- "change" | "destructive"
request TEXT, -- JSON: parameters + the planned frames (hex)
ack TEXT, -- JSON: ack summary
verified TEXT, -- "ok" | "mismatch" | "not_checked"
outcome TEXT NOT NULL, -- "pending" | "sent" | "skipped" | "failed"
error TEXT,
caller TEXT -- "webapp" | "terra-view" | "script" | ...
);
CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts);
- Add the methods to
SeismoDb. Use the existing_new_id()and_connect(),json.dumps/json.loadsforrequest/ack, and a UTC ISO string forts/finished_ts. query_device_commandsorders byts DESC.- Create
sfm/audit.py:
"""The SDM side of the device audit: DeviceAccess calls this sink, which writes
SeismoDb.device_commands. Kept here so sfm.device_access never imports the DB."""
from __future__ import annotations
from typing import Any, Callable
class DbAudit:
def __init__(self, get_db: Callable[[], Any]) -> None:
self._get_db = get_db
def begin(self, **fields: Any) -> str:
return self._get_db().begin_device_command(**fields)
def finish(self, command_id: str, **fields: Any) -> None:
self._get_db().finish_device_command(command_id, **fields)
-
Add
GET /db/device_commands, with paramsserial: Optional[str] = Query(None)andlimit: int = Query(100). It returns{"commands": _get_db().query_device_commands(serial, limit)}. Put it near the other/db/*reads. -
Step 4: Run the tests and watch them pass. Then run the full suite, commit and push. Message:
feat(sfm): device_commands audit table -- one row per change attempt.
Task 4: The Series-4 change operation and DeviceAccess.start_monitoring / stop_monitoring
Files:
- Modify:
sfm/device_access/models.py(addChangeResult),sfm/device_access/s4.py(adds4_change_monitoring),sfm/device_access/access.py,sfm/device_access/__init__.py - Modify:
tests/device_access_fakes.py - Test:
tests/test_device_access_change.py(new)
Interfaces:
-
Consumes: Task 1 (
execute), Task 2 (read_run_state,serial(refresh=)), and the phase-2plan_start_monitoring/plan_stop_monitoring. -
Produces:
ChangeResult, with the fields shown below.DeviceAccess(..., audit=None, sleep=time.sleep, verify_timeout_s=60.0, verify_interval_s=2.0)DeviceAccess.start_monitoring(address, serial, *, dry_run=False, even_if_already=False, caller="api") -> ChangeResult, and the same forstop_monitoring.
-
Step 1: Extend the fakes. In
tests/device_access_fakes.py, giveFakeMicromateClientthese keyword arguments:run_states=None, a list of codes consumed one perread_run_state()call, with the last one repeating; it defaults to[0x00];serial_reported=None, defaulting toserial;execute_error=None.
Then add these methods:
def serial(self, *, refresh=False):
self._step("serial")
return self.serial_reported
def read_run_state(self):
from micromate.models import MicromateRunState
self._step("read_run_state")
code = self.run_states.pop(0) if len(self.run_states) > 1 else self.run_states[0]
names = {0x00: "idle", 0x02: "monitoring", 0x03: "calling_home"}
return MicromateRunState(code, names.get(code, f"unknown(0x{code:02X})"))
On _FakeProtocol, add:
def execute(self, plan):
self._owner._step("execute")
self._owner.executed.append(plan)
if self._owner.execute_error is not None:
raise self._owner.execute_error
return [type("Ack", (), {"sub": s.ack_sub, "data": bytes(11)})() for s in plan.steps]
Also add self.executed = [] to FakeMicromateClient.__init__.
- Step 2: Write the failing tests in
tests/test_device_access_change.py:
"""Start/stop through the safety layer: identity, state, dry run, audit, read-back, no retry."""
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 device_access_fakes import FakeMicromateClient # noqa: E402
from sfm.device_access.access import DeviceAccess # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
CallHomeInProgress, NotSupported, WrongUnit,
)
from sfm.device_access.models import UnitAddress # noqa: E402
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
class Audit:
def __init__(self):
self.rows = {}
def begin(self, **f):
cid = f"c{len(self.rows) + 1}"
self.rows[cid] = dict(f, outcome="pending")
return cid
def finish(self, cid, **f):
self.rows[cid].update(f)
def access(fake, audit="default"):
return DeviceAccess(s4_client_factory=lambda a, **kw: fake, start_reaper=False,
audit=Audit() if audit == "default" else audit,
sleep=lambda s: None, verify_timeout_s=6.0, verify_interval_s=2.0)
def test_a_dry_run_returns_the_exact_frames_and_sends_nothing():
fake = FakeMicromateClient(run_states=[0x00])
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147", dry_run=True)
assert (r.dry_run, r.sent, r.outcome, r.state_before) == (True, False, "dry_run", "idle")
assert r.plan["steps"][0]["frame"] == "41021010009600ffff00000000000000000000a403"
assert fake.executed == [] and da._audit.rows == {}
def test_start_sends_once_and_verifies_by_reading_back():
fake = FakeMicromateClient(run_states=[0x00, 0x00, 0x02])
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert (r.sent, r.outcome, r.verified, r.state_after) == (True, "sent", "ok", "monitoring")
assert len(fake.executed) == 1
row = da._audit.rows[r.audit_id]
assert (row["outcome"], row["verified"], row["action"]) == ("sent", "ok", "start monitoring")
assert r.detail["states_seen"][-1] == "monitoring"
def test_already_in_state_is_skipped_and_audited_as_skipped():
fake = FakeMicromateClient(run_states=[0x02])
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert (r.sent, r.outcome) == (False, "skipped") and fake.executed == []
assert da._audit.rows[r.audit_id]["outcome"] == "skipped"
def test_even_if_already_sends_anyway():
fake = FakeMicromateClient(run_states=[0x02])
r = access(fake).start_monitoring(ADDR, "UM20147", even_if_already=True)
assert r.sent and len(fake.executed) == 1
def test_a_unit_calling_home_is_refused_and_nothing_is_sent():
fake = FakeMicromateClient(run_states=[0x03])
with pytest.raises(CallHomeInProgress):
access(fake).stop_monitoring(ADDR, "UM20147")
assert fake.executed == []
def test_a_different_unit_on_the_fresh_serial_read_is_refused_before_writing():
fake = FakeMicromateClient(serial_reported="UM12947")
with pytest.raises(WrongUnit):
access(fake).start_monitoring(ADDR, "UM20147")
assert fake.executed == []
def test_a_live_change_without_an_audit_sink_is_refused():
fake = FakeMicromateClient()
with pytest.raises(NotSupported, match="audit"):
access(fake, audit=None).start_monitoring(ADDR, "UM20147")
assert fake.executed == []
def test_a_clean_ack_but_no_state_change_is_a_failed_change():
fake = FakeMicromateClient(run_states=[0x00]) # never leaves idle
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert (r.outcome, r.verified, r.state_after) == ("failed", "mismatch", "idle")
assert len(r.detail["states_seen"]) == 4 # 6 s window / 2 s + the first read
assert da._audit.rows[r.audit_id]["verified"] == "mismatch"
def test_a_lost_ack_is_never_retried():
fake = FakeMicromateClient(run_states=[0x00, 0x02],
execute_error=mm_proto.TimeoutError("no ack"))
da = access(fake)
r = da.start_monitoring(ADDR, "UM20147")
assert len(fake.executed) == 1
assert (r.outcome, r.state_after) == ("failed", "monitoring")
assert "no ack" in r.detail["error"]
assert da._audit.rows[r.audit_id]["outcome"] == "failed"
def test_a_change_on_a_dropped_held_line_is_not_retried():
fake = FakeMicromateClient(run_states=[0x00])
da = access(fake)
da.status(ADDR, "UM20147") # hold the line
fake.fail = [mm_proto.TimeoutError("peer gone")] # next call fails
with pytest.raises(Exception):
da.start_monitoring(ADDR, "UM20147")
assert fake.executed == [] # never reached the write, never re-tried
Before running, check FakeMicromateClient.status's call sequence, so the fail queue in the last test hits the first call of the change. Adapt the queue position if needed, and say so in the report.
-
Step 3: Run the tests and watch them fail (AttributeError:
start_monitoring). -
Step 4: Implement.
sfm/device_access/models.py, append:
@dataclass
class ChangeResult:
"""The outcome of a change request. `outcome`: "dry_run" | "skipped" | "sent" |
"failed". `verified`: "ok" | "mismatch" | "not_checked". `plan` is the exact
frames planned (dry run) or sent."""
serial: str
series: int
action: str
dry_run: bool
sent: bool
outcome: str
verified: str
state_before: Optional[str]
state_after: Optional[str]
audit_id: Optional[str]
plan: Dict[str, Any] = field(default_factory=dict)
detail: Dict[str, Any] = field(default_factory=dict)
sfm/device_access/s4.py, add:
- imports:
from micromate.writes import plan_start_monitoring, plan_stop_monitoring, plusChangeResult,CallHomeInProgress,NotSupportedandWrongUnitwhere not already imported; - the function below. It is a plain function;
DeviceAccesscalls it insidesession.run.
def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool,
even_if_already: bool, audit: Any, address: UnitAddress,
caller: str, sleep: Callable[[float], None],
verify_timeout_s: float, verify_interval_s: float) -> ChangeResult:
"""Identity -> state -> (dry run | skip | audit -> send -> read back -> audit)."""
action = "start monitoring" if start else "stop monitoring"
want = "monitoring" if start else "idle"
reported = normalise_serial(client.serial(refresh=True))
if reported != serial:
raise WrongUnit(f"asked for {serial} but {reported} answered at {address.key} -- "
"nothing sent")
before = client.read_run_state()
if before.name == "calling_home":
raise CallHomeInProgress(_RING_MESSAGE)
plan = plan_start_monitoring() if start else plan_stop_monitoring()
base = dict(serial=serial, series=4, action=action, plan=plan.describe(),
state_before=before.name)
if dry_run:
return ChangeResult(dry_run=True, sent=False, outcome="dry_run",
verified="not_checked", state_after=None, audit_id=None, **base)
if audit is None:
raise NotSupported("no audit log is configured -- SFM refuses to change a unit "
"without one (nothing sent)")
request = {"plan": plan.describe(), "even_if_already": even_if_already}
cid = audit.begin(serial=serial, series=4, address=address.key, action=action,
tier="change", request=request, caller=caller)
if before.name == want and not even_if_already:
audit.finish(cid, outcome="skipped", verified="not_checked", ack=None,
error=f"already {want}")
return ChangeResult(dry_run=False, sent=False, outcome="skipped",
verified="not_checked", state_after=before.name,
audit_id=cid, detail={"reason": f"the unit is already {want}"}, **base)
try:
acks = client.protocol.execute(plan)
except Exception as exc: # noqa: BLE001 -- recorded, never retried
after = _try_run_state(client)
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
error=f"no clean ack: {exc}")
if after is None:
raise # the line is suspect: let _exchange hang up
return ChangeResult(dry_run=False, sent=True, outcome="failed",
verified="not_checked", state_after=after, audit_id=cid,
detail={"error": f"no clean ack: {exc}"}, **base)
ack = {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]}
seen = [before.name]
polls = int(verify_timeout_s // verify_interval_s)
for _ in range(polls):
sleep(verify_interval_s)
seen.append(client.read_run_state().name)
if seen[-1] == want:
break
ok = seen[-1] == want
audit.finish(cid, outcome="sent" if ok else "failed", verified="ok" if ok else "mismatch",
ack=ack, error=None if ok else f"unit reads {seen[-1]}, expected {want}")
return ChangeResult(dry_run=False, sent=True, outcome="sent" if ok else "failed",
verified="ok" if ok else "mismatch", state_after=seen[-1],
audit_id=cid, detail={"states_seen": seen, "ack": ack}, **base)
def _try_run_state(client: Any) -> Optional[str]:
try:
return client.read_run_state().name
except Exception: # noqa: BLE001
return None
Check the poll count against the test's expectation. With a 6 s window and a 2 s interval, the loop gives 3 reads after the first, so 4 in total. Keep the test and the code consistent. If you change one, say which in the report.
In sfm/device_access/access.py:
- Constructor: add the keyword arguments
audit: Any = None,sleep: Callable[[float], None] = time.sleep,verify_timeout_s: float = 60.0andverify_interval_s: float = 2.0, and store them, withself._audit = audit. - Add
change: bool = Falseto_dispatch. Make the Series-4 retry conditionif was_held and not change and isinstance(exc, (NoAnswer, ConnectFailed)):, and update the comment: a change is never retried, by construction. - Add the public methods:
def start_monitoring(self, address: UnitAddress, serial: str, *, dry_run: bool = False,
even_if_already: bool = False, caller: str = "api") -> ChangeResult:
return self._change_monitoring(address, serial, start=True, dry_run=dry_run,
even_if_already=even_if_already, caller=caller)
def stop_monitoring(self, address: UnitAddress, serial: str, *, dry_run: bool = False,
even_if_already: bool = False, caller: str = "api") -> ChangeResult:
return self._change_monitoring(address, serial, start=False, dry_run=dry_run,
even_if_already=even_if_already, caller=caller)
def _change_monitoring(self, address, serial, *, start, dry_run, even_if_already, caller):
kw = dict(start=start, dry_run=dry_run, even_if_already=even_if_already,
audit=self._audit, address=address, caller=caller, sleep=self._sleep,
verify_timeout_s=self._verify_timeout_s,
verify_interval_s=self._verify_interval_s)
return self._dispatch(
address, serial,
lambda a, s: self._s3.change_monitoring(a, s, **kw),
lambda c, s: s4_change_monitoring(c, s, **kw),
change=True)
self._s3.change_monitoring arrives in Task 5. Until then, add a stub on Series3Adapter that raises NotSupported("Series 3 start/stop through DeviceAccess arrives in Task 5"), so this task's tests run.
-
Export
ChangeResultfrom__init__.py. -
Step 5: Run the tests and watch them pass. Run:
.venv/bin/python -m pytest tests/test_device_access_change.py tests/test_device_access*.py -qExpected: all pass. -
Step 6: Full suite, then commit and push. Message:
feat(sfm): start/stop monitoring for Series 4 -- identity, state, dry run, audit, read-back, never retried.
Task 5: The Series-3 change operation
Files:
- Modify:
sfm/device_access/s3.py - Modify:
tests/device_access_fakes.py - Test:
tests/test_device_access_change.py(append)
Interfaces:
-
Produces:
Series3Adapter.change_monitoring(address, serial, **kw) -> ChangeResult, with the same keyword arguments ass4_change_monitoring.Series3Adapter._run(address, fn, timeout=None, retry=True)
-
Step 1: Extend the fakes. On
FakeMiniMateClient:- add the keyword arguments
monitor_states=None(a list of bools consumed byget_monitor_status(), with the last one repeating; it defaults to[monitoring]) andwrite_error=None; - add
self.writes = []; - add
start_monitoring()andstop_monitoring(). Each_steps, appends its name towrites, and raiseswrite_errorif one is set; - make
get_monitor_status()consumemonitor_states.
- add the keyword arguments
-
Step 2: Write the failing tests (append to
tests/test_device_access_change.py):
# ── Series 3 ──────────────────────────────────────────────────────────────────
import minimateplus.protocol as mmp_proto # noqa: E402
from device_access_fakes import FakeMiniMateClient # noqa: E402
TCP3 = UnitAddress(host="10.0.0.6", tcp_port=12345, port=None, baud=None)
def access3(fake, audit="default"):
seen = []
def factory(a, **kw):
seen.append(kw)
return fake
da = DeviceAccess(s3_client_factory=factory, start_reaper=False,
audit=Audit() if audit == "default" else audit,
sleep=lambda s: None, verify_timeout_s=6.0, verify_interval_s=2.0)
da.factory_calls = seen
return da
def test_series3_dry_run_returns_its_own_frame_and_sends_nothing():
fake = FakeMiniMateClient(monitor_states=[False])
r = access3(fake).start_monitoring(TCP3, "BE18193", dry_run=True)
assert (r.series, r.outcome, r.state_before) == (3, "dry_run", "idle")
assert r.plan["steps"][0]["sub"] == "0x96" and fake.writes == []
def test_series3_start_is_verified_by_monitor_status():
fake = FakeMiniMateClient(monitor_states=[False, False, True])
da = access3(fake)
r = da.start_monitoring(TCP3, "BE18193")
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "monitoring")
assert fake.writes == ["start_monitoring"]
def test_series3_wrong_unit_is_refused_before_writing():
fake = FakeMiniMateClient(serial="BE11529")
with pytest.raises(WrongUnit):
access3(fake).stop_monitoring(TCP3, "BE18193")
assert fake.writes == []
def test_series3_a_lost_ack_is_never_retried_even_over_tcp():
fake = FakeMiniMateClient(monitor_states=[False, True],
write_error=mmp_proto.TimeoutError("no ack"))
da = access3(fake)
r = da.start_monitoring(TCP3, "BE18193")
assert fake.writes == ["start_monitoring"] # one send, no cold-boot retry
assert r.outcome == "failed" and r.state_after == "monitoring"
-
Step 3: Run them and watch them fail (the Task 4 stub raises NotSupported).
-
Step 4: Implement. In
sfm/device_access/s3.py:_rungainsretry: bool = True. In itsexcept NoAnswer:, addif not retry or not address.host: raise.- Replace the stub with
change_monitoring. It followss4_change_monitoringstep for step:info = client.connect()andself._check(info.serial, serial, address). This is the fresh identity read:connect()reads0x15.before = "monitoring" if client.get_monitor_status().is_monitoring else "idle".- The dry-run plan, built from
minimateplus.framing.build_bw_write_frame(SUB_START_MONITORING or SUB_STOP_MONITORING, b""). Take the SUB constants fromminimateplus.protocol. Shape it as{"action", "sends_nothing": True, "steps": [{"sub": "0x96", "what": ..., "offset": "0x0000", "data_len": 0, "expect_ack": "0x69", "frame": <hex>}]}, the same shape as Series 4. - The audit, skip, send (
client.start_monitoring()/stop_monitoring()), read-back poll and audit-finish logic, identical in shape to Series 4. There is nocalling_homestate on Series 3. - Call
self._run(address, op, timeout=S3_EVENT_TIMEOUT, retry=False).
- Factor the shared poll/audit tail out of
s4_change_monitoringinto a helper in a new module,sfm/device_access/change.py, if that keeps both short. Do not duplicate 40 lines.
-
Step 5: Run the tests and watch them pass, then the full suite, then commit and push. Message:
feat(sfm): start/stop monitoring for Series 3 through the same safety layer.
Task 6: The endpoints
Files:
- Modify:
sfm/server.py. Changedevice_monitor_startanddevice_monitor_stop, add to_SERIAL_AWARE_PATHS, and build_device_access_instancewithaudit=DbAudit(_get_db). - Test:
tests/test_server_device_access.py(append)
Interfaces:
- Produces:
POST /device/monitor/startandPOST /device/monitor/stop. Each gainsserial,dry_run: bool = False,even_if_already: bool = Falseandcaller: Optional[str] = None, and returns theChangeResultas JSON. The HTTP status:
| case | status |
|---|---|
| dry_run, skipped, sent and verified ok | 200 |
failed with verified "mismatch" |
409 |
| any other failed | 502 |
a DeviceError |
its own status |
-
Step 1: Write the failing tests. Append direct-call handler tests. Build each
DeviceAccesswith the fakes and anAuditrecorder, and monkeypatchsrv._device_access_instance. Cover:- a dry run returns 200 with the frame;
- a live start that verifies returns 200;
- a mismatch returns 409 with the body still holding
states_seen; - a lost ack where the state read back fine returns 502;
/device/monitor/startwithoutserialruns the legacy code unchanged. Use the same "legacy untouchable" pattern as the existing events test: monkeypatch_device_accessto raise, and monkeypatch_build_clientto raise a sentinel.- Add both paths to the guard test's "allowed" list.
-
Step 2: Run them and watch them fail.
-
Step 3: Implement.
baudparameter:baudbecomesOptional[int] = Query(None)on both routes.- New parameters: append
serial: Optional[str] = Query(None, description=_SERIAL_DOC),dry_run: bool = Query(False),even_if_already: bool = Query(False)andcaller: Optional[str] = Query(None). - Docstring: add a paragraph. With
serial: identity check, state first, dry run, audit, read-back, never retried. The response is the ChangeResult. Withoutserial: the legacy behaviour below. - Serial branch: put it first in each route, then
baud = 38400 if baud is None else baudbefore the legacy code.
if serial:
return _change_response(lambda: _device_access().start_monitoring(
_unit_address(port, baud, host, tcp_port), serial, dry_run=dry_run,
even_if_already=even_if_already, caller=caller or "api"))
- The helper:
def _change_response(fn) -> JSONResponse:
try:
result = fn()
except DeviceError as exc:
raise HTTPException(status_code=exc.http_status, detail=str(exc)) from exc
status = 200
if result.outcome == "failed":
status = 409 if result.verified == "mismatch" else 502
return JSONResponse(status_code=status, content=dataclasses.asdict(result))
-
Wiring:
_device_access_instance = DeviceAccess(audit=DbAudit(_get_db)). ImportDbAuditfromsfm.audit. -
Guard: add
"/device/monitor/start"and"/device/monitor/stop"to_SERIAL_AWARE_PATHS. -
Step 4: Run the tests, watch them pass, then the full suite, commit and push. Message:
feat(sfm): start/stop monitoring by serial -- dry run, audit, read-back.
Task 7: The first live send, at the bench (controller and Brian, not a subagent)
Run only with Brian present and saying go. UM20147 is on /dev/ttyACM0 (sg dialout). SFM runs on port 8299 with a scratch database, through the phase-1b launcher pattern (patch _DEFAULT_DB_PATH, write a PID file, start and stop in one command). Log micromate.protocol at DEBUG, so every TX/RX frame is recorded.
-
Dry run, both actions:
POST /device/monitor/start?serial=UM20147&port=/dev/ttyACM0&dry_run=true- the same for
/stop
Show Brian the state and the exact frame. It must be
41021010009600ffff00000000000000000000a403for start, byte-identical to THOR's. -
Brian says go: a live
POST /device/monitor/start. Record:- the HTTP status and body;
- the debug TX/RX lines;
states_seen, including any sensor-check interval;- the
device_commandsrow.
Confirm on the unit's screen that it is monitoring.
-
Brian says go: a live
POST /device/monitor/stop. Record the same, and confirm on the screen. -
Optional, if Brian wants to settle the open question:
- Stop again with
even_if_already=truewhile idle. This records the ack of a "stop while stopped" (spec: open bench question). - The plain stop-while-idle path is a skip and sends nothing.
- Stop again with
-
Record the results:
docs/micromate_protocol_reference.md: a dated, graded entry with the frames, acks, states and timings. It answers "does0x49reflect the change immediately", and records the sensor-check delay if any.CLAUDE.md: retract, in place, "No command has ever been originated against a unit by this project". Add: the first commands were0x96/0x97to UM20147 on , sent by SFM at the bench with Brian's approval.- Trilium: a dev-log entry.
Self-review notes
-
Spec coverage. Build phases item 3 and its six preconditions:
- per-call permission: Task 1;
- ceiling: Task 1;
- never retry: Tasks 4 and 5;
- plan built inside the lock right before sending, with no stored dry-run plan ever sent: Task 4, where the plan is built inside the dispatched operation;
- read state first: Tasks 4 and 5;
- Micromate flags: Task 1.
The safety layer's identity check, audit table and read-back are Tasks 3–5. The dry run is Tasks 4–6. The bench protocol is Task 7.
-
Not in phase 3: call-home writes (phase 4), setup push (phase 5), the dry-run digest echo (optional in the spec, deferred), Series-3 held sessions, and the blind-stop-tool decision (Brian).
-
The verify window. It is 60 s by default. Series 3's sensor check took about 40 s (4-8-26). Series 4's is unmeasured, and Task 7 measures it.