diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index ec259a2..0d9e86b 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -2,7 +2,7 @@ {"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-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-03-28T03:29:14.955787324Z","source_repo":".","compaction_level":0,"original_size":0,"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-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":"open","priority":3,"issue_type":"phase","created_at":"2026-03-27T01:55:55.188364609Z","created_by":"coding","updated_at":"2026-04-10T02:03:09.755220479Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:1"],"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":""}]} +{"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":""}]} {"id":"spaxel-19h","title":"fix: localization/spatial_weights.go unused variable linkID","description":"## Problem\n`internal/localization/spatial_weights.go:601` declares `linkID` but never uses it, causing build failure.\n\n## Fix\nFind line 601 in `mothership/internal/localization/spatial_weights.go` and either:\n- Remove the `linkID` variable assignment, or\n- Use the value (pass it somewhere meaningful), or\n- Replace with blank identifier: `linkID` → `_`\n\n## Verify\n```bash\ncd /home/coding/spaxel/mothership && PATH=$PATH:/home/coding/go/bin go build ./internal/localization/\n```\nMust compile with no errors.","status":"closed","priority":1,"issue_type":"task","assignee":"bravo","created_at":"2026-04-06T22:29:51.085342479Z","created_by":"coding","updated_at":"2026-04-06T22:35:21.502259769Z","closed_at":"2026-04-06T22:35:21.502022402Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0} {"id":"spaxel-1l2j","title":"Implement GET /api/events/{id} detail endpoint","description":"Implement GET /api/events/{id} for single event detail. Acceptance Criteria: Returns 404 for non-existent event IDs; Returns full event details for valid IDs.","status":"closed","priority":2,"issue_type":"task","assignee":"hotel","created_at":"2026-04-09T18:14:45.476239078Z","created_by":"coding","updated_at":"2026-04-09T19:09:34.130476972Z","closed_at":"2026-04-09T19:09:34.130355809Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["mitosis-child","mitosis-depth:1","parent-spaxel-yeh"]} {"id":"spaxel-1xt","title":"events: REST API GET /api/events with FTS5 search and cursor pagination","description":"## Overview\nImplement the HTTP handler for the events REST API (part 3 of spaxel-2ap split).\n\n## Endpoint\n`GET /api/events`\n\nQuery params:\n- `limit` (default 50, max 500)\n- `before` (cursor: timestamp_ms as string — keyset pagination, NOT OFFSET)\n- `after` (ISO8601 datetime)\n- `type` (filter by event type)\n- `zone` (filter by zone name)\n- `person` (filter by person label)\n- `q` (FTS5 query — prefix matching, e.g. `q=motion*`)\n\nResponse:\n```json\n{\"events\": [...], \"cursor\": \"1744000000000\", \"has_more\": true, \"total_filtered\": 42}\n```\n\n## Implementation\n- Register at `/api/events` in the existing chi router (requires spaxel-6ha is wired, but can be added independently)\n- FTS5 query via: `SELECT e.* FROM fts_events ft JOIN events e ON e.id = ft.rowid WHERE fts_events MATCH ? ORDER BY e.timestamp_ms DESC LIMIT ?`\n- Keyset: add `AND timestamp_ms < ?` when `before` cursor is provided\n- total_filtered: COUNT from same query without LIMIT\n\n## Verify\n```bash\ncd /home/coding/spaxel/mothership && PATH=$PATH:/home/coding/go/bin go build ./...\n# Run mothership and curl:\n# curl 'http://localhost:8080/api/events?limit=10&q=detection*'\n```\n\nRequires: spaxel-4u6 (schema must exist first)","status":"closed","priority":2,"issue_type":"task","assignee":"echo","created_at":"2026-04-06T22:31:17.453879797Z","created_by":"coding","updated_at":"2026-04-07T17:27:48.091794931Z","closed_at":"2026-04-07T17:27:48.091693315Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred"],"dependencies":[{"issue_id":"spaxel-1xt","depends_on_id":"spaxel-4u6","type":"blocks","created_at":"2026-04-06T22:31:24.454688305Z","created_by":"coding","metadata":"{}","thread_id":""}]} @@ -91,7 +91,7 @@ {"id":"spaxel-jcc","title":"Reintegrate phase 6+ packages into default build","description":"## Problem\n\nmain_phase6.go uses a 'phase6' build tag which excludes all Phase 6+ code from the default binary. All backend work from Phase 6 onward is dead code that never runs.\n\n## What needs to change\n\n- Remove the 'phase6' build tag gating from main_phase6.go (or merge into cmd/mothership/main.go)\n- Ensure all packages under: automation/, events/, notify/, replay/, prediction/, learning/, analytics/, sleep/, tracker/, zones/, mqtt/ are wired into the server at startup\n- Run 'go build ./...' to confirm all packages compile cleanly\n- Run 'go test ./...' — all tests must pass\n\n## Files to check\n\n- mothership/cmd/mothership/main.go\n- mothership/cmd/mothership/main_phase6.go (if it exists)\n- Any file with '//go:build phase6'\n\n## Acceptance\n\n'go build -o /dev/null ./...' succeeds with no build tags. All routes, goroutines, and managers from phase 6 packages are initialized in main().","status":"closed","priority":1,"issue_type":"task","assignee":"alpha","created_at":"2026-04-06T12:55:18.201589244Z","created_by":"coding","updated_at":"2026-04-07T06:29:44.917129307Z","closed_at":"2026-04-07T06:29:44.917067598Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["blocked","failure-count:82"],"dependencies":[{"issue_id":"spaxel-jcc","depends_on_id":"spaxel-19h","type":"blocks","created_at":"2026-04-06T22:30:41.001290765Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-jcc","depends_on_id":"spaxel-7nk","type":"blocks","created_at":"2026-04-06T22:30:41.103813566Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-jcc","depends_on_id":"spaxel-9nj","type":"blocks","created_at":"2026-04-06T22:30:40.971412241Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-jcc","depends_on_id":"spaxel-glq","type":"blocks","created_at":"2026-04-06T22:30:40.945729745Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-jcc","depends_on_id":"spaxel-she","type":"blocks","created_at":"2026-04-06T22:30:41.126328414Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-jcc","depends_on_id":"spaxel-uln","type":"blocks","created_at":"2026-04-06T22:30:41.045136934Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-jcc","depends_on_id":"spaxel-x59","type":"blocks","created_at":"2026-04-06T22:30:41.167499700Z","created_by":"coding","metadata":"{}","thread_id":""}]} {"id":"spaxel-jk0","title":"Simple mode with progressive disclosure","description":"## Background\n\nThe 3D expert interface is powerful but overwhelming for casual household members who just want to know \"is anyone home?\" or \"is the baby still asleep?\". Simple mode is a card-based, mobile-first UI that surfaces the most important information without any 3D scene. It should be usable by anyone who can read a smartphone screen, including elderly family members and non-technical partners who did not install the system.\n\nProgressive disclosure means: start with the simplest possible view, and let users reach more complexity when they want it — without being exposed to complexity they don't need.\n\n## Auto-Detection of Simple Mode\n\nSimple mode is automatically selected as the default view based on:\n1. Screen width < 768px (phones, small tablets in portrait)\n2. User-agent contains \"Mobile\" (additional phone detection signal)\n3. User has previously selected simple mode (localStorage \"spaxel_mode\" = \"simple\")\n\nExpert mode is the default for desktop browsers. A user can override the auto-detection and save their preference.\n\n## Room Occupancy Cards\n\nThe main view is a card grid (CSS Grid, 1 column on phones, 2 columns on small tablets). One card per defined zone.\n\nEach occupancy card shows:\n- Zone name (large, readable typography, min 20px font size)\n- Zone colour as a left border accent\n- Occupant count: large number\n- Named occupants: first names in a row (e.g. \"Alice, Bob\"). Anonymous tracks: \"1 person\"\n- Status icon: person silhouette if occupied, empty room icon if vacant\n- \"Last activity\" time: \"3 minutes ago\" (time since last zone transition event in this zone)\n\nAuto-update: cards update in real-time via WebSocket. When occupancy changes, the card animates briefly (a gentle pulse or highlight) to draw attention to the change.\n\nEmpty state (no zones defined): show a \"Get started\" prompt: \"Set up your rooms to see who's home. [Go to setup]\"\n\n## Activity Feed\n\nScrollable list below the zone cards (or as a separate tab). Shows the last 20 person-relevant events, filtered to exclude system noise (no node_connected, no weight_update events — only ZoneTransition, FallDetected, AnomalyDetected).\n\nEvent items: icon + one-line description + timestamp. Examples:\n- \"Alice walked into the Kitchen — 2 minutes ago\"\n- \"Bob left the house — 14 minutes ago\"\n- \"No one home since 8:32am\"\n- \"Possible fall: Alice in Hallway — 3 minutes ago [View] [Acknowledge]\"\n\nPlain English descriptions — no jargon. \"Possible fall\" not \"FallDetected event in zone_hallway_01.\"\n\nTap any event: shows a brief detail popup (not a full detail view). For zone transitions: \"Alice (via Living Room door) at 14:23\". For falls: the fall alert card with acknowledge button.\n\n## Alert Banner\n\nWhen an active unacknowledged alert exists (fall, anomaly, node offline), show a full-width banner at the top of the simple mode view:\n- Fall alert: red background, \"Possible fall — Alice in Hallway. [Acknowledge]\"\n- Anomaly (away mode): orange background, \"Movement detected while away. [View details]\"\n- Node offline: yellow background, \"Node Living Room went offline. [Help]\"\n\nAlerts are ordered by severity (fall > anomaly > node offline) if multiple are active. The [Help] button links to the troubleshooting flow (spaxel-r0l Phase 4 bead).\n\n## Sleep Summary Card\n\nA morning-only card, shown only between 6am and 11am on the day after a sleep session:\n- Position: above zone cards (highest priority in morning)\n- Content: \"Alice slept 7h 23m last night. 2 brief wake-ups. [View details]\"\n- If multiple people: stacked cards or a compact multi-person summary\n- Dismiss button: card hidden for today (localStorage flag \"spaxel_sleep_summary_{date}_shown\")\n- \"View details\" navigates to the Sleep panel in expert mode\n\n## Navigation\n\nBottom navigation bar (mobile-standard pattern): five tabs with icons + labels:\n1. Home (house icon) — occupancy cards (default tab)\n2. Activity (clock icon) — activity feed\n3. (empty centre spot for potential quick-action FAB in future)\n4. Alerts (bell icon) — active alerts and history. Badge with alert count.\n5. Settings (gear icon) — simplified settings: notification channel, person names, mode toggle\n\nThe Settings tab in simple mode shows only: display name for each person (from BLE registry), notification channel status (green = configured, grey = not set), and \"Switch to expert mode\" at the bottom.\n\n## Expert Mode Toggle\n\nA clearly labelled button: \"Expert Mode\" in the settings tab and as a persistent bottom-nav item. Tapping it:\n- If a PIN is configured (expert mode lock, settable in expert mode settings): shows PIN entry pad\n- If no PIN: immediately switches to expert mode\n- Saves preference to localStorage\n\nThe mode toggle is intentionally in settings/bottom-nav rather than prominently on the home screen — to reduce accidental switches for non-technical users.\n\n## Night Mode (OLED Dark)\n\nAuto-active during configured quiet hours (e.g. 10pm-7am). Uses CSS media query prefers-color-scheme: dark plus a manual override. OLED optimised: true black background (#000000), not just dark grey. This saves battery on OLED screens and reduces light disruption in bedrooms.\n\nAll card backgrounds in night mode: #0a0a0a (near-black). Text: #ffffff. Zone colour accents remain colourful.\n\n## Design System\n\nSimple mode uses a separate CSS file (dashboard/css/simple.css) that does NOT import from the expert mode styles. No Three.js canvas, no OrbitControls, no shader materials. Pure HTML + CSS + vanilla JS.\n\nFont size hierarchy: 14px minimum for secondary text, 16px for primary, 24px+ for zone names and counts. All interactive targets: minimum 44px height for WCAG AA touch target compliance.\n\n## Files to Create or Modify\n\n- dashboard/simple.html: simple mode HTML shell with bottom nav\n- dashboard/js/simple.js: card rendering, WebSocket updates, event feed\n- dashboard/js/simplemode.js: mode detection, localStorage mode preference\n- dashboard/css/simple.css: simple mode styles, night mode\n- mothership/internal/dashboard/routes.go: ensure /simple route is served\n\n## Tests\n\n- Test that room occupancy cards correctly reflect current zone state from WebSocket messages\n- Test activity feed filtering: inject a node_connected event and a zone_transition event; only the zone_transition should appear in simple mode feed\n- Test alert banner appears and dismisses correctly on acknowledge\n- Test mode toggle correctly switches between simple and expert mode routes\n- Test sleep summary card appears only between 6am-11am on the morning after a session\n- Test that occupancy card updates show the animated pulse on change\n- Test night mode activates based on quiet hours configuration\n\n## Acceptance Criteria\n\n- Simple mode loads correctly on a 320px wide screen (iPhone SE) without horizontal scrolling\n- Occupancy cards update in real-time as people move between zones\n- Activity feed shows only person-relevant events in plain English\n- Alert banner appears prominently and dismisses on acknowledge\n- Sleep summary card shown between 6am-11am after sleep session, dismissed when tapped\n- Mode toggle to expert mode works and saves preference\n- Night mode activates during configured quiet hours\n- All tap targets are at least 44px in height\n- Tests pass","status":"open","priority":3,"issue_type":"task","created_at":"2026-03-28T01:59:32.690434334Z","created_by":"coding","updated_at":"2026-03-28T03:29:14.851752276Z","source_repo":".","compaction_level":0,"original_size":0,"dependencies":[{"issue_id":"spaxel-jk0","depends_on_id":"spaxel-sl2","type":"blocks","created_at":"2026-03-28T03:29:14.851714754Z","created_by":"coding","metadata":"{}","thread_id":""}]} {"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-jxru","title":"Build fleet status page","description":"Full table view with bulk actions and camera fly-to functionality.","status":"open","priority":2,"issue_type":"task","created_at":"2026-04-10T02:03:09.725489218Z","created_by":"coding","updated_at":"2026-04-10T02:03:09.725489218Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["mitosis-child","mitosis-depth:1","parent-spaxel-17u"]} +{"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-09T23:28:13.618819456Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:325"]} {"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-klf","title":"Build self-improving localization","description":"Implement localization that learns from ground truth data.\n\nDeliverables:\n- BLE integration as ground truth source\n- Fresnel zone weight refinement algorithm\n- Continuous weight adjustment based on feedback\n\nAcceptance: Localization accuracy improves automatically as BLE ground truth data accumulates.","notes":"Implementation COMPLETE. Components:\n\n- BLEGroundTruthProvider: RSSI trilateration with Gauss-Newton iteration\n- WeightLearner: Gradient-based Fresnel zone weight refinement \n- SpatialWeightLearner: Per-zone spatial weights with SGD\n- WeightStore: SQLite persistence (link_weights table)\n- Engine fusion.go: Applies learned weights during localization\n- REST API: /api/localization/* endpoints for all features\n\nAcceptance met: Accuracy improves automatically as BLE data accumulates.\n\nPhase 7 (Learning & Analytics) marked COMPLETE in PROGRESS.md.","status":"closed","priority":2,"issue_type":"task","assignee":"golf","created_at":"2026-03-29T19:25:03.995110604Z","created_by":"coding","updated_at":"2026-04-09T14:34:11.347506328Z","closed_at":"2026-04-09T14:34:11.347172223Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:927","mitosis-child","mitosis-depth:1","parent-spaxel-i28"]} @@ -111,7 +111,7 @@ {"id":"spaxel-ncw","title":"Add system health messages to WebSocket feed","description":"Add 'system_health' message type to /ws/dashboard for periodic system stats every 60s. Broadcast: { type: 'system_health', health: { uptime_s, node_count, bead_count, go_routines, mem_mb } }. Handle in app.js onmessage.","status":"closed","priority":2,"issue_type":"task","assignee":"bravo","created_at":"2026-04-06T14:18:27.674751078Z","created_by":"coding","updated_at":"2026-04-07T12:53:38.767877850Z","closed_at":"2026-04-07T12:53:38.767672942Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","mitosis-child","mitosis-depth:1","parent-spaxel-9eg"]} {"id":"spaxel-nhl","title":"Build detection explainability system","description":"Create X-ray overlay showing:\n- Contributing links to detections\n- Confidence breakdown\n\nAcceptance: Users can see exactly why a detection was triggered with visual overlays and confidence metrics.","status":"in_progress","priority":2,"issue_type":"task","assignee":"hotel","created_at":"2026-04-09T14:54:38.671332846Z","created_by":"coding","updated_at":"2026-04-09T15:42:40.598403686Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:6","mitosis-child","mitosis-depth:1","parent-spaxel-sl2"]} {"id":"spaxel-nk6","title":"Dashboard: PIN setup, login, and session cookie authentication","description":"## Overview\nProtect the dashboard with a PIN that is set on first run and verified on every subsequent visit via session cookies.\n\n## Backend (mothership/internal/auth/)\n- SQLite auth table: pin_bcrypt TEXT, install_secret TEXT (singleton row)\n- GET /api/auth/status — return {pin_configured: bool} — no auth required\n- POST /api/auth/setup — body: {pin:'1234'} — only works if pin not yet configured; bcrypt cost=12; store hash\n- POST /api/auth/login — body: {pin:'1234'} — verify bcrypt; on success issue session cookie:\n Name: spaxel_session, HttpOnly, SameSite=Strict (if TLS), Path=/, Max-Age=604800\n Store session_id → expires_at in SQLite sessions table\n- POST /api/auth/logout — clear session cookie; delete session from SQLite\n- Session middleware: all /api/* and /ws/* require valid session cookie; return 401 if missing/expired\n- Rolling window: on each authenticated request, if within 24h of expiry, extend by 7 days\n\n## Dashboard (dashboard/js/auth.js)\n- On load: GET /api/auth/status; if pin_configured=false → show first-run PIN setup page (full-screen, blocks dashboard)\n- First-run page: enter PIN + confirm PIN → POST /api/auth/setup → reload\n- Login page: shown on 401; PIN entry form → POST /api/auth/login → reload on success\n- Logout button in settings panel → POST /api/auth/logout → redirect to login\n\n## Acceptance\n- Fresh install: setup page shown before any dashboard content\n- After PIN set: login required on next visit\n- Session cookie survives page refresh; expires after 7 days of inactivity\n- 401 returned immediately for any /api/ call without valid cookie","status":"closed","priority":1,"issue_type":"task","assignee":"alpha","created_at":"2026-04-06T16:43:02.833541561Z","created_by":"coding","updated_at":"2026-04-06T17:17:02.044261204Z","closed_at":"2026-04-06T17:17:02.044047110Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:2"]} -{"id":"spaxel-nqh","title":"BLE-to-blob identity matching","description":"## Background\n\nThe BLE device registry (spaxel-2wg) tells us which labelled devices are present in the home and their per-node RSSI. The CSI fusion engine (spaxel-m9a) and blob tracker (spaxel-n9n) tell us where anonymous humanoid figures are located in 3D space. Identity matching bridges these two systems: given named BLE devices with per-node RSSI observations, and anonymous CSI blobs with estimated 3D positions, assign device identities to blobs.\n\nWhen a match is confident, the humanoid figure in the 3D view gains a name label and person colour. \"Alice is in the Kitchen\" becomes a real-time fact rather than an approximation.\n\n## RSSI Triangulation Algorithm\n\nFor each BLE device with observations from multiple nodes in the current scan cycle (last 5 seconds):\n\nStep 1: Convert RSSI to distance for each observing node.\nDistance model: d = d0 * 10^((RSSI_ref - RSSI) / (10 * n))\nParameters: d0 = 1.0m (reference distance), RSSI_ref = -65 dBm (RSSI at 1m in typical indoor environment), n = 2.5 (indoor path loss exponent — typical range 2.0-3.5; 2.5 is a reasonable default for residential spaces).\n\nStep 2: With 2+ nodes, perform weighted least squares triangulation.\nPosition estimate: argmin_P { sum_i w_i * (|P - node_i| - d_i)^2 }\nwhere w_i = 1/sigma_i^2, sigma_i = d_i * ln(10) / (10 * n) * RSSI_noise_sigma (typically 5 dBm).\nSolve with 3-5 iterations of gradient descent or Gauss-Newton (the system is nonlinear).\nWith 1 node: only an approximate range estimate; triangulation confidence = 0.2.\nWith 2 nodes: 2D position estimate on a circle/arc; confidence = 0.5.\nWith 3+ nodes: full 2D position estimate with residual as quality indicator; confidence = min(1.0, 0.7 + 0.1 * (n-3)) where n is node count.\n\nStep 3: Assign to nearest CSI blob.\nFor each triangulated BLE position, find the nearest active CSI blob (from TrackManager) within a 2-metre search radius. The assignment uses Euclidean distance in the horizontal plane (ignore Z for BLE since antenna height is variable).\n\nIf multiple BLE devices map to the same blob (e.g. Alice has a phone AND a Fitbit), use the device with the highest triangulation confidence.\n\nIf a BLE device position is triangulated but no CSI blob is within 2 metres: create a \"BLE-only\" placeholder track at the BLE position. BLE-only tracks are shown as a different visual (outlined circle rather than filled, lower opacity) to indicate lower confidence.\n\n## Match Confidence Score\n\nFor each BLE-to-blob assignment, compute a match confidence:\nconfidence = f_observations * f_node_count * f_residual * f_distance\n\nwhere:\n- f_observations: 1.0 if device seen in last 5s, 0.5 if last 15s, 0.0 if older\n- f_node_count: 0.2 (1 node), 0.5 (2 nodes), 0.8+ (3+ nodes)\n- f_residual: 1.0 - min(1.0, triangulation_residual_metres / 2.0) — penalise poor triangulation fit\n- f_distance: 1.0 if blob distance < 0.5m, linear decay to 0 at 2.0m\n\nOnly assign identity if confidence > 0.6. Below this threshold: keep the blob anonymous (\"Unknown\").\n\n## Identity Persistence\n\nOnce a BLE-blob match is made, the identity persists for 5 minutes even if:\n- The BLE device rotates its MAC (new MAC will match same person via the person record)\n- The BLE device briefly falls below RSSI threshold of all nodes (indoor dead zone)\n- The CSI blob briefly disappears (tracker coasted state, per spaxel-n9n)\n\nAfter 5 minutes of no BLE observation and no high-confidence re-match: revert to anonymous.\n\nThis 5-minute persistence prevents flickering identity labels when people walk through areas with inconsistent BLE coverage.\n\n## TrackManager Integration\n\nExtend the TrackState struct in mothership/internal/tracker/ (spaxel-n9n):\n- PersonID string (from BLE registry people table)\n- PersonLabel string\n- PersonColor string\n- IdentityConfidence float64\n- IdentitySource string (\"ble_triangulation\" or \"ble_only\" or \"\")\n\nTrackManager.UpdateIdentities(blePositions map[deviceMAC]Vec3, registry BLERegistry) method: runs the matching algorithm and updates track identity fields.\n\nCalled at the same frequency as FusionEngine (10 Hz), but BLE positions only update at 5s intervals — cache the last BLE positions and re-use them between BLE updates.\n\n## API\n\nGET /api/tracks enriches the existing track list with person_id, person_label, person_color, and identity_confidence fields.\n\nExample response:\n[{\n \"id\": \"track-1\",\n \"position\": {\"x\": 3.2, \"y\": 1.8, \"z\": 1.0},\n \"velocity\": {\"x\": 0.1, \"y\": -0.2, \"z\": 0.0},\n \"confidence\": 0.87,\n \"posture_hint\": \"standing\",\n \"person_id\": \"uuid-alice\",\n \"person_label\": \"Alice\",\n \"person_color\": \"#3b82f6\",\n \"identity_confidence\": 0.82\n}]\n\n## Dashboard Integration\n\nIn the 3D view (Three.js scene): tracks with confirmed identity display a floating text label (person name) above the humanoid figure mesh, rendered using THREE.Sprite with a canvas texture containing the name in the person's colour.\n\nIn the \"People and Devices\" panel: each person row shows \"Currently: Kitchen\" (current zone from room transition portals, Phase 6) and \"In 3D view: [jump to track]\" link.\n\n## Tests\n\n- Test RSSI-to-distance conversion with known values: RSSI=-65 -> d=1.0m, RSSI=-75 -> d=2.5m (with default params)\n- Test triangulation with 3 nodes at known positions and known distances: verify position error < 0.5m\n- Test nearest-blob assignment: 2 blobs at (2,2) and (5,5), BLE device triangulated at (2.3,1.9) -> assigns to first blob\n- Test confidence gate: confidence=0.55 -> no assignment; confidence=0.65 -> assignment made\n- Test BLE-only placeholder track creation when no blob within 2m\n- Test identity persistence: after BLE device disappears, track retains identity for 5 minutes then reverts\n- Test identity handoff when BLE device MAC rotates: same person assignment maintained via person record\n\n## Acceptance Criteria\n\n- Named identity labels appear on 3D blobs when person carries a labelled BLE device with confidence > 0.6\n- Identity is maintained through brief BLE dead zones (up to 5 minutes)\n- Two people in the same room get correct distinct identities when their BLE devices are distinguishable\n- Confidence gate prevents wrong assignments (no identity label when confidence < 0.6)\n- BLE-only placeholder tracks appear for people whose BLE device is heard but no CSI blob is nearby\n- Tests pass","status":"open","priority":3,"issue_type":"task","created_at":"2026-03-28T01:44:50.795871765Z","created_by":"coding","updated_at":"2026-04-09T23:28:13.640321106Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:52"]} +{"id":"spaxel-nqh","title":"BLE-to-blob identity matching","description":"## Background\n\nThe BLE device registry (spaxel-2wg) tells us which labelled devices are present in the home and their per-node RSSI. The CSI fusion engine (spaxel-m9a) and blob tracker (spaxel-n9n) tell us where anonymous humanoid figures are located in 3D space. Identity matching bridges these two systems: given named BLE devices with per-node RSSI observations, and anonymous CSI blobs with estimated 3D positions, assign device identities to blobs.\n\nWhen a match is confident, the humanoid figure in the 3D view gains a name label and person colour. \"Alice is in the Kitchen\" becomes a real-time fact rather than an approximation.\n\n## RSSI Triangulation Algorithm\n\nFor each BLE device with observations from multiple nodes in the current scan cycle (last 5 seconds):\n\nStep 1: Convert RSSI to distance for each observing node.\nDistance model: d = d0 * 10^((RSSI_ref - RSSI) / (10 * n))\nParameters: d0 = 1.0m (reference distance), RSSI_ref = -65 dBm (RSSI at 1m in typical indoor environment), n = 2.5 (indoor path loss exponent — typical range 2.0-3.5; 2.5 is a reasonable default for residential spaces).\n\nStep 2: With 2+ nodes, perform weighted least squares triangulation.\nPosition estimate: argmin_P { sum_i w_i * (|P - node_i| - d_i)^2 }\nwhere w_i = 1/sigma_i^2, sigma_i = d_i * ln(10) / (10 * n) * RSSI_noise_sigma (typically 5 dBm).\nSolve with 3-5 iterations of gradient descent or Gauss-Newton (the system is nonlinear).\nWith 1 node: only an approximate range estimate; triangulation confidence = 0.2.\nWith 2 nodes: 2D position estimate on a circle/arc; confidence = 0.5.\nWith 3+ nodes: full 2D position estimate with residual as quality indicator; confidence = min(1.0, 0.7 + 0.1 * (n-3)) where n is node count.\n\nStep 3: Assign to nearest CSI blob.\nFor each triangulated BLE position, find the nearest active CSI blob (from TrackManager) within a 2-metre search radius. The assignment uses Euclidean distance in the horizontal plane (ignore Z for BLE since antenna height is variable).\n\nIf multiple BLE devices map to the same blob (e.g. Alice has a phone AND a Fitbit), use the device with the highest triangulation confidence.\n\nIf a BLE device position is triangulated but no CSI blob is within 2 metres: create a \"BLE-only\" placeholder track at the BLE position. BLE-only tracks are shown as a different visual (outlined circle rather than filled, lower opacity) to indicate lower confidence.\n\n## Match Confidence Score\n\nFor each BLE-to-blob assignment, compute a match confidence:\nconfidence = f_observations * f_node_count * f_residual * f_distance\n\nwhere:\n- f_observations: 1.0 if device seen in last 5s, 0.5 if last 15s, 0.0 if older\n- f_node_count: 0.2 (1 node), 0.5 (2 nodes), 0.8+ (3+ nodes)\n- f_residual: 1.0 - min(1.0, triangulation_residual_metres / 2.0) — penalise poor triangulation fit\n- f_distance: 1.0 if blob distance < 0.5m, linear decay to 0 at 2.0m\n\nOnly assign identity if confidence > 0.6. Below this threshold: keep the blob anonymous (\"Unknown\").\n\n## Identity Persistence\n\nOnce a BLE-blob match is made, the identity persists for 5 minutes even if:\n- The BLE device rotates its MAC (new MAC will match same person via the person record)\n- The BLE device briefly falls below RSSI threshold of all nodes (indoor dead zone)\n- The CSI blob briefly disappears (tracker coasted state, per spaxel-n9n)\n\nAfter 5 minutes of no BLE observation and no high-confidence re-match: revert to anonymous.\n\nThis 5-minute persistence prevents flickering identity labels when people walk through areas with inconsistent BLE coverage.\n\n## TrackManager Integration\n\nExtend the TrackState struct in mothership/internal/tracker/ (spaxel-n9n):\n- PersonID string (from BLE registry people table)\n- PersonLabel string\n- PersonColor string\n- IdentityConfidence float64\n- IdentitySource string (\"ble_triangulation\" or \"ble_only\" or \"\")\n\nTrackManager.UpdateIdentities(blePositions map[deviceMAC]Vec3, registry BLERegistry) method: runs the matching algorithm and updates track identity fields.\n\nCalled at the same frequency as FusionEngine (10 Hz), but BLE positions only update at 5s intervals — cache the last BLE positions and re-use them between BLE updates.\n\n## API\n\nGET /api/tracks enriches the existing track list with person_id, person_label, person_color, and identity_confidence fields.\n\nExample response:\n[{\n \"id\": \"track-1\",\n \"position\": {\"x\": 3.2, \"y\": 1.8, \"z\": 1.0},\n \"velocity\": {\"x\": 0.1, \"y\": -0.2, \"z\": 0.0},\n \"confidence\": 0.87,\n \"posture_hint\": \"standing\",\n \"person_id\": \"uuid-alice\",\n \"person_label\": \"Alice\",\n \"person_color\": \"#3b82f6\",\n \"identity_confidence\": 0.82\n}]\n\n## Dashboard Integration\n\nIn the 3D view (Three.js scene): tracks with confirmed identity display a floating text label (person name) above the humanoid figure mesh, rendered using THREE.Sprite with a canvas texture containing the name in the person's colour.\n\nIn the \"People and Devices\" panel: each person row shows \"Currently: Kitchen\" (current zone from room transition portals, Phase 6) and \"In 3D view: [jump to track]\" link.\n\n## Tests\n\n- Test RSSI-to-distance conversion with known values: RSSI=-65 -> d=1.0m, RSSI=-75 -> d=2.5m (with default params)\n- Test triangulation with 3 nodes at known positions and known distances: verify position error < 0.5m\n- Test nearest-blob assignment: 2 blobs at (2,2) and (5,5), BLE device triangulated at (2.3,1.9) -> assigns to first blob\n- Test confidence gate: confidence=0.55 -> no assignment; confidence=0.65 -> assignment made\n- Test BLE-only placeholder track creation when no blob within 2m\n- Test identity persistence: after BLE device disappears, track retains identity for 5 minutes then reverts\n- Test identity handoff when BLE device MAC rotates: same person assignment maintained via person record\n\n## Acceptance Criteria\n\n- Named identity labels appear on 3D blobs when person carries a labelled BLE device with confidence > 0.6\n- Identity is maintained through brief BLE dead zones (up to 5 minutes)\n- Two people in the same room get correct distinct identities when their BLE devices are distinguishable\n- Confidence gate prevents wrong assignments (no identity label when confidence < 0.6)\n- BLE-only placeholder tracks appear for people whose BLE device is heard but no CSI blob is nearby\n- Tests pass","status":"closed","priority":3,"issue_type":"task","assignee":"golf","created_at":"2026-03-28T01:44:50.795871765Z","created_by":"coding","updated_at":"2026-04-10T10:03:27.832363950Z","closed_at":"2026-04-10T10:03:27.832299485Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:53"]} {"id":"spaxel-o0e","title":"Fresnel zone debug overlay","description":"## Background\n\nThe Fresnel zone geometry is at the heart of the fusion algorithm (spaxel-m9a). Every link's contribution to the 3D occupancy grid is weighted by how much of the candidate voxel falls within the first Fresnel zone ellipsoid. When debugging why localisation is placing a blob in the wrong position, being able to see the actual Fresnel ellipsoids for each active link — overlaid on the 3D scene — instantly reveals whether the zones are covering the right area.\n\nThis is a pure debug/developer tool. It is toggle-able (off by default) and intended for system tuners and developers, not end users. The explainability overlay (spaxel-ez4) already shows Fresnel ellipsoids for a specific selected blob. The Fresnel zone debug overlay shows them persistently for all active links simultaneously.\n\n## Ellipsoid Geometry (Recap)\n\nFor each active link with TX at position P1 and RX at position P2:\n- Link distance d = |P1 - P2|\n- WiFi channel wavelength lambda: 5 GHz -> lambda = 0.06m, 2.4 GHz -> lambda = 0.125m. Use the channel reported in the node's hello message (or the channel from the link's last received CSI frame header).\n- Semi-major axis: a = (d + lambda/2) / 2\n- Semi-minor axis: b = sqrt(a^2 - (d/2)^2)\n- Ellipsoid centre: midpoint(P1, P2)\n- Ellipsoid orientation: major axis along the P1->P2 unit vector\n\nThe first Fresnel zone ellipsoid represents the region where a point reflector would shorten the signal path by at most half a wavelength relative to the direct path. Motion within this region has maximum impact on CSI.\n\n## Three.js Rendering\n\nEllipsoid mesh construction:\n1. Start with THREE.SphereGeometry(1, 32, 16) — a unit sphere\n2. Apply non-uniform scaling: new THREE.Vector3(a, b, b) via mesh.scale.set(a, b, b)\n3. Rotate to align with the link axis: compute the quaternion that maps (1,0,0) to the P1->P2 unit vector using THREE.Quaternion.setFromUnitVectors(new THREE.Vector3(1,0,0), linkAxis)\n4. Apply the quaternion to mesh.quaternion\n\nMaterial: TWO materials:\n- Wireframe: THREE.LineSegments with EdgesGeometry for crisp wireframe edges, line color matching the link line colour, opacity 0.6\n- Fill: THREE.MeshBasicMaterial with transparent=true, opacity 0.08, colour matching the link, depthWrite=false (so the fill doesn't obscure other geometry)\n\nLayer toggle: add \"Fresnel Zones\" checkbox to the 3D layer control panel (in the \"Debug\" section, only visible when expert mode is active). Default: off. When toggled on, add all ellipsoid meshes to the scene. When toggled off, remove them.\n\n## Per-Link Controls\n\nWhen a user hovers over a Fresnel ellipsoid in the 3D scene (using Three.js raycasting):\n- The corresponding link line highlights (brightness increase)\n- A tooltip appears (HTML overlay, positioned at screen coordinates of the hover point):\n \"Link: [tx_label] to [rx_label]\n Fresnel zone radius at midpoint: {b:.2f}m\n Link distance: {d:.2f}m\n Wavelength: {lambda:.3f}m (channel {ch})\n Link health: {health_score:.0%}\"\n\nClicking an ellipsoid:\n- Selects the corresponding link in the link panel (sidebar)\n- Highlights the link entry in the link list\n\n## Performance Considerations\n\nWith 6 active links, we render 6 pairs of meshes (wireframe + fill = 12 Three.js objects). This is negligible for any modern GPU. However, the wireframe geometry uses EdgesGeometry which creates one Line for each edge — for a sphere with 32 horizontal and 16 vertical segments, that's approximately 1000 line segments per ellipsoid. At 6 links, 6000 line segments total. This should render at 60 fps on any modern device, but if performance is an issue on mobile, reduce the sphere segment count to 16x8 when the debug overlay is active on mobile viewports.\n\nPre-compute at link addition time: when a new link is registered (node hello + peer MAC), compute the ellipsoid geometry and add it to the scene (hidden if the layer is off). Update on node position change. Remove when link becomes inactive (no frames for > 30s).\n\n## Relationship to Explainability Overlay\n\nThe Fresnel zone debug overlay (this bead) and the detection explainability overlay (spaxel-ez4) both render Fresnel ellipsoids. They share the same geometry computation code (dashboard/js/fresnel.js — the ellipsoid helper function). The difference:\n- This overlay: shows all active link ellipsoids simultaneously, toggle-able layer\n- Explainability overlay: shows only contributing link ellipsoids for a specific selected blob, in explain mode\n\nBoth import from fresnel.js. The helper function FresnelEllipsoid(P1, P2, lambda) returns a Three.js Mesh ready for scene insertion.\n\n## Files to Create or Modify\n\n- dashboard/js/fresnel.js: FresnelEllipsoid helper function (shared with explainability)\n- dashboard/js/layers.js: add \"Fresnel Zones\" toggle in the debug layer section\n- dashboard/js/app.js: integrate Fresnel overlay management — create/update/remove ellipsoids on link events\n\n## Tests\n\n- Test ellipsoid geometry computation with known TX/RX positions: TX at (0,0,0), RX at (4,0,0), lambda=0.06m -> a ~= 2.015, b ~= 0.345. Verify to 3 decimal places.\n- Test semi-minor axis for edge case: very short link d=0.1m -> b should be very small but positive\n- Test for diagonal link: TX at (0,0,0), RX at (3,4,0) (distance=5m) -> verify a and b are computed correctly\n- Test that toggling the layer on/off adds/removes the correct number of mesh objects from the scene (mock Three.js scene)\n- Test hover tooltip shows correct data (link health from mock, link endpoints from mock)\n- Test that ellipsoids update when node position changes\n\n## Acceptance Criteria\n\n- Fresnel zone ellipsoids render correctly for all active links when the debug layer is toggled on\n- Ellipsoid semi-major and semi-minor axes match theoretical first Fresnel zone values for the link distance and frequency\n- Toggle shows/hides all ellipsoids cleanly without leaving orphan objects in the scene\n- Hovering an ellipsoid shows the correct tooltip with link details and health score\n- Clicking an ellipsoid selects the corresponding link in the link panel\n- Geometry computation is shared with the explainability overlay via fresnel.js\n- Tests pass","status":"open","priority":3,"issue_type":"task","created_at":"2026-03-28T01:58:33.424914116Z","created_by":"coding","updated_at":"2026-03-28T03:29:14.736776003Z","source_repo":".","compaction_level":0,"original_size":0,"dependencies":[{"issue_id":"spaxel-o0e","depends_on_id":"spaxel-i28","type":"blocks","created_at":"2026-03-28T03:29:14.736620594Z","created_by":"coding","metadata":"{}","thread_id":""}]} {"id":"spaxel-o4l","title":"Bidirectional node protocol","description":"Implement full bidirectional protocol over the existing WebSocket connection.\n\n## Deliverables\n- Registration (hello message with capabilities)\n- Health reporting (heap, WiFi RSSI, uptime, temperature every 10s)\n- BLE scan relay (device list JSON)\n- Role/config push from mothership (TX/RX/passive mode, packet rate)\n- OTA command messages (trigger update, progress tracking)\n- All messages over the existing single WebSocket per node\n\n## Acceptance Criteria\n- Nodes register on connect with full capability advertisement\n- Mothership can push role changes and config updates\n- Health metrics flow reliably at 10s intervals\n- Protocol is backward-compatible with Phase 1 implementation\n\n## References\n- Current protocol: mothership/internal/ingestion/message.go\n- Firmware WebSocket: firmware/main/websocket.c","status":"closed","priority":2,"issue_type":"task","assignee":"spaxel-alpha","created_at":"2026-03-27T01:56:31.632551776Z","created_by":"coding","updated_at":"2026-03-28T01:34:05.644219477Z","closed_at":"2026-03-27T03:14:43.201850105Z","close_reason":"Implemented full bidirectional node protocol. Firmware: motion hints wired to websocket_send_motion_hint() with rate-limiting, csi_set_rate() fixed, all message types active (hello/health/ble/motion_hint/ota_status). Mothership: OnMotionHint() ramps adjacent nodes via topology callback, idle timeout 30s, variance threshold adaptive, added SendRoleToMAC() and SendOTAToMAC() for dynamic downstream pushes, OTA status logging. Binary CSI frames remain backward-compatible with Phase 1.","source_repo":".","compaction_level":0,"original_size":0,"dependencies":[{"issue_id":"spaxel-o4l","depends_on_id":"spaxel-uc9","type":"blocks","created_at":"2026-03-28T01:34:05.644181123Z","created_by":"coding","metadata":"{}","thread_id":""}]} {"id":"spaxel-ofa","title":"End-to-end integration test harness (simulator + mothership assertions)","description":"## Overview\nBuild an automated integration test that starts the mothership, runs the CSI simulator against it, and asserts on observable behavior — providing a production-realism gate for CI.\n\n## Test harness (tests/e2e/run.sh or Go test)\n\n### Setup:\n1. Start mothership container (or binary): docker run -d -p 8080:8080 ronaldraygun/spaxel:latest\n2. Wait for /healthz to return {status:'ok'} with 15s timeout (poll every 500ms)\n3. If PIN auth enabled: POST /api/auth/setup with test PIN; POST /api/auth/login\n\n### Run simulator:\n4. Start: sim --mothership http://localhost:8080 --nodes 4 --walkers 2 --duration 30s --rate 20 --ble --seed 42\n5. Simulator exits non-zero if it receives {type:'reject'} message; test fails immediately\n\n### Assert during run (poll every 1s for 30s):\n6. GET /api/blobs (or WebSocket) → assert blob_count > 0 within first 15s\n7. GET /api/nodes → assert nodes_online == 4 within first 5s\n8. GET /healthz → assert status=='ok' throughout entire run\n\n### Assert after run:\n9. GET /api/events?type=detection → assert at least 1 detection event recorded\n10. Simulator printed per-second frame counts to stdout; verify no frame-rate drop >20% from target\n\n## CI integration\n- GitHub Actions workflow: .github/workflows/e2e.yml (but only triggers from Argo Workflows via spaxel-ci)\n- Build image → run test harness → post result as bead comment\n\n## Acceptance\n- Test passes on fresh container with seed 42 configuration\n- Test fails clearly when mothership rejects frames (wrong protocol)\n- Test runs in <90s total (15s startup + 30s sim + 45s buffer)","status":"closed","priority":2,"issue_type":"task","assignee":"alpha","created_at":"2026-04-06T16:44:47.443177386Z","created_by":"coding","updated_at":"2026-04-07T20:01:09.701396700Z","closed_at":"2026-04-07T20:01:09.701265832Z","close_reason":"Implemented end-to-end integration test harness for Spaxel:\n\n1. Argo WorkflowTemplate spaxel-e2e-workflowtemplate.yml added to declarative-config for CI/CD integration\n\n2. Existing test infrastructure already in place:\n - Bash script harness: tests/e2e/run.sh\n - Go test harness: mothership/tests/e2e/e2e_test.go\n - CSI simulator: mothership/cmd/sim/main.go\n - GitHub Actions workflow: .github/workflows/e2e.yml\n\n3. Test harness behavior:\n - Starts mothership container (or local binary)\n - Waits for /healthz to return ok (15s timeout, 500ms poll)\n - Handles PIN auth setup if enabled\n - Runs simulator with configurable nodes/walkers/duration/rate\n - Asserts during run: health ok, nodes online, blobs detected\n - Asserts after run: detection events, frame rate\n - Runs in under 90s total\n\n4. CI integration via Argo Workflows spaxel-e2e template","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:19"]} @@ -128,7 +128,7 @@ {"id":"spaxel-q9d","title":"Add GDOP overlay","description":"Implement GDOP (Geometric Dilution of Precision) overlay for the simulator.\n\nAcceptance:\n- GDOP overlay visualizes accuracy metrics across the virtual space\n- Simulator produces realistic synthetic data matching real-world conditions","status":"closed","priority":2,"issue_type":"task","assignee":"golf","created_at":"2026-04-09T16:11:25.552156606Z","created_by":"coding","updated_at":"2026-04-10T00:30:03.856931576Z","closed_at":"2026-04-10T00:30:03.856827566Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:14","mitosis-child","mitosis-depth:1","parent-spaxel-d41"]} {"id":"spaxel-qfp","title":"Sleep quality monitoring","description":"## Background\n\nThe breathing analysis feature (Phase 5, spaxel-r37) detects the micro-motion of breathing in stationary people. Run continuously in bedroom zones overnight, it can compute sleep quality metrics without any wearable device. Chest displacement during breathing at 15 breaths/minute produces a detectable 0.25 Hz signal in CSI. By tracking this overnight, combined with motion events (wake episodes) and the timing of presence in the bedroom zone, we can produce a sleep summary that rivals basic commercial sleep trackers — without the user wearing anything.\n\n## Sleep Session Detection\n\nSleepMonitor in mothership/internal/sleep/monitor.go.\n\nSession onset detection (all conditions must hold):\n1. Person is in a bedroom zone (zone with is_bedroom flag = true, set in zone editor)\n2. Stationary detection fires (STATIONARY_DETECTED state from breathing analysis bead)\n3. BLE device shows reduced activity (optional enhancement: phone advertising rate drops when screen is off; this is a bonus signal, not required)\nTentative onset: all conditions met. Confirmed onset: conditions hold for 15 consecutive minutes.\n\nSession end detection:\n1. Person leaves bedroom zone (zone transition event fires)\n2. OR: motion detection fires for > 2 minutes (sustained motion = getting up)\n3. OR: stationary detection drops and does not return for > 30 minutes (person left room without portal crossing — reconciliation path)\n\nSession record stored in SQLite:\nCREATE TABLE sleep_sessions (\n id TEXT PRIMARY KEY,\n person_id TEXT NOT NULL,\n zone_id TEXT NOT NULL, -- bedroom zone\n session_date DATE NOT NULL, -- the date this sleep night belongs to (typically today-1 for morning reports)\n sleep_onset DATETIME, -- time tentative detection was confirmed\n wake_time DATETIME,\n time_in_bed_minutes REAL,\n sleep_latency_minutes REAL, -- time from entering bedroom to sleep onset\n wake_episode_count INTEGER DEFAULT 0,\n wake_after_sleep_onset_minutes REAL, -- total time awake after first sleep onset\n breathing_rate_mean REAL,\n breathing_rate_stddev REAL,\n breathing_anomaly_count INTEGER DEFAULT 0, -- breathing < 8 or > 25 per minute\n sleep_efficiency REAL -- (time_in_bed - waso) / time_in_bed * 100\n);\n\nCREATE TABLE sleep_wake_episodes (\n id TEXT PRIMARY KEY,\n session_id TEXT,\n episode_start DATETIME,\n episode_end DATETIME,\n duration_seconds REAL\n);\n\n## Sleep Metrics Computation\n\nDuring the sleep session, SleepMonitor subscribes to:\n- Breathing data: periodic sample of breathing_freq_hz from BreathingDetector (spaxel-r37). Store in a rolling buffer.\n- Motion events: MOTION_DETECTED state transitions from LinkProcessor. Each motion event during a confirmed sleep session is a potential wake episode.\n\nWake episode classification:\n- If deltaRMS > threshold for > 3 seconds: wake episode starts\n- If deltaRMS returns below threshold and breathing signal resumes: wake episode ends\n- Store episode start/end in sleep_wake_episodes\n\nBreathing analysis during sleep:\n- Mean breathing rate (bpm): mean(breathing_freq_hz * 60) over all samples in session\n- Breathing rate standard deviation: indicates sleep stage variability (higher variance may indicate REM activity)\n- Breathing anomaly: if breathing_freq_hz * 60 < 8 or > 25 for > 3 consecutive minutes: log anomaly. This is a proxy for potential sleep apnoea or hyperventilation.\n\nSleep efficiency: (time_in_bed_minutes - wake_after_sleep_onset_minutes) / time_in_bed_minutes * 100. A value above 85% is considered good sleep efficiency.\n\n## Morning Summary Card\n\nOn first WebSocket connection from the dashboard after 6am AND after a sleep session has ended (wake_time is set):\n- Mothership pushes a \"morning_summary\" WebSocket message with the completed session data\n- Dashboard renders a dismissible card in simple mode (full width at top) and as a floating panel in expert mode\n\nCard content:\n- \"Last night: [sleep_duration] h [mm] min\"\n- Colored efficiency indicator: green (>85%), amber (70-85%), red (<70%)\n- Wake episodes: \"2 wake episodes, [total waso] min awake after sleep onset\"\n- Breathing: \"Average breathing: [N] breaths/min\"\n- Anomaly note (if applicable): \"Unusual breathing detected at [time]. [View details]\"\n- \"View full sleep report\" link (opens detailed timeline view in expert mode)\n\n## Weekly Trends\n\nDashboard \"Sleep\" panel:\n- 7-day sparkline of sleep duration per night\n- 7-day sparkline of sleep efficiency per night\n- Average breathing rate over the week\n- Week-over-week comparison: \"This week you slept 6h 48m on average (vs. 7h 12m last week)\"\n\n## Per-Person Tracking\n\nSleep monitoring is person-specific and requires BLE identity (so the system knows whose bedroom this is). Multiple people sharing a bedroom: each person has their own sleep session if their BLE devices can be distinguished. If both people are in bed simultaneously, the breathing detector may pick up a blend of two breathing rates — acknowledge this limitation in documentation.\n\nFor anonymous tracks (no BLE identity): detect in-bedroom stationary presence only (no per-person sleep report). Log \"Unidentified person in bedroom zone\" for 8+ hour periods.\n\n## Zone Configuration\n\nThe zone editor (portals bead, spaxel-qlh) is extended with a zone type selector:\n- Normal zone (default)\n- Bedroom (enables sleep monitoring)\n- Kitchen (no special behavior)\n- Children's zone (suppresses fall detection)\n\nThis is stored as zone_type in the zones table.\n\n## Files to Create or Modify\n\n- mothership/internal/sleep/monitor.go: SleepMonitor, session detection, metric computation\n- mothership/internal/sleep/report.go: morning summary generation, weekly trend aggregation\n- mothership/internal/signal/breathing.go (spaxel-r37): add tick-based sample reporting for sleep monitor\n- dashboard/js/sleep.js: morning summary card, Sleep panel\n- mothership/internal/events/events.go: SleepSessionStartEvent, SleepSessionEndEvent\n\n## Tests\n\n- Test sleep session onset: stationary detection fires, person in bedroom, 15 minutes -> session confirmed\n- Test that stationary detection < 15 minutes does not create a session (avoids brief naps misclassified)\n- Test wake episode counting: 3 MOTION_DETECTED events > 3s each during a session -> wake_episode_count = 3\n- Test wake after sleep onset calculation: 3 episodes of 5 minutes each -> waso = 15 minutes\n- Test sleep efficiency calculation: 480 minutes in bed, 45 minutes waso -> efficiency = 90.6%\n- Test breathing anomaly detection: inject 4 minutes of breathing_freq_hz = 0.1 (6 bpm) -> anomaly logged\n- Test morning summary trigger fires only on first connection after 6am AND after session end\n\n## Acceptance Criteria\n\n- Sleep session detected within 15 minutes of confirmed onset (stationary in bedroom zone)\n- Wake episodes counted correctly (tested with synthetic motion event injection)\n- Morning summary card appears on first dashboard open after wake time (6am by default, configurable)\n- Weekly trends sparkline shows 7 nights of data after 7 days\n- Sleep session data persists in SQLite across mothership restarts\n- Breathing anomaly flag fires correctly for rate < 8 or > 25 bpm\n- Tests pass","status":"in_progress","priority":3,"issue_type":"task","assignee":"hotel","created_at":"2026-03-28T01:52:06.457208929Z","created_by":"coding","updated_at":"2026-04-09T17:45:50.699344621Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:81"]} {"id":"spaxel-qgj","title":"Implement NTP client in ESP32 firmware","description":"Add NTP synchronization to firmware/main/wifi.c or ntp.c:\n- Call esp_sntp_setservername(0, ntp_server) before esp_sntp_init() on boot\n- ntp_server read from NVS 'ntp_server' key (default: 'pool.ntp.org')\n- Attempt sync for up to 10 seconds after WiFi connect; log WARN if sync fails\n- On sync failure: proceed without stagger (rely on CSMA/CA)\n- Resync every 10 minutes via esp_timer periodic callback\n- Include ntp_synced status in health JSON message\n\nAcceptance: Node health messages show ntp_synced: true when pool is reachable; ntp_synced: false when NTP blocked — node still operates normally; resync occurs every ~600s (verified via UART logs)","status":"closed","priority":2,"issue_type":"task","assignee":"alpha","created_at":"2026-04-07T14:37:00.302557793Z","created_by":"coding","updated_at":"2026-04-07T17:32:57.896842167Z","closed_at":"2026-04-07T17:32:57.896693758Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["failure-count:1","mitosis-child","mitosis-depth:1","parent-spaxel-u7y"]} -{"id":"spaxel-qlh","title":"Room transition portals and zone occupancy","description":"## Background\n\nKnowing a blob is at coordinates (3.2m, 1.8m, 1.0m) is useful to the algorithm, but \"Alice is in the Kitchen\" is useful to a person. Room transition portals define doorway planes between named zones. When a track's trajectory intersects a portal plane, the zone occupancy counts update and a transition event fires. This is the foundation for natural language presence display (\"Alice is in the Kitchen\"), automation triggers (\"when Alice enters the bedroom\"), and the activity timeline (\"Alice moved from Living Room to Kitchen at 14:23\").\n\n## Zone Definitions\n\nZones are named 3D volumes represented as axis-aligned bounding boxes (AABB) for simplicity. Each zone has: id (uuid), name (\"Kitchen\"), bounds_min (Vec3), bounds_max (Vec3), color (hex string for 3D overlay), created_at.\n\nSQLite schema:\nCREATE TABLE zones (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n bounds_min_x REAL, bounds_min_y REAL, bounds_min_z REAL,\n bounds_max_x REAL, bounds_max_y REAL, bounds_max_z REAL,\n color TEXT DEFAULT '#3b82f6',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP\n);\n\nContainment test: a position P is in zone Z if bounds_min_x <= P.x <= bounds_max_x AND bounds_min_y <= P.y <= bounds_max_y. The Z bounds are typically 0 to ceiling height (usually 2.5m) since we track floor-plane position.\n\n## Portal Definitions\n\nA portal is a vertical plane segment spanning a doorway. It divides two zones and detects crossings.\n\nPortal schema:\nCREATE TABLE portals (\n id TEXT PRIMARY KEY,\n name TEXT, -- e.g. \"Kitchen Door\"\n zone_a_id TEXT, -- zone on one side\n zone_b_id TEXT, -- zone on other side\n plane_point Vec3, -- a point on the portal plane (e.g. centre of doorway)\n plane_normal Vec3, -- unit normal vector of the portal plane\n width REAL, -- width of the doorway in metres\n height REAL, -- height of the doorway (default: 2.1m)\n created_at DATETIME\n);\n\nA portal normal points from zone_a toward zone_b. A crossing from zone_a to zone_b has dot(velocity, normal) > 0. A crossing from zone_b to zone_a has dot(velocity, normal) < 0.\n\n## Portal Editor (3D Dashboard)\n\nExtend the node placement UI (spaxel-qq6) with portal editing:\n1. User clicks \"Add Portal\" button\n2. A vertical plane appears in the 3D scene at the camera's focal point\n3. User drags the plane using TransformControls (from Three.js addons) to position it across a doorway\n4. User adjusts width and assigns zone names on each side (dropdown of existing zones or \"Create new zone\")\n5. User clicks \"Save\" — portal is stored in SQLite and rendered as a semi-transparent divider plane in the 3D scene\n\nPortal rendering: thin coloured plane (opacity 0.3, colour #a855f7 purple) with a label at the top edge showing the portal name. When a track crosses the portal, the plane briefly flashes brighter (animated opacity increase then decay back to 0.3).\n\nZone rendering: semi-transparent coloured cuboid volumes (opacity 0.1, colour from zone.color). Zone name displayed as a floating text label at the zone centroid (using THREE.Sprite). A \"Zones\" layer toggle in the 3D view hides/shows all zones simultaneously.\n\n## Crossing Detection\n\nCrossingDetector runs as part of the TrackManager update loop (10 Hz). For each track update:\n\n1. For each active portal, test if the track crossed the portal plane in the last update step:\n - Previous position P_prev, current position P_curr\n - Check if the line segment P_prev -> P_curr intersects the portal plane within the portal's rectangular bounds (width x height centered on plane_point)\n - Intersection test: t = dot(plane_point - P_prev, normal) / dot(P_curr - P_prev, normal). If 0 <= t <= 1, compute intersection point P_int = P_prev + t*(P_curr - P_prev), then check if P_int is within the doorway rectangle.\n - Crossing direction: if dot(P_curr - P_prev, normal) > 0, direction is A_to_B; otherwise B_to_A.\n\n2. On crossing detected: update occupancy counts, emit ZoneCrossingEvent.\n\nZoneCrossingEvent: {portal_id, track_id, person_id, person_label, from_zone_id, from_zone_name, to_zone_id, to_zone_name, direction, timestamp}.\n\nThis event is:\n- Published to the internal event bus\n- Broadcast via WebSocket to dashboard as type \"zone_transition\"\n- Appended to activity timeline (Phase 8)\n- Processed by automation engine (Phase 6)\n\n## Occupancy Counter\n\nOccupancyManager maintains a per-zone current occupant list (map[zoneID][]TrackID).\n\nUpdates from two sources:\n1. CrossingDetector portal events: when a track crosses from zone A to B, move its entry in the occupancy map from A to B.\n2. Direct containment check: run every 30 seconds as a reconciliation pass. For each active track, check if it is within any zone's bounding box. If the track is in zone C but the occupancy map says it is in zone A (e.g. track was created inside a zone without crossing a portal), update accordingly.\nThe containment check prevents \"teleportation\" inconsistencies when tracks are created or resume from coasting state.\n\n## WebSocket Broadcast\n\nOn each zone occupancy change, the mothership broadcasts:\n{\"type\":\"zone_occupancy\",\"zones\":[{\"id\":\"zone-kitchen\",\"name\":\"Kitchen\",\"occupants\":[{\"track_id\":\"track-1\",\"person_id\":\"uuid-alice\",\"person_label\":\"Alice\"}]},{\"id\":\"zone-living\",\"name\":\"Living Room\",\"occupants\":[]}]}\n\nAnd specifically on crossings:\n{\"type\":\"zone_transition\",\"portal_id\":\"...\",\"person_label\":\"Alice\",\"from_zone\":\"Kitchen\",\"to_zone\":\"Living Room\",\"timestamp\":\"2026-03-27T14:23:00Z\"}\n\n## REST API\n\nGET /api/zones: list all zones with current occupancy\nPOST /api/zones: create zone\nPUT /api/zones/{id}: update zone bounds/name/color\nDELETE /api/zones/{id}: delete zone (removes from all occupancy tracking)\n\nGET /api/portals: list all portals\nPOST /api/portals: create portal\nPUT /api/portals/{id}: update portal\nDELETE /api/portals/{id}: delete portal\n\nGET /api/zones/{id}/history?since=2026-03-27T00:00:00Z: get crossing history for zone (list of ZoneCrossingEvent)\n\n## Tests\n\n- Test portal crossing detection with a track path that passes through the portal plane: verify crossing event fires with correct direction\n- Test that a track path that runs parallel to a portal plane but within 0.1m does not fire a false crossing\n- Test that a track path outside the portal's width bounds does not fire a crossing\n- Test occupancy count updates: zone Kitchen starts with 1 occupant, track crosses portal to Living Room, Kitchen count = 0, Living Room count = 1\n- Test the 30-second reconciliation pass: track that appears inside a zone without crossing a portal is correctly assigned to that zone\n- Test zone containment with a position exactly on the bounds_min edge (inclusive boundary)\n- Test that zone_transition WebSocket message is broadcast with correct from_zone and to_zone names\n\n## Acceptance Criteria\n\n- Portal editor allows placing vertical plane portals across doorways in the 3D scene\n- Zone bounding boxes are editable and render as semi-transparent volumes in 3D view\n- Zone labels update in real-time as people move between zones (\"Kitchen: Alice, Bob\")\n- Zone transition events fire within one track update cycle (100ms) of the crossing occurring\n- Reconciliation pass correctly handles tracks that appear inside zones without portal crossings\n- Zone and portal data persists across mothership restarts via SQLite\n- WebSocket broadcasts zone_occupancy after every occupancy change\n- Tests pass","status":"open","priority":3,"issue_type":"task","created_at":"2026-03-28T01:45:41.668543362Z","created_by":"coding","updated_at":"2026-03-28T03:29:14.268105795Z","source_repo":".","compaction_level":0,"original_size":0,"dependencies":[{"issue_id":"spaxel-qlh","depends_on_id":"spaxel-c0q","type":"blocks","created_at":"2026-03-28T03:29:14.268078719Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-qlh","depends_on_id":"spaxel-nqh","type":"blocks","created_at":"2026-03-28T01:45:44.642770328Z","created_by":"coding","metadata":"{}","thread_id":""}]} +{"id":"spaxel-qlh","title":"Room transition portals and zone occupancy","description":"## Background\n\nKnowing a blob is at coordinates (3.2m, 1.8m, 1.0m) is useful to the algorithm, but \"Alice is in the Kitchen\" is useful to a person. Room transition portals define doorway planes between named zones. When a track's trajectory intersects a portal plane, the zone occupancy counts update and a transition event fires. This is the foundation for natural language presence display (\"Alice is in the Kitchen\"), automation triggers (\"when Alice enters the bedroom\"), and the activity timeline (\"Alice moved from Living Room to Kitchen at 14:23\").\n\n## Zone Definitions\n\nZones are named 3D volumes represented as axis-aligned bounding boxes (AABB) for simplicity. Each zone has: id (uuid), name (\"Kitchen\"), bounds_min (Vec3), bounds_max (Vec3), color (hex string for 3D overlay), created_at.\n\nSQLite schema:\nCREATE TABLE zones (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n bounds_min_x REAL, bounds_min_y REAL, bounds_min_z REAL,\n bounds_max_x REAL, bounds_max_y REAL, bounds_max_z REAL,\n color TEXT DEFAULT '#3b82f6',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP\n);\n\nContainment test: a position P is in zone Z if bounds_min_x <= P.x <= bounds_max_x AND bounds_min_y <= P.y <= bounds_max_y. The Z bounds are typically 0 to ceiling height (usually 2.5m) since we track floor-plane position.\n\n## Portal Definitions\n\nA portal is a vertical plane segment spanning a doorway. It divides two zones and detects crossings.\n\nPortal schema:\nCREATE TABLE portals (\n id TEXT PRIMARY KEY,\n name TEXT, -- e.g. \"Kitchen Door\"\n zone_a_id TEXT, -- zone on one side\n zone_b_id TEXT, -- zone on other side\n plane_point Vec3, -- a point on the portal plane (e.g. centre of doorway)\n plane_normal Vec3, -- unit normal vector of the portal plane\n width REAL, -- width of the doorway in metres\n height REAL, -- height of the doorway (default: 2.1m)\n created_at DATETIME\n);\n\nA portal normal points from zone_a toward zone_b. A crossing from zone_a to zone_b has dot(velocity, normal) > 0. A crossing from zone_b to zone_a has dot(velocity, normal) < 0.\n\n## Portal Editor (3D Dashboard)\n\nExtend the node placement UI (spaxel-qq6) with portal editing:\n1. User clicks \"Add Portal\" button\n2. A vertical plane appears in the 3D scene at the camera's focal point\n3. User drags the plane using TransformControls (from Three.js addons) to position it across a doorway\n4. User adjusts width and assigns zone names on each side (dropdown of existing zones or \"Create new zone\")\n5. User clicks \"Save\" — portal is stored in SQLite and rendered as a semi-transparent divider plane in the 3D scene\n\nPortal rendering: thin coloured plane (opacity 0.3, colour #a855f7 purple) with a label at the top edge showing the portal name. When a track crosses the portal, the plane briefly flashes brighter (animated opacity increase then decay back to 0.3).\n\nZone rendering: semi-transparent coloured cuboid volumes (opacity 0.1, colour from zone.color). Zone name displayed as a floating text label at the zone centroid (using THREE.Sprite). A \"Zones\" layer toggle in the 3D view hides/shows all zones simultaneously.\n\n## Crossing Detection\n\nCrossingDetector runs as part of the TrackManager update loop (10 Hz). For each track update:\n\n1. For each active portal, test if the track crossed the portal plane in the last update step:\n - Previous position P_prev, current position P_curr\n - Check if the line segment P_prev -> P_curr intersects the portal plane within the portal's rectangular bounds (width x height centered on plane_point)\n - Intersection test: t = dot(plane_point - P_prev, normal) / dot(P_curr - P_prev, normal). If 0 <= t <= 1, compute intersection point P_int = P_prev + t*(P_curr - P_prev), then check if P_int is within the doorway rectangle.\n - Crossing direction: if dot(P_curr - P_prev, normal) > 0, direction is A_to_B; otherwise B_to_A.\n\n2. On crossing detected: update occupancy counts, emit ZoneCrossingEvent.\n\nZoneCrossingEvent: {portal_id, track_id, person_id, person_label, from_zone_id, from_zone_name, to_zone_id, to_zone_name, direction, timestamp}.\n\nThis event is:\n- Published to the internal event bus\n- Broadcast via WebSocket to dashboard as type \"zone_transition\"\n- Appended to activity timeline (Phase 8)\n- Processed by automation engine (Phase 6)\n\n## Occupancy Counter\n\nOccupancyManager maintains a per-zone current occupant list (map[zoneID][]TrackID).\n\nUpdates from two sources:\n1. CrossingDetector portal events: when a track crosses from zone A to B, move its entry in the occupancy map from A to B.\n2. Direct containment check: run every 30 seconds as a reconciliation pass. For each active track, check if it is within any zone's bounding box. If the track is in zone C but the occupancy map says it is in zone A (e.g. track was created inside a zone without crossing a portal), update accordingly.\nThe containment check prevents \"teleportation\" inconsistencies when tracks are created or resume from coasting state.\n\n## WebSocket Broadcast\n\nOn each zone occupancy change, the mothership broadcasts:\n{\"type\":\"zone_occupancy\",\"zones\":[{\"id\":\"zone-kitchen\",\"name\":\"Kitchen\",\"occupants\":[{\"track_id\":\"track-1\",\"person_id\":\"uuid-alice\",\"person_label\":\"Alice\"}]},{\"id\":\"zone-living\",\"name\":\"Living Room\",\"occupants\":[]}]}\n\nAnd specifically on crossings:\n{\"type\":\"zone_transition\",\"portal_id\":\"...\",\"person_label\":\"Alice\",\"from_zone\":\"Kitchen\",\"to_zone\":\"Living Room\",\"timestamp\":\"2026-03-27T14:23:00Z\"}\n\n## REST API\n\nGET /api/zones: list all zones with current occupancy\nPOST /api/zones: create zone\nPUT /api/zones/{id}: update zone bounds/name/color\nDELETE /api/zones/{id}: delete zone (removes from all occupancy tracking)\n\nGET /api/portals: list all portals\nPOST /api/portals: create portal\nPUT /api/portals/{id}: update portal\nDELETE /api/portals/{id}: delete portal\n\nGET /api/zones/{id}/history?since=2026-03-27T00:00:00Z: get crossing history for zone (list of ZoneCrossingEvent)\n\n## Tests\n\n- Test portal crossing detection with a track path that passes through the portal plane: verify crossing event fires with correct direction\n- Test that a track path that runs parallel to a portal plane but within 0.1m does not fire a false crossing\n- Test that a track path outside the portal's width bounds does not fire a crossing\n- Test occupancy count updates: zone Kitchen starts with 1 occupant, track crosses portal to Living Room, Kitchen count = 0, Living Room count = 1\n- Test the 30-second reconciliation pass: track that appears inside a zone without crossing a portal is correctly assigned to that zone\n- Test zone containment with a position exactly on the bounds_min edge (inclusive boundary)\n- Test that zone_transition WebSocket message is broadcast with correct from_zone and to_zone names\n\n## Acceptance Criteria\n\n- Portal editor allows placing vertical plane portals across doorways in the 3D scene\n- Zone bounding boxes are editable and render as semi-transparent volumes in 3D view\n- Zone labels update in real-time as people move between zones (\"Kitchen: Alice, Bob\")\n- Zone transition events fire within one track update cycle (100ms) of the crossing occurring\n- Reconciliation pass correctly handles tracks that appear inside zones without portal crossings\n- Zone and portal data persists across mothership restarts via SQLite\n- WebSocket broadcasts zone_occupancy after every occupancy change\n- Tests pass","status":"in_progress","priority":3,"issue_type":"task","assignee":"golf","created_at":"2026-03-28T01:45:41.668543362Z","created_by":"coding","updated_at":"2026-04-10T12:04:54.854119818Z","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:19"],"dependencies":[{"issue_id":"spaxel-qlh","depends_on_id":"spaxel-c0q","type":"blocks","created_at":"2026-03-28T03:29:14.268078719Z","created_by":"coding","metadata":"{}","thread_id":""},{"issue_id":"spaxel-qlh","depends_on_id":"spaxel-nqh","type":"blocks","created_at":"2026-03-28T01:45:44.642770328Z","created_by":"coding","metadata":"{}","thread_id":""}]} {"id":"spaxel-qob","title":"Webhook action firing & fault tolerance for automations","description":"## Overview\nReliable webhook delivery for automation trigger actions with error handling and dashboard feedback.\n\n## Backend (mothership/automation/)\n- HTTP client: POST to configured URL with 5s timeout; fire-and-forget (no retry)\n- Payload schema: {trigger_id, trigger_name, condition, blob_id, person, position:{x,y,z}, zone, dwell_s, timestamp_ms}\n- Error handling:\n - 4xx response: disable trigger + set trigger.error_message; push WS alert to dashboard\n - 5xx / timeout: log warning + increment trigger.error_count; do NOT disable\n - error_count resets on first 2xx response\n- Test endpoint: POST /api/triggers/{id}/test — fires webhook once with synthetic payload, returns {status, response_ms, error}\n- Audit log: webhook_log table (trigger_id, fired_at_ms, url, status_code, latency_ms, error)\n\n## Dashboard\n- Error badge on trigger card when disabled due to 4xx\n- 'Test Webhook' button in trigger edit panel — shows response in real time\n- Last N firings visible in trigger detail view (from webhook_log)\n- 'Re-enable' button to clear error state and retry\n\n## Acceptance\n- 5xx failures do not disable triggers\n- 4xx disables trigger and shows dashboard warning within 2s\n- Test endpoint returns response within timeout + 500ms overhead\n- Requires: spaxel-6ha (REST API), spaxel-vuw (trigger volumes), spaxel-9eg (WS alerts)","status":"closed","priority":2,"issue_type":"task","assignee":"foxtrot","created_at":"2026-04-06T13:01:53.677999018Z","created_by":"coding","updated_at":"2026-04-07T04:16:09.129273227Z","closed_at":"2026-04-07T04:16:09.129061569Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","failure-count:8"]} {"id":"spaxel-qp3","title":"Implement firmware LED blink handler","description":"Parse downstream JSON message {type:'identify', duration_ms: 5000} and implement LED blink handler that toggles GPIO LED pin at 100ms on/100ms off for duration_ms. LED GPIO is board-specific (default GPIO8 for ESP32-S3-DevKitC; configurable via sdkconfig). Run blink in a FreeRTOS task so it doesn't block WebSocket processing. Cancel any running blink when new identify message received or on disconnect.\n\n**Acceptance:**\n- LED blinks at ~5 Hz for the specified duration when identify message received\n- Blink stops automatically when duration_ms expires","status":"closed","priority":2,"issue_type":"task","assignee":"golf","created_at":"2026-04-09T10:58:29.697004135Z","created_by":"coding","updated_at":"2026-04-09T11:02:15.832414111Z","closed_at":"2026-04-09T11:02:15.832335990Z","close_reason":"done","source_repo":".","compaction_level":0,"original_size":0,"labels":["mitosis-child","mitosis-depth:1","parent-spaxel-lve"]} {"id":"spaxel-qpi","title":"Add sleep quality monitoring","description":"Implement overnight sleep analysis and reporting.\n\nDeliverables:\n- Breathing analysis during sleep hours\n- Motion scoring integration\n- Morning summary generation\n\nAcceptance: System generates daily sleep quality reports with breathing and motion metrics.","status":"closed","priority":2,"issue_type":"task","assignee":"sp4","created_at":"2026-03-29T19:25:04.113915797Z","created_by":"coding","updated_at":"2026-03-29T21:49:08.422771059Z","closed_at":"2026-03-29T21:49:08.422704623Z","close_reason":"Implemented overnight sleep quality monitoring with breathing analysis, motion scoring, and morning summary generation. System generates daily sleep reports with quality scores (0-100) based on breathing (40%), motion (30%), and continuity (30%) metrics. Added REST API at /api/sleep/* for status and reports.","source_repo":".","compaction_level":0,"original_size":0,"labels":["deferred","mitosis-child","mitosis-depth:1","parent-spaxel-i28"]} diff --git a/.needle-predispatch-sha b/.needle-predispatch-sha index f30ed56..fefc99a 100644 --- a/.needle-predispatch-sha +++ b/.needle-predispatch-sha @@ -1 +1 @@ -b583990d434dd472d8bac8cfb60f3129ff93e56a +5803bb790a995dc1ab91e8185a8bb5b08eb3faf7 diff --git a/dashboard/index.html b/dashboard/index.html index a298ba8..ee66e0f 100644 --- a/dashboard/index.html +++ b/dashboard/index.html @@ -1490,6 +1490,126 @@ #room-editor-btn:hover { background: rgba(255,255,255,0.12); color: #ccc; } #room-editor-btn.active { background: rgba(79,195,247,0.2); color: #4fc3f7; border-color: #4fc3f7; } + /* Add Portal button in status bar */ + #add-portal-btn { + background: rgba(255, 167, 38, 0.15); + border: 1px solid rgba(255, 167, 38, 0.4); + color: #ffa726; + font-size: 12px; + padding: 3px 10px; + border-radius: 4px; + cursor: pointer; + transition: background 0.2s, color 0.2s; + } + + #add-portal-btn:hover { + background: rgba(255, 167, 38, 0.25); + } + + /* Portal editor button */ + #portal-editor-btn { + background: rgba(255,255,255,0.06); + border: 1px solid rgba(255,255,255,0.12); + color: #888; + font-size: 12px; + padding: 3px 10px; + border-radius: 4px; + cursor: pointer; + transition: background 0.2s, color 0.2s; + } + #portal-editor-btn:hover { background: rgba(255,255,255,0.12); color: #ccc; } + #portal-editor-btn.active { background: rgba(255,167,38,0.2); color: #ffa726; border-color: #ffa726; } + + /* Portal editor panel */ + #portal-editor-panel { + position: fixed; + top: 60px; + left: 580px; + width: 240px; + background: rgba(0, 0, 0, 0.85); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 8px; + padding: 16px; + z-index: 100; + display: none; + backdrop-filter: blur(10px); + } + + #portal-editor-panel h3 { + font-size: 14px; + color: #ffa726; + text-transform: uppercase; + letter-spacing: 1px; + margin-bottom: 12px; + } + + #portal-editor-panel .room-field { + margin-bottom: 12px; + } + + #portal-editor-panel .room-field label { + display: block; + font-size: 11px; + color: #888; + margin-bottom: 4px; + } + + #portal-editor-panel .room-field input, + #portal-editor-panel .room-field select { + width: 100%; + background: rgba(255, 255, 255, 0.05); + border: 1px solid rgba(255, 255, 255, 0.1); + color: #fff; + padding: 6px 8px; + border-radius: 4px; + font-size: 12px; + box-sizing: border-box; + } + + #portal-editor-panel .room-field input:focus, + #portal-editor-panel .room-field select:focus { + outline: none; + border-color: rgba(255, 167, 38, 0.5); + } + + #portal-editor-panel .portal-actions { + display: flex; + gap: 8px; + margin-top: 16px; + } + + #portal-editor-panel .portal-actions button { + flex: 1; + background: rgba(79, 195, 247, 0.15); + border: 1px solid rgba(79, 195, 247, 0.4); + color: #4fc3f7; + padding: 6px 12px; + border-radius: 4px; + cursor: pointer; + font-size: 11px; + transition: background 0.2s; + } + + #portal-editor-panel .portal-actions button:hover { + background: rgba(79, 195, 247, 0.25); + } + + #portal-editor-panel .portal-delete-btn { + background: rgba(239, 83, 80, 0.15); + border-color: rgba(239, 83, 80, 0.4); + color: #ef5350; + } + + #portal-editor-panel .portal-delete-btn:hover { + background: rgba(239, 83, 80, 0.25); + } + + #portal-editor-panel .portal-position-info { + font-size: 11px; + color: #888; + margin-bottom: 8px; + } + /* Simulator button */ #simulator-btn { background: rgba(255,255,255,0.06); @@ -2868,7 +2988,11 @@ + + + + @@ -2961,6 +3085,10 @@ + + + + @@ -3049,6 +3177,94 @@ + + + + + +