Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
19 KiB
SFM phase 1c — the webapp on the serial-based endpoints, plus wrong-series safeguards
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: The SFM standalone page (sfm/sfm_webapp.html) drives both series through the serial-based device endpoints. In addition, no MiniMate-only write or erase can reach a unit that has not identified itself as Series 3.
Architecture:
- Server: one helper refuses the legacy Series-3 write/erase routes unless the unit's own serial (read on the same connection) says Series 3.
- Page: the series routing and button rules live in a marked block of pure functions, tested through Node. The DOM wiring calls those functions and nothing else to build a
/device/URL or decide a button's state.
Tech Stack: Python 3.10 / FastAPI (sfm/server.py), vanilla JS in one HTML file, pytest. Node 20 (~/.local/bin/node) runs the page-logic tests.
Spec: docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md covers "The webapp", "Scope: the parity table" rows 1–5 and 7, and "Build phases" 1c. The design agreed with Brian on 2026-10-28 is recorded in the Global Constraints below.
Global Constraints
- Work in worktree
~/seismo-relay-parity, on branchfeat/series4-sfm-parity. Never commit tomain. Check withgit branch --show-currentbefore every commit. - Run tests with
/home/serversdown/seismo-relay/.venv/bin/python -m pytest -q -p no:cacheprovider. The baseline is 16 known failures (15 intest_bw_ascii_report.py, 1 intest_event_file_io.py). Read the failure list before committing. Apytest | tailexits 0. - Serial optional: with a serial, the Live tabs use the serial-based endpoints:
/device/info,/device/monitor/status,/device/settings,/device/events,POST /device/events/download, andPOST /device/monitor/start|stop(all withserial=), plusPOST /device/hangup?host=&tcp_port=. With the serial blank, every read behaves exactly as today. - Series comes from the unit's reply. The badge and every series-specific control follow the
seriesfield of the last/device/inforeply, and only if itsserialequals the typed one. A typed serial alone never enables a series-specific control. - Write buttons:
- Start/stop use the audited serial path for both series.
- Config write and Call-Home write are disabled for both series. Their tooltips read exactly "Coming in phase 5 (#46)" and "Coming in phase 4".
- Diagnostics (erase, rescue, slow drip, blind stop) is enabled only when the confirmed series is 3.
- Hang up is shown only when the confirmed series is 4.
- Start feedback: while a start is in flight, show "Starting — the unit runs its sensor check first (about 35 s)". The legacy 60-second
_pollMonitorConfirmloop is not used in serial mode. - Results are reported as SFM returned them: outcome, verified, state before → after, and the first 8 characters of the audit id. HTTP error
detailstrings are shown verbatim. - Speed (Brian): no new request may be added to a path unless the plan says why. The server identity check reuses the serial that
connect()already reads. OnrescueandPOST /device/call_homeit adds exactly one SUB 0x15 read. - No codec, store or DB change. The legacy
/device/*routes keep their URLs and parameters (a new optionalserialis added).
Review Focus
- A typed
BE…serial at an address that holds a Micromate. The server must refuse every guarded route with 409 and send no write. In the page, Diagnostics stays disabled until/device/infoanswers Series 3. Pinned by Task 1 (test_guarded_route_refuses_a_unit_that_answers_as_series4) and Task 2 (controls: typed serial is not confirmation). - The serial is edited after a successful identify. The confirmation must stop counting the moment the typed serial no longer matches. Pinned by Task 2 (
controls: confirmation drops when the serial changes). - Lower-case or space-padded serials (
" be9441 ") are normalised the same way the server normalises them. Pinned by Task 2 (seriesFromSerialandunitQuerycases). - A start that times out (504) or reads back a mismatch (409). The page must show the server's detail and the audit id, never "started". Pinned by Task 2 (
changeSummarycases forfailed/mismatch) and Task 5 (an error-path render). - A download that is already stored (
inserted: false) is reported as "already stored" and still opens the stored event. Pinned by Task 2 (downloadSummary).
Task 1: Server — legacy Series-3 writes refuse a unit that isn't Series 3
Files:
- Modify:
sfm/server.py:device_config(~1107),device_events_erase(~1427),device_rescue(~1763), thedevice_call_homePOST (~2066);device_config_projectpassesserialthrough.
- Modify:
minimateplus/client.py: addMiniMateClient.read_serial(). - Test: create
tests/test_server_series3_guard.py.
Interfaces:
-
Produces:
MiniMateClient.read_serial(self) -> str. Requires an open, polled session. It runs the SUB 0x15 read (self._require_proto().read(SUB_SERIAL_NUMBER)) and returns_decode_serial_number(...).serial. -
Produces:
sfm.server._require_series3(unit_serial: Optional[str], expected: Optional[str]) -> None. It raisesHTTPException(409, detail)when either:series_for_serial(unit_serial)is not 3 (an unknown serial counts as not 3), with detailf"the unit at this address answers as {unit_serial!r}, not a Series-3 unit -- nothing sent"; orexpectedis given andnormalise_serial(expected) != normalise_serial(unit_serial), with detailf"the unit at this address is {unit_serial}, not {expected} -- nothing sent".
-
Each guarded route gains
serial: Optional[str] = Query(None, description=_SERIAL_DOC). It calls the guard right after it knows the unit's serial, and before its first write:device_configanddevice_events_erase:info = client.connect()→_require_series3(info.serial, serial);device_rescueanddevice_call_home(POST): afterclient.poll()→_require_series3(client.read_serial(), serial).
-
Not guarded, and each gets a one-line comment saying why: legacy
monitor/start|stop,stop_monitoring_blind,stop_monitoring_slow_drip,stop_monitoring_spam. They send only0x96/0x97, which mean the same on both series (measured 2026-10-25/27), and the rescue tools must work on a unit too wedged to answer. -
Step 1: Write the failing tests in
tests/test_server_series3_guard.py. Usemonkeypatch.setattr(srv, "_build_client", factory)astests/test_server_device_access.py:398does. The fake client records every call:test_guarded_route_refuses_a_unit_that_answers_as_series4[route]: parametrise over the four routes. The fake'sconnect()returns aDeviceInfo(serial="UM20147"), or itsread_serial()returns"UM20147". AssertHTTPException.status_code == 409, and that the recorded calls contain no write method (delete_all_events,apply_config,set_call_home_config,stop_monitoring).test_guarded_route_refuses_a_different_series3_unit: the unit answers"BE9441", the request namesserial="BE12599", so the response is 409 with"not BE12599"in the detail.test_guarded_route_proceeds_for_the_named_series3_unit: the unit answers"BE9441"withserial="be9441 "(normalised), and the write method is called once.test_unguarded_stop_routes_send_without_an_identity_read:stop_monitoring_blind(it writes through a bareTcpTransport; stubsrv.TcpTransport) sends its stop frames, and nothing builds a client or reads a serial.
-
Step 2: Run them.
…pytest tests/test_server_series3_guard.py -q→ FAIL (_require_series3/read_serialdon't exist). -
Step 3: Implement
read_serial,_require_series3, theserialquery parameter, and the four guard calls as specified. -
Step 4: Run the new tests plus
tests/test_server_device_access.py→ PASS. Then the full suite → only the 16 known failures. -
Step 5: Commit
fix(sfm): legacy Series-3 writes and erase refuse a unit that does not answer as Series 3.
Task 2: Page — the device-routing block (pure functions) and its Node-run tests
Files:
- Modify:
sfm/sfm_webapp.html. Add one<script>block, delimited by the lines/* <device-routing> */and/* </device-routing> */. It must not touchdocumentorfetch. - Test: create
tests/test_webapp_device_routing.py. It extracts the block, appendsmodule.exports = {…}, and runs cases throughnode -e(viasubprocess, reading JSON on stdout). Skip with a clear reason ifshutil.which("node")isNone.
Interfaces (Produces, used by Tasks 3–6):
-
seriesFromSerial(serial) -> 3 | 4 | null: trims and upper-cases;UM…→ 4,BE…/BA…→ 3 (prefix plus at least one more character), anything else →null. Mirrorssfm/device_access/series.py. -
unitQuery(unit) -> string, whereunit = {serial, host, tcpPort}:- serial mode:
serial=<NORMALISED>&host=<h>&tcp_port=<p>; - blank serial:
host=<h>&tcp_port=<p>; - every value goes through
encodeURIComponent.
- serial mode:
-
deviceUrl(action, unit, params = {}) -> {method, path}:pathis relative, e.g./device/info?serial=…. Actions:info,status,settings,events→ GET;download(needsparams.event_id),start,stop→ POST;hangup→ POST, with noserial(host/port only);- legacy actions:
storage_range,index,erase,rescue,blind_stop,slow_drip,call_home_read(GET/device/call_home),call_home_write,config_write(POST/device/config).
settings,downloadandhangupwith a blank serial returnnull, since there is no legacy equivalent. Unknown actions throw. -
confirmedSeries(unit) -> 3 | 4 | null, whereunit.confirmed = {serial, series}comes from the last/device/inforeply:- returns
unit.confirmed.seriesonly when the normalised typed serial equalsunit.confirmed.serial; - with a blank typed serial, returns
unit.confirmed.seriesfrom a legacy identify; - otherwise
null.
- returns
-
controlsFor(unit) -> {startStop, hangup, diagnostics, callHomeRead, configWrite, callHomeWrite, reasons}, all booleans exceptreasons:startStop= serial mode andconfirmedSeries ∈ {3, 4};hangup=confirmedSeries === 4;diagnostics=confirmedSeries === 3;callHomeRead=confirmedSeries === 3;configWrite=callHomeWrite=false;reasons={configWrite: "Coming in phase 5 (#46)", callHomeWrite: "Coming in phase 4"}.
-
changeSummary(body) -> string, for a ChangeResult JSON (action, outcome, verified, state_before, state_after, audit_id, plan):dry_run→"<action>: dry run — would send <subs comma-joined>";skipped→"<action>: already <state_before> — nothing sent";sent+ok→"<action>: confirmed — <state_before> → <state_after> (audit <id8>)";- anything else →
"<action>: <outcome>, <verified> (audit <id8>)".
-
downloadSummary(body) -> string, for an EventDownload JSON:inserted: false→"already stored — <stored_filename>";- otherwise
"stored <stored_filename>, <filesize> bytes, check: <detail.check>".
-
Step 1: Write the failing test file. Each case is
(function, args, expected)and runs asnodeevaluatingJSON.stringify(fn(...args)). Cases that must be present:seriesFromSerial:"UM20147"→4," be9441 "→3,"BA123"→3,"BE"→null,"XX1"→null.unitQuery: serial mode upper-cases and trims; blank serial omitsserial=; a host with&is encoded.deviceUrl:infowith a serial →{method:"GET", path:"/device/info?serial=BE9441&host=h&tcp_port=9034"};hangup→ noserial;settingswith a blank serial →null;downloadcarriesevent_id.- controls (named for Review Focus 1 and 2):
- typed serial is not confirmation: typed
BE9441withconfirmed:null→diagnostics:false, startStop:false; - confirmed S3: diagnostics true, hangup false;
- confirmed S4: hangup true, diagnostics false, callHomeRead false;
- confirmation drops when the serial changes: confirmed
{serial:"BE9441",series:3}with typedBE9442→ all false; - config/call-home write always false, with the exact reason strings.
- typed serial is not confirmation: typed
changeSummary: one case per outcome, includingfailedwithverified:"not_checked"andsentwithverified:"mismatch".downloadSummary: inserted and already-stored.
-
Step 2: Run → FAIL (no block in the page).
-
Step 3: Implement the block in the page, just before the existing main
<script>'s first function. Exactly the functions above, no DOM. -
Step 4: Run → PASS. Full suite → only the 16 known failures.
-
Step 5: Commit
feat(webapp): the device-routing rules as pure functions, tested through Node.
Task 3: Page — unit bar, series badge, Device tab and status panel, Hang up
Files: Modify sfm/sfm_webapp.html. Test: extend tests/test_webapp_device_routing.py with the static check below.
Interfaces:
-
Consumes:
unitQuery,deviceUrl,confirmedSeries,controlsFor(Task 2). -
Produces: a page-level
currentUnit()returning{serial, host, tcpPort, confirmed}.confirmedis held in a module variable set only byconnectUnit()from the/device/inforeply ({serial: body.serial, series: body.series}), and cleared whenever the serial or host field changes. AlsoapplyControls(), which sets every series-specific control'sdisabled/hiddenstate and tooltip fromcontrolsFor(currentUnit()). Tasks 4–6 callapplyControls()after any state change. -
Step 1: Write the failing static test.
test_every_device_url_is_built_by_deviceUrl: outside the device-routing block, the page source contains no`${api()}/device/and no'/device/string literal. ThedeviceUrlcall sites are the only way to build one. -
Step 2: Run → FAIL (today's page builds them by hand).
-
Step 3: Implement.
- A Serial input beside host/port,
id="dev-serial", with placeholder"BE…/BA… or UM… (optional)". - A badge
id="series-badge"showingSeries 3/Series 4fromconfirmedSeries, or hidden. connectUnit()andrefreshMonitorStatus()go throughdeviceUrl('info'|'status', …). The Device tab and status panel renderUnitInfo/UnitStatusfields with "—" for null (device_timeandevent_countare null on Series 3).- A Hang up button
id="hangup-btn", visible only whencontrolsFor().hangup, which POSTsdeviceUrl('hangup'). - Convert every remaining hand-built
/device/URL todeviceUrl(legacy actions included), so the static test passes. With a blank serial, behaviour is unchanged.
- A Serial input beside host/port,
-
Step 4: Run the page tests and the full suite → PASS, only the 16 known failures.
-
Step 5: Commit
feat(webapp): name a unit by serial; series badge from the unit's own answer; Hang up for Series 4.
Task 4: Page — Events tab by serial
Files: Modify sfm/sfm_webapp.html.
Interfaces:
-
Consumes:
deviceUrl('events'|'download'),downloadSummary(Task 2),currentUnit()(Task 3), and the existingopenSidecarModal(dbEventId)(~line 2780). -
Step 1: Implement. In serial mode, the Events tab lists
EventList.events: index,timestamp,record_type, PVS and peaks, or "—". Each row has a Download button that POSTsdeviceUrl('download', unit, {event_id}), showsdownloadSummary(body)in the status bar, and then callsopenSidecarModal(body.db_event_id)when it isn't null. HTTP errors showdetailverbatim. With a blank serial, the existing legacy list and waveform behaviour is unchanged. -
Step 2: Verify the page tests and the full suite → only the 16 known failures. The bench check covers the live behaviour.
-
Step 3: Commit
feat(webapp): list and download events by serial, for both series.
Task 5: Page — Start/Stop through the audited path
Files: Modify sfm/sfm_webapp.html.
Interfaces:
-
Consumes:
deviceUrl('start'|'stop'),changeSummary,controlsFor().startStop(Task 2). -
Step 1: Implement.
- In serial mode,
startMonitoring()/stopMonitoring()confirm()with"Start monitoring on <serial>?"/"Stop monitoring on <serial>?". - Then POST once (never retried). While a start is in flight, show "Starting — the unit runs its sensor check first (about 35 s)".
- Show
changeSummary(body)for any JSON body, including a 409/502 ChangeResult; showdetailverbatim for an error without one (e.g. 504). - Then call
refreshMonitorStatus(). - Buttons are enabled only by
controlsFor().startStop. - In serial mode the legacy
_pollMonitorConfirmisn't called. With a blank serial, the legacy behaviour is unchanged.
- In serial mode,
-
Step 2: Verify the page tests and the full suite → only the 16 known failures. Task 2's
changeSummarycases cover the 409/mismatchandfailedbodies; the bench check covers the live behaviour. -
Step 3: Commit
feat(webapp): start/stop through the audited serial path, with the honest result.
Task 6: Page — Config, Call Home and Diagnostics gating
Files: Modify sfm/sfm_webapp.html.
Interfaces:
-
Consumes:
deviceUrl('settings'|'call_home_read'|…),controlsFor()(Task 2),applyControls()(Task 3). -
Step 1: Implement.
- Config tab: in serial mode, Read shows
UnitSettings(setup name, record mode, sample rate, record time, histogram interval, geo trigger, notes, with "—" for null). Write is disabled for both series, with the tooltip fromreasons.configWrite. - Call Home tab: read enabled only by
callHomeRead; for Series 4 it says "Not yet available for Series 4". Write is disabled, withreasons.callHomeWrite. - Diagnostics: every button is enabled only by
controlsFor().diagnostics; the erase confirmation stays as is. Diagnostics requests passserialwhen one is typed, so the server guard (Task 1) checks it as well. - With a blank serial, the legacy reads are unchanged, while writes and erase follow
controlsFor. A legacy identify (blank serial) that answers as BE… confirms Series 3.
- Config tab: in serial mode, Read shows
-
Step 2: Verify the page tests and the full suite → only the 16 known failures.
-
Step 3: Commit
feat(webapp): config and call-home writes wait for phases 4-5; Diagnostics only for a confirmed Series-3 unit.
Task 7: Docs
Files: CLAUDE.md (the SFM REST API section, and "Where things stand"), docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md (the 1c entry in Build phases).
-
Step 1: Document:
- the legacy-route Series-3 guard (which routes, why the stop tools are exempt);
- the page's serial mode;
- the
noderequirement fortests/test_webapp_device_routing.py.
No CHANGELOG (feature branch).
-
Step 2: Commit
docs: phase 1c -- the webapp by serial, and the Series-3 guard on legacy writes.
After Task 7 (controller, with Brian, not an implementer task): a bench pass on BE9441 and UM20147, through the bridge or cellular:
- identify;
- status;
- settings read;
- events list and one download each;
- one audited start/stop each (Brian's go per send);
- for the Micromate, Hang up;
- Diagnostics disabled on UM20147, and enabled only after BE9441 identifies.