Files
seismo-relay/CLAUDE.md
T
serversdownandClaude Opus 5.5 4c934a2665 docs: trim CLAUDE.md to its rules and a short status (147 KB -> 21 KB)
Every session loaded the whole file at start-up, ~150 KB of it protocol
history.  CLAUDE.md now keeps:

- a short "Where things stand" (goal, checker, Thor, .MLG, device control,
  what is next)
- "Rules that bite": device safety, Series-III framing, constants not to
  "fix", the store, tests and fixtures
- where protocol knowledge lives, the changelog & release convention
  (verbatim), where code goes (ADR 0003), an updated layout, the API

The rest -- the status log, the waveform codec, the protocol gotchas,
field locations, write / monitor / erase / monitor-log / call-home
sections, capture tables, the superseded tier model and the old layout --
moved verbatim to docs/working_notes.md.  A script checked every non-blank
line of the old file: each is in one of the two files except four,
changed on purpose (the intro, and the changelog example's "~2 h" backfill,
now ~8 h as v0.34.0 and v0.35.0 measured).

The last full copy is `git show v0.36.0:CLAUDE.md`.  Code comments that
cite "CLAUDE.md" for a protocol fact now mean docs/working_notes.md, as
both files say.  Suite: 1,806 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-12-04 17:31:20 -05:00

20 KiB
Raw Blame History

CLAUDE.md — seismo-relay

Ground-up Python replacement for Blastware, Instantel's Windows-only software for managing MiniMate Plus seismographs, and for THOR, its Series IV counterpart. The product is SFM: it talks to units over direct RS-232 or cellular modem (Sierra Wireless RV50 / RV55 / RX55), decodes their files, stores the events and serves them to Terra-View. Current version: v0.36.0.

Stack-level context — which repo owns what, and how the three project versions pair — lives in ../terra-view/docs/tmi-stack.md, which is also loaded as ~/CLAUDE.md.

Trimmed 2026-12-04. This file holds the rules and a short status. The protocol notes, field layouts, gotchas and status log that used to fill it moved, verbatim, to docs/working_notes.md. git show v0.36.0:CLAUDE.md is the last full copy. A code comment, plan or changelog entry that cites "CLAUDE.md" for a protocol fact means that file now.


Where things stand (updated 2026-12-04)

Read this first when picking the project back up.

  • Releases. v0.36.0 is on main (2026-12-04, #61). Deploying it needs only scripts/backfill_thor_events.py; the Series-3 decode did not change.
  • 🔑 The goal is full function without Blastware (Brian, 2026-10-29).
    • Today: when a _ASCII.TXT report arrives with a Blastware file, WaveformStore.save_imported_bw overlays its peaks, notes, sample rate and record time onto SFM's decode (event_file_io.apply_report_to_event). Events without a report run on the decoder alone: every DL2 event before 2025, and everything SFM downloads itself.
    • The README roadmap's four steps:
      1. the checker ✅
      2. complete the file-only decode ✅ in the decoder (below); some decoded fields are not stored yet: displacement, time of peak, acceleration, sensor-check results, the Monitor Log line, over-range flags
      3. switch ingest so reports are kept only for checking (retire the overlay)
      4. stop the watchers forwarding reports
    • Until step 3, prod keeps the report as truth wherever one exists.
  • 🔑 The Series-3 decode checker.
    • Running it: scratch/check_s3_decode.py ~/dl2-archive/files ~/dl2-archive/xml decodes each event from its bytes only (no filename, no report) and compares every field, sample and interval with Blastware's _XML.XML: 70,042 events, 2016–2026, ~22 min at --jobs 4. Output goes to ~/dl2-archive/checker-runs/ and is never committed.
    • The rule: every mismatch is SFM's bug unless a carve-out with evidence covers it.
    • Status (v0.35.0, run 20261109-144544): 80 of 88 fields match on every event; every other field matches or is accepted under a carve-out. Left, by Brian's decision (2026-11-11): the vector sum's last digit on 4 waveform/histogram twins, and 4 accelerations (reference D.6.11, D.6.12).
    • Byte layouts of every field read from the file: reference Appendix D.6.
  • Thor (Series IV) files decode per-sample exact against Thor's own CSV exports (3,807,158 / 3,807,165 samples; scratch/verify_thor_against_csv.py). Since v0.36.0 SFM reads a Thor file's settings, notes and event time from the file itself (docs/idf_protocol_reference.md, Signature A).
  • 🔑 Monitor logs (.MLG) and each unit's timeline (v0.35.0).
    • What: every unit sends an .MLG at every call-in, in every mode. SFM reads it (minimateplus/mlg_file.py, reference D.4) and builds each unit's monitoring timeline: sessions, gaps and what they mean, clock steps, call-ins.
    • Why (Brian, 2026-11-09): shot reports need proof that a unit which did not trigger was monitoring. Outage history is the second use.
    • Spec: docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md.
    • Not yet: the watcher does not forward .MLGs (its repo, Brian's call), the DL2 archive is not imported, and Terra-View shows none of it. The prod tables are empty until then.
  • Live device control, both series, by serial (phases 1–5, merged 2026-11-04): identify, status, settings read and change, event list and download, start/stop, call-home on/off. All of it goes through sfm/device_access/; the SFM page is sfm/sfm_webapp.html. Specs: docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md and …/2026-11-03-sfm-phase5-settings-design.md. The Series-4 wire protocol has no unknowns left (docs/micromate_protocol_reference.md).
  • Next, Brian deciding (2026-12-03): retire the overlay (step 3); work-hours recording for both series, replacing THOR's scheduler; finish the .MLG work. Then triage the old open issues, starting with #6.
  • The "offset" hardware fault (a geophone resting off zero; 5 of 45 units, persistent until serviced) has its own journal, docs/offset_investigation.md. Detect it with scratch/offset_scan3.py on the pre-trigger floor; never score only the dominant axis and never use the mean.

The status log as it stood before the trim, with every bench finding and phase history, is the first section of docs/working_notes.md.


Rules that bite

Each of these cost a real bug, a bench session or a near miss. The evidence is in the references and docs/working_notes.md.

Talking to units

  • Every write to a unit goes through sfm/device_access/change.py: a fresh identity read, the run state (calling home or never measured is refused), dry_run (the exact frames, nothing sent), a row in the device_commands audit table, one send never retried, then a read-back. A bench send needs Brian's go for that send.
  • ⚠⚠ SUB 0xA2 is CONFIRM ERASE on Series III and ends a call-home on Series IV: same opcode, same 0x5D reply, opposite consequence. The two stacks share a transport, so dispatch on series before that byte reaches a wire. MicromateProtocol._send refuses 0xA2 always.
  • ⚠ Never write modem baud or modem type remotely. The remote link is the modem port; a mismatch strands the unit until a site visit.
  • ⚠ A MiniMate's open setup menu wins: a change sent while it is open is lost when the operator presses Cancel or Save.
  • Neither series takes a call-home change while monitoring (a MiniMate returns its device-info block; a Micromate acks and ignores it). SFM refuses up front.
  • A monitoring MiniMate answers nothing until woken (41 03, SESSION_RESET, before the POLL) and nothing during its ~30–40 s sensor check after a start.
  • A unit boots when its serial port opens and ignores a POLL sent before its Operating System banner.
  • THOR and SFM share a Micromate modem's single TCP session. A call-home is lost while SFM holds the line. Brian (2026-10-29): keep the hold as it is; the long-term fix is SFM handling call-ins itself.
  • SFM runs a single uvicorn worker: its locks and held lines are per process.
  • Hardware: a Micromate's USB-A host port drives FTDI and CDC-ACM only, never a Prolific PL2303 (lsusb: 0403 works, 067b does not). /dev/ttyACM0 needs sg dialout -c "…" from a shell started before the dialout membership. The modem settings SFM needs (Quiet Mode on, flow control off, …) are in docs/working_notes.md → Required ACEmanager settings.

Series-III framing

  • Every MiniMate request and reply DLE-escapes 02, 03, 04 and 10, payload and checksum alike, and the checksum is SUM8 of the unescaped payload (748 / 748 requests; 7,747 / 7,747 replies, #58). Older notes about "partial stuffing", "raw write frames", a "DLE-aware checksum", "offset_hi 0x10 raw" or "metadata pages 0x1002/0x1004" are retracted misreadings of these same bytes.
  • A 5A read is an ordinary request: a length at a 32-bit linear address, bounded by the full 32-bit end key in the event's STRT record (build_5a_request, parse_strt_end_key). Write frames are ordinary requests too (#46).
  • Response SUB = 0xFF − request SUB, no exceptions.
  • A MiniMate's settings block (1A) is Series IV's 0x1A layout: headed by N = 2090 and read by position (#48). One codec serves both series: micromate/setup_fields.py. ⚠ It reads the keypad's edit buffer live, so unsaved values show while someone is in the menu.
  • S3FrameParser cannot see Micromate replies. A Micromate answers Series-III command frames, but its replies start with a bare STX, carry 0xC5 or 0x03 at payload[1], and give the data length as a uint16 BE at payload[8:10].

Decoding: constants not to "fix"

  • Series-3 geophone full scale is 32,000 counts, not 32,768 (_GEO_INT16_FS in sfm/event_hdf5.py and minimateplus/event_file_io.py). Dividing by 32,768 reads every sample 2.34% low.
  • Thor's geophone LSB is 0.000310308 in/s per count (micromate/idf_file._GEO_LSB_IPS). Series 3's scale does not carry over. Do NOT retune it: the 7 stragglers in 3.8 million samples are Thor's own rounding.
  • Thor's histogram PPV has a 0.0050 in/s display floor. On quiet files SFM's decode is more accurate than Thor's; do not make the decoder match it.
  • Mic: one count = 0.25 Pa (an eighth of that at mic range 1); dB(L) = 81.938216 + 20·log10(|count|).
  • "Units" means three different things (recorded counts, a report's units, the unit's own peaks); keep them apart (reference D.6.6).
  • A walker stops at a tag it does not know rather than raising, so an unhandled block shows up as silently short channels. Check sample counts against ground truth, not only the bundled fixtures.
  • A large DC offset in a waveform is usually the meter, not the decoder. Check Blastware's own export before changing the codec.

The store and the database

  • Events are keyed unit + time + type: UNIQUE(serial, timestamp, record_type). A waveform and its histogram can share a second, so any lookup "by event" must include the type.
  • After any codec change, regenerate the store. Stored .h5 files do not update themselves.
    • Back up seismo_relay.db first.
    • Series 3: scripts/backfill_sidecars.py, then scripts/backfill_event_shape.py. About 8 hours on the office NAS (~1.5 files/s, against ~85/s on the dev box).
    • Series 4 only: scripts/backfill_thor_events.py.
    • TOOL_VERSION in minimateplus/event_file_io.py gates the regeneration; it is bumped at release when the codec changed, so no --force is needed.
  • The DB is seismo_relay.db (default bridges/captures/seismo_relay.db, --db-path to override); migrations live in sfm/database.py.

Tests and fixtures

  • Run the suite with .venv/bin/python -m pytest (the system Python has no numpy). dev's suite is green (v0.36.0: 1,806 passed, 0 failed, 0 skipped), so any FAILED is real. A pytest | tail pipe exits 0: read the failure list.
  • ⚠ A test reads only tracked files. bridges/captures/, example-events/ and most of tests/fixtures/ are gitignored, so a file a test reads from there exists only on this box. Copy what the test needs into tests/fixtures/ and git add -f it (captures go under tests/fixtures/captures/<their folder>/), and do not guard a fixture with a skip: a missing fixture should fail. A fresh worktree is the check.
  • New fixtures go in their own dated subdirectory of tests/fixtures/, named topic then date, e.g. tests/fixtures/mlg-11-9-26/.
  • Text files are LF; tests/test_line_endings.py fails on CRLF. Fixtures keep their bytes.

Where protocol knowledge lives

what document
Series III (MiniMate Plus / BlastMate) docs/instantel_protocol_reference.md
Series IV (Micromate / THOR) docs/micromate_protocol_reference.md
Thor IDF files docs/idf_protocol_reference.md
Blastware's own files (.MLG, event file layouts D.6) docs/instantel_protocol_reference.md Appendix D
The notes moved out of this file docs/working_notes.md
  • Record a new protocol finding in the matching reference. Add a line here only when it changes a rule or the status above.
  • Retractions stay in place. Never delete what turned out to be wrong; mark it retracted, say what replaced it and why. That convention has already saved re-deriving the same mistakes twice.
  • Grade every claim measured or inferred, and do not act on a unit on an unexamined inference.

Changelog & release convention

Feature branches do NOT touch CHANGELOG.md. Write the entry on dev, as part of finishing the merge, under ## Unreleased. Cut the version on dev in a dedicated release commit when you are ready to ship to main.

  • The changelog is written on dev, never on a feature branch. With several branches in flight they all edit the same few lines at the top of the file and conflict every time. Writing it once, after the merge, also lets it describe what actually landed — including anything that changed during conflict resolution.
  • ⚠ The merge is not finished until ## Unreleased is updated. Same sitting, not "later" — that is the one failure mode of writing it after the fact. Reconstruct from the branch's own commit messages: git log --oneline dev..<branch> before you merge, or git log --oneline <merge-base>..<branch> after.
  • No preamble under ## Unreleased — just the ### Added / ### Changed / ### Fixed lists. The themed opening paragraph gets written at release time, when the whole release is visible and can be named honestly. A theme written when the first item landed is stale by the third.
  • ⚠ State the operational consequence on any entry touching the codec, the waveform store, or the DB — including when it is "none." "requires backfill_sidecars.py + backfill_event_shape.py, ~8 h on the NAS", "TOOL_VERSION bumped", "no schema change, no migration". Silence is ambiguous; "none" is information. This repo's changelog is how future-you learns whether a deploy costs hours.
  • Releases are cut on judgement, not on a schedule or a merge. Unreleased is the staging area for whatever is going into the next release; when enough has accumulated to be worth shipping, it gets a number and a date. Nothing about a merge to dev triggers a release.
  • Cutting a release is its own chore(release): vX.Y.Z — <theme> commit on dev, renaming ## Unreleased → ## vX.Y.Z — YYYY-MM-DD and touching: CHANGELOG.md, pyproject.toml, the version line in CLAUDE.md and README.md, and minimateplus/event_file_io.py (TOOL_VERSION) when the codec changed — that constant gates .h5 regeneration.
  • main carries only released versions. No ## Unreleased section there; it lands via the dev → main PR. main lagging dev by a version is normal.

Where code goes

Decided in Terra-View's docs/adr/0003-stack-components-and-names.md (2026-10-27). The old SFM / SDM split is retired; its text is in docs/working_notes.md.

  • SFM is the whole seismograph module: the call-in server, the device adapters, decoding, the store, per-event measurements and the API.
  • The codec library stays pure: minimateplus/{waveform_codec,histogram_codec, event_file_io,bw_ascii_report,blastware_file,mlg_file}.py and micromate/{idf_file,idf_ascii_report}.py take bytes and return objects. They do not import from sfm/, never touch a DB, and read only files passed to them.
  • Lab tools stay out of the production image: bridges/ bench tools, scratch/, seismo_lab.py. One that becomes a real production tool is ported into sfm/, rebuilt on sfm/device_access.
  • Terra-View reads SFM's /db/* and never talks to a unit itself.

Project layout

minimateplus/        Series III: transport, framing, protocol, client, models, and the
                       codecs (waveform_codec, histogram_codec, event_file_io,
                       blastware_file, bw_ascii_report, bw_xml_report, mlg_file, crc)
  decode_check*.py     the checker's comparison rules and carve-outs
micromate/           Series IV: framing, protocol, client, models, setup_block /
                       setup_fields (the 0x1A codec both series use), writes, idf_file
sfm/server.py        FastAPI app: /device/* (live units) and /db/* (the store)
sfm/device_access/   by-serial access for both series; change.py is the write safety core
sfm/database.py      SeismoDb and its migrations; waveform_store.py, event_hdf5.py the store
sfm/mlg_ingest.py, mlg_timeline.py   .MLG import and each unit's timeline
sfm/sfm_webapp.html  the SFM page; its JavaScript is in sfm/static/ (no inline JS)
scripts/             backfills and data maintenance (backfill_*, import_mlg_dir, …)
scratch/             checkers, harnesses, one-off analysis (not in the image)
bridges/             bench tools: probes, MITM relays, captures (not in the image)
tests/               pytest; tests/fixtures/ holds the force-added fixtures
docs/                protocol references, specs and plans (docs/superpowers/), journals

SFM REST API (sfm/server.py)

Live device endpoints (connect to device per-request)

GET  /device/info?port=COM5                              ← serial
GET  /device/info?host=1.2.3.4&tcp_port=9034            ← cellular
GET  /device/events?host=1.2.3.4&tcp_port=9034&baud=38400
GET  /device/events?serial=UM20147&host=...&tcp_port=...  ← list with event_id, either series (no 5A on a MiniMate)
POST /device/events/download?serial=UM20147&event_id=...&host=...  ← download, check, store; returns db_event_id
GET  /device/event?host=1.2.3.4&tcp_port=9034&index=0
GET  /device/monitor/status?host=1.2.3.4&tcp_port=9034  ← battery, memory, mode
POST /device/monitor/start?host=1.2.3.4&tcp_port=9034   ← start recording
POST /device/monitor/stop?host=1.2.3.4&tcp_port=9034    ← stop recording
POST /device/monitor/start?serial=UM20147&host=...&tcp_port=...&dry_run=&even_if_already=  ← audited start, either series
POST /device/monitor/stop?serial=UM20147&host=...&tcp_port=...&dry_run=&even_if_already=   ← audited stop, either series
GET  /device/settings?serial=UM20147&host=1.2.3.4&tcp_port=9034  ← shared-model settings, either series
POST /device/hangup?host=1.2.3.4&tcp_port=9034          ← release a held Series-4 line

serial= (UM = Series 4, BE/BA = Series 3) on /device/info, /connect, /monitor/status, /settings returns the shared model, uncached; on /events and /events/download it lists and downloads by event_id; on /monitor/start and /monitor/stop it runs the audited change (dry_run=true returns the frames and sends nothing; even_if_already=true sends even when the unit is already in that state). A UM serial on any other /device/* route is 501; any request taking the legacy Series-3 path at a held Series-4 address is 409. The legacy Series-3 writes and erase (POST /device/config, /config/project, /events/erase, /rescue, POST /device/call_home) take an optional serial= and refuse 409, nothing sent, when the unit at the address does not answer as Series 3 or is not the named unit. The stop tools (monitor/start|stop without a serial, stop_monitoring_blind, _slow_drip, _spam) are exempt by design. SFM must run a single uvicorn worker (locks and held lines are per process).

Server retries once on ProtocolError for TCP connections (handles cold-boot timing).

DB read endpoints (query seismo_relay.db written by ach_server.py)

GET  /db/units                                           ← all known serials + summary stats
GET  /db/events?serial=BE11529&from_dt=&to_dt=&limit=   ← triggered events, newest first
GET  /db/monitor_log?serial=BE11529&from_dt=&to_dt=     ← monitoring intervals, newest first
GET  /db/sessions?serial=BE11529&limit=50               ← ACH call-home sessions, newest first
PATCH /db/events/{id}/false_trigger?value=true          ← flag/unflag false triggers
GET  /db/device_commands?serial=UM20147&limit=100       ← start/stop audit trail (sent, states), newest first
POST /db/import/mlg_file?serial=&call_in=true           ← Blastware .MLG upload (form field mtimes = JSON {name: unix s UTC})
GET  /db/units/{serial}/timeline?from_dt=&to_dt=        ← sessions, gaps (+ meaning), clock steps, call-ins, from .MLGs
GET  /db/units/{serial}/monitoring_at?at=               ← monitoring / not_monitoring / unknown at a unit-clock time
GET  /db/mlg_records?serial=BE8081&from_dt=&to_dt=      ← raw .MLG records, oldest first
GET  /db/mlg_files/{id}                                 ← the original .MLG, byte for byte

DB file: bridges/captures/seismo_relay.db (default; override with --db-path at startup). All DB endpoints are read-only except PATCH /db/events/{id}/false_trigger and the /db/import/* uploads.