diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl
index 7743236..bc9d076 100644
--- a/.beads/issues.jsonl
+++ b/.beads/issues.jsonl
@@ -2,7 +2,7 @@
{"id":"spaxel-0fm8","title":"Add quiet hours gate tests","description":"Write tests for quiet hours gate: LOW at 23:00 with 22:00-07:00 quiet hours -> queued, URGENT at 23:00 -> delivered. Acceptance Criteria: Quiet hours tests pass (queueing, bypass).","status":"in_progress","priority":2,"issue_type":"task","assignee":"bravo","created_at":"2026-04-11T08:15:07.990827798Z","created_by":"coding","updated_at":"2026-04-11T08:39:52.275270077Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:1","mitosis-child","mitosis-depth:1","parent-spaxel-40tl"]}
{"id":"spaxel-0ii","title":"Implement Zones CRUD REST endpoints","description":"Implement CRUD endpoints for zones: GET/POST /api/zones, PUT/DELETE /api/zones/{id}. Include OpenAPI-style godoc comments. Zone changes must reflect in live 3D view within one WebSocket cycle.","status":"closed","priority":2,"issue_type":"task","assignee":"echo","created_at":"2026-04-07T13:56:27.275139529Z","created_by":"coding","updated_at":"2026-04-07T19:01:48.974563569Z","closed_at":"2026-04-07T19:01:48.974408083Z","close_reason":"Zones CRUD REST endpoints already fully implemented: GET/POST /api/zones, PUT/DELETE /api/zones/{id}, GET /api/zones/{id}/history, plus portals CRUD. OpenAPI godoc comments, WebSocket broadcasting for live 3D view, 31 table-driven tests. go vet and go test pass.","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:1","mitosis-child","mitosis-depth:1","parent-spaxel-21n"],"dependencies":[{"issue_id":"spaxel-0ii","depends_on_id":"spaxel-3rd","type":"blocks","created_at":"2026-04-07T17:01:33.629176640Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-0ii","depends_on_id":"spaxel-5lo","type":"blocks","created_at":"2026-04-07T17:01:33.542274773Z","created_by":"coding","metadata":"{}","thread_id":""}]}
{"id":"spaxel-0j0k","title":"Implement responsive canvas resize and orientation handling","description":"Handle canvas resize on window resize and orientation change events, including iOS Safari visual viewport quirks and bottom navigation bar spacing.\n\n**Files:** dashboard/js/app.js (resize/orientationchange listeners), dashboard/css/expert.css (canvas height calculation)\n\n**Acceptance Criteria:**\n- Canvas resizes correctly on window resize event\n- Canvas resizes correctly on orientationchange event\n- renderer.setSize() called with updated dimensions\n- camera.aspect updated and camera.updateProjectionMatrix() called\n- Uses visualViewport.width/height on iOS Safari (fallback to window.innerWidth/Height)\n- Canvas height uses calc(100vh - 56px) when simple mode nav is visible","status":"closed","priority":2,"issue_type":"task","assignee":"bravo","created_at":"2026-04-11T06:26:50.081049506Z","created_by":"coding","updated_at":"2026-04-11T06:51:20.327121642Z","closed_at":"2026-04-11T06:51:20.327061414Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["mitosis-child","mitosis-depth:1","parent-spaxel-kth"]}
-{"id":"spaxel-0w4","title":"Fleet status page","description":"## Background\n\nThe 3D scene is great for spatial context but poor for bulk fleet management tasks. With 6+ nodes, finding a specific node in the 3D view, checking its firmware version, and triggering an update involves hunting through the scene. The fleet status page provides a flat table view of all nodes with their key metrics and inline actions — the same information you would find in a server management panel, adapted for ESP32 nodes. It complements the 3D view rather than replacing it.\n\n## Fleet Status Table\n\nNew dashboard route: /fleet\n\nThe page layout:\n- Page header: \"Fleet Status\" title, total node count, online count, \"Update All\" button, \"Download report\" button\n- Filter and sort bar (below header)\n- Fleet table (main content)\n\nTable columns:\n1. Checkbox (for multi-select)\n2. Label (editable inline on double-click)\n3. MAC address (truncated, full on hover tooltip)\n4. Status: coloured dot + text. \"Online\" (green) / \"Offline\" (red) / \"Updating\" (yellow spinner)\n5. Firmware version: current version string. If a newer version is in the firmware manifest: version displayed in amber with an \"→ {new_version}\" indicator and an \"Update\" action badge.\n6. Uptime: formatted as \"3d 4h 12m\". Only valid when online.\n7. Current role: TX / RX / TX-RX / Passive. Small badge.\n8. Signal health: composite health score for this node's links as a small colour bar (green → red)\n9. Packet rate: \"{actual} / {configured} Hz\" as a fraction. Colour-coded: > 90% = green, 70-90% = amber, < 70% = red.\n10. Temperature: from health message. Shown as \"{N}°C\" or \"--\" if not reported. Alert colour if > 75°C.\n11. Actions column: [Locate] [OTA] [...more] buttons\n\nThe table rows are clickable (full row click = fly 3D camera to that node's position). Only clicking action buttons or the checkbox should not trigger the row fly-to.\n\n## Inline Label Edit\n\nDouble-clicking the label cell makes it inline-editable:\n- Input field replaces the text\n- Enter to confirm, Escape to cancel\n- Blur (click outside) to confirm\n- On confirm: PATCH /api/nodes/{mac}/label with the new label. Update the display.\n- Validation: max 32 characters, no control characters.\n\n## Action Buttons\n\n\"Locate\" (flash LED): sends a downstream command {\"type\":\"identify\"} to the node via WebSocket. The node flashes its onboard LED rapidly for 5 seconds. The button shows a spinner while the command is in-flight, then a brief green checkmark.\n\n\"OTA\" (firmware update): available only if the node's firmware version != latest in the manifest. Clicking shows a confirmation tooltip: \"Update Node [label] from v{current} to v{latest}? [Confirm] [Cancel]\". On confirm: POST /api/nodes/{mac}/ota. The node's row shows \"Updating\" status and a progress bar (populated from ota_status WebSocket messages for this node).\n\n\"More actions\" (... button): dropdown with: \"Re-assign role\", \"View health history\", \"View event history\", \"Remove from fleet\". Each with an appropriate icon.\n\n## Bulk Actions\n\nCheckbox column allows multi-selecting rows. When any row is selected, a bulk-actions bar slides in above the table:\n- \"Update {N} selected to latest firmware\" — confirms and triggers OTA for all selected nodes in sequence (with 30s stagger)\n- \"Re-assign roles\" — opens the role optimiser with the selected nodes included\n- \"Remove {N} from fleet\" — confirmation required: lists the nodes to be removed\n\nDeselect all: \"Clear selection\" button in the bulk actions bar, or uncheck all checkboxes.\n\n## Camera Fly-To\n\nClicking a table row (non-action click) triggers a smooth camera fly-to the node's position in the expert mode 3D view. The fleet page and expert mode are on different routes, so this requires:\n1. Store the target node MAC in localStorage or URL parameter (\"?highlight={mac}\")\n2. Redirect to the expert mode route / (or open expert mode in a second tab)\n3. On load, if ?highlight={mac} parameter is present, fly camera to that node's position\n\nAlternatively: if the fleet page is opened alongside the expert mode in a split-pane layout (future enhancement), coordinate via a shared state store. For Phase 9, the redirect approach is sufficient.\n\n## Sorting and Filtering\n\nColumn header click: sort by that column. First click = ascending, second = descending. Sort state shown with a small arrow indicator.\n\nFilter row (below column headers, toggle-able with a \"Filter\" button):\n- Label / MAC: text input, filters rows containing the substring\n- Status: dropdown \"All / Online / Offline\"\n- Firmware: dropdown \"All / Outdated only\"\n- Role: multi-select dropdown \"All / TX / RX / TX-RX / Passive\"\n\nActive filters: shown as chips above the table with individual dismiss buttons. \"Clear all filters\" link.\n\n## Download Report\n\n\"Download report\" button: exports the current fleet table (including all filters) as a CSV file. Columns: MAC, label, status, firmware_version, uptime_s, role, health_score, packet_rate_hz, temperature_c, last_seen.\n\nImplemented as a client-side CSV generation from the current table data (no API call needed if data is cached in the dashboard state). Use Blob + URL.createObjectURL for download.\n\n## REST API\n\nGET /api/fleet: returns all provisioned nodes with full details (same as GET /api/nodes but with more fields: uptime, firmware_version, temperature, health_score, packet_rate).\nPATCH /api/nodes/{mac}/label: update label\nPOST /api/nodes/{mac}/locate: send identify command\nPOST /api/nodes/{mac}/role: assign new role\nDELETE /api/nodes/{mac}: remove from fleet (disconnects and archives)\n\n## Files to Create or Modify\n\n- dashboard/fleet.html: fleet page HTML shell\n- dashboard/js/fleet.js: table rendering, sorting, filtering, bulk actions, inline edit\n- dashboard/css/fleet.css: fleet page styles\n- mothership/internal/dashboard/routes.go: fleet-specific API routes, /fleet HTML route\n\n## Tests\n\n- Test fleet table renders correctly with mock data: 4 nodes, verify all columns populated\n- Test inline label edit: double-click cell, type new label, Enter -> PATCH API called with correct body\n- Test bulk selection: check 3 nodes, verify bulk actions bar appears with correct count\n- Test bulk OTA triggers OTA for all 3 selected nodes\n- Test sorting: click \"Firmware version\" header -> rows sorted ascending by version string\n- Test filter: enter \"living\" in label filter -> only rows matching \"living\" visible\n- Test camera fly-to: clicking a row stores MAC in localStorage and redirects to expert mode with ?highlight parameter\n- Test CSV download: verify blob is created with correct headers and values\n\n## Acceptance Criteria\n\n- Fleet page loads with all nodes and their current metrics\n- Inline label edit saves correctly to the API and updates the display\n- Bulk OTA fires for all selected nodes with correct stagger\n- Sorting and filtering work correctly for all columns\n- Camera fly-to positions the 3D view correctly on the selected node after redirect\n- CSV download contains correct headers and all fleet data\n- Tests pass","status":"open","priority":3,"issue_type":"task","created_at":"2026-03-28T02:06:06.562532476Z","created_by":"coding","updated_at":"2026-04-11T08:20:42.548134891Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred"],"dependencies":[{"issue_id":"spaxel-0w4","depends_on_id":"spaxel-sl2","type":"blocks","created_at":"2026-03-28T03:29:14.955755499Z","created_by":"coding","metadata":"{}","thread_id":""}]}
+{"id":"spaxel-0w4","title":"Fleet status page","description":"## Background\n\nThe 3D scene is great for spatial context but poor for bulk fleet management tasks. With 6+ nodes, finding a specific node in the 3D view, checking its firmware version, and triggering an update involves hunting through the scene. The fleet status page provides a flat table view of all nodes with their key metrics and inline actions — the same information you would find in a server management panel, adapted for ESP32 nodes. It complements the 3D view rather than replacing it.\n\n## Fleet Status Table\n\nNew dashboard route: /fleet\n\nThe page layout:\n- Page header: \"Fleet Status\" title, total node count, online count, \"Update All\" button, \"Download report\" button\n- Filter and sort bar (below header)\n- Fleet table (main content)\n\nTable columns:\n1. Checkbox (for multi-select)\n2. Label (editable inline on double-click)\n3. MAC address (truncated, full on hover tooltip)\n4. Status: coloured dot + text. \"Online\" (green) / \"Offline\" (red) / \"Updating\" (yellow spinner)\n5. Firmware version: current version string. If a newer version is in the firmware manifest: version displayed in amber with an \"→ {new_version}\" indicator and an \"Update\" action badge.\n6. Uptime: formatted as \"3d 4h 12m\". Only valid when online.\n7. Current role: TX / RX / TX-RX / Passive. Small badge.\n8. Signal health: composite health score for this node's links as a small colour bar (green → red)\n9. Packet rate: \"{actual} / {configured} Hz\" as a fraction. Colour-coded: > 90% = green, 70-90% = amber, < 70% = red.\n10. Temperature: from health message. Shown as \"{N}°C\" or \"--\" if not reported. Alert colour if > 75°C.\n11. Actions column: [Locate] [OTA] [...more] buttons\n\nThe table rows are clickable (full row click = fly 3D camera to that node's position). Only clicking action buttons or the checkbox should not trigger the row fly-to.\n\n## Inline Label Edit\n\nDouble-clicking the label cell makes it inline-editable:\n- Input field replaces the text\n- Enter to confirm, Escape to cancel\n- Blur (click outside) to confirm\n- On confirm: PATCH /api/nodes/{mac}/label with the new label. Update the display.\n- Validation: max 32 characters, no control characters.\n\n## Action Buttons\n\n\"Locate\" (flash LED): sends a downstream command {\"type\":\"identify\"} to the node via WebSocket. The node flashes its onboard LED rapidly for 5 seconds. The button shows a spinner while the command is in-flight, then a brief green checkmark.\n\n\"OTA\" (firmware update): available only if the node's firmware version != latest in the manifest. Clicking shows a confirmation tooltip: \"Update Node [label] from v{current} to v{latest}? [Confirm] [Cancel]\". On confirm: POST /api/nodes/{mac}/ota. The node's row shows \"Updating\" status and a progress bar (populated from ota_status WebSocket messages for this node).\n\n\"More actions\" (... button): dropdown with: \"Re-assign role\", \"View health history\", \"View event history\", \"Remove from fleet\". Each with an appropriate icon.\n\n## Bulk Actions\n\nCheckbox column allows multi-selecting rows. When any row is selected, a bulk-actions bar slides in above the table:\n- \"Update {N} selected to latest firmware\" — confirms and triggers OTA for all selected nodes in sequence (with 30s stagger)\n- \"Re-assign roles\" — opens the role optimiser with the selected nodes included\n- \"Remove {N} from fleet\" — confirmation required: lists the nodes to be removed\n\nDeselect all: \"Clear selection\" button in the bulk actions bar, or uncheck all checkboxes.\n\n## Camera Fly-To\n\nClicking a table row (non-action click) triggers a smooth camera fly-to the node's position in the expert mode 3D view. The fleet page and expert mode are on different routes, so this requires:\n1. Store the target node MAC in localStorage or URL parameter (\"?highlight={mac}\")\n2. Redirect to the expert mode route / (or open expert mode in a second tab)\n3. On load, if ?highlight={mac} parameter is present, fly camera to that node's position\n\nAlternatively: if the fleet page is opened alongside the expert mode in a split-pane layout (future enhancement), coordinate via a shared state store. For Phase 9, the redirect approach is sufficient.\n\n## Sorting and Filtering\n\nColumn header click: sort by that column. First click = ascending, second = descending. Sort state shown with a small arrow indicator.\n\nFilter row (below column headers, toggle-able with a \"Filter\" button):\n- Label / MAC: text input, filters rows containing the substring\n- Status: dropdown \"All / Online / Offline\"\n- Firmware: dropdown \"All / Outdated only\"\n- Role: multi-select dropdown \"All / TX / RX / TX-RX / Passive\"\n\nActive filters: shown as chips above the table with individual dismiss buttons. \"Clear all filters\" link.\n\n## Download Report\n\n\"Download report\" button: exports the current fleet table (including all filters) as a CSV file. Columns: MAC, label, status, firmware_version, uptime_s, role, health_score, packet_rate_hz, temperature_c, last_seen.\n\nImplemented as a client-side CSV generation from the current table data (no API call needed if data is cached in the dashboard state). Use Blob + URL.createObjectURL for download.\n\n## REST API\n\nGET /api/fleet: returns all provisioned nodes with full details (same as GET /api/nodes but with more fields: uptime, firmware_version, temperature, health_score, packet_rate).\nPATCH /api/nodes/{mac}/label: update label\nPOST /api/nodes/{mac}/locate: send identify command\nPOST /api/nodes/{mac}/role: assign new role\nDELETE /api/nodes/{mac}: remove from fleet (disconnects and archives)\n\n## Files to Create or Modify\n\n- dashboard/fleet.html: fleet page HTML shell\n- dashboard/js/fleet.js: table rendering, sorting, filtering, bulk actions, inline edit\n- dashboard/css/fleet.css: fleet page styles\n- mothership/internal/dashboard/routes.go: fleet-specific API routes, /fleet HTML route\n\n## Tests\n\n- Test fleet table renders correctly with mock data: 4 nodes, verify all columns populated\n- Test inline label edit: double-click cell, type new label, Enter -> PATCH API called with correct body\n- Test bulk selection: check 3 nodes, verify bulk actions bar appears with correct count\n- Test bulk OTA triggers OTA for all 3 selected nodes\n- Test sorting: click \"Firmware version\" header -> rows sorted ascending by version string\n- Test filter: enter \"living\" in label filter -> only rows matching \"living\" visible\n- Test camera fly-to: clicking a row stores MAC in localStorage and redirects to expert mode with ?highlight parameter\n- Test CSV download: verify blob is created with correct headers and values\n\n## Acceptance Criteria\n\n- Fleet page loads with all nodes and their current metrics\n- Inline label edit saves correctly to the API and updates the display\n- Bulk OTA fires for all selected nodes with correct stagger\n- Sorting and filtering work correctly for all columns\n- Camera fly-to positions the 3D view correctly on the selected node after redirect\n- CSV download contains correct headers and all fleet data\n- Tests pass","status":"in_progress","priority":3,"issue_type":"task","assignee":"bravo","created_at":"2026-03-28T02:06:06.562532476Z","created_by":"coding","updated_at":"2026-04-11T11:24:15.426859361Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:3"],"dependencies":[{"issue_id":"spaxel-0w4","depends_on_id":"spaxel-sl2","type":"blocks","created_at":"2026-03-28T03:29:14.955755499Z","created_by":"coding","metadata":"{}","thread_id":""}]}
{"id":"spaxel-16e","title":"Captive portal WiFi recovery","description":"## Background\n\nIf a node loses WiFi connectivity — because a router was replaced, credentials changed, or the node was moved out of range — it currently has no recovery path without physical intervention. The firmware already implements a captive portal AP fallback in firmware/main/wifi.c: after 10 consecutive WiFi connection failures with exponential backoff (up to 30s between attempts), the firmware transitions to AP mode with SSID \"spaxel-{last4mac}\". However, the captive portal HTTP config page served in this mode is currently a stub and needs to be completed. This bead finishes that implementation and adds the mothership-side offline detection and dashboard alert.\n\n## What Already Exists (Phase 1)\n\nfirmware/main/wifi.c implements the WIFI_STATE_CAPTIVE_PORTAL state transition after failure threshold. The firmware starts a SoftAP with SSID \"spaxel-{last4mac}\" and password-free (open AP). A stub HTTP server exists but serves only a 200 OK response with no content. The DNS server for captive portal hijacking is not yet implemented.\n\n## Captive Portal HTTP Server (Firmware)\n\nUse ESP-IDF's esp_http_server component to serve a config page at http://192.168.4.1/ when in AP mode.\n\nThe config page (served as inline HTML, no external resources — it must work fully offline):\n- Shows current provisioned SSID (from NVS, read-only display)\n- Form: new SSID input, password input, optional mothership host/port\n- Submit button: \"Save and Reconnect\"\n- On form submission: firmware writes new credentials to NVS (wifi_ssid, wifi_pass, optionally mothership_host/port) and calls esp_restart()\n- Minimal HTML with inline CSS: max 4KB so it fits in IRAM. No JavaScript needed.\n- Works on iOS Safari (no JS requirement), Android Chrome, desktop browsers\n\nThe HTTP server must handle the iOS and Android captive portal probe paths:\n- GET /hotspot-detect.html (iOS)\n- GET /generate_204 (Android)\n- GET /ncsi.txt (Windows)\nRespond to all of these with a 302 redirect to http://192.168.4.1/ to trigger the OS captive portal popup.\n\n## DNS Hijacking for Captive Portal Detection\n\nModern mobile OSes detect captive portals by making a DNS lookup for a known hostname (connectivitycheck.android.com, captive.apple.com, etc.) and checking if the response is correct. To trigger the OS captive portal popup automatically (so the user does not need to manually navigate to 192.168.4.1):\n\nImplement a minimal DNS server using lwIP's UDP API. The DNS server binds to UDP port 53 on the SoftAP interface (192.168.4.1). It responds to ALL DNS queries with an A record pointing to 192.168.4.1, regardless of the queried hostname. This causes the OS to detect the captive portal and show the popup.\n\nESP-IDF does not provide a ready-made DNS hijacking component — implement using esp_event_loop and lwIP udp_new()/udp_bind()/udp_recv() APIs. Keep the implementation minimal: parse enough of the DNS query to extract the transaction ID and question name, then build a minimal A record response.\n\n## Mothership Offline Detection and Dashboard Alert\n\nThe mothership detects node disconnection via heartbeat timeout. When a node's WebSocket closes (or health messages stop for > 30s), the mothership:\n1. Sets node status to OFFLINE in the node registry\n2. Broadcasts a node_offline WebSocket message to dashboard: {\"type\":\"node_offline\",\"mac\":\"aa:bb:cc:dd:ee:ff\",\"label\":\"Living Room\",\"last_seen\":\"2026-03-27T14:23:00Z\",\"likely_cause\":\"wifi_loss\"}\n\nThe dashboard shows an offline alert card:\n- \"Node [Living Room] went offline at 14:23. It may need WiFi reconfiguration.\"\n- Shows the captive portal AP SSID to connect to: \"Connect to Wi-Fi network 'spaxel-ff01' to reconfigure\"\n- Troubleshooting steps: 1) Check power LED, 2) Check WiFi router is online, 3) Connect to captive portal if LED is blinking\n\nThe likely_cause field is set by the mothership based on the last health message before disconnect (e.g. low WiFi RSSI in last health message -> \"wifi_range\", no recent health messages at all -> \"unknown\").\n\n## Reconnection and Portal Exit\n\nWhen the user submits new credentials in the captive portal and the node reboots:\n1. The SoftAP goes down (existing connections to \"spaxel-ff01\" are dropped)\n2. The node attempts WiFi connection with new credentials\n3. On success, connects to mothership — mothership sets status to ONLINE and broadcasts node_online event\n4. Dashboard shows reconnection notification: \"Node [Living Room] reconnected successfully\"\n\nIf the new credentials also fail (e.g. user mistyped), the node re-enters captive portal mode after another 10 failures. The portal should display an error on re-entry if the previous attempt failed.\n\n## Implementation Files\n\n- firmware/main/wifi.c: complete captive portal HTTP server, add DNS hijacking task\n- firmware/main/captive_portal.c (new): DNS hijacking task + HTTP handler functions\n- mothership/internal/ingestion/server.go: heartbeat timeout detection, node_offline event\n- mothership/internal/fleet/manager.go: node status tracking (ONLINE/OFFLINE/CAPTIVE_PORTAL)\n- dashboard/js/app.js: node_offline event handler, offline alert card rendering\n\n## Testing Challenges\n\nThis feature is difficult to unit test due to hardware dependency. Recommended approaches:\n1. Firmware: Integration test in QEMU (esp32s3 target) — simulate WiFi failures by mocking the WiFi event loop, verify state machine transitions to CAPTIVE_PORTAL after failure threshold\n2. DNS server: Unit test the DNS response builder function with a fixed query buffer and verify the response parses correctly\n3. HTTP config page: Unit test the form handler that writes to NVS (mock the NVS API)\n4. Mothership: Unit test heartbeat timeout detection with a fake time source, verify node_offline event is emitted\n\n## Acceptance Criteria\n\n- After WiFi failure (10 consecutive failures), node enters AP mode with SSID \"spaxel-{last4mac}\" within 5 minutes of initial loss\n- Mobile device connecting to the captive portal AP automatically sees the OS captive portal popup (tested on iOS 16+ and Android 12+)\n- Config page is served and functional without JavaScript\n- Updating credentials causes node to reboot and reconnect to mothership within 60s\n- Dashboard shows offline node alert within 30s of disconnection\n- Reconnection notification appears in dashboard within 30s of node reconnecting\n- Captive portal DNS server responds correctly to all DNS queries with 192.168.4.1\n- Tests pass","status":"closed","priority":2,"issue_type":"task","created_at":"2026-03-28T01:38:15.579673840Z","created_by":"coding","updated_at":"2026-03-28T05:36:39.291892350Z","closed_at":"2026-03-28T05:36:39.291803146Z","close_reason":"Implemented: firmware/main/wifi.c (fb69190, 89 lines added) — captive portal AP mode (spaxel-XXXX SSID), esp_http_server config page at 192.168.4.1, DNS hijacking to trigger OS captive portal popup, NVS credential update on form submission","source_repo":".","compaction_level":0,"original_size":0,"dependencies":[{"issue_id":"spaxel-16e","depends_on_id":"spaxel-uc9","type":"blocks","created_at":"2026-03-28T03:29:13.901241816Z","created_by":"coding","metadata":"{}","thread_id":""}]}
{"id":"spaxel-16z3","title":"Add webhook delivery tests","description":"Write tests for webhook delivery: verifies JSON structure and base64 PNG field. Acceptance Criteria: Webhook delivery tests pass.","status":"closed","priority":2,"issue_type":"task","assignee":"bravo","created_at":"2026-04-11T08:15:08.130589490Z","created_by":"coding","updated_at":"2026-04-11T09:07:17.379388848Z","closed_at":"2026-04-11T09:07:17.379333570Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:1","mitosis-child","mitosis-depth:1","parent-spaxel-40tl"]}
{"id":"spaxel-17u","title":"Phase 9: UX Polish & Accessibility","description":"Goal: Accessible to every household member. Power user efficiency.\n\nDeliverables:\n- Simple mode (card-based mobile-first UI, room occupancy cards, activity feed)\n- Ambient dashboard mode (/ambient for wall tablets, simplified top-down, auto-dim)\n- Spatial quick actions (right-click context menus on 3D elements, follow camera)\n- Command palette (Ctrl+K universal search/command, fuzzy matching)\n- Morning briefing (daily summary card, push notification option)\n- Guided troubleshooting (proactive contextual help, post-feedback explanations)\n- Mobile-responsive expert mode (touch orbit/pan/zoom)\n- Fleet status page (full table, bulk actions, camera fly-to)\n\nExit criteria: Non-technical user can check occupancy without training. Ambient mode runs 7+ days.","status":"closed","priority":3,"issue_type":"phase","assignee":"golf","created_at":"2026-03-27T01:55:55.188364609Z","created_by":"coding","updated_at":"2026-04-10T09:52:30.053325636Z","closed_at":"2026-04-10T09:52:30.053221884Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:2"],"dependencies":[{"issue_id":"spaxel-17u","depends_on_id":"spaxel-2tlm","type":"blocks","created_at":"2026-04-10T02:03:09.311198456Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-17u","depends_on_id":"spaxel-2x1w","type":"blocks","created_at":"2026-04-10T02:03:09.525865595Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-17u","depends_on_id":"spaxel-7b3g","type":"blocks","created_at":"2026-04-10T02:03:09.377986112Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-17u","depends_on_id":"spaxel-bsek","type":"blocks","created_at":"2026-04-10T02:03:09.442882165Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-17u","depends_on_id":"spaxel-duvd","type":"blocks","created_at":"2026-04-10T02:03:09.577884728Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-17u","depends_on_id":"spaxel-eelr","type":"blocks","created_at":"2026-04-10T02:03:09.654765280Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-17u","depends_on_id":"spaxel-jxru","type":"blocks","created_at":"2026-04-10T02:03:09.755196510Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-17u","depends_on_id":"spaxel-sl2","type":"blocks","created_at":"2026-03-28T01:33:53.433780442Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-17u","depends_on_id":"spaxel-trsm","type":"blocks","created_at":"2026-04-10T02:03:09.707647462Z","created_by":"coding","metadata":"{}","thread_id":""}]}
@@ -20,14 +20,14 @@
{"id":"spaxel-2wg","title":"BLE device registry and labelling","description":"## Background\n\nThe firmware scans BLE advertisements every 5 seconds and relays them to the mothership via the bidirectional protocol (spaxel-o4l, Phase 3). Each BLE relay message contains a list of {mac, name, rssi, manufacturer_data} tuples for all devices heard by that node in the last 5 seconds. Phase 6 turns this raw stream into a structured \"People and Devices\" registry where users can label their devices and associate them with named people. This is the identity layer that transforms anonymous CSI blobs into \"Alice\" and \"Bob\".\n\n## BLE Device Auto-Detection\n\nThe mothership can identify device types from manufacturer data embedded in BLE advertisement packets. The Bluetooth SIG assigns Company IDs to manufacturers; the first 2 bytes of manufacturer_data encode the company ID (little-endian).\n\nCompany IDs to detect:\n- 0x004C (Apple): likely iPhone, iPad, AirPods, or Apple Watch. Sub-type from manufacturer data length and flags.\n- 0x0006 (Microsoft): Windows devices\n- 0x0075 (Samsung): Samsung phones/tablets\n- 0x009E (Fitbit): Fitness trackers\n- 0x0157 (Garmin): GPS watches / fitness devices\n- 0x0059 (Nordic): Tile trackers (Nordic Semiconductor is used by many Tile-like devices)\n- 0x0499 (Ruuvi): Ruuvi temperature/humidity sensors\n- 0x00E0 (Google): Android devices (Nearby Share beacons)\nClassify all others as \"Unknown\". The device name field (if present in the advertisement) provides additional signal.\n\nWearable heuristic: RSSI typically -55 to -75 dBm across multiple nodes with relatively consistent signal (worn close to body). Static devices (speakers, tablets) show higher variance. Flags this heuristic as \"possibly wearable\" (not definitive).\n\n## BLERegistry\n\nNew package: mothership/internal/identity/ble.go\n\nBLERegistry struct: backed by SQLite table ble_devices.\n\nSQLite schema:\nCREATE TABLE ble_devices (\n mac TEXT PRIMARY KEY,\n name TEXT,\n manufacturer TEXT,\n device_type TEXT, -- apple_phone, apple_earbuds, fitbit, garmin, tile, samsung, unknown\n label TEXT, -- user-assigned label\n person_id TEXT, -- FK to people.id\n rssi_min INTEGER,\n rssi_max INTEGER,\n rssi_avg INTEGER,\n first_seen DATETIME,\n last_seen DATETIME,\n is_archived BOOLEAN DEFAULT FALSE,\n last_seen_node_mac TEXT\n);\n\nCREATE TABLE people (\n id TEXT PRIMARY KEY, -- uuid\n name TEXT NOT NULL,\n color TEXT, -- hex colour for dashboard rendering\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE TABLE person_devices (\n person_id TEXT,\n device_mac TEXT,\n PRIMARY KEY (person_id, device_mac)\n);\n\nBLERegistry methods:\n- ProcessRelayMessage(nodeMac string, devices []BLEDevice): upsert all devices, update last_seen, update RSSI stats\n- GetDevices(includeArchived bool) []BLEDeviceRecord\n- UpdateLabel(mac, label string) error\n- AssignToPerson(mac, personID string) error\n- CreatePerson(name, color string) (Person, error)\n- GetPeople() []Person\n- ArchiveStale(olderThan time.Duration): set is_archived=true for devices not seen for > olderThan\n\n## BLE MAC Randomisation Handling\n\nModern iPhones and Android phones randomise their BLE MAC address periodically (every 10-15 minutes for iPhones, similar for Android). This is a fundamental privacy feature. The implications for spaxel:\n\n1. The same physical phone appears as multiple different MAC addresses in the registry. The BLERegistry will create new entries for each rotated address.\n2. Long-term tracking of phones by MAC is unreliable. The registry will accumulate many entries for a single phone over time.\n3. Workarounds: (a) Apple uses Resolvable Private Addresses (RPA) that can be resolved with the Identity Resolving Key (IRK) — requires pairing, not available without user action. (b) Device name is sometimes consistent across rotations. (c) Wearable devices (Fitbit, Garmin, AirTag) typically do NOT rotate their MACs — they provide reliable long-term tracking.\n\nThe dashboard must clearly explain this limitation in the \"People and Devices\" panel:\n\"Your phone's Bluetooth address changes regularly for privacy reasons. For reliable person tracking, use a Fitbit, Garmin watch, or AirTag, which have stable addresses.\"\n\nGrouping heuristic: if two devices have the same manufacturer data prefix (first 6 bytes) and name, and were never seen simultaneously at high RSSI from the same node, they are likely the same device with a rotated MAC. Surface this as a \"possible duplicate\" suggestion in the UI: \"These may be the same device: [mac1] and [mac2]. Merge?\"\n\n## REST API\n\nGET /api/ble/devices: returns list of BLEDeviceRecord, optionally filtered by ?archived=true\nGET /api/ble/devices/{mac}: returns single device with full history\nPUT /api/ble/devices/{mac}: update label, device_type, or person assignment. Body: {\"label\":\"Alice's Phone\",\"device_type\":\"apple_phone\",\"person_id\":\"uuid-123\"}\nDELETE /api/ble/devices/{mac}: archive (not hard delete)\n\nGET /api/people: returns list of People with their associated devices\nPOST /api/people: create person. Body: {\"name\":\"Alice\",\"color\":\"#3b82f6\"}\nPUT /api/people/{id}: update name or color\nDELETE /api/people/{id}: soft-delete (retain historical data)\n\n## Dashboard Panel\n\n\"People and Devices\" sidebar panel showing:\n- People section: list of defined people with avatar (initials in circle with their color), device count, last seen time\n - Per person: click to expand, shows associated devices\n - \"Add person\" button opens inline form\n- All devices section (below people): list of devices not yet assigned to a person\n - Per device: device type icon (Apple logo, Fitbit icon, etc.), last seen node (abbreviated), last seen timestamp, RSSI bar\n - Inline label edit on double-click\n - Drag-and-drop to assign to a person card\n - Archive button (hides from active list, accessible via \"Show archived\" toggle)\n- Privacy notice: \"Phones may appear multiple times due to address rotation. Wearables and AirTags have stable addresses.\"\n\n## Tests\n\n- Test device auto-detection: Apple company ID 0x004C -> device_type \"apple_phone\", Fitbit 0x009E -> \"fitbit\"\n- Test that ProcessRelayMessage correctly upserts devices and updates last_seen and RSSI stats\n- Test ArchiveStale marks devices not seen for > 7 days as archived\n- Test person creation and device-to-person assignment API calls\n- Test MAC randomisation handling: two devices with same name and no simultaneous sighting are flagged as possible duplicates\n- Test that archived devices are excluded from GetDevices(false) but included in GetDevices(true)\n\n## Acceptance Criteria\n\n- Discovered BLE devices appear in the dashboard \"People and Devices\" panel within 30 seconds of first observation\n- Device type is auto-detected correctly for Apple, Fitbit, Garmin, and Samsung devices\n- User can assign labels and associate devices with named people via the dashboard UI\n- Drag-and-drop device-to-person assignment works in the UI\n- Devices not seen for > 7 days are automatically archived and hidden from the active list\n- Privacy limitation is clearly documented in the panel UI\n- Possible duplicate MAC-rotated devices are surfaced as merge suggestions\n- Tests pass","status":"closed","priority":3,"issue_type":"task","assignee":"juliet","created_at":"2026-03-28T01:44:02.204633291Z","created_by":"coding","updated_at":"2026-03-29T18:07:39.656772405Z","closed_at":"2026-03-29T18:07:39.656662663Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred"],"dependencies":[{"issue_id":"spaxel-2wg","depends_on_id":"spaxel-c0q","type":"blocks","created_at":"2026-03-28T03:29:14.172209347Z","created_by":"coding","metadata":"{}","thread_id":""}]}
{"id":"spaxel-2x1w","title":"Implement command palette","description":"Ctrl+K universal search/command with fuzzy matching for power user efficiency.","status":"open","priority":2,"issue_type":"task","created_at":"2026-04-10T02:03:09.482985749Z","created_by":"coding","updated_at":"2026-04-10T02:03:09.482985749Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["mitosis-child","mitosis-depth:1","parent-spaxel-17u"]}
{"id":"spaxel-32o","title":"Link weather diagnostics and repositioning advice","description":"## Background\n\nEven with good hardware and correct placement, some links will chronically underperform. A user who placed a node on a metal shelf, behind a TV, or in a corner will see consistently poor detection without understanding why. Telling users \"your detection quality is low\" is useless without telling them what to do about it. Link weather diagnostics provide root-cause analysis and specific, actionable repositioning advice — including 3D visualisation of why a link is performing poorly and where to move a node to fix it.\n\nThe name \"link weather\" is deliberate: just as weather forecasts present complex atmospheric state in human terms (\"partly cloudy with 60% chance of rain\"), link weather presents complex RF state as: \"Node A to Node B: interference detected. Likely cause: microwave oven or 2.4GHz congestion. Try moving Node B 1.5 metres to the right.\"\n\n## DiagnosticEngine\n\nNew module: mothership/internal/diagnostics/linkweather.go\n\nDiagnosticEngine runs as a background goroutine, consuming link health history from SQLite and emitting Diagnosis structs. It runs a full diagnostic pass every 15 minutes.\n\nA Diagnosis struct contains:\n- LinkID string\n- RuleID string (identifies which rule fired)\n- Severity: INFO, WARNING, ACTIONABLE\n- Title string (human-readable headline)\n- Detail string (explanation of the diagnosis in plain language)\n- Advice string (specific actionable steps)\n- RepositioningTarget *Vec3 (3D position to move the node to, or nil if repositioning is not the solution)\n- RepositioningNodeMAC string (which node to move)\n- ConfidenceScore float64 (how confident the diagnostic engine is in this diagnosis)\n\n## Diagnostic Rules\n\nRule 1: Environmental Change\nTrigger: High baseline drift (>5% per hour) correlated across multiple links simultaneously (>50% of active links).\nTitle: \"Environmental change detected\"\nDetail: \"Multiple sensing links are showing simultaneous baseline shifts. This typically indicates a temperature change, or a large object was moved in the space. The system is adapting automatically.\"\nAdvice: \"No action needed. The baseline will re-stabilise within 30 minutes.\"\nRepositioningTarget: nil\nConfidence: 0.85 if drift is correlated across >50% of links\n\nRule 2: WiFi Congestion or Distance\nTrigger: Packet rate health < 0.8 for more than 10 minutes on a single link.\nTitle: \"Node B has low signal rate\"\nDetail: \"Node [B] is only delivering [N]% of the expected [M] packets per second. The most common causes are distance from the WiFi router or congestion from nearby networks.\"\nAdvice: \"1. Move Node [B] within 10 metres of your WiFi router. 2. If already close, check if the 2.4GHz channel is congested (3+ networks on overlapping channels). 3. ESP32-S3 supports both 2.4GHz and 5GHz — if your router supports 5GHz, update Node B's WiFi config to use the 5GHz SSID.\"\nRepositioningTarget: nil (advice is router proximity, not specific coordinates)\n\nRule 3: Near-Field Metal Interference\nTrigger: Low phase stability (< 0.4) sustained for > 30 minutes during known-quiet periods.\nTitle: \"Metal interference near Node [A]\"\nDetail: \"The sensing link [A to B] has unstable phase measurements even when no one is moving. This is typically caused by metal objects in the near field of the node's antenna (within 10cm): metal shelves, radiators, TV backs, or large appliances.\"\nAdvice: \"Check for metal objects within 10cm of Node [A]. If Node [A] is on a metal surface or shelf, mount it on a non-metal bracket or wall. Try repositioning it 20-30cm away from metal surfaces.\"\nRepositioningTarget: nil (advice is clearance from metal, not a specific position)\n\nRule 4: Fresnel Zone Blockage (Half-Room Dead Zone)\nTrigger: Consistent miss rate (>30% of test walks that should be detected are missed) in a specific area of the room, AND the missing area correlates geometrically with an obstacle in the link's Fresnel zone.\nThis rule requires the feedback loop data (Phase 7, spaxel-i28) — specifically the user-submitted false negatives with position information. If no feedback data is available, this rule can trigger heuristically when one side of the room consistently shows lower blob confidence scores.\nTitle: \"Coverage gap detected — possible obstruction\"\nDetail: \"The area near [zone description] shows lower detection coverage. An obstacle may be blocking the path between Node [A] and Node [B], interrupting their sensing zone.\"\nAdvice: \"Move Node [B] [direction] by approximately [distance] to restore coverage. The target position is marked in green in the 3D view.\"\nRepositioningTarget: computed_optimal_position (see below)\n\nRule 5: Periodic Interference Spikes\nTrigger: Periodic spikes in deltaRMS variance (3-10 events per hour, each lasting 1-3 minutes) not correlated with occupancy data (no people detected moving).\nTitle: \"Periodic interference detected\"\nDetail: \"Node [A] to Node [B] is experiencing regular interference bursts [N] times per hour. This pattern is consistent with a microwave oven, a cordless phone, or a pulsed 2.4GHz source.\"\nAdvice: \"Consider the following: 1. Is Node [A] or Node [B] near a kitchen? Microwave ovens cause strong 2.4GHz interference. 2. A cordless DECT phone or baby monitor near one of the nodes may be the source. 3. Try moving the affected node at least 2 metres from any 2.4GHz appliances.\"\nRepositioningTarget: nil (interference is appliance-specific)\n\n## Repositioning Advice in 3D\n\nFor Rule 4 (Fresnel zone blockage), compute the optimal repositioning target:\n1. Use the GDOP-based coverage optimiser from Phase 5 self-healing fleet (spaxel-jc4) to compute the position that maximises GDOP for the blocked zone while keeping all other nodes fixed.\n2. The optimal position is the computed_optimal_position Vec3.\n3. In the 3D dashboard, render a \"ghost\" node at this position: translucent version of the node mesh, with a dashed line from the current position to the ghost position.\n4. Show expected GDOP improvement: \"Moving Node B here would improve detection in the east corner from [N]% to [M]%.\"\n\n## Weekly Reliability Trends\n\nStore daily health score averages in SQLite: link_health_daily (link_id TEXT, date DATE, avg_health REAL, min_health REAL, max_health REAL, PRIMARY KEY (link_id, date)).\n\nA background job runs daily at midnight and writes the day's health averages from the link health log (link_health_log table: link_id, timestamp, composite_score).\n\nDashboard shows for each link: 7-day sparkline of daily average health score. \"Best day\" annotation (highest average) and \"worst day\" annotation (lowest average). This gives users a sense of long-term reliability.\n\n## Files to Create or Modify\n\n- mothership/internal/diagnostics/linkweather.go: DiagnosticEngine and all 5 rules\n- mothership/internal/diagnostics/reposition.go: repositioning target computation\n- mothership/internal/health/linkhealth.go: add link_health_log table writes\n- dashboard/js/linkhealth.js: link health panel, diagnostics display, ghost node rendering\n- mothership/internal/dashboard/routes.go: GET /api/links/{id}/diagnostics, GET /api/links/{id}/health-history\n\n## Tests\n\n- Test Rule 1 (environmental change): inject simultaneous high-drift events across 60% of links, verify diagnosis fires with Severity=INFO\n- Test Rule 2 (WiFi congestion): inject packet_rate=0.7 for 15 minutes, verify diagnosis fires with appropriate advice text\n- Test Rule 3 (metal interference): inject phase_stability=0.3 for 35 minutes during a quiet window, verify diagnosis fires\n- Test Rule 4 (Fresnel blockage): requires feedback data — inject synthetic false-negative feedback events clustered in one spatial zone, verify diagnosis fires and RepositioningTarget is non-nil\n- Test Rule 5 (periodic interference): inject 5 deltaRMS variance spikes per hour for 2 hours, verify diagnosis fires with correct periodicity estimate\n- Test weekly trend aggregation: inject 7 days of health scores, verify daily averages are correctly computed and stored\n- Test that repositioning target is within room bounds and improves GDOP\n\n## Acceptance Criteria\n\n- All 5 diagnostic rules fire correctly on synthetic test data that matches their trigger conditions\n- Repositioning advice for Rule 4 appears as a ghost node in the 3D dashboard view\n- Expected GDOP improvement shown alongside repositioning ghost node\n- Weekly 7-day sparkline visible in link health panel for each link\n- Diagnostics accessible via API and displayed in Link Health panel on link click\n- Tests pass","status":"closed","priority":3,"issue_type":"task","assignee":"juliet","created_at":"2026-03-28T01:43:13.596164634Z","created_by":"coding","updated_at":"2026-03-29T18:07:39.683230580Z","closed_at":"2026-03-29T18:07:39.683089345Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred"],"dependencies":[{"issue_id":"spaxel-32o","depends_on_id":"spaxel-axa","type":"blocks","created_at":"2026-03-28T03:29:14.023730499Z","created_by":"coding","metadata":"{}","thread_id":""}]}
-{"id":"spaxel-35lb","title":"Add test-notification endpoint integration test","description":"Write integration test for test-notification endpoint fires correctly. Acceptance Criteria: Test endpoint integration test passes.","status":"in_progress","priority":2,"issue_type":"task","assignee":"bravo","created_at":"2026-04-11T08:15:08.173375326Z","created_by":"coding","updated_at":"2026-04-11T09:22:39.584816855Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:3","mitosis-child","mitosis-depth:1","parent-spaxel-40tl"]}
+{"id":"spaxel-35lb","title":"Add test-notification endpoint integration test","description":"Write integration test for test-notification endpoint fires correctly. Acceptance Criteria: Test endpoint integration test passes.","status":"closed","priority":2,"issue_type":"task","assignee":"bravo","created_at":"2026-04-11T08:15:08.173375326Z","created_by":"coding","updated_at":"2026-04-11T10:40:05.106805090Z","closed_at":"2026-04-11T10:40:05.106665541Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:13","mitosis-child","mitosis-depth:1","parent-spaxel-40tl"]}
{"id":"spaxel-3ca","title":"Add time-travel debugging","description":"Implement:\n- Pause live mode\n- Timeline scrubbing\n- Replay 3D from recorded CSI data\n\nAcceptance: Can replay 24 hours of historical data with full 3D visualization.","status":"closed","priority":2,"issue_type":"task","assignee":"golf","created_at":"2026-04-09T14:54:38.737598265Z","created_by":"coding","updated_at":"2026-04-09T17:41:51.707526513Z","closed_at":"2026-04-09T17:41:51.707468066Z","close_reason":"Time-travel debugging implementation complete. All acceptance criteria met:\n- Pause live mode: Implemented in dashboard/js/replay.js with Pause Live button\n- Timeline scrubbing: Full scrubber UI with seek functionality \n- Replay 3D from recorded CSI: Viz3D integration with enterReplayMode/exitReplayMode/updateReplayBlobs\n- 24-hour replay: Recording buffer supports 48-hour retention (exceeds requirement)\n\nBackend (mothership/internal/api/replay.go, replay/worker.go):\n- REST API for session management (start, stop, seek, tune, set-speed, set-state)\n- Separate signal processing pipeline for replay\n- Blob broadcasting to dashboard\n\nFrontend (dashboard/js/replay.js):\n- Complete replay controls UI\n- Parameter tuning panel with instant preview\n- Timeline loop polling session state\n\n3D Visualization (dashboard/js/viz3d.js):\n- Stores/restores live blob states during replay transitions\n- Full 3D blob rendering from replay data\n\nVerification: Comprehensive test suite exists (replay_test.go) covering session lifecycle, multiple sessions, parameter tuning, and timestamp parsing.","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:20","mitosis-child","mitosis-depth:1","parent-spaxel-sl2"]}
{"id":"spaxel-3ps","title":"Detection feedback loop and accuracy tracking","description":"## Background\n\nEvery detection algorithm produces errors. False positives (detected presence when no one is there) are annoying and erode trust. False negatives (missed detection of a real person) are dangerous for safety applications. The feedback loop gives users a direct mechanism to correct errors and the system learns from those corrections. Showing users measurable improvement over time (\"You've provided 47 corrections. Accuracy improved 12% this week\") creates a virtuous engagement loop and transforms users into active participants in improving the system.\n\n## Feedback UI Elements\n\nEvery detection event exposed to the user should have feedback affordances. Three contexts:\n\n1. Dashboard 3D view: Each active track has a small thumbs-up/down icon that appears on hover/focus. Clicking thumbs-down opens a quick inline form.\n\n2. Activity timeline (Phase 8): Every detection event entry has thumbs-up/thumbs-down at the end of the row. Space-efficient: 2 icon buttons.\n\n3. Push notifications: Fall and anomaly notifications include a quick-reply option (via ntfy actions or Pushover callbacks): \"False alarm — clear this.\"\n\n4. \"I was here and wasn't detected\" button: On the timeline panel, a button \"Report missed detection\" opens a form: \"When? [time picker, default: now]\", \"Where? [zone picker]\", \"Who? [person picker, optional]\". Submits as a FALSE_NEGATIVE feedback event with the user-provided position.\n\nFeedback form for thumbs-down:\n- \"What was wrong?\" (radio buttons):\n - \"No one was there (false alarm)\"\n - \"Someone was missed at this location\"\n - \"Wrong person identified\"\n - \"Wrong zone/location\"\n- Optional free-text \"Notes\" field\n- Submit / Cancel\n\n## Feedback Storage\n\nSQLite schema:\nCREATE TABLE detection_feedback (\n id TEXT PRIMARY KEY,\n event_id TEXT, -- references events table (activity timeline)\n event_type TEXT, -- \"blob_detection\", \"zone_transition\", \"fall_alert\", \"anomaly\"\n feedback_type TEXT, -- \"TRUE_POSITIVE\", \"FALSE_POSITIVE\", \"FALSE_NEGATIVE\", \"WRONG_IDENTITY\", \"WRONG_ZONE\"\n details_json TEXT, -- {\"zone_id\":\"...\", \"person_id\":\"...\", \"notes\":\"...\"}\n timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,\n applied BOOLEAN DEFAULT FALSE, -- set to TRUE after weight refinement processes it\n processed_at DATETIME\n);\n\nThe applied flag enables incremental processing: the weight learner (Phase 7 self-improving localisation) queries WHERE applied = FALSE, processes batches, and marks them TRUE.\n\n## Accuracy Metrics\n\nCompute precision/recall/F1 per link, per zone, and per person weekly. This requires knowing the true positives, false positives, and false negatives.\n\nGround truth sources:\n- User thumbs-up -> TRUE_POSITIVE for the corresponding detection event\n- User thumbs-down (false alarm) -> FALSE_POSITIVE for the detection event\n- User \"missed detection\" report -> FALSE_NEGATIVE for the reported time/zone\n\nNote: ground truth is sparse — users will not feedback every event. We use the feedback we have as a sample. Assume events without feedback are TRUE_POSITIVE for the purpose of precision estimates (conservative: this means precision is an upper bound, not exact).\n\nMetrics computed weekly:\n- precision = TP / (TP + FP) — of all detections, what fraction were correct\n- recall = TP / (TP + FN) — of all true presence events, what fraction were detected\n- F1 = 2 * precision * recall / (precision + recall)\n- Per-link metrics: which links have the most false positives (worst precision)\n- Per-zone metrics: which zones are most often missed (worst recall)\n\nStorage: detection_accuracy (week TEXT, scope_type TEXT, scope_id TEXT, precision REAL, recall REAL, f1 REAL, tp_count INT, fp_count INT, fn_count INT, computed_at DATETIME). Scope types: \"system\", \"link\", \"zone\", \"person\".\n\n## Accuracy Trend Display\n\nDashboard \"Accuracy\" panel (in expert mode):\n- Overall accuracy gauge: composite F1 score as a circular gauge (0-100%)\n- Week-over-week trend graph: sparkline of weekly F1 over the last 8 weeks\n- \"You've provided N corrections. Your accuracy improved X% this week.\" — motivational counter\n- Per-zone breakdown: bar chart of precision/recall per zone (click a zone bar to jump to it in 3D view)\n- Per-link breakdown: link health vs. feedback score correlation (are high-health links also high-accuracy?)\n- Feedback count: total corrections given, open corrections (not yet processed), processed corrections\n\nThe accuracy trend display intentionally shows the improvement trajectory, not just the absolute value, to reinforce that feedback has an effect.\n\n## Feedback Application\n\nProcessing happens in a background goroutine (mothership/internal/learning/feedback_processor.go) that runs every 6 hours or when triggered manually.\n\nFor FALSE_POSITIVE events with associated CSI data (in the recording buffer from Phase 2):\n- Retrieve the CSI data from the recording buffer at the event timestamp for all links\n- Add the CSI frame data to a \"known false positive\" set in SQLite: false_positive_frames (link_id, timestamp, delta_rms, context_json)\n- The weight learner (self-improving localisation bead) uses this set as negative examples\n\nFor FALSE_NEGATIVE events with user-reported position:\n- Add to \"known false negative\" set: false_negative_frames (link_id, timestamp, expected_position_xyz, context_json)\n- The weight learner uses this as a positive example at the specified position\n\nAfter processing, mark feedback.applied = TRUE.\n\n## Files to Create or Modify\n\n- mothership/internal/learning/feedback_processor.go: feedback processing pipeline\n- mothership/internal/analytics/accuracy.go: weekly metric computation\n- dashboard/js/feedback.js: thumbs-up/down UI components (reusable across 3D view and timeline)\n- dashboard/js/accuracy.js: Accuracy panel rendering\n- mothership/internal/dashboard/routes.go: POST /api/feedback, GET /api/accuracy\n\n## Tests\n\n- Test feedback storage: POST /api/feedback with each feedback_type, verify SQLite record created\n- Test accuracy metric computation with synthetic TP/FP/FN data: 8 TP, 2 FP, 1 FN -> precision=0.8, recall=0.888\n- Test weekly rollup: 7 days of daily feedback -> correctly aggregated weekly metric\n- Test that applied=false events are found and marked as applied after processor run\n- Test \"improvements\" counter: feedback_count increases on each POST /api/feedback call\n\n## Acceptance Criteria\n\n- Thumbs-up/down buttons appear on active tracks in 3D view and on all timeline events\n- \"Missed detection\" button and form available in timeline panel\n- Feedback stored in SQLite with correct feedback_type and details\n- Accuracy metrics computed weekly and stored in detection_accuracy table\n- Accuracy panel shows week-over-week trend (requires at least 2 weeks of data)\n- Feedback improvement counter shows correct counts\n- Applied flag correctly set after processor run\n- Tests pass","status":"closed","priority":3,"issue_type":"task","assignee":"sp4","created_at":"2026-03-28T01:49:50.419277632Z","created_by":"coding","updated_at":"2026-03-29T22:08:03.778130122Z","closed_at":"2026-03-29T22:08:03.778000167Z","close_reason":"Implementation complete: feedback storage (SQLite), accuracy computation (precision/recall/F1 weekly), feedback processor (6h interval), API endpoints (/api/learning/*), frontend feedback UI (thumbs up/down, missed detection form), accuracy panel (F1 gauge, sparkline, per-zone breakdown). All 12 tests pass.","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:1"],"dependencies":[{"issue_id":"spaxel-3ps","depends_on_id":"spaxel-zvs","type":"blocks","created_at":"2026-03-28T03:29:14.442377218Z","created_by":"coding","metadata":"{}","thread_id":""}]}
{"id":"spaxel-3rd","title":"Wire WebSocket integration for zone changes","description":"Ensure zone changes from CRUD endpoints reflect in live 3D view within one WebSocket cycle. Acceptance: creating/updating/deleting a zone via REST API triggers an update broadcast through the WebSocket system.","status":"closed","priority":2,"issue_type":"task","assignee":"echo","created_at":"2026-04-07T17:01:33.587080369Z","created_by":"coding","updated_at":"2026-04-07T18:42:55.455708044Z","closed_at":"2026-04-07T18:42:55.455446177Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","mitosis-child","mitosis-depth:1","parent-spaxel-0ii"]}
{"id":"spaxel-403","title":"Implement anomaly detection & security mode","description":"Build pattern learning and anomaly detection for security.\n\nDeliverables:\n- 7-day pattern learning algorithm\n- Anomaly scoring against learned patterns\n- Security mode integration\n\nAcceptance: System detects deviations from learned patterns; accuracy improves measurably over 4 weeks.","status":"closed","priority":2,"issue_type":"task","assignee":"golf","created_at":"2026-03-29T19:25:04.187535979Z","created_by":"coding","updated_at":"2026-04-09T12:18:14.752621360Z","closed_at":"2026-04-09T12:18:14.752279788Z","close_reason":"Anomaly detection & security mode implementation verified complete.\n\nDeliverables implemented:\n- 7-day pattern learning algorithm with Welford's online algorithm (analytics/patterns.go)\n- Anomaly scoring against learned patterns with z-score based computation\n- Security mode integration with Armed/Disarmed/ArmedStay states\n\nAcceptance criteria met:\n- System detects deviations from learned patterns via multiple anomaly types (UnusualHour, UnknownBLE, MotionDuringAway, UnusualDwell)\n- Accuracy improves measurably through feedback loop integration with learning/feedback_store\n\nKey components:\n- PatternLearner: 7-day cold start, hourly pattern updates, per-slot readiness checking\n- Detector: Multiple anomaly types, configurable thresholds, alert chain with timers\n- Security API: /api/security/arm, /api/security/disarm, /api/security/status\n- Alert Handler: Dashboard → webhook → escalation notification chain\n- Integration: Fully wired in main.go with zones, BLE registry, dashboard, and feedback store","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:922","mitosis-child","mitosis-depth:1","parent-spaxel-i28"]}
-{"id":"spaxel-40tl","title":"Write comprehensive tests for notification system","description":"Add test files for all notification components. Tests must cover: floor-plan renderer produces 300x300 PNG with correct dimensions, zone boundaries appear at correct pixel coordinates, batching behavior (3 LOW events in 10s -> 1 notification, 1 URGENT -> immediate), quiet hours gate (LOW at 23:00 with 22:00-07:00 quiet hours -> queued, URGENT at 23:00 -> delivered), morning digest delivery bundles queued events at quiet_hours_end, ntfy delivery with mock HTTP server verifies headers/body, webhook delivery verifies JSON structure and base64 PNG field, test-notification endpoint fires correctly.\n\nAcceptance Criteria:\n- All renderer tests pass (dimensions, coordinates, colors)\n- All batching tests pass (windowing, priority bypass)\n- All quiet hours tests pass (queueing, bypass, digest)\n- All delivery client tests pass with mocks\n- Test endpoint integration test passes\n- Test coverage >= 80% for notification packages","status":"open","priority":2,"issue_type":"task","created_at":"2026-04-10T12:19:08.646045806Z","created_by":"coding","updated_at":"2026-04-11T08:15:08.208399293Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:1","mitosis-child","mitosis-depth:1","parent-spaxel-zpt"],"dependencies":[{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-0fm8","type":"blocks","created_at":"2026-04-11T08:15:08.008025729Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-16z3","type":"blocks","created_at":"2026-04-11T08:15:08.148112051Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-28j7","type":"blocks","created_at":"2026-04-11T08:15:07.907058347Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-35lb","type":"blocks","created_at":"2026-04-11T08:15:08.208324942Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-4frg","type":"blocks","created_at":"2026-04-11T08:15:08.056467899Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-k0rs","type":"blocks","created_at":"2026-04-11T08:15:07.972516975Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-wekq","type":"blocks","created_at":"2026-04-11T08:15:08.101758877Z","created_by":"coding","metadata":"{}","thread_id":""}]}
+{"id":"spaxel-40tl","title":"Write comprehensive tests for notification system","description":"Add test files for all notification components. Tests must cover: floor-plan renderer produces 300x300 PNG with correct dimensions, zone boundaries appear at correct pixel coordinates, batching behavior (3 LOW events in 10s -> 1 notification, 1 URGENT -> immediate), quiet hours gate (LOW at 23:00 with 22:00-07:00 quiet hours -> queued, URGENT at 23:00 -> delivered), morning digest delivery bundles queued events at quiet_hours_end, ntfy delivery with mock HTTP server verifies headers/body, webhook delivery verifies JSON structure and base64 PNG field, test-notification endpoint fires correctly.\n\nAcceptance Criteria:\n- All renderer tests pass (dimensions, coordinates, colors)\n- All batching tests pass (windowing, priority bypass)\n- All quiet hours tests pass (queueing, bypass, digest)\n- All delivery client tests pass with mocks\n- Test endpoint integration test passes\n- Test coverage >= 80% for notification packages","status":"in_progress","priority":2,"issue_type":"task","assignee":"bravo","created_at":"2026-04-10T12:19:08.646045806Z","created_by":"coding","updated_at":"2026-04-11T10:50:09.370950475Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:2","mitosis-child","mitosis-depth:1","parent-spaxel-zpt"],"dependencies":[{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-0fm8","type":"blocks","created_at":"2026-04-11T08:15:08.008025729Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-16z3","type":"blocks","created_at":"2026-04-11T08:15:08.148112051Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-28j7","type":"blocks","created_at":"2026-04-11T08:15:07.907058347Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-35lb","type":"blocks","created_at":"2026-04-11T08:15:08.208324942Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-4frg","type":"blocks","created_at":"2026-04-11T08:15:08.056467899Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-k0rs","type":"blocks","created_at":"2026-04-11T08:15:07.972516975Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-40tl","depends_on_id":"spaxel-wekq","type":"blocks","created_at":"2026-04-11T08:15:08.101758877Z","created_by":"coding","metadata":"{}","thread_id":""}]}
{"id":"spaxel-4fg","title":"Implement Replay/Time-Travel REST endpoints","description":"Implement GET /api/replay/sessions to list recording sessions. Add POST endpoints: /api/replay/start to start replay at timestamp, /api/replay/stop to return to live, /api/replay/seek to seek within session, /api/replay/tune to update pipeline parameters mid-replay. Include OpenAPI-style godoc comments.","status":"closed","priority":2,"issue_type":"task","assignee":"alpha","created_at":"2026-04-06T15:31:10.497876498Z","created_by":"coding","updated_at":"2026-04-07T13:20:09.903154198Z","closed_at":"2026-04-07T13:20:09.902983511Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["mitosis-child","mitosis-depth:1","parent-spaxel-6ha"]}
-{"id":"spaxel-4frg","title":"Add morning digest tests","description":"Write tests for morning digest delivery: bundles queued events at quiet_hours_end. Acceptance Criteria: Morning digest tests pass.","status":"in_progress","priority":2,"issue_type":"task","assignee":"alpha","created_at":"2026-04-11T08:15:08.033947792Z","created_by":"coding","updated_at":"2026-04-11T09:19:40.113718797Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:3","mitosis-child","mitosis-depth:1","parent-spaxel-40tl"]}
+{"id":"spaxel-4frg","title":"Add morning digest tests","description":"Write tests for morning digest delivery: bundles queued events at quiet_hours_end. Acceptance Criteria: Morning digest tests pass.","status":"closed","priority":2,"issue_type":"task","assignee":"alpha","created_at":"2026-04-11T08:15:08.033947792Z","created_by":"coding","updated_at":"2026-04-11T09:24:34.821263381Z","closed_at":"2026-04-11T09:24:34.821202594Z","close_reason":"Morning digest tests implemented and passing. All 8 morning digest tests pass covering queuing at quiet_hours_end, disabled behavior, once-per-day, empty handling, event inclusion, queue clearing, mixed priorities, and title format. Acceptance criteria met.","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:3","mitosis-child","mitosis-depth:1","parent-spaxel-40tl"]}
{"id":"spaxel-4u6","title":"events: SQLite schema, FTS5 table, indexes, and 90-day archive job","description":"## Overview\nCreate the SQLite storage layer for the unified activity timeline (part 1 of spaxel-2ap split).\n\n## Schema to create in mothership/internal/events/ (db setup or migration)\n```sql\nCREATE TABLE IF NOT EXISTS events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n type TEXT NOT NULL,\n timestamp_ms INTEGER NOT NULL,\n zone TEXT,\n person TEXT,\n blob_id TEXT,\n detail_json TEXT,\n severity TEXT\n);\n\nCREATE VIRTUAL TABLE IF NOT EXISTS fts_events USING fts5(\n type, zone, person, detail_json,\n content='events', content_rowid='id'\n);\n\nCREATE INDEX IF NOT EXISTS idx_events_ts ON events(timestamp_ms DESC);\nCREATE INDEX IF NOT EXISTS idx_events_type ON events(type);\nCREATE INDEX IF NOT EXISTS idx_events_zone ON events(zone);\nCREATE INDEX IF NOT EXISTS idx_events_person ON events(person);\n\nCREATE TABLE IF NOT EXISTS events_archive (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n type TEXT NOT NULL,\n timestamp_ms INTEGER NOT NULL,\n zone TEXT, person TEXT, blob_id TEXT, detail_json TEXT, severity TEXT\n);\n```\n\n## Archive job\n- In `events` package, add `RunArchiveJob(db *sql.DB)` that runs nightly at 02:00 local time\n- Migrates rows from `events` where `timestamp_ms < now - 90 days` into `events_archive`\n- Deletes moved rows from `events`\n\n## Go types\n```go\ntype Event struct {\n ID int64\n Type string\n TimestampMs int64\n Zone string\n Person string\n BlobID string\n DetailJSON string\n Severity string\n}\n\nfunc InsertEvent(db *sql.DB, e Event) error\nfunc QueryEvents(db *sql.DB, params QueryParams) ([]Event, string, bool, error)\n```\n\n## Verify\n```bash\ncd /home/coding/spaxel/mothership && PATH=$PATH:/home/coding/go/bin go build ./internal/events/\n```","status":"closed","priority":2,"issue_type":"task","assignee":"charlie","created_at":"2026-04-06T22:30:57.090344045Z","created_by":"coding","updated_at":"2026-04-07T16:45:36.428356135Z","closed_at":"2026-04-07T16:45:36.428249897Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:2"]}
{"id":"spaxel-51k","title":"OTA firmware update system","description":"## Background\n\nOnce nodes are deployed in a home, they need to be updated without physical access. ESP-IDF has a mature OTA (Over-The-Air) update mechanism: two OTA flash partitions (factory, ota_0, ota_1 as defined in firmware/partitions.csv), HTTP download to the inactive partition, cryptographic verification, set boot partition, reboot. The mothership serves firmware binaries and triggers the update via a WebSocket downstream command. Phase 1 laid the groundwork in the firmware; this bead completes the mothership side.\n\n## What Already Exists\n\nfirmware/main/websocket.c has OTA command handling and an ota_download_task that handles the HTTP download to the inactive OTA partition. The partition table in firmware/partitions.csv has factory + ota_0 + ota_1 slots. The firmware parses {type:\"ota\", url:\"...\", md5:\"...\", version:\"...\"} downstream commands and initiates the download. What is missing is:\n- The mothership HTTP server for firmware binary serving\n- The REST API for triggering OTA per-node or fleet-wide\n- The firmware manifest for version management\n- The rollback detection logic on the mothership side\n- The dashboard UI for OTA management\n\n## Mothership Firmware Serving\n\nGET /firmware/latest or GET /firmware/{version}: serves the compiled .bin file from the /firmware volume mount. The response must include:\n- Content-Length header (required by ESP-IDF OTA HTTP client for progress reporting)\n- ETag header (MD5 of the binary, for caching)\n- Content-Type: application/octet-stream\n\nFirmware binaries are placed in the /firmware volume mount (configured in docker-compose.yml or k8s volume mount). The mothership reads the firmware manifest on startup and re-reads it when a new file appears (inotify watch or periodic re-scan every 60s).\n\n## Firmware Manifest\n\nFile: /firmware/manifest.json — auto-generated by the CI build process, or manually created.\nFormat: list of objects, each with version (semver string), filename (basename within /firmware/), md5 (hex string of binary MD5), size (integer bytes), build_timestamp (ISO8601).\nThe mothership's \"latest\" version is determined by sorting manifest entries by semver and taking the highest.\n\n## OTA Trigger API\n\nPOST /api/nodes/{mac}/ota — trigger OTA for a specific node\nRequest body: {\"version\": \"0.2.0\"} (optional; defaults to latest if omitted)\nResponse: {\"job_id\": \"abc123\", \"node_mac\": \"aa:bb:cc:dd:ee:ff\", \"target_version\": \"0.2.0\", \"status\": \"initiated\"}\n\nThe mothership looks up the node's active WebSocket session in the connection registry and sends the OTA command:\n{\"type\":\"ota\",\"url\":\"http://{mothership_ip}:{port}/firmware/0.2.0\",\"md5\":\"{hex_md5}\",\"version\":\"0.2.0\"}\n\nThe firmware immediately begins the download in a background task, sends ota_status messages ({\"type\":\"ota_status\",\"progress\":45,\"status\":\"downloading\"}) which the mothership logs and broadcasts to the dashboard.\n\n## Fleet Rolling Update\n\nPOST /api/ota/fleet — trigger OTA for all connected nodes\nRequest body: {\"version\": \"0.2.0\", \"stagger_seconds\": 30} (default stagger: 30s)\n\nThe rolling update coordinator in the mothership triggers OTA for the first node, waits stagger_seconds, then the next, and so on. This ensures:\n- Not all nodes reboot simultaneously (avoids a coverage gap window)\n- If a node fails OTA, the remaining nodes can be halted before more disruption\n- Fleet update progress is visible in dashboard per-node\n\nThe fleet update job is stored in SQLite (ota_jobs table) and survives mothership restarts.\n\n## Rollback Detection\n\nESP-IDF automatically rolls back to the previous firmware if the new image does not call esp_ota_mark_app_valid_cancel_rollback() within a boot window (the firmware does this on successful WebSocket connection to the mothership). The mothership detects rollback by comparing the firmware_version field in the hello message after OTA against the requested target version. If they differ, the mothership logs an OTA rollback event and updates the node's status to \"rollback\".\n\n## Dashboard OTA UI\n\nAdd an OTA panel to the dashboard settings or fleet page:\n- Per-node: current firmware version, available version (if newer), \"Update\" button\n- Fleet: \"Update All\" button with stagger slider, progress per node (with percentage from ota_status messages), last updated time per node\n- Version history: per-node firmware version history in tooltip or expandable row\n- Rollback indicator: nodes that rolled back are highlighted with a warning and the reason (if known)\n\n## Files to Create or Modify\n\n- mothership/internal/ota/server.go: firmware file serving with Content-Length and ETag\n- mothership/internal/ota/manifest.go: manifest parsing and latest-version logic\n- mothership/internal/ota/jobs.go: OTA job creation, fleet rolling update coordinator, status tracking\n- mothership/internal/dashboard/routes.go: register OTA API routes\n- dashboard/js/fleet.js or dashboard/js/ota.js: OTA UI panel\n\n## Tests\n\n- Test OTA command JSON serialisation matches firmware's expected format exactly\n- Test rolling update stagger timing with a mock time source (use a clock interface for testability)\n- Test that firmware version in hello message is parsed and stored in the node registry\n- Test manifest parsing: valid manifest, empty manifest, malformed manifest\n- Test rollback detection when hello version does not match target version\n\n## Acceptance Criteria\n\n- OTA command reaches firmware and triggers download (verified via ota_status messages)\n- Rolling update staggers correctly with the configured delay between nodes\n- After successful OTA, node reconnects with new firmware version in hello message\n- Rollback is detectable via hello version mismatch and displayed in dashboard\n- MD5 verification failure in firmware logs an error and the old firmware remains running\n- Fleet update status visible per-node in dashboard\n- Tests pass","status":"closed","priority":2,"issue_type":"task","created_at":"2026-03-28T01:37:32.472078279Z","created_by":"coding","updated_at":"2026-03-28T05:36:39.250035631Z","closed_at":"2026-03-28T05:36:39.249972673Z","close_reason":"Implemented: ota/manager.go + ota/server.go (fb69190) — HTTP firmware serving from /firmware volume, WebSocket-triggered OTA command, rolling update with 30s stagger, MD5 verification, firmware manifest.json, rollback detection via hello version mismatch","source_repo":".","compaction_level":0,"original_size":0,"dependencies":[{"issue_id":"spaxel-51k","depends_on_id":"spaxel-uc9","type":"blocks","created_at":"2026-03-28T03:29:13.874999678Z","created_by":"coding","metadata":"{}","thread_id":""}]}
{"id":"spaxel-54i","title":"load-shedding: add per-iteration timing and rolling avg to ProcessorManager","description":"## Task\nAdd pipeline timing and a 5-iteration rolling average to `ProcessorManager` in `mothership/internal/signal/processor.go`.\n\n## Changes to ProcessorManager struct (lines 221-228)\nAdd these fields:\n```go\ntype ProcessorManager struct {\n // ... existing fields ...\n iterDurations [5]time.Duration // ring buffer for last 5 iteration times\n iterIdx int // next write index (mod 5)\n iterCount int // how many values filled (0-5)\n shedLevel int // current load shedding level (0-3)\n steadyCount int // consecutive iters below recovery threshold\n}\n```\n\n## Changes to LinkProcessor.Process() (line 54)\nWrap the entire Process body to time it. At the START of Process():\n```go\nt0 := time.Now()\n```\nAt the END of Process(), before return, update the manager's ring buffer. BUT — Process is on LinkProcessor, not ProcessorManager. So instead, add timing to ProcessorManager.Process() (line 252):\n\n```go\nfunc (pm *ProcessorManager) Process(linkID string, ...) (*ProcessResult, error) {\n t0 := time.Now()\n // ... existing lock + delegate to processor ...\n result, err := processor.Process(payload, rssiDBm, nSub, recvTime)\n pm.mu.Unlock() // already have write lock\n elapsed := time.Since(t0)\n pm.updateShedding(elapsed)\n return result, err\n}\n```\n\n## New method updateShedding(elapsed time.Duration)\n```go\nfunc (pm *ProcessorManager) updateShedding(elapsed time.Duration) {\n pm.iterDurations[pm.iterIdx%5] = elapsed\n pm.iterIdx++\n if pm.iterCount < 5 { pm.iterCount++ }\n\n // compute rolling avg\n var sum time.Duration\n for i := 0; i < pm.iterCount; i++ {\n sum += pm.iterDurations[i]\n }\n avg := sum / time.Duration(pm.iterCount)\n\n // level up\n if avg >= 95*time.Millisecond && pm.shedLevel < 3 {\n pm.shedLevel = 3; pm.steadyCount = 0\n } else if avg >= 90*time.Millisecond && pm.shedLevel < 2 {\n pm.shedLevel = 2; pm.steadyCount = 0\n } else if avg >= 80*time.Millisecond && pm.shedLevel < 1 {\n pm.shedLevel = 1; pm.steadyCount = 0\n }\n\n // recovery: step down one level when avg < 60ms for 10 consecutive iters\n if avg < 60*time.Millisecond {\n pm.steadyCount++\n if pm.steadyCount >= 10 && pm.shedLevel > 0 {\n pm.shedLevel--\n pm.steadyCount = 0\n }\n } else {\n pm.steadyCount = 0\n }\n}\n```\n\n## New getter\n```go\nfunc (pm *ProcessorManager) GetShedLevel() int {\n pm.mu.RLock()\n defer pm.mu.RUnlock()\n return pm.shedLevel\n}\n```\n\nNote: `updateShedding` must NOT hold `pm.mu` because it's called after unlock. The iterDurations ring buffer is only written from `Process` so it is already serialized by the caller's lock sequence. Add a separate `mu` for the shed state or call updateShedding while still holding pm.mu — simplest: call it BEFORE Unlock, while still holding the write lock.\n\n## Verify\n```bash\ncd /home/coding/spaxel/mothership && PATH=$PATH:/home/coding/go/bin go build ./...\n```","status":"closed","priority":2,"issue_type":"task","assignee":"bravo","created_at":"2026-04-07T06:33:03.697771676Z","created_by":"coding","updated_at":"2026-04-07T16:53:42.209613205Z","closed_at":"2026-04-07T16:53:42.209404722Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0}
@@ -107,7 +107,7 @@
{"id":"spaxel-jkw","title":"Add Identify context menu to 3D view","description":"Add 'Identify (blink LED)' option to the right-click context menu in the 3D view that POSTs to /api/nodes/{mac}/identify.\n\n**Acceptance:**\n- 3D view right-click menu has 'Identify (blink LED)' option","status":"closed","priority":2,"issue_type":"task","assignee":"golf","created_at":"2026-04-09T11:11:50.047388206Z","created_by":"coding","updated_at":"2026-04-09T11:32:19.559003892Z","closed_at":"2026-04-09T11:32:19.558903935Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:1","mitosis-child","mitosis-depth:1","parent-spaxel-h58"]}
{"id":"spaxel-jv8q","title":"Cap devicePixelRatio on mobile","description":"On screens < 1024px width, cap devicePixelRatio at 2.0 using Math.min(window.devicePixelRatio, 2.0) in renderer initialization.","status":"open","priority":2,"issue_type":"task","created_at":"2026-04-11T06:59:34.136495463Z","created_by":"coding","updated_at":"2026-04-11T06:59:34.136495463Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["mitosis-child","mitosis-depth:1","parent-spaxel-gufk"]}
{"id":"spaxel-jxru","title":"Build fleet status page","description":"Full table view with bulk actions and camera fly-to functionality.","status":"closed","priority":2,"issue_type":"task","assignee":"golf","created_at":"2026-04-10T02:03:09.725489218Z","created_by":"coding","updated_at":"2026-04-10T09:39:43.690167347Z","closed_at":"2026-04-10T09:39:43.690013432Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:4","mitosis-child","mitosis-depth:1","parent-spaxel-17u"]}
-{"id":"spaxel-jy4","title":"Crowd flow visualisation","description":"## Background\n\nOver days and weeks, the movement patterns of household members accumulate into meaningful flows: the main corridor between bedroom and bathroom, the typical path from the front door to the kitchen, habitual dwell spots (the favourite chair, the home office desk, the kitchen counter). Visualising these as directional flow maps and dwell hotspot heatmaps provides useful insight into how the space is actually used — and can inform furniture placement, automation placement, and even architectural decisions. It's also a compelling visual that demonstrates the system's accumulated knowledge.\n\n## FlowAccumulator\n\nNew package: mothership/internal/analytics/flow.go\n\nFlowAccumulator subscribes to TrackManager updates (10 Hz) and accumulates trajectory data.\n\nTrajectory sampling: for each track update, if the track has moved > 0.2m since the last recorded waypoint (for that track), record the movement:\n- from_xyz: last waypoint position\n- to_xyz: current position\n- speed: metres per second at this step\n- person_id: if identity is known\n- timestamp\n\nThis 0.2m threshold prevents accumulating thousands of micro-samples for stationary people.\n\nSQLite table: trajectory_segments (id TEXT PRIMARY KEY, person_id TEXT, from_x REAL, from_y REAL, from_z REAL, to_x REAL, to_y REAL, to_z REAL, speed REAL, timestamp DATETIME). Only store ground plane (from_z and to_z floor-projected: set to 0 for the flow map, since we render on the ground plane).\n\nTable growth management: the table accumulates indefinitely. Prune segments older than 90 days (configurable) with a daily background job. With 4 people at typical home movement rates, 90 days generates approximately 50,000 segments — manageable for SQLite.\n\n## Flow Map Computation\n\nQuery: for each 0.25m grid cell (same resolution as OccupancyGrid in FusionEngine), average the movement vectors of all trajectory segments that pass through that cell.\n\nSQL approach: for each segment, determine which grid cells it passes through (Bresenham's line algorithm on the grid). Accumulate vector components (to_x - from_x, to_y - from_y) into per-cell accumulators.\n\nIn practice: compute on demand when requested (not continuously). Cache the result for up to 5 minutes (or until a \"flow dirty\" flag is set by new trajectory data).\n\nOutput: FlowMap struct with per-cell vectors (x_component, y_component) and a cell count. Serialised to JSON for the dashboard.\n\n## Dwell Hotspot Heatmap\n\nQuery: for each track update where speed < 0.1 m/s (stationary or near-stationary), increment the dwell counter for the corresponding 0.25m grid cell.\n\nSQLite table: dwell_accumulator (grid_x INT, grid_y INT, person_id TEXT, count INT, last_updated DATETIME, PRIMARY KEY (grid_x, grid_y, person_id)). Aggregated at the person+cell level for person-filtered views.\n\nOutput: DwellHeatmap struct mapping (grid_x, grid_y) to count. Normalised to [0, 1] by dividing by the max count across all cells.\n\n## Corridor Detection\n\nIdentify grid cells with consistently high flow volume AND low angular variance in their flow vectors. These are likely corridors or pathways.\n\nAlgorithm:\n1. For each cell, compute the circular variance of the flow vector angles across all segments that contributed. Low variance = directional consistency = corridor.\n2. Threshold: cells with segment_count > 10 AND circular_variance < 0.3 are candidate corridor cells.\n3. Connected component analysis: group adjacent corridor cells into corridor regions.\n4. Each corridor region is represented by its dominant direction and a bounding box.\n\nCorridor regions are stored in SQLite: detected_corridors (id, centroid_xyz, dominant_direction_xy, length_m, width_m, cell_count, last_computed). Recomputed weekly.\n\n## Time and Person Filters\n\nThe dashboard allows filtering flow data by:\n- Time range: \"Today\", \"This week\", \"This month\", custom date range. Implemented as SQL WHERE timestamp >= ? filters on the trajectory_segments table.\n- Person: filter to show only trajectories attributed to a specific person_id (or \"All people\").\n\nFiltered queries are run on-demand with SQL indices on (timestamp, person_id).\n\n## Dashboard Visualisation\n\nAdd two toggle-able layers to the 3D scene (in addition to existing layers):\n\n1. \"Flow\" layer: render flow vectors as animated arrows on the ground plane. Each arrow is positioned at the cell centre, oriented in the cell's average flow direction, and sized proportional to the flow volume (segment count). Use Three.js ArrowHelper for rendering. Animate: cycle the arrow colour from 0% to 100% opacity (flowing effect) on a 2-second loop. Only render cells with > 5 segments.\n\n2. \"Dwell Hotspot\" layer: render a heatmap on the ground plane as coloured rectangle patches (Three.js PlaneGeometry with MeshBasicMaterial, colour mapped from blue (low dwell) through green to red (high dwell)). Opacity 0.4. Only render cells with > 10 dwell samples.\n\n3. Corridor highlighting: detected corridors rendered as slightly raised platform geometry (extruded rectangle, height 0.01m) with a pathway colour (warm grey, opacity 0.3). Toggle-able as sub-option of the \"Flow\" layer.\n\nLayer controls: new \"Patterns\" section in the 3D layer control panel. Three checkboxes: \"Movement flows\", \"Dwell hotspots\", \"Corridors\". Time filter dropdown: \"All time / Last 7 days / Last 30 days\". Person filter dropdown.\n\n## REST API\n\nGET /api/analytics/flow?person_id=&since=&until= — returns FlowMap JSON\nGET /api/analytics/dwell?person_id=&since=&until= — returns DwellHeatmap JSON\nGET /api/analytics/corridors — returns list of DetectedCorridor\n\n## Tests\n\n- Test trajectory sampling: track moves 0.25m -> segment recorded; track moves 0.05m -> no segment\n- Test flow vector averaging: 5 segments all pointing East -> cell vector = (1, 0); 5 East + 5 North -> cell vector ~= (0.5, 0.5)\n- Test dwell accumulation: 100 track updates at speed=0 in cell (5, 7) -> dwell_accumulator[5][7] count = 100\n- Test corridor detection: 20 aligned segments in adjacent cells with angular_variance < 0.3 -> corridor detected\n- Test time-range filtering: insert segments at T-1day and T-8days; query since T-7days -> only T-1day segment returned\n- Test 90-day pruning job removes old segments\n\n## Acceptance Criteria\n\n- Flow layer renders correctly in 3D view with animated arrows for rooms with > 7 days of data\n- Dwell hotspot heatmap visible and renders high-use spots (favourite chair, kitchen counter) correctly\n- Corridor overlay visible with detected high-traffic pathways\n- Time and person filter controls update the rendered layers\n- Layer toggles show/hide each layer cleanly without scene rebuild\n- Tests pass","status":"open","priority":3,"issue_type":"task","created_at":"2026-03-28T01:52:55.852672681Z","created_by":"coding","updated_at":"2026-04-11T08:07:10.162948692Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:325"]}
+{"id":"spaxel-jy4","title":"Crowd flow visualisation","description":"## Background\n\nOver days and weeks, the movement patterns of household members accumulate into meaningful flows: the main corridor between bedroom and bathroom, the typical path from the front door to the kitchen, habitual dwell spots (the favourite chair, the home office desk, the kitchen counter). Visualising these as directional flow maps and dwell hotspot heatmaps provides useful insight into how the space is actually used — and can inform furniture placement, automation placement, and even architectural decisions. It's also a compelling visual that demonstrates the system's accumulated knowledge.\n\n## FlowAccumulator\n\nNew package: mothership/internal/analytics/flow.go\n\nFlowAccumulator subscribes to TrackManager updates (10 Hz) and accumulates trajectory data.\n\nTrajectory sampling: for each track update, if the track has moved > 0.2m since the last recorded waypoint (for that track), record the movement:\n- from_xyz: last waypoint position\n- to_xyz: current position\n- speed: metres per second at this step\n- person_id: if identity is known\n- timestamp\n\nThis 0.2m threshold prevents accumulating thousands of micro-samples for stationary people.\n\nSQLite table: trajectory_segments (id TEXT PRIMARY KEY, person_id TEXT, from_x REAL, from_y REAL, from_z REAL, to_x REAL, to_y REAL, to_z REAL, speed REAL, timestamp DATETIME). Only store ground plane (from_z and to_z floor-projected: set to 0 for the flow map, since we render on the ground plane).\n\nTable growth management: the table accumulates indefinitely. Prune segments older than 90 days (configurable) with a daily background job. With 4 people at typical home movement rates, 90 days generates approximately 50,000 segments — manageable for SQLite.\n\n## Flow Map Computation\n\nQuery: for each 0.25m grid cell (same resolution as OccupancyGrid in FusionEngine), average the movement vectors of all trajectory segments that pass through that cell.\n\nSQL approach: for each segment, determine which grid cells it passes through (Bresenham's line algorithm on the grid). Accumulate vector components (to_x - from_x, to_y - from_y) into per-cell accumulators.\n\nIn practice: compute on demand when requested (not continuously). Cache the result for up to 5 minutes (or until a \"flow dirty\" flag is set by new trajectory data).\n\nOutput: FlowMap struct with per-cell vectors (x_component, y_component) and a cell count. Serialised to JSON for the dashboard.\n\n## Dwell Hotspot Heatmap\n\nQuery: for each track update where speed < 0.1 m/s (stationary or near-stationary), increment the dwell counter for the corresponding 0.25m grid cell.\n\nSQLite table: dwell_accumulator (grid_x INT, grid_y INT, person_id TEXT, count INT, last_updated DATETIME, PRIMARY KEY (grid_x, grid_y, person_id)). Aggregated at the person+cell level for person-filtered views.\n\nOutput: DwellHeatmap struct mapping (grid_x, grid_y) to count. Normalised to [0, 1] by dividing by the max count across all cells.\n\n## Corridor Detection\n\nIdentify grid cells with consistently high flow volume AND low angular variance in their flow vectors. These are likely corridors or pathways.\n\nAlgorithm:\n1. For each cell, compute the circular variance of the flow vector angles across all segments that contributed. Low variance = directional consistency = corridor.\n2. Threshold: cells with segment_count > 10 AND circular_variance < 0.3 are candidate corridor cells.\n3. Connected component analysis: group adjacent corridor cells into corridor regions.\n4. Each corridor region is represented by its dominant direction and a bounding box.\n\nCorridor regions are stored in SQLite: detected_corridors (id, centroid_xyz, dominant_direction_xy, length_m, width_m, cell_count, last_computed). Recomputed weekly.\n\n## Time and Person Filters\n\nThe dashboard allows filtering flow data by:\n- Time range: \"Today\", \"This week\", \"This month\", custom date range. Implemented as SQL WHERE timestamp >= ? filters on the trajectory_segments table.\n- Person: filter to show only trajectories attributed to a specific person_id (or \"All people\").\n\nFiltered queries are run on-demand with SQL indices on (timestamp, person_id).\n\n## Dashboard Visualisation\n\nAdd two toggle-able layers to the 3D scene (in addition to existing layers):\n\n1. \"Flow\" layer: render flow vectors as animated arrows on the ground plane. Each arrow is positioned at the cell centre, oriented in the cell's average flow direction, and sized proportional to the flow volume (segment count). Use Three.js ArrowHelper for rendering. Animate: cycle the arrow colour from 0% to 100% opacity (flowing effect) on a 2-second loop. Only render cells with > 5 segments.\n\n2. \"Dwell Hotspot\" layer: render a heatmap on the ground plane as coloured rectangle patches (Three.js PlaneGeometry with MeshBasicMaterial, colour mapped from blue (low dwell) through green to red (high dwell)). Opacity 0.4. Only render cells with > 10 dwell samples.\n\n3. Corridor highlighting: detected corridors rendered as slightly raised platform geometry (extruded rectangle, height 0.01m) with a pathway colour (warm grey, opacity 0.3). Toggle-able as sub-option of the \"Flow\" layer.\n\nLayer controls: new \"Patterns\" section in the 3D layer control panel. Three checkboxes: \"Movement flows\", \"Dwell hotspots\", \"Corridors\". Time filter dropdown: \"All time / Last 7 days / Last 30 days\". Person filter dropdown.\n\n## REST API\n\nGET /api/analytics/flow?person_id=&since=&until= — returns FlowMap JSON\nGET /api/analytics/dwell?person_id=&since=&until= — returns DwellHeatmap JSON\nGET /api/analytics/corridors — returns list of DetectedCorridor\n\n## Tests\n\n- Test trajectory sampling: track moves 0.25m -> segment recorded; track moves 0.05m -> no segment\n- Test flow vector averaging: 5 segments all pointing East -> cell vector = (1, 0); 5 East + 5 North -> cell vector ~= (0.5, 0.5)\n- Test dwell accumulation: 100 track updates at speed=0 in cell (5, 7) -> dwell_accumulator[5][7] count = 100\n- Test corridor detection: 20 aligned segments in adjacent cells with angular_variance < 0.3 -> corridor detected\n- Test time-range filtering: insert segments at T-1day and T-8days; query since T-7days -> only T-1day segment returned\n- Test 90-day pruning job removes old segments\n\n## Acceptance Criteria\n\n- Flow layer renders correctly in 3D view with animated arrows for rooms with > 7 days of data\n- Dwell hotspot heatmap visible and renders high-use spots (favourite chair, kitchen counter) correctly\n- Corridor overlay visible with detected high-traffic pathways\n- Time and person filter controls update the rendered layers\n- Layer toggles show/hide each layer cleanly without scene rebuild\n- Tests pass","status":"in_progress","priority":3,"issue_type":"task","assignee":"alpha","created_at":"2026-03-28T01:52:55.852672681Z","created_by":"coding","updated_at":"2026-04-11T11:19:10.020268336Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:328"]}
{"id":"spaxel-jza","title":"Dashboard: PIN change flow","description":"## Overview\nAllow authenticated users to change their dashboard PIN after first setup.\n\n## Backend\n- POST /api/auth/change-pin — requires valid session; body: {old_pin:'...', new_pin:'...'}\n- Verify old_pin against current bcrypt hash; return HTTP 403 if mismatch\n- Hash new_pin with bcrypt cost=12; update auth.pin_bcrypt\n- Existing sessions remain valid after PIN change (session tokens are independent of PIN)\n- Return {ok:true} on success\n\n## Dashboard\n- Settings panel: 'Security' section with 'Change PIN' button\n- Modal form: old PIN → new PIN → confirm new PIN → Submit\n- On 403: show 'Incorrect current PIN' error inline\n- On success: show 'PIN changed successfully' toast; close modal\n\n## Acceptance\n- Old PIN still works immediately after change attempt fails (403)\n- New PIN works on next login after successful change\n- Active session cookie remains valid after PIN change\n- Requires: spaxel-nk6 (PIN auth)","status":"closed","priority":3,"issue_type":"task","assignee":"golf","created_at":"2026-04-06T16:43:09.899017181Z","created_by":"coding","updated_at":"2026-04-09T12:10:28.896292868Z","closed_at":"2026-04-09T12:10:28.896154010Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred"]}
{"id":"spaxel-k0rs","title":"Add batching logic tests","description":"Write tests for notification batching behavior: 3 LOW events in 10s -> 1 notification, 1 URGENT -> immediate. Acceptance Criteria: Batching tests pass (windowing, priority bypass).","status":"in_progress","priority":2,"issue_type":"task","assignee":"alpha","created_at":"2026-04-11T08:15:07.948908838Z","created_by":"coding","updated_at":"2026-04-11T08:28:56.889629625Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:1","mitosis-child","mitosis-depth:1","parent-spaxel-40tl"]}
{"id":"spaxel-kgn4","title":"Implement feature discovery notifications","description":"Fire single non-blocking notification when features become available. Events: DiurnalBaselineActivated (7 days), FirstSleepSessionComplete, WeightUpdateApproved, AutomationFirstFired, PredictionModelReady (7 days per person). Each keyed by unique event ID in SQLite (feature_notifications table: event_id, fired_at, acknowledged_at). Never fires twice. Dismissed by tapping. Does not fire during quiet hours. Files: mothership/internal/help/notifier.go. Acceptance: each notification fires exactly once per feature; plain language messages; respects quiet hours; SQLite persistence prevents duplicates.","status":"in_progress","priority":2,"issue_type":"task","assignee":"alpha","created_at":"2026-04-11T03:34:49.150476063Z","created_by":"coding","updated_at":"2026-04-11T04:59:10.558085497Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:5","mitosis-child","mitosis-depth:1","parent-spaxel-tig"]}
@@ -162,7 +162,7 @@
{"id":"spaxel-she","title":"fix: mqtt/client.go API mismatches for paho v1.5.0","description":"## Problem\n`internal/mqtt/client.go` uses methods that don't exist in paho.mqtt.golang v1.5.0 (the version in go.mod):\n\n1. **Line 120**: `opts.SetCleanOnConnect(true)` — method doesn't exist. In paho v1.5.0 the method is `opts.SetCleanSession(true)`\n2. **Line 147**: `opts.OnDisconnect = func(...)` — field doesn't exist. In paho v1.5.0 the callback is set via `opts.SetConnectionLostHandler(func(...))`\n3. **Lines 402, 404**: Redundant type assertions inside a type switch:\n - `case string: data = []byte(v.(string))` — `v` is already typed as `string` in this case branch; change to `data = []byte(v)`\n - `case []byte: data = v.([]byte)` — `v` is already `[]byte`; change to `data = v`\n\n## Fixes\n1. Line 120: `opts.SetCleanOnConnect(true)` → `opts.SetCleanSession(true)`\n2. Lines 147-160 (OnDisconnect assignment block): Replace with `opts.SetConnectionLostHandler(func(client mqtt.Client, err error) { ... })`\n3. Lines 402, 404: Remove the redundant type assertions\n\n## Verify\n```bash\ncd /home/coding/spaxel/mothership && PATH=$PATH:/home/coding/go/bin go build ./internal/mqtt/\n```","status":"closed","priority":1,"issue_type":"task","assignee":"delta","created_at":"2026-04-06T22:30:21.813369312Z","created_by":"coding","updated_at":"2026-04-06T22:47:51.175731416Z","closed_at":"2026-04-06T22:47:51.175482589Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:1"]}
{"id":"spaxel-sl2","title":"Phase 8: Analysis & Developer Tools","description":"Goal: Deep debugging, system tuning, detection explainability.\n\nDeliverables:\n- Activity timeline (universal event stream, tap-to-jump, inline feedback)\n- Detection explainability (X-ray overlay, contributing links, confidence breakdown)\n- Time-travel debugging (pause live, scrub timeline, replay 3D from recorded CSI)\n- Pre-deployment simulator (virtual space + nodes + synthetic walkers, GDOP overlay)\n- CSI simulator Go CLI (virtual nodes, synthetic CSI binary frames, for dev/testing)\n- Fresnel zone debug overlay (wireframe ellipsoids between active links)\n\nExit criteria: Time-travel replays 24h of data. Simulator produces realistic synthetic data.","status":"closed","priority":3,"issue_type":"phase","assignee":"golf","created_at":"2026-03-27T01:55:47.111916358Z","created_by":"coding","updated_at":"2026-04-10T01:37:01.689881858Z","closed_at":"2026-04-10T01:37:01.689692542Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:1"],"dependencies":[{"issue_id":"spaxel-sl2","depends_on_id":"spaxel-3ca","type":"blocks","created_at":"2026-04-09T14:54:38.771420677Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-sl2","depends_on_id":"spaxel-5a3","type":"blocks","created_at":"2026-04-09T14:54:38.947095956Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-sl2","depends_on_id":"spaxel-70i","type":"blocks","created_at":"2026-04-09T14:54:38.897281189Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-sl2","depends_on_id":"spaxel-8ke","type":"blocks","created_at":"2026-04-09T14:54:38.637243667Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-sl2","depends_on_id":"spaxel-d41","type":"blocks","created_at":"2026-04-09T14:54:38.841330220Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-sl2","depends_on_id":"spaxel-i28","type":"blocks","created_at":"2026-03-28T01:33:51.145107801Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-sl2","depends_on_id":"spaxel-nhl","type":"blocks","created_at":"2026-04-09T14:54:38.714247271Z","created_by":"coding","metadata":"{}","thread_id":""}]}
{"id":"spaxel-sty","title":"CSI simulator Go CLI","description":"## Background\n\nThe pre-deployment simulator (spaxel-btj) provides a browser-based spatial planning tool. The CSI simulator CLI is a complementary developer tool: a standalone Go command-line program that opens WebSocket connections to a running mothership as virtual nodes and injects synthetic CSI binary frames. This enables automated integration testing, performance benchmarking, and algorithm development entirely without ESP32 hardware.\n\nThe critical difference: the pre-deployment simulator generates CSI on the server side (using the simulation API). The CLI simulator generates CSI externally and connects via the standard node WebSocket interface — testing the full network stack and protocol, not just the signal processing.\n\n## CLI Implementation\n\nNew Go command: mothership/cmd/sim/main.go\n\nUsage examples:\n sim --mothership localhost:8080 --nodes 4 --walkers 2 --rate 20 --duration 60\n sim --mothership localhost:8080 --token abc123def456 --nodes 2 --walkers 1 --seed 42\n sim --space \"6x4x2.5\" --nodes 4 --walkers 3 --rate 50 --duration 120 --ble\n sim --verify --mothership localhost:8080 --nodes 2 --walkers 1 --duration 10\n\nCLI Flags:\n- --mothership: URL of the mothership (default: ws://localhost:8080/ws)\n- --token: provision token. If not specified, automatically provisions via POST /api/provision with synthetic credentials.\n- --nodes: number of virtual nodes (default 2). Each node opens a separate WebSocket connection.\n- --walkers: number of synthetic walkers (default 1).\n- --rate: CSI transmission rate in Hz per node pair (default 20).\n- --duration: total run time in seconds (default 60). \"0\" means run until Ctrl+C.\n- --seed: random seed for reproducible walker paths (default: random seed, logged at startup).\n- --space: room dimensions in \"WxDxH\" format (default \"5x5x2.5\").\n- --ble: include synthetic BLE advertisements (one BLE device per walker, with stable random MAC).\n- --verify: after --duration seconds, verify that the mothership produced the expected number of blobs. Exit 0 on success, 1 on failure.\n- --noise-sigma: Gaussian noise standard deviation for I/Q generation (default 0.005).\n- --wall: add a wall as \"x1,y1,x2,y2\" (can be repeated). Walls affect the path loss model.\n- --output-csv: write synthetic ground truth (walker positions + link deltaRMS) to a CSV file for offline analysis.\n\n## Synthetic CSI Frame Generation\n\nFor each virtual node pair (TX, RX) and each walker at each timestep:\n\n1. Compute RSSI from path loss model (same as simulator physics, mothership/internal/simulator/physics.go — reuse this package).\n\n2. Compute deltaRMS from Fresnel zone overlap (same physics model).\n\n3. Generate binary CSI frame matching the Phase 1 protocol format:\n Header (24 bytes):\n - Magic: 0xABCDEF01 (4 bytes)\n - Version: 1 (1 byte)\n - Node MAC: 6 bytes (synthetic, consistent per virtual node)\n - Peer MAC: 6 bytes (TX node's MAC for RX-side frames)\n - Channel: 6 (2.4GHz ch 6) or 36 (5GHz) — configurable\n - RSSI: 1 byte (signed, from path loss calculation)\n - Num subcarriers: 64 (1 byte)\n - Timestamp_us: 8 bytes (current Unix microseconds)\n\n Payload (128 bytes = 64 subcarriers * 2 bytes each):\n - For each subcarrier i: I = amplitude * cos(phase_i) + noise, Q = amplitude * sin(phase_i) + noise\n - amplitude: from Fresnel zone deltaRMS model\n - phase_i: phase_base + i * phase_step + phase_noise (simulate subcarrier phase variation)\n - noise: gaussian(sigma=--noise-sigma)\n - Values are int8 (clamped to [-127, 127])\n\nThe frame format is validated against the actual firmware output by comparing to real recorded frames in docs/research/reference_frames.bin (if available).\n\n## Connection Protocol\n\nEach virtual node:\n1. Opens WebSocket to ws://{mothership}/ws\n2. Sends hello message: {\"type\":\"hello\",\"mac\":\"{virtual_mac}\",\"firmware_version\":\"sim-1.0.0\",\"capabilities\":{\"can_tx\":true,\"can_rx\":true},\"free_heap\":200000,\"wifi_rssi\":-45,\"ip_addr\":\"127.0.0.{n}\"}\n3. Waits for role push from mothership (expects {\"type\":\"role\",\"role\":N})\n4. If receives {\"type\":\"reject\"}: logs error and exits with code 2\n5. Begins sending CSI frames at the configured rate using the binary WebSocket message format (not JSON)\n6. Also sends health messages every 10s: {\"type\":\"health\",\"heap\":200000,\"rssi\":-45,\"uptime_s\":N}\n7. If --ble: sends BLE relay messages every 5s: {\"type\":\"ble\",\"devices\":[{\"mac\":\"...\",\"name\":\"sim-person-1\",\"rssi\":-60}]}\n\n## Verification Mode (--verify)\n\nAfter --duration seconds:\n1. Stop sending CSI frames\n2. Wait 2 seconds for pipeline to settle\n3. GET {mothership}/api/blobs — gets current list of active blobs\n4. Assert: blob_count == walker_count (within ±1 tolerance)\n5. If all walkers are within the room bounds: assert all walkers have a blob within 2m distance\n6. Print: \"PASS: {blob_count} blobs detected for {walker_count} walkers\" or \"FAIL: expected N blobs, got M\"\n7. Exit 0 (PASS) or 1 (FAIL)\n\nThis is the CI smoke test that verifies the full pipeline end-to-end without hardware.\n\n## CI Integration\n\nAdd a CI step to the mothership GitHub Actions workflow (if one exists, or document the command):\n1. Start mothership with test config (in-memory SQLite, no recording)\n2. Run: sim --verify --nodes 2 --walkers 1 --duration 10 --seed 42\n3. Assert exit code 0\n\nThis becomes the primary end-to-end integration test. If the sim fails to produce blobs, something in the pipeline is broken.\n\n## Performance Testing\n\nThe simulator supports high-throughput testing:\n- sim --nodes 16 --walkers 4 --rate 50 --duration 60: measures mothership throughput at 16 nodes * 50 Hz = 800 frames/second\n- The simulator prints throughput statistics at the end: frames sent, frames per second, CPU time\n- Use for benchmarking and profiling the mothership processing pipeline\n\n## Files to Create\n\n- mothership/cmd/sim/main.go: CLI entry point with all flags\n- mothership/cmd/sim/generator.go: synthetic CSI frame generator\n- mothership/cmd/sim/walker.go: synthetic walker movement simulation\n- mothership/cmd/sim/verify.go: blob count verification logic\n- mothership/internal/simulator/physics.go: reuse from pre-deployment simulator (shared package)\n\n## Tests\n\n- Test that generated frames have the correct binary header format (magic, version bytes in correct positions)\n- Test that RSSI value is within plausible range for the given walker distance (e.g. walker at 2m, wall_attenuation=0 -> RSSI in [-50, -70])\n- Test that generated I/Q values are clamped to int8 range [-127, 127]\n- Test hello message format matches what the mothership ingestion server expects (parsed successfully)\n- Test that --verify correctly detects missing blobs (inject 1 walker, mock mothership returns 0 blobs -> FAIL)\n- Test --seed 42 produces identical walker paths across two runs (reproducibility)\n- Test --output-csv generates a CSV with correct headers and ground truth positions\n\n## Acceptance Criteria\n\n- CLI connects and streams synthetic CSI to a running mothership\n- Mothership blob count equals walker count (within ±1) when --verify is used\n- CLI exits cleanly after --duration seconds\n- --verify returns exit code 0 when blobs match, exit code 1 when they don't\n- Works correctly in a CI environment without hardware\n- High-throughput test (16 nodes, 50 Hz) completes without mothership errors or OOM\n- Tests pass","status":"open","priority":3,"issue_type":"task","created_at":"2026-03-28T01:57:48.145516684Z","created_by":"coding","updated_at":"2026-03-28T03:29:14.669157389Z","source_repo":".","compaction_level":0,"original_size":0,"dependencies":[{"issue_id":"spaxel-sty","depends_on_id":"spaxel-i28","type":"blocks","created_at":"2026-03-28T03:29:14.669138899Z","created_by":"coding","metadata":"{}","thread_id":""}]}
-{"id":"spaxel-tgj","title":"Home automation integration (MQTT and webhooks)","description":"## Background\n\nMany home automation systems — Home Assistant, OpenHAB, Node-RED, Domoticz — use MQTT as their primary integration backbone. By publishing spaxel state as MQTT topics with Home Assistant auto-discovery payloads, spaxel becomes a first-class presence sensor in any HA setup. No custom integration code is needed: the entities appear automatically in Home Assistant's entity registry simply by being powered on and having MQTT configured. This makes spaxel accessible to millions of home automation users who already have HA running.\n\n## MQTT Client\n\nOptional MQTT client in mothership/internal/mqtt/client.go.\n\nThe client is optional — if MQTT is not configured, the module is a no-op. Configuration via dashboard Settings or mothership config file:\n- broker_url: e.g. \"tcp://homeassistant.local:1883\" or \"mqtt://192.168.1.100:1883\"\n- username, password (optional)\n- tls: true/false\n- client_id: \"spaxel-{mothership_id}\" (unique per mothership instance)\n- retain: true (retained messages for presence and occupancy topics)\n\nUse the github.com/eclipse/paho.mqtt.golang library (the de-facto standard Go MQTT client).\n\nReconnect policy: exponential backoff from 5s to 120s, indefinite retry. Log reconnect attempts.\n\n## MQTT Topic Structure\n\nAll topics are prefixed with \"spaxel/{mothership_id}/\" where mothership_id is the unique ID from the mothership config.\n\nPerson presence:\n- Topic: spaxel/{mothership_id}/person/{person_id}/presence\n- Payload: \"home\" or \"not_home\" (plain string, retained)\n- Updated when: a person's first labelled BLE device is seen (home) or all their BLE devices have been absent for > 15 minutes (not_home)\n\nZone occupancy:\n- Topic: spaxel/{mothership_id}/zone/{zone_id}/occupancy\n- Payload: integer count (plain string, retained, e.g. \"2\")\n- Topic: spaxel/{mothership_id}/zone/{zone_id}/occupants\n- Payload: JSON array of person names (retained, e.g. [\"Alice\",\"Bob\"])\n- Updated on every zone occupancy change\n\nFall detection:\n- Topic: spaxel/{mothership_id}/fall_detected\n- Payload: JSON {\"person_id\":\"...\",\"person_label\":\"Alice\",\"zone_id\":\"...\",\"zone_name\":\"Hallway\",\"timestamp\":\"2026-03-27T14:23:00Z\"}\n- Not retained (event topic)\n\nSystem health:\n- Topic: spaxel/{mothership_id}/system/health\n- Payload: JSON {\"node_count\":4,\"online_count\":4,\"detection_quality\":0.87,\"mode\":\"home\"}\n- Retained, updated every 60s\n\n## Home Assistant Auto-Discovery\n\nOn initial MQTT connection (and on reconnect), publish HA auto-discovery payloads to the homeassistant/ prefix topics. HA processes these automatically and adds the entities to its registry.\n\nPer person: binary_sensor (presence)\nDiscovery topic: homeassistant/binary_sensor/spaxel_{mothership_id}_{person_id}/config\nPayload (JSON, retained):\n{\n \"name\": \"Alice Presence\",\n \"unique_id\": \"spaxel_{mothership_id}_{person_id}_presence\",\n \"state_topic\": \"spaxel/{mothership_id}/person/{person_id}/presence\",\n \"payload_on\": \"home\",\n \"payload_off\": \"not_home\",\n \"device_class\": \"presence\",\n \"device\": {\n \"identifiers\": [\"spaxel_{mothership_id}\"],\n \"name\": \"Spaxel\",\n \"model\": \"Spaxel Presence System\",\n \"manufacturer\": \"Spaxel\"\n }\n}\n\nPer zone: sensor (occupancy count) + binary_sensor (zone occupied)\nDiscovery topic: homeassistant/sensor/spaxel_{mothership_id}_{zone_id}_occupancy/config\nPayload: {name, unique_id, state_topic, unit_of_measurement: \"people\", device_class: null, device: ...}\n\nFall detection: binary_sensor with device_class: \"safety\"\nDiscovery topic: homeassistant/binary_sensor/spaxel_{mothership_id}_fall/config\n\nSystem mode: select (home/away/sleep) or input_select via MQTT\nDiscovery + command topics so HA can set system mode.\n\nWhen a person or zone is deleted, publish an empty payload to the corresponding discovery topic (HA treats this as \"remove entity\").\n\n## Event Publishing\n\nThe MQTT client subscribes to the internal event bus and publishes:\n- ZoneCrossingEvent -> update zone occupancy topics\n- PersonPresenceChangeEvent -> update person presence topic\n- FallEvent -> publish to fall_detected topic\n- SystemHealthEvent -> publish to system health topic (60s interval)\n\n## Generic Webhook Integration\n\nA complementary feature: a system-level webhook that delivers ALL spaxel events to a single user-configured URL, not just user-configured automations. This is for integrations that want to receive the full event stream (e.g. a custom backend, a logging service, or a complex HA automation that can't be expressed in the automation builder).\n\nPOST /api/settings/system-webhook: set URL\nAll internal events are serialised as JSON and POST'd to this URL with event type in the X-Spaxel-Event header.\nSame retry policy as automation webhooks (one retry after 30s on 5xx).\n\n## Dashboard Settings\n\nSettings panel -> \"Integrations\" tab:\n- MQTT section: broker URL, username, password (masked), TLS toggle, \"Test Connection\" button, \"Publish discovery payloads now\" button\n- System webhook section: URL input, \"Test\" button, recent delivery log (last 10 events with status)\n- Status indicator: green dot if MQTT connected, red if disconnected with last error message\n\n## Tests\n\n- Test MQTT connection to a local broker (use go-mqtt-broker test dependency or a Docker Eclipse Mosquitto in CI)\n- Test auto-discovery payload format against HA MQTT auto-discovery spec (compare JSON structure)\n- Test retained messages: verify that on reconnect, retained messages are not re-published if unchanged\n- Test that fall_detected topic is published on FallEvent\n- Test that zone occupancy topics update correctly on ZoneCrossingEvent\n- Test auto-discovery cleanup: deleting a person sends empty payload to discovery topic\n- Test system webhook delivers all event types to a mock HTTP server\n- Test reconnect policy: simulate broker disconnect, verify client reconnects with backoff\n\n## Acceptance Criteria\n\n- Spaxel entities appear automatically in Home Assistant entity list after MQTT config without any HA config editing\n- Person presence binary_sensor in HA updates within 30 seconds of BLE presence change\n- Zone occupancy sensor in HA reflects correct integer count\n- Fall detection binary_sensor fires and resets correctly\n- System mode select allows bidirectional control from HA (HA can set spaxel mode via MQTT)\n- System webhook receives all event types\n- Tests pass","status":"open","priority":3,"issue_type":"task","created_at":"2026-03-28T01:49:02.414667027Z","created_by":"coding","updated_at":"2026-04-11T08:07:10.188946631Z","source_repo":".","compaction_level":0,"original_size":0,"dependencies":[{"issue_id":"spaxel-tgj","depends_on_id":"spaxel-c0q","type":"blocks","created_at":"2026-03-28T03:29:14.412533268Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tgj","depends_on_id":"spaxel-c1c","type":"blocks","created_at":"2026-03-28T01:49:05.719934686Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tgj","depends_on_id":"spaxel-nqh","type":"blocks","created_at":"2026-03-28T01:49:05.665936722Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tgj","depends_on_id":"spaxel-qlh","type":"blocks","created_at":"2026-03-28T01:49:05.694421101Z","created_by":"coding","metadata":"{}","thread_id":""}]}
+{"id":"spaxel-tgj","title":"Home automation integration (MQTT and webhooks)","description":"## Background\n\nMany home automation systems — Home Assistant, OpenHAB, Node-RED, Domoticz — use MQTT as their primary integration backbone. By publishing spaxel state as MQTT topics with Home Assistant auto-discovery payloads, spaxel becomes a first-class presence sensor in any HA setup. No custom integration code is needed: the entities appear automatically in Home Assistant's entity registry simply by being powered on and having MQTT configured. This makes spaxel accessible to millions of home automation users who already have HA running.\n\n## MQTT Client\n\nOptional MQTT client in mothership/internal/mqtt/client.go.\n\nThe client is optional — if MQTT is not configured, the module is a no-op. Configuration via dashboard Settings or mothership config file:\n- broker_url: e.g. \"tcp://homeassistant.local:1883\" or \"mqtt://192.168.1.100:1883\"\n- username, password (optional)\n- tls: true/false\n- client_id: \"spaxel-{mothership_id}\" (unique per mothership instance)\n- retain: true (retained messages for presence and occupancy topics)\n\nUse the github.com/eclipse/paho.mqtt.golang library (the de-facto standard Go MQTT client).\n\nReconnect policy: exponential backoff from 5s to 120s, indefinite retry. Log reconnect attempts.\n\n## MQTT Topic Structure\n\nAll topics are prefixed with \"spaxel/{mothership_id}/\" where mothership_id is the unique ID from the mothership config.\n\nPerson presence:\n- Topic: spaxel/{mothership_id}/person/{person_id}/presence\n- Payload: \"home\" or \"not_home\" (plain string, retained)\n- Updated when: a person's first labelled BLE device is seen (home) or all their BLE devices have been absent for > 15 minutes (not_home)\n\nZone occupancy:\n- Topic: spaxel/{mothership_id}/zone/{zone_id}/occupancy\n- Payload: integer count (plain string, retained, e.g. \"2\")\n- Topic: spaxel/{mothership_id}/zone/{zone_id}/occupants\n- Payload: JSON array of person names (retained, e.g. [\"Alice\",\"Bob\"])\n- Updated on every zone occupancy change\n\nFall detection:\n- Topic: spaxel/{mothership_id}/fall_detected\n- Payload: JSON {\"person_id\":\"...\",\"person_label\":\"Alice\",\"zone_id\":\"...\",\"zone_name\":\"Hallway\",\"timestamp\":\"2026-03-27T14:23:00Z\"}\n- Not retained (event topic)\n\nSystem health:\n- Topic: spaxel/{mothership_id}/system/health\n- Payload: JSON {\"node_count\":4,\"online_count\":4,\"detection_quality\":0.87,\"mode\":\"home\"}\n- Retained, updated every 60s\n\n## Home Assistant Auto-Discovery\n\nOn initial MQTT connection (and on reconnect), publish HA auto-discovery payloads to the homeassistant/ prefix topics. HA processes these automatically and adds the entities to its registry.\n\nPer person: binary_sensor (presence)\nDiscovery topic: homeassistant/binary_sensor/spaxel_{mothership_id}_{person_id}/config\nPayload (JSON, retained):\n{\n \"name\": \"Alice Presence\",\n \"unique_id\": \"spaxel_{mothership_id}_{person_id}_presence\",\n \"state_topic\": \"spaxel/{mothership_id}/person/{person_id}/presence\",\n \"payload_on\": \"home\",\n \"payload_off\": \"not_home\",\n \"device_class\": \"presence\",\n \"device\": {\n \"identifiers\": [\"spaxel_{mothership_id}\"],\n \"name\": \"Spaxel\",\n \"model\": \"Spaxel Presence System\",\n \"manufacturer\": \"Spaxel\"\n }\n}\n\nPer zone: sensor (occupancy count) + binary_sensor (zone occupied)\nDiscovery topic: homeassistant/sensor/spaxel_{mothership_id}_{zone_id}_occupancy/config\nPayload: {name, unique_id, state_topic, unit_of_measurement: \"people\", device_class: null, device: ...}\n\nFall detection: binary_sensor with device_class: \"safety\"\nDiscovery topic: homeassistant/binary_sensor/spaxel_{mothership_id}_fall/config\n\nSystem mode: select (home/away/sleep) or input_select via MQTT\nDiscovery + command topics so HA can set system mode.\n\nWhen a person or zone is deleted, publish an empty payload to the corresponding discovery topic (HA treats this as \"remove entity\").\n\n## Event Publishing\n\nThe MQTT client subscribes to the internal event bus and publishes:\n- ZoneCrossingEvent -> update zone occupancy topics\n- PersonPresenceChangeEvent -> update person presence topic\n- FallEvent -> publish to fall_detected topic\n- SystemHealthEvent -> publish to system health topic (60s interval)\n\n## Generic Webhook Integration\n\nA complementary feature: a system-level webhook that delivers ALL spaxel events to a single user-configured URL, not just user-configured automations. This is for integrations that want to receive the full event stream (e.g. a custom backend, a logging service, or a complex HA automation that can't be expressed in the automation builder).\n\nPOST /api/settings/system-webhook: set URL\nAll internal events are serialised as JSON and POST'd to this URL with event type in the X-Spaxel-Event header.\nSame retry policy as automation webhooks (one retry after 30s on 5xx).\n\n## Dashboard Settings\n\nSettings panel -> \"Integrations\" tab:\n- MQTT section: broker URL, username, password (masked), TLS toggle, \"Test Connection\" button, \"Publish discovery payloads now\" button\n- System webhook section: URL input, \"Test\" button, recent delivery log (last 10 events with status)\n- Status indicator: green dot if MQTT connected, red if disconnected with last error message\n\n## Tests\n\n- Test MQTT connection to a local broker (use go-mqtt-broker test dependency or a Docker Eclipse Mosquitto in CI)\n- Test auto-discovery payload format against HA MQTT auto-discovery spec (compare JSON structure)\n- Test retained messages: verify that on reconnect, retained messages are not re-published if unchanged\n- Test that fall_detected topic is published on FallEvent\n- Test that zone occupancy topics update correctly on ZoneCrossingEvent\n- Test auto-discovery cleanup: deleting a person sends empty payload to discovery topic\n- Test system webhook delivers all event types to a mock HTTP server\n- Test reconnect policy: simulate broker disconnect, verify client reconnects with backoff\n\n## Acceptance Criteria\n\n- Spaxel entities appear automatically in Home Assistant entity list after MQTT config without any HA config editing\n- Person presence binary_sensor in HA updates within 30 seconds of BLE presence change\n- Zone occupancy sensor in HA reflects correct integer count\n- Fall detection binary_sensor fires and resets correctly\n- System mode select allows bidirectional control from HA (HA can set spaxel mode via MQTT)\n- System webhook receives all event types\n- Tests pass","status":"closed","priority":3,"issue_type":"task","assignee":"alpha","created_at":"2026-03-28T01:49:02.414667027Z","created_by":"coding","updated_at":"2026-04-11T10:36:18.940696600Z","closed_at":"2026-04-11T10:36:18.940634302Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:7"],"dependencies":[{"issue_id":"spaxel-tgj","depends_on_id":"spaxel-c0q","type":"blocks","created_at":"2026-03-28T03:29:14.412533268Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tgj","depends_on_id":"spaxel-c1c","type":"blocks","created_at":"2026-03-28T01:49:05.719934686Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tgj","depends_on_id":"spaxel-nqh","type":"blocks","created_at":"2026-03-28T01:49:05.665936722Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tgj","depends_on_id":"spaxel-qlh","type":"blocks","created_at":"2026-03-28T01:49:05.694421101Z","created_by":"coding","metadata":"{}","thread_id":""}]}
{"id":"spaxel-tig","title":"Guided troubleshooting (enhanced for production)","description":"## Background\n\nThe Phase 4 guided troubleshooting bead (spaxel-r0l) covers onboarding failures and basic node offline recovery. This Phase 9 bead extends it with production-quality proactive assistance that emerges from the system's own understanding of its state: detection quality degradation warnings with root-cause analysis, post-feedback explanations that close the loop for curious users, feature discovery notifications that teach users about new capabilities as they become available, and a searchable help system for self-service support.\n\nThe philosophy: the system should feel like a knowledgeable, helpful companion that notices problems before you do and explains them in terms you understand.\n\n## 1. Proactive Quality Prompts\n\nTrigger: when ambient confidence score (Phase 5, spaxel-sbi) drops below 0.6 on any link for more than 5 consecutive minutes.\n\nAction: show a non-blocking, dismissible prompt card in the dashboard:\n\"Detection quality has dropped on [Node A] to [Node B]. This link is at [N]% reliability.\"\n\nThe card includes:\n- A \"Diagnose\" button that runs the link weather diagnostics (Phase 5, spaxel-32o) and shows the results in a slide-out panel.\n- \"Dismiss for today\" option (hides until tomorrow or until quality recovers and drops again)\n- The 3D link line is highlighted (pulsing amber) while the prompt is active\n\nThe link weather diagnostic result is shown in plain English:\n- \"Possible cause: new furniture may be blocking the sensing zone. [See where to move the node]\"\n- \"Possible cause: WiFi congestion from neighbouring networks. [What to do about this]\"\n- \"Cause unknown — system is adapting. [No action needed]\"\n\nDo NOT show this prompt if the quality drop is temporary (< 5 minutes). Many quality drops are transient (microwave oven use, brief WiFi congestion) and showing a prompt for every one would train the user to ignore them.\n\n## 2. Repeated-Setting Change Detection\n\nTrigger: if a user changes the same configuration setting (motion threshold, baseline tau, etc.) more than 3 times within a 24-hour period.\n\nThis is a signal that the user is struggling to find the right value. The system should proactively offer help rather than silently watch the user thrash.\n\nAction: show a non-intrusive prompt: \"Looks like you're fine-tuning the motion threshold. Would you like help finding the right value for your space?\"\n\nThe \"Help me tune this\" button opens a guided calibration flow:\n1. \"Set threshold too low?\" -> walk around room, system shows how many false positives at the current setting\n2. \"Set threshold too high?\" -> sit still, system shows if motion is being missed\n3. Suggests optimal value based on the diurnal baseline SNR and link health\n4. \"Apply suggested value: [N]\" button\n\nTrack repeated changes in localStorage: {setting_name: {count, last_change_timestamp}} for the last 24h.\n\n## 3. Post-Feedback Explanations\n\nWhen a user marks a detection event as a false positive (FALSE_POSITIVE feedback from spaxel-3ps), show an explanation:\n\n\"The system detected motion here because: [link A to link B]'s signal (deltaRMS) exceeded the motion threshold by [N]x at [time]. This could be caused by: [root cause from diagnostic rules, if any match, or 'ambient RF interference' as default]. We've noted this and will apply a correction.\"\n\nThe explanation uses the ExplainabilitySnapshot for the event (spaxel-ez4) to identify the contributing link, and runs a quick diagnostic check (spaxel-32o rule engine) on the link's health history at the event timestamp.\n\nShow as an expandable section (\"Why did this happen?\") on the feedback confirmation card, not as a separate notification.\n\n## 4. Feature Discovery Notifications\n\nWhen a feature becomes available for the first time (requires a one-time condition to be met), fire a single non-blocking notification:\n\nEvents and their messages:\n- DiurnalBaselineActivated (after 7 days of data, Phase 5): \"Your system has learned your home's daily patterns. Detection accuracy should improve starting today.\"\n- FirstSleepSessionComplete (first sleep monitored, Phase 7): \"Your first sleep session was tracked overnight. Tap to see your sleep summary.\"\n- WeightUpdateApproved (first self-improving weight update, Phase 7): \"Localisation accuracy improved based on your BLE device positions. Median position error decreased.\"\n- AutomationFirstFired (first automation triggered, Phase 6): \"Your first automation just ran! [View in automations log]\"\n- PredictionModelReady (7 days per person, Phase 7): \"Presence predictions are now available for [person name]. [View predictions]\"\n\nEach notification:\n- Keyed by a unique event ID stored in SQLite: feature_notifications (event_id TEXT PRIMARY KEY, fired_at DATETIME, acknowledged_at DATETIME)\n- Never fires twice (primary key ensures uniqueness)\n- Dismissed by tapping (marks acknowledged_at)\n- Does not fire during quiet hours (uses notification manager quiet hours logic)\n\n## 5. Contextual Help System\n\nA \"?\" button in the expert mode header opens a searchable help overlay. The overlay contains:\n- A search input (same fuzzy search as command palette, Phase 9 spaxel-tvq)\n- A list of help articles (approximately 30 covering all major features)\n- Each article: title, 1-3 sentence plain-English explanation, link to a relevant dashboard section or action\n\nSample articles:\n- \"What is a sensing link?\" — \"A sensing link is the path between two spaxel nodes (one transmitting, one receiving). Motion in the space between them changes the signal, which spaxel detects.\"\n- \"Why is my detection quality low?\" — \"Low quality usually means interference from other WiFi devices, an obstacle in the sensing zone, or the node is too far from your router. Click 'Diagnose' on the link to find the specific cause.\"\n- \"How does presence prediction work?\" — \"After 7 days, spaxel learns when people are typically in each room and predicts where they'll be next. Predictions appear in the Predictions panel.\"\n- \"What is the Fresnel zone?\" — \"The Fresnel zone is the region in space where motion has the most impact on the signal between two nodes. Spaxel uses this geometry to estimate where in the room a person is.\"\n\nArticles are stored as a static JSON file (dashboard/help_articles.json, 30-50 articles). No server round-trip needed for help.\n\n## Implementation Structure\n\n- mothership/internal/help/notifier.go: feature discovery notification manager, persistence\n- dashboard/js/proactive.js: quality prompt, repeated-setting detector, post-feedback explanation\n- dashboard/js/help.js: help overlay, fuzzy search on articles, article rendering\n- dashboard/help_articles.json: all help article content\n- mothership/internal/diagnostics/linkweather.go: add GetDiagnosticFor(linkID, timestamp) method for post-feedback use\n\n## Tests\n\n- Test quality prompt trigger: mock confidence score = 0.55 for 6 minutes, verify prompt appears; confidence = 0.55 for 3 minutes, verify no prompt\n- Test repeated-setting detection: mock 4 threshold changes in 20h, verify help prompt fires\n- Test post-feedback explanation: inject FALSE_POSITIVE feedback on an event with a known ExplainabilitySnapshot, verify explanation text contains the contributing link name\n- Test feature discovery: inject DiurnalBaselineActivated event, verify notification fires once; inject again, verify no second notification\n- Test help search: query \"fresnel\" -> \"What is the Fresnel zone?\" appears in results\n- Test dismissed prompts don't re-appear (localStorage + SQLite persistence)\n\n## Acceptance Criteria\n\n- Quality prompt appears within 5 minutes of confidence score dropping below 0.6 threshold\n- Prompt does NOT appear for transient drops shorter than 5 minutes\n- \"Diagnose\" in quality prompt shows root cause in plain language\n- Repeated-setting detection fires after 3+ changes in 24h\n- Post-feedback explanation shown after any FALSE_POSITIVE feedback submission\n- Feature discovery notifications fire exactly once per feature, in plain language\n- Help overlay opens with \"?\" button, search finds relevant articles\n- Dismissed prompts never re-appear (unless condition reoccurs after recovery)\n- Tests pass","status":"open","priority":3,"issue_type":"task","created_at":"2026-03-28T02:04:15.981731936Z","created_by":"coding","updated_at":"2026-04-11T03:34:49.204992554Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:1"],"dependencies":[{"issue_id":"spaxel-tig","depends_on_id":"spaxel-32o","type":"blocks","created_at":"2026-03-28T02:04:22.625685956Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tig","depends_on_id":"spaxel-dz5s","type":"blocks","created_at":"2026-04-11T03:34:48.997943090Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tig","depends_on_id":"spaxel-kgn4","type":"blocks","created_at":"2026-04-11T03:34:49.167476389Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tig","depends_on_id":"spaxel-qaaa","type":"blocks","created_at":"2026-04-11T03:34:49.204953181Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tig","depends_on_id":"spaxel-sbi","type":"blocks","created_at":"2026-03-28T02:04:22.592483085Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tig","depends_on_id":"spaxel-sl2","type":"blocks","created_at":"2026-03-28T03:29:15.089304486Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tig","depends_on_id":"spaxel-v1ep","type":"blocks","created_at":"2026-04-11T03:34:49.052040423Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-tig","depends_on_id":"spaxel-x6jb","type":"blocks","created_at":"2026-04-11T03:34:49.115061838Z","created_by":"coding","metadata":"{}","thread_id":""}]}
{"id":"spaxel-tim","title":"Adaptive sensing rate","description":"Implement mothership-controlled sensing rate with on-device burst detection.\n\n## Deliverables\n- Mothership rate control: send rate change commands (2Hz idle ↔ 50Hz active) per link via WebSocket\n- Rate decision logic: drop to 2Hz when no motion for 30s, burst to 50Hz on motion\n- On-device amplitude variance check at low rate (2Hz) — if variance exceeds threshold, burst to full rate and notify mothership\n- Motion hints from ESP32 to preemptively ramp adjacent links\n- Firmware changes: firmware/main/csi.c to support dynamic rate changes\n\n## Acceptance Criteria\n- Idle links automatically drop to 2Hz packet rate\n- Motion triggers burst to configured active rate\n- ESP32 can locally detect motion onset and self-burst before mothership commands\n- Adjacent links ramp up on motion hints from nearby nodes\n- Tests for rate decision logic in mothership\n\n## References\n- Plan: docs/plan/plan.md item 12\n- CSI capture: firmware/main/csi.c\n- Signal pipeline: mothership/internal/signal/processor.go","status":"closed","priority":2,"issue_type":"task","assignee":"spaxel-alpha","created_at":"2026-03-27T01:56:21.876231481Z","created_by":"coding","updated_at":"2026-03-28T05:36:02.592406514Z","closed_at":"2026-03-28T05:36:02.592346365Z","close_reason":"Implemented: ratecontrol.go (bcfd1e3, fb69190) — mothership-controlled 2Hz↔50Hz rate changes, firmware csi.c/websocket.c dynamic rate config, on-device amplitude variance burst detection","source_repo":".","compaction_level":0,"original_size":0}
{"id":"spaxel-tqj","title":"CSI recording buffer","description":"Implement disk-backed circular buffer for CSI frame recording.\n\n## Deliverables\n- New package: mothership/internal/recording/\n- Append incoming CSI frames to disk-backed circular buffer (48h default retention)\n- Binary format for efficient storage (same frame format as WebSocket)\n- Configurable retention period via environment variable\n- Foundation for time-travel replay feature (Phase 8)\n\n## Acceptance Criteria\n- CSI frames are persisted to disk as they arrive\n- Buffer auto-prunes frames older than retention period\n- Can read back frames for a given time range\n- Storage is bounded (auto-prune prevents disk exhaustion)\n- Tests cover write, read-back, and pruning\n\n## References\n- Frame format: mothership/internal/ingestion/frame.go (24-byte header + payload)\n- Ring buffer: mothership/internal/ingestion/ring.go (in-memory reference)","status":"closed","priority":2,"issue_type":"task","assignee":"spaxel-alpha","created_at":"2026-03-27T01:56:09.947974130Z","created_by":"coding","updated_at":"2026-03-28T01:34:05.658150061Z","closed_at":"2026-03-27T03:02:15.596740568Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"dependencies":[{"issue_id":"spaxel-tqj","depends_on_id":"spaxel-cxm","type":"blocks","created_at":"2026-03-28T01:34:05.658124716Z","created_by":"coding","metadata":"{}","thread_id":""}]}
diff --git a/.needle-predispatch-sha b/.needle-predispatch-sha
index 86c4ed3..35afd44 100644
--- a/.needle-predispatch-sha
+++ b/.needle-predispatch-sha
@@ -1 +1 @@
-1a32011739ada09071efddbad8f50b7be1bd7040
+abaf070f4791d03798f596dfa27a8bcc1338e22b
diff --git a/dashboard/index.html b/dashboard/index.html
index c92b734..7ac11e4 100644
--- a/dashboard/index.html
+++ b/dashboard/index.html
@@ -3504,6 +3504,8 @@
+
+
diff --git a/dashboard/js/crowdflow.js b/dashboard/js/crowdflow.js
new file mode 100644
index 0000000..04ff1ff
--- /dev/null
+++ b/dashboard/js/crowdflow.js
@@ -0,0 +1,356 @@
+/**
+ * Spaxel Dashboard - Crowd Flow Visualization Layer
+ *
+ * Manages the crowd flow visualization layers including:
+ * - Movement flows (animated arrows)
+ * - Dwell hotspots (heatmap)
+ * - Corridors (detected pathways)
+ *
+ * Fetches data from the analytics API and manages layer state.
+ */
+
+(function() {
+ 'use strict';
+
+ // ============================================
+ // Layer State
+ // ============================================
+ const state = {
+ flowVisible: false,
+ dwellVisible: false,
+ corridorVisible: false,
+ personFilter: '', // Empty string = all people
+ timeFilter: 'all', // 'all', '7d', '30d'
+ lastRefresh: null,
+ autoRefreshMinutes: 5 // Auto-refresh every 5 minutes
+ };
+
+ // ============================================
+ // API Fetching
+ // ============================================
+
+ /**
+ * Fetch flow map data from the API.
+ * @returns {Promise