diff --git a/docs/superpowers/plans/2026-11-13-mlg-unit-timeline.md b/docs/superpowers/plans/2026-11-13-mlg-unit-timeline.md new file mode 100644 index 0000000..9cd5572 --- /dev/null +++ b/docs/superpowers/plans/2026-11-13-mlg-unit-timeline.md @@ -0,0 +1,655 @@ +# Monitor logs (.MLG) and each unit's monitoring timeline — 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:** SFM reads Blastware `.MLG` files, stores them, and answers "was unit X monitoring at +time T?" and "when was it not, and why?" from each unit's monitoring timeline. + +**Architecture:** +- **Codec library:** a pure reader and writer in `minimateplus/mlg_file.py`. +- **SFM:** + - two new tables, plus the original files kept in the waveform store + - one ingest function shared by the HTTP route and the bulk-import script + - the timeline as a pure function over stored rows, computed on each request + +**Tech Stack:** Python 3.10, FastAPI, SQLite (`sfm/database.py`), pytest. + +**Spec:** `docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md`. Read it first: the +measured format, session shapes and anti-goals are there and are not repeated here. + +## Global Constraints + +- **Where to work:** worktree `~/seismo-relay-mlg`, branch `feat/mlg-import`. + - Never commit to `dev` or `main`. + - Do not touch `CHANGELOG.md` (it is written on `dev` at merge). +- **Do not edit** `minimateplus/event_file_io.py`, `decode_check.py`, `histogram_codec.py` or + `waveform_codec.py`. Another session owns them; import from them only. +- **Running tests:** `cd ~/seismo-relay-mlg && ~/seismo-relay/.venv/bin/python -m pytest …`. + - The worktree has no venv. The tests put the worktree first on `sys.path`. + - `httpx` is not installed, so `starlette.testclient` tests skip silently. Test routes by + calling the route functions directly. +- **Baseline:** 1,659 passed, 63 skipped, 0 failed. Every commit keeps 0 failed. Read the + summary line, not just the exit code. + - That baseline needs the main checkout's git-ignored fixtures in the worktree. They were + copied on 2026-11-13; without them, 13 `idf`/`save_shape` tests fail. + - If they are missing: `rsync -a --ignore-existing ~/seismo-relay/tests/fixtures/ tests/fixtures/` +- **The codec library stays pure:** `minimateplus/` never imports `sfm`, never touches a DB, + and does no I/O beyond reading a path it was given. +- **The checksum:** CRC-16/AUG-CCITT (poly `0x1021`, init `0x1D0F`, no reflection), over + `record[0:288]`, stored little-endian at `record[290:292]`. Bytes `[288:290]` are `00 00`. +- **The format:** + - prefix `10 00 01 80 00 00 "Instantel\0" 07 2c` (18 bytes), then whole 292-byte records + - each record starts with its length `22 01` (290 LE) + - id `0e a0` is the header record (always first), `0e 80` a log record + - year little-endian in every timestamp +- **Time:** unit times are naive `datetime`s on the unit's own clock, stored with + `.isoformat()` and never converted. File times are aware UTC `datetime`s. +- **Fixtures:** `tests/fixtures/` is git-ignored, so new fixtures need `git add -f`. +- **Docs:** `docs/instantel_protocol_reference.md` is LF (enforced by `tests/test_line_endings.py`). +- **Commit messages** end with: + ``` + Co-Authored-By: Claude Opus 5.5 + Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1 + ``` + +## Review Focus + +1. **An empty file whose name prefix matches two known serials** (`BE11010304.MLG` with both + `BE1101` and `BE11010` known) resolves to the longest, `BE11010`. Test: Task 4, + `test_empty_file_takes_the_longest_known_serial`. +2. **One request with a good file and a corrupted one** stores the good file and refuses the bad + one per file. Nothing of the bad one lands: no row, no file in the store. Test: Task 6, + `test_import_route_stores_good_file_and_refuses_bad_one`. +3. **The same open "monitoring started" record arriving in a second file** (a re-forward, or a + cable download) is stored once, despite its NULL stop. Test: Task 3, + `test_open_record_is_stored_once`. +4. **A serial with no `.MLG` data** gets an empty timeline and `unknown`, never a 500 or a + "not monitoring". Test: Task 6, `test_timeline_routes_for_unknown_serial`. +5. **`at` exactly on a session's start or stop, or inside the repeated hour after the + clock step back,** gives a defined answer: boundaries count as monitoring, and the repeated + hour is `ambiguous`. Tests: Task 5, `test_monitoring_at_boundaries_are_inclusive`, + `test_clock_step_back_is_not_a_negative_gap`. + +--- + +### Task 1: The reader, and one shared CRC + +**Files:** +- Create: `minimateplus/crc.py`, `minimateplus/mlg_file.py`, `tests/test_mlg_file.py` +- Modify: `minimateplus/models.py` (add `MlgRecord`, `MlgFile` after `MonitorLogEntry`) +- Modify: `micromate/setup_block.py:63-69` (`_crc16_aug_ccitt` calls the shared function) +- Fixtures: `tests/fixtures/mlg-11-9-26/` (force-added) + +**Interfaces:** +- Produces: + - `minimateplus.crc.crc16_aug_ccitt(data: bytes) -> int` + - `models.MlgRecord`, with fields: + - `index: int`: position in the file; 0 is the header record + - `start: datetime`, `stop: Optional[datetime]` + - `flags: int`, `trigger_source: int`, `serial: str` + - `text_raw: bytes`: exactly `record[34:288]` + - `event_time: Optional[datetime]` + - `text: str`, `trigger_level: Optional[str]`, `description: str` + - `crc_ok: bool` + - property `is_start` (`flags == 0xFFFF`) + - `models.MlgFile`: + - fields `serial: Optional[str]`, `records: list[MlgRecord]` (log records only, file order) + - properties `empty` (no records and no serial) and `crc_failures -> list[int]` (the indexes) + - `mlg_file.MlgFormatError(ValueError)`, `mlg_file.MLG_PREFIX: bytes`, + `mlg_file.RECORD_SIZE = 292` + - `mlg_file.parse_mlg(data: bytes) -> MlgFile`, `mlg_file.read_mlg(path) -> MlgFile` + +- [ ] **Step 1: Copy the fixtures and force-add them** + +Copy into `tests/fixtures/mlg-11-9-26/` with `cp -p`: +- from `~/dl2-archive/mlg/mlg-slice/`: `BE128443065.MLG`, `BE128443067.MLG`, + `BE128443068.MLG`, `BE128443155.MLG`, `BE128443156.MLG`, `BE6907750.MLG`, `BE6907751.MLG` +- from `~/dl2-archive/mlg/mlg-slice2/`: `BE8081.MLG`, `BE8081321.MLG` +- from `~/seismo-relay/example-events/ach-vs-manual/`: `BE11529.MLG`, `BE115292.MLG` +- from `~/seismo-relay/example-events/10-26-26/`: `BE94412.MLG` + +Then `git add -f tests/fixtures/mlg-11-9-26`. Expected: 12 files, about 14 KB. + +- [ ] **Step 2: Write the failing tests** in `tests/test_mlg_file.py` + +Use `FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"` and +`dt = datetime.datetime`. + +```python +def test_crc_matches_the_micromate_rule(): + from micromate.setup_block import _crc16_aug_ccitt + assert crc16_aug_ccitt(b"123456789") == _crc16_aug_ccitt(b"123456789") == 0xE5CC + +def test_every_fixture_record_passes_its_checksum(): + for p in FIX.glob("*.MLG"): + assert parse_mlg(p.read_bytes()).crc_failures == [], p.name + +def test_closed_records(): # BE128443065 + m = read_mlg(FIX / "BE128443065.MLG") + assert m.serial == "BE12844" and len(m.records) == 2 + r1, r2 = m.records + assert (r1.index, r1.start, r1.stop, r1.flags, r1.trigger_source) == ( + 1, dt(2026, 9, 5, 18, 47, 26), dt(2026, 9, 5, 20, 0, 0), 0x0010, 0) + assert r1.description == "Timer Stop" + assert r1.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)" + assert (r2.start, r2.stop, r2.description) == ( + dt(2026, 9, 6, 6, 0, 13), dt(2026, 9, 6, 18, 45, 0), "Modem Exit") + +def test_monitoring_started_and_an_event(): # BE128443067 + m = read_mlg(FIX / "BE128443067.MLG") + start, ev = m.records[1], m.records[2] + assert start.is_start and start.stop is None and start.description == "Monitoring started" + assert start.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)" + assert (ev.flags, ev.trigger_source, ev.description) == (0x0001, 0x0001, "Event Recorded") + assert ev.event_time == dt(2026, 9, 8, 13, 38, 22) + assert ev.text == "Geo: 0.0500 in/s Mic: 125.0 dB(L)\rTran: 0.0500 in/s" + assert ev.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)" + +def test_histogram_with_a_waveform_event(): # BE8081.MLG + r = read_mlg(FIX / "BE8081.MLG").records + assert (r[1].flags, r[1].trigger_source, r[1].description) == ( + 0x0021, 0x0400, "Event Recorded Modem Exit") + assert r[1].trigger_level == "Histogram" + assert (r[2].trigger_source, r[2].trigger_level) == (0x0002, "Geo: 0.300 in/s") + +def test_trigger_level_with_or_without_a_space_before_the_colon(): + a = read_mlg(FIX / "BE11529.MLG").records[0] + b = read_mlg(FIX / "BE115292.MLG").records[0] + assert a.text == "Trigger Level: Histogram" and b.text == "Trigger Level : Histogram" + assert a.trigger_level == b.trigger_level == "Histogram" + +def test_empty_file(): + m = read_mlg(FIX / "BE6907751.MLG") + assert m.serial is None and m.records == [] and m.empty + +def test_a_flipped_byte_fails_only_its_record(): + data = bytearray((FIX / "BE128443065.MLG").read_bytes()) + data[18 + 292 + 40] ^= 0xFF # inside record 1's text + m = parse_mlg(bytes(data)) + assert m.crc_failures == [1] + assert m.records[0].crc_ok is False and m.records[1].crc_ok is True + +@pytest.mark.parametrize("mangle", [ + lambda d: d[:-1], # not 18 + 292·n + lambda d: b"\x00" + d[1:], # wrong prefix + lambda d: d[:18] + b"\x23" + d[19:], # header length field not 290 +]) +def test_structure_errors_raise(mangle): + with pytest.raises(MlgFormatError): + parse_mlg(mangle((FIX / "BE128443065.MLG").read_bytes())) +``` + +- [ ] **Step 3: Run them to verify they fail** + +Run: `~/seismo-relay/.venv/bin/python -m pytest tests/test_mlg_file.py -q` +Expected: collection error, `ModuleNotFoundError: minimateplus.crc`. + +- [ ] **Step 4: Implement** + +**The shared CRC.** `crc16_aug_ccitt` uses the same bitwise loop as `setup_block`. Point +`setup_block._crc16_aug_ccitt` at it, keeping the name, since its tests import it. + +**Timestamps.** A timestamp is `day, month, year LE (2 bytes), 0, hour, minute, second`, and +all-zero means `None`. + +**`parse_mlg` raises `MlgFormatError`, naming the record, when:** +- `len < 18`, or the prefix differs +- `(len - 18) % 292 != 0` +- any record's length field is not 290 +- record 0's id is not `0e a0`, or a later record's id is not `0e 80` +- a start time cannot be decoded + +**A checksum failure does not raise.** It only sets `crc_ok=False`. + +**The text:** +- If `text_raw[0] == 0x08`, then `event_time` is `text_raw[1:9]` and the text starts at + `text_raw[9]`. +- `text` is the bytes up to the first NUL, latin-1. +- `trigger_level` is `text`'s first line (split on `\r`), with a leading `Trigger Level :` or + `Trigger Level:` removed and stripped. An empty result is `None`. + +**`description`** is `"Monitoring started"` for `is_start`. Otherwise it is +`event_file_io.monitor_log_description(flags).strip()`. + +**The header record** gives `MlgFile.serial` (`record[24:34]`, NUL-stripped ASCII). + +- [ ] **Step 5: Run the tests, then the whole suite** + +Run: `~/seismo-relay/.venv/bin/python -m pytest tests/test_mlg_file.py tests/test_micromate_setup.py -q` +Expected: all pass. + +Then the full suite. Expected: `0 failed`. + +- [ ] **Step 6: Commit** + +```bash +git add minimateplus/crc.py minimateplus/mlg_file.py minimateplus/models.py micromate/setup_block.py tests/test_mlg_file.py +git commit -m "feat(mlg): read Blastware .MLG files, every record's checksum verified" +``` + +--- + +### Task 2: The writer, and the old MLG code retired + +**Files:** +- Modify: `minimateplus/mlg_file.py` (add the writer) +- Modify: `minimateplus/blastware_file.py`: + - delete `_build_mlg_header`, `_build_mlg_record`, the old `write_mlg`, the `read_mlg` stub, + `_MLG_*` and `MLG_FLAGS_*` + - the module docstring's MLG sections become one line pointing at `minimateplus/mlg_file.py` + - ⚠ **Do not re-export from `blastware_file`.** `event_file_io` imports `blastware_file` + and `mlg_file` imports `event_file_io`, so a re-export makes an import cycle. Nothing outside + `blastware_file.py` uses the old names (checked 2026-11-13). +- Test: `tests/test_mlg_file.py` + +**Interfaces:** +- Consumes: `MlgFile`, `MlgRecord` (Task 1) +- Produces: + - `mlg_file.mlg_bytes(mlg: MlgFile) -> bytes` + - `mlg_file.write_mlg(mlg: MlgFile, path) -> None` + +- [ ] **Step 1: Write the failing tests** + +```python +@pytest.mark.parametrize("name", sorted(p.name for p in FIX.glob("*.MLG"))) +def test_rebuilds_every_fixture_byte_for_byte(name): + raw = (FIX / name).read_bytes() + assert mlg_bytes(parse_mlg(raw)) == raw + +def test_old_mlg_code_is_gone(): + import minimateplus.blastware_file as bw + assert not hasattr(bw, "read_mlg") and not hasattr(bw, "MLG_FLAGS_TRIGGER") +``` + +- [ ] **Step 2: Run them to verify they fail** (`ImportError: mlg_bytes`) + +- [ ] **Step 3: Implement `mlg_bytes`** + +Write the prefix, then for a non-empty file the header record: +- length, id `0e a0`, zeros, the serial at `[24:34]`, zeros, then the CRC + +Every other byte of the header record is zero on all 1,273 DL2 files (measured). + +Then each log record, from its fields: +- length, id `0e 80`, both times, flags and source LE, the serial +- `text_raw`, then `00 00`, then the CRC + +An empty `MlgFile` is the prefix alone. Confirm nothing else imports the deleted names: +`grep -rn "MLG_FLAGS_\|_build_mlg\|_MLG_" --include=*.py .` + +- [ ] **Step 4: Run the tests and the full suite.** Expected: 12 rebuilds pass; `0 failed`. + +- [ ] **Step 5: Commit** + +`git commit -m "feat(mlg): write .MLG files as Blastware does; retire the old writer"` + +--- + +### Task 3: Storage + +**Files:** +- Modify: `sfm/database.py`: the two tables appended to `_SCHEMA`, and the methods below. + - The docstring's table list gains both tables. + - No migration: `CREATE … IF NOT EXISTS` runs on every start. +- Modify: `sfm/waveform_store.py`: add `save_mlg` +- Test: `tests/test_mlg_storage.py` + +**Interfaces:** +- Consumes: `MlgRecord` (Task 1) +- Produces: + - `WaveformStore.save_mlg(serial: Optional[str], file_name: str, data: bytes) -> str`. + - Writes `//mlg/` and returns that path + relative to the root (posix). + - If that path already holds different bytes, it uses `.`. + - If it holds the same bytes, it reuses the path. + - `SeismoDb.mlg_file_exists(file_name: str, sha256: str) -> bool` + - `SeismoDb.insert_mlg(*, serial, file_name, sha256, size, empty, call_in, file_mtime, stored_path, records) -> tuple[Optional[str], int, int]` + - One transaction; returns `(file_id, inserted, skipped)`. + - Returns `(None, 0, 0)` when `(file_name, sha256)` already exists. + - `SeismoDb.query_mlg_records(serial: str, from_dt=None, to_dt=None) -> list[dict]`: + - ascending by `start_time`, then `seq` + - keys: `id, serial, start_time, stop_time, flags, trigger_source, text, trigger_level, + event_time, file_id, seq` + - `SeismoDb.query_mlg_files(serial: str) -> list[dict]`: + - ascending by `COALESCE(file_mtime, received_at)` + - keys: `id, serial, file_name, sha256, size, record_count, empty, call_in, file_mtime, + received_at, stored_path` + - `SeismoDb.get_mlg_file(file_id: str) -> Optional[dict]` + - `SeismoDb.known_serials() -> set[str]`: distinct non-null serials from `events`, + `mlg_files` and `mlg_records` + +Schema: + +```sql +CREATE TABLE IF NOT EXISTS mlg_files ( + id TEXT PRIMARY KEY, serial TEXT, file_name TEXT NOT NULL, sha256 TEXT NOT NULL, + size INTEGER NOT NULL, record_count INTEGER NOT NULL, empty INTEGER NOT NULL, + call_in INTEGER NOT NULL DEFAULT 1, file_mtime TEXT, + received_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + stored_path TEXT, UNIQUE(file_name, sha256)); +CREATE TABLE IF NOT EXISTS mlg_records ( + id TEXT PRIMARY KEY, serial TEXT NOT NULL, start_time TEXT NOT NULL, stop_time TEXT, + flags INTEGER NOT NULL, trigger_source INTEGER NOT NULL, text TEXT, trigger_level TEXT, + event_time TEXT, file_id TEXT NOT NULL REFERENCES mlg_files(id), seq INTEGER NOT NULL); +CREATE UNIQUE INDEX IF NOT EXISTS ux_mlg_records_identity + ON mlg_records(serial, start_time, COALESCE(stop_time, ''), flags, trigger_source); +CREATE INDEX IF NOT EXISTS idx_mlg_files_serial ON mlg_files(serial); +``` + +- [ ] **Step 1: Write the failing tests** + - `test_insert_and_query_round_trip`: insert BE128443067's records; query returns 3 rows in + start order, with the open record's `stop_time` None. + - `test_same_file_twice_is_a_duplicate`: the second `insert_mlg` returns `(None, 0, 0)` and + there is still one file row. + - `test_open_record_is_stored_once`: insert the same `MlgFile` under two names (as a cable + download would arrive). The second returns `inserted == 0, skipped == 3`. + - `test_records_differing_only_in_text_are_the_same_record`: `BE11529.MLG`, then + `BE115292.MLG`. The second is `(id, 0, 3)`. + - `test_known_serials`, and `test_save_mlg_keeps_both_when_names_collide`: same name, + different bytes, two paths. + +- [ ] **Step 2: Run them to verify they fail** (`AttributeError: insert_mlg`) + +- [ ] **Step 3: Implement** the schema and the methods above. `record_count` is + `len(records)`. + +- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`. + +- [ ] **Step 5: Commit** + +`git commit -m "feat(mlg): store .MLG files and records, each record once"` + +--- + +### Task 4: Ingest + +**Files:** +- Create: `sfm/mlg_ingest.py`, `tests/test_mlg_ingest.py` + +**Interfaces:** +- Consumes: `parse_mlg`, `MlgFormatError` (Task 1); `insert_mlg`, `mlg_file_exists`, + `known_serials`, `save_mlg` (Task 3) +- Produces: + - `resolve_serial(file_name: str, header_serial: Optional[str], hint: Optional[str], known: set[str]) -> Optional[str]` + - `ingest_mlg(db, store, file_name: str, data: bytes, *, serial_hint=None, file_mtime: Optional[datetime]=None, call_in: bool=True) -> dict` + + Keys: `filename, status ("ok" | "duplicate" | "error"), detail, serial, serial_unresolved, + empty, records, inserted, skipped, file_id`. + +**Rules:** +- **Serial:** the header serial wins. Otherwise the hint. Otherwise the longest known serial + that the name starts with (case-insensitive), as long as only digits follow it before + `.MLG`. Otherwise `None`. +- **Order of work:** + 1. parse + 2. a `MlgFormatError`, or any checksum failure, is `status "error"`, with `detail` naming + the record (e.g. `"record 1 fails its checksum"`); nothing is written + 3. `mlg_file_exists` gives `"duplicate"` + 4. `save_mlg` + 5. `insert_mlg` + +- [ ] **Step 1: Write the failing tests** (a tmp `SeismoDb` and `WaveformStore`, as + `tests/test_db_snapshot_endpoints.py::_client` builds them) + - `test_ingest_ok`: BE128443067 gives `status "ok"`, serial `BE12844`, `records 3`, + `inserted 3`. The file exists in the store under `BE12844/mlg/`. + - `test_ingest_twice_is_duplicate` + - `test_corrupted_file_stores_nothing`: flip byte `18+292+40`. Expect `"error"`, `"record 1"` + in `detail`, no `mlg_files` row, and no `mlg/` directory in the store. + - `test_truncated_file_is_an_error` + - `test_empty_file_takes_known_serial`: ingest `BE6907750` then `BE6907751`. The second is + `serial "BE6907"`, `empty True`. + - `test_empty_file_without_known_serial_is_unresolved`: serial `None`, + `serial_unresolved True`, stored under `_unresolved/mlg/`. + - `test_empty_file_takes_the_longest_known_serial`: + - `resolve_serial("BE11010304.MLG", None, None, {"BE1101", "BE11010"}) == "BE11010"` + - `resolve_serial("XY123.MLG", None, None, {"BE1101"}) is None` + - `resolve_serial("BE6907751.MLG", "BE12844", "BE6907", {"BE6907"}) == "BE12844"` (the + header wins) + - `test_file_mtime_and_call_in_are_stored` + +- [ ] **Step 2: Run them to verify they fail** +- [ ] **Step 3: Implement `sfm/mlg_ingest.py`** +- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`. +- [ ] **Step 5: Commit** + +`git commit -m "feat(mlg): ingest one .MLG: verify, resolve the serial, keep the original"` + +--- + +### Task 5: The timeline + +**Files:** +- Create: `sfm/mlg_timeline.py`, `tests/test_mlg_timeline.py` + +**Interfaces:** +- Consumes: rows from `query_mlg_records` and `query_mlg_files` (Task 3) +- Produces: + - `build_timeline(records: list[dict], files: list[dict]) -> dict`, with keys `sessions`, + `gaps`, `clock_steps`, `call_ins`. All times are ISO strings. + - **a session:** `start, stop, end_after, end_before, ended_by, kind ("histogram" | + "monitoring"), trigger_level, running_at_last_report, events` + - **an event:** `start, stop, trigger_source, trigger_level, description` + - **a gap:** `start, stop, minutes, meaning` + - **a clock step:** `previous_stop, next_start, minutes` (negative) + - **a call-in:** `kind ("delivered" | "no_file" | "nothing_new"), unit_time, file_time, + file_name` + - `monitoring_at(timeline: dict, at: datetime) -> dict`, with keys `status ("monitoring" | + "not_monitoring" | "unknown"), ambiguous, sessions, gap, trigger_level, reason` + +**Rules.** These are the spec's §4 rules, made exact. + +- **Sort:** records by `(start_time, 0 if flags == 0xFFFF else 1, seq)`. +- **Record kinds:** + - **start:** `flags == 0xFFFF` + - **histogram:** `flags & 1` and `trigger_source == 0x0400` + - **event:** `flags & 1` and any other non-zero source + - **closed:** everything else +- **Building sessions, walking the sorted records:** + - **A start record opens a pending session.** Close any pending one first, with + `end_after` = its last event's stop (or its own start) and `end_before` = this start. + - **A histogram record joins the pending session** when its start is ≤ 2 s after the pending + start, giving the session `stop` and `kind "histogram"`. Otherwise it is a session of its + own. + - **An event record:** + - joins the last session if its start lies within that session's `[start, stop]` + - otherwise it joins the pending session + - an event carrying an end bit closes a pending (non-histogram) session at its stop + - with no session to join, it opens one at its own start + - **A closed record** first closes any pending session (as above, `end_before` = its start), + then is a session `[start, stop]`. + - **A session still pending at the end** has `running_at_last_report True` and + `end_after` = its last event's stop, or its start. +- **`ended_by`** is `monitor_log_description(flags & ~1).strip()` of the record that set + `stop`, or `None`. `trigger_level` is the start record's, else the stop record's. +- **Gaps:** from a session's end (`stop`, else `end_after`) to the next session's start. + - If the next start is earlier than that end, it is a clock step, not a gap. + - The meaning comes from `ended_by`: + - Modem Exit: "call-in" + - Timer Stop: "scheduled off" + - Battery Low Exit: "lost power" + - Keyboard Exit and Remote Exit: "stopped by a person" + - Memory Full Exit: "memory full" + - anything else: "unknown" +- **Call-ins**, per file in `query_mlg_files` order (`file_time` = `file_mtime`, else + `received_at`): + - **An empty file** gives `nothing_new`. + - **A `call_in` file with records** gives `delivered`, with `unit_time` = the stop of the + file's last record (by `seq`). Each Modem Exit (`flags & 0x20`, not a start) that is not + the file's last record gives `no_file`, with `unit_time` = its stop and `file_time` None. + - **Non-call-in files** give nothing. +- **`monitoring_at`:** + - **monitoring:** `start ≤ at ≤ stop`, or `≤ end_after` when the stop is unknown. Two or more + matches set `ambiguous True`. + - **unknown:** inside an unknown end window, or after `end_after` of a session running at the + last report. + - **not_monitoring:** inside a gap, with the gap. + - **unknown:** anything else, including no data. + +- [ ] **Step 1: Write the failing tests.** Ingest fixtures into a tmp DB with explicit + `file_mtime` values, then call `build_timeline(db.query_mlg_records(s), db.query_mlg_files(s))`. + - `test_sessions_gaps_and_an_event_session` (BE128443067 + 068): + - three sessions: `09-07 18:47:27 → 20:00:00 "Timer Stop"`; `09-08 06:00:13`, stop None, + `end_after 13:38:25`, `end_before 13:41:16`, 1 event; `13:41:16 → 18:45:00 "Modem Exit"` + - gaps: `"scheduled off"`, `minutes ≈ 600.217`; then `"unknown"`, `≈ 2.85` + - `test_monitoring_at`, on the same data: + - `09-08 10:00` is `monitoring`, trigger level `"Geo: 0.0500 in/s Mic: 125.0 dB(L)"` + - `09-08 13:40:00` is `unknown` + - `09-07 23:00` is `not_monitoring` with meaning `"scheduled off"` + - `2027-01-01` is `unknown` + - `test_monitoring_at_boundaries_are_inclusive`: `09-07 18:47:27` and `09-07 20:00:00` are + both `monitoring`. + - `test_clock_step_back_is_not_a_negative_gap` (BE128443155 + 156): + - no gap with negative minutes + - one clock step: `previous_stop 2026-11-01T18:45:00`, `next_start 2026-11-01T17:47:25`, + `minutes ≈ -57.58` + - `monitoring_at(11-01 18:00)` is `monitoring`, `ambiguous True`, 2 sessions + - `test_weekend_battery_outage_and_missed_calls` (BE8081321 alone): + - sessions start at `04-12 17:17:59` (histogram, from the start record), + `04-12 18:38:14`, `04-13 07:05:15` ("Battery Low Exit") and `04-15 12:47:05` + - the gap `04-13 10:47:15 → 04-15 12:47:05` is `"lost power"`, `minutes ≈ 2999.83` + - two `"call-in"` gaps of `≈ 5.23` + - call-ins: `no_file` at `2019-04-12T18:33:00`, `no_file` at `2019-04-13T07:00:01`, + `delivered` at `2019-04-15T17:15:00`, with `file_name "BE8081321.MLG"` + - `monitoring_at(2019-04-14 12:00)` is `not_monitoring`, `"lost power"` + - `test_histogram_session_keeps_its_waveform_event` (BE8081.MLG): + - one session `2018-02-16 15:15:31 → 15:15:49`, `kind "histogram"`, + `trigger_level "Histogram"` + - one event with `trigger_source 2` and `trigger_level "Geo: 0.300 in/s"` + - `test_event_with_an_end_bit_inside_a_histogram` (BE94412): + - the histogram session `16:06:34 → 16:07:21` keeps its stop and `"Keyboard Exit"` + - it holds the Memory Full event + - the `17:00:36` histogram is a session of its own + - `test_call_in_kinds` (BE6907750 + 751): `no_file` at `2026-08-22T18:30:00`, `delivered` at + `2026-08-23T18:30:00`, then `nothing_new`. + +- [ ] **Step 2: Run them to verify they fail** +- [ ] **Step 3: Implement `sfm/mlg_timeline.py`** (pure: no DB, no I/O) +- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`. +- [ ] **Step 5: Commit** + +`git commit -m "feat(mlg): each unit's monitoring timeline, and was it monitoring at T"` + +--- + +### Task 6: Routes + +**Files:** +- Modify: `sfm/server.py`: the routes go after `db_import_idf_file` +- Create: `tests/test_mlg_routes.py` + +**Interfaces:** +- Consumes: `ingest_mlg` (Task 4); `build_timeline`, `monitoring_at` (Task 5); Task 3's queries +- Produces: + - `POST /db/import/mlg_file` → `db_import_mlg_file(files: list[UploadFile] = File(...), serial: Optional[str] = Query(None), call_in: bool = Query(True), mtimes: Optional[str] = Form(None))`. + `mtimes` is JSON `{filename: unix_seconds_utc}`. Returns `{"count", "results": [ingest + dicts]}`. + - `GET /db/units/{serial}/timeline?from_dt=&to_dt=` → `db_unit_timeline(...)`: the full + timeline, with sessions, gaps and call-ins filtered to those overlapping the window. + - `GET /db/units/{serial}/monitoring_at?at=` → `db_unit_monitoring_at(...)` + - `GET /db/mlg_records?serial=&from_dt=&to_dt=` → `db_mlg_records(...)` + - `GET /db/mlg_files/{file_id}` → `db_mlg_file(...)`: the original bytes as a `FileResponse` + with the original `file_name`; 404 if unknown. + +- [ ] **Step 1: Write the failing tests.** Set up as `_client` does (monkeypatch `srv._db` and + `srv._store`). Call the route functions directly: `asyncio.run(...)` for the import, with + `UploadFile(file=io.BytesIO(data), filename=name)`. + - `test_import_route_stores_good_file_and_refuses_bad_one`: + - two files, BE128443065 and a corrupted copy named `BE128443099.MLG` + - results: `["ok", "error"]` + - one `mlg_files` row; only the good file under the store's `mlg/` + - `test_import_route_reads_mtimes`: `mtimes='{"BE128443065.MLG": 1788734760}'` stores + `file_mtime` `2026-09-06T22:46:00+00:00`. + - `test_timeline_and_monitoring_at_routes`, with BE8081321 imported: the timeline has 4 + sessions, and `monitoring_at` at `2019-04-14T12:00:00` is `not_monitoring`. + - `test_timeline_routes_for_unknown_serial`: `BE0000` gives empty `sessions`, `gaps` and + `call_ins`, and `monitoring_at` is `unknown`. + - `test_mlg_file_route_returns_original_bytes`, and a 404 for an unknown id. + +- [ ] **Step 2: Run them to verify they fail** +- [ ] **Step 3: Implement the routes.** They stay thin: parse the query, call Tasks 3–5. +- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`. +- [ ] **Step 5: Commit** + +`git commit -m "feat(mlg): /db routes: import .MLG, a unit's timeline, monitoring at T"` + +--- + +### Task 7: Bulk import and the cross-check + +**Files:** +- Create: `scripts/import_mlg_dir.py`, `scratch/check_mlg_vs_events.py`, + `tests/test_import_mlg_dir.py` + +**Interfaces:** +- Consumes: `ingest_mlg` (Task 4), `parse_mlg` (Task 1), `crc16_aug_ccitt` (Task 1) +- Produces: + - **`scripts/import_mlg_dir.py --db-path P --store-root S [--dry-run] [--not-call-in]`** + - `main(argv) -> int`, following `scripts/backfill_event_shape.py` + - walks `*.MLG` (case-insensitive) recursively + - **two passes:** files with records first, then the empty ones, each oldest file time + first. Every unit's serial is then known before its empty files arrive, whatever the + folder order. + - `file_mtime` from `os.stat` as UTC + - prints counts: files, ok, duplicate, error, empty, unresolved, inserted, skipped + - dry run: parse and checksums only, nothing written + - **`scratch/check_mlg_vs_events.py `** + - matches every non-start record with the Event Recorded bit to an event file by + `(serial, stop, flag word, trigger source)` + - an event file's serial number comes from its name, via + `sfm.waveform_store._serial_number_from_bw_filename`, compared with the MLG serial's + digits + - only event files inside each serial's MLG period count (its first record's start to its + last record's stop). DL2 holds years of event files from before the `.MLG`s. + - reads each event file's footer straight from its last 28 bytes: `00 1a 0e 08`, both times + with a big-endian year, flag word and source BE. It checks the footer's CRC with + `crc16_aug_ccitt` too. + - prints matched / record-only / file-only per serial, with up to 5 examples each + +- [ ] **Step 1: Write the failing test.** `test_import_dir_counts`: + - copy the fixture dir to `tmp_path` + - the dry run prints `files 12`, writes no DB file and returns 0 + - a real run imports 12 files with 0 errors, and a second run reports 12 duplicates +- [ ] **Step 2: Run it to verify it fails** +- [ ] **Step 3: Implement both tools** +- [ ] **Step 4: Run the tests and the full suite.** Expected: pass; `0 failed`. +- [ ] **Step 5: Run both tools on the real data, on the dev box only** + +```bash +~/seismo-relay/.venv/bin/python scripts/import_mlg_dir.py ~/dl2-archive/mlg --db-path /tmp/claude-1000/mlg-check.db --store-root /tmp/claude-1000/mlg-check-store +~/seismo-relay/.venv/bin/python scratch/check_mlg_vs_events.py ~/dl2-archive/mlg ~/dl2-archive/files +``` + +Expected: +- 1,273 files, 0 errors, 231 empty, 0 unresolved +- BE8081: 785 matched, 0 record-only, 0 file-only +- BE6907: 6 matched, 5 record-only, 0 file-only +- BE12844: 19 matched, 37 record-only, 0 file-only +- every record-only one stops after 2026-08-25, where the DL2 copy ends + +Put the numbers in the commit message. + +- [ ] **Step 6: Commit** + +`git commit -m "feat(mlg): bulk import, and a cross-check against the event files"` + +--- + +### Task 8: Documentation + +**Files:** +- Modify: `docs/instantel_protocol_reference.md`: + - D.4 to D.4.3 rewritten from the spec's "What was measured", each claim graded + - the old D.4.2 table kept under a ⚠ RETRACTED banner (its CRC position, BE timestamps + and flag table) + - a row in the Changelog table at the top +- Modify: `CLAUDE.md`: + - the "SFM REST API" `/db` list gains the five routes + - one line under "Where things stand" pointing at the spec +- Modify: `docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md` §8: the footer CRC + note becomes "recorded on dev, `8544e9c`" + +- [ ] **Step 1: Edit the three files** +- [ ] **Step 2: Run `tests/test_line_endings.py` and the full suite.** Expected: `0 failed`. +- [ ] **Step 3: Commit** + +`git commit -m "docs: the .MLG format measured (reference D.4), and the new /db routes"`