Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

run CI and releases on Node 24 (matching .nvmrc) and remove the stale GSD .planning workspace

[._.]/ Adam Eivy5a27bd0762e0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a9b07e6c9f..b6e55ae477 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,3 +1,7 @@
+## CI
+
+- **CI and release workflows now run Node 24.x** (matching `.nvmrc`, which has pinned 24 while the workflows still ran 20.x). Also removed the stale v1.14-era GSD planning workspace (`.planning/`, `.plan-questions.md`) from the repo root — the milestone it tracked shipped in February and GSD is no longer in use for PortOS itself (the GSD feature for managed apps is unaffected; it simply no longer lists PortOS).
+
## Documentation
- **Full documentation audit — accuracy, organization, and a master index.** Six parallel audits verified every doc against the current code and the drift is now fixed. Highlights: `docs/API.md` corrected (the four `/api/agents/*` sections and the scaffold/templates section had wrong base paths, the stale CoS scheduled-scripts section is replaced by the real `/cos/jobs` surface, dead Socket.IO events — `detect:stream`, `errors:subscribe`, `cos:status`/`cos:log`/`script:*`/`cos:memory:*` — replaced with the real ones, and a complete route-domain index of every mounted `/api/*` prefix added, pointing at the OpenAPI spec on `/api-access`); the PostgreSQL-primary reality (June ADR) now reflected everywhere it was missing (`README.md` tech stack + contributing notes, `GOALS.md` non-goals, `docs/ARCHITECTURE.md` diagram/storage tier, `docs/CONTRIBUTING.md` prerequisites, `docs/TROUBLESHOOTING.md` database section, `docs/features/memory-system.md` storage story); `docs/DEPS.md` tables resynced to the real dependency lists (`sax` removed via #1824, `portos-ai-toolkit` vendored in-tree, `googleapis` → scoped `@googleapis/*`, missing `pdf-lib`/`sharp`/`undici` + client test deps + full override-pin list added); `docs/GITHUB_ACTIONS.md` now describes the actual CI jobs (Postgres service container, `test:ci`/`test:db:ci`, client tests, smoke boot, client lint); stale service/page paths fixed across the feature docs (`digital-twin.js`, `promptService.js`, `PromptManager.jsx`, `/api/detect/port`, JIRA sprint manager's move to the Schedule system, unbuilt M35 Phase-5 services marked "(not built)", shipped-status notes on the OpenClaw spec/audit); `ecosystem.config.cjs` docs (`docs/PM2.md`, `docs/PORTS.md`, `docs/ARCHITECTURE.md`) updated to the top-level `PORTS` convention and the real `portos-ui` process name. Organization: new `docs/README.md` master index (linked from the root README), convention READMEs for `docs/decisions/`, `docs/research/`, and `docs/superpowers/`, the brain build-plan artifacts moved from `docs/features/brain/` to `docs/plans/`, the undated research review date-prefixed, and `docs/SECURITY_AUDIT.md` labeled as the historical 2026-02 snapshot it is (title year typo fixed). README also gained the missing feature bullets (Music Studio, Music Video, Mood Boards, Catalog, Tribe, Morse/CW trainer) and the previously unlinked docs (`DEPS.md`, `GOALS_OPERATIONAL.md`, `claude-ollama.md`).
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ff217107d3..8d85224f36 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -17,7 +17,7 @@ jobs:
strategy:
matrix:
- node-version: [20.x]
+ node-version: [24.x]
# Postgres (with pgvector) for the DB-backed adapter suites. The image ships
# the `vector` extension that init-db.sql requires. The default `portos` DB
@@ -93,10 +93,10 @@ jobs:
steps:
- uses: actions/checkout@v7
- - name: Use Node.js 20.x
+ - name: Use Node.js 24.x
uses: actions/setup-node@v6
with:
- node-version: 20.x
+ node-version: 24.x
cache: 'npm'
- name: Install root dependencies
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 3a228fa511..698d3764db 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -19,10 +19,10 @@ jobs:
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
- - name: Use Node.js 20.x
+ - name: Use Node.js 24.x
uses: actions/setup-node@v6
with:
- node-version: 20.x
+ node-version: 24.x
- name: Configure git
run: |
diff --git a/.plan-questions.md b/.plan-questions.md
deleted file mode 100644
index cb80dc7292..0000000000
--- a/.plan-questions.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# Plan Question: Orphan peer subscriptions vs provider fallback scope
-
-## PLAN.md Item
-- [ ] [prune-orphan-subscriptions-for-deleted-records] **Sweep orphaned peer subscriptions left by tombstone prune.** `pruneTombstonedUniverses` / `pruneTombstonedSeries` rm the record dir but leave its rows in `data/peer_subscriptions.json`. After the 2026-05-23 leaked-fixture cleanup (22 universes force-pruned), the matching subs are now orphaned — on `peer:online`, `retryPendingPushesForPeer` walks them, `loadOne` returns null, and the push no-ops (harmless but inflates the "retrying N pending pushes" count — saw 141). Add an orphan-subscription sweep (drop subs whose `recordKind/recordId` no longer resolves to an on-disk record) to the tombstone GC path, or call it from the prune helpers. Low urgency; cosmetic + minor wasted work per sync cycle. Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22). When a stuck provider has N simultaneous in-flight calls, each failure independently runs `pickFallbackProvider` → `getAllProviders()` → `loadProviders()` (which reads `providers.json` from disk every time — no in-memory cache) → `markUnavailable` (writing `provider-status.json`). Two fixes that compound: (a) add a tiny TTL cache (~1s) to `aiToolkit/providers.js#loadProviders` so the read cost is amortized; (b) coalesce per-provider failure handling in `promptRunner.js` with a `Map<providerId, Promise>` so subsequent failures for the same provider await the first's mark-and-pick result and skip the duplicate work. Together they cut N-way failure storms to one disk-write + one mark. Acceptance: under a simulated 10-concurrent-failure load, providers.json is read at most twice and provider-status.json is written once.
-
-## Questions
-- Should `[prune-orphan-subscriptions-for-deleted-records]` cover only the peer-subscription sweep, with the AI provider fallback load-cache/coalescing work split into a separate PLAN.md slug?
-- If both concerns are intentionally bundled, what acceptance criteria should govern the orphan-subscription sweep, and should the provider 10-concurrent-failure acceptance remain part of this slug?
diff --git a/.planning/MILESTONES.md b/.planning/MILESTONES.md
deleted file mode 100644
index 2b5a028447..0000000000
--- a/.planning/MILESTONES.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Milestones
-
-## v1.14 Next Actions Batch (Shipped: 2026-02-27)
-
-**Phases:** 5 | **Plans:** 10 | **Commits:** 52
-**Files changed:** 92 | **Insertions:** +13,388
-**Timeline:** 2026-02-26 (single day)
-
-**Key accomplishments:**
-1. Genome migration cleanup — fixed stale digital-twin references, updated service paths, route comments, and IdentityTab navigation
-2. Data backup & recovery — incremental rsync to external drive with SHA-256 integrity, scheduled/manual triggers, dashboard widget with restore UI
-3. Apple Health integration — JSON ingest with dedup, SAX streaming XML import (500MB+ without OOM), WebSocket progress, MeatSpace health cards with correlation charts
-4. Cross-domain insights engine — genome-to-health correlations using 117 curated markers, LLM taste-to-identity theme analysis, insights dashboard with confidence levels and narrative summaries
-5. Unified search (Cmd+K) — server-side fan-out across 5 data sources, Spotlight-style overlay with keyboard navigation, grouped results with highlighted snippets and deep-link navigation
-
-**Requirements:** 24/24 v1 requirements shipped (GEN-01-03, BAK-01-07, HLT-01-06, INS-01-04, SRC-01-04)
-
-**Archive:** `.planning/milestones/v1.14-ROADMAP.md`, `.planning/milestones/v1.14-REQUIREMENTS.md`
-
----
diff --git a/.planning/PROJECT.md b/.planning/PROJECT.md
deleted file mode 100644
index 17df572103..0000000000
--- a/.planning/PROJECT.md
+++ /dev/null
@@ -1,85 +0,0 @@
-# PortOS
-
-## What This Is
-
-PortOS is a self-hosted personal operating system that centralizes app management, AI agent orchestration, knowledge capture, digital identity modeling, and health tracking into a single dashboard — accessible anywhere via Tailscale VPN. With v1.14, genome data informs health insights, all data is backed up and restorable, Apple Health metrics are integrated, cross-domain patterns surface automatically, and any piece of information is one keystroke away via Cmd+K search.
-
-## Core Value
-
-A connected, protected, and searchable personal OS — where data flows between domains (genome, health, identity, taste) to surface insights, everything is backed up, and universal search makes any piece of information one keystroke away.
-
-## Requirements
-
-### Validated
-
-- ✓ Centralized app lifecycle management (PM2, logs, JIRA) — M0-M4
-- ✓ Multi-provider AI orchestration with CoS agent system — M5, M14, M19, M35
-- ✓ Brain capture and semantic memory with LLM classification — M16, M31, M32
-- ✓ Digital twin identity modeling (soul, personality, taste, autobiography) — M33, M34, M42 P1-P4
-- ✓ Developer toolkit (shell, git, browser, history, CyberCity) — M6, M10, M36, M41
-- ✓ Self-improving intelligence (task learning, autonomous jobs) — M23-M27, M37
-- ✓ Agent tools and platform support (Moltbook, Moltworld) — M38, M43
-- ✓ MeatSpace health tracking (death clock, LEV, alcohol, blood, body, epigenetic, eye, genome, lifestyle) — M44 P1-P5
-- ✓ Tailscale anywhere access with mobile-responsive UI — existing
-- ✓ Genome migration cleanup — fix stale digital-twin references — v1.14
-- ✓ Data backup & recovery — scheduled incremental rsync with integrity verification and restore — v1.14
-- ✓ Apple Health integration — JSON ingest, SAX XML import, health metric cards and correlations — v1.14
-- ✓ Cross-domain insights — genome-to-health correlations, taste-to-identity themes, LLM narratives — v1.14
-- ✓ Unified search (Cmd+K) — server fan-out, Spotlight-style overlay, keyboard navigation, deep linking — v1.14
-
-### Active
-
-(None — next milestone requirements TBD via `/gsd:new-milestone`)
-
-### Out of Scope
-
-- Semantic/vector search in Cmd+K — keyword-first for v1, semantic layers on later via existing BM25+vector infra
-- Cloud backup targets — local external drive only, NAS/rsync can be added later
-- Apple Health live sync setup — endpoint built, app not yet purchased
-- Multi-modal identity capture (voice, video) — future tier
-- Push notifications (M47) — deferred to next batch
-- Dashboard customization / workspace contexts — Tier 4, later
-- Content Calendar — Tier 2, later
-
-## Context
-
-PortOS has 44+ completed milestones with a mature Express.js + React + PM2 architecture. All data persists to JSON files in `./data/`. v1.14 shipped 5 phases (10 plans, 24 requirements) transforming siloed features into a connected system. The codebase is ~79K server LOC + ~55K client LOC (JavaScript/JSX).
-
-**Shipped in v1.14:**
-- Genome data reads from correct meatspace paths
-- Incremental rsync backup with SHA-256 manifest, scheduler, dashboard widget, snapshot restore
-- Apple Health JSON ingest with dedup + SAX XML import (500MB+ streaming) + health cards with correlation charts
-- Cross-domain insights engine with 117 curated genome markers, LLM theme analysis, confidence levels
-- Cmd+K unified search across Brain, Memory, Apps, History, Health with grouped results and deep linking
-
-**Infrastructure available for next milestone:**
-- Vector + BM25 hybrid search in memory system
-- Socket.IO real-time updates
-- Zod validation on all routes
-- PM2 ecosystem managing 5+ processes
-- `portos-ai-toolkit` for AI provider management
-- Fan-out search architecture (easily extensible to new sources)
-
-## Constraints
-
-- **Tech stack**: Express.js backend, React/Vite frontend, JSON file persistence — no databases
-- **Single user**: No auth, no multi-tenancy, private Tailscale network
-- **Ports**: 5554-5560 allocated, define new ports in `ecosystem.config.cjs`
-- **No hardcoded localhost**: Use `window.location.hostname` for all URLs
-- **Backup target**: Local external drive (mounted path)
-
-## Key Decisions
-
-| Decision | Rationale | Outcome |
-|----------|-----------|---------|
-| Keyword-first search for M46 | Ship faster, semantic search can layer on later via existing vector infra | ✓ Good — shipped in one session, keyword covers 90% of use cases |
-| Local external drive for backup | Simplest reliable target, NAS/rsync can be added later | ✓ Good — works reliably, rsync incremental is fast |
-| Genome→Health and Taste→Identity as priority insights | User's most-wanted cross-domain correlations | ✓ Good — 117 curated markers + LLM themes provide actionable insights |
-| Build Apple Health endpoint before purchasing app | Endpoint + sample data testing first, real device later | ✓ Good — full pipeline tested with sample data |
-| SAX streaming for Apple Health XML | 500MB+ files would OOM with DOM parsing | ✓ Good — processes large exports with constant memory |
-| Portal rendering for Cmd+K overlay | z-index isolation above sidebar | ✓ Good — no stacking context issues |
-| Promise.allSettled for search fan-out | Individual source failures shouldn't break entire search | ✓ Good — graceful degradation |
-| Day-partitioned JSON for health data | Aligns with Health Auto Export's daily cadence, fast date-range queries | ✓ Good — simple, performant |
-
----
-*Last updated: 2026-02-27 after v1.14 milestone*
diff --git a/.planning/RETROSPECTIVE.md b/.planning/RETROSPECTIVE.md
deleted file mode 100644
index 2a2f5c4651..0000000000
--- a/.planning/RETROSPECTIVE.md
+++ /dev/null
@@ -1,70 +0,0 @@
-# Project Retrospective
-
-*A living document updated after each milestone. Lessons feed forward into future planning.*
-
-## Milestone: v1.14 — Next Actions Batch
-
-**Shipped:** 2026-02-27
-**Phases:** 5 | **Plans:** 10 | **Sessions:** ~5
-
-### What Was Built
-- Genome migration cleanup (stale digital-twin references fixed)
-- Data backup & recovery (rsync, SHA-256 manifest, scheduler, dashboard widget, restore UI)
-- Apple Health integration (JSON ingest + SAX XML import + health cards + correlation charts)
-- Cross-domain insights engine (genome-health correlations, taste-identity themes, LLM narratives)
-- Unified search Cmd+K (server fan-out, Spotlight overlay, keyboard nav, deep linking)
-
-### What Worked
-- Wave-based plan execution with parallel agents completed 10 plans in ~1.5 hours
-- Research phase prevented zero-dependency additions — all 5 phases used existing libraries only
-- Fan-out architecture (Promise.allSettled) made search gracefully degradable from day one
-- Day-partitioned JSON storage for health data aligned naturally with Apple Health export cadence
-- CONTEXT.md from discuss-phase locked decisions early — no mid-execution design debates
-- SAX streaming decision (from research) prevented OOM on 500MB+ Apple Health XML files
-
-### What Was Inefficient
-- Some ROADMAP.md plan checkboxes fell out of sync during multi-phase execution (manual fix needed)
-- Verification checkpoint for Phase 5 partially duplicated the Phase 5 verifier output
-- Research agent sometimes explored files already well-documented in CLAUDE.md
-- GSD milestone versioning defaulted to "v1.0" instead of reading package.json version — required manual fix
-
-### Patterns Established
-- Portal rendering for overlays (z-index isolation above sidebar) — CmdKSearch sets the pattern
-- Correlation text summaries via pure data math (no LLM) for zero-latency deterministic display
-- "Evidence" and "Risk Marker" language for genome correlations — never causation claims
-- 14-day minimum data threshold before showing correlation insights
-- multer diskStorage (not memoryStorage) for large file uploads
-- Raw fetch() instead of request() helper when Content-Type needs to be multipart/form-data
-
-### Key Lessons
-1. Day-partitioned JSON files are a strong pattern for time-series data when the query pattern is date-range-based
-2. Promise.allSettled is the right default for fan-out queries where partial results are acceptable
-3. SAX streaming should be the default for any user-uploaded XML/JSON over 10MB
-4. CONTEXT.md (from discuss-phase) is the highest-leverage step — it prevents 80% of mid-execution pivots
-5. GSD milestone labels should match the project's actual semver (from package.json), not arbitrary "v1.0" labels
-
-### Cost Observations
-- Model mix: ~30% opus (orchestration, user interaction), ~70% sonnet (research, execution, verification)
-- Sessions: ~5 (discuss + plan + execute per phase, some combined)
-- Notable: Single-day milestone execution — all 5 phases shipped 2026-02-26
-
----
-
-## Cross-Milestone Trends
-
-### Process Evolution
-
-| Milestone | Sessions | Phases | Key Change |
-|-----------|----------|--------|------------|
-| v1.14 | ~5 | 5 | First GSD milestone — established wave execution, discuss-phase context, fan-out patterns |
-
-### Cumulative Quality
-
-| Milestone | Tests | Coverage | Zero-Dep Additions |
-|-----------|-------|----------|-------------------|
-| v1.14 | existing | — | 5/5 phases (zero new npm dependencies) |
-
-### Top Lessons (Verified Across Milestones)
-
-1. Research before planning prevents unnecessary dependency additions
-2. CONTEXT.md locks design decisions — downstream agents execute without asking the user
diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md
deleted file mode 100644
index 069e66d55e..0000000000
--- a/.planning/ROADMAP.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# Roadmap: PortOS
-
-## Milestones
-
-- **v1.14 Next Actions Batch** — Phases 1-5 (shipped 2026-02-27) | [Archive](milestones/v1.14-ROADMAP.md)
-
-## Progress
-
-| Phase | Milestone | Plans Complete | Status | Completed |
-|-------|-----------|----------------|--------|-----------|
-| 1. Genome Migration Cleanup | v1.14 | 1/1 | Complete | 2026-02-26 |
-| 2. Data Backup & Recovery | v1.14 | 2/2 | Complete | 2026-02-26 |
-| 3. Apple Health Integration | v1.14 | 3/3 | Complete | 2026-02-26 |
-| 4. Cross-Domain Insights Engine | v1.14 | 2/2 | Complete | 2026-02-26 |
-| 5. Unified Search (Cmd+K) | v1.14 | 2/2 | Complete | 2026-02-26 |
diff --git a/.planning/STATE.md b/.planning/STATE.md
deleted file mode 100644
index 2824d551e8..0000000000
--- a/.planning/STATE.md
+++ /dev/null
@@ -1,66 +0,0 @@
----
-gsd_state_version: 1.0
-milestone: null
-milestone_name: null
-status: milestone_complete
-last_updated: "2026-02-27"
-progress:
- total_phases: 5
- completed_phases: 5
- total_plans: 10
- completed_plans: 10
----
-
-# Project State
-
-## Project Reference
-
-See: .planning/PROJECT.md (updated 2026-02-27)
-
-**Core value:** A connected, protected, and searchable personal OS
-**Current focus:** Planning next milestone
-
-## Current Position
-
-Milestone v1.14 Next Actions Batch — SHIPPED 2026-02-27
-All 5 phases, 10 plans, 24 requirements complete.
-
-Next step: `/gsd:new-milestone` to define next milestone scope
-
-## Performance Metrics
-
-**v1.14 Velocity:**
-- Total plans: 10
-- Average duration: ~7 min/plan
-- Total execution time: ~1.5 hours
-- Timeline: completed 2026-02-26 (single day)
-
-**By Phase:**
-
-| Phase | Plans | Avg/Plan |
-|-------|-------|----------|
-| 01-genome-migration-cleanup | 1 | 108s |
-| 02-data-backup-recovery | 2 | ~7min |
-| 03-apple-health-integration | 3 | ~6min |
-| 04-cross-domain-insights-engine | 2 | ~4min |
-| 05-unified-search | 2 | ~12min |
-
-## Accumulated Context
-
-### Decisions
-
-See PROJECT.md Key Decisions table for full history.
-
-### Pending Todos
-
-None.
-
-### Blockers/Concerns
-
-None.
-
-## Session Continuity
-
-Last session: 2026-02-27
-Stopped at: Milestone v1.14 archived
-Resume file: None
diff --git a/.planning/codebase/ARCHITECTURE.md b/.planning/codebase/ARCHITECTURE.md
deleted file mode 100644
index 50b9a13496..0000000000
--- a/.planning/codebase/ARCHITECTURE.md
+++ /dev/null
@@ -1,172 +0,0 @@
-# Architecture
-
-**Analysis Date:** 2026-02-26
-
-## Pattern Overview
-
-**Overall:** Monorepo with centralized Express.js backend serving multiple PM2-managed processes and a Vite/React frontend
-
-**Key Characteristics:**
-- Multi-process orchestration via PM2 (server, UI, CoS agent runner, autofixer, browser automation)
-- Layered backend (routes → services → lib utilities)
-- Validation-first approach with Zod schemas
-- Centralized error handling with Socket.IO event broadcasting
-- JSON file persistence in `/data/` directory
-- Functional React components with custom hooks for state management
-
-## Layers
-
-**Presentation (Client):**
-- Purpose: User interface for monitoring, controlling, and configuring PortOS and managed apps
-- Location: `client/src/`
-- Contains: React pages, reusable components, service clients, hooks, utilities
-- Depends on: HTTP API via `api.js`, WebSocket via `socket.js`
-- Used by: End users via Vite dev server (port 5554) or production build
-
-**API Layer (Routes):**
-- Purpose: HTTP request handlers that validate input and delegate to services
-- Location: `server/routes/`
-- Contains: Route handlers for apps, agents, CoS, brain, digital-twin, providers, etc.
-- Depends on: Services (business logic), lib/validation.js (Zod schemas)
-- Used by: Express app, consumed by client via HTTP
-
-**Business Logic (Services):**
-- Purpose: Core application logic, PM2 management, file I/O, event publishing
-- Location: `server/services/`
-- Contains: ~100+ service files managing apps, agents, CoS runner, brain, digital-twin, providers, etc.
-- Depends on: lib/ (validation, error handling, file utils), PM2, Socket.IO
-- Used by: Routes, other services, scheduled tasks
-
-**Validation & Utilities (Lib):**
-- Purpose: Shared schemas, error handling, file operations, platform detection
-- Location: `server/lib/`
-- Contains: Zod validation schemas, error handler, file utilities, vector math, task parsing
-- Depends on: Zod, fs/promises
-- Used by: Routes, services, Socket.IO validation
-
-**Data Persistence:**
-- Purpose: Store application state in JSON files
-- Location: `data/` directory (runtime), `data.reference/` (template)
-- Contains: apps.json, providers.json, runs/, prompts/, cos/, agents/, brain/, digital-twin/, meatspace/
-- Accessed by: Services via fileUtils and custom loaders
-
-**External Integration (portos-ai-toolkit):**
-- Purpose: AI provider management, run tracking, prompt templating
-- Location: External npm module at `../portos-ai-toolkit`
-- Contains: Provider drivers, CLI runner, hooks system
-- Integrated at: `server/index.js` creates toolkit instance, routes extend it
-
-**Process Management (PM2):**
-- Purpose: Orchestrate multi-process lifecycle
-- Location: `ecosystem.config.cjs` (configuration), `server/cos-runner/index.js` (isolated CoS runner)
-- Contains: Process definitions for server, UI, CoS runner, autofixer, browser service
-- Managed by: PM2 CLI, PortOS routes use pm2Service for control
-
-## Data Flow
-
-**Typical Request Flow:**
-
-1. Client initiates HTTP request via `services/api.js`
-2. Express route handler (`server/routes/*.js`) receives request
-3. Route validates input using Zod schema from `lib/validation.js`
-4. Route calls service(s) via `server/services/`
-5. Service executes business logic (file I/O, PM2 commands, external APIs)
-6. Route responds with JSON result or throws ServerError
-7. ErrorMiddleware catches errors, emits Socket.IO event, returns error response
-8. Client displays response or error toast notification
-
-**WebSocket Flow (Real-time Updates):**
-
-1. Client subscribes via socket event (e.g., `detect:start`, `logs:subscribe`)
-2. `services/socket.js` handles event with validation
-3. Socket handler spawns long-running operation (detection, streaming logs)
-4. Handler emits progress updates back via `socket.emit()`
-5. Service publishes state change events (e.g., `apps:changed`)
-6. All connected clients receive broadcast update
-
-**State Management:**
-- Server: JSON files + in-memory caches (e.g., `appsCache` in `services/apps.js`)
-- Client: React state via hooks + Socket.IO subscriptions + API fetches
-- Cache invalidation: File watchers, event emitters, TTL-based caching
-
-## Key Abstractions
-
-**App Registry:**
-- Purpose: Track managed applications (PortOS itself, user projects)
-- Examples: `server/services/apps.js`, routes/apps.js
-- Pattern: In-memory cache (2s TTL) backed by `data/apps.json`, EventEmitter for subscriptions
-
-**PM2 Service Layer:**
-- Purpose: Abstract PM2 CLI commands behind consistent interface
-- Examples: `server/services/pm2.js`, `pm2Standardizer.js`
-- Pattern: Spawn child processes, parse output, return typed results
-
-**Zod Validation:**
-- Purpose: Runtime schema validation at API boundary
-- Examples: `lib/validation.js`, `lib/digitalTwinValidation.js`, `lib/brainValidation.js`
-- Pattern: Define schemas once, validate in routes and Socket.IO handlers
-
-**Error Broadcasting:**
-- Purpose: Propagate server errors to all UI clients in real-time
-- Examples: `lib/errorHandler.js`, `services/autoFixer.js`
-- Pattern: ServerError with metadata → errorMiddleware → Socket.IO `error:occurred` event → Toast UI
-
-**AI Toolkit Integration:**
-- Purpose: Centralize AI provider configuration and execution tracking
-- Examples: `server/services/providers.js`, `runner.js`, routes/providers.js
-- Pattern: Import toolkit, extend routes, set hooks for PortOS lifecycle tracking
-
-## Entry Points
-
-**Server Initialization:**
-- Location: `server/index.js`
-- Triggers: `npm run dev` or `pm2 start ecosystem.config.cjs`
-- Responsibilities: Create Express app, initialize Socket.IO, load routes, set middleware, start HTTP server on port 5555
-
-**Client Initialization:**
-- Location: `client/src/main.jsx` → `App.jsx`
-- Triggers: Vite dev server (port 5554) or production build
-- Responsibilities: Set up React Router, initialize hooks, load Layout component with nested routes
-
-**PM2 CoS Runner Process:**
-- Location: `server/cos-runner/index.js`
-- Triggers: Spawned by PM2 (separate process, not watched)
-- Responsibilities: Run isolated Claude CLI agent instances, prevent orphaned processes
-
-**Autofixer Service:**
-- Location: `autofixer/server.js`
-- Triggers: PM2 spawned process (port 5559)
-- Responsibilities: Listen for error events, execute recovery scripts, report status
-
-## Error Handling
-
-**Strategy:** Catch errors at route level, emit Socket.IO events, let client display toast
-
-**Patterns:**
-- Routes use `asyncHandler` wrapper to catch Promise rejections
-- Services throw `ServerError` with status, code, context
-- `errorMiddleware` catches uncaught errors and emits via Socket.IO
-- Client hook `useErrorNotifications` subscribes to `error:occurred` events
-- Platform errors (PLATFORM_UNAVAILABLE) emit as warnings, not errors
-
-## Cross-Cutting Concerns
-
-**Logging:** Single-line format with emoji prefixes, string interpolation
-- Example: `console.log('🚀 Server started on port ${PORT}')`
-- Used in: All services and routes
-
-**Validation:** Zod schemas defined in `lib/validation.js` and domain-specific files
-- Routes call `validateRequest(schema, data, next)`
-- Socket.IO calls `validateSocketData(schema, rawData, socket, eventName)`
-
-**Authentication:** Not applicable (single-user, internal tool behind Tailscale VPN)
-
-**File I/O:** Centralized through `lib/fileUtils.js` with consistent PATHS constants
-- Services use `readJSONFile()`, `writeFile()`, `ensureDir()`
-
-**Process Management:** PM2 commands abstracted via `services/pm2.js`
-- All process lifecycle operations go through pm2Service
-
----
-
-*Architecture analysis: 2026-02-26*
diff --git a/.planning/codebase/CONCERNS.md b/.planning/codebase/CONCERNS.md
deleted file mode 100644
index 77f1dd3e26..0000000000
--- a/.planning/codebase/CONCERNS.md
+++ /dev/null
@@ -1,259 +0,0 @@
-# Codebase Concerns
-
-**Analysis Date:** 2026-02-26
-
-## Tech Debt
-
-**Large Service Files (>3000 LOC):**
-- Issue: Core services have grown monolithic with mixed responsibilities
-- Files: `server/services/cos.js` (3763 LOC), `server/services/subAgentSpawner.js` (3145 LOC), `server/services/digital-twin.js` (2823 LOC)
-- Impact: Harder to test, refactor, and reason about code flow; increased cognitive load for maintainers
-- Fix approach: Extract services into focused modules (e.g., agent indexing, state management, spawning logic into separate files); consider facade pattern to reduce coupling
-
-**Race Conditions in File State Management:**
-- Issue: Multiple services write to shared JSON state files without coordinated locking
-- Files: `server/services/cos.js`, `server/services/memory.js`, `server/services/taskSchedule.js`
-- Current mitigation: Mutex locks exist in `memory.js` (line 48: `createMutex()`) but not consistently applied to cos.js state mutations
-- Impact: Risk of corrupted state.json, index.json, or embeddings.json on concurrent writes; loss of agent metadata
-- Fix approach: Wrap all state mutations in `withLock()` in cos.js; implement atomic write-via-temp-file pattern consistently across all state files
-
-**Unprotected Atomic Write Operations:**
-- Issue: `writeFile` → `rename` sequences in `cos.js` (lines 429-430, 108-112) attempt atomicity but catch handlers swallow errors
-- Files: `server/services/cos.js` (lines 108-112: agent index save), `server/lib/fileUtils.js` (no fallback for atomic writes)
-- Impact: On rename failure, temp files accumulate in data/cos; corrupt writes if process crashes between writeFile and rename
-- Fix approach: Implement guaranteed atomic writes with rollback; add cleanup for orphaned temp files on startup; log critical failures
-
-**Missing Mutex in CoS State Mutations:**
-- Issue: CoS daemon writes state without mutex protection while sub-agents read/update agents
-- Files: `server/services/cos.js` (state writes at lines 429-430)
-- Impact: Sub-agent updates to agent metadata can collide with CoS state persistence; lost updates
-- Fix approach: Create dedicated state manager with `withLock()` wrapper for all state.json mutations
-
-## Known Bugs
-
-**Agent Index Migration Incomplete:**
-- Symptoms: Agents created before date-bucket migration may not be found on subsequent runs
-- Files: `server/services/cos.js` (lines 96-98, 160-228)
-- Trigger: Migration runs once on first access to `loadAgentIndex()`; if migration fails silently, old flat agents are orphaned
-- Workaround: Manually move agent directories from `data/cos/agents/` to `data/cos/agents/YYYY-MM-DD/` buckets
-- Fix approach: Add recovery log for failed migrations; implement rollback mechanism; add startup validation
-
-**Challenge Solver AI Timeout Vulnerability:**
-- Symptoms: Moltbook posts get stuck in "verification_required" state indefinitely
-- Files: `server/integrations/moltbook/challengeSolver.js` (lines 52-84)
-- Trigger: AI provider timeout (specified as `provider.timeout || 300000` = 5min) exceeds verification window (Moltbook requires answer within ~5 minutes)
-- Impact: Post never publishes; no retry mechanism; user must manually re-attempt
-- Workaround: Lower challenge solving timeout or ensure LM Studio is responsive
-- Fix approach: Add exponential backoff with per-attempt timeout reduction; implement verification retry with new challenge; cache solved challenges
-
-**Memory Embeddings Out-of-Sync:**
-- Symptoms: Memory search returns low-quality results; embeddings vector dimension mismatches
-- Files: `server/services/memory.js` (lines 88-95), `server/services/memoryEmbeddings.js`
-- Trigger: Provider changed without regenerating all embeddings; embedding config updated mid-operation
-- Impact: New memories use correct dimension, old ones don't; BM25 fallback masks the issue
-- Fix approach: Add migration tool to regenerate embeddings on provider change; validate dimension consistency on load; batch re-embed on startup
-
-**Moltbook API Verification State Not Persisted:**
-- Symptoms: Successfully verified posts lose verification state on restart
-- Files: `server/integrations/moltbook/api.js` (line 59: `data.verification_solved = true`)
-- Trigger: State held in-memory only; not written to persistent queue file
-- Impact: Post verification succeeds but isn't recorded; re-attempts verification on next run
-- Fix approach: Persist verification_solved flag in post queue; check flag before re-verifying
-
-## Security Considerations
-
-**Challenge Solver AI Injection Risk:**
-- Risk: User-controlled task descriptions flow into LLM prompt for challenge solving
-- Files: `server/integrations/moltbook/challengeSolver.js` (lines 35-40)
-- Current mitigation: None; prompt is user-controlled via task.metadata.context
-- Recommendations: Sanitize challenge text before passing to LLM; add prompt injection detection; use structured format (JSON) instead of free-form text
-
-**Command Security Allowlist Not Enforced in All Paths:**
-- Risk: Some services may bypass `server/lib/commandSecurity.js` validation
-- Files: `server/lib/commandSecurity.js`, various services executing shell commands
-- Current mitigation: Primary routes validated; integrations (Moltbook/world APIs) may spawn processes without checks
-- Recommendations: Audit all `exec`, `execFile`, `spawn` calls; centralize command execution with mandatory allowlist check
-
-**Plaintext Credential Storage in Provider Configuration:**
-- Risk: API keys, tokens, and credentials stored in `data/providers.json` as plaintext
-- Files: `server/data/providers.json`
-- Current mitigation: File permissions (644 by default); deployed behind Tailscale but accessible if machine compromised
-- Recommendations: Implement encryption-at-rest for sensitive provider fields; use environment variables for critical credentials; rotate provider secrets regularly
-
-**WebSocket Events Broadcast Without Sanitization on All Paths:**
-- Risk: Error context emitted via Socket.IO may contain sensitive data
-- Files: `server/lib/errorHandler.js` (lines 110-130 implements sanitization)
-- Current mitigation: Context sanitization exists in errorHandler
-- Recommendations: Audit all `cosEvents.emit()` and `io.emit()` calls to ensure no PII/credentials escape; add audit logging for security-relevant events
-
-## Performance Bottlenecks
-
-**Agent Index Loaded Into Memory:**
-- Problem: Agent index (Map of agentId → date-bucket) requires full file read/parse on each access
-- Files: `server/services/cos.js` (lines 83-100)
-- Cause: Lazy-load pattern reads entire INDEX_FILE on first access; no caching invalidation on new agents
-- Current state: Index is ~50KB (described as avoiding 16MB full cache), cached in-memory after load
-- Improvement path: Use persistent cache with file-watch invalidation; consider LRU cache for large deployments; implement background index updates
-
-**Memory Search with Dual-Path Fallback:**
-- Problem: Every memory search tries vector embedding first, then falls back to BM25 if embeddings unavailable
-- Files: `server/services/memory.js` (multiple search functions with fallback logic)
-- Cause: Embedding provider availability is external dependency; BM25 adds latency
-- Improvement path: Cache search index to disk; pre-compute BM25 on memory upsert; parallelize embedding availability check
-
-**CoS State Loaded Synchronously on Every Daemon Cycle:**
-- Problem: Full state.json read on each task cycle without incremental updates
-- Files: `server/services/cos.js` (state loading in main loop)
-- Cause: No state subscription/change tracking; daemon re-reads full file repeatedly
-- Improvement path: Implement state change stream; use file watch or atomic updates-only; consider in-memory state with periodic flush
-
-**History File Grows Unbounded:**
-- Problem: `data/history.json` accumulates all-time execution history
-- Files: Various services append to history without truncation
-- Current state: Unknown size; no pruning mechanism observed
-- Improvement path: Implement rolling window (keep last N entries or last 30 days); archive old history; use JSONL with streaming reads
-
-**DevTools Page Re-renders All Components on State Change:**
-- Problem: Large tabbed interface in DevTools.jsx (2758 LOC) may cause full re-renders
-- Files: `client/src/pages/DevTools.jsx`
-- Cause: Centralized state management; no component-level memoization observed
-- Improvement path: Split tabs into separate components; implement React.memo; use context selectors; lazy-load inactive tabs
-
-## Fragile Areas
-
-**SubAgent Spawner Task Classification:**
-- Files: `server/services/subAgentSpawner.js` (lines 49-62: extractTaskTypeKey, 72-112: detectSkillTemplate)
-- Why fragile: Task type detection relies on string matching in description; brittle pattern matching for skill templates (e.g., "[self-improvement]" marker must be exact)
-- Safe modification: Add regression tests for new task types before changing matchers; implement fuzzy matching for skill detection; add logging for unmatched tasks
-- Test coverage: `subAgentSpawner.test.js` exists; coverage gaps on skill detection and edge cases
-
-**Moltbook Integration Rate Limiting:**
-- Files: `server/integrations/moltbook/rateLimits.js`, `server/integrations/moltbook/api.js`
-- Why fragile: External rate limits (unknown specs for Moltbook API) not enforced; API responses may contain throttle headers not currently parsed
-- Safe modification: Add response header parsing for `Retry-After`, `X-RateLimit-*`; log actual rate limit responses; implement adaptive backoff
-- Test coverage: No tests for rate limit edge cases
-
-**Task Watcher File Monitoring:**
-- Files: `server/services/taskWatcher.js`
-- Why fragile: Depends on reliable file system watch events; TASKS.md changes may be missed if fs.watch is unreliable on the system
-- Safe modification: Add poll-based fallback; implement CRC hash validation; test on target OS
-- Test coverage: Unknown; watch behavior is notoriously platform-dependent
-
-**Provider Status Fallback Chain:**
-- Files: `server/services/providerStatus.js` (line 20: defaultFallbackPriority)
-- Why fragile: Hard-coded fallback list may not match available providers; if all providers in chain fail, no fallback defined
-- Safe modification: Generate fallback chain dynamically based on available providers; add sentinel provider (console-based); test with single provider available
-- Test coverage: No tests for fallback chain exhaustion
-
-## Scaling Limits
-
-**Single State Machine for All Agent Executions:**
-- Current capacity: Unknown; depends on PM2 process limits and concurrent CoS runner instances
-- Limit: Event-driven architecture may bottleneck if many agents spawn simultaneously
-- Scaling path: Implement execution lanes/queues with configurable concurrency; separate spawner process; use work queue (Redis-like) for agent scheduling
-
-**Date-Bucket Directory Structure for Agents:**
-- Current capacity: One directory per day; subdirectories per agent
-- Limit: File system readdir() scales linearly with directory size; millions of agents across months will be slow
-- Scaling path: Implement multi-level bucketing (YYYY/MM/DD or by agent hash); consider flat file database (SQLite) for agent metadata
-
-**In-Memory Index for All Memories:**
-- Current capacity: Unknown; embeddings cache can grow to MB for large memory databases
-- Limit: 10,000 max memories configured; embeddings vector (768 dimension) = ~3KB per memory ≈ 30MB max
-- Scaling path: Implement lazy-loading per category; use disk-backed vector DB (Milvus, Qdrant); implement memory consolidation/pruning
-
-**WebSocket Event Broadcasting to All Clients:**
-- Current capacity: Unknown; `io.emit()` broadcasts to all connected clients
-- Limit: Many clients + large log events = saturated network
-- Scaling path: Implement rooms/namespaces per dashboard view; filter events client-side; add event sampling for high-frequency logs
-
-## Dependencies at Risk
-
-**portos-ai-toolkit ^0.5.0:**
-- Risk: Non-breaking version; if toolkit API changes (e.g., provider field structure), PortOS may break without major version bump
-- Impact: Provider configuration could become incompatible; sub-agent spawning could fail if toolkit's model selection changes
-- Migration plan: Pin to specific version (0.5.0) until ready to test 0.6.x; implement compatibility layer for provider config; test with toolkit updates before deploying
-
-**PM2 ^5.4.3:**
-- Risk: Node-based process manager; process spawning reliability depends on PM2 internals; ECMAScript module support was recently added
-- Impact: If PM2 has bugs with ESM modules, app lifecycle management breaks; agent processes may not restart correctly
-- Migration plan: Monitor PM2 changelog; test process recovery scenarios regularly; have fallback (systemd/Docker) ready
-
-**Node-PTY ^1.2.0-beta.10:**
-- Risk: Beta version with ongoing development; PTY handling is low-level and platform-specific
-- Impact: Shell command execution may fail or hang; character encoding issues in CLI output; terminal resize events may be lost
-- Migration plan: Monitor for stable release; implement timeout/cancellation for PTY commands; test on target OS before updating
-
-**Zod ^3.24.1:**
-- Risk: While stable, no major concerns; however, validation schemas scattered across `server/lib/validation.js` and route files
-- Impact: Schema changes require updates in multiple places; potential inconsistency
-- Migration plan: Consider centralized schema registry; implement schema versioning
-
-## Missing Critical Features
-
-**No Persistent Queue for Failed Tasks:**
-- Problem: If CoS daemon crashes mid-task, in-progress agents may be lost or orphaned
-- Blocks: Reliable autonomous job execution; task recovery after outages
-- Fix approach: Implement persistent task queue (file-based or Redis); implement checkpoint/resume for agents; track agent lineage
-
-**No Data Validation on Load (JSON Files):**
-- Problem: Corrupted state.json, embeddings.json, or index.json can crash services
-- Blocks: Reliable startup after unclean shutdown
-- Fix approach: Implement Zod schema validation on all file loads; add recovery/rollback for corrupted files; implement backup rotation
-
-**No Audit Logging for Critical Operations:**
-- Problem: No record of who triggered what, when, or why (important for autonomous system)
-- Blocks: Debugging issues; security investigation; accountability
-- Fix approach: Implement audit log to `data/cos/audit.jsonl`; log all task creations, agent spawns, provider changes, memory mutations; implement retention policy
-
-**No Graceful Degradation for Missing Providers:**
-- Problem: If embedding provider (LM Studio) is offline, all memory operations hang or fail
-- Blocks: Resilience to infrastructure changes; usability during provider maintenance
-- Fix approach: Add provider health checks; implement memory-only mode without embeddings; queue embeddings until provider recovers
-
-**No Rate Limiting on Sub-Agent Spawning:**
-- Problem: Rapid task creation could spawn unbounded agents, exhausting system resources
-- Blocks: Resource safety; preventing runaway CoS daemon
-- Fix approach: Implement execution lanes with configurable limits; add task queue with backpressure; expose limits in settings
-
-## Test Coverage Gaps
-
-**Critical Services Without Tests:**
-- Files: `server/services/cos.js` (no dedicated test file; core daemon logic untested)
-- What's not tested: Daemon startup/shutdown cycles, state persistence, agent spawning coordination, error recovery
-- Risk: Daemon bugs can cause data loss or orphaned processes; hard to refactor safely
-- Priority: High
-
-**File System Operations Not Tested:**
-- Files: `server/services/cos.js`, `server/lib/fileUtils.js`
-- What's not tested: Atomic write failures, concurrent file access, corruption recovery, migration edge cases
-- Risk: State corruption under load or after crashes
-- Priority: High
-
-**External Integration Failures:**
-- Files: `server/integrations/moltbook/` and `server/integrations/moltworld/`
-- What's not tested: Rate limit exhaustion, network timeouts, malformed API responses, challenge solving edge cases
-- Risk: Silent failures in autonomous posting; posts get stuck in unknown states
-- Priority: Medium
-
-**Provider Fallback Chain:**
-- Files: `server/services/providerStatus.js`, `server/services/subAgentSpawner.js`
-- What's not tested: All providers in fallback chain unavailable, provider switching mid-execution, model availability edge cases
-- Risk: Sub-agents fail with unclear errors; no model available to escalate to
-- Priority: Medium
-
-**Memory Search Path with Embeddings Unavailable:**
-- Files: `server/services/memory.js`, `server/services/memoryBM25.js`
-- What's not tested: Embedding provider offline, partial embeddings available (some memories have vectors, some don't), vector dimension mismatch
-- Risk: Memory search returns inconsistent results or crashes
-- Priority: Medium
-
-**Client WebSocket Reconnection:**
-- Files: `client/src/services/socket.js`
-- What's not tested: Rapid reconnect/disconnect cycles, message loss during disconnection, stale state after reconnect
-- Risk: UI out of sync with server; lost notifications
-- Priority: Low
-
----
-
-*Concerns audit: 2026-02-26*
diff --git a/.planning/codebase/CONVENTIONS.md b/.planning/codebase/CONVENTIONS.md
deleted file mode 100644
index 23b12a5920..0000000000
--- a/.planning/codebase/CONVENTIONS.md
+++ /dev/null
@@ -1,249 +0,0 @@
-# Coding Conventions
-
-**Analysis Date:** 2026-02-26
-
-## Naming Patterns
-
-**Files:**
-- Kebab-case for all files: `apps.js`, `errorHandler.js`, `asyncMutex.js`
-- Test files: `{name}.test.js` or `{name}.spec.js` (e.g., `validation.test.js`, `apps.test.js`)
-- Integration tests: `{name}.integration.test.js` (e.g., `visionTest.integration.test.js`)
-- Route files grouped by domain: `routes/apps.js`, `routes/health.js`, `routes/cos.js`
-- Service files grouped by domain: `services/apps.js`, `services/pm2.js`, `services/history.js`
-- Library/utility files in `lib/`: `lib/validation.js`, `lib/errorHandler.js`, `lib/logger.js`
-- React components: PascalCase with `.jsx` extension: `Layout.jsx`, `Logo.jsx`, `NotificationDropdown.jsx`
-
-**Functions:**
-- camelCase for all functions: `asyncHandler`, `validateRequest`, `normalizeError`, `getAppById`, `createApp`
-- Prefix boolean functions with `is` or `has` where applicable: `existsSync`, `hasLength`
-- Event handlers prefixed with appropriate verb: `handleError`, `handleRecoveryRequested`, `handleCriticalError`
-
-**Variables:**
-- camelCase for all variables: `pm2Home`, `statusValues`, `overallStatus`, `mockApps`, `mockPm2Processes`
-- Constant-like data structures in camelCase (not SCREAMING_SNAKE_CASE): `PORTOS_APP_ID`, `APPS_FILE`, `DATA_DIR`, `API_BASE`
-- Private/internal variables can use underscore prefix: `_internal`
-- Event emitter instances: `appsEvents`, `errorEvents`, `cosEvents`
-
-**Types:**
-- Zod schemas use descriptive names ending with `Schema`: `appSchema`, `processSchema`, `providerSchema`, `agentPersonalitySchema`, `platformAccountSchema`
-- Partial update schemas use naming pattern: `{type}UpdateSchema` (e.g., `appUpdateSchema`)
-- Enum schemas follow pattern: `{type}TypeSchema` (e.g., `personalityStyleSchema`, `platformTypeSchema`)
-
-## Code Style
-
-**Formatting:**
-- No explicit ESLint or Prettier config found
-- ES Module syntax (`import`/`export`) required in all files (`"type": "module"` in package.json)
-- 2-space indentation (observed in codebase)
-- No semicolons suppressed (semicolons present throughout)
-
-**Linting:**
-- No ESLint configuration detected
-- Code relies on natural JavaScript conventions
-
-## Import Organization
-
-**Order:**
-1. Node.js built-in modules: `import { Router } from 'express'`, `import { spawn } from 'child_process'`, `import { EventEmitter } from 'events'`
-2. Third-party packages: `import express from 'express'`, `import { z } from 'zod'`, `import toast from 'react-hot-toast'`
-3. Local modules (relative imports): `import * as appsService from '../services/apps.js'`, `import { validateRequest } from '../lib/validation.js'`
-4. Local specific imports after wildcard imports
-
-**Path Aliases:**
-- No path aliases configured (uses relative paths: `../services/`, `../lib/`, `./components/`)
-- Server-side: Uses consistent relative path depth from routes/services to lib
-- Client-side: Uses relative imports from services, hooks, components directories
-
-## Error Handling
-
-**Patterns:**
-- No try/catch blocks (per CLAUDE.md conventions) — errors bubble to centralized middleware
-- Async route handlers wrapped with `asyncHandler()` middleware defined in `errorHandler.js`
-- `ServerError` class used for structured error creation with metadata
-- `normalizeError()` function converts any error type to `ServerError` for consistency
-- HTTP status codes map to error codes: `404 → NOT_FOUND`, `400 → BAD_REQUEST`, `422 → VALIDATION_ERROR`
-- Error context object attached to errors for additional debugging info: `{ context: { resource: 'user' } }`
-- Errors emit Socket.IO events for client notification (see `emitErrorEvent()`)
-- `PLATFORM_UNAVAILABLE` errors treated as warnings rather than critical errors
-
-Example from `server/routes/apps.js`:
-```javascript
-const loadApp = asyncHandler(async (req, res, next) => {
- const app = await appsService.getAppById(req.params.id);
- if (!app) {
- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
- }
- req.loadedApp = app;
- next();
-});
-```
-
-## Logging
-
-**Framework:** `console` (no external logging library)
-
-**Patterns:**
-- Single-line logging with emoji prefixes (per CLAUDE.md conventions)
-- Never log full JSON blobs or arrays
-- Use string interpolation for values
-- Logger utility functions in `server/lib/logger.js`:
- - `startup()` → 🚀 (initialization messages)
- - `process()` → 📜 (operation progress)
- - `error()` → ❌ (errors to console.error)
- - `success()` → ✅ (successful operations)
- - `config()` → 🔧 (configuration changes)
- - `feature()` → 🎉 (new features)
- - `bug()` → 🐛 (bug detection)
- - `info()` → ℹ️ (informational messages)
- - `warning()` → ⚠️ (deprecations, warnings to console.warn)
- - `debug()` → 🔍 (debug traces)
-
-Example patterns:
-```javascript
-console.log(`🚀 Server started on port ${PORT}`);
-console.log(`📜 Processing ${items.length} items`);
-console.error(`❌ Failed to connect: ${err.message}`);
-```
-
-## Comments
-
-**When to Comment:**
-- JSDoc/TSDoc comments on exported functions: `/** * Utility description * @param {type} name - description */`
-- Explain "why" not "what" for complex logic
-- Comments above sections: `// =============================================================================`
-- Inline comments for non-obvious logic, but sparingly
-
-Example from `server/lib/validation.js`:
-```javascript
-// =============================================================================
-// AGENT PERSONALITY SCHEMAS
-// =============================================================================
-
-// Agent personality style
-export const personalityStyleSchema = z.enum([
- 'professional',
- 'casual',
- 'witty',
- 'academic',
- 'creative'
-]);
-```
-
-## Function Design
-
-**Size:** Functions are generally focused on single responsibility, ranging 5-40 lines
-
-**Parameters:**
-- Destructured parameters for objects: `asyncHandler(async (req, res, next) => { ... })`
-- Optional options objects as last parameter: `readJSONFile(APPS_FILE, { apps: {} })`
-- Middleware pattern for Express routes: `(req, res, next) => { ... }`
-
-**Return Values:**
-- Handlers return void (Express middleware)
-- Services return Promises (async functions)
-- Utility functions return data or Promise<data>
-- Schema validation returns result object: `{ success: boolean, data?: T, errors?: Array }`
-
-Example from `server/routes/apps.js`:
-```javascript
-router.get('/', asyncHandler(async (req, res) => {
- const apps = await appsService.getAllApps();
- // ... enrichment logic ...
- res.json(enriched);
-}));
-```
-
-## Module Design
-
-**Exports:**
-- Named exports for most utilities and services: `export const getAppById = async (id) => { ... }`
-- Default exports rarely used
-- Service modules export both data and functions: `export const PORTOS_APP_ID = 'portos-default'`, `export async function getAllApps() { ... }`
-
-**Barrel Files:**
-- Minimal use of barrel files; prefer specific imports
-- Routes/services imported with wildcard: `import * as appsService from '../services/apps.js'`
-
-## Async Patterns
-
-**Promise handling:**
-- Async/await preferred over .then() chains
-- Error handling via asyncHandler wrapper, not try/catch
-- Promise.all() for concurrent operations with settled promises when appropriate
-
-Example from `server/routes/apps.js`:
-```javascript
-const enriched = await Promise.all(apps.map(async (app) => {
- const pm2Home = app.pm2Home || null;
- const pm2Map = pm2Maps.get(pm2Home) || new Map();
- // ... processing logic ...
- return { ...app, pm2Status: statuses, overallStatus };
-}));
-```
-
-## React/Client Conventions
-
-**Hooks:**
-- Functional components with hooks only (no classes)
-- Custom hooks file naming: `use{Purpose}.js` (e.g., `useErrorNotifications.js`, `useNotifications.js`)
-- Hooks return object with methods: `return { requestAutoFix }`
-
-**Component Organization:**
-- Components in `client/src/components/`
-- Pages in `client/src/pages/` (route-based)
-- Services in `client/src/services/` (API and WebSocket)
-- Custom hooks in `client/src/hooks/`
-- Utilities in `client/src/utils/`
-
-**Navigation:**
-- Sidebar nav items in `Layout.jsx` organized alphabetically (after Dashboard + CyberCity section and separator)
-- URL params for tabbed pages instead of local state: `/devtools/history` not `/devtools` with internal state
-- All views must be linkable routes
-
-**UI Patterns:**
-- No `window.alert()` or `window.confirm()` — use toast notifications via `react-hot-toast`
-- Toast notifications with emoji icons: `toast()`, `toast.error()`, `toast.success()`
-- Example: `toast('Recovery agent dispatched', { icon: '🔧' })`
-
-Example hook from `client/src/hooks/useErrorNotifications.js`:
-```javascript
-export function useErrorNotifications() {
- const requestAutoFix = useCallback((errorCode, context) => {
- socket.emit('error:recover', { code: errorCode, context });
- toast('Recovery agent dispatched', { icon: '🔧' });
- }, []);
-
- useEffect(() => {
- socket.emit('errors:subscribe');
- // ... handlers setup ...
- return () => {
- socket.off('error:occurred', handleError);
- };
- }, []);
-
- return { requestAutoFix };
-}
-```
-
-## Data Validation
-
-**Zod Schemas:**
-- All route inputs validated via Zod schemas in `server/lib/validation.js`
-- `validateRequest(schema, data)` wrapper function normalizes validation results
-- Validation result format: `{ success: boolean, data?: T, errors?: Array<{ path: string, message: string }> }`
-- Schemas define defaults, optional fields, and constraints
-
-Example:
-```javascript
-export const appSchema = z.object({
- name: z.string().min(1).max(100),
- repoPath: z.string().min(1),
- type: z.string().default('express'),
- uiPort: z.number().int().min(1).max(65535).nullable().optional(),
- processes: z.array(processSchema).optional()
-});
-```
-
----
-
-*Convention analysis: 2026-02-26*
diff --git a/.planning/codebase/INTEGRATIONS.md b/.planning/codebase/INTEGRATIONS.md
deleted file mode 100644
index 3b73ce9b3f..0000000000
--- a/.planning/codebase/INTEGRATIONS.md
+++ /dev/null
@@ -1,243 +0,0 @@
-# External Integrations
-
-**Analysis Date:** 2026-02-26
-
-## APIs & External Services
-
-**Moltworld (Voxel World):**
-- Purpose: AI agent movement, building, communication, and SIM token earning
-- Integration: `server/integrations/moltworld/`
-- SDK/Client: Custom client class `MoltworldClient` with stateful wrapper
-- API Base: https://moltworld.io
-- Auth: API key stored in platform accounts config
-- Methods:
- - `joinWorld()` - Agent entry point
- - `think()` - Agent thoughts/communication
- - `build()` - Structure creation
- - `getProfile()`, `updateProfile()` - Agent identity
- - `getBalance()` - SIM token balance
-- Rate Limits: Enforced per agent (checked before requests)
-- Reference: `server/integrations/moltworld/rateLimits.js`
-
-**Moltbook (AI Agent Social Platform):**
-- Purpose: AI agent social networking, posts, comments, voting, following
-- Integration: `server/integrations/moltbook/`
-- SDK/Client: Custom client class `MoltbookClient` with stateful wrapper
-- API Base: https://www.moltbook.com/api/v1
-- Auth: API key required for all requests
-- Methods:
- - Posts: `createPost()`, `getFeed()`, `getPost()`, `deletePost()`
- - Comments: `createComment()`, `replyToComment()`, `getComments()`
- - Voting: `upvote()`, `downvote()`, `upvoteComment()`
- - Social: `follow()`, `unfollow()`, `getFollowers()`, `getFollowing()`
- - Account: `getStatus()`, `getProfile()`, `updateProfile()`, `heartbeat()`
- - Submolts: `getSubmolts()`, `getSubmolt()`
-- Rate Limits: Enforced per API key (checked before requests)
-- Reference: `server/integrations/moltbook/rateLimits.js`
-- Account Suspension Detection: `isAccountSuspended()` checks for locked accounts
-
-**JIRA:**
-- Purpose: Task/issue tracking, multi-instance support
-- Service: `server/services/jira.js`
-- HTTP Client: axios with HTTPS certificate handling
-- Auth: Personal Access Token (PAT) per instance
- - Configured in: `data/jira.json`
- - Env var for token: Per-instance basis (no global var)
-- Multi-Instance: Each JIRA instance has:
- - `id`, `name`, `baseUrl`, `email`, `apiToken`
- - `createdAt`, `updatedAt`, `tokenUpdatedAt` timestamps
-- Route: `server/routes/jira.js` handles HTTP requests
-- Features: Create/read/update issues, search, custom fields support
-
-**LMStudio (Local LLM):**
-- Purpose: Local AI inference server alternative
-- Configuration: Accessible via localhost endpoints
-- Route: `server/routes/lmstudio.js`
-- Protocol: HTTP API (similar to OpenAI-compatible)
-- Default: `http://localhost:1234/v1` (for scaffolding templates)
-
-**Ollama (Local LLM):**
-- Purpose: Local AI model runner
-- Default Endpoint: `http://localhost:11434/v1` (in scaffolding templates)
-- Used as fallback local provider option
-
-## Data Storage
-
-**Databases:**
-- Not used; all data persists to JSON files in `./data/`
-
-**File Storage:**
-- Local filesystem only
-- Key directories:
- - `data/screenshots/` - Screenshots captured by browser or agents
- - `data/uploads/` - User uploads and attachments
- - `data/browser-profile/` - Chrome user data directory for persistent sessions
-- Routes:
- - `server/routes/screenshots.js` - Screenshot management
- - `server/routes/uploads.js` - Upload handling
- - `server/routes/attachments.js` - Attachment linking
-
-**Caching:**
-- None detected; minimal in-memory caching for browser config and AI toolkit
-
-## Authentication & Identity
-
-**Auth Provider:**
-- Custom/None for external - PortOS is single-user internal tool
-- Per-provider credentials stored in `data/providers.json` (from AI Toolkit)
-- Per-Moltbook account: API keys in platform accounts
-- Per-Moltworld account: API keys in platform accounts
-- Per-JIRA instance: Personal Access Tokens in `data/jira.json`
-
-**Platform Accounts:**
-- Route: `server/routes/platformAccounts.js`
-- Stores credentials for third-party platforms (Moltbook, Moltworld, etc.)
-- Example: `data/agents/{agentId}/accounts.json`
-
-## Monitoring & Observability
-
-**Error Tracking:**
-- None detected (no external service)
-- Local error events via `server/lib/errorHandler.js`
-- Error broadcast via Socket.IO to client: `errorEvents.emit('error', {...})`
-
-**Logs:**
-- Console.log with emoji prefixes (e.g., `🚀`, `❌`, `📜`)
-- Single-line logging pattern (no JSON blobs)
-- PM2 manages log persistence:
- - Log file format: `YYYY-MM-DDTHH:mm:ss.SSS[Z]` (UTC)
- - Output via `pm2 logs` command
- - Configured in `ecosystem.config.cjs`
-
-## CI/CD & Deployment
-
-**Hosting:**
-- Local machine (dev) / Private network behind Tailscale VPN
-- Not exposed to public internet
-- Deployment: PM2 process manager (`ecosystem.config.cjs`)
-
-**CI Pipeline:**
-- GitHub Actions workflows in `.github/workflows/`
-- Release process: Merge `dev` → `main` triggers:
- - Version bump via `npm version` (manual in commit message)
- - Changelog substitution (v0.10.x → actual version)
- - GitHub release creation
- - Archive changelog with version number
-
-**Process Management:**
-- PM2 orchestrates 6 processes:
- - `portos-server` (5554) - Express API
- - `portos-cos` (5558) - Chief of Staff agent runner
- - `portos-ui` (5555) - Vite dev server
- - `portos-autofixer` (5559) - Error recovery
- - `portos-autofixer-ui` (5560) - Autofixer UI
- - `portos-browser` (5556/5557) - Chrome CDP
-
-## AI Provider Integration
-
-**Framework:**
-- portos-ai-toolkit (separate npm module `^0.5.0`)
-- Imported: `import { createAIToolkit } from 'portos-ai-toolkit/server'`
-
-**Provider Management:**
-- Route: `server/routes/providers.js` - Lists/tests/creates providers
-- Service: `server/services/providers.js` - Toolkit wrapper
-- Config: `data/providers.json` - Provider definitions
- - Fields: id, name, type, baseUrl, apiKey, model, tier, fallbackProvider, lightModel, etc.
- - Managed by toolkit's `createProvider()` and `updateProvider()`
-
-**Run Execution:**
-- Route: `server/routes/runs.js` - Run history and execution
-- Service: `server/services/runner.js` - Toolkit wrapper with CLI execution fix
- - Fixed DEP0190 security warning by removing `shell: true`
-- Data: `data/runs/` - Run results and metadata
-- Lifecycle hooks:
- - `onRunCreated` - Records session usage
- - `onRunCompleted` - Tracks token usage
- - `onRunFailed` - Emits error event with context
-
-**Prompt Templates:**
-- Route: `server/routes/prompts.js` - Prompt management
-- Service: `server/services/promptService.js` - Toolkit wrapper
-- Data: `data/prompts/` - Saved templates
-- Features: Template versioning, variable substitution
-
-**Provider Status Monitoring:**
-- Service: `server/services/providerStatus.js`
-- Health checks for configured providers
-- Emits status events via `providerStatusEvents`
-
-## Browser & Automation
-
-**Chrome DevTools Protocol (CDP):**
-- Service: `server/services/browserService.js`
-- Process: `browser/server.js` (separate PM2 process)
-- Config: `data/browser-config.json`
-- Settings:
- - CDP Port: 5556 (default)
- - CDP Host: 127.0.0.1 (localhost only, security)
- - Health Port: 5557
- - Headless: true (default)
- - User Data: `data/browser-profile/` (persistent cookies/sessions)
-- HTTP health check: GET `/json/version` on health port
-- Feature: Persistent Chrome profile for session maintenance
-
-**Terminal Emulation:**
-- node-pty for shell/terminal integration
-- Routes: `server/routes/history.js` - Command history
-- Real-time terminal via Socket.IO
-
-## Webhooks & Callbacks
-
-**Incoming:**
-- Socket.IO subscriptions (client subscribes to server events)
-- Webhook channels: detect, logs, errors, notifications, agents, cosmos, instances, brain
-
-**Outgoing:**
-- Socket.IO emissions to subscribed clients
-- No webhook API for external services detected
-- Browser events emitted locally: `browserEvents.emit()`
-
-## Automation & Scheduling
-
-**Automation Scheduler:**
-- Service: `server/services/automationScheduler.js`
-- Route: `server/routes/automationSchedules.js`
-- Triggers: Time-based schedules for agent actions
-- Agent Action Execution: `server/services/agentActionExecutor.js`
-
-**Brain Scheduler:**
-- Service: `server/services/brainScheduler.js`
-- Features: Daily digests, weekly reviews
-- Started via `startBrainScheduler()`
-
-**Task Learning:**
-- Service: `server/services/taskLearning.js`
-- Tracks agent task completions for learning
-
-## Environment Configuration
-
-**Required Environment Variables:**
-- `NODE_ENV`: development/production
-- `PORT`: 5554 (API server), configurable
-- `HOST`: 0.0.0.0 (default) or specific IP
-- `TZ`: UTC (forced in ecosystem.config.cjs)
-- `CDP_PORT`, `CDP_HOST`: Browser CDP settings
-- `VITE_API_HOST`: Client Vite config for API proxy (localhost default)
-
-**Secrets Location:**
-- AI Provider API keys: `data/providers.json` (managed by toolkit)
-- JIRA PATs: `data/jira.json`
-- Moltbook/Moltworld API keys: Per-platform-account config
-- Browser config: `data/browser-config.json`
-- No `.env` files used; all config via JSON files in `data/`
-
-**Note on Security Model:**
-- PortOS is intentionally designed for single-user, internal use on private network
-- No authentication, CORS restrictions, rate limiting, or HTTPS
-- Deployment context: Behind Tailscale VPN, not internet-exposed
-- Security handled at network level, not application level
-
----
-
-*Integration audit: 2026-02-26*
diff --git a/.planning/codebase/STACK.md b/.planning/codebase/STACK.md
deleted file mode 100644
index 2c42eccebc..0000000000
--- a/.planning/codebase/STACK.md
+++ /dev/null
@@ -1,156 +0,0 @@
-# Technology Stack
-
-**Analysis Date:** 2026-02-26
-
-## Languages
-
-**Primary:**
-- JavaScript (ES6 modules) - Across all server/client code
-- JSX - React components in client code (`client/src/**/*.jsx`)
-
-## Runtime
-
-**Environment:**
-- Node.js v22.21.1 (development; actual runtime flexible)
-- npm v10.9.4
-
-**Package Manager:**
-- npm 10.9.4
-- Lockfiles: `package-lock.json`, `server/package-lock.json`, `client/package-lock.json` (committed)
-
-## Frameworks
-
-**Backend:**
-- Express.js ^4.21.2 - HTTP server and routing
-- Socket.IO ^4.8.3 - Real-time bidirectional communication
-- node-pty ^1.2.0-beta.10 - Terminal emulation and shell integration
-- axios ^1.7.9 - HTTP client for external APIs
-- ws ^8.18.0 - WebSocket library
-- Zod ^3.24.1 - TypeScript-first schema validation
-
-**Frontend:**
-- React ^18.3.1 - UI framework
-- React Router DOM ^7.1.1 - Client-side routing
-- Vite ^6.0.6 - Build tool and dev server
-- Tailwind CSS ^3.4.17 - Utility-first CSS framework
-- PostCSS ^8.4.49 - CSS transformation
-- Autoprefixer ^10.4.20 - CSS vendor prefixes
-
-**3D Graphics & Terminal:**
-- Three.js ^0.182.0 - WebGL 3D graphics
-- @react-three/fiber ^8.18.0 - React renderer for Three.js
-- @react-three/drei ^9.122.0 - Useful helpers for React Three
-- @xterm/xterm ^6.0.0 - Terminal emulator (web)
-- @xterm/addon-fit ^0.11.0 - XTerm fit addon
-- @xterm/addon-web-links ^0.12.0 - XTerm web links addon
-
-**UI Components & Interaction:**
-- react-hot-toast ^2.6.0 - Toast notification system
-- lucide-react ^0.562.0 - Icon library
-- react-markdown ^10.1.0 - Markdown rendering
-- recharts ^3.7.0 - React charting library
-- geist ^1.7.0 - UI component library
-- @dnd-kit/core ^6.3.1 - Drag-and-drop primitives
-- @dnd-kit/sortable ^10.0.0 - Sortable drag-and-drop
-- @dnd-kit/utilities ^3.2.2 - Drag-and-drop utilities
-- fflate ^0.8.2 - JavaScript deflate compression
-- socket.io-client ^4.8.3 - WebSocket client
-
-**Development & Build:**
-- Vite ^6.0.6 - Module bundler and dev server
-- @vitejs/plugin-react ^4.3.4 - React plugin for Vite
-- vitest ^4.0.16 - Unit test framework
-- @vitest/coverage-v8 ^4.0.16 - Test coverage reporting
-- supertest ^7.1.4 - HTTP assertion library
-
-**Process Management:**
-- PM2 ^5.4.3 - Application process manager (root and server deps)
-
-**Utilities:**
-- uuid ^11.0.3 - UUID generation
-- cors ^2.8.5 - CORS middleware
-
-## Key Dependencies
-
-**Critical for AI Integration:**
-- portos-ai-toolkit ^0.5.0 - Separate npm module for AI provider management, run tracking, and prompt templates
- - Located at `../portos-ai-toolkit` in development
- - Manages provider configuration (models, tiers, fallbacks)
- - Handles provider lifecycle and CLI execution
-
-**External Service Integration:**
-- axios - HTTP client for Jira, Moltbook, Moltworld APIs
-- node-pty - Terminal spawning for shell commands and script execution
-- ws - WebSocket connections for real-time features
-
-**Validation & Error Handling:**
-- Zod - Input validation for all Express routes
-- Centralized error middleware in `server/lib/errorHandler.js`
-
-## Configuration
-
-**Environment:**
-- Process environment variables via `ecosystem.config.cjs`:
- - `NODE_ENV`: 'development' (base)
- - `TZ`: 'UTC' (all timestamps in UTC)
- - `PORT`: 5555 (API), configurable per process
- - `HOST`: '0.0.0.0' (server), '127.0.0.1' (CDP/CoS)
-
-**Build Configuration:**
-- Vite config: `client/vite.config.js` (port 5554, API proxy to 5555)
-- Tailwind config: `client/tailwind.config.js` (custom design tokens)
-- PostCSS: `client/postcss.config.js` (Tailwind + Autoprefixer)
-- Server test: `server/vitest.config.js` (30% coverage threshold)
-
-**Asset Bundling:**
-- Manual Vite chunks for vendor libraries:
- - `vendor-react`: React, React DOM, React Router
- - `vendor-realtime`: Socket.IO, React Hot Toast
- - `vendor-dnd`: @dnd-kit libraries
- - `vendor-icons`: lucide-react (largest)
-
-## Platform Requirements
-
-**Development:**
-- Node.js v22.x (tested v22.21.1)
-- npm v10.x
-- Chrome/Chromium (for browser automation via CDP)
-- Shell environment (bash/sh for command execution)
-
-**Production:**
-- Node.js runtime (same as development)
-- PM2 for process orchestration (`ecosystem.config.cjs`)
-- Chrome/Chromium (optional, for browser features)
-- File system access for JSON data persistence
-
-## Data Persistence
-
-**Storage Method:**
-- JSON files in `./data/` directory (not database)
-- Key files:
- - `data/providers.json` - AI provider configurations
- - `data/runs/` - AI provider runs and results
- - `data/prompts/` - Prompt templates
- - `data/agents/` - Agent configurations
- - `data/jira.json` - JIRA instance configurations
- - `data/browser-config.json` - Browser CDP settings
- - `data/screenshots/` - Screenshots captured by agents
- - `data/apps.json` - Detected/monitored applications
- - `data/history.json` - Command history
- - `data/brain/` - Memory and learning data
- - `data/digital-twin/` - Identity and autobiography data
-
-## Port Allocation
-
-Defined in `ecosystem.config.cjs`:
-- **5554**: Vite client dev server (React UI)
-- **5555**: Express API server (core PortOS backend)
-- **5556**: Chrome CDP (browser remote debugging)
-- **5557**: Browser health check endpoint
-- **5558**: Chief of Staff (CoS) agent runner
-- **5559**: Autofixer API
-- **5560**: Autofixer UI
-
----
-
-*Stack analysis: 2026-02-26*
diff --git a/.planning/codebase/STRUCTURE.md b/.planning/codebase/STRUCTURE.md
deleted file mode 100644
index a5298f5187..0000000000
--- a/.planning/codebase/STRUCTURE.md
+++ /dev/null
@@ -1,280 +0,0 @@
-# Codebase Structure
-
-**Analysis Date:** 2026-02-26
-
-## Directory Layout
-
-```
-PortOS/
-├── .planning/
-│ ├── codebase/ # Generated codebase analysis documents
-│ └── ...
-├── .changelog/ # Release changelogs (v0.10.x.md, etc)
-├── .github/
-│ └── workflows/ # GitHub Actions CI/CD
-├── .claude/
-│ └── commands/ # Claude Code custom commands
-├── autofixer/ # Autofixer standalone service
-│ ├── server.js # Autofixer API server
-│ └── ui.js # Autofixer UI server
-├── browser/ # Browser automation service (Playwright CDP)
-│ └── server.js # CDP proxy and health check server
-├── client/ # React/Vite frontend
-│ ├── src/
-│ │ ├── main.jsx # Vite entry point
-│ │ ├── App.jsx # Router setup and main layout
-│ │ ├── index.css # Tailwind imports
-│ │ ├── pages/ # Route pages (~20 main pages)
-│ │ ├── components/ # Reusable UI components (~140 files)
-│ │ ├── hooks/ # Custom React hooks
-│ │ ├── services/
-│ │ │ ├── api.js # HTTP client wrapper
-│ │ │ └── socket.js # Socket.IO connection singleton
-│ │ └── utils/ # Utility functions
-│ ├── public/ # Static assets (fonts, favicon)
-│ └── dist/ # Production build output
-├── data/ # Runtime JSON storage (gitignored)
-│ ├── apps.json # Registry of managed applications
-│ ├── providers.json # AI provider configurations
-│ ├── runs/ # AI run history
-│ ├── prompts/ # Prompt templates
-│ ├── cos/ # Chief of Staff agent data
-│ │ ├── memory/ # CoS memory/context
-│ │ ├── agents/ # Sub-agent instances
-│ │ ├── scripts/ # CoS script library
-│ │ ├── missions/ # CoS mission definitions
-│ │ └── reports/ # CoS execution reports
-│ ├── brain/ # Brain state (thoughts, digests, reviews)
-│ ├── digital-twin/ # Digital twin profile data
-│ ├── agents/ # Agent personalities and state
-│ ├── meatspace/ # Meatspace (IRL) tracking data
-│ └── screenshots/ # Captured screenshots
-├── data.reference/ # Sample data templates (checked in)
-│ ├── providers.json # Sample provider config
-│ ├── prompts/ # Default prompt templates
-│ ├── cos/ # Sample CoS structure
-│ └── ...
-├── docs/ # Documentation
-│ ├── PORTS.md # Port allocation guide
-│ ├── VERSIONING.md # Version management
-│ ├── features/ # Feature documentation
-│ └── media/ # Images and diagrams
-├── scripts/ # Utility scripts for setup and development
-│ ├── dev-start.js # Start PM2 with dev-specific config
-│ ├── setup-data.js # Initialize data directory
-│ ├── setup-browser.js # Configure browser environment
-│ └── setup-ghostty.js # Configure terminal
-├── server/ # Express.js backend
-│ ├── index.js # Server entry point, middleware, route mounting
-│ ├── routes/ # HTTP route handlers (~50 route files)
-│ │ ├── apps.js # App registry CRUD
-│ │ ├── agents.js # Agent process management
-│ │ ├── cos.js # Chief of Staff routes
-│ │ ├── brain.js # Brain state management
-│ │ ├── digital-twin.js # Digital twin profile
-│ │ ├── providers.js # AI provider config extension
-│ │ ├── runs.js # AI run history
-│ │ ├── prompts.js # Prompt management
-│ │ ├── health.js # System health checks
-│ │ ├── logs.js # App log streaming
-│ │ ├── git.js # Git operations
-│ │ ├── history.js # Activity history
-│ │ ├── commands.js # Shell command execution
-│ │ └── ... (30+ more)
-│ ├── services/ # Business logic (~130 files)
-│ │ ├── apps.js # App registry persistence and caching
-│ │ ├── pm2.js # PM2 CLI wrapper
-│ │ ├── agents.js # Agent lifecycle management
-│ │ ├── cos.js # Chief of Staff orchestration
-│ │ ├── brain.js # Brain state management
-│ │ ├── digital-twin.js # Digital twin operations
-│ │ ├── socket.js # Socket.IO event handlers
-│ │ ├── errorHandler.js # Socket.IO error broadcasting
-│ │ ├── autoFixer.js # Error recovery automation
-│ │ ├── providers.js # AI provider management (toolkit wrapper)
-│ │ ├── runner.js # AI CLI execution (toolkit wrapper)
-│ │ ├── history.js # Activity logging
-│ │ ├── usage.js # Usage tracking
-│ │ ├── pm2Standardizer.js # Auto-configure PM2 ecosystem files
-│ │ ├── streamingDetect.js # Detect app config from repo
-│ │ └── ... (100+ more)
-│ ├── lib/ # Shared utilities (~30 files)
-│ │ ├── validation.js # Zod schemas for all entities
-│ │ ├── errorHandler.js # ServerError class and middleware
-│ │ ├── fileUtils.js # File I/O and path constants
-│ │ ├── logger.js # Logging utilities
-│ │ ├── taskParser.js # Parse task descriptions
-│ │ ├── brainValidation.js # Brain schema validation
-│ │ ├── digitalTwinValidation.js # Digital twin schema validation
-│ │ ├── memoryValidation.js # Memory schema validation
-│ │ ├── bm25.js # BM25 search algorithm
-│ │ ├── vectorMath.js # Vector operations
-│ │ └── ... (more)
-│ ├── cos-runner/ # CoS isolated process
-│ │ └── index.js # Spawn Claude CLI agents
-│ ├── integrations/ # External platform integrations
-│ │ ├── moltworld/ # Moltworld integration
-│ │ └── moltbook/ # Moltbook integration
-│ ├── scripts/ # Standalone utility scripts
-│ │ └── ... (various data prep scripts)
-│ ├── data/ # Symlink to ../data for local references
-│ └── node_modules/
-├── shell/ # Terminal/shell customization
-│ ├── themes/ # Terminal color themes
-│ └── shaders/ # Terminal shader configs
-├── ecosystem.config.cjs # PM2 process configuration
-├── package.json # Root workspace package
-├── package-lock.json
-├── vite.config.js # Vite build config (if at root)
-└── CLAUDE.md # Developer instructions
-```
-
-## Directory Purposes
-
-**`.planning/codebase/`:**
-- Purpose: Generated analysis documents for GSD orchestrator
-- Contains: ARCHITECTURE.md, STRUCTURE.md, CONVENTIONS.md, TESTING.md, CONCERNS.md
-- Key files: None (auto-generated)
-
-**`client/src/pages/`:**
-- Purpose: Route-level page components (one per major feature)
-- Contains: Dashboard, Apps, ChiefOfStaff, Brain, DigitalTwin, DevTools, etc.
-- Key files: `Dashboard.jsx` (homepage), `Apps.jsx` (app management)
-
-**`client/src/components/`:**
-- Purpose: Reusable UI components organized by feature
-- Contains: Base components (Layout, AppTile, BrailleSpinner) + feature-specific subdirs (city/, cos/, brain/, digital-twin/, etc.)
-- Key files: `Layout.jsx` (main shell with sidebar), `AppIcon.jsx` (app icon renderer)
-
-**`client/src/hooks/`:**
-- Purpose: Custom React hooks for reusable logic
-- Contains: useErrorNotifications (toast subscription), useSocket (singleton access), useTheme, useCityData, etc.
-- Key files: `useErrorNotifications.js` (subscribes to Socket.IO error events)
-
-**`server/routes/`:**
-- Purpose: HTTP route handlers for specific features
-- Contains: CRUD operations with Zod validation, delegates to services
-- Key files: `apps.js` (150+ lines), `cos.js` (45K+ lines), `brain.js`, `agents.js`
-
-**`server/services/`:**
-- Purpose: Business logic and state management
-- Contains: File I/O, PM2 management, event publishing, domain-specific workflows
-- Key files: `apps.js` (registry + caching), `cos.js` (129K+ CoS orchestration), `pm2.js` (process control)
-
-**`server/lib/`:**
-- Purpose: Shared infrastructure and utilities
-- Contains: Zod schemas, error handling, file operations, validation logic
-- Key files: `validation.js` (14K+ agent/account/brain schemas), `errorHandler.js`, `fileUtils.js`
-
-**`server/cos-runner/`:**
-- Purpose: Isolated process for spawning long-running Claude CLI agents
-- Contains: CoS agent spawner, process lifecycle management
-- Key files: `index.js` (must not auto-restart with main server)
-
-**`data/`:**
-- Purpose: Runtime JSON storage (all app state, user data)
-- Contains: JSON files for apps, providers, runs, prompts, agents, CoS memory, brain state, etc.
-- Generated by: Services via fileUtils, AI toolkit
-
-**`data.reference/`:**
-- Purpose: Template data checked into git for bootstrapping new instances
-- Contains: Sample provider configs, prompt templates, CoS mission examples
-- Key files: `providers.json` (template AI providers)
-
-## Key File Locations
-
-**Entry Points:**
-- Server: `server/index.js` (Express setup, route mounting, Socket.IO init)
-- Client: `client/src/main.jsx` → `App.jsx` (Router setup)
-- CoS Runner: `server/cos-runner/index.js` (Isolated agent spawner)
-- PM2 Config: `ecosystem.config.cjs` (Process definitions)
-
-**Configuration:**
-- PM2: `ecosystem.config.cjs` (port allocation, env setup)
-- Vite: `client/vite.config.js` (build config)
-- Tailwind: `client/tailwind.config.js` (design tokens)
-- AI Toolkit: `server/services/providers.js` (extends toolkit config)
-
-**Core Logic:**
-- App Management: `server/services/apps.js` (registry), `server/routes/apps.js` (API)
-- PM2 Control: `server/services/pm2.js` (CLI wrapper), `routes/apps.js` (process endpoints)
-- AI Execution: `server/services/runner.js` (toolkit wrapper), `routes/runs.js` (history)
-- Error Handling: `server/lib/errorHandler.js` (ServerError + middleware), `services/socket.js` (broadcasting)
-
-**Testing:**
-- Unit Tests: Co-located with services, e.g., `services/apps.test.js`
-- Test Config: `server/package.json` defines vitest/jest commands
-- Key test files: `services/autobiography.test.js`, `services/brain.test.js`
-
-## Naming Conventions
-
-**Files:**
-- Services: camelCase, descriptive (e.g., `agentActionExecutor.js`, `automationScheduler.js`)
-- Routes: Match resource name (e.g., `apps.js`, `cos.js`)
-- Components: PascalCase, descriptive (e.g., `SystemHealthWidget.jsx`)
-- Pages: PascalCase, match route (e.g., `ChiefOfStaff.jsx`, `DigitalTwin.jsx`)
-- Utilities: camelCase (e.g., `taskParser.js`, `vectorMath.js`)
-
-**Directories:**
-- Feature directories: kebab-case (e.g., `digital-twin/`, `cos-runner/`)
-- Component categories: lowercase plural (e.g., `components/city/`, `hooks/`)
-- Data domains: kebab-case (e.g., `data/digital-twin/`, `data/brain/`)
-
-## Where to Add New Code
-
-**New Feature:**
-- Primary code: `server/services/{feature}.js` (business logic)
-- Route handler: `server/routes/{feature}.js` (API endpoints)
-- Tests: `server/services/{feature}.test.js`
-- Schemas: Add to `server/lib/validation.js` or create `server/lib/{feature}Validation.js`
-- Client: Create `client/src/pages/{Feature}.jsx` for new page
-
-**New Component/Module:**
-- Reusable components: `client/src/components/{Component}.jsx`
-- Feature-specific components: `client/src/components/{feature}/`
-- Hooks: `client/src/hooks/use{Hook}.js`
-- Services: `server/services/{service}.js` (follow existing patterns)
-
-**Utilities:**
-- Shared server utilities: `server/lib/{utility}.js`
-- Validation schemas: `server/lib/{domain}Validation.js`
-- Client utilities: `client/src/utils/{utility}.js`
-- API methods: Add to `client/src/services/api.js`
-
-## Special Directories
-
-**`data/`:**
-- Purpose: All runtime application state
-- Generated: Yes (by services at runtime)
-- Committed: No (gitignored)
-- Persistence: JSON files, watched by services for changes
-
-**`data.reference/`:**
-- Purpose: Bootstrap templates for new instances
-- Generated: No (checked in manually)
-- Committed: Yes (part of repo)
-- Usage: Copied or referenced during setup
-
-**`docs/`:**
-- Purpose: User and developer documentation
-- Key files: `PORTS.md` (port allocation), `VERSIONING.md` (release process)
-- Maintenance: Update when architecture changes
-
-**`shell/`:**
-- Purpose: Terminal environment customization
-- Contains: Theme files, shader configs
-- Used by: `setup-ghostty.js` during initialization
-
-**`autofixer/`:**
-- Purpose: Standalone microservice for error recovery
-- Contains: `server.js` (API), `ui.js` (UI server)
-- Managed by: PM2 process (separate from main server)
-
-**`browser/`:**
-- Purpose: Browser automation via Playwright CDP
-- Contains: CDP proxy server with health checks
-- Managed by: PM2 process (separate, bound to localhost only)
-
----
-
-*Structure analysis: 2026-02-26*
diff --git a/.planning/codebase/TESTING.md b/.planning/codebase/TESTING.md
deleted file mode 100644
index b30b8dcec6..0000000000
--- a/.planning/codebase/TESTING.md
+++ /dev/null
@@ -1,522 +0,0 @@
-# Testing Patterns
-
-**Analysis Date:** 2026-02-26
-
-## Test Framework
-
-**Runner:**
-- Vitest v4.0.16
-- Config: `server/vitest.config.js`
-- ES modules support (native)
-
-**Assertion Library:**
-- Vitest built-in: `expect()` from vitest
-
-**Run Commands:**
-```bash
-cd server && npm test # Run all tests (vitest run)
-cd server && npm run test:watch # Watch mode (vitest)
-cd server && npm run test:coverage # Coverage report (vitest run --coverage)
-```
-
-## Test File Organization
-
-**Location:**
-- Co-located with source code in same directory
-- Not in separate `__tests__` directory
-
-**Naming:**
-- `.test.js` suffix: `validation.test.js`, `errorHandler.test.js`, `logger.test.js`
-- Integration tests: `.integration.test.js` suffix (e.g., `visionTest.integration.test.js`)
-
-**Structure:**
-```
-server/
-├── lib/
-│ ├── validation.js
-│ └── validation.test.js # Co-located test
-├── routes/
-│ ├── apps.js
-│ └── apps.test.js # Co-located test
-└── services/
- ├── apps.js
- └── apps.test.js # Co-located test
-```
-
-## Test Structure
-
-**Suite Organization:**
-```javascript
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-
-describe('Module Name', () => {
- describe('FeatureName', () => {
- it('should do something specific', () => {
- // Test implementation
- });
-
- it('should handle edge case', () => {
- // Test implementation
- });
- });
-
- describe('AnotherFeature', () => {
- // More tests
- });
-});
-```
-
-**Test Patterns:**
-- `describe()` blocks group related tests (domain or function-level)
-- Nested `describe()` blocks for feature-specific tests
-- `it()` for individual test cases with clear, descriptive names starting with "should"
-- Tests are independent and can run in any order
-
-Example from `server/lib/validation.test.js`:
-```javascript
-describe('validation.js', () => {
- describe('processSchema', () => {
- it('should validate a complete process object', () => {
- const process = {
- name: 'test-process',
- port: 3000,
- description: 'A test process'
- };
- const result = processSchema.safeParse(process);
- expect(result.success).toBe(true);
- expect(result.data).toEqual(process);
- });
-
- it('should reject empty name', () => {
- const process = { name: '' };
- const result = processSchema.safeParse(process);
- expect(result.success).toBe(false);
- });
- });
-});
-```
-
-## Test Setup/Teardown
-
-**Patterns:**
-```javascript
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-
-describe('Module', () => {
- let mockData;
-
- beforeEach(() => {
- // Fresh setup for each test
- mockData = { id: '123', value: 'test' };
- vi.clearAllMocks();
- });
-
- afterEach(() => {
- // Cleanup after each test
- vi.clearAllMocks();
- mockData = null;
- });
-
- it('should test something', () => {
- // Test body
- });
-});
-```
-
-Example from `server/routes/apps.test.js`:
-```javascript
-describe('Apps Routes', () => {
- let app;
-
- beforeEach(() => {
- app = express();
- app.use(express.json());
- app.use('/api/apps', appsRoutes);
-
- // Reset all mocks
- vi.clearAllMocks();
- });
-
- it('should return list of apps with PM2 status', async () => {
- // Test implementation
- });
-});
-```
-
-Example from `server/lib/logger.test.js`:
-```javascript
-describe('logger', () => {
- let consoleLogSpy;
- let consoleErrorSpy;
- let consoleWarnSpy;
-
- beforeEach(() => {
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
- consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- });
-
- afterEach(() => {
- consoleLogSpy.mockRestore();
- consoleErrorSpy.mockRestore();
- consoleWarnSpy.mockRestore();
- });
-
- test('startup logs with rocket emoji', () => {
- logger.startup('Server started');
- expect(consoleLogSpy).toHaveBeenCalledWith('🚀 Server started');
- });
-});
-```
-
-## Mocking
-
-**Framework:** Vitest built-in `vi` from 'vitest'
-
-**Patterns:**
-
-### Module Mocking:
-```javascript
-vi.mock('../services/apps.js', () => ({
- getAllApps: vi.fn(),
- getAppById: vi.fn(),
- createApp: vi.fn(),
- updateApp: vi.fn(),
- deleteApp: vi.fn(),
- PORTOS_APP_ID: 'portos-default'
-}));
-
-// Then import the mocked module
-import * as appsService from '../services/apps.js';
-
-// Usage in tests
-appsService.getAllApps.mockResolvedValue(mockApps);
-```
-
-### Function Mocking with vi.fn():
-```javascript
-const mockSocket = {
- id: 'socket-123',
- emit: vi.fn(),
- on: vi.fn()
-};
-
-// Assertions on calls
-expect(mockSocket.emit).toHaveBeenCalledWith('cos:subscribed');
-```
-
-### Spy Mocking:
-```javascript
-const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
-expect(consoleLogSpy).toHaveBeenCalledWith('🚀 Server started');
-consoleLogSpy.mockRestore();
-```
-
-### Return Value Mocking:
-```javascript
-appsService.getAllApps.mockResolvedValue([
- { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'] }
-]);
-
-pm2Service.listProcesses.mockResolvedValue([
- { name: 'test-app', status: 'online' }
-]);
-```
-
-Example from `server/routes/apps.test.js`:
-```javascript
-vi.mock('../services/apps.js', () => ({
- getAllApps: vi.fn(),
- getAppById: vi.fn(),
- createApp: vi.fn(),
- updateApp: vi.fn(),
- deleteApp: vi.fn(),
- archiveApp: vi.fn(),
- notifyAppsChanged: vi.fn(),
- PORTOS_APP_ID: 'portos-default'
-}));
-
-vi.mock('../services/pm2.js', () => ({
- listProcesses: vi.fn(),
- getAppStatus: vi.fn(),
- startWithCommand: vi.fn(),
- stopApp: vi.fn(),
- restartApp: vi.fn(),
- getLogs: vi.fn()
-}));
-
-// Later in test
-appsService.getAllApps.mockResolvedValue(mockApps);
-pm2Service.listProcesses.mockResolvedValue(mockPm2Processes);
-```
-
-**What to Mock:**
-- External service dependencies (apps service, pm2 service, history service)
-- HTTP/Socket.IO calls
-- File system operations (when testing business logic, not I/O)
-- Console methods when testing log output
-- EventEmitter instances
-
-**What NOT to Mock:**
-- Validation schemas (test real Zod validation)
-- Error handler logic (test with real ServerError)
-- Core utility functions (test real implementations)
-- Internal module logic you're testing
-
-## Fixtures and Factories
-
-**Test Data:**
-- Inline mock data in test files (no separate fixtures directory)
-- Reusable data objects defined at top of describe blocks or in beforeEach
-
-Example pattern from `server/routes/apps.test.js`:
-```javascript
-const mockApps = [
- { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'], repoPath: '/tmp/test' }
-];
-
-const mockPm2Processes = [
- { name: 'test-app', status: 'online' }
-];
-
-// Reuse in multiple tests
-appsService.getAllApps.mockResolvedValue(mockApps);
-```
-
-Example from `server/lib/errorHandler.test.js`:
-```javascript
-const testCases = [
- { status: 400, code: 'BAD_REQUEST' },
- { status: 401, code: 'UNAUTHORIZED' },
- { status: 403, code: 'FORBIDDEN' },
- { status: 404, code: 'NOT_FOUND' },
- // ... more cases
-];
-
-for (const tc of testCases) {
- const error = new Error('Test');
- error.status = tc.status;
- const normalized = normalizeError(error);
- expect(normalized.code).toBe(tc.code);
-}
-```
-
-**Location:**
-- Test data lives inline in test files
-- No separate fixtures directory
-- Shared data reused via variables/functions in beforeEach
-
-## Coverage
-
-**Requirements:** 30% threshold for lines, functions, branches, and statements
-
-**Configuration** (in `server/vitest.config.js`):
-```javascript
-coverage: {
- provider: 'v8',
- reporter: ['text', 'text-summary', 'html'],
- reportsDirectory: './coverage',
- include: ['lib/**/*.js', 'routes/**/*.js', 'services/**/*.js'],
- exclude: [
- '**/*.test.js',
- '**/index.js',
- '**/cos-runner/**'
- ],
- thresholds: {
- lines: 30,
- functions: 30,
- branches: 30,
- statements: 30
- }
-}
-```
-
-**View Coverage:**
-```bash
-npm run test:coverage
-# Generates HTML report in ./coverage/index.html
-```
-
-**Included:**
-- `lib/**/*.js` - All utility/library code
-- `routes/**/*.js` - All route handlers
-- `services/**/*.js` - All service code
-
-**Excluded:**
-- `*.test.js` - Test files themselves
-- `index.js` - Entry points
-- `cos-runner/**` - External agent runner code
-
-## Test Types
-
-**Unit Tests:**
-- Scope: Single function or small module
-- Approach: Test business logic in isolation with mocked dependencies
-- No external I/O (unless testing I/O specifically)
-- Fast execution (< 100ms per test)
-
-Example from `server/lib/validation.test.js`:
-```javascript
-it('should validate a complete process object', () => {
- const process = {
- name: 'test-process',
- port: 3000,
- description: 'A test process'
- };
- const result = processSchema.safeParse(process);
- expect(result.success).toBe(true);
- expect(result.data).toEqual(process);
-});
-```
-
-**Integration Tests:**
-- Scope: Multiple modules working together, typically route + service
-- Approach: Mock external services, test request/response cycle
-- Uses `supertest` for HTTP testing with Express
-- May use real validation and error handling
-
-Example from `server/routes/apps.test.js`:
-```javascript
-it('should return list of apps with PM2 status', async () => {
- const mockApps = [
- { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'], repoPath: '/tmp/test' }
- ];
- const mockPm2Processes = [
- { name: 'test-app', status: 'online' }
- ];
-
- appsService.getAllApps.mockResolvedValue(mockApps);
- pm2Service.listProcesses.mockResolvedValue(mockPm2Processes);
-
- const response = await request(app).get('/api/apps');
-
- expect(response.status).toBe(200);
- expect(response.body).toHaveLength(1);
- expect(response.body[0].overallStatus).toBe('online');
-});
-```
-
-**E2E Tests:**
-- Framework: Not currently in use
-- Vision testing only (integration test with `.integration.test.js` suffix)
-
-## Common Patterns
-
-**Async Testing:**
-```javascript
-it('should serialize concurrent operations', async () => {
- const withLock = createMutex();
- const results = [];
-
- const p1 = withLock(async () => {
- await new Promise(r => setTimeout(r, 20));
- results.push('first');
- return 'first';
- });
-
- const p2 = withLock(async () => {
- results.push('second');
- return 'second';
- });
-
- const p3 = withLock(async () => {
- results.push('third');
- return 'third';
- });
-
- await Promise.all([p1, p2, p3]);
-
- expect(results).toEqual(['first', 'second', 'third']);
-});
-```
-
-**Error Testing:**
-```javascript
-it('should propagate errors from the wrapped function', async () => {
- const withLock = createMutex();
-
- await expect(
- withLock(async () => {
- throw new Error('test error');
- })
- ).rejects.toThrow('test error');
-});
-```
-
-**HTTP Route Testing with supertest:**
-```javascript
-import request from 'supertest';
-import express from 'express';
-import routes from './routes.js';
-
-const app = express();
-app.use(express.json());
-app.use('/api', routes);
-
-it('should return 200 with correct data', async () => {
- const response = await request(app)
- .get('/api/health');
-
- expect(response.status).toBe(200);
- expect(response.body.status).toBe('ok');
- expect(response.body.version).toBeDefined();
-});
-```
-
-**Zod Schema Validation Testing:**
-```javascript
-it('should validate with safeParse', () => {
- const data = { name: 'Test', repoPath: '/path' };
- const result = appSchema.safeParse(data);
- expect(result.success).toBe(true);
- expect(result.data.type).toBe('express'); // default value
-});
-
-it('should reject invalid data', () => {
- const data = { name: '', repoPath: '' };
- const result = appSchema.safeParse(data);
- expect(result.success).toBe(false);
- expect(result.errors).toBeDefined();
- expect(result.errors.length).toBeGreaterThan(0);
-});
-```
-
-**Mock Callback Testing:**
-```javascript
-it('should emit error event to errorEvents', () => {
- const listener = vi.fn();
- errorEvents.on('error', listener);
-
- const error = new ServerError('Test error');
- emitErrorEvent(mockIo, error);
-
- expect(listener).toHaveBeenCalledWith(error);
- errorEvents.off('error', listener);
-});
-```
-
-## Test File Examples
-
-**Unit Test:** `server/lib/errorHandler.test.js`
-- Tests ServerError class creation with options
-- Tests normalizeError() conversion logic
-- Tests error code mapping from HTTP status
-- Tests emitErrorEvent() with mocked io and event listeners
-
-**Integration Test:** `server/routes/apps.test.js`
-- Mocks all services (apps, pm2, history, streamingDetect)
-- Tests HTTP GET/POST/PUT/DELETE endpoints
-- Uses supertest for request/response testing
-- Verifies request validation and response shape
-- Tests multiple scenarios: success, empty results, error handling
-
-**Utility Test:** `server/lib/validation.test.js`
-- Tests multiple schemas: processSchema, appSchema, providerSchema, runSchema
-- Tests valid data with all fields and defaults
-- Tests invalid data rejection (empty strings, out-of-range values)
-- Tests optional fields (null, omitted)
-- Tests validate() wrapper function error formatting
-
----
-
-*Testing analysis: 2026-02-26*
diff --git a/.planning/config.json b/.planning/config.json
deleted file mode 100644
index 330145de34..0000000000
--- a/.planning/config.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "mode": "yolo",
- "depth": "comprehensive",
- "parallelization": true,
- "commit_docs": true,
- "model_profile": "balanced",
- "workflow": {
- "research": true,
- "plan_check": true,
- "verifier": true
- }
-}
diff --git a/.planning/milestones/v1.14-REQUIREMENTS.md b/.planning/milestones/v1.14-REQUIREMENTS.md
deleted file mode 100644
index a88a0cb0c8..0000000000
--- a/.planning/milestones/v1.14-REQUIREMENTS.md
+++ /dev/null
@@ -1,133 +0,0 @@
-# Requirements Archive: v1.0 Next Actions Batch
-
-**Archived:** 2026-02-27
-**Status:** SHIPPED
-
-For current requirements, see `.planning/REQUIREMENTS.md`.
-
----
-
-# Requirements: PortOS Next Actions Batch
-
-**Defined:** 2026-02-26
-**Core Value:** Ship the five planned next actions that transform PortOS from powerful but siloed features into a connected, protected, and searchable system.
-
-## v1 Requirements
-
-Requirements for this milestone batch. Each maps to roadmap phases.
-
-### Genome Cleanup
-
-- [x] **GEN-01**: Route comments updated from `/api/digital-twin/genome/` to `/api/meatspace/genome/`
-- [x] **GEN-02**: IdentityTab Genome card removed or redirected to `/meatspace/genome`
-- [x] **GEN-03**: genome.js data paths verified to read from correct directory
-
-### Backup
-
-- [x] **BAK-01**: Incremental rsync backup copies changed files from `./data/` to configurable external drive path
-- [x] **BAK-02**: SHA-256 manifest tracks file integrity across backups
-- [x] **BAK-03**: Daily backup runs via existing scheduler with configurable interval
-- [x] **BAK-04**: Dashboard widget shows last backup time, next scheduled, health status (green/yellow/red)
-- [x] **BAK-05**: One-click manual backup trigger from dashboard
-- [x] **BAK-06**: Restore from named snapshot with dry-run mode showing what would change
-- [x] **BAK-07**: Selective directory restore (e.g., only `data/brain/` without touching other dirs)
-
-### Apple Health
-
-- [x] **HLT-01**: POST `/api/health/ingest` accepts Health Auto Export JSON, validates with Zod, deduplicates by metric+timestamp
-- [x] **HLT-02**: Health data persists to day-partitioned `data/health/YYYY-MM-DD.json` files
-- [x] **HLT-03**: Bulk XML import streams Apple Health export (500MB+) without OOM via SAX parser
-- [x] **HLT-04**: XML import reports progress via WebSocket during processing
-- [x] **HLT-05**: MeatSpace dashboard cards for steps, heart rate, sleep, HRV trends
-- [x] **HLT-06**: Correlate Apple Health data with existing MeatSpace data (alcohol vs HRV, activity vs blood work)
-
-### Cross-Insights
-
-- [x] **INS-01**: Rule-based genome-to-health correlations using curated 117 markers against actual blood/body data
-- [x] **INS-02**: LLM-generated taste-to-identity theme analysis connecting preferences to identity patterns
-- [x] **INS-03**: Insights dashboard UI with confidence levels, source attribution, and domain grouping
-- [x] **INS-04**: LLM narrative summaries of cross-domain patterns refreshable on demand
-
-### Unified Search
-
-- [x] **SRC-01**: Cmd+K / Ctrl+K opens search overlay from any page
-- [x] **SRC-02**: Server-side `/api/search` endpoint fans out keyword queries to existing service search functions
-- [x] **SRC-03**: Results categorized by source (Brain, Memory, Apps, History, Health, etc.) with icons and snippets
-- [x] **SRC-04**: Click result navigates to deep-linked location (specific brain capture, agent run, health entry, etc.)
-
-## v2 Requirements
-
-Deferred to future milestone. Tracked but not in current roadmap.
-
-### Search Enhancements
-
-- **SRC-05**: Semantic/vector search layered on top of keyword search using existing BM25+vector infrastructure
-- **SRC-06**: Recent searches and search history
-
-### Backup Enhancements
-
-- **BAK-08**: Rsync to NAS/network target
-- **BAK-09**: Backup encryption for sensitive data
-- **BAK-10**: Retention policy with N daily + N weekly snapshot pruning
-
-### Health Enhancements
-
-- **HLT-07**: Time-series charts with configurable date ranges for Apple Health metrics
-- **HLT-08**: Workout GPS route visualization
-
-### Insights Enhancements
-
-- **INS-05**: Automated insight regeneration when source data changes (EventEmitter-driven cache invalidation)
-- **INS-06**: Personality-to-goals insights connecting behavioral patterns to goal success/stall rates
-
-## Out of Scope
-
-| Feature | Reason |
-|---------|--------|
-| Cloud backup (S3, GCS) | Local external drive is sufficient; no cloud dependency |
-| HealthKit direct API | Requires native iOS app; Health Auto Export app provides the bridge |
-| Causal genome claims | Insights show correlations with confidence, never claim causation |
-| Client-side search indexing | Data lives server-side; server fan-out is simpler and consistent |
-| Semantic search in Cmd+K v1 | Keyword-first ships faster; semantic layers on later via existing infra |
-| Dashboard drag-and-drop | Tier 4 feature, not in this batch |
-| Push notifications (M47) | Deferred to next batch |
-
-## Traceability
-
-Which phases cover which requirements. Updated during roadmap creation.
-
-| Requirement | Phase | Status |
-|-------------|-------|--------|
-| GEN-01 | Phase 1 | Complete |
-| GEN-02 | Phase 1 | Complete |
-| GEN-03 | Phase 1 | Complete |
-| BAK-01 | Phase 2 | Complete |
-| BAK-02 | Phase 2 | Complete |
-| BAK-03 | Phase 2 | Complete |
-| BAK-04 | Phase 2 | Complete |
-| BAK-05 | Phase 2 | Complete |
-| BAK-06 | Phase 2 | Complete |
-| BAK-07 | Phase 2 | Complete |
-| HLT-01 | Phase 3 | Complete |
-| HLT-02 | Phase 3 | Complete |
-| HLT-03 | Phase 3 | Complete |
-| HLT-04 | Phase 3 | Complete |
-| HLT-05 | Phase 3 | Complete |
-| HLT-06 | Phase 3 | Complete |
-| INS-01 | Phase 4 | Complete |
-| INS-02 | Phase 4 | Complete |
-| INS-03 | Phase 4 | Complete |
-| INS-04 | Phase 4 | Complete |
-| SRC-01 | Phase 5 | Complete |
-| SRC-02 | Phase 5 | Complete |
-| SRC-03 | Phase 5 | Complete |
-| SRC-04 | Phase 5 | Complete |
-
-**Coverage:**
-- v1 requirements: 24 total
-- Mapped to phases: 24
-- Unmapped: 0 ✓
-
----
-*Requirements defined: 2026-02-26*
-*Last updated: 2026-02-26 after initial definition*
diff --git a/.planning/milestones/v1.14-ROADMAP.md b/.planning/milestones/v1.14-ROADMAP.md
deleted file mode 100644
index 281277de18..0000000000
--- a/.planning/milestones/v1.14-ROADMAP.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# Roadmap: PortOS Next Actions Batch
-
-## Overview
-
-This batch transforms PortOS from a collection of powerful but siloed features into a connected, protected, and searchable system. Five phases follow a strict dependency chain: clean up stale genome references (unblocking insights), protect all data with backup (before adding new data writers), ingest Apple Health data (the richest new source), derive cross-domain insights (connecting genome, health, taste, and identity), and finally wire up unified search across everything. Each phase delivers a complete, independently verifiable capability.
-
-## Phases
-
-**Phase Numbering:**
-- Integer phases (1, 2, 3): Planned milestone work
-- Decimal phases (2.1, 2.2): Urgent insertions (marked with INSERTED)
-
-Decimal phases appear between their surrounding integers in numeric order.
-
-- [x] **Phase 1: Genome Migration Cleanup** - Fix stale digital-twin genome references so data reads from the correct meatspace location
-- [x] **Phase 2: Data Backup & Recovery** - Incremental rsync backup to external drive with scheduling, dashboard widget, and restore capability (completed 2026-02-26)
-- [x] **Phase 3: Apple Health Integration** - Ingest Health Auto Export JSON and bulk XML into day-partitioned storage with dashboard cards (completed 2026-02-26)
-- [x] **Phase 4: Cross-Domain Insights Engine** - Genome-to-health correlations and taste-to-identity themes with confidence levels and source attribution (completed 2026-02-26)
-- [ ] **Phase 5: Unified Search (Cmd+K)** - Keyboard-triggered search overlay with server-side fan-out across all data sources
-
-## Phase Details
-
-### Phase 1: Genome Migration Cleanup
-**Goal**: Genome data reads from the correct directory and all stale digital-twin references are eliminated
-**Depends on**: Nothing (first phase)
-**Requirements**: GEN-01, GEN-02, GEN-03
-**Success Criteria** (what must be TRUE):
- 1. All genome API route comments reference `/api/meatspace/genome/` (no digital-twin references remain)
- 2. IdentityTab no longer shows a Genome card (or it links to `/meatspace/genome` instead of a dead route)
- 3. genome.js reads data from `data/meatspace/` paths and returns valid genome data
-**Plans**: 1 plan
-
-Plans:
-- [x] 01-01-PLAN.md -- Complete genome migration: update service paths, route comments, client navigation, docs, and move data files
-
-### Phase 2: Data Backup & Recovery
-**Goal**: All PortOS data is automatically backed up to an external drive with integrity verification and restore capability
-**Depends on**: Nothing (can parallel with Phase 1)
-**Requirements**: BAK-01, BAK-02, BAK-03, BAK-04, BAK-05, BAK-06, BAK-07
-**Success Criteria** (what must be TRUE):
- 1. Running backup copies changed files from `./data/` to the configured external drive path using incremental rsync
- 2. A SHA-256 manifest file exists after each backup and can verify file integrity
- 3. Backup runs automatically on a daily schedule and can be triggered manually from the dashboard
- 4. Dashboard widget displays last backup time, next scheduled time, and health status (green/yellow/red)
- 5. User can restore from a named snapshot with dry-run preview, and can selectively restore individual directories
-**Plans**: 2 plans
-
-Plans:
-- [ ] 02-01-PLAN.md -- Backup engine, scheduler, REST routes, validation schemas, and client API functions (BAK-01, BAK-02, BAK-03)
-- [ ] 02-02-PLAN.md -- Dashboard backup widget with health status, manual trigger, snapshot list, and restore UI (BAK-04, BAK-05, BAK-06, BAK-07)
-
-### Phase 3: Apple Health Integration
-**Goal**: Apple Health data flows into PortOS via JSON ingest and bulk XML import, with health metrics visible on the MeatSpace dashboard
-**Depends on**: Phase 2 (backup must protect data before adding new data writers)
-**Requirements**: HLT-01, HLT-02, HLT-03, HLT-04, HLT-05, HLT-06
-**Success Criteria** (what must be TRUE):
- 1. POST `/api/health/ingest` accepts Health Auto Export JSON, validates it, deduplicates by metric+timestamp, and persists to day-partitioned files
- 2. Bulk Apple Health XML export (500MB+) imports without OOM via streaming SAX parser, with progress reported via WebSocket
- 3. MeatSpace dashboard shows cards for steps, heart rate, sleep, and HRV trends from ingested data
- 4. Apple Health data correlates with existing MeatSpace data (alcohol vs HRV, activity vs blood work)
-**Plans**: 3 plans
-
-Plans:
-- [x] 03-01-PLAN.md -- Backend foundation: Zod validation, JSON ingest with dedup, day-partitioned storage, query service, REST routes, client API functions (HLT-01, HLT-02)
-- [ ] 03-02-PLAN.md -- SAX streaming XML import with WebSocket progress, multer diskStorage upload, Import tab XML file picker UI (HLT-03, HLT-04)
-- [ ] 03-03-PLAN.md -- MeatSpace Health tab with steps/HR/sleep/HRV cards, range selector, alcohol-HRV and activity-blood correlation charts (HLT-05, HLT-06)
-
-### Phase 4: Cross-Domain Insights Engine
-**Goal**: PortOS surfaces actionable cross-domain patterns by correlating genome markers with health data and taste preferences with identity themes
-**Depends on**: Phase 1 (clean genome paths), Phase 3 (health data available for correlation)
-**Requirements**: INS-01, INS-02, INS-03, INS-04
-**Success Criteria** (what must be TRUE):
- 1. Genome-to-health correlations display against actual blood/body data using the curated 117 markers, with provenance citations
- 2. LLM-generated taste-to-identity theme analysis connects user preferences to identity patterns
- 3. Insights dashboard groups results by domain with confidence levels and source attribution
- 4. LLM narrative summaries of cross-domain patterns can be refreshed on demand
-**Plans**: 2 plans
-
-Plans:
-- [x] 04-01-PLAN.md -- Backend insights engine: insightsService.js with genome-health correlations, LLM taste-identity themes, cross-domain narrative; REST routes, Zod validation, client API functions (INS-01, INS-02, INS-04)
-- [x] 04-02-PLAN.md -- Insights dashboard UI: /insights/:tab page with Overview, Genome-Health, Taste-Identity, Cross-Domain tabs; shared components, App.jsx routes, Layout.jsx nav entry (INS-03, INS-01, INS-02, INS-04)
-
-### Phase 5: Unified Search (Cmd+K)
-**Goal**: Any piece of information in PortOS is one keystroke away via a global search overlay
-**Depends on**: Phases 1-4 (benefits from all data sources existing, but technically only needs server routes)
-**Requirements**: SRC-01, SRC-02, SRC-03, SRC-04
-**Success Criteria** (what must be TRUE):
- 1. Pressing Cmd+K (or Ctrl+K) from any page opens a search overlay
- 2. Typing a query returns results from all data sources (Brain, Memory, Apps, History, Health, etc.) via server-side fan-out
- 3. Results are categorized by source with icons and text snippets
- 4. Clicking a result navigates to the deep-linked location (specific brain capture, agent run, health entry, etc.)
-**Plans**: 2 plans
-
-Plans:
-- [ ] 05-01-PLAN.md -- Server search engine: fan-out search service with 5 source adapters, GET /api/search route, Zod validation, client API function (SRC-02, SRC-03)
-- [ ] 05-02-PLAN.md -- Cmd+K overlay UI: useCmdKSearch hook, CmdKSearch portal component with keyboard nav, highlighted snippets, deep-link navigation, Layout.jsx mount (SRC-01, SRC-03, SRC-04)
-
-## Progress
-
-**Execution Order:**
-Phases execute in numeric order: 1 -> 2 -> 3 -> 4 -> 5
-Note: Phases 1 and 2 have no dependency on each other and can execute in parallel.
-
-| Phase | Plans Complete | Status | Completed |
-|-------|----------------|--------|-----------|
-| 1. Genome Migration Cleanup | 1/1 | Complete | 2026-02-26 |
-| 2. Data Backup & Recovery | 2/2 | Complete | 2026-02-26 |
-| 3. Apple Health Integration | 2/3 | Complete | 2026-02-26 |
-| 4. Cross-Domain Insights Engine | 2/2 | Complete | 2026-02-26 |
-| 5. Unified Search (Cmd+K) | 1/2 | In Progress| |
diff --git a/.planning/phases/01-genome-migration-cleanup/01-01-PLAN.md b/.planning/phases/01-genome-migration-cleanup/01-01-PLAN.md
deleted file mode 100644
index fcd17f6349..0000000000
--- a/.planning/phases/01-genome-migration-cleanup/01-01-PLAN.md
+++ /dev/null
@@ -1,252 +0,0 @@
----
-phase: 01-genome-migration-cleanup
-plan: 01
-type: execute
-wave: 1
-depends_on: []
-files_modified:
- - server/routes/genome.js
- - server/services/genome.js
- - server/services/clinvar.js
- - server/services/epigenetic.js
- - client/src/components/digital-twin/tabs/IdentityTab.jsx
- - docs/API.md
- - docs/features/identity-system.md
-autonomous: true
-requirements:
- - GEN-01
- - GEN-02
- - GEN-03
-
-must_haves:
- truths:
- - "All route comments in genome.js reference /api/meatspace/genome/ (zero digital-twin references)"
- - "IdentityTab 'View Full Genome' button navigates to /meatspace/genome (a live route)"
- - "genome.js, clinvar.js, and epigenetic.js read/write data from data/meatspace/ directory"
- - "Genome data files (genome.json, genome-raw.txt, clinvar-index.json, clinvar-meta.json) exist in data/meatspace/"
- - "No genome data files remain in data/digital-twin/"
- artifacts:
- - path: "server/routes/genome.js"
- provides: "Corrected route comments"
- contains: "/api/meatspace/genome"
- - path: "server/services/genome.js"
- provides: "Correct data directory"
- contains: "PATHS.meatspace"
- - path: "server/services/clinvar.js"
- provides: "Correct data directory"
- contains: "PATHS.meatspace"
- - path: "server/services/epigenetic.js"
- provides: "Correct data directory"
- contains: "PATHS.meatspace"
- - path: "client/src/components/digital-twin/tabs/IdentityTab.jsx"
- provides: "Working genome navigation"
- contains: "navigate('/meatspace/genome')"
- - path: "data/meatspace/genome.json"
- provides: "Migrated genome metadata"
- - path: "data/meatspace/genome-raw.txt"
- provides: "Migrated raw genome file"
- - path: "data/meatspace/clinvar-index.json"
- provides: "Migrated ClinVar index"
- - path: "data/meatspace/clinvar-meta.json"
- provides: "Migrated ClinVar metadata"
- key_links:
- - from: "server/services/genome.js"
- to: "data/meatspace/genome.json"
- via: "GENOME_DIR = PATHS.meatspace"
- pattern: "PATHS\\.meatspace"
- - from: "server/services/clinvar.js"
- to: "data/meatspace/clinvar-index.json"
- via: "GENOME_DIR = PATHS.meatspace"
- pattern: "PATHS\\.meatspace"
- - from: "client/src/components/digital-twin/tabs/IdentityTab.jsx"
- to: "MeatSpace.jsx genome tab"
- via: "navigate('/meatspace/genome')"
- pattern: "navigate\\('/meatspace/genome'\\)"
----
-
-<objective>
-Complete the genome data migration from digital-twin to meatspace by updating all stale path references in server services, route comments, client navigation, and documentation, then moving the physical data files.
-
-Purpose: The genome API was partially migrated -- the Express mount point and client API calls already reference `/api/meatspace/genome`, but three service files still read from `data/digital-twin/`, route comments are stale, IdentityTab has a dead navigation link, and docs reference old paths. This plan completes the migration so genome data reads from the correct location and all references are consistent.
-
-Output: Updated service files, route comments, client navigation, documentation, and migrated data files.
-</objective>
-
-<execution_context>
-@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
-@/Users/antic/.claude/get-shit-done/templates/summary.md
-</execution_context>
-
-<context>
[email protected]/phases/01-genome-migration-cleanup/01-RESEARCH.md
-
-Key facts from research:
-- `server/index.js` line 209 mounts genome router at `/api/meatspace/genome` (already correct -- do NOT touch)
-- `client/src/services/api.js` already calls `/meatspace/genome/...` endpoints (already correct -- do NOT touch)
-- `client/src/pages/MeatSpace.jsx` line 29 has `case 'genome': return <GenomeTab />` (live route, confirmed)
-- `PATHS.meatspace` is defined at `server/lib/fileUtils.js` line 31 (already exists -- do NOT create a new constant)
-- `data/digital-twin/` contains: `genome.json`, `genome-raw.txt`, `clinvar-index.json`, `clinvar-meta.json` (must move all four)
-- `data/meatspace/` already contains: `blood-tests.json`, `config.json`, `daily-log.json`, `epigenetic-tests.json`, `eyes.json` (no genome files yet)
-- `epigenetic.js` writes `epigenetic.json` (NOT `epigenetic-tests.json`) -- no epigenetic data file exists in `data/digital-twin/`, so no epigenetic data migration needed
-- `docs/API.md` lines 400-415 reference `/digital-twin/genome` paths (stale)
-- `docs/features/identity-system.md` references `data/digital-twin/genome.json` and `/digital-twin/genome` route (stale)
-</context>
-
-<tasks>
-
-<task type="auto">
- <name>Task 1: Update service data paths and route comments</name>
- <files>
- server/services/genome.js
- server/services/clinvar.js
- server/services/epigenetic.js
- server/routes/genome.js
- </files>
- <action>
-1. In `server/services/genome.js` line 7, replace `PATHS.digitalTwin` with `PATHS.meatspace`:
- ```
- const GENOME_DIR = PATHS.meatspace;
- ```
-
-2. In `server/services/clinvar.js` line 9, replace `PATHS.digitalTwin` with `PATHS.meatspace`:
- ```
- const GENOME_DIR = PATHS.meatspace;
- ```
-
-3. In `server/services/epigenetic.js` line 6, replace `PATHS.digitalTwin` with `PATHS.meatspace`:
- ```
- const DATA_DIR = PATHS.meatspace;
- ```
-
-4. In `server/routes/genome.js`, replace ALL 18 occurrences of `/api/digital-twin/genome` with `/api/meatspace/genome` in route comments (lines 19, 25, 39, 52, 59, 66, 80, 95, 101, 120, 141, 149, 155, 162, 169, 176, 190, 204, 217). Use replace_all -- these are comment-only changes, no functional code is affected.
-
-Do NOT modify `server/index.js` (mount point is already correct).
-Do NOT modify `client/src/services/api.js` (API calls are already correct).
- </action>
- <verify>
- <automated>cd /Users/antic/github.com/atomantic/PortOS && grep -c "PATHS.digitalTwin" server/services/genome.js server/services/clinvar.js server/services/epigenetic.js && grep -c "digital-twin/genome" server/routes/genome.js</automated>
- All four counts must be 0.
- </verify>
- <done>All three service files use PATHS.meatspace. All 18 route comments reference /api/meatspace/genome/. Zero occurrences of PATHS.digitalTwin or /api/digital-twin/genome remain in these files.</done>
-</task>
-
-<task type="auto">
- <name>Task 2: Fix client navigation and update documentation</name>
- <files>
- client/src/components/digital-twin/tabs/IdentityTab.jsx
- docs/API.md
- docs/features/identity-system.md
- </files>
- <action>
-1. In `client/src/components/digital-twin/tabs/IdentityTab.jsx` line 190, replace:
- ```
- onClick={() => navigate('/digital-twin/genome')}
- ```
- with:
- ```
- onClick={() => navigate('/meatspace/genome')}
- ```
- This redirects the "View Full Genome" button to the live meatspace genome tab. Keep the genome card and completeness chip -- only the navigation target changes.
-
-2. In `docs/API.md` lines 400-415, replace all occurrences of `/digital-twin/genome` with `/meatspace/genome` in the API route table. Use replace_all for the string `/digital-twin/genome` in that file.
-
-3. In `docs/features/identity-system.md`:
- - Replace `data/digital-twin/genome.json` with `data/meatspace/genome.json` (line 11 area)
- - Replace `/digital-twin/genome` with `/meatspace/genome` where referencing the route (line 255 area)
-
-4. Verify no other client files reference `/digital-twin/genome` by running:
- ```
- grep -r "digital-twin/genome" client/src/ --include="*.jsx" --include="*.js"
- ```
- Expected: zero results after the IdentityTab fix.
- </action>
- <verify>
- <automated>cd /Users/antic/github.com/atomantic/PortOS && grep -c "digital-twin/genome" client/src/components/digital-twin/tabs/IdentityTab.jsx docs/API.md docs/features/identity-system.md && grep -r "digital-twin/genome" client/src/ --include="*.jsx" --include="*.js" -l | wc -l</automated>
- All counts must be 0 and the client search must return 0 files.
- </verify>
- <done>IdentityTab navigates to /meatspace/genome. docs/API.md and docs/features/identity-system.md reference meatspace paths. No client-side references to /digital-twin/genome remain.</done>
-</task>
-
-<task type="auto">
- <name>Task 3: Migrate genome data files from digital-twin to meatspace</name>
- <files>
- data/digital-twin/genome.json
- data/digital-twin/genome-raw.txt
- data/digital-twin/clinvar-index.json
- data/digital-twin/clinvar-meta.json
- data/meatspace/genome.json
- data/meatspace/genome-raw.txt
- data/meatspace/clinvar-index.json
- data/meatspace/clinvar-meta.json
- </files>
- <action>
-Move the four genome/clinvar data files from `data/digital-twin/` to `data/meatspace/`. Use `mv` (move, not copy) so stale files do not remain:
-
-```bash
-mv data/digital-twin/genome.json data/meatspace/genome.json
-mv data/digital-twin/genome-raw.txt data/meatspace/genome-raw.txt
-mv data/digital-twin/clinvar-index.json data/meatspace/clinvar-index.json
-mv data/digital-twin/clinvar-meta.json data/meatspace/clinvar-meta.json
-```
-
-IMPORTANT: Do NOT move any other files from `data/digital-twin/`. That directory still holds non-genome data (chronotype.json, goals.json, etc.) used by other services.
-
-Do NOT move `epigenetic.json` -- it does not exist in `data/digital-twin/`. The epigenetic service will create it in `data/meatspace/` on first write.
-
-Note: These data files are in `.gitignore` (they are user data, not tracked). The move happens on disk only.
-
-After the move, verify the genome API still works by checking the file exists and is valid JSON:
-```bash
-node -e "const fs=require('fs'); const d=JSON.parse(fs.readFileSync('data/meatspace/genome.json','utf-8')); console.log('uploaded:', d.uploaded, 'markers:', d.savedMarkers?.length ?? 0)"
-```
- </action>
- <verify>
- <automated>cd /Users/antic/github.com/atomantic/PortOS && ls data/meatspace/genome.json data/meatspace/genome-raw.txt data/meatspace/clinvar-index.json data/meatspace/clinvar-meta.json && ls data/digital-twin/genome.json 2>&1 | grep -c "No such file"</automated>
- First ls should succeed (all four files exist in meatspace). Second ls should show "No such file" (count = 1).
- </verify>
- <done>All four genome/clinvar files exist in data/meatspace/. Zero genome/clinvar files remain in data/digital-twin/. genome.json parses as valid JSON with expected fields.</done>
-</task>
-
-</tasks>
-
-<verification>
-After all tasks complete, run these checks:
-
-1. **No stale references in code:**
- ```bash
- grep -r "PATHS.digitalTwin" server/services/genome.js server/services/clinvar.js server/services/epigenetic.js
- # Expected: no output
- grep -r "digital-twin/genome" server/routes/genome.js client/src/ docs/API.md docs/features/identity-system.md
- # Expected: no output
- ```
-
-2. **Data files in correct location:**
- ```bash
- ls -la data/meatspace/genome.json data/meatspace/genome-raw.txt data/meatspace/clinvar-index.json data/meatspace/clinvar-meta.json
- # Expected: all four files exist
- ls data/digital-twin/genome* data/digital-twin/clinvar* 2>&1
- # Expected: "No such file or directory" for all
- ```
-
-3. **Tests pass:**
- ```bash
- cd server && npm test
- # Expected: all tests pass (no genome-specific tests exist, but no regressions)
- ```
-</verification>
-
-<success_criteria>
-- Zero occurrences of `PATHS.digitalTwin` in genome.js, clinvar.js, epigenetic.js
-- Zero occurrences of `/api/digital-twin/genome` in server/routes/genome.js
-- Zero occurrences of `/digital-twin/genome` in IdentityTab.jsx, docs/API.md, docs/features/identity-system.md
-- Zero occurrences of `/digital-twin/genome` in any client .jsx or .js file
-- genome.json, genome-raw.txt, clinvar-index.json, clinvar-meta.json all exist in data/meatspace/
-- No genome/clinvar files remain in data/digital-twin/
-- `npm test` passes in server/
-</success_criteria>
-
-<output>
-After completion, create `.planning/phases/01-genome-migration-cleanup/01-01-SUMMARY.md`
-</output>
diff --git a/.planning/phases/01-genome-migration-cleanup/01-01-SUMMARY.md b/.planning/phases/01-genome-migration-cleanup/01-01-SUMMARY.md
deleted file mode 100644
index 1541e8c239..0000000000
--- a/.planning/phases/01-genome-migration-cleanup/01-01-SUMMARY.md
+++ /dev/null
@@ -1,103 +0,0 @@
----
-phase: 01-genome-migration-cleanup
-plan: "01"
-subsystem: genome
-tags: [migration, data-paths, genome, meatspace]
-dependency_graph:
- requires: []
- provides: [genome-meatspace-paths]
- affects: [genome-service, clinvar-service, epigenetic-service, identity-tab]
-tech_stack:
- added: []
- patterns: [PATHS.meatspace]
-key_files:
- created:
- - .changelog/v1.14.x.md
- modified:
- - server/services/genome.js
- - server/services/clinvar.js
- - server/services/epigenetic.js
- - server/routes/genome.js
- - client/src/components/digital-twin/tabs/IdentityTab.jsx
- - docs/API.md
- - docs/features/identity-system.md
-decisions:
- - "Used PATHS.meatspace (existing constant) rather than creating a new one — avoids duplication"
- - "Moved data files with mv (not copy) to ensure no stale files remain in data/digital-twin/"
- - "Updated docs/API.md section header from 'Digital Twin Genome' to 'Meatspace Genome' for consistency"
-metrics:
- duration: "108 seconds"
- completed: "2026-02-26"
- tasks_completed: 3
- files_modified: 8
----
-
-# Phase 01 Plan 01: Genome Migration Cleanup Summary
-
-Complete migration of genome data from digital-twin to meatspace — services now read from `data/meatspace/`, navigation links to live route, docs updated.
-
-## Tasks Completed
-
-| Task | Name | Commit | Files |
-|------|------|--------|-------|
-| 1 | Update service data paths and route comments | 6503b70 | genome.js, clinvar.js, epigenetic.js, routes/genome.js |
-| 2 | Fix client navigation and update documentation | 912946f | IdentityTab.jsx, docs/API.md, docs/features/identity-system.md |
-| 3 | Migrate genome data files from digital-twin to meatspace | (disk only — gitignored) | data/meatspace/{genome.json,genome-raw.txt,clinvar-index.json,clinvar-meta.json} |
-
-## What Was Done
-
-The genome API was partially migrated — the Express mount point (`/api/meatspace/genome`) and client API calls were already correct, but three service files still read from `data/digital-twin/`, route JSDoc comments were stale, IdentityTab had a dead navigation link pointing to `/digital-twin/genome`, and docs referenced old paths.
-
-This plan completed the migration:
-
-1. **Service paths:** All three services (`genome.js`, `clinvar.js`, `epigenetic.js`) now use `PATHS.meatspace` instead of `PATHS.digitalTwin` for their data directory constant. The `PATHS.meatspace` constant already existed in `server/lib/fileUtils.js`.
-
-2. **Route comments:** All 18 JSDoc route comments in `server/routes/genome.js` updated from `/api/digital-twin/genome` to `/api/meatspace/genome` (comment-only changes, no functional code affected).
-
-3. **Client navigation:** IdentityTab "View Full Genome" button now calls `navigate('/meatspace/genome')` instead of the broken `/digital-twin/genome`. The `/meatspace/genome` route was already live via `MeatSpace.jsx` case `'genome'`.
-
-4. **Documentation:** `docs/API.md` section header and all 16 endpoint paths updated to `/meatspace/genome`. `docs/features/identity-system.md` updated two stale references (`data/digital-twin/genome.json` and `/digital-twin/genome` route).
-
-5. **Data migration:** Four files moved from `data/digital-twin/` to `data/meatspace/` using `mv`. All files are gitignored (user data). Verified `genome.json` parses as valid JSON with `uploaded: true` and 117 saved markers.
-
-## Verification Results
-
-- Zero occurrences of `PATHS.digitalTwin` in genome.js, clinvar.js, epigenetic.js
-- Zero occurrences of `/digital-twin/genome` anywhere in server routes, client src, or docs
-- All four genome/clinvar files present in `data/meatspace/`, none remaining in `data/digital-twin/`
-- `genome.json` valid: `uploaded: true`, 117 markers
-- 1192 server tests pass (42 test files, no regressions)
-
-## Deviations from Plan
-
-### Auto-fixed Issues
-
-**1. [Rule 2 - Missing] Updated docs/API.md section header**
-- **Found during:** Task 2
-- **Issue:** The `### Digital Twin Genome` section header was still stale after updating all endpoint paths
-- **Fix:** Updated section header to `### Meatspace Genome` for consistency
-- **Files modified:** `docs/API.md`
-- **Commit:** 912946f
-
-**2. [Rule 2 - Missing] Created v1.14.x.md changelog**
-- **Found during:** Post-task
-- **Issue:** CLAUDE.md requires updating changelog when making changes; no v1.14.x.md existed for the current version
-- **Fix:** Created `.changelog/v1.14.x.md` with entries for all genome migration changes
-- **Files modified:** `.changelog/v1.14.x.md`
-- **Commit:** (in metadata commit)
-
-## Self-Check: PASSED
-
-Files verified:
-- FOUND: server/services/genome.js (contains PATHS.meatspace)
-- FOUND: server/services/clinvar.js (contains PATHS.meatspace)
-- FOUND: server/services/epigenetic.js (contains PATHS.meatspace)
-- FOUND: data/meatspace/genome.json
-- FOUND: data/meatspace/genome-raw.txt
-- FOUND: data/meatspace/clinvar-index.json
-- FOUND: data/meatspace/clinvar-meta.json
-- MISSING from digital-twin: genome.json, genome-raw.txt, clinvar-index.json, clinvar-meta.json (confirmed)
-
-Commits verified:
-- FOUND: 6503b70 (Task 1)
-- FOUND: 912946f (Task 2)
diff --git a/.planning/phases/01-genome-migration-cleanup/01-RESEARCH.md b/.planning/phases/01-genome-migration-cleanup/01-RESEARCH.md
deleted file mode 100644
index 2334e4e1f2..0000000000
--- a/.planning/phases/01-genome-migration-cleanup/01-RESEARCH.md
+++ /dev/null
@@ -1,288 +0,0 @@
-# Phase 1: Genome Migration Cleanup - Research
-
-**Researched:** 2026-02-26
-**Domain:** Internal codebase migration — stale path references, data directory alignment
-**Confidence:** HIGH
-
-## Summary
-
-This phase is a targeted cleanup of stale `digital-twin` path references left over from when genome data was under `data/digital-twin/`. The data and API surface have already been partially migrated: the server mounts the genome router at `/api/meatspace/genome` (server/index.js line 209), the client's `api.js` calls `/meatspace/genome/...` endpoints, and the Layout sidebar links to `/meatspace/genome`. However, three mismatches remain.
-
-First, every route comment in `server/routes/genome.js` still says `// GET /api/digital-twin/genome/...` (18 occurrences). Second, `server/services/genome.js`, `server/services/clinvar.js`, and `server/services/epigenetic.js` all set their data directory to `PATHS.digitalTwin` — meaning genome files (`genome.json`, `genome-raw.txt`, `clinvar-index.json`, etc.) are read from and written to `data/digital-twin/`, not `data/meatspace/`. Third, `IdentityTab.jsx` has a "View Full Genome" button that navigates to `/digital-twin/genome` — a tab case that does not exist in the DigitalTwin page — making it a dead route.
-
-The fix requires three precise edits: (1) update route comments, (2) switch three service files from `PATHS.digitalTwin` to `PATHS.meatspace`, (3) update the IdentityTab navigation target. The data files in `data/digital-twin/` (`genome.json`, `genome-raw.txt`, `clinvar-index.json`, `clinvar-meta.json`) must also be moved to `data/meatspace/`, or the service path change will cause genome data to appear missing on next startup.
-
-**Primary recommendation:** Make all three code changes atomically with the data migration (move files from `data/digital-twin/` to `data/meatspace/`) in a single commit so the system is never in a broken state.
-
-<phase_requirements>
-## Phase Requirements
-
-| ID | Description | Research Support |
-|----|-------------|-----------------|
-| GEN-01 | Route comments updated from `/api/digital-twin/genome/` to `/api/meatspace/genome/` | All 18 occurrences are in `server/routes/genome.js` lines 19-217; simple string replacement |
-| GEN-02 | IdentityTab Genome card removed or redirected to `/meatspace/genome` | IdentityTab.jsx line 190: `navigate('/digital-twin/genome')` → `navigate('/meatspace/genome')`; the meatspace genome tab exists in MeatSpace.jsx |
-| GEN-03 | genome.js reads data from `data/meatspace/` paths and returns valid genome data | Three service files use `PATHS.digitalTwin`; must switch to `PATHS.meatspace` and move existing data files |
-</phase_requirements>
-
-## Standard Stack
-
-### Core
-
-| Library | Version | Purpose | Why Standard |
-|---------|---------|---------|--------------|
-| Node.js `fs/promises` | (project runtime) | File I/O for genome data | Already used throughout all genome services |
-| Express Router | (project runtime) | Route mounting | Already in use; no change needed |
-| React Router `useNavigate` | (project runtime) | Client-side navigation | Already imported in IdentityTab.jsx |
-
-### Supporting
-
-| Library | Version | Purpose | When to Use |
-|---------|---------|---------|-------------|
-| `PATHS` from `server/lib/fileUtils.js` | internal | Centralized path constants | Already the sole source of truth for data dirs — change here propagates to all services |
-
-### Alternatives Considered
-
-| Instead of | Could Use | Tradeoff |
-|------------|-----------|----------|
-| Changing `PATHS.digitalTwin` in 3 service files | Add a `PATHS.genomeData` alias | Alias approach adds indirection with no benefit; direct use of `PATHS.meatspace` is cleaner and consistent with other meatspace services |
-| Moving data files manually | Leave old files and add a migration shim | Migration shim is speculative complexity; a one-time file move is simpler and correct |
-
-**Installation:** No new packages required.
-
-## Architecture Patterns
-
-### Recommended Project Structure
-
-After migration, genome data lives in:
-```
-data/
-├── digital-twin/ # Identity, chronotype, longevity, taste, goals (no genome files)
-│ ├── chronotype.json
-│ ├── goals.json
-│ └── ...
-└── meatspace/ # Physical health data including genome
- ├── genome.json # (moved from data/digital-twin/)
- ├── genome-raw.txt # (moved from data/digital-twin/)
- ├── clinvar-index.json # (moved from data/digital-twin/)
- ├── clinvar-meta.json # (moved from data/digital-twin/)
- ├── blood-tests.json
- └── ...
-```
-
-### Pattern 1: PATHS constant swap
-
-**What:** Replace `PATHS.digitalTwin` with `PATHS.meatspace` in the three affected service files.
-
-**When to use:** `PATHS.meatspace` already exists in `server/lib/fileUtils.js` (line 31) — no new constant needed.
-
-**Example (server/services/genome.js):**
-```javascript
-// Before (line 7)
-const GENOME_DIR = PATHS.digitalTwin;
-
-// After
-const GENOME_DIR = PATHS.meatspace;
-```
-
-Apply the same change to:
-- `server/services/clinvar.js` line 9: `const GENOME_DIR = PATHS.digitalTwin;`
-- `server/services/epigenetic.js` line 6: `const DATA_DIR = PATHS.digitalTwin;`
-
-### Pattern 2: Route comment update
-
-**What:** Replace all route comment path prefixes in `server/routes/genome.js`.
-
-**When to use:** 18 comment lines follow the format `// [METHOD] /api/digital-twin/genome[/suffix]`.
-
-**Example (routes/genome.js line 19):**
-```javascript
-// Before
-// GET /api/digital-twin/genome — Summary
-
-// After
-// GET /api/meatspace/genome — Summary
-```
-
-All 18 occurrences are a string replace of `/api/digital-twin/genome` → `/api/meatspace/genome`.
-
-### Pattern 3: IdentityTab navigation fix
-
-**What:** Update the "View Full Genome" button to navigate to the correct meatspace route.
-
-**Example (client/src/components/digital-twin/tabs/IdentityTab.jsx line 190):**
-```javascript
-// Before
-onClick={() => navigate('/digital-twin/genome')}
-
-// After
-onClick={() => navigate('/meatspace/genome')}
-```
-
-The `/meatspace/genome` tab is confirmed to exist: `MeatSpace.jsx` has a `case 'genome': return <GenomeTab />;` at line 29, and `Layout.jsx` includes `{ to: '/meatspace/genome', label: 'Genome', icon: Dna }` at line 134.
-
-### Anti-Patterns to Avoid
-
-- **Partial migration:** Do not change service paths without moving data files, or genome data will silently appear missing (the service uses `readFile(...).catch(() => null)` which returns null on missing file, appearing as "not uploaded").
-- **Leaving old files in digital-twin:** Old `data/digital-twin/genome.json` and `genome-raw.txt` will not be automatically cleaned up. They should be moved, not copied, to avoid confusing future debugging.
-- **Changing the actual route mount:** The Express mount at `server/index.js` line 209 (`app.use('/api/meatspace/genome', genomeRoutes)`) is already correct. Do not touch it.
-
-## Don't Hand-Roll
-
-| Problem | Don't Build | Use Instead | Why |
-|---------|-------------|-------------|-----|
-| File migration | Shell copy script | `fs.rename()` or git-tracked shell one-liner | Simple rename; no edge cases at this scale |
-| Path aliasing | New PATHS constant | Directly use existing `PATHS.meatspace` | PATHS.meatspace already defined at fileUtils.js:31 |
-
-**Key insight:** This phase contains zero new logic. Every change is a string substitution or constant swap in existing code. The risk is entirely operational: leaving the system in a state where data files are at the old path while code reads from the new path.
-
-## Common Pitfalls
-
-### Pitfall 1: Data files not moved with code change
-**What goes wrong:** genome.js starts reading from `data/meatspace/` but `genome.json` and `genome-raw.txt` are still in `data/digital-twin/`. `getGenomeSummary()` returns `{ uploaded: false }`. All genome features appear broken until files are moved.
-**Why it happens:** Code change and data migration are treated as separate steps and one gets forgotten.
-**How to avoid:** Include the file move (`mv data/digital-twin/genome*.* data/meatspace/ && mv data/digital-twin/clinvar*.* data/meatspace/`) as part of the same plan, verified before commit.
-**Warning signs:** After code deploy, genome page shows "Upload genome data to enable genetic analysis" despite data existing.
-
-### Pitfall 2: Clinvar files missed
-**What goes wrong:** `genome.json` and `genome-raw.txt` are moved but `clinvar-index.json` and `clinvar-meta.json` are left behind.
-**Why it happens:** Clinvar is a separate service (`clinvar.js`) and its files are easily overlooked when focusing on `genome.js`.
-**How to avoid:** Move all four files atomically: `genome.json`, `genome-raw.txt`, `clinvar-index.json`, `clinvar-meta.json`.
-**Warning signs:** Genome summary loads but ClinVar scan returns "No ClinVar data downloaded" even though it was downloaded previously.
-
-### Pitfall 3: Epigenetic data missed
-**What goes wrong:** `epigenetic.js` uses `PATHS.digitalTwin` but there are already epigenetic data files in `data/digital-twin/` (e.g., `epigenetic-tests.json` is in `data/meatspace/` — this needs verification).
-**Why it happens:** Assuming all three services read the same files.
-**How to avoid:** Before migrating, list what files each service reads: `genome.js` → `genome.json`, `genome-raw.txt`; `clinvar.js` → `clinvar-*.json`; `epigenetic.js` → its own files (check the service). Verify each file exists in the old path and move only those.
-**Warning signs:** Epigenetic tracker shows empty data after deploy.
-
-### Pitfall 4: Digital Twin page genome tab still referenced
-**What goes wrong:** If there are any other links to `/digital-twin/genome` that were not caught (e.g., in documentation, other tabs), they will silently route to the default Digital Twin tab (`/digital-twin/overview` via redirect) rather than showing an error.
-**Why it happens:** The `<Route path="digital-twin/:tab">` catch-all in App.jsx renders `OverviewTab` as default for unknown tabs.
-**How to avoid:** Search for all remaining occurrences of `/digital-twin/genome` in the client before marking GEN-02 complete.
-**Warning signs:** No 404, but wrong page renders when navigating to that old URL.
-
-## Code Examples
-
-### Current state of affected lines (verified by direct inspection)
-
-**server/routes/genome.js — 18 stale comment lines (lines 19-217):**
-```javascript
-// GET /api/digital-twin/genome — Summary ← line 19
-// POST /api/digital-twin/genome/upload ← line 25
-// POST /api/digital-twin/genome/scan ← line 39
-// POST /api/digital-twin/genome/search ← line 52
-// POST /api/digital-twin/genome/markers ← line 59
-// PUT /api/digital-twin/genome/markers/:id/notes ← line 66
-// DELETE /api/digital-twin/genome/markers/:id ← line 80
-// GET /api/digital-twin/genome/clinvar/status ← line 95
-// POST /api/digital-twin/genome/clinvar/sync ← line 101
-// POST /api/digital-twin/genome/clinvar/scan ← line 120
-// DELETE /api/digital-twin/genome/clinvar ← line 141
-// GET /api/digital-twin/genome/epigenetic ← line 149
-// GET /api/digital-twin/genome/epigenetic/recommendations ← line 155
-// GET /api/digital-twin/genome/epigenetic/compliance ← line 162
-// POST /api/digital-twin/genome/epigenetic ← line 169
-// POST /api/digital-twin/genome/epigenetic/:id/log ← line 176
-// PUT /api/digital-twin/genome/epigenetic/:id ← line 190
-// DELETE /api/digital-twin/genome/epigenetic/:id ← line 204
-// DELETE /api/digital-twin/genome ← line 217
-```
-
-**server/services/genome.js — data path (line 7):**
-```javascript
-const GENOME_DIR = PATHS.digitalTwin; // reads/writes data/digital-twin/
-```
-
-**server/services/clinvar.js — data path (line 9):**
-```javascript
-const GENOME_DIR = PATHS.digitalTwin; // reads/writes data/digital-twin/
-```
-
-**server/services/epigenetic.js — data path (line 6):**
-```javascript
-const DATA_DIR = PATHS.digitalTwin; // reads/writes data/digital-twin/
-```
-
-**client/src/components/digital-twin/tabs/IdentityTab.jsx — dead route (line 190):**
-```javascript
-onClick={() => navigate('/digital-twin/genome')} // tab does not exist in DigitalTwin.jsx
-```
-
-### Data files to migrate
-
-Current location (`data/digital-twin/`):
-- `genome.json` — upload metadata and saved markers
-- `genome-raw.txt` — raw 23andMe TSV file
-- `clinvar-index.json` — downloaded ClinVar index
-- `clinvar-meta.json` — ClinVar sync metadata
-
-Target location (`data/meatspace/`): same filenames.
-
-Note: `data/meatspace/` already exists and contains `blood-tests.json`, `config.json`, `daily-log.json`, `epigenetic-tests.json`, `eyes.json`. The genome files do not yet exist there.
-
-### PATHS.meatspace confirmation (fileUtils.js line 31)
-
-```javascript
-export const PATHS = {
- root: join(__lib_dirname, '../..'),
- data: join(__lib_dirname, '../../data'),
- // ...
- meatspace: join(__lib_dirname, '../../data/meatspace') // ← already defined
-};
-```
-
-## State of the Art
-
-| Old Approach | Current Approach | When Changed | Impact |
-|--------------|------------------|--------------|--------|
-| Genome data in `data/digital-twin/` | Genome data belongs in `data/meatspace/` | Partial migration already done (server mount, client API, Layout nav) | Phase 1 completes the migration by fixing services + IdentityTab |
-| Route mounted at `/api/digital-twin/genome` | Route mounted at `/api/meatspace/genome` | Already done in server/index.js | Server mount is correct; only route file comments are stale |
-
-**Deprecated/outdated:**
-- `/api/digital-twin/genome` path: no longer the mount point; comments in routes/genome.js are wrong
-- `navigate('/digital-twin/genome')` in IdentityTab: dead route — `/digital-twin/:tab` renders OverviewTab as default when tab is not recognized
-
-## Open Questions
-
-1. **Does epigenetic.js write its own separate files or share genome.json?**
- - What we know: `epigenetic.js` sets `const DATA_DIR = PATHS.digitalTwin` but `data/meatspace/` already has `epigenetic-tests.json`. It is possible epigenetic data is already being written to meatspace (if `epigenetic.js` uses a different path construction), or the epigenetic tests file is a sample/fixture.
- - What's unclear: Whether changing `epigenetic.js` to `PATHS.meatspace` would find existing data or new data.
- - Recommendation: Read `server/services/epigenetic.js` fully before writing the plan to confirm what filenames it uses and whether those files currently exist in `data/digital-twin/` vs `data/meatspace/`.
-
-2. **Should the "Genome" status chip in IdentityTab's completeness header be removed or kept?**
- - What we know: The `sectionKeys` array includes `'genome'`, which drives the completeness header chips (line 101). The genome card itself (lines 152-196) has the dead navigation button.
- - What's unclear: GEN-02 says "removed or redirected." Redirecting the button is simpler and preserves the completeness indicator. Removing the card entirely is more work and changes the UX.
- - Recommendation: Default to redirecting the button (navigate to `/meatspace/genome`) rather than removing the card. The status chip in the completeness header should be kept as it reflects genome data status and drives the percentage counter.
-
-## Sources
-
-### Primary (HIGH confidence)
-- Direct file inspection: `server/routes/genome.js` — 18 stale comment occurrences confirmed
-- Direct file inspection: `server/services/genome.js` line 7 — `PATHS.digitalTwin` confirmed
-- Direct file inspection: `server/services/clinvar.js` line 9 — `PATHS.digitalTwin` confirmed
-- Direct file inspection: `server/services/epigenetic.js` line 6 — `PATHS.digitalTwin` confirmed
-- Direct file inspection: `server/lib/fileUtils.js` line 31 — `PATHS.meatspace` confirmed present
-- Direct file inspection: `server/index.js` line 209 — `app.use('/api/meatspace/genome', genomeRoutes)` confirmed
-- Direct file inspection: `client/src/components/digital-twin/tabs/IdentityTab.jsx` line 190 — dead route confirmed
-- Direct file inspection: `client/src/pages/DigitalTwin.jsx` — no `genome` case in switch, confirmed dead
-- Direct file inspection: `client/src/pages/MeatSpace.jsx` line 29 — `case 'genome': return <GenomeTab />` confirmed live
-- Direct file inspection: `client/src/services/api.js` lines 1183-1228 — all API calls use `/meatspace/genome/...` already
-- Directory listing: `data/digital-twin/` contains `genome.json`, `genome-raw.txt`, `clinvar-index.json`, `clinvar-meta.json`
-- Directory listing: `data/meatspace/` does NOT contain genome files
-
-### Secondary (MEDIUM confidence)
-- None required — all findings from direct code inspection
-
-### Tertiary (LOW confidence)
-- None
-
-## Metadata
-
-**Confidence breakdown:**
-- Standard stack: HIGH — no new libraries; all changes use existing code patterns
-- Architecture: HIGH — all files directly inspected, no guessing
-- Pitfalls: HIGH — data migration risk is observable from directory inspection
-- Open question on epigenetic.js: MEDIUM — file exists in meatspace already but the service code needs full read to confirm
-
-**Research date:** 2026-02-26
-**Valid until:** Indefinitely (internal migration, no external dependencies)
diff --git a/.planning/phases/01-genome-migration-cleanup/01-VERIFICATION.md b/.planning/phases/01-genome-migration-cleanup/01-VERIFICATION.md
deleted file mode 100644
index 2667126fa3..0000000000
--- a/.planning/phases/01-genome-migration-cleanup/01-VERIFICATION.md
+++ /dev/null
@@ -1,93 +0,0 @@
----
-phase: 01-genome-migration-cleanup
-verified: 2026-02-26T22:00:00Z
-status: passed
-score: 5/5 must-haves verified
-re_verification: false
----
-
-# Phase 1: Genome Migration Cleanup Verification Report
-
-**Phase Goal:** Genome data reads from the correct directory and all stale digital-twin references are eliminated
-**Verified:** 2026-02-26
-**Status:** PASSED
-**Re-verification:** No — initial verification
-
-## Goal Achievement
-
-### Observable Truths
-
-| # | Truth | Status | Evidence |
-|---|-------|--------|----------|
-| 1 | All route comments in genome.js reference `/api/meatspace/genome/` (zero digital-twin references) | VERIFIED | 19 occurrences of `meatspace/genome` in `server/routes/genome.js`, 0 occurrences of `digital-twin`; grep returns exit 1 (no matches) |
-| 2 | IdentityTab "View Full Genome" button navigates to `/meatspace/genome` (a live route) | VERIFIED | Line 190: `onClick={() => navigate('/meatspace/genome')}` confirmed; `MeatSpace.jsx` line 29 confirms `case 'genome'` is live |
-| 3 | genome.js, clinvar.js, and epigenetic.js read/write data from `data/meatspace/` directory | VERIFIED | genome.js line 7: `GENOME_DIR = PATHS.meatspace`; clinvar.js line 9: `GENOME_DIR = PATHS.meatspace`; epigenetic.js line 6: `DATA_DIR = PATHS.meatspace`; zero `PATHS.digitalTwin` remaining |
-| 4 | Genome data files (genome.json, genome-raw.txt, clinvar-index.json, clinvar-meta.json) exist in `data/meatspace/` | VERIFIED | All four files confirmed on disk: genome.json (82KB), genome-raw.txt (16MB), clinvar-index.json (44MB), clinvar-meta.json (142B) |
-| 5 | No genome data files remain in `data/digital-twin/` | VERIFIED | `ls data/digital-twin/genome.json data/digital-twin/genome-raw.txt data/digital-twin/clinvar-index.json data/digital-twin/clinvar-meta.json` → "No such file or directory" for all four |
-
-**Score:** 5/5 truths verified
-
-### Required Artifacts
-
-| Artifact | Expected | Status | Details |
-|----------|----------|--------|---------|
-| `server/routes/genome.js` | Corrected route comments containing `/api/meatspace/genome` | VERIFIED | 19 meatspace references, 0 digital-twin references |
-| `server/services/genome.js` | Correct data directory via `PATHS.meatspace` | VERIFIED | Line 7: `const GENOME_DIR = PATHS.meatspace;` |
-| `server/services/clinvar.js` | Correct data directory via `PATHS.meatspace` | VERIFIED | Line 9: `const GENOME_DIR = PATHS.meatspace;` |
-| `server/services/epigenetic.js` | Correct data directory via `PATHS.meatspace` | VERIFIED | Line 6: `const DATA_DIR = PATHS.meatspace;` |
-| `client/src/components/digital-twin/tabs/IdentityTab.jsx` | Working genome navigation to `/meatspace/genome` | VERIFIED | Line 190: `navigate('/meatspace/genome')` |
-| `data/meatspace/genome.json` | Migrated genome metadata | VERIFIED | 82KB file, parses as valid JSON: `uploaded: true`, `savedMarkers` is an object with 117 entries |
-| `data/meatspace/genome-raw.txt` | Migrated raw genome file | VERIFIED | 16MB file present on disk |
-| `data/meatspace/clinvar-index.json` | Migrated ClinVar index | VERIFIED | 44MB file present on disk |
-| `data/meatspace/clinvar-meta.json` | Migrated ClinVar metadata | VERIFIED | 142B file present on disk |
-
-### Key Link Verification
-
-| From | To | Via | Status | Details |
-|------|----|-----|--------|---------|
-| `server/services/genome.js` | `data/meatspace/genome.json` | `GENOME_DIR = PATHS.meatspace` | WIRED | Pattern `PATHS\.meatspace` found at line 7; data file confirmed on disk |
-| `server/services/clinvar.js` | `data/meatspace/clinvar-index.json` | `GENOME_DIR = PATHS.meatspace` | WIRED | Pattern `PATHS\.meatspace` found at line 9; data file confirmed on disk |
-| `client/src/components/digital-twin/tabs/IdentityTab.jsx` | `MeatSpace.jsx` genome tab | `navigate('/meatspace/genome')` | WIRED | Pattern `navigate\('/meatspace/genome'\)` found at line 190; `MeatSpace.jsx` confirms live `case 'genome'` route |
-
-### Requirements Coverage
-
-| Requirement | Source Plan | Description | Status | Evidence |
-|-------------|------------|-------------|--------|----------|
-| GEN-01 | 01-01-PLAN.md | Route comments updated from `/api/digital-twin/genome/` to `/api/meatspace/genome/` | SATISFIED | 19 meatspace route comment references in `server/routes/genome.js`, 0 digital-twin references remain |
-| GEN-02 | 01-01-PLAN.md | IdentityTab Genome card removed or redirected to `/meatspace/genome` | SATISFIED | `IdentityTab.jsx` line 190 navigates to `/meatspace/genome`; destination route is live |
-| GEN-03 | 01-01-PLAN.md | genome.js data paths verified to read from correct directory | SATISFIED | All three services (genome.js, clinvar.js, epigenetic.js) use `PATHS.meatspace`; data files confirmed in `data/meatspace/` |
-
-All three GEN requirements fully satisfied. No orphaned requirements — REQUIREMENTS.md maps only GEN-01, GEN-02, GEN-03 to Phase 1, and all three are covered by plan 01-01.
-
-### Anti-Patterns Found
-
-No anti-patterns found. Scan of all modified files (`server/routes/genome.js`, `server/services/genome.js`, `server/services/clinvar.js`, `server/services/epigenetic.js`, `client/src/components/digital-twin/tabs/IdentityTab.jsx`) returned zero matches for TODO, FIXME, placeholder patterns, empty implementations, or console.log-only stubs.
-
-**Note on `docs/features/identity-system.md`:** The file contains references to `data/digital-twin/chronotype.json` and `data/digital-twin/identity.json` (lines 260-262). These are for a future identity orchestrator feature (not genome), are unrelated to this phase's scope, and do not constitute stale genome references. Not a concern.
-
-**Note on `data/meatspace/genome.json` `savedMarkers` structure:** The SUMMARY described `savedMarkers` as having `length: 117`, but it is an object keyed by UUID (not an array), so `.length` is `undefined`. The actual data is correct — 117 saved markers exist as keys in the object. This is a minor SUMMARY inaccuracy, not a code defect.
-
-### Human Verification Required
-
-None. All must-haves are programmatically verifiable and confirmed.
-
-The one item that would benefit from a manual smoke test is runtime behavior — confirming the genome API actually serves data successfully when hit over HTTP. This is a confidence check rather than a gap; the code paths are correctly wired.
-
-### Commits Verified
-
-| Hash | Task | Files |
-|------|------|-------|
-| 6503b70 | Task 1: service paths + route comments | genome.js, clinvar.js, epigenetic.js, routes/genome.js |
-| 912946f | Task 2: client navigation + docs | IdentityTab.jsx, docs/API.md, docs/features/identity-system.md |
-| Task 3 | Data file migration (disk only — gitignored) | data/meatspace/{genome.json,genome-raw.txt,clinvar-index.json,clinvar-meta.json} |
-
-Both code commits confirmed present in git history.
-
-### Gaps Summary
-
-No gaps. All five observable truths verified, all nine artifacts confirmed (exists, substantive, wired), all three key links confirmed wired, and all three requirements (GEN-01, GEN-02, GEN-03) are satisfied with implementation evidence.
-
----
-
-_Verified: 2026-02-26_
-_Verifier: Claude (gsd-verifier)_
diff --git a/.planning/phases/02-data-backup-recovery/02-01-PLAN.md b/.planning/phases/02-data-backup-recovery/02-01-PLAN.md
deleted file mode 100644
index 701f4cd096..0000000000
--- a/.planning/phases/02-data-backup-recovery/02-01-PLAN.md
+++ /dev/null
@@ -1,365 +0,0 @@
----
-phase: 02-data-backup-recovery
-plan: "01"
-type: execute
-wave: 1
-depends_on: []
-files_modified:
- - server/services/backup.js
- - server/services/backupScheduler.js
- - server/routes/backup.js
- - server/lib/validation.js
- - server/index.js
- - client/src/services/api.js
-autonomous: true
-requirements:
- - BAK-01
- - BAK-02
- - BAK-03
-
-must_haves:
- truths:
- - "Running POST /api/backup/run copies changed files from ./data/ to the configured external drive path via rsync"
- - "A manifest.json with SHA-256 hashes exists inside each snapshot directory after backup completes"
- - "Backup runs automatically on a daily cron schedule registered with eventScheduler"
- - "GET /api/backup/status returns last backup time, next scheduled time, and current status"
- - "GET /api/backup/snapshots returns a list of all snapshots with creation time and file count"
- artifacts:
- - path: "server/services/backup.js"
- provides: "Core backup engine: runBackup, generateManifest, listSnapshots, restoreSnapshot, getState"
- exports: ["runBackup", "generateManifest", "listSnapshots", "restoreSnapshot", "getState", "getNextRunTime"]
- - path: "server/services/backupScheduler.js"
- provides: "Scheduler registration mirroring brainScheduler.js pattern"
- exports: ["startBackupScheduler", "stopBackupScheduler"]
- - path: "server/routes/backup.js"
- provides: "REST API: GET /status, POST /run, GET /snapshots, POST /restore"
- - path: "server/lib/validation.js"
- provides: "Zod schemas: backupConfigSchema, restoreRequestSchema"
- contains: "backupConfigSchema"
- - path: "client/src/services/api.js"
- provides: "Client API functions: getBackupStatus, triggerBackup, getBackupSnapshots, restoreBackup"
- key_links:
- - from: "server/routes/backup.js"
- to: "server/services/backup.js"
- via: "import and call runBackup, listSnapshots, getState, restoreSnapshot"
- pattern: "import.*backup"
- - from: "server/services/backupScheduler.js"
- to: "server/services/eventScheduler.js"
- via: "schedule() call with cron type"
- pattern: "eventScheduler.*schedule"
- - from: "server/index.js"
- to: "server/routes/backup.js"
- via: "app.use('/api/backup', backupRoutes)"
- pattern: "app\\.use.*backup"
- - from: "server/index.js"
- to: "server/services/backupScheduler.js"
- via: "startBackupScheduler() call at server startup"
- pattern: "startBackupScheduler"
----
-
-<objective>
-Build the backup engine, scheduler, REST routes, and client API functions for PortOS data backup.
-
-Purpose: Establish the core backup infrastructure — rsync-based incremental copy from `./data/` to an external drive, SHA-256 manifest generation for integrity verification, cron scheduling via the existing eventScheduler, and a complete REST API. This enables Plan 02 to wire up the dashboard widget and restore UI.
-
-Output: Working backup service with scheduler, validated routes, and client API functions ready for widget consumption.
-</objective>
-
-<execution_context>
-@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
-@/Users/antic/.claude/get-shit-done/templates/summary.md
-</execution_context>
-
-<context>
[email protected]/phases/02-data-backup-recovery/02-RESEARCH.md
-
-<interfaces>
-<!-- Key types and contracts the executor needs. Extracted from codebase. -->
-<!-- Executor should use these directly -- no codebase exploration needed. -->
-
-From server/services/eventScheduler.js:
-```javascript
-export {
- schedule, // schedule({ id, type, cron, intervalMs, delayMs, handler, metadata })
- cancel, // cancel(id) -> boolean
- pause, // pause(id) -> boolean
- resume, // resume(id) -> boolean
- getScheduledEvents, // -> Array<{ id, type, active, nextRunAt, lastRunAt, runCount, metadata }>
- getEvent, // getEvent(id) -> { id, type, active, cron, intervalMs, nextRunAt, lastRunAt, runCount, metadata } | null
- getHistory,
- getStats,
- cancelAll,
- triggerNow, // triggerNow(id) -> Promise<boolean>
- parseCronToNextRun,
- MAX_TIMEOUT
-}
-```
-
-From server/services/brainScheduler.js (pattern to mirror):
-```javascript
-export function startBrainScheduler() { ... } // Called at server startup in index.js
-export function stopBrainScheduler() { ... }
-```
-
-From server/services/settings.js:
-```javascript
-export const getSettings = load; // -> Promise<object> (reads data/settings.json)
-export const updateSettings = async (patch) => { ... }; // -> Promise<merged>
-```
-
-From server/lib/fileUtils.js:
-```javascript
-export const PATHS = {
- root: join(__lib_dirname, '../..'),
- data: join(__lib_dirname, '../../data'),
- // ... other paths ...
- meatspace: join(__lib_dirname, '../../data/meatspace')
-};
-export async function ensureDir(dir) { ... }
-export async function readJSONFile(filePath, defaultValue = null, { allowArray, logError } = {}) { ... }
-```
-
-From server/lib/errorHandler.js:
-```javascript
-export class ServerError extends Error { ... }
-export function asyncHandler(fn) { ... } // Wraps async route handlers
-export function normalizeError(err) { ... }
-```
-
-From server/lib/validation.js:
-```javascript
-export function validateRequest(schema, data) { ... } // Throws ServerError on failure
-```
-
-From server/index.js (route registration pattern):
-```javascript
-import backupRoutes from './routes/backup.js'; // alphabetical with other imports
-app.use('/api/backup', backupRoutes); // alphabetical among app.use() calls
-import { startBackupScheduler } from './services/backupScheduler.js';
-startBackupScheduler(); // after startBrainScheduler() call on line 228
-```
-
-From client/src/services/api.js (pattern):
-```javascript
-async function request(endpoint, options = {}) { ... } // base request function
-export const getBackupStatus = (options) => request('/backup/status', options);
-```
-</interfaces>
-</context>
-
-<tasks>
-
-<task type="auto">
- <name>Task 1: Create backup service and scheduler</name>
- <files>
- server/services/backup.js
- server/services/backupScheduler.js
- </files>
- <action>
-Create `server/services/backup.js` with these exports:
-
-1. **`runBackup(destPath, io = null)`** — Core backup function:
- - Check `isRunning` flag; if true, log and return `{ skipped: true }`.
- - Validate `destPath` exists with `fs.access(destPath)`. If missing, throw `new Error('Backup destination not found: ${destPath}')`.
- - Set `isRunning = true`.
- - Create snapshot ID from ISO timestamp with colons replaced: `new Date().toISOString().replace(/:/g, '-').replace(/\..+/, '')`.
- - Create snapshot dir: `join(destPath, 'snapshots', snapshotId)` and data subdir: `join(snapshotDir, 'data')`.
- - Spawn rsync: `spawn('/usr/bin/rsync', ['--archive', '--itemize-changes', srcDir + '/', dataDestDir], { shell: false })`.
- - Collect changed file lines from stdout (lines starting with `>` or `<`).
- - Accept exit codes 0 and 24 as success (24 = vanished files, normal for active system). Reject on other codes.
- - After rsync, call `generateManifest(dataDestDir, join(snapshotDir, 'manifest.json'))`.
- - Save state via `saveState({ lastRun, lastSnapshotId, status: 'ok', filesChanged, error: null })`.
- - Set `isRunning = false` in a finally-equivalent pattern (set in both success path and error path).
- - If `io` is provided, emit `backup:started` and `backup:completed` events.
- - Use `PATHS.data` from `../lib/fileUtils.js` as source directory.
-
-2. **`generateManifest(snapshotDataDir, manifestPath)`** — Walk the snapshot data directory recursively:
- - Use `fs.readdir` with `{ recursive: true }` and `fs.stat` to find regular files.
- - For files under 512KB: `createHash('sha256').update(await readFile(filePath)).digest('hex')`.
- - For files 512KB+: use streaming hash with `fs.createReadStream(filePath)` piped to `createHash('sha256')`.
- - Write `manifest.json`: `{ generatedAt, fileCount, files: { relativePath: sha256Hash } }`.
- - Return the manifest object.
-
-3. **`listSnapshots(destPath)`** — Read `join(destPath, 'snapshots')` directory, for each entry read its `manifest.json` if exists, return `[{ id, createdAt, fileCount }]` sorted newest-first.
-
-4. **`restoreSnapshot(destPath, snapshotId, { dryRun = true, subdirFilter = null } = {})`** — Reverse rsync from snapshot back to `PATHS.data`:
- - Build flags array: if `dryRun`, add `'--dry-run'`. Always include `'--archive'`, `'--itemize-changes'`.
- - If `subdirFilter`, add `--include=${subdirFilter}/***`, `--include=*/`, `--exclude=*`.
- - Spawn rsync from `join(destPath, 'snapshots', snapshotId, 'data')` to `PATHS.data`.
- - Return `{ dryRun, snapshotId, subdirFilter, changedFiles }`.
-
-5. **`getState()`** — Read `join(PATHS.data, 'backup', 'state.json')` via `readJSONFile` with default `{ lastRun: null, status: 'never', lastSnapshotId: null, filesChanged: 0, error: null }`.
-
-6. **`saveState(patch)`** — Read current state, merge patch, write back to `join(PATHS.data, 'backup', 'state.json')`. Ensure `data/backup/` directory exists via `ensureDir`.
-
-7. **`getNextRunTime()`** — Import `getEvent` from `eventScheduler.js`, call `getEvent('backup-daily')`, return `event?.nextRunAt ? new Date(event.nextRunAt).toISOString() : null`.
-
-Internal helper **`runRsync(srcDir, destDir, flags = [])`** — as described in research Pattern 2. Use `spawn('/usr/bin/rsync', ...)` with `shell: false`.
-
-Logging: Use single-line emoji format per CLAUDE.md convention with `console.log()`:
-- `console.log('backup starting: snapshot ${snapshotId}')` (with appropriate emoji)
-- `console.log('backup rsync complete: ${changed.length} files changed (exit ${code})')` (with appropriate emoji)
-- `console.log('backup manifest: ${manifest.fileCount} files')` (with appropriate emoji)
-
-Create `server/services/backupScheduler.js` mirroring `brainScheduler.js` pattern:
-
-1. **`startBackupScheduler()`** — Import `schedule` from `eventScheduler.js` and `getSettings` from `settings.js`. Call `schedule({ id: 'backup-daily', type: 'cron', cron: settings.backup?.cronExpression || '0 2 * * *', handler: async () => { ... call runBackup ... }, metadata: { source: 'backupScheduler' } })`. Only schedule if `settings.backup?.enabled !== false` and `settings.backup?.destPath` exists. Log startup.
-
-2. **`stopBackupScheduler()`** — Import `cancel` from `eventScheduler.js`, cancel `'backup-daily'`.
-
-No try/catch blocks — errors bubble up per CLAUDE.md convention. The only exceptions are the `.catch()` patterns for file reads returning defaults (e.g., `readdir(...).catch(() => [])` in listSnapshots) which are acceptable project patterns.
- </action>
- <verify>
- <automated>cd /Users/antic/github.com/atomantic/PortOS/server && node -e "import('./services/backup.js').then(m => { console.log('exports:', Object.keys(m)); })" && node -e "import('./services/backupScheduler.js').then(m => { console.log('exports:', Object.keys(m)); })"</automated>
- </verify>
- <done>
- - backup.js exports: runBackup, generateManifest, listSnapshots, restoreSnapshot, getState, saveState, getNextRunTime
- - backupScheduler.js exports: startBackupScheduler, stopBackupScheduler
- - No syntax errors on import
- </done>
-</task>
-
-<task type="auto">
- <name>Task 2: Create routes, validation schemas, wire into server, and add client API functions</name>
- <files>
- server/routes/backup.js
- server/lib/validation.js
- server/index.js
- client/src/services/api.js
- </files>
- <action>
-**1. Add Zod schemas to `server/lib/validation.js`:**
-
-Add at the end of the file (before the closing comment if any), in a new section:
-
-```javascript
-// =============================================================================
-// BACKUP SCHEMAS
-// =============================================================================
-
-export const backupConfigSchema = z.object({
- destPath: z.string().min(1),
- cronExpression: z.string().optional(),
- enabled: z.boolean().optional().default(true)
-});
-
-export const restoreRequestSchema = z.object({
- snapshotId: z.string().min(1),
- subdirFilter: z.string().optional().nullable(),
- dryRun: z.boolean().optional().default(true)
-});
-```
-
-**2. Create `server/routes/backup.js`:**
-
-```javascript
-import { Router } from 'express';
-import { asyncHandler } from '../lib/errorHandler.js';
-import { validateRequest } from '../lib/validation.js';
-import { restoreRequestSchema } from '../lib/validation.js';
-import * as backup from '../services/backup.js';
-import { getSettings } from '../services/settings.js';
-
-const router = Router();
-
-// GET /api/backup/status
-router.get('/status', asyncHandler(async (req, res) => {
- const state = await backup.getState();
- const settings = await getSettings();
- const nextRun = backup.getNextRunTime();
- res.json({ ...state, destPath: settings.backup?.destPath ?? null, nextRun });
-}));
-
-// POST /api/backup/run
-router.post('/run', asyncHandler(async (req, res) => {
- const settings = await getSettings();
- const io = req.app.get('io');
- const result = await backup.runBackup(settings.backup?.destPath, io);
- res.json(result);
-}));
-
-// GET /api/backup/snapshots
-router.get('/snapshots', asyncHandler(async (req, res) => {
- const settings = await getSettings();
- const snapshots = await backup.listSnapshots(settings.backup?.destPath);
- res.json(snapshots);
-}));
-
-// POST /api/backup/restore
-router.post('/restore', asyncHandler(async (req, res) => {
- const { snapshotId, subdirFilter, dryRun } = validateRequest(restoreRequestSchema, req.body);
- const settings = await getSettings();
- const result = await backup.restoreSnapshot(settings.backup?.destPath, snapshotId, { dryRun, subdirFilter });
- res.json(result);
-}));
-
-export default router;
-```
-
-**3. Wire into `server/index.js`:**
-
-- Add import alphabetically among the existing route imports (after `autobiographyRoutes`, before `brainRoutes`):
- `import backupRoutes from './routes/backup.js';`
-
-- Add route registration alphabetically among `app.use()` calls (after `/api/attachments` and before `/api/brain`):
- `app.use('/api/backup', backupRoutes);`
-
-- Add scheduler import alongside the `brainScheduler` import:
- `import { startBackupScheduler } from './services/backupScheduler.js';`
-
-- Add `startBackupScheduler();` call right after the existing `startBrainScheduler();` call (around line 228-229).
-
-**4. Add client API functions to `client/src/services/api.js`:**
-
-Add these exports at an appropriate location (alphabetically near other domain-grouped functions, or at the end before the file's last export group):
-
-```javascript
-// Backup
-export const getBackupStatus = (options) => request('/backup/status', options);
-export const triggerBackup = () => request('/backup/run', { method: 'POST' });
-export const getBackupSnapshots = (options) => request('/backup/snapshots', options);
-export const restoreBackup = (data) => request('/backup/restore', { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } });
-```
-
-Note: Check if `request()` already sets `Content-Type: application/json` header by default (it likely does based on the existing patterns). If so, omit the explicit headers in `restoreBackup`. Match the existing pattern in the file.
- </action>
- <verify>
- <automated>cd /Users/antic/github.com/atomantic/PortOS/server && npm test 2>&1 | tail -5</automated>
- </verify>
- <done>
- - All existing server tests pass (no regressions)
- - `server/routes/backup.js` exists with GET /status, POST /run, GET /snapshots, POST /restore handlers
- - `server/lib/validation.js` contains backupConfigSchema and restoreRequestSchema
- - `server/index.js` imports and mounts backup routes at `/api/backup`
- - `server/index.js` calls `startBackupScheduler()` at startup
- - `client/src/services/api.js` exports getBackupStatus, triggerBackup, getBackupSnapshots, restoreBackup
- </done>
-</task>
-
-</tasks>
-
-<verification>
-1. `node -e "import('./server/services/backup.js').then(m => console.log(Object.keys(m)))"` — confirms exports
-2. `node -e "import('./server/services/backupScheduler.js').then(m => console.log(Object.keys(m)))"` — confirms exports
-3. `cd server && npm test` — all existing tests pass (no regressions from validation.js or index.js changes)
-4. `grep -c 'backupConfigSchema\|restoreRequestSchema' server/lib/validation.js` — returns 2+
-5. `grep 'api/backup' server/index.js` — confirms route mount
-6. `grep 'startBackupScheduler' server/index.js` — confirms scheduler wired
-7. `grep 'getBackupStatus\|triggerBackup\|getBackupSnapshots\|restoreBackup' client/src/services/api.js` — confirms client functions
-</verification>
-
-<success_criteria>
-- backup.js and backupScheduler.js exist and import without errors
-- Validation schemas added to validation.js
-- Routes mounted at /api/backup in index.js
-- Scheduler starts at server boot
-- Client API functions available for widget consumption
-- All existing server tests pass
-</success_criteria>
-
-<output>
-After completion, create `.planning/phases/02-data-backup-recovery/02-01-SUMMARY.md`
-</output>
diff --git a/.planning/phases/02-data-backup-recovery/02-01-SUMMARY.md b/.planning/phases/02-data-backup-recovery/02-01-SUMMARY.md
deleted file mode 100644
index bbe44d738c..0000000000
--- a/.planning/phases/02-data-backup-recovery/02-01-SUMMARY.md
+++ /dev/null
@@ -1,109 +0,0 @@
----
-phase: 02-data-backup-recovery
-plan: "01"
-subsystem: backup
-tags: [backup, rsync, scheduler, api, validation]
-dependency_graph:
- requires:
- - server/services/eventScheduler.js
- - server/services/settings.js
- - server/lib/fileUtils.js
- - server/lib/errorHandler.js
- - server/lib/validation.js
- provides:
- - server/services/backup.js
- - server/services/backupScheduler.js
- - server/routes/backup.js
- affects:
- - server/index.js
- - server/lib/validation.js
- - client/src/services/api.js
-tech_stack:
- added:
- - rsync (system binary, /usr/bin/rsync)
- - Node.js crypto.createHash (SHA-256)
- - Node.js fs.createReadStream (streaming hash for large files)
- patterns:
- - Rsync incremental backup with itemize-changes and exit code 24 tolerance
- - SHA-256 file manifest with size-based streaming threshold (512KB)
- - eventScheduler cron integration (mirroring brainScheduler pattern)
- - asyncHandler + validateRequest route pattern
-key_files:
- created:
- - server/services/backup.js
- - server/services/backupScheduler.js
- - server/routes/backup.js
- modified:
- - server/lib/validation.js
- - server/index.js
- - client/src/services/api.js
-decisions:
- - "Used fs.createReadStream (not fs/promises) for streaming hash — createReadStream is only available on the synchronous fs module"
- - "Exit code 24 accepted as success — rsync code 24 means files vanished mid-transfer, normal for active systems"
- - "startBackupScheduler is async (reads settings) and called with .catch() in index.js to match other async inits"
-metrics:
- duration: 135s
- completed: 2026-02-26
- tasks_completed: 2
- files_created: 3
- files_modified: 3
----
-
-# Phase 02 Plan 01: Backup Engine and API Summary
-
-**One-liner:** Rsync-based incremental backup engine with SHA-256 manifests, daily cron scheduling via eventScheduler, and a complete REST + client API.
-
-## What Was Built
-
-A complete backup infrastructure for PortOS data:
-
-1. **`server/services/backup.js`** — Core backup engine with 7 exports:
- - `runBackup(destPath, io)` — spawns rsync to copy `data/` to a timestamped snapshot directory, generates manifest, saves state
- - `generateManifest(snapshotDataDir, manifestPath)` — walks snapshot files, hashes each (streaming for 512KB+), writes `manifest.json`
- - `listSnapshots(destPath)` — reads snapshot directories, returns metadata sorted newest-first
- - `restoreSnapshot(destPath, snapshotId, { dryRun, subdirFilter })` — reverse rsync from snapshot back to live data
- - `getState()` / `saveState(patch)` — persist backup state to `data/backup/state.json`
- - `getNextRunTime()` — delegates to eventScheduler's `getEvent('backup-daily')`
-
-2. **`server/services/backupScheduler.js`** — Reads settings, conditionally registers `backup-daily` cron with eventScheduler. Skips if disabled or no destPath configured.
-
-3. **`server/routes/backup.js`** — 4 REST endpoints:
- - `GET /api/backup/status` — state + destPath + nextRun
- - `POST /api/backup/run` — trigger immediate backup
- - `GET /api/backup/snapshots` — list snapshots
- - `POST /api/backup/restore` — restore with dryRun support
-
-4. **`server/lib/validation.js`** — Added `backupConfigSchema` and `restoreRequestSchema` Zod schemas.
-
-5. **`server/index.js`** — Routes mounted at `/api/backup`; `startBackupScheduler()` called after `startBrainScheduler()`.
-
-6. **`client/src/services/api.js`** — Added `getBackupStatus`, `triggerBackup`, `getBackupSnapshots`, `restoreBackup`.
-
-## Deviations from Plan
-
-### Auto-fixed Issues
-
-**1. [Rule 3 - Blocking] Fixed `createReadStream` import from wrong module**
-- **Found during:** Task 1 verification
-- **Issue:** `createReadStream` is not exported by `fs/promises`; initial code imported it from there
-- **Fix:** Split import — `createReadStream` from `'fs'`, file stat/read functions from `'fs/promises'`
-- **Files modified:** `server/services/backup.js`
-- **Commit:** 8a01c2b (fixed inline before committing)
-
-## Commits
-
-| Task | Name | Commit | Key Files |
-|------|------|--------|-----------|
-| 1 | Backup service and scheduler | 8a01c2b | server/services/backup.js, server/services/backupScheduler.js |
-| 2 | Routes, validation, server wiring, client API | 523ffd7 | server/routes/backup.js, server/lib/validation.js, server/index.js, client/src/services/api.js |
-
-## Verification Results
-
-- backup.js imports without errors: exports generateManifest, getNextRunTime, getState, listSnapshots, restoreSnapshot, runBackup, saveState
-- backupScheduler.js imports without errors: exports startBackupScheduler, stopBackupScheduler
-- All 42 server test files pass (1192 tests) — no regressions
-- validation.js contains backupConfigSchema and restoreRequestSchema (2 schema exports)
-- server/index.js mounts /api/backup and calls startBackupScheduler()
-- client/src/services/api.js exports all 4 backup API functions
-
-## Self-Check: PASSED
diff --git a/.planning/phases/02-data-backup-recovery/02-02-PLAN.md b/.planning/phases/02-data-backup-recovery/02-02-PLAN.md
deleted file mode 100644
index 621427db0f..0000000000
--- a/.planning/phases/02-data-backup-recovery/02-02-PLAN.md
+++ /dev/null
@@ -1,271 +0,0 @@
----
-phase: 02-data-backup-recovery
-plan: "02"
-type: execute
-wave: 2
-depends_on:
- - "02-01"
-files_modified:
- - client/src/components/BackupWidget.jsx
- - client/src/pages/Dashboard.jsx
-autonomous: false
-requirements:
- - BAK-04
- - BAK-05
- - BAK-06
- - BAK-07
-
-must_haves:
- truths:
- - "Dashboard displays a backup widget showing last backup time, next scheduled time, and health status with green/yellow/red indicator"
- - "User can click a button in the widget to trigger a manual backup and sees toast feedback"
- - "User can view a list of snapshots and initiate a restore with dry-run preview"
- - "User can selectively restore a specific directory (e.g., brain/) from a snapshot"
- artifacts:
- - path: "client/src/components/BackupWidget.jsx"
- provides: "Dashboard widget: status display, manual trigger, health indicator, snapshot list, restore UI"
- min_lines: 80
- - path: "client/src/pages/Dashboard.jsx"
- provides: "BackupWidget imported and rendered in dashboard grid"
- contains: "BackupWidget"
- key_links:
- - from: "client/src/components/BackupWidget.jsx"
- to: "client/src/services/api.js"
- via: "import and call getBackupStatus, triggerBackup, getBackupSnapshots, restoreBackup"
- pattern: "api\\.getBackupStatus|api\\.triggerBackup"
- - from: "client/src/components/BackupWidget.jsx"
- to: "client/src/hooks/useAutoRefetch.js"
- via: "useAutoRefetch hook for status polling"
- pattern: "useAutoRefetch"
- - from: "client/src/pages/Dashboard.jsx"
- to: "client/src/components/BackupWidget.jsx"
- via: "import and render in JSX grid"
- pattern: "import BackupWidget"
----
-
-<objective>
-Build the dashboard backup widget with health status display, manual backup trigger, snapshot listing, and restore UI with dry-run preview and selective directory restore.
-
-Purpose: Give the user visibility into backup health and one-click control over backup/restore operations directly from the dashboard. This completes the user-facing half of the backup system.
-
-Output: BackupWidget component rendered on the Dashboard, providing all BAK-04 through BAK-07 functionality.
-</objective>
-
-<execution_context>
-@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
-@/Users/antic/.claude/get-shit-done/templates/summary.md
-</execution_context>
-
-<context>
[email protected]/phases/02-data-backup-recovery/02-RESEARCH.md
[email protected]/phases/02-data-backup-recovery/02-01-SUMMARY.md
-
-<interfaces>
-<!-- Key types and contracts the executor needs from Plan 02-01. -->
-
-From client/src/services/api.js (added by Plan 02-01):
-```javascript
-export const getBackupStatus = (options) => request('/backup/status', options);
-export const triggerBackup = () => request('/backup/run', { method: 'POST' });
-export const getBackupSnapshots = (options) => request('/backup/snapshots', options);
-export const restoreBackup = (data) => request('/backup/restore', { method: 'POST', body: JSON.stringify(data) });
-```
-
-API response shapes:
-
-GET /api/backup/status:
-```json
-{
- "lastRun": "2026-02-26T02:00:00.000Z",
- "lastSnapshotId": "2026-02-26T02-00-00",
- "status": "ok" | "running" | "error" | "never",
- "filesChanged": 12,
- "error": null | "error message",
- "destPath": "/Volumes/BackupDrive/PortOS",
- "nextRun": "2026-02-27T02:00:00.000Z"
-}
-```
-
-GET /api/backup/snapshots:
-```json
-[
- { "id": "2026-02-26T02-00-00", "createdAt": "2026-02-26T02-00-00", "fileCount": 245 },
- { "id": "2026-02-25T02-00-00", "createdAt": "2026-02-25T02-00-00", "fileCount": 240 }
-]
-```
-
-POST /api/backup/restore (request):
-```json
-{ "snapshotId": "2026-02-26T02-00-00", "dryRun": true, "subdirFilter": "brain" }
-```
-
-POST /api/backup/restore (response):
-```json
-{ "dryRun": true, "snapshotId": "2026-02-26T02-00-00", "subdirFilter": "brain", "changedFiles": [">f..t...... brain/captures.json"] }
-```
-
-From client/src/hooks/useAutoRefetch.js:
-```javascript
-export function useAutoRefetch(fetchFn, intervalMs) {
- // Returns { data, loading }
-}
-```
-
-From client/src/pages/Dashboard.jsx (existing imports and widget grid):
-```jsx
-import SystemHealthWidget from '../components/SystemHealthWidget';
-import CosDashboardWidget from '../components/CosDashboardWidget';
-// ... other widget imports ...
-// Widgets rendered inside a grid layout
-```
-
-Design tokens from CLAUDE.md:
-```
-port-bg: #0f0f0f port-card: #1a1a1a
-port-border: #2a2a2a port-accent: #3b82f6
-port-success: #22c55e port-warning: #f59e0b
-port-error: #ef4444
-```
-</interfaces>
-</context>
-
-<tasks>
-
-<task type="auto">
- <name>Task 1: Create BackupWidget component and add to Dashboard</name>
- <files>
- client/src/components/BackupWidget.jsx
- client/src/pages/Dashboard.jsx
- </files>
- <action>
-**Create `client/src/components/BackupWidget.jsx`:**
-
-A functional React component using `memo` (consistent with other widgets). Structure:
-
-**1. Status Section (always visible):**
-- Use `useAutoRefetch(() => api.getBackupStatus({ silent: true }).catch(() => null), 60000)` for status polling.
-- Show health indicator dot: green (`port-success`) if last run < 25 hours ago with no error, yellow (`port-warning`) if 25-49 hours or status is 'never', red (`port-error`) if > 49 hours or status is 'error'.
-- Display: "Last backup: {relative time}" (e.g., "2 hours ago"), "Next: {relative time}" (e.g., "in 22 hours"), destination path.
-- If `status === 'never'`, show "No backups yet" with guidance text.
-- If `status === 'running'`, show a spinner/indicator.
-- If `status === 'error'`, show the error message in red text.
-
-**2. Manual Trigger Button (BAK-05):**
-- Button labeled "Backup Now".
-- On click: call `api.triggerBackup()`, show `toast('Backup started', { icon: '...' })` on success, `toast.error('Backup failed: ' + err.message)` on failure. Use react-hot-toast (already imported pattern in api.js).
-- Disable button while status is 'running'.
-- No `window.alert` or `window.confirm` per CLAUDE.md.
-
-**3. Snapshots & Restore Section (expandable/collapsible):**
-- A toggle to show/hide snapshot list (keeps widget compact by default).
-- When expanded, fetch snapshots via `api.getBackupSnapshots()`.
-- List snapshots with date and file count.
-- Each snapshot has a "Restore" action that expands an inline restore panel (not a modal without URL per CLAUDE.md, but since this is a widget action within the dashboard, an inline expandable is acceptable).
-
-**4. Restore Panel (BAK-06, BAK-07):**
-- Shows for the selected snapshot.
-- Has a text input for `subdirFilter` (optional, placeholder: "e.g., brain" — for selective directory restore).
-- "Preview" button: calls `api.restoreBackup({ snapshotId, dryRun: true, subdirFilter: filter || null })`. Displays the list of files that would change.
-- "Restore" button (only enabled after preview): calls `api.restoreBackup({ snapshotId, dryRun: false, subdirFilter })`. Shows toast on completion.
-- The dry-run preview list shows each changed file path in a scrollable container.
-
-**5. Health computation helper function (not a hook, just a pure function):**
-```javascript
-function computeHealth(status) {
- if (!status || status.status === 'error') return 'critical';
- if (status.status === 'never') return 'warning';
- if (status.status === 'running') return 'healthy';
- if (!status.lastRun) return 'warning';
- const hoursSince = (Date.now() - new Date(status.lastRun).getTime()) / (1000 * 60 * 60);
- if (hoursSince < 25) return 'healthy';
- if (hoursSince < 49) return 'warning';
- return 'critical';
-}
-```
-
-**6. Relative time helper:**
-Use a simple relative time formatter (compute from Date.now() - target). Examples: "2 hours ago", "in 22 hours", "3 days ago". No external dependency needed — a small pure function is sufficient.
-
-**Styling:** Use Tailwind classes with the project's design tokens:
-- Widget card: `bg-port-card border border-port-border rounded-lg p-4`
-- Health dot: `w-2.5 h-2.5 rounded-full` with `bg-port-success`, `bg-port-warning`, or `bg-port-error`
-- Buttons: Match existing button patterns in the codebase (look at SystemHealthWidget or other widgets for consistent styling)
-- Text: `text-gray-400` for secondary, `text-white` for primary
-
-**Wire into `client/src/pages/Dashboard.jsx`:**
-
-- Add import alphabetically among widget imports (after `BrailleSpinner`, before `CosDashboardWidget`):
- `import BackupWidget from '../components/BackupWidget';`
-
-- Add `<BackupWidget />` in the dashboard grid. Place it near SystemHealthWidget (it's infrastructure status). Look at the existing grid layout and add it in a logical position — after SystemHealthWidget is a good spot since both are system-status widgets.
- </action>
- <verify>
- <automated>cd /Users/antic/github.com/atomantic/PortOS && grep -c 'BackupWidget' client/src/pages/Dashboard.jsx && grep -c 'useAutoRefetch\|getBackupStatus\|triggerBackup\|restoreBackup' client/src/components/BackupWidget.jsx</automated>
- </verify>
- <done>
- - BackupWidget.jsx exists with health status display, manual trigger button, snapshot list, and restore panel
- - Dashboard.jsx imports and renders BackupWidget
- - Health indicator uses green/yellow/red color coding
- - Manual trigger uses toast notifications (no window.alert)
- - Restore supports dry-run preview and selective directory filter
- </done>
-</task>
-
-<task type="checkpoint:human-verify" gate="blocking">
- <name>Task 2: Verify complete backup system end-to-end</name>
- <files>client/src/components/BackupWidget.jsx</files>
- <action>
-Human verification of the complete backup system. Before requesting verification, run these automated pre-checks:
-
-1. `curl -s http://localhost:5554/api/backup/status | node -e "process.stdin.on('data',d=>{const j=JSON.parse(d);console.log('status:',j.status,'nextRun:',j.nextRun)})"` -- confirms API responds
-2. `mkdir -p /tmp/portos-backup-test && curl -s -X PUT http://localhost:5554/api/settings -H 'Content-Type: application/json' -d '{"backup":{"destPath":"/tmp/portos-backup-test","enabled":true}}'` -- configure test destination
-3. `curl -s -X POST http://localhost:5554/api/backup/run | node -e "process.stdin.on('data',d=>{const j=JSON.parse(d);console.log('snapshot:',j.snapshotId,'files:',j.fileCount)})"` -- run a test backup
-4. `ls /tmp/portos-backup-test/snapshots/` -- verify snapshot directory created
-
-Then request human verification:
-- Open the PortOS dashboard in browser
-- Verify BackupWidget is visible with health indicator (green after test backup)
-- Click "Backup Now" button -- verify toast notification appears
-- Expand snapshot list -- verify snapshot appears with file count
-- Select a snapshot, type "brain" in filter field, click "Preview" -- verify dry-run file list appears
- </action>
- <verify>
- <automated>curl -s http://localhost:5554/api/backup/status | node -e "process.stdin.on('data',d=>{const j=JSON.parse(d);console.log(j.status!=='never'?'PASS':'FAIL')})"</automated>
- </verify>
- <done>
- - Dashboard shows BackupWidget with correct health status
- - Manual backup trigger works end-to-end
- - Snapshot list displays correctly
- - Dry-run restore preview shows expected file changes
- - User has approved the visual and functional verification
- </done>
-</task>
-
-</tasks>
-
-<verification>
-1. Dashboard shows BackupWidget with health status indicator
-2. Manual backup trigger works end-to-end (rsync copies files, manifest generated)
-3. Snapshot list displays with file counts
-4. Dry-run restore preview shows changed files
-5. Selective directory filter limits restore scope
-6. No window.alert or window.confirm usage
-7. Toast notifications for all user actions
-8. Health indicator correctly reflects backup age (green < 25h, yellow 25-49h, red > 49h)
-</verification>
-
-<success_criteria>
-- BackupWidget renders on Dashboard with current backup status
-- Health indicator shows green/yellow/red based on backup recency
-- "Backup Now" triggers manual backup with toast feedback
-- Snapshot list is viewable from the widget
-- Restore with dry-run preview works for both full and selective (subdirectory) restore
-- All existing tests still pass
-</success_criteria>
-
-<output>
-After completion, create `.planning/phases/02-data-backup-recovery/02-02-SUMMARY.md`
-</output>
diff --git a/.planning/phases/02-data-backup-recovery/02-02-SUMMARY.md b/.planning/phases/02-data-backup-recovery/02-02-SUMMARY.md
deleted file mode 100644
index 7e2c6da3a0..0000000000
--- a/.planning/phases/02-data-backup-recovery/02-02-SUMMARY.md
+++ /dev/null
@@ -1,112 +0,0 @@
----
-phase: 02-data-backup-recovery
-plan: "02"
-subsystem: ui
-tags: [react, dashboard, backup, widget, tailwind, lucide]
-
-# Dependency graph
-requires:
- - phase: 02-data-backup-recovery
- plan: "01"
- provides: "Backup REST API (status, run, snapshots, restore) and client api.js helpers"
-provides:
- - BackupWidget React component on the Dashboard with health indicator, manual trigger, snapshot list, and restore UI
- - Dashboard integration (Row 4, beside SystemHealthWidget)
-affects: [future dashboard layout changes, backup feature extensions]
-
-# Tech tracking
-tech-stack:
- added: []
- patterns:
- - "useAutoRefetch for polling with silent option (60s status, 120s snapshots)"
- - "computeHealth() pure function for backup age threshold logic"
- - "Inline expandable restore panel per snapshot (not a URL-less modal)"
- - "Dry-run preview required before restore button is enabled"
-
-key-files:
- created:
- - client/src/components/BackupWidget.jsx
- modified:
- - client/src/pages/Dashboard.jsx
- - .changelog/v1.14.x.md
-
-key-decisions:
- - "RestorePanel as inline expandable within SnapshotList (avoids URL-less modal per CLAUDE.md)"
- - "Dry-run preview must be completed before Restore button is active"
- - "BackupWidget placed in Dashboard Row 4 (system-status row) beside SystemHealthWidget"
- - "SnapshotList fetches lazily (only when expanded) to avoid unnecessary API calls"
-
-patterns-established:
- - "computeHealth(status): pure function pattern for threshold-based health states"
- - "relativeTime(isoString): pure relative time formatter with future/past awareness"
- - "Silent auto-refetch + lazy expansion keeps widget compact until needed"
-
-requirements-completed: [BAK-04, BAK-05, BAK-06, BAK-07]
-
-# Metrics
-duration: 10min
-completed: 2026-02-26
----
-
-# Phase 2 Plan 02: Backup Dashboard Widget Summary
-
-**BackupWidget on Dashboard with green/yellow/red health indicator, "Backup Now" toast trigger, expandable snapshot list, and inline dry-run restore panel with selective subdirectory filter**
-
-## Performance
-
-- **Duration:** ~10 min
-- **Started:** 2026-02-26T22:08:38Z
-- **Completed:** 2026-02-26T22:22:10Z
-- **Tasks:** 2 of 2
-- **Files modified:** 3
-
-## Accomplishments
-
-- Created BackupWidget component (402 lines) with full health/trigger/snapshot/restore UI
-- Wired BackupWidget into Dashboard.jsx (import + Row 4 render)
-- Verified backup API works end-to-end: server restarted, test backup ran, snapshot created at `/tmp/portos-backup-test/snapshots/2026-02-26T22-10-54`
-
-## Task Commits
-
-Each task was committed atomically:
-
-1. **Task 1: Create BackupWidget component and add to Dashboard** - `516c7c7` (feat)
-
-2. **Task 2: Verify complete backup system end-to-end** - `e0985c2` (checkpoint:human-verify — approved)
-
-**Plan metadata:** pending final docs commit
-
-## Files Created/Modified
-
-- `client/src/components/BackupWidget.jsx` - Health indicator, manual backup trigger, expandable snapshot list, inline restore panel with dry-run preview and subdirFilter
-- `client/src/pages/Dashboard.jsx` - Added BackupWidget import (alphabetically) and render in Row 4
-- `.changelog/v1.14.x.md` - Added BackupWidget entry under Features
-
-## Decisions Made
-
-- RestorePanel is an inline expandable within each snapshot row (avoids URL-less modal pattern prohibited by CLAUDE.md)
-- Restore button only enabled after a dry-run preview is completed — prevents accidental destructive restores
-- SnapshotList component fetches lazily (only rendered when user expands the snapshots toggle)
-- BackupWidget placed in Row 4 (system-status row) alongside SystemHealthWidget — infrastructure status belongs together
-
-## Deviations from Plan
-
-None - plan executed exactly as written.
-
-## Issues Encountered
-
-- `/api/backup/status` returned `NOT_FOUND` initially — server was running with the old code (before Plan 02-01 changes). Restarted PM2 apps via `pm2 restart ecosystem.config.cjs` which resolved it.
-- Test backup took ~2 minutes to complete (94,194 files) — background job, verified via status poll after completion.
-
-## User Setup Required
-
-None - no external service configuration required for this plan. Backup destination path is configured via Settings UI.
-
-## Next Phase Readiness
-
-- Human verification approved: BackupWidget visible on dashboard with green health indicator, Backup Now button triggers toast, snapshots list shows test snapshot, selective restore preview works
-- Phase 2 is complete — ready for Phase 3 (Health Auto Export)
-
----
-*Phase: 02-data-backup-recovery*
-*Completed: 2026-02-26*
diff --git a/.planning/phases/02-data-backup-recovery/02-RESEARCH.md b/.planning/phases/02-data-backup-recovery/02-RESEARCH.md
deleted file mode 100644
index e96667099e..0000000000
--- a/.planning/phases/02-data-backup-recovery/02-RESEARCH.md
+++ /dev/null
@@ -1,584 +0,0 @@
-# Phase 2: Data Backup & Recovery - Research
-
-**Researched:** 2026-02-26
-**Domain:** Incremental filesystem backup, SHA-256 integrity, scheduler integration, restore tooling, dashboard widget
-**Confidence:** HIGH
-
-## Summary
-
-Phase 2 implements a complete backup and restore system for PortOS's `./data/` directory using `rsync` (already available on macOS as `openrsync` at `/usr/bin/rsync`), Node.js built-in `crypto` for SHA-256 manifests, and the existing `eventScheduler` service for scheduling. No new npm dependencies are required for the core backup engine — all critical primitives exist in the current stack.
-
-The design follows a snapshot-per-run model: each backup run creates a dated directory under the external drive target path (e.g., `<dest>/snapshots/2026-02-26T14-30-00/`). Rsync's `--archive` and `--itemize-changes` flags handle incremental transfer. A SHA-256 manifest file is generated by Node.js `crypto` after each successful run. Restore operations re-use rsync in reverse with `--dry-run` for preview. The dashboard widget uses the existing `useAutoRefetch` hook pattern for live status.
-
-**Primary recommendation:** Implement backup as a standalone `backupService.js` with a matching `backupScheduler.js` (mirroring `brainScheduler.js`), a `routes/backup.js` REST layer, and a `BackupWidget.jsx` dashboard component. Use Node.js `spawn('rsync', [...], { shell: false })` for all rsync invocations, consistent with how `commands.js` executes child processes. Store backup state in `data/backup/state.json`.
-
-<phase_requirements>
-## Phase Requirements
-
-| ID | Description | Research Support |
-|----|-------------|-----------------|
-| BAK-01 | Incremental rsync backup copies changed files from `./data/` to configurable external drive path | rsync `--archive --itemize-changes` with snapshot dirs; `spawn()` from Node.js |
-| BAK-02 | SHA-256 manifest tracks file integrity across backups | Node.js `crypto.createHash('sha256')` — no new deps; walk destination tree after rsync, write manifest.json |
-| BAK-03 | Daily backup runs via existing scheduler with configurable interval | `eventScheduler.schedule({ type: 'cron', cron: '0 2 * * *', ... })` — directly uses existing scheduler |
-| BAK-04 | Dashboard widget shows last backup time, next scheduled, health status | `BackupWidget.jsx` using `useAutoRefetch` hook + GET `/api/backup/status` endpoint |
-| BAK-05 | One-click manual backup trigger from dashboard | POST `/api/backup/run` route; widget button dispatches it with toast notification |
-| BAK-06 | Restore from named snapshot with dry-run mode showing what would change | `rsync --dry-run --archive <snapshot>/ <dest>/` captures itemize-changes output for preview |
-| BAK-07 | Selective directory restore (e.g., only `data/brain/` without touching other dirs) | rsync `--include='brain/***' --exclude='*'` pattern applied to snapshot path |
-</phase_requirements>
-
-## Standard Stack
-
-### Core
-
-| Library | Version | Purpose | Why Standard |
-|---------|---------|---------|--------------|
-| `rsync` (system) | openrsync 2.6.9 compat | Incremental file sync to external drive | Already on macOS; `--archive`, `--itemize-changes`, `--dry-run`, `--link-dest` all verified working |
-| `node:crypto` | Node built-in | SHA-256 hash of each file for manifest | Zero deps; `createHash('sha256').update(buf).digest('hex')` works in tests |
-| `node:child_process` `spawn` | Node built-in | Execute rsync from server process | Consistent with `commands.js` pattern; `shell: false` prevents injection |
-| `node:fs/promises` | Node built-in | Walk destination tree, write manifest/state | Already used everywhere in services |
-| `eventScheduler` | Project service | Cron scheduling for daily backup | Existing scheduler; `schedule({ type: 'cron', cron: '0 2 * * *', ... })` |
-| `zod` | ^3.24.1 | Validate backup config / restore request inputs | Project standard; in `lib/validation.js` |
-
-### Supporting
-
-| Library | Version | Purpose | When to Use |
-|---------|---------|---------|-------------|
-| `socket.io` | ^4.8.3 | Emit real-time progress during backup run | Already initialized; emit `backup:progress` events; widget listens optionally |
-| `uuid` | ^11.0.3 | Generate snapshot IDs if needed | Already in package.json |
-
-### Alternatives Considered
-
-| Instead of | Could Use | Tradeoff |
-|------------|-----------|----------|
-| System rsync + Node.js crypto | `node-rsync` npm package | Extra dep with no meaningful benefit; direct spawn is simpler and already the project pattern |
-| System rsync + Node.js crypto | `tar` + `gzip` archives | Tarballs don't support incremental transfers; harder to restore individual files |
-| eventScheduler cron | `node-cron` npm package | Extra dep; `eventScheduler` already supports cron expressions and is the project-standard scheduler |
-| Per-file SHA-256 in manifest | `md5` or `sha1` | SHA-256 is stronger, is the project requirement (BAK-02), and crypto is built-in |
-
-**Installation:** No new packages required.
-
-## Architecture Patterns
-
-### Recommended Project Structure
-
-```
-server/
- routes/
- backup.js # REST handlers: GET /status, POST /run, POST /restore, GET /snapshots
- services/
- backup.js # Core logic: runBackup(), generateManifest(), restore(), listSnapshots()
- backupScheduler.js # Scheduler init: mirrors brainScheduler.js pattern
- lib/
- validation.js # Add: backupConfigSchema, restoreRequestSchema (extend existing file)
-
-client/src/
- components/
- BackupWidget.jsx # Dashboard widget: status, manual trigger, health indicator
- services/
- api.js # Add: getBackupStatus(), triggerBackup(), getBackupSnapshots(), restoreBackup()
-
-data/
- backup/
- state.json # { lastRun, nextRun, status, snapshotCount, lastError }
-```
-
-### Pattern 1: Snapshot Directory Layout on External Drive
-
-**What:** Each backup run creates a dated subdirectory. rsync copies only changed files. Manifest is stored inside the snapshot directory.
-
-**When to use:** Default for all runs.
-
-```
-<destPath>/ # User-configured external drive mount
- snapshots/
- 2026-02-26T02-00-00/
- data/ # Mirror of ./data/
- brain/
- meatspace/
- ...
- manifest.json # { generatedAt, fileCount, files: { path: sha256 } }
- 2026-02-25T02-00-00/
- data/
- manifest.json
- state.json # { lastSnapshot, snapshotCount }
-```
-
-**Why dated dirs vs. link-dest:** macOS `openrsync` supports `--link-dest` but snapshot dirs are simpler to browse and restore from. `--link-dest` can be added in v2 (BAK-10 deferred). For v1, simple dated copies are correct.
-
-### Pattern 2: rsync Invocation (Incremental Transfer)
-
-**What:** Spawn rsync with `--archive --itemize-changes` (no `--delete` in v1 to be safe). Capture stdout line-by-line for file tracking.
-
-**When to use:** All backup runs.
-
-```javascript
-// Source: verified against openrsync 2.6.9 on macOS 24.6.0
-import { spawn } from 'child_process';
-import { join } from 'path';
-
-function runRsync(srcDir, destDir, flags = []) {
- const args = [
- '--archive', // recursive + preserve metadata
- '--itemize-changes', // per-file change indicators for logging
- ...flags,
- `${srcDir}/`, // trailing slash = copy contents, not dir itself
- destDir
- ];
-
- const child = spawn('rsync', args, { shell: false });
- const changed = [];
-
- child.stdout.on('data', (chunk) => {
- const lines = chunk.toString().split('\n').filter(Boolean);
- for (const line of lines) {
- if (line.startsWith('>') || line.startsWith('<')) {
- changed.push(line.trim());
- }
- }
- });
-
- return new Promise((resolve, reject) => {
- child.on('close', (code) => {
- if (code === 0 || code === 24) { // 24 = partial transfer (vanished files), acceptable
- resolve({ changed, code });
- } else {
- reject(new Error(`rsync exited with code ${code}`));
- }
- });
- child.on('error', reject);
- });
-}
-```
-
-### Pattern 3: SHA-256 Manifest Generation
-
-**What:** Walk the snapshot `data/` directory with `fs.readdir` recursively, hash each file, write `manifest.json`.
-
-```javascript
-// Source: Node.js built-in crypto (verified working on Node 20+)
-import { createHash } from 'crypto';
-import { readFile, writeFile, readdir, stat } from 'fs/promises';
-import { join, relative } from 'path';
-
-async function generateManifest(snapshotDataDir, manifestPath) {
- const files = {};
- await walkDir(snapshotDataDir, async (filePath) => {
- const content = await readFile(filePath);
- const hash = createHash('sha256').update(content).digest('hex');
- files[relative(snapshotDataDir, filePath)] = hash;
- });
- const manifest = {
- generatedAt: new Date().toISOString(),
- fileCount: Object.keys(files).length,
- files
- };
- await writeFile(manifestPath, JSON.stringify(manifest, null, 2));
- return manifest;
-}
-```
-
-### Pattern 4: Scheduler Integration
-
-**What:** Register a cron event with the existing `eventScheduler` at server startup. Mirror `brainScheduler.js` exactly.
-
-```javascript
-// Source: server/services/eventScheduler.js (project code, verified)
-import * as eventScheduler from './eventScheduler.js';
-import { runBackup } from './backup.js';
-import { getSettings } from './settings.js';
-
-let scheduledEventId = null;
-
-export function startBackupScheduler() {
- const id = 'backup-daily';
- eventScheduler.schedule({
- id,
- type: 'cron',
- cron: '0 2 * * *', // default: 2 AM daily; override from settings
- handler: async () => {
- console.log('💾 Backup scheduler: Running daily backup...');
- const settings = await getSettings();
- await runBackup(settings.backup?.destPath);
- },
- metadata: { source: 'backupScheduler' }
- });
- scheduledEventId = id;
- console.log('💾 Backup scheduler started');
-}
-
-export function stopBackupScheduler() {
- if (scheduledEventId) {
- eventScheduler.cancel(scheduledEventId);
- scheduledEventId = null;
- }
-}
-```
-
-### Pattern 5: Dry-Run Restore Preview
-
-**What:** Run rsync with `--dry-run` flag. Capture `--itemize-changes` output. Return list of files that would be changed before actually running.
-
-```javascript
-// Source: verified against openrsync on macOS (--dry-run supported, exit 0)
-async function previewRestore(snapshotDataDir, targetDir, subdirFilter = null) {
- const flags = ['--dry-run'];
- if (subdirFilter) {
- // Selective restore: only data/brain/ for example
- flags.push(`--include=${subdirFilter}/***`, '--exclude=*');
- }
- const { changed } = await runRsync(snapshotDataDir, targetDir, flags);
- return changed; // array of itemize-changes lines describing what would change
-}
-```
-
-### Pattern 6: Zod Validation for Backup Routes
-
-**What:** Add backup schemas to `server/lib/validation.js` following the existing schema pattern.
-
-```javascript
-// Add to server/lib/validation.js
-export const backupConfigSchema = z.object({
- destPath: z.string().min(1), // external drive mount path
- cronExpression: z.string().optional(), // e.g., '0 2 * * *'
- enabled: z.boolean().optional().default(true)
-});
-
-export const restoreRequestSchema = z.object({
- snapshotId: z.string().min(1), // snapshot directory name
- subdirFilter: z.string().optional().nullable(), // e.g., 'brain' for selective restore
- dryRun: z.boolean().optional().default(true) // always default to safe dry-run
-});
-```
-
-### Pattern 7: Dashboard Widget
-
-**What:** React component using `useAutoRefetch` (existing hook) to poll `/api/backup/status`. Shows last backup time, next scheduled time, and health status (green/yellow/red). Follows `SystemHealthWidget.jsx` structural pattern.
-
-```jsx
-// Pattern from SystemHealthWidget.jsx and CosDashboardWidget.jsx
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
-import * as api from '../services/api';
-
-const BackupWidget = memo(function BackupWidget() {
- const { data: status, loading } = useAutoRefetch(
- () => api.getBackupStatus({ silent: true }).catch(() => null),
- 60000 // refresh every 60s
- );
-
- // health: 'healthy' (last run < 25h ago, no error)
- // 'warning' (last run 25-49h ago or missed)
- // 'critical' (last run > 49h ago or errored)
- const health = computeHealth(status); // green/yellow/red
-
- // Manual trigger button: POST /api/backup/run
- // Uses toast for feedback (no window.alert)
-});
-```
-
-### Anti-Patterns to Avoid
-
-- **Running rsync with `shell: true`:** Project convention in `commands.js` is `shell: false`. Rsync called directly with `spawn('rsync', argsArray, { shell: false })` prevents injection.
-- **Using `window.alert` / `window.confirm`:** Project forbids this. All feedback via `react-hot-toast` (already imported in `api.js`). Confirmation of destructive restore goes via inline modal UI state, not a dialog.
-- **Hardcoding `localhost`:** Widget fetches from `/api/backup/...` (relative), not `http://localhost:5554`. See CLAUDE.md.
-- **Storing backup state outside `data/`:** Backup state JSON goes in `data/backup/state.json` so it is itself backed up.
-- **Deleting old snapshots in v1:** `--delete` is deferred (BAK-10 retention policy is v2). v1 snapshots accumulate until disk fills — document this, provide snapshot list UI.
-- **Giant try/catch blocks:** Project pattern (CLAUDE.md) is no try/catch; errors bubble to `asyncHandler` middleware.
-- **Blocking the event loop with large file reads:** Manifest generation reads files sequentially to avoid memory spikes. For very large data dirs, use streaming hash: `fs.createReadStream()` piped to `crypto.createHash()`.
-
-## Don't Hand-Roll
-
-| Problem | Don't Build | Use Instead | Why |
-|---------|-------------|-------------|-----|
-| Incremental file sync | Custom file-diff logic | `rsync --archive --itemize-changes` | rsync handles timestamps, permissions, symlinks, partial transfers correctly |
-| File integrity verification | Custom file comparison | Node.js `crypto.createHash('sha256')` | Built-in, battle-tested, no deps |
-| Cron scheduling | Custom minute-check interval | `eventScheduler.schedule({ type: 'cron', ... })` | Already in project, handles edge cases, re-uses existing infrastructure |
-| Progress streaming | Custom WebSocket protocol | Emit `backup:progress` on existing `socket.io` instance (`req.app.get('io')`) | Already initialized in `server/index.js`; pattern used by other services |
-
-**Key insight:** The entire backup engine is assembling existing system tools and Node built-ins. The only novel logic is the state tracking, manifest generation, and schedule integration.
-
-## Common Pitfalls
-
-### Pitfall 1: macOS openrsync vs GNU rsync feature gaps
-**What goes wrong:** openrsync (macOS default) has different flag support than GNU rsync. Some GNU flags (`--checksum` for file-content comparison, `--link-dest` in some forms) may behave differently.
-**Why it happens:** Apple ships OpenBSD's rsync implementation, not the GNU one from rsync.samba.org.
-**How to avoid:** Verified flags on this system: `--archive`, `--itemize-changes`, `--dry-run`, `--link-dest`, `--include`, `--exclude` all work (confirmed via manual test). Do NOT use `--checksum` for deduplication (not reliably supported). Do NOT use rsync's built-in checksums as a replacement for the Node.js SHA-256 manifest.
-**Warning signs:** rsync exits with unexpected error codes or silently ignores flags — always check exit code in the spawn handler.
-
-### Pitfall 2: External Drive Not Mounted
-**What goes wrong:** Backup silently fails or creates directories in wrong location if the drive path doesn't exist.
-**Why it happens:** External drives have non-deterministic mount paths on macOS (e.g., `/Volumes/BackupDrive`).
-**How to avoid:** Before running backup, verify `destPath` exists with `fs.access(destPath)`. If missing: set state to `{ status: 'error', error: 'Destination path not found' }`, emit Socket.IO event for dashboard notification. Never auto-create the destPath (could silently write to wrong location).
-**Warning signs:** Dashboard shows "drive not found" error state; no snapshot directories created.
-
-### Pitfall 3: Concurrent Backup Runs
-**What goes wrong:** If the cron fires while a manual backup is in progress, or if two manual triggers are fired rapidly, rsync instances conflict on the destination path.
-**Why it happens:** No lock mechanism.
-**How to avoid:** Use an in-memory `isRunning` flag in `backup.js`. Check before starting; return early if already running. Store `{ status: 'running', startedAt }` in state.json while active.
-**Warning signs:** Two rsync processes with same source/dest in `ps aux`; corrupted snapshot directory.
-
-### Pitfall 4: Large File Reads for Manifest on Large `./data/` Directories
-**What goes wrong:** Reading entire files into memory for SHA-256 hashing causes memory spikes if `data/runs/` contains many large AI output files.
-**Why it happens:** `readFile()` loads entire file into a Buffer.
-**How to avoid:** Use streaming hash for files over a size threshold (e.g., > 1MB): `fs.createReadStream(path).pipe(hash)`. Or hash only metadata (path + mtime + size) for the manifest rather than content — acceptable approximation since rsync already handles content integrity.
-**Warning signs:** Node.js memory usage spikes during manifest generation; OOM in PM2 logs.
-
-### Pitfall 5: Rsync Exit Code 24 (Partial Transfer / Vanished Files)
-**What goes wrong:** Treat exit code 24 as an error, causing backup to report failure when it actually succeeded.
-**Why it happens:** Exit code 24 means "some source files vanished during transfer" — completely normal for an active system where JSON files are being written.
-**How to avoid:** Accept exit codes 0 and 24 as success. Log the code but don't set error state. Only codes 1, 2, 3, etc. are real errors.
-**Warning signs:** Backup always reports "failed" despite successful file transfer.
-
-### Pitfall 6: Route Not Registered in index.js
-**What goes wrong:** New backup routes exist but return 404 because they weren't imported in `server/index.js`.
-**Why it happens:** The import + `app.use()` registration pattern requires explicit wiring.
-**How to avoid:** After creating `routes/backup.js`, add to `server/index.js` alphabetically (project convention): `import backupRoutes from './routes/backup.js'` and `app.use('/api/backup', backupRoutes)`.
-**Warning signs:** 404 on all `/api/backup/*` endpoints; widget shows loading forever.
-
-### Pitfall 7: Backup Widget Hidden Due to Missing Data
-**What goes wrong:** Widget renders nothing during initial load because status is null, leading to layout shift.
-**Why it happens:** `useAutoRefetch` starts with `loading: true`, and widgets often return null while loading.
-**How to avoid:** Unlike CosDashboardWidget (which hides when no activity), BackupWidget should always render since backup status is always relevant. Show a skeleton/loading state rather than returning null. If backup has never run, show "No backups yet" with configure button.
-
-## Code Examples
-
-### Run Backup (Core Flow)
-
-```javascript
-// server/services/backup.js
-import { spawn } from 'child_process';
-import { createHash } from 'crypto';
-import { readFile, writeFile, readdir, stat, mkdir, access } from 'fs/promises';
-import { join, relative } from 'path';
-import { PATHS } from '../lib/fileUtils.js';
-
-let isRunning = false;
-
-export async function runBackup(destPath) {
- if (isRunning) {
- console.log('💾 Backup already running, skipping');
- return { skipped: true };
- }
- if (!destPath) throw new Error('No backup destination configured');
-
- // Verify destination exists
- await access(destPath).catch(() => {
- throw new Error(`Backup destination not found: ${destPath}`);
- });
-
- isRunning = true;
- const startedAt = new Date().toISOString();
- const snapshotId = startedAt.replace(/:/g, '-').replace(/\..+/, '');
- const snapshotDir = join(destPath, 'snapshots', snapshotId);
- const dataDestDir = join(snapshotDir, 'data');
-
- console.log(`💾 Backup starting: snapshot ${snapshotId}`);
-
- await mkdir(dataDestDir, { recursive: true });
- const { changed, code } = await runRsync(PATHS.data, dataDestDir);
- console.log(`💾 Backup rsync complete: ${changed.length} files changed (exit ${code})`);
-
- const manifest = await generateManifest(dataDestDir, join(snapshotDir, 'manifest.json'));
- console.log(`💾 Backup manifest generated: ${manifest.fileCount} files`);
-
- const completedAt = new Date().toISOString();
- await saveState({ lastRun: completedAt, lastSnapshotId: snapshotId, status: 'ok', filesChanged: changed.length });
-
- isRunning = false;
- return { snapshotId, filesChanged: changed.length, fileCount: manifest.fileCount };
-}
-```
-
-### List Snapshots
-
-```javascript
-export async function listSnapshots(destPath) {
- const snapshotsDir = join(destPath, 'snapshots');
- const entries = await readdir(snapshotsDir).catch(() => []);
- const snapshots = await Promise.all(
- entries.map(async (name) => {
- const manifestPath = join(snapshotsDir, name, 'manifest.json');
- const manifest = await readFile(manifestPath, 'utf-8').then(JSON.parse).catch(() => null);
- return { id: name, createdAt: name, fileCount: manifest?.fileCount ?? null };
- })
- );
- return snapshots.sort((a, b) => b.id.localeCompare(a.id)); // newest first
-}
-```
-
-### Restore with Dry-Run
-
-```javascript
-// server/services/backup.js
-export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, subdirFilter = null } = {}) {
- const snapshotDataDir = join(destPath, 'snapshots', snapshotId, 'data');
- const flags = dryRun ? ['--dry-run'] : [];
- if (subdirFilter) {
- // Only restore e.g. 'brain' directory
- flags.push(`--include=${subdirFilter}/***`, '--include=*/', '--exclude=*');
- }
- const { changed } = await runRsync(snapshotDataDir, PATHS.data, flags);
- console.log(`💾 Restore ${dryRun ? 'preview' : 'completed'}: snapshot ${snapshotId}, ${changed.length} files ${dryRun ? 'would change' : 'changed'}`);
- return { dryRun, snapshotId, subdirFilter, changedFiles: changed };
-}
-```
-
-### REST Routes
-
-```javascript
-// server/routes/backup.js
-import { Router } from 'express';
-import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { validateRequest } from '../lib/validation.js';
-import { restoreRequestSchema } from '../lib/validation.js';
-import * as backup from '../services/backup.js';
-import { getSettings } from '../services/settings.js';
-
-const router = Router();
-
-// GET /api/backup/status
-router.get('/status', asyncHandler(async (req, res) => {
- const state = await backup.getState();
- const settings = await getSettings();
- const nextRun = backup.getNextRunTime(); // from eventScheduler
- res.json({ ...state, destPath: settings.backup?.destPath, nextRun });
-}));
-
-// POST /api/backup/run
-router.post('/run', asyncHandler(async (req, res) => {
- const settings = await getSettings();
- const result = await backup.runBackup(settings.backup?.destPath);
- res.json(result);
-}));
-
-// GET /api/backup/snapshots
-router.get('/snapshots', asyncHandler(async (req, res) => {
- const settings = await getSettings();
- const snapshots = await backup.listSnapshots(settings.backup?.destPath);
- res.json(snapshots);
-}));
-
-// POST /api/backup/restore
-router.post('/restore', asyncHandler(async (req, res) => {
- const { snapshotId, subdirFilter, dryRun } = validateRequest(restoreRequestSchema, req.body);
- const settings = await getSettings();
- const result = await backup.restoreSnapshot(settings.backup?.destPath, snapshotId, { dryRun, subdirFilter });
- res.json(result);
-}));
-
-export default router;
-```
-
-### API Client Functions (to add to `api.js`)
-
-```javascript
-// client/src/services/api.js additions
-export const getBackupStatus = (options) => request('/backup/status', options);
-export const triggerBackup = () => request('/backup/run', { method: 'POST' });
-export const getBackupSnapshots = (options) => request('/backup/snapshots', options);
-export const restoreBackup = (data) => request('/backup/restore', { method: 'POST', body: JSON.stringify(data) });
-```
-
-### Settings Schema (extend existing `settings.json`)
-
-```javascript
-// Backup config stored in data/settings.json under 'backup' key
-{
- "backup": {
- "destPath": "/Volumes/BackupDrive/PortOS", // user-configured
- "cronExpression": "0 2 * * *", // 2 AM daily default
- "enabled": true
- }
-}
-```
-
-### Backup State File (`data/backup/state.json`)
-
-```json
-{
- "lastRun": "2026-02-26T02:00:00.000Z",
- "lastSnapshotId": "2026-02-26T02-00-00",
- "status": "ok",
- "filesChanged": 12,
- "nextRun": "2026-02-27T02:00:00.000Z",
- "error": null
-}
-```
-
-## State of the Art
-
-| Old Approach | Current Approach | When Changed | Impact |
-|--------------|------------------|--------------|--------|
-| Manual tar archives | rsync incremental with snapshot dirs | Standard for local backup | Faster, resumable, browsable |
-| MD5 manifests | SHA-256 manifests | 2015+ (SHA-1 weaknesses) | More secure |
-| cron daemon (system-level) | App-internal scheduler | Node.js ecosystem shift | No system cron config needed |
-| Full restore only | Selective directory restore | Modern backup tools | Less disruptive restore |
-
-**Deprecated/outdated:**
-- System-level `crontab` entries: Project self-manages scheduling via `eventScheduler`. Don't add crontab entries.
-- `node-cron` npm package: Project already has a custom `eventScheduler` with cron support. Redundant.
-
-## Open Questions
-
-1. **External Drive Detection**
- - What we know: Backup destination is user-configured (a path, not auto-detected)
- - What's unclear: Should the dashboard show available external drives for user to pick? Or just a text field for path?
- - Recommendation: Start with a simple text field in settings (via PUT `/api/settings`). Drive picker is UI complexity not in v1 requirements.
-
-2. **Backup Config Location**
- - What we know: Settings live in `data/settings.json` managed by `settings.js`
- - What's unclear: Should backup config have its own file (`data/backup/config.json`) or extend the global settings object?
- - Recommendation: Extend global `settings.json` under a `backup` key — consistent with how brain settings work. No new file needed.
-
-3. **Streaming Progress to Dashboard (BAK-03 / BAK-04)**
- - What we know: Socket.IO is available (`req.app.get('io')`) and `backup:progress` events can be emitted
- - What's unclear: Does the widget need real-time rsync file-by-file progress, or just start/complete?
- - Recommendation: Emit `backup:started` and `backup:completed` events only. File-by-file progress is scope creep for v1. Widget polls via `useAutoRefetch` every 60s; during active backup shows "Running..." from state.json.
-
-4. **Manifest File Size**
- - What we know: `data/` contains `runs/` (AI run outputs, potentially hundreds of files) and `memory/` embeddings
- - What's unclear: Could manifest.json become very large (thousands of file hashes)?
- - Recommendation: Use streaming hash (`fs.createReadStream` piped to hash) for files > 512KB to prevent memory spikes. File count will likely be hundreds not thousands — acceptable.
-
-5. **Rsync `rsync` not found on remote Tailscale access**
- - What we know: Server runs on the local machine; rsync is at `/usr/bin/rsync`
- - What's unclear: Will PATH include rsync when spawned from Node.js PM2 process?
- - Recommendation: Hardcode path in spawn: `spawn('/usr/bin/rsync', args, ...)` or use `which rsync` at startup to resolve path. Avoid PATH dependency in PM2 context.
-
-## Validation Architecture
-
-> `workflow.nyquist_validation` is not present in `.planning/config.json` — skipping this section.
-
-## Sources
-
-### Primary (HIGH confidence)
-
-- System `rsync` tested directly (`/usr/bin/rsync`) — `--archive`, `--itemize-changes`, `--dry-run`, `--link-dest`, `--include`, `--exclude` all confirmed working on macOS 24.6.0
-- Node.js built-in `crypto` — `createHash('sha256')` verified working in Node.js on this system
-- `server/services/eventScheduler.js` — project source code, cron scheduling verified
-- `server/services/brainScheduler.js` — scheduling pattern to mirror
-- `server/services/commands.js` — `spawn` with `shell: false` pattern to follow
-- `server/lib/commandSecurity.js` — `rsync` is NOT in current ALLOWED_COMMANDS (only matters if using the command executor — backup service will use spawn directly, not commandSecurity)
-- `server/lib/fileUtils.js` — `PATHS.data`, `ensureDir`, `readJSONFile` utilities available
-- `server/lib/validation.js` — Zod schema patterns for new backup schemas
-- `client/src/hooks/useAutoRefetch.js` — polling hook for widget
-- `client/src/components/SystemHealthWidget.jsx` — widget structural pattern
-- `server/index.js` — route registration pattern; `app.use('/api/backup', backupRoutes)` location
-
-### Secondary (MEDIUM confidence)
-
-- rsync exit code documentation: exit 24 (partial transfer/vanished files) is acceptable for active systems — confirmed across multiple rsync documentation sources
-- SHA-256 streaming pattern for large files — standard Node.js pattern, no verification needed
-
-### Tertiary (LOW confidence)
-
-- None — all research items confirmed against project source or live system testing
-
-## Metadata
-
-**Confidence breakdown:**
-- Standard stack: HIGH — verified on live system, no external deps needed
-- Architecture: HIGH — mirrors existing project patterns exactly
-- Pitfalls: HIGH — most identified from reading project code patterns + live rsync testing
-
-**Research date:** 2026-02-26
-**Valid until:** 2026-08-26 (stable domain; rsync, Node.js crypto, and project patterns won't change significantly)
diff --git a/.planning/phases/02-data-backup-recovery/02-VERIFICATION.md b/.planning/phases/02-data-backup-recovery/02-VERIFICATION.md
deleted file mode 100644
index 7a9b230a1d..0000000000
--- a/.planning/phases/02-data-backup-recovery/02-VERIFICATION.md
+++ /dev/null
@@ -1,142 +0,0 @@
----
-phase: 02-data-backup-recovery
-verified: 2026-02-26T23:00:00Z
-status: human_needed
-score: 5/5 must-haves verified
-re_verification: false
-human_verification:
- - test: "Open the PortOS dashboard and confirm BackupWidget is visible in Row 4 alongside SystemHealthWidget"
- expected: "Widget renders with health indicator dot (green/yellow/red), last backup time, next scheduled time, and a 'Backup Now' button"
- why_human: "Visual rendering and layout position cannot be verified programmatically"
- - test: "Click the 'Backup Now' button (with a valid destPath configured in Settings)"
- expected: "Toast notification appears ('Backup started' with disk emoji) and the widget health indicator updates after backup completes"
- why_human: "End-to-end rsync execution + toast UX requires a browser with the actual server running"
- - test: "Expand the 'Snapshots' toggle after a backup has run, select a snapshot, type 'brain' in the filter field, click 'Preview'"
- expected: "A list of files that would change appears in a scrollable container; Restore button becomes enabled"
- why_human: "Dry-run preview flow with live data requires human interaction and a real external drive path"
- - test: "Verify the 'Restore' button is only enabled after Preview is completed"
- expected: "Restore button is disabled before Preview; enabled only after changedFiles list is returned"
- why_human: "State-gated UI button interaction requires manual testing"
----
-
-# Phase 2: Data Backup & Recovery Verification Report
-
-**Phase Goal:** All PortOS data is automatically backed up to an external drive with integrity verification and restore capability
-**Verified:** 2026-02-26T23:00:00Z
-**Status:** human_needed
-**Re-verification:** No — initial verification
-
-## Goal Achievement
-
-All five success criteria from the ROADMAP are satisfied by substantive, wired artifacts. No gaps were found in the automated checks. Four items require human verification for end-to-end UI behavior.
-
-### Observable Truths (from ROADMAP Success Criteria)
-
-| # | Truth | Status | Evidence |
-|---|-------|--------|----------|
-| 1 | Running backup copies changed files from `./data/` to the configured external drive path using incremental rsync | VERIFIED | `runBackup()` in `server/services/backup.js` spawns `/usr/bin/rsync --archive --itemize-changes` with `PATHS.data` as src. Exit codes 0 and 24 accepted. Route `POST /api/backup/run` calls `runBackup(settings.backup?.destPath, io)`. |
-| 2 | A SHA-256 manifest file exists after each backup and can verify file integrity | VERIFIED | `generateManifest()` walks the snapshot data directory, hashes each file (streaming for 512KB+), writes `manifest.json` with `{ generatedAt, fileCount, files: { path: sha256 } }`. Called immediately after rsync inside `runBackup()`. |
-| 3 | Backup runs automatically on a daily schedule and can be triggered manually from the dashboard | VERIFIED | `backupScheduler.js` calls `schedule({ id: 'backup-daily', type: 'cron', cron: '0 2 * * *', ... })` via `eventScheduler`. `startBackupScheduler()` is called in `server/index.js` at line 233. Manual trigger via `POST /api/backup/run` is wired in routes. |
-| 4 | Dashboard widget displays last backup time, next scheduled time, and health status (green/yellow/red) | VERIFIED | `BackupWidget.jsx` (402 lines) polls `api.getBackupStatus` every 60s via `useAutoRefetch`. Renders health dot using `HEALTH_STYLES` with `bg-port-success/bg-port-warning/bg-port-error`. Displays `relativeTime(status.lastRun)` and `relativeTime(status.nextRun)`. Widget imported and rendered in `Dashboard.jsx` line 136. |
-| 5 | User can restore from a named snapshot with dry-run preview, and can selectively restore individual directories | VERIFIED | `RestorePanel` component: Preview calls `api.restoreBackup({ dryRun: true, subdirFilter })`, displays `changedFiles` list. Restore button only enabled after preview. `subdirFilter` input supports selective directory restore. Server-side `restoreSnapshot()` adds `--include=${subdirFilter}/***` rsync flag. |
-
-**Score:** 5/5 truths verified
-
----
-
-### Required Artifacts
-
-| Artifact | Status | Details |
-|----------|--------|---------|
-| `server/services/backup.js` | VERIFIED | 265 lines. Exports: `generateManifest, getNextRunTime, getState, listSnapshots, restoreSnapshot, runBackup, saveState`. Confirmed via `node -e "import(...)"`. |
-| `server/services/backupScheduler.js` | VERIFIED | 54 lines. Exports: `startBackupScheduler, stopBackupScheduler`. Confirmed via dynamic import. |
-| `server/routes/backup.js` | VERIFIED | 41 lines. Four route handlers: `GET /status`, `POST /run`, `GET /snapshots`, `POST /restore`. All import and call backup service functions. |
-| `server/lib/validation.js` | VERIFIED | `backupConfigSchema` at line 405, `restoreRequestSchema` at line 411. Both are full Zod schemas with correct field definitions. |
-| `client/src/services/api.js` | VERIFIED | Lines 1351-1354. All four client functions present: `getBackupStatus`, `triggerBackup`, `getBackupSnapshots`, `restoreBackup`. |
-| `client/src/components/BackupWidget.jsx` | VERIFIED | 402 lines (min_lines: 80 satisfied). Full UI with health indicator, `Backup Now` button, `SnapshotList`, and `RestorePanel`. |
-| `client/src/pages/Dashboard.jsx` | VERIFIED | Line 4: `import BackupWidget from '../components/BackupWidget'`. Line 136: `<BackupWidget />` rendered in JSX. |
-
----
-
-### Key Link Verification
-
-| From | To | Via | Status | Details |
-|------|----|-----|--------|---------|
-| `server/routes/backup.js` | `server/services/backup.js` | `import * as backup` + calls to `runBackup`, `listSnapshots`, `getState`, `restoreSnapshot`, `getNextRunTime` | WIRED | `import * as backup from '../services/backup.js'` at line 4; all five service functions called in route handlers |
-| `server/services/backupScheduler.js` | `server/services/eventScheduler.js` | `schedule({ id: 'backup-daily', type: 'cron', ... })` | WIRED | `import { schedule, cancel } from './eventScheduler.js'` at line 8; `schedule(...)` called inside `startBackupScheduler()` |
-| `server/index.js` | `server/routes/backup.js` | `app.use('/api/backup', backupRoutes)` | WIRED | Line 43: import; line 192: `app.use('/api/backup', backupRoutes)` |
-| `server/index.js` | `server/services/backupScheduler.js` | `startBackupScheduler()` call at startup | WIRED | Line 59: import; line 233: `startBackupScheduler().catch(...)` |
-| `client/src/components/BackupWidget.jsx` | `client/src/services/api.js` | `import * as api` + calls to `getBackupStatus`, `triggerBackup`, `restoreBackup`, `getBackupSnapshots` | WIRED | Line 17: `import * as api from '../services/api'`; api functions called in `useAutoRefetch` and event handlers |
-| `client/src/components/BackupWidget.jsx` | `client/src/hooks/useAutoRefetch.js` | `useAutoRefetch` hook for status polling | WIRED | Line 18: `import { useAutoRefetch } from '../hooks/useAutoRefetch'`; used at lines 203 and 258 |
-| `client/src/pages/Dashboard.jsx` | `client/src/components/BackupWidget.jsx` | `import BackupWidget` + render in JSX | WIRED | Line 4: import; line 136: `<BackupWidget />` in grid |
-
-All 7 key links: WIRED.
-
----
-
-### Requirements Coverage
-
-| Requirement | Source Plan | Description | Status | Evidence |
-|-------------|------------|-------------|--------|----------|
-| BAK-01 | 02-01-PLAN.md | Incremental rsync backup copies changed files from `./data/` to configurable external drive path | SATISFIED | `runBackup()` spawns `/usr/bin/rsync --archive --itemize-changes` from `PATHS.data` to snapshot dir |
-| BAK-02 | 02-01-PLAN.md | SHA-256 manifest tracks file integrity across backups | SATISFIED | `generateManifest()` hashes all files and writes `manifest.json` with SHA-256 per file |
-| BAK-03 | 02-01-PLAN.md | Daily backup runs via existing scheduler with configurable interval | SATISFIED | `backupScheduler.js` registers `backup-daily` cron with `eventScheduler`; default `0 2 * * *`, overridable via `settings.backup.cronExpression` |
-| BAK-04 | 02-02-PLAN.md | Dashboard widget shows last backup time, next scheduled, health status (green/yellow/red) | SATISFIED | `BackupWidget.jsx` renders all three: `relativeTime(lastRun)`, `relativeTime(nextRun)`, health dot with `port-success/warning/error` colors |
-| BAK-05 | 02-02-PLAN.md | One-click manual backup trigger from dashboard | SATISFIED | `handleBackupNow()` calls `api.triggerBackup()`; success shows `toast.success('Backup started')`, failure shows `toast.error(...)` |
-| BAK-06 | 02-02-PLAN.md | Restore from named snapshot with dry-run mode showing what would change | SATISFIED | `RestorePanel` calls `api.restoreBackup({ dryRun: true })`, displays `changedFiles` list; Restore button only active after preview |
-| BAK-07 | 02-02-PLAN.md | Selective directory restore (e.g., only `data/brain/`) | SATISFIED | `RestorePanel` has `subdirFilter` text input; server-side `restoreSnapshot()` applies `--include=${subdirFilter}/***` rsync filter |
-
-All 7 requirements (BAK-01 through BAK-07): SATISFIED.
-
-No orphaned requirements — all BAK-* IDs from REQUIREMENTS.md are covered by Phase 2 plans.
-
----
-
-### Anti-Patterns Found
-
-| File | Line | Pattern | Severity | Impact |
-|------|------|---------|----------|--------|
-| `client/src/components/BackupWidget.jsx` | 137-138 | `placeholder="e.g., brain"` | Info | Legitimate HTML input placeholder attribute for the subdirFilter field — not a code stub |
-
-No blockers. No warnings. The single info entry is a true HTML attribute, not a stub pattern.
-
----
-
-### Human Verification Required
-
-#### 1. Dashboard widget visual rendering
-
-**Test:** Open the PortOS dashboard in a browser and look for the BackupWidget in Row 4 alongside SystemHealthWidget.
-**Expected:** Widget is visible with a health indicator dot (green if backup ran within 25h, yellow if 25-49h or never, red if error), last backup time, next scheduled time, and a "Backup Now" button.
-**Why human:** Visual rendering and layout position cannot be verified by grep or file inspection.
-
-#### 2. Manual backup trigger with toast feedback
-
-**Test:** With a valid `destPath` configured in Settings, click "Backup Now" in the widget.
-**Expected:** A toast notification appears with "Backup started" (disk emoji). The backup completes in the background. Health indicator turns green after completion.
-**Why human:** End-to-end rsync execution against a real external drive + toast notification UX requires a running browser and server.
-
-#### 3. Snapshot list and dry-run preview
-
-**Test:** After a backup has run, expand the "Snapshots" toggle. Select a snapshot, type "brain" in the subdirFilter field, click "Preview changes".
-**Expected:** A scrollable list of files that would change appears. The "Restore N file(s)" button becomes enabled.
-**Why human:** Requires live data from a real snapshot directory on an external drive; the dry-run flow is interactive.
-
-#### 4. Restore button gating
-
-**Test:** Open the RestorePanel for a snapshot without clicking Preview first.
-**Expected:** The Restore button is not present (only the Preview button is shown until `preview` state is set).
-**Why human:** State-gated conditional render requires interactive testing to confirm the gate holds correctly.
-
----
-
-### Verification Summary
-
-All five roadmap success criteria are met. All seven requirements (BAK-01 through BAK-07) are satisfied by substantive, fully-wired implementations. No stubs, no missing artifacts, no broken links.
-
-The four human verification items cover UI rendering, end-to-end rsync execution with toast feedback, the dry-run preview flow, and the restore button gate. These require a running PortOS instance with an external drive configured. The SUMMARY documents that a human verified these items on 2026-02-26 (commit `e0985c2` — "checkpoint:human-verify — approved"), so the automated code verification is complete. A fresh human spot-check of the widget in its current form is recommended before closing the phase.
-
----
-
-_Verified: 2026-02-26T23:00:00Z_
-_Verifier: Claude (gsd-verifier)_
diff --git a/.planning/phases/03-apple-health-integration/03-01-PLAN.md b/.planning/phases/03-apple-health-integration/03-01-PLAN.md
deleted file mode 100644
index b7f48b2247..0000000000
--- a/.planning/phases/03-apple-health-integration/03-01-PLAN.md
+++ /dev/null
@@ -1,423 +0,0 @@
----
-phase: 03-apple-health-integration
-plan: 01
-type: execute
-wave: 1
-depends_on: []
-files_modified:
- - server/routes/health.js
- - server/routes/systemHealth.js
- - server/index.js
- - client/src/services/api.js
- - server/lib/appleHealthValidation.js
- - server/services/appleHealthIngest.js
- - server/services/appleHealthQuery.js
- - server/routes/appleHealth.js
- - server/lib/fileUtils.js
-autonomous: true
-requirements:
- - HLT-01
- - HLT-02
-
-must_haves:
- truths:
- - "POST /api/health/ingest accepts Health Auto Export JSON, validates with Zod, and returns success with record counts"
- - "Duplicate records (same metric name + timestamp) are silently skipped on re-ingest"
- - "Health data is persisted to day-partitioned files at data/health/YYYY-MM-DD.json"
- - "GET /api/health/metrics returns aggregated metric data for a requested date range"
- - "Existing system health endpoints moved to /api/system/health and /api/system/health/details without breakage"
- artifacts:
- - path: "server/routes/systemHealth.js"
- provides: "Renamed system health routes (was health.js)"
- exports: ["default (router)"]
- - path: "server/lib/appleHealthValidation.js"
- provides: "Zod schemas for Health Auto Export JSON ingest payload"
- exports: ["healthIngestSchema"]
- - path: "server/services/appleHealthIngest.js"
- provides: "JSON ingest, dedup, day-file merge logic"
- exports: ["ingestHealthData"]
- - path: "server/services/appleHealthQuery.js"
- provides: "Date-range queries for health metrics"
- exports: ["getMetrics", "getMetricSummary", "getAvailableDateRange"]
- - path: "server/routes/appleHealth.js"
- provides: "REST endpoints for ingest and query"
- exports: ["default (router)"]
- key_links:
- - from: "server/routes/appleHealth.js"
- to: "server/services/appleHealthIngest.js"
- via: "ingestHealthData(payload)"
- pattern: "ingestHealthData"
- - from: "server/routes/appleHealth.js"
- to: "server/services/appleHealthQuery.js"
- via: "getMetrics(metricName, from, to)"
- pattern: "getMetrics"
- - from: "server/index.js"
- to: "server/routes/appleHealth.js"
- via: "app.use('/api/health', appleHealthRoutes)"
- pattern: "appleHealthRoutes"
- - from: "server/index.js"
- to: "server/routes/systemHealth.js"
- via: "app.use('/api/system', systemHealthRoutes)"
- pattern: "systemHealthRoutes"
----
-
-<objective>
-Build the Apple Health data ingest pipeline: Zod validation for Health Auto Export JSON, deduplication by metric+timestamp, day-partitioned file storage at `data/health/YYYY-MM-DD.json`, and query service for reading metrics by date range. Also resolves the `/api/health` namespace conflict by moving existing system health endpoints to `/api/system/health`.
-
-Purpose: Creates the data foundation that both XML import (Plan 03-02) and dashboard cards (Plan 03-03) depend on.
-Output: Working REST API at `/api/health/ingest` and `/api/health/metrics`, data persisted to day-partitioned files. System health endpoints relocated to `/api/system/health`.
-</objective>
-
-<execution_context>
-@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
-@/Users/antic/.claude/get-shit-done/templates/summary.md
-</execution_context>
-
-<context>
[email protected]/phases/03-apple-health-integration/03-RESEARCH.md
-
-@server/lib/fileUtils.js — PATHS constants, readJSONFile, ensureDir
-@server/lib/meatspaceValidation.js — Zod schema patterns
-@server/routes/backup.js — Route pattern with asyncHandler, io access
-@server/routes/health.js — EXISTING system health routes (must be renamed to avoid collision)
-@server/services/meatspaceAlcohol.js — Service patterns (pure functions, file read/write)
-@server/index.js — Route registration pattern
-
-<interfaces>
-<!-- Key types and contracts the executor needs. Extracted from codebase. -->
-
-From server/lib/fileUtils.js:
-```javascript
-export const PATHS = {
- root: join(__lib_dirname, '../..'),
- data: join(__lib_dirname, '../../data'),
- meatspace: join(__lib_dirname, '../../data/meatspace')
- // ... health needs to be added here
-};
-export async function ensureDir(dir) { ... }
-export async function readJSONFile(filePath, defaultValue) { ... }
-```
-
-From server/lib/errorHandler.js:
-```javascript
-export function asyncHandler(fn) { ... }
-export class ServerError extends Error { ... }
-```
-
-From server/lib/validation.js:
-```javascript
-export function validateRequest(schema, data) { ... }
-```
-
-From server/routes/health.js (EXISTING — must be relocated):
-```javascript
-// Currently registered as: app.use('/api', healthRoutes)
-// Routes: GET /health, GET /health/system
-// These collide with Apple Health's /api/health namespace
-// Must be renamed to: GET /system/health, GET /system/health/details
-```
-
-From client/src/services/api.js (EXISTING — must be updated):
-```javascript
-// Currently:
-export const checkHealth = () => request('/health');
-export const getSystemHealth = (options) => request('/health/system', options);
-// Must become:
-export const checkHealth = () => request('/system/health');
-export const getSystemHealth = (options) => request('/system/health/details', options);
-```
-
-Health Auto Export JSON schema (from research):
-```json
-{
- "data": {
- "metrics": [
- {
- "name": "step_count",
- "units": "count",
- "data": [{ "qty": 8432, "date": "2024-01-15 08:30:00 -0800" }]
- }
- ]
- }
-}
-```
-
-Day-partitioned file schema:
-```json
-{
- "date": "2024-01-15",
- "metrics": {
- "step_count": [
- { "date": "2024-01-15 08:30:00 -0800", "qty": 4211, "unit": "count" }
- ]
- },
- "updated": "2024-01-16T10:00:00.000Z"
-}
-```
-</interfaces>
-</context>
-
-<tasks>
-
-<task type="auto">
- <name>Task 1: Rename system health routes to free /api/health namespace</name>
- <files>
- server/routes/health.js
- server/routes/systemHealth.js
- server/index.js
- client/src/services/api.js
- </files>
- <action>
-**Why:** The existing `server/routes/health.js` registers GET `/health` and GET `/health/system`, mounted at `app.use('/api', healthRoutes)` in index.js. This means GET `/api/health` and GET `/api/health/system` are taken. The locked decision from CONTEXT.md specifies Health Auto Export pushes to `/api/health/ingest`. To avoid route collision, we must relocate the system health endpoints to `/api/system/health`.
-
-**1. Rename server/routes/health.js to server/routes/systemHealth.js:**
-
-Use `git mv server/routes/health.js server/routes/systemHealth.js` to preserve git history.
-
-**2. Update route paths inside server/routes/systemHealth.js:**
-
-Change the two route definitions:
-- `router.get('/health', ...)` becomes `router.get('/health', ...)` (unchanged, since mount point changes)
-- `router.get('/health/system', ...)` becomes `router.get('/health/details', ...)` (rename `/system` to `/details` to avoid redundancy with the new `/api/system` mount point)
-
-The routes inside the file should be:
-```javascript
-router.get('/health', async (req, res) => { ... }); // → GET /api/system/health
-router.get('/health/details', async (req, res) => { ... }); // → GET /api/system/health/details
-```
-
-**3. Update server/index.js:**
-
-Change the import:
-```javascript
-// Before:
-import healthRoutes from './routes/health.js';
-// After:
-import systemHealthRoutes from './routes/systemHealth.js';
-```
-
-Change the route registration:
-```javascript
-// Before:
-app.use('/api', healthRoutes);
-// After:
-app.use('/api/system', systemHealthRoutes);
-```
-
-Place the new registration alphabetically among the other `/api/*` routes — near `/api/standardize` or `/api/settings`.
-
-**4. Update client/src/services/api.js:**
-
-Change the two system health API calls:
-```javascript
-// Before:
-export const checkHealth = () => request('/health');
-export const getSystemHealth = (options) => request('/health/system', options);
-// After:
-export const checkHealth = () => request('/system/health');
-export const getSystemHealth = (options) => request('/system/health/details', options);
-```
-
-**5. Search for any other references to the old paths:**
-
-Run `grep -r "/api/health" client/src/ server/` to find any other references to the old `/api/health` or `/health/system` paths. Update any found references. Key places to check:
-- Dashboard components that call `checkHealth()` or `getSystemHealth()` — these call the API functions, not URLs directly, so they should work without changes.
-- Any test files referencing `/api/health` — update to `/api/system/health`.
- </action>
- <verify>
- <automated>cd server && npm test</automated>
- </verify>
- <done>
- - server/routes/health.js renamed to server/routes/systemHealth.js via git mv
- - System health routes now at GET /api/system/health and GET /api/system/health/details
- - server/index.js updated: import systemHealthRoutes, mount at /api/system
- - client/src/services/api.js updated: checkHealth and getSystemHealth use new paths
- - No stale references to old /api/health or /api/health/system paths remain
- - All existing tests pass
- </done>
-</task>
-
-<task type="auto">
- <name>Task 2: Create validation schemas, ingest service, and day-partitioned storage</name>
- <files>
- server/lib/appleHealthValidation.js
- server/services/appleHealthIngest.js
- server/lib/fileUtils.js
- </files>
- <action>
-**1. Add PATHS.health to fileUtils.js:**
-
-In `server/lib/fileUtils.js`, add to the PATHS object:
-```javascript
-health: join(__lib_dirname, '../../data/health'),
-```
-Place it alphabetically between `digitalTwin` and `memory`.
-
-**2. Create server/lib/appleHealthValidation.js:**
-
-Zod schemas following the meatspaceValidation.js pattern:
-
-- `healthDataPointSchema`: Object with `date` (string, required), `qty` (number, optional), `Min`/`Avg`/`Max` (number, optional for heart rate), `totalSleep`/`deep`/`rem`/`core`/`awake` (number, optional for sleep). Use `.passthrough()` to allow future fields from app updates.
-
-- `healthMetricSchema`: Object with `name` (string, min 1), `units` (string, optional), `data` (array of healthDataPointSchema).
-
-- `healthIngestSchema`: Object with `data` (object containing `metrics` array of healthMetricSchema, defaulting to `[]`, and `workouts` array of `z.unknown()`, defaulting to `[]`). Use `.passthrough()` on the `data` object to allow future Health Auto Export fields.
-
-Export all three schemas.
-
-**3. Create server/services/appleHealthIngest.js:**
-
-Pure functions + file I/O service:
-
-- `extractDateStr(dateString)`: Extract YYYY-MM-DD from Apple Health timestamp string. Use `dateString.substring(0, 10)` (not Date parsing) to avoid timezone conversion issues per research pitfall 5. Validate with regex `/^\d{4}-\d{2}-\d{2}$/`. Return null for invalid dates.
-
-- `dedupKey(metricName, dateString)`: Return `${metricName}::${dateString}` for dedup comparisons.
-
-- `readDayFile(dateStr)`: Read `join(PATHS.health, dateStr + '.json')` using `readJSONFile` with default `{ date: dateStr, metrics: {} }`.
-
-- `writeDayFile(dateStr, data)`: Ensure PATHS.health dir exists, set `data.updated = new Date().toISOString()`, write JSON with 2-space indent.
-
-- `mergeIntoDay(dateStr, metricName, newPoints)`: Load existing day file, build Set of existing date strings for that metric, filter new points to only those not already present, append unique points, write day file. Return count of new unique points added.
-
-- `ingestHealthData(payload)`: Main entry point. Iterate `payload.data.metrics`. For each metric, group its `data` points by extracted date string (skip points with null/invalid date). For each day group, call `mergeIntoDay`. Accumulate totals. Return `{ metricsProcessed, recordsIngested, recordsSkipped (dupes), daysAffected }`. Log with emoji prefix: `console.log('🍎 Health ingest: ${recordsIngested} records across ${daysAffected} days')`.
-
-**Important:** All metric types from the payload are stored (not just the core four). The decision locks "import ALL Apple Health metric types."
- </action>
- <verify>
- <automated>cd server && node -e "import('./lib/appleHealthValidation.js').then(m => { const r = m.healthIngestSchema.safeParse({ data: { metrics: [{ name: 'step_count', units: 'count', data: [{ date: '2024-01-15 08:30:00 -0800', qty: 100 }] }] } }); console.log(r.success ? 'PASS' : 'FAIL: ' + JSON.stringify(r.error.issues)); })"</automated>
- </verify>
- <done>
- - healthIngestSchema validates Health Auto Export JSON format with passthrough for future fields
- - extractDateStr correctly pulls YYYY-MM-DD from timestamp strings without timezone conversion
- - mergeIntoDay deduplicates by metric name + date string, skipping existing records
- - Day files written to data/health/YYYY-MM-DD.json with correct schema
- - PATHS.health added to fileUtils.js
- </done>
-</task>
-
-<task type="auto">
- <name>Task 3: Create query service, REST routes, and client API functions</name>
- <files>
- server/services/appleHealthQuery.js
- server/routes/appleHealth.js
- server/index.js
- client/src/services/api.js
- </files>
- <action>
-**1. Create server/services/appleHealthQuery.js:**
-
-Query functions for reading health data:
-
-- `listDayFiles()`: Read the `PATHS.health` directory, return sorted array of date strings (from filenames without .json extension). Handle dir not existing (return `[]`).
-
-- `getAvailableDateRange()`: Call `listDayFiles()`, return `{ from: firstDate, to: lastDate, totalDays }` or null if no files.
-
-- `getMetrics(metricName, from, to)`: Read day files in the date range. For each day file, extract the metric's data array. Return flat array of all data points across the range, sorted by date. If `from`/`to` not provided, default to last 7 days.
-
-- `getMetricSummary(metricName, from, to)`: Call `getMetrics`, then compute summary stats: `count`, `latest` (most recent data point), `average` (of `qty` values if present, or `Avg` for heart rate). Return `{ metricName, count, latest, average, from, to, dataPoints }`.
-
-- `getDailyAggregates(metricName, from, to)`: Group data points by day and aggregate. For `step_count`: sum `qty` per day. For `heart_rate`: average of `Avg` values per day. For `heart_rate_variability_sdnn`: average `qty` per day. For `sleep_analysis`: take `totalSleep` directly. For all others: average `qty`. Return array of `{ date, value }` objects.
-
-- `getCorrelationData(from, to)`: Read health metrics AND alcohol data (import `getDailyAlcohol` from `meatspaceAlcohol.js`) for the date range. Build daily records with: `{ date, hrv, alcoholGrams, steps }`. Return the merged array. Also read blood tests (import `getBloodTests` from `meatspaceHealth.js`) for activity-blood correlation. Return `{ dailyData, bloodTests }`.
-
-**2. Create server/routes/appleHealth.js:**
-
-Following backup.js route pattern with asyncHandler:
-
-- `POST /ingest`: Validate body with `healthIngestSchema` using `validateRequest`. Call `ingestHealthData(validated)`. Return result object.
-
-- `GET /metrics/:metricName`: Query params `from`, `to` (optional strings). Call `getMetricSummary(metricName, from, to)`. Return summary.
-
-- `GET /metrics/:metricName/daily`: Query params `from`, `to`. Call `getDailyAggregates(metricName, from, to)`. Return array.
-
-- `GET /range`: Call `getAvailableDateRange()`. Return range object.
-
-- `GET /correlation`: Query params `from`, `to`. Call `getCorrelationData(from, to)`. Return correlation data.
-
-Export default router.
-
-**3. Register routes in server/index.js:**
-
-Add import at top (alphabetical with other route imports):
-```javascript
-import appleHealthRoutes from './routes/appleHealth.js';
-```
-
-Add route registration — mount at `/api/health` to match the locked decision path `/api/health/ingest`:
-```javascript
-app.use('/api/health', appleHealthRoutes);
-```
-
-Place this before `/api/instances` (alphabetically). Note: The old system health routes were already moved to `/api/system` in Task 1, so `/api/health` is now free.
-
-**4. Add client API functions in client/src/services/api.js:**
-
-Add a new section "// Apple Health" (alphabetical placement, near the top after "// Apps"):
-
-```javascript
-// Apple Health
-export const ingestAppleHealth = (data) => request('/health/ingest', {
- method: 'POST',
- body: JSON.stringify(data)
-});
-export const getAppleHealthMetrics = (metricName, from, to) => {
- const params = new URLSearchParams();
- if (from) params.set('from', from);
- if (to) params.set('to', to);
- return request(`/health/metrics/${metricName}/daily?${params}`);
-};
-export const getAppleHealthSummary = (metricName, from, to) => {
- const params = new URLSearchParams();
- if (from) params.set('from', from);
- if (to) params.set('to', to);
- return request(`/health/metrics/${metricName}?${params}`);
-};
-export const getAppleHealthRange = () => request('/health/range');
-export const getAppleHealthCorrelation = (from, to) => {
- const params = new URLSearchParams();
- if (from) params.set('from', from);
- if (to) params.set('to', to);
- return request(`/health/correlation?${params}`);
-};
-```
- </action>
- <verify>
- <automated>cd server && node -e "import('./routes/appleHealth.js').then(m => console.log(m.default ? 'PASS: router exported' : 'FAIL'))" && node -e "import('./services/appleHealthQuery.js').then(m => console.log(typeof m.getMetrics === 'function' && typeof m.getDailyAggregates === 'function' ? 'PASS' : 'FAIL'))"</automated>
- </verify>
- <done>
- - GET /api/health/metrics/:metricName returns metric summary for date range
- - GET /api/health/metrics/:metricName/daily returns daily aggregated values
- - GET /api/health/range returns available data date range
- - GET /api/health/correlation returns merged HRV+alcohol+steps+blood data
- - POST /api/health/ingest validates and persists Health Auto Export JSON
- - Route registered in index.js at /api/health (namespace freed by Task 1)
- - Client API functions added for all endpoints using /health/* paths
- </done>
-</task>
-
-</tasks>
-
-<verification>
-1. `curl -s http://localhost:5554/api/system/health | node -e "process.stdin.on('data',d=>{const r=JSON.parse(d);console.log(r.status==='ok'?'PASS':'FAIL')})"` -- system health moved successfully
-2. `cd server && node -e "import('./lib/appleHealthValidation.js').then(m => console.log('validation OK'))"` -- validation module loads
-3. `cd server && node -e "import('./services/appleHealthIngest.js').then(m => console.log('ingest OK'))"` -- ingest service loads
-4. `cd server && node -e "import('./services/appleHealthQuery.js').then(m => console.log('query OK'))"` -- query service loads
-5. `cd server && node -e "import('./routes/appleHealth.js').then(m => console.log('routes OK'))"` -- routes load
-6. `cd server && npm test` -- all existing tests pass (no regressions)
-</verification>
-
-<success_criteria>
-- Existing system health endpoints relocated to /api/system/health and /api/system/health/details
-- POST /api/health/ingest accepts Health Auto Export JSON and returns record counts (matches locked decision)
-- Duplicate records are silently skipped on re-ingest
-- Data persists to data/health/YYYY-MM-DD.json files
-- Query service returns aggregated metrics for date ranges
-- All existing tests pass
-</success_criteria>
-
-<output>
-After completion, create `.planning/phases/03-apple-health-integration/03-01-SUMMARY.md`
-</output>
diff --git a/.planning/phases/03-apple-health-integration/03-01-SUMMARY.md b/.planning/phases/03-apple-health-integration/03-01-SUMMARY.md
deleted file mode 100644
index 7f73fa23ba..0000000000
--- a/.planning/phases/03-apple-health-integration/03-01-SUMMARY.md
+++ /dev/null
@@ -1,113 +0,0 @@
----
-phase: 03-apple-health-integration
-plan: "01"
-subsystem: health-ingest
-tags: [apple-health, ingest, validation, zod, day-partitioned-storage, query-service]
-dependency_graph:
- requires: []
- provides:
- - POST /api/health/ingest (Health Auto Export JSON ingest with dedup)
- - GET /api/health/metrics/:name (metric summary by date range)
- - GET /api/health/metrics/:name/daily (daily aggregated values)
- - GET /api/health/range (available data date range)
- - GET /api/health/correlation (merged HRV+alcohol+steps+blood data)
- - GET /api/system/health (renamed from /api/health)
- - GET /api/system/health/details (renamed from /api/health/system)
- affects:
- - client/src/services/api.js (checkHealth, getSystemHealth paths updated; Apple Health API functions added)
- - 03-02-PLAN.md (XML import can now call ingestHealthData)
- - 03-03-PLAN.md (dashboard cards use getAppleHealthMetrics, getAppleHealthSummary)
-tech_stack:
- added: []
- patterns:
- - Day-partitioned JSON files at data/health/YYYY-MM-DD.json
- - Deduplication by metric name + full date string (Set-based O(1) lookup)
- - substring(0,10) for timezone-safe date extraction from Apple Health timestamps
- - passthrough() on Zod schemas for future Health Auto Export field compatibility
-key_files:
- created:
- - server/lib/appleHealthValidation.js
- - server/services/appleHealthIngest.js
- - server/services/appleHealthQuery.js
- - server/routes/appleHealth.js
- modified:
- - server/lib/fileUtils.js (added PATHS.health)
- - server/index.js (systemHealthRoutes at /api/system, appleHealthRoutes at /api/health)
- - client/src/services/api.js (checkHealth/getSystemHealth paths + 5 Apple Health functions)
- - server/routes/systemHealth.js (renamed from health.js via git mv, /health/system -> /health/details)
- - server/routes/health.test.js (updated to import systemHealth.js, use /api/system/health)
-decisions:
- - "Extracted YYYY-MM-DD using substring(0,10) not Date() to prevent timezone shift on Apple Health timestamps"
- - "Used passthrough() on healthDataPointSchema and data object to support future Health Auto Export fields"
- - "Dedup key is the full date string (not extracted date) to distinguish multiple readings on same day"
- - "Renamed /health/system to /health/details inside systemHealth.js to avoid redundancy with /api/system mount point"
- - "getDailyAggregates uses per-metric strategy: step_count sums qty, heart_rate averages Avg, sleep_analysis takes totalSleep, default averages qty"
-metrics:
- duration: 210s
- tasks_completed: 3
- files_created: 4
- files_modified: 5
- completed_date: "2026-02-26"
----
-
-# Phase 03 Plan 01: Apple Health Ingest Pipeline Summary
-
-**One-liner:** Zod-validated Health Auto Export JSON ingest with timezone-safe dedup into day-partitioned files, REST query API, correlation endpoint, and system health namespace relocation to /api/system.
-
-## What Was Built
-
-### Task 1: System Health Route Relocation
-Freed the `/api/health` namespace by moving system health endpoints:
-- `server/routes/health.js` renamed to `server/routes/systemHealth.js` via `git mv`
-- Route `/health/system` renamed to `/health/details` inside the file (avoids redundancy with mount at `/api/system`)
-- `server/index.js`: `app.use('/api/system', systemHealthRoutes)` replaces `app.use('/api', healthRoutes)`
-- `client/src/services/api.js`: `checkHealth` now calls `/system/health`, `getSystemHealth` calls `/system/health/details`
-- Test updated to import `systemHealth.js` and use new path
-
-### Task 2: Validation Schemas and Ingest Service
-- `server/lib/appleHealthValidation.js`: `healthDataPointSchema` (passthrough for future fields), `healthMetricSchema`, `healthIngestSchema`
-- `server/lib/fileUtils.js`: added `PATHS.health = data/health/`
-- `server/services/appleHealthIngest.js`:
- - `extractDateStr()`: uses `substring(0,10)` to avoid timezone conversion (research pitfall 5)
- - `dedupKey()`: produces `metricName::dateString` composite key
- - `readDayFile()` / `writeDayFile()`: reads/writes `data/health/YYYY-MM-DD.json`
- - `mergeIntoDay()`: deduplicates by building Set of existing date strings, appends only unique points
- - `ingestHealthData()`: groups all metric data points by day, calls mergeIntoDay, returns `{ metricsProcessed, recordsIngested, recordsSkipped, daysAffected }`
-
-### Task 3: Query Service, REST Routes, and Client Functions
-- `server/services/appleHealthQuery.js`:
- - `listDayFiles()`: reads health dir, filters/sorts YYYY-MM-DD.json files
- - `getAvailableDateRange()`: returns `{ from, to, totalDays }` or null
- - `getMetrics()`: flat array of all data points for a metric in date range
- - `getMetricSummary()`: count, latest, average (qty or Avg), plus raw dataPoints
- - `getDailyAggregates()`: per-metric strategy (step_count sums, heart_rate averages Avg, HRV averages qty, sleep takes totalSleep, others average qty)
- - `getCorrelationData()`: merges HRV + steps + alcohol (from meatspaceAlcohol) + blood tests (from meatspaceHealth)
-- `server/routes/appleHealth.js`: 5 REST endpoints using asyncHandler + validateRequest pattern
-- `server/index.js`: registered `app.use('/api/health', appleHealthRoutes)` before `/api/instances`
-- `client/src/services/api.js`: added `ingestAppleHealth`, `getAppleHealthMetrics`, `getAppleHealthSummary`, `getAppleHealthRange`, `getAppleHealthCorrelation`
-
-## Decisions Made
-
-1. **Timezone-safe date extraction** — `substring(0,10)` instead of `new Date()` to avoid timezone shift on Apple Health timestamps like `"2024-01-15 08:30:00 -0800"`. `new Date()` would convert to UTC, shifting dates near midnight to the wrong day.
-
-2. **passthrough() on schemas** — `healthDataPointSchema` and the `data` object use `.passthrough()` so future fields added by Health Auto Export app updates don't break validation.
-
-3. **Full date string as dedup key** — Dedup uses the full date string from the data point (e.g., `"2024-01-15 08:30:00 -0800"`), not just the extracted YYYY-MM-DD. This correctly distinguishes multiple readings on the same calendar day (e.g., two heart rate readings at different times).
-
-4. **Route rename from /health/system to /health/details** — When mounting at `/api/system`, the route `/health/system` would produce `/api/system/health/system` which is redundant. Renamed to `/health/details` for `/api/system/health/details`.
-
-5. **Per-metric daily aggregation strategies** — Different metrics require different aggregation: step_count needs a sum (not average) of all steps in a day; heart_rate uses the `Avg` field not `qty`; sleep_analysis has `totalSleep` not `qty`. Hardcoded per-metric strategies with a sensible default.
-
-## Deviations from Plan
-
-None — plan executed exactly as written.
-
-## Self-Check: PASSED
-
-Verified:
-- `server/lib/appleHealthValidation.js` exists and healthIngestSchema validates test payload
-- `server/services/appleHealthIngest.js` loads, extractDateStr returns `2024-01-15` from `"2024-01-15 08:30:00 -0800"`
-- `server/services/appleHealthQuery.js` loads, getMetrics and getDailyAggregates are functions
-- `server/routes/appleHealth.js` loads, router exported
-- All 1192 tests pass (42 test files, 0 regressions)
-- Commits: 7c2a592 (Task 1), 200a0d2 (Task 2), 2cd855f (Task 3)
diff --git a/.planning/phases/03-apple-health-integration/03-02-PLAN.md b/.planning/phases/03-apple-health-integration/03-02-PLAN.md
deleted file mode 100644
index 4c93b260cb..0000000000
--- a/.planning/phases/03-apple-health-integration/03-02-PLAN.md
+++ /dev/null
@@ -1,355 +0,0 @@
----
-phase: 03-apple-health-integration
-plan: 02
-type: execute
-wave: 2
-depends_on:
- - 03-01
-files_modified:
- - server/services/appleHealthXml.js
- - server/routes/appleHealth.js
- - client/src/components/meatspace/tabs/ImportTab.jsx
-autonomous: false
-requirements:
- - HLT-03
- - HLT-04
-
-must_haves:
- truths:
- - "Uploading a 500MB+ Apple Health XML export completes without OOM errors"
- - "XML import progress (record count) updates in real-time via WebSocket during import"
- - "XML records are normalized to the same day-file format as JSON ingest (metric names mapped from HK identifiers)"
- - "Sleep XML records with categorical values are correctly parsed into duration-based stage data"
- - "Import tab shows a working file picker and progress bar for Apple Health XML upload"
- artifacts:
- - path: "server/services/appleHealthXml.js"
- provides: "SAX streaming XML parser for Apple Health exports"
- exports: ["importAppleHealthXml"]
- - path: "server/routes/appleHealth.js"
- provides: "POST /import/xml endpoint with multer diskStorage"
- contains: "upload.single"
- - path: "client/src/components/meatspace/tabs/ImportTab.jsx"
- provides: "XML file picker with WebSocket progress bar"
- contains: "health:xml:progress"
- key_links:
- - from: "server/routes/appleHealth.js"
- to: "server/services/appleHealthXml.js"
- via: "importAppleHealthXml(filePath, io)"
- pattern: "importAppleHealthXml"
- - from: "client/src/components/meatspace/tabs/ImportTab.jsx"
- to: "socket.io client"
- via: "socket.on('health:xml:progress')"
- pattern: "health:xml:progress"
- - from: "server/services/appleHealthXml.js"
- to: "server/services/appleHealthIngest.js"
- via: "readDayFile/writeDayFile for persistence"
- pattern: "writeDayFile"
----
-
-<objective>
-Build the streaming XML import pipeline for bulk Apple Health exports (500MB+) using SAX parsing, and update the Import tab with a working file picker and real-time WebSocket progress bar.
-
-Purpose: Enables importing years of historical Apple Health data from iOS exports without memory issues.
-Output: Working XML upload at POST /api/health/import/xml, real-time progress in Import tab.
-</objective>
-
-<execution_context>
-@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
-@/Users/antic/.claude/get-shit-done/templates/summary.md
-</execution_context>
-
-<context>
[email protected]/phases/03-apple-health-integration/03-RESEARCH.md
[email protected]/phases/03-apple-health-integration/03-01-SUMMARY.md
-
-@server/services/appleHealthIngest.js — readDayFile, writeDayFile from Plan 03-01
-@server/routes/appleHealth.js — Existing routes from Plan 03-01
-@server/routes/backup.js — io.emit WebSocket pattern
-@client/src/components/meatspace/tabs/ImportTab.jsx — Existing import tab with Apple Health placeholder
-@client/src/services/socket.js — Socket.io client
-
-<interfaces>
-<!-- From Plan 03-01 (will exist by execution time) -->
-
-From server/services/appleHealthIngest.js:
-```javascript
-export async function readDayFile(dateStr) { ... }
-export async function writeDayFile(dateStr, data) { ... }
-export function extractDateStr(dateString) { ... }
-```
-
-From server/routes/appleHealth.js:
-```javascript
-// Router mounted at /api/health with existing POST /ingest and GET endpoints
-// Add POST /import/xml to this same router
-```
-
-WebSocket pattern (from backup.js):
-```javascript
-const io = req.app.get('io');
-// Service emits: io.emit('health:xml:progress', { processed, total })
-// Service emits: io.emit('health:xml:complete', { days, records })
-```
-
-Apple Health XML Record structure:
-```xml
-<Record type="HKQuantityTypeIdentifierStepCount" value="432" startDate="2024-01-15 10:00:00 -0800" endDate="..." unit="count" sourceName="iPhone"/>
-<Record type="HKCategoryTypeIdentifierSleepAnalysis" value="HKCategoryValueSleepAnalysisAsleepDeep" startDate="..." endDate="..."/>
-```
-</interfaces>
-</context>
-
-<tasks>
-
-<task type="auto">
- <name>Task 1: Create SAX XML streaming service and add XML import route</name>
- <files>
- server/services/appleHealthXml.js
- server/routes/appleHealth.js
- </files>
- <action>
-**Install dependencies first:**
-```bash
-cd server && npm install sax multer
-```
-
-**1. Create server/services/appleHealthXml.js:**
-
-Streaming SAX XML parser for Apple Health exports. Key components:
-
-**XML-to-metric name mapping:**
-```javascript
-const XML_TO_METRIC_NAME = {
- 'HKQuantityTypeIdentifierStepCount': 'step_count',
- 'HKQuantityTypeIdentifierHeartRate': 'heart_rate',
- 'HKQuantityTypeIdentifierHeartRateVariabilitySDNN': 'heart_rate_variability_sdnn',
- 'HKCategoryTypeIdentifierSleepAnalysis': 'sleep_analysis',
- // All other types: store with original HK identifier (lowercase normalized)
-};
-```
-
-**Sleep stage mapping:**
-```javascript
-const SLEEP_STAGE_MAP = {
- 'HKCategoryValueSleepAnalysisAsleepDeep': 'deep',
- 'HKCategoryValueSleepAnalysisAsleepREM': 'rem',
- 'HKCategoryValueSleepAnalysisAsleepCore': 'core',
- 'HKCategoryValueSleepAnalysisAwake': 'awake',
- 'HKCategoryValueSleepAnalysisInBed': 'inBed',
- 'HKCategoryValueSleepAnalysisAsleep': 'asleep' // Legacy pre-iOS 16
-};
-```
-
-**`normalizeXmlRecord(node)`:** Pure function. Takes SAX opentag node with attributes. Returns `{ metricName, dateStr, dataPoint }` or null for invalid records.
-
-- Extract `type`, `value`, `startdate`, `enddate`, `unit`, `sourcename` from `node.attributes` (lowercase because `sax.createStream(false, { lowercase: true })`).
-- Map `type` via `XML_TO_METRIC_NAME`, falling back to lowercase type string for unknown types.
-- Extract dateStr using `extractDateStr(startdate)` from appleHealthIngest.js. Return null if invalid.
-- For sleep analysis (`type === 'hkcategorytypeidentifiersleepanalysis'` — lowercase): Calculate duration in hours from `(new Date(enddate) - new Date(startdate)) / 3600000`. Map `value` via `SLEEP_STAGE_MAP`. Create data point with `{ date: startdate, stage: mappedStage, durationHours: duration }`.
-- For numeric types: Create data point with `{ date: startdate, qty: parseFloat(value), unit: unit ?? null, src: sourcename ?? null }`. If `type` is heart rate, also add `end: enddate`.
-- Skip records where `startdate` is missing.
-
-**`importAppleHealthXml(filePath, io = null)`:** Main export.
-
-- Create `sax.createStream(false, { lowercase: true })` (non-strict mode per research pitfall 1).
-- Accumulate records into `dayBuckets = {}` keyed by dateStr, then by metricName.
-- On `opentag`: If `node.name !== 'record'`, return. Call `normalizeXmlRecord(node)`. If result is null, skip. Accumulate into dayBuckets. Increment `processedRecords`. Every 10000 records, emit `io.emit('health:xml:progress', { processed: processedRecords })` and log `console.log('🍎 XML import progress: ${processedRecords} records')`.
-- On `error`: Clear `this._parser.error = null`, call `this._parser.resume()` (per research pitfall 1 — Apple Health XML can have minor malformations). Log error with `console.error('❌ XML parse error at record ${processedRecords}: ${e.message}')`.
-- Pipe `createReadStream(filePath)` to saxStream. Await stream end via Promise.
-- **After parsing completes:** For step_count in dayBuckets, aggregate: sum all `qty` values per day into a single entry (per research pitfall 3). For sleep_analysis, aggregate stage durations per day into a single summary: `{ date, totalSleep, deep, rem, core, awake }` (sum durations by stage).
-- Write all day files sequentially (not during SAX event loop — per research pitfall 7). For each dateStr in dayBuckets: read existing day file, merge new metrics (dedup by date string within each metric), write back.
-- Delete temp file: `unlink(filePath, () => {})`.
-- Emit `io.emit('health:xml:complete', { days: Object.keys(dayBuckets).length, records: processedRecords })`.
-- Log `console.log('🍎 XML import complete: ${processedRecords} records across ${days} days')`.
-- Return `{ days: daysCount, records: processedRecords }`.
-
-Export `normalizeXmlRecord` (for testing) and `importAppleHealthXml`.
-
-**2. Add XML import route to server/routes/appleHealth.js:**
-
-At the top of the file, add imports:
-```javascript
-import multer from 'multer';
-import { tmpdir } from 'os';
-import { importAppleHealthXml } from '../services/appleHealthXml.js';
-```
-
-Configure multer with diskStorage (NOT memoryStorage — per research, avoids OOM on 500MB files):
-```javascript
-const upload = multer({
- storage: multer.diskStorage({
- destination: (req, file, cb) => cb(null, tmpdir()),
- filename: (req, file, cb) => cb(null, `apple-health-${Date.now()}.xml`)
- }),
- limits: { fileSize: 2 * 1024 * 1024 * 1024 }, // 2GB max
- fileFilter: (req, file, cb) => {
- if (file.mimetype === 'text/xml' || file.mimetype === 'application/xml' || file.originalname.endsWith('.xml')) {
- cb(null, true);
- } else {
- cb(new ServerError('Only XML files are accepted', 400));
- }
- }
-});
-```
-
-Add route:
-```javascript
-// POST /api/health/import/xml
-router.post('/import/xml', upload.single('file'), asyncHandler(async (req, res) => {
- const io = req.app.get('io');
- const filePath = req.file?.path;
- if (!filePath) throw new ServerError('No file uploaded', 400);
- const result = await importAppleHealthXml(filePath, io);
- res.json(result);
-}));
-```
- </action>
- <verify>
- <automated>cd server && node -e "import('./services/appleHealthXml.js').then(m => console.log(typeof m.importAppleHealthXml === 'function' && typeof m.normalizeXmlRecord === 'function' ? 'PASS' : 'FAIL'))"</automated>
- </verify>
- <done>
- - SAX streaming parser handles Apple Health XML without loading file into memory
- - XML metric types mapped to normalized metric names matching JSON ingest format
- - Sleep categorical values parsed into duration-based stage data
- - Step counts aggregated per day (not raw sensor readings)
- - Non-strict SAX mode handles malformed XML gracefully
- - WebSocket progress emitted every 10000 records
- - Temp file cleaned up after import
- - POST /import/xml route uses multer diskStorage with 2GB limit
- </done>
-</task>
-
-<task type="auto">
- <name>Task 2: Update Import tab with Apple Health XML file picker and progress bar</name>
- <files>
- client/src/components/meatspace/tabs/ImportTab.jsx
- client/src/services/api.js
- </files>
- <action>
-**1. Add XML upload API function in client/src/services/api.js:**
-
-Add to the "// Apple Health" section (created in Plan 03-01):
-```javascript
-export const uploadAppleHealthXml = (file) => {
- const formData = new FormData();
- formData.append('file', file);
- return fetch(`${API_BASE}/health/import/xml`, {
- method: 'POST',
- body: formData
- // No Content-Type header — browser sets multipart boundary automatically
- }).then(async res => {
- if (!res.ok) {
- const err = await res.json().catch(() => ({ error: res.statusText }));
- throw new Error(err.error || res.statusText);
- }
- return res.json();
- });
-};
-```
-
-Note: This uses `fetch` directly instead of the `request` helper because `request` sets `Content-Type: application/json` which conflicts with `multipart/form-data`. The FormData upload needs the browser to set the Content-Type with the correct boundary.
-
-**2. Replace the Apple Health placeholder in ImportTab.jsx:**
-
-Remove the disabled placeholder section (the `<div>` with `opacity-60` and "Coming soon" text, lines ~134-143 of current file).
-
-Replace with a working Apple Health XML import section:
-
-- Import `socket` from `'../../../services/socket'` and `uploadAppleHealthXml` from api.
-- Add state: `xmlImporting`, `xmlProgress`, `xmlResult`, `xmlError`, `xmlFileName`.
-- Add `xmlFileInputRef` useRef.
-- Add useEffect for WebSocket listeners:
- ```javascript
- useEffect(() => {
- const onProgress = ({ processed }) => setXmlProgress(processed);
- const onComplete = (result) => { setXmlResult(result); setXmlImporting(false); };
- socket.on('health:xml:progress', onProgress);
- socket.on('health:xml:complete', onComplete);
- return () => {
- socket.off('health:xml:progress', onProgress);
- socket.off('health:xml:complete', onComplete);
- };
- }, []);
- ```
-- Add `handleXmlFileSelect` handler: Get file from input, validate `.xml` extension, set `xmlImporting(true)`, `xmlProgress(0)`, clear errors/results, call `uploadAppleHealthXml(file)`. On error, set xmlError. On success, result comes via WebSocket `onComplete`.
-
-UI structure (matching the existing TSV import card style):
-- Card with `bg-port-card border border-port-border rounded-xl p-6`.
-- Header: Apple icon (use `Upload` from lucide, or `Apple` if available — check lucide-react; if not, use `HeartPulse`) + "Apple Health XML Import" in uppercase tracking-wider.
-- Description: "Import your Apple Health export. On your iPhone: Settings > Health > Export All Health Data. Extract the ZIP and select the export.xml file."
-- Instruction note: "Extract the ZIP file first — upload the export.xml file directly."
-- File picker button: Same style as TSV button. Accepts `.xml` files only.
-- During import: Show progress bar with `bg-port-accent` fill and record count text: "{xmlProgress.toLocaleString()} records processed". Use a pulsing/animated progress bar since total count is unknown (indeterminate style with the record count as text).
-- On complete: Show success card with days and records counts (matching TSV success card style).
-- On error: Show error card (matching TSV error card style).
- </action>
- <verify>
- <automated>cd server && npm test && cd ../client && npm run build</automated>
- </verify>
- <done>
- - Apple Health placeholder replaced with working XML file picker
- - File picker accepts .xml files only
- - Progress bar shows live record count during import via WebSocket
- - Success state shows days and records imported
- - Error state displays error message
- - Import follows existing TSV import card styling
- - Instructions tell user to extract ZIP and upload export.xml
- - Client builds cleanly with new component
- </done>
-</task>
-
-<task type="checkpoint:human-verify" gate="blocking">
- <name>Task 3: Verify XML import and ingest pipeline</name>
- <files>none (verification only)</files>
- <action>
-Human verification checkpoint. Verify:
-1. The Import tab shows the Apple Health XML Import section (replacing the old placeholder)
-2. The file picker accepts only .xml files
-3. POST /api/health/ingest works with curl test data
-4. Day-partitioned files are created in data/health/
-5. Dedup works on repeated ingest
- </action>
- <verify>
- <automated>curl -s -X POST http://localhost:5554/api/health/ingest -H 'Content-Type: application/json' -d '{"data":{"metrics":[{"name":"step_count","units":"count","data":[{"date":"2024-01-15 08:30:00 -0800","qty":8432}]}]}}' | node -e "process.stdin.on('data',d=>{const r=JSON.parse(d);console.log(r.recordsIngested>0?'PASS':'FAIL')})"</automated>
- </verify>
- <done>XML import pipeline and JSON ingest verified end-to-end, Import tab UI confirmed</done>
- <what-built>Apple Health XML import pipeline with streaming SAX parser, WebSocket progress, and Import tab UI</what-built>
- <how-to-verify>
- 1. Navigate to MeatSpace page and find the Import tab (check if it is accessible from the Lifestyle tab or a separate import section)
- 2. Verify the Apple Health XML Import section replaces the old placeholder
- 3. Verify the file picker only accepts .xml files
- 4. If you have an Apple Health export.xml available, test importing it. Otherwise, verify the UI renders correctly with proper styling.
- 5. Verify `curl -X POST http://localhost:5554/api/health/ingest -H 'Content-Type: application/json' -d '{"data":{"metrics":[{"name":"step_count","units":"count","data":[{"date":"2024-01-15 08:30:00 -0800","qty":8432}]}]}}'` returns success with recordsIngested count
- 6. Verify `ls data/health/` shows `2024-01-15.json` was created
- 7. Re-run the same curl command and verify `recordsSkipped` increases (dedup working)
- </how-to-verify>
- <resume-signal>Type "approved" or describe issues</resume-signal>
-</task>
-
-</tasks>
-
-<verification>
-1. `npm install` in server completes with `sax` and `multer` added to package.json
-2. POST /api/health/ingest accepts and persists Health Auto Export JSON
-3. POST /api/health/import/xml accepts XML upload via multipart form
-4. Import tab shows Apple Health XML import section with progress bar
-5. `cd server && npm test` — all existing tests pass
-6. `cd client && npm run build` — client compiles cleanly
-</verification>
-
-<success_criteria>
-- Apple Health XML files (500MB+) can be imported without OOM via SAX streaming
-- Import progress updates in real-time via WebSocket (record count every 10k records)
-- XML metric types are normalized to match JSON ingest metric names
-- Sleep XML categorical values are correctly converted to duration data
-- Import tab has working file picker replacing the disabled placeholder
-- All existing tests pass
-- Client builds without errors
-</success_criteria>
-
-<output>
-After completion, create `.planning/phases/03-apple-health-integration/03-02-SUMMARY.md`
-</output>
diff --git a/.planning/phases/03-apple-health-integration/03-02-SUMMARY.md b/.planning/phases/03-apple-health-integration/03-02-SUMMARY.md
deleted file mode 100644
index b708aaba81..0000000000
--- a/.planning/phases/03-apple-health-integration/03-02-SUMMARY.md
+++ /dev/null
@@ -1,140 +0,0 @@
----
-phase: 03-apple-health-integration
-plan: 02
-subsystem: api
-tags: [apple-health, sax, xml, streaming, multer, websocket, react, file-upload]
-
-# Dependency graph
-requires:
- - phase: 03-apple-health-integration
- plan: 01
- provides: readDayFile/writeDayFile/extractDateStr from appleHealthIngest.js, existing POST /ingest and GET routes
-
-provides:
- - SAX streaming XML parser for Apple Health export.xml files (500MB+ without OOM)
- - POST /api/health/import/xml with multer diskStorage upload
- - Real-time WebSocket progress (health:xml:progress, health:xml:complete)
- - normalizeXmlRecord() pure function for HK identifier mapping
- - Working Apple Health XML Import section in Import tab
-
-affects:
- - 03-03-apple-health-insights
- - meatspace health data availability
-
-# Tech tracking
-tech-stack:
- added:
- - sax (SAX streaming XML parser, non-strict mode for malformed Apple Health XML)
- - multer (multipart file upload with diskStorage to avoid OOM on large files)
- patterns:
- - SAX stream piped from createReadStream for memory-efficient XML parsing
- - Post-parse aggregation pattern (collect all records first, then aggregate outside SAX event loop)
- - WebSocket progress emission every N records for long-running imports
- - Raw fetch() for file uploads (bypasses request() helper's Content-Type: application/json)
- - useEffect socket listener cleanup pattern for WebSocket events in React
-
-key-files:
- created:
- - server/services/appleHealthXml.js
- modified:
- - server/routes/appleHealth.js
- - client/src/services/api.js
- - client/src/components/meatspace/tabs/ImportTab.jsx
- - .changelog/v1.7.x.md
-
-key-decisions:
- - "SAX non-strict mode (createStream(false)) handles malformed Apple Health XML gracefully; error handler clears parser error and resumes"
- - "Post-parse aggregation: collect all records in dayBuckets map first, then aggregate step_count (sum) and sleep_analysis (stage durations) after stream ends — avoids complexity in SAX event callbacks"
- - "multer diskStorage (not memoryStorage) for XML upload route — prevents OOM on 500MB+ files by writing to tmpdir immediately"
- - "uploadAppleHealthXml uses raw fetch() not the request() helper — request() sets Content-Type: application/json which conflicts with multipart/form-data boundary"
- - "Indeterminate progress bar with live record count — total record count is unknown before parsing ends"
-
-patterns-established:
- - "Pattern 1: SAX streaming with post-parse aggregation — parse into buckets, aggregate after stream ends, then write files sequentially"
- - "Pattern 2: WebSocket progress for long-running server operations — emit every N records with processed count"
- - "Pattern 3: Raw fetch for multipart uploads in PortOS client — api.js request() is JSON-only"
-
-requirements-completed:
- - HLT-03
- - HLT-04
-
-# Metrics
-duration: 3min
-completed: 2026-02-26
----
-
-# Phase 3 Plan 02: Apple Health XML Import Summary
-
-**SAX streaming XML import pipeline for 500MB+ Apple Health exports with multer diskStorage, HK identifier normalization, sleep/step aggregation, and real-time WebSocket progress in Import tab**
-
-## Performance
-
-- **Duration:** ~7 min (including human-verify checkpoint)
-- **Started:** 2026-02-26T23:30:08Z
-- **Completed:** 2026-02-26T23:37:06Z
-- **Tasks:** 3 of 3 (including Task 3 checkpoint:human-verify — approved)
-- **Files modified:** 5
-
-## Accomplishments
-
-- Created `appleHealthXml.js` SAX streaming service: parses Apple Health export.xml without loading into memory, normalizes HK identifiers, aggregates step counts and sleep stage durations per day
-- Added `POST /api/health/import/xml` route with multer diskStorage (2GB limit), emitting WebSocket progress every 10k records
-- Replaced Import tab Apple Health placeholder with working XML file picker, indeterminate progress bar showing live record count, and success/error states
-
-## Task Commits
-
-1. **Task 1: Create SAX XML streaming service and add XML import route** - `8967415` (feat)
-2. **Task 2: Update Import tab with Apple Health XML file picker and progress bar** - `a4b2d20` (feat)
-3. **Task 3: Verify XML import and ingest pipeline (checkpoint:human-verify)** - Approved by human; no code commit
-
-## Files Created/Modified
-
-- `/Users/antic/github.com/atomantic/PortOS/server/services/appleHealthXml.js` - SAX streaming parser: normalizeXmlRecord(), importAppleHealthXml(), sleep/step aggregation
-- `/Users/antic/github.com/atomantic/PortOS/server/routes/appleHealth.js` - Added multer config and POST /import/xml route
-- `/Users/antic/github.com/atomantic/PortOS/client/src/services/api.js` - Added uploadAppleHealthXml() using raw fetch for multipart
-- `/Users/antic/github.com/atomantic/PortOS/client/src/components/meatspace/tabs/ImportTab.jsx` - Working XML import section replacing disabled placeholder
-- `/Users/antic/github.com/atomantic/PortOS/.changelog/v1.7.x.md` - Added Apple Health XML import entries
-
-## Decisions Made
-
-- SAX non-strict mode (`sax.createStream(false, { lowercase: true })`) handles Apple Health's occasionally malformed XML; error handler clears parser state and resumes rather than aborting
-- Post-parse aggregation approach: collect all records into `dayBuckets` map during SAX events, then aggregate after stream ends (outside event callbacks for simplicity)
-- `multer.diskStorage` for upload route prevents OOM on 500MB+ files — writes to system tmpdir immediately, no in-memory buffering
-- `uploadAppleHealthXml` uses raw `fetch()` not the `request()` helper — the helper hardcodes `Content-Type: application/json` which would break multipart/form-data boundary
-- ServerError constructor corrected to use `{ status: 400, code: 'BAD_REQUEST' }` object signature (not positional statusCode) matching the existing class definition
-
-## Deviations from Plan
-
-### Auto-fixed Issues
-
-**1. [Rule 1 - Bug] Fixed ServerError constructor call signature**
-- **Found during:** Task 1 (adding XML import route)
-- **Issue:** Plan showed `new ServerError('Only XML files are accepted', 400)` but the ServerError constructor takes `(message, options = {})` not `(message, statusCode)`
-- **Fix:** Changed to `new ServerError('...', { status: 400, code: 'BAD_REQUEST' })`
-- **Files modified:** `server/routes/appleHealth.js`
-- **Verification:** Routes file loads cleanly via Node.js import test
-- **Committed in:** `8967415` (Task 1 commit)
-
----
-
-**Total deviations:** 1 auto-fixed (Rule 1 - bug)
-**Impact on plan:** Necessary correction to match existing codebase conventions. No scope creep.
-
-## Issues Encountered
-
-None beyond the auto-fixed ServerError constructor mismatch above.
-
-## User Setup Required
-
-None — no external service configuration required.
-
-## Next Phase Readiness
-
-- XML import pipeline complete and verified: automated tests pass (1192), client builds cleanly, human checkpoint approved
-- Plan 03-03 (Apple Health insights/visualization) can proceed immediately
-- Data from both XML import and JSON ingest is available in the same day-file format under data/health/
-- No blockers for 03-03
-
----
-*Phase: 03-apple-health-integration*
-*Completed: 2026-02-26*
diff --git a/.planning/phases/03-apple-health-integration/03-03-PLAN.md b/.planning/phases/03-apple-health-integration/03-03-PLAN.md
deleted file mode 100644
index ae05dea473..0000000000
--- a/.planning/phases/03-apple-health-integration/03-03-PLAN.md
+++ /dev/null
@@ -1,379 +0,0 @@
----
-phase: 03-apple-health-integration
-plan: 03
-type: execute
-wave: 2
-depends_on:
- - 03-01
-files_modified:
- - client/src/components/meatspace/constants.js
- - client/src/components/meatspace/tabs/HealthTab.jsx
- - client/src/components/meatspace/StepsCard.jsx
- - client/src/components/meatspace/HeartRateCard.jsx
- - client/src/components/meatspace/SleepCard.jsx
- - client/src/components/meatspace/HrvCard.jsx
- - client/src/components/meatspace/AlcoholHrvCorrelation.jsx
- - client/src/components/meatspace/ActivityBloodCorrelation.jsx
- - client/src/pages/MeatSpace.jsx
-autonomous: false
-requirements:
- - HLT-05
- - HLT-06
-
-must_haves:
- truths:
- - "MeatSpace has a Health tab showing steps, heart rate, sleep, and HRV cards with trend charts"
- - "Each health card shows a hero number (current/average) and line chart trend for the selected range"
- - "Range selector buttons (7d/30d/90d/1y) filter all health cards consistently"
- - "Sleep card shows total hours as hero and stacked horizontal bar for stage proportions"
- - "Alcohol vs HRV dual-axis chart shows correlation with auto-generated text summary"
- - "Activity vs blood work chart shows 30-day rolling average steps alongside blood markers"
- - "Correlations show minimum data threshold message when fewer than 14 days of data exist"
- artifacts:
- - path: "client/src/components/meatspace/tabs/HealthTab.jsx"
- provides: "Health tab container with range selector and card grid"
- contains: "HealthTab"
- - path: "client/src/components/meatspace/StepsCard.jsx"
- provides: "Steps trend card with hero number and LineChart"
- contains: "StepsCard"
- - path: "client/src/components/meatspace/HeartRateCard.jsx"
- provides: "Heart rate card with avg/min/max"
- contains: "HeartRateCard"
- - path: "client/src/components/meatspace/SleepCard.jsx"
- provides: "Sleep card with stacked horizontal bar"
- contains: "SleepCard"
- - path: "client/src/components/meatspace/HrvCard.jsx"
- provides: "HRV trend card"
- contains: "HrvCard"
- - path: "client/src/components/meatspace/AlcoholHrvCorrelation.jsx"
- provides: "Dual-axis correlation chart"
- contains: "AlcoholHrvCorrelation"
- - path: "client/src/components/meatspace/ActivityBloodCorrelation.jsx"
- provides: "Activity vs blood work correlation"
- contains: "ActivityBloodCorrelation"
- key_links:
- - from: "client/src/components/meatspace/tabs/HealthTab.jsx"
- to: "/api/health/metrics/:metricName/daily"
- via: "api.getAppleHealthMetrics()"
- pattern: "getAppleHealthMetrics"
- - from: "client/src/components/meatspace/tabs/HealthTab.jsx"
- to: "/api/health/correlation"
- via: "api.getAppleHealthCorrelation()"
- pattern: "getAppleHealthCorrelation"
- - from: "client/src/pages/MeatSpace.jsx"
- to: "client/src/components/meatspace/tabs/HealthTab.jsx"
- via: "case 'health' in renderTabContent"
- pattern: "HealthTab"
----
-
-<objective>
-Build the MeatSpace Health tab with four metric cards (steps, heart rate, sleep, HRV), time range selector, and two correlation charts (alcohol vs HRV, activity vs blood work) with auto-generated text summaries.
-
-Purpose: Makes ingested Apple Health data visible and actionable on the MeatSpace dashboard.
-Output: New Health tab in MeatSpace with trend charts and correlation insights.
-</objective>
-
-<execution_context>
-@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
-@/Users/antic/.claude/get-shit-done/templates/summary.md
-</execution_context>
-
-<context>
[email protected]/phases/03-apple-health-integration/03-RESEARCH.md
[email protected]/phases/03-apple-health-integration/03-01-SUMMARY.md
-
-@client/src/components/meatspace/constants.js — TABS array, design tokens
-@client/src/components/meatspace/AlcoholChart.jsx — Recharts patterns for dark theme
-@client/src/components/meatspace/BloodTestCard.jsx — Card component patterns
-@client/src/pages/MeatSpace.jsx — Tab routing, renderTabContent switch
-@client/src/services/api.js — API functions from Plan 03-01
-
-<interfaces>
-<!-- From Plan 03-01 (will exist by execution time) -->
-
-From client/src/services/api.js:
-```javascript
-export const getAppleHealthMetrics = (metricName, from, to) => ...;
-export const getAppleHealthSummary = (metricName, from, to) => ...;
-export const getAppleHealthRange = () => ...;
-export const getAppleHealthCorrelation = (from, to) => ...;
-```
-
-API response shapes:
-```javascript
-// GET /api/health/metrics/:metricName/daily
-[{ date: "2024-01-15", value: 8432 }, ...]
-
-// GET /api/health/metrics/:metricName
-{ metricName, count, latest, average, from, to, dataPoints: [...] }
-
-// GET /api/health/correlation
-{ dailyData: [{ date, hrv, alcoholGrams, steps }], bloodTests: [...] }
-```
-
-From constants.js:
-```javascript
-export const TABS = [
- { id: 'overview', ... },
- { id: 'alcohol', ... },
- { id: 'blood', ... },
- { id: 'genome', ... },
- { id: 'lifestyle', ... }
-];
-```
-
-Recharts imports (already installed v3.7.0):
-```javascript
-import { LineChart, Line, BarChart, Bar, ComposedChart, XAxis, YAxis,
- CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
-```
-
-Design tokens:
-```
-bg-port-card (#1a1a1a), border-port-border (#2a2a2a), text-port-accent (#3b82f6)
-CartesianGrid stroke="#2a2a2a", tick fill="#9ca3af" fontSize 11
-Tooltip: background '#1a1a1a', border '1px solid #2a2a2a', color '#fff'
-```
-</interfaces>
-</context>
-
-<tasks>
-
-<task type="auto">
- <name>Task 1: Create four health metric cards and HealthTab container</name>
- <files>
- client/src/components/meatspace/StepsCard.jsx
- client/src/components/meatspace/HeartRateCard.jsx
- client/src/components/meatspace/SleepCard.jsx
- client/src/components/meatspace/HrvCard.jsx
- client/src/components/meatspace/tabs/HealthTab.jsx
- </files>
- <action>
-**All four cards follow the same layout pattern (per locked decision):**
-- Card wrapper: `bg-port-card border border-port-border rounded-xl p-6`
-- Hero number at top: large text showing current/average value with unit label
-- Line chart trend below using recharts `ResponsiveContainer` + `LineChart`
-- Charts use dark theme tokens: CartesianGrid `stroke="#2a2a2a"`, tick `fill="#9ca3af" fontSize={11}`, Tooltip with dark background
-- Each card receives `data` (array of `{ date, value }`) and `loading` as props
-
-**1. StepsCard.jsx:**
-- Hero: Daily average steps for the range, formatted with `toLocaleString()` (e.g., "8,432")
-- Unit label: "avg daily steps"
-- Chart: LineChart with `dataKey="value"`, stroke `#3b82f6` (port-accent), dot={false}, strokeWidth 2
-- Empty state: "No step data available" in gray text
-
-**2. HeartRateCard.jsx:**
-- Hero: Average resting heart rate (use average of `value` field), with "bpm" unit
-- Chart: LineChart with `dataKey="value"`, stroke `#ef4444` (red/port-error for heart), dot={false}
-- Empty state: "No heart rate data available"
-
-**3. SleepCard.jsx:**
-- Hero: Average total sleep hours (e.g., "7.2 hrs")
-- Below hero: Stacked horizontal BarChart showing stage proportions for the most recent days. Use `BarChart layout="vertical"` with stacked Bars:
- - deep: `#3b82f6` (blue)
- - rem: `#8b5cf6` (purple)
- - core: `#06b6d4` (cyan)
- - awake: `#6b7280` (gray)
-- This card accepts `data` shaped as `[{ date, totalSleep, deep, rem, core, awake }]`
-- Only show last 7 days in the stacked bar (even if range is larger) to keep it readable
-- Empty state: "No sleep data available"
-
-**4. HrvCard.jsx:**
-- Hero: Average HRV in ms (e.g., "42 ms")
-- Chart: LineChart with `dataKey="value"`, stroke `#22c55e` (green/port-success), dot={false}
-- Empty state: "No HRV data available"
-
-**5. HealthTab.jsx:**
-- State: `range` (default `'7d'`), `stepsData`, `hrData`, `sleepData`, `hrvData`, `correlationData`, `loading`
-- Range selector: Row of buttons `7d`, `30d`, `90d`, `1y` (per locked decision). Active button highlighted with `bg-port-accent/10 text-port-accent`. Calculate `from` date string from range.
-- On mount and range change: Fetch all four metrics in parallel using `Promise.all([api.getAppleHealthMetrics('step_count', from, to), api.getAppleHealthMetrics('heart_rate', from, to), ...])`. Also fetch correlation data: `api.getAppleHealthCorrelation(from, to)`.
-- Layout: 2-column grid on lg, 1-column on mobile (`grid grid-cols-1 lg:grid-cols-2 gap-6`).
- - Row 1: StepsCard, HeartRateCard
- - Row 2: SleepCard, HrvCard
- - Row 3 (full width): Correlations section (rendered by correlation components from Task 2)
-- Pass fetched data and loading state to each card.
-- Row 3 correlations section: Render a placeholder `<div>` with a `{/* Correlation charts — wired in Task 2 */}` comment. Do NOT import AlcoholHrvCorrelation or ActivityBloodCorrelation — those files don't exist yet and will break the build. Task 2 will add the imports and replace this placeholder.
- </action>
- <verify>
- <automated>cd client && npm run build</automated>
- </verify>
- <done>
- - StepsCard shows hero average + LineChart trend
- - HeartRateCard shows hero avg BPM + LineChart trend
- - SleepCard shows hero avg hours + stacked horizontal BarChart for stages
- - HrvCard shows hero avg ms + LineChart trend
- - HealthTab fetches all metrics in parallel on range change
- - Range selector buttons (7d/30d/90d/1y) control all cards consistently
- - All cards have empty states for when no data exists
- - Dark theme tokens used consistently across all charts
- - Row 3 has a placeholder div for correlations (no correlation imports yet)
- - Client builds cleanly with all new components
- </done>
-</task>
-
-<task type="auto">
- <name>Task 2: Create correlation charts and wire Health tab into MeatSpace</name>
- <files>
- client/src/components/meatspace/AlcoholHrvCorrelation.jsx
- client/src/components/meatspace/ActivityBloodCorrelation.jsx
- client/src/components/meatspace/tabs/HealthTab.jsx
- client/src/components/meatspace/constants.js
- client/src/pages/MeatSpace.jsx
- </files>
- <action>
-**1. AlcoholHrvCorrelation.jsx:**
-
-Dual-axis overlay chart (per locked decision):
-- Receives `data` prop: `{ dailyData: [{ date, hrv, alcoholGrams }] }` and `range`
-- Minimum data threshold check: If `dailyData.length < 14`, show message "Need 14+ days of data for correlations -- {dailyData.length} days so far." in a subtle card with `text-gray-400`.
-- Chart: `ComposedChart` with two `YAxis`:
- - Left YAxis (`yAxisId="hrv"`): HRV in ms, `orientation="left"`
- - Right YAxis (`yAxisId="alcohol"`): Alcohol in grams, `orientation="right"`
- - `Line` for HRV: `yAxisId="hrv"`, stroke `#22c55e` (green), dot={false}
- - `Bar` for alcohol: `yAxisId="alcohol"`, fill `#f59e0b` (amber/port-warning), opacity 0.7
-- Card wrapper with title: "Alcohol vs HRV" with HeartPulse + Beer icons
-- **Auto-generated text summary below chart** (per locked decision — computed, NOT LLM):
- ```
- Calculate:
- - drinkingDays = days where alcoholGrams > 0
- - soberDays = days where alcoholGrams === 0
- - avgHrvDrinking = average HRV on drinking days
- - avgHrvSober = average HRV on sober days
- - percentDiff = ((avgHrvSober - avgHrvDrinking) / avgHrvSober * 100).toFixed(0)
-
- Display: "HRV averages {avgHrvDrinking}ms on drinking days vs {avgHrvSober}ms on sober days ({percentDiff}% difference)"
- If no drinking days: "No alcohol data recorded in this period"
- If no sober days: "No sober days recorded in this period"
- ```
-- Dark theme styling matching other charts
-
-**2. ActivityBloodCorrelation.jsx:**
-
-Activity vs blood work chart (per locked decision):
-- Receives `data` prop: `{ dailyData: [{ date, steps }], bloodTests: [{ date, results: {...} }] }` and `range`
-- Minimum data threshold: Same 14-day check as alcohol correlation.
-- Calculate 30-day rolling average steps leading up to each blood test date:
- ```javascript
- For each blood test:
- - Find the 30 days of dailyData before the blood test date
- - Calculate average steps for those 30 days
- - Pair with key blood markers from the test (use markers from the test results if available)
- ```
-- Chart: `ComposedChart` showing:
- - Bar for rolling average steps (`yAxisId="steps"`)
- - Line/dots for key blood markers at test dates (`yAxisId="markers"`) — choose 2-3 most common markers (cholesterol, glucose, or whatever is in the blood test data)
- - If no blood tests in range, show message: "No blood tests in this period to correlate with activity"
-- **Auto-generated text summary:** "Average {avgSteps} steps/day in the 30 days before your {testDate} blood test"
-- Card wrapper with title: "Activity vs Blood Work"
-- Wrap in `ResponsiveContainer`
-
-**3. Wire correlation components into HealthTab.jsx:**
-
-Now that both correlation component files exist, update `HealthTab.jsx`:
-- Add imports at top: `import AlcoholHrvCorrelation from '../AlcoholHrvCorrelation'` and `import ActivityBloodCorrelation from '../ActivityBloodCorrelation'`
-- Replace the placeholder `<div>` (with the `{/* Correlation charts — wired in Task 2 */}` comment) with the actual correlation components:
- ```jsx
- {correlationData && (
- <>
- <AlcoholHrvCorrelation data={correlationData} range={range} />
- <ActivityBloodCorrelation data={correlationData} range={range} />
- </>
- )}
- ```
-
-**4. Add Health tab to constants.js:**
-
-In the TABS array, add (alphabetically between 'genome' and 'lifestyle'):
-```javascript
-{ id: 'health', label: 'Health', icon: HeartPulse }
-```
-
-Note: HeartPulse is already imported in constants.js (used for Blood & Body). But 'health' uses it too. Since Blood & Body already uses HeartPulse, use a different icon for Health. Check available lucide-react icons: use `Activity` (already imported) for Health since it represents activity/vitals. Actually `Activity` is used for Overview. Use `Heart` from lucide-react instead — import it.
-
-Wait, looking at constants.js: `Activity` is used for Overview, `HeartPulse` for Blood & Body. For the Health tab, import and use `Stethoscope` from lucide-react — it's distinct and represents health monitoring.
-
-Update the import line to include `Stethoscope`.
-
-**5. Wire Health tab into MeatSpace.jsx:**
-
-Add import:
-```javascript
-import HealthTab from '../components/meatspace/tabs/HealthTab';
-```
-
-Add case to `renderTabContent` switch (alphabetically between 'genome' and 'lifestyle'):
-```javascript
-case 'health':
- return <HealthTab />;
-```
- </action>
- <verify>
- <automated>cd client && npm run build && cd ../server && npm test</automated>
- </verify>
- <done>
- - AlcoholHrvCorrelation shows dual-axis chart with auto-generated text summary
- - ActivityBloodCorrelation shows activity vs blood markers with text summary
- - Both correlations show minimum data threshold message when < 14 days
- - Health tab appears in MeatSpace tab bar between Genome and Lifestyle
- - Clicking Health tab renders HealthTab component via URL routing (/meatspace/health)
- - All correlation text summaries are computed from data, not LLM-generated
- - Client builds cleanly with all new components
- </done>
-</task>
-
-<task type="checkpoint:human-verify" gate="blocking">
- <name>Task 3: Verify Health tab and correlation charts</name>
- <files>none (verification only)</files>
- <action>
-Human verification checkpoint. Verify:
-1. Health tab appears in MeatSpace at /meatspace/health
-2. Four metric cards render correctly with empty states or data
-3. Range selector buttons work
-4. Correlation charts show threshold messages or data
-5. URL is deep-linkable
- </action>
- <verify>
- <automated>curl -s http://localhost:5554/api/health/range | node -e "process.stdin.on('data',d=>{console.log('PASS: range endpoint responding')})"</automated>
- </verify>
- <done>Health tab verified visually with cards, range selector, and correlations</done>
- <what-built>MeatSpace Health tab with four metric cards, range selector, and two correlation charts</what-built>
- <how-to-verify>
- 1. Navigate to http://localhost:5555/meatspace/health
- 2. Verify the Health tab appears in the MeatSpace tab bar (between Genome and Lifestyle)
- 3. Verify range selector buttons (7d/30d/90d/1y) are visible and clickable
- 4. If health data was ingested via curl in Plan 03-02 checkpoint, verify cards show data
- 5. If no data: verify empty states display correctly ("No step data available" etc.)
- 6. Verify card styling matches existing MeatSpace cards (dark theme, rounded corners)
- 7. Verify correlation section shows threshold message if < 14 days of data
- 8. Verify the URL is deep-linkable: refreshing /meatspace/health returns to the Health tab
- </how-to-verify>
- <resume-signal>Type "approved" or describe issues</resume-signal>
-</task>
-
-</tasks>
-
-<verification>
-1. Health tab appears in MeatSpace at /meatspace/health
-2. Four metric cards render with hero numbers and trend charts
-3. Range selector controls all cards consistently
-4. Correlation charts show dual-axis data or threshold messages
-5. All existing tests pass: `cd server && npm test`
-6. Client builds cleanly: `cd client && npm run build`
-</verification>
-
-<success_criteria>
-- MeatSpace Health tab shows steps, heart rate, sleep, and HRV cards
-- Each card has hero number + line chart (sleep has stacked bar for stages)
-- Range selector (7d/30d/90d/1y) filters all cards
-- Alcohol vs HRV correlation shows dual-axis chart with computed text summary
-- Activity vs blood work correlation shows 30-day rolling average with markers
-- Correlations show "Need 14+ days" message when insufficient data
-- Health tab is deep-linkable at /meatspace/health
-</success_criteria>
-
-<output>
-After completion, create `.planning/phases/03-apple-health-integration/03-03-SUMMARY.md`
-</output>
diff --git a/.planning/phases/03-apple-health-integration/03-03-SUMMARY.md b/.planning/phases/03-apple-health-integration/03-03-SUMMARY.md
deleted file mode 100644
index b9e7e89af7..0000000000
--- a/.planning/phases/03-apple-health-integration/03-03-SUMMARY.md
+++ /dev/null
@@ -1,141 +0,0 @@
----
-phase: 03-apple-health-integration
-plan: "03"
-subsystem: ui
-tags: [react, recharts, health, meatspace, charts, correlation]
-
-# Dependency graph
-requires:
- - phase: 03-01
- provides: Apple Health API endpoints (getAppleHealthMetrics, getAppleHealthCorrelation)
-provides:
- - MeatSpace Health tab with four metric cards (steps, heart rate, sleep, HRV)
- - Time range selector (7d/30d/90d/1y) controlling all health cards
- - AlcoholHrvCorrelation dual-axis chart with computed text summary
- - ActivityBloodCorrelation chart with 30-day rolling average steps vs blood markers
- - Deep-linkable /meatspace/health route
-affects: [04-health-insights, any phase adding MeatSpace tabs]
-
-# Tech tracking
-tech-stack:
- added: []
- patterns:
- - Hero number + trend chart card pattern for metric visualization
- - Parallel data fetching with Promise.all on range change
- - Computed correlation text summaries (no LLM, pure data math)
- - Minimum data threshold guard (14-day check) before rendering correlations
- - Stacked horizontal BarChart for sleep stage proportions
-
-key-files:
- created:
- - client/src/components/meatspace/StepsCard.jsx
- - client/src/components/meatspace/HeartRateCard.jsx
- - client/src/components/meatspace/SleepCard.jsx
- - client/src/components/meatspace/HrvCard.jsx
- - client/src/components/meatspace/tabs/HealthTab.jsx
- - client/src/components/meatspace/AlcoholHrvCorrelation.jsx
- - client/src/components/meatspace/ActivityBloodCorrelation.jsx
- modified:
- - client/src/components/meatspace/constants.js
- - client/src/pages/MeatSpace.jsx
-
-key-decisions:
- - "Correlation text summaries computed from data math (avgHrv, percentDiff) not LLM calls — keeps latency at zero"
- - "Minimum 14-day data threshold guard prevents misleading correlations with sparse data"
- - "Task 1 used placeholder div for correlations to avoid broken imports during two-task build"
- - "Health tab icon uses Stethoscope (lucide-react) — Activity and HeartPulse already used by other tabs"
-
-patterns-established:
- - "Two-step card build pattern: card with placeholder (Task 1) then correlation wiring (Task 2) to prevent build failures"
- - "Dark theme chart tokens: CartesianGrid stroke=#2a2a2a, tick fill=#9ca3af fontSize=11, Tooltip bg=#1a1a1a"
-
-requirements-completed: [HLT-05, HLT-06]
-
-# Metrics
-duration: ~15min
-completed: 2026-02-26
----
-
-# Phase 3 Plan 03: MeatSpace Health Tab Summary
-
-**Four recharts-powered health metric cards (steps, heart rate, sleep, HRV) with time range selector and dual-axis alcohol/HRV and activity/blood correlation charts wired into MeatSpace at /meatspace/health**
-
-## Performance
-
-- **Duration:** ~15 min
-- **Started:** 2026-02-26T23:20:00Z
-- **Completed:** 2026-02-26T23:37:11Z
-- **Tasks:** 3 (2 auto + 1 checkpoint:human-verify)
-- **Files modified:** 9
-
-## Accomplishments
-
-- Four health metric cards (StepsCard, HeartRateCard, SleepCard, HrvCard) each with hero number and recharts trend chart
-- SleepCard uses stacked horizontal BarChart for sleep stage proportions (deep/rem/core/awake)
-- HealthTab fetches all metrics in parallel via Promise.all on range change (7d/30d/90d/1y)
-- AlcoholHrvCorrelation dual-axis ComposedChart with auto-computed text summary (avgHrvDrinking vs avgHrvSober)
-- ActivityBloodCorrelation shows 30-day rolling average steps alongside blood test markers
-- Both correlation charts guard with 14-day minimum threshold message for sparse data
-- Health tab wired into MeatSpace.jsx at case 'health' and added to constants.js TABS with Stethoscope icon
-
-## Task Commits
-
-Each task was committed atomically:
-
-1. **Task 1: Create four health metric cards and HealthTab container** - `11cc0ea` (feat)
-2. **Task 2: Create correlation charts and wire Health tab into MeatSpace** - `81bd182` (feat)
-3. **Task 3: Verify Health tab and correlation charts** - checkpoint:human-verify, approved by user
-
-## Files Created/Modified
-
-- `client/src/components/meatspace/StepsCard.jsx` - Steps trend card with hero average + LineChart, stroke #3b82f6
-- `client/src/components/meatspace/HeartRateCard.jsx` - Heart rate card with avg BPM + LineChart, stroke #ef4444
-- `client/src/components/meatspace/SleepCard.jsx` - Sleep card with avg hours hero + stacked horizontal BarChart for stages
-- `client/src/components/meatspace/HrvCard.jsx` - HRV trend card with avg ms + LineChart, stroke #22c55e
-- `client/src/components/meatspace/tabs/HealthTab.jsx` - Health tab container with range selector, card grid, and correlation section
-- `client/src/components/meatspace/AlcoholHrvCorrelation.jsx` - Dual-axis ComposedChart with computed text summary and 14-day threshold
-- `client/src/components/meatspace/ActivityBloodCorrelation.jsx` - 30-day rolling average steps vs blood markers with threshold guard
-- `client/src/components/meatspace/constants.js` - Added Health tab with Stethoscope icon between Genome and Lifestyle
-- `client/src/pages/MeatSpace.jsx` - Added HealthTab import and case 'health' in renderTabContent
-
-## Decisions Made
-
-- Correlation text summaries computed via pure data math (no LLM) — zero latency, deterministic output
-- 14-day minimum threshold guard prevents misleading correlations when data is sparse
-- Two-task build pattern: Task 1 used a placeholder comment div for correlations to avoid broken imports before Task 2 created the files
-- Stethoscope icon chosen for Health tab — Activity already used by Overview, HeartPulse already used by Blood & Body
-
-## Deviations from Plan
-
-None - plan executed exactly as written.
-
-## Issues Encountered
-
-None — build passed cleanly after both tasks, server tests passed.
-
-## User Setup Required
-
-None - no external service configuration required.
-
-## Next Phase Readiness
-
-- Health tab is live at /meatspace/health and deep-linkable
-- All four metric cards and both correlation charts are wired to Phase 03-01 API endpoints
-- Phase 04 (health insights/correlations) can extend AlcoholHrvCorrelation and ActivityBloodCorrelation with additional scientific correlation rules
-- No blockers for next phase
-
-## Self-Check: PASSED
-
-- FOUND: client/src/components/meatspace/StepsCard.jsx
-- FOUND: client/src/components/meatspace/HeartRateCard.jsx
-- FOUND: client/src/components/meatspace/SleepCard.jsx
-- FOUND: client/src/components/meatspace/HrvCard.jsx
-- FOUND: client/src/components/meatspace/tabs/HealthTab.jsx
-- FOUND: client/src/components/meatspace/AlcoholHrvCorrelation.jsx
-- FOUND: client/src/components/meatspace/ActivityBloodCorrelation.jsx
-- FOUND: commit 11cc0ea (Task 1)
-- FOUND: commit 81bd182 (Task 2)
-
----
-*Phase: 03-apple-health-integration*
-*Completed: 2026-02-26*
diff --git a/.planning/phases/03-apple-health-integration/03-CONTEXT.md b/.planning/phases/03-apple-health-integration/03-CONTEXT.md
deleted file mode 100644
index e8e0d8ff13..0000000000
--- a/.planning/phases/03-apple-health-integration/03-CONTEXT.md
+++ /dev/null
@@ -1,75 +0,0 @@
-# Phase 3: Apple Health Integration - Context
-
-**Gathered:** 2026-02-26
-**Status:** Ready for planning
-
-<domain>
-## Phase Boundary
-
-Ingest Apple Health data into PortOS via Health Auto Export JSON push and bulk XML import, persist to day-partitioned storage, and display health metrics (steps, heart rate, sleep, HRV) on the MeatSpace dashboard with cross-data correlations. All Apple Health metric types are stored, but only the core four get dashboard cards. Creating insights or cross-domain analysis beyond simple correlations belongs in Phase 4.
-
-</domain>
-
-<decisions>
-## Implementation Decisions
-
-### Import workflow
-- Two ingest paths: Health Auto Export REST push to `/api/health/ingest` AND manual file upload in the Import tab
-- Bulk XML import via file picker in the existing Import tab (replace the disabled placeholder)
-- XML import progress shown as progress bar with percentage + live record counts, updated via WebSocket
-- Duplicate handling: silent dedup by metric type + timestamp — no user notification unless error
-
-### Health metric scope
-- Import ALL Apple Health metric types into day-partitioned storage (not just core four)
-- Dashboard cards built for core four only: steps, heart rate, sleep analysis, HRV
-- All other metrics stored for future use (Phase 4 correlations, future dashboard expansion)
-- Apple Health nutrition data REPLACES existing daily-log nutrition for overlapping days (overwrite silently, no backup)
-- One file per day with all metrics: `data/health/YYYY-MM-DD.json`
-
-### Dashboard cards
-- New "Health" tab added to MeatSpace (alongside Overview, Alcohol, Blood & Body, Genome, Lifestyle)
-- Default time range: last 7 days
-- Range selector buttons: 7d / 30d / 90d / 1y — consistent across all health cards
-- Card layout: hero number (current/average value) at top, line chart trend below
-- Sleep card: total hours as hero number, stacked horizontal bar showing deep/REM/light/awake stage proportions, time-in-bed vs actual sleep
-
-### Health correlations
-- Correlations section at the bottom of the new Health tab
-- Alcohol vs HRV: dual-axis overlay chart (HRV left axis, alcohol grams right axis, same time range)
-- Activity vs blood work: 30-day rolling average steps/activity leading up to each blood test date, plotted alongside key blood markers
-- Each correlation chart includes an auto-generated text summary below (e.g., "HRV averages 42ms on drinking days vs 58ms on sober days (-28%)") — computed from data, no LLM
-- Minimum data threshold: 14+ days before showing correlations. Show message: "Need 14+ days of data for correlations — X days so far."
-
-### Claude's Discretion
-- Chart library choice and styling details
-- Exact JSON schema for day-partitioned health files
-- SAX parser implementation details for XML streaming
-- Health Auto Export JSON validation schema specifics
-- Card grid layout and responsive breakpoints
-- Color palette for chart lines and sleep stage bars
-- How to handle Apple Health records with no date or invalid timestamps
-
-</decisions>
-
-<specifics>
-## Specific Ideas
-
-- Cards should follow the existing MeatSpace card pattern: `bg-port-card`, `border-port-border`, rounded corners
-- Health Auto Export is an iOS app that can be configured to POST JSON to a REST endpoint on each sync
-- The existing Import tab already has a disabled Apple Health placeholder — replace it with the real file picker
-- Sleep visualization inspired by Apple Health's own sleep cards (stacked bar for stages)
-- Correlation text summaries should be simple computed comparisons (averages, percentages), not AI-generated
-
-</specifics>
-
-<deferred>
-## Deferred Ideas
-
-None — discussion stayed within phase scope
-
-</deferred>
-
----
-
-*Phase: 03-apple-health-integration*
-*Context gathered: 2026-02-26*
diff --git a/.planning/phases/03-apple-health-integration/03-RESEARCH.md b/.planning/phases/03-apple-health-integration/03-RESEARCH.md
deleted file mode 100644
index 2f6401c378..0000000000
--- a/.planning/phases/03-apple-health-integration/03-RESEARCH.md
+++ /dev/null
@@ -1,715 +0,0 @@
-# Phase 3: Apple Health Integration - Research
-
-**Researched:** 2026-02-26
-**Domain:** Health data ingestion, streaming XML parsing, time-series dashboard
-**Confidence:** HIGH
-
-<user_constraints>
-## User Constraints (from CONTEXT.md)
-
-### Locked Decisions
-
-**Import workflow:**
-- Two ingest paths: Health Auto Export REST push to `/api/health/ingest` AND manual file upload in the Import tab
-- Bulk XML import via file picker in the existing Import tab (replace the disabled placeholder)
-- XML import progress shown as progress bar with percentage + live record counts, updated via WebSocket
-- Duplicate handling: silent dedup by metric type + timestamp — no user notification unless error
-
-**Health metric scope:**
-- Import ALL Apple Health metric types into day-partitioned storage (not just core four)
-- Dashboard cards built for core four only: steps, heart rate, sleep analysis, HRV
-- All other metrics stored for future use (Phase 4 correlations, future dashboard expansion)
-- Apple Health nutrition data REPLACES existing daily-log nutrition for overlapping days (overwrite silently, no backup)
-- One file per day with all metrics: `data/health/YYYY-MM-DD.json`
-
-**Dashboard cards:**
-- New "Health" tab added to MeatSpace (alongside Overview, Alcohol, Blood & Body, Genome, Lifestyle)
-- Default time range: last 7 days
-- Range selector buttons: 7d / 30d / 90d / 1y — consistent across all health cards
-- Card layout: hero number (current/average value) at top, line chart trend below
-- Sleep card: total hours as hero number, stacked horizontal bar showing deep/REM/light/awake stage proportions, time-in-bed vs actual sleep
-
-**Health correlations:**
-- Correlations section at the bottom of the new Health tab
-- Alcohol vs HRV: dual-axis overlay chart (HRV left axis, alcohol grams right axis, same time range)
-- Activity vs blood work: 30-day rolling average steps/activity leading up to each blood test date, plotted alongside key blood markers
-- Each correlation chart includes an auto-generated text summary below (e.g., "HRV averages 42ms on drinking days vs 58ms on sober days (-28%)") — computed from data, no LLM
-- Minimum data threshold: 14+ days before showing correlations. Show message: "Need 14+ days of data for correlations — X days so far."
-
-### Claude's Discretion
-- Chart library choice and styling details
-- Exact JSON schema for day-partitioned health files
-- SAX parser implementation details for XML streaming
-- Health Auto Export JSON validation schema specifics
-- Card grid layout and responsive breakpoints
-- Color palette for chart lines and sleep stage bars
-- How to handle Apple Health records with no date or invalid timestamps
-
-### Deferred Ideas (OUT OF SCOPE)
-
-None — discussion stayed within phase scope
-</user_constraints>
-
-<phase_requirements>
-## Phase Requirements
-
-| ID | Description | Research Support |
-|----|-------------|-----------------|
-| HLT-01 | POST `/api/health/ingest` accepts Health Auto Export JSON, validates with Zod, deduplicates by metric+timestamp | Health Auto Export JSON schema documented below; Zod patterns from existing project; dedup logic is in-memory before write |
-| HLT-02 | Health data persists to day-partitioned `data/health/YYYY-MM-DD.json` files | Day-partition file layout documented; PATHS.health constant needs adding to fileUtils.js |
-| HLT-03 | Bulk XML import streams Apple Health export (500MB+) without OOM via SAX parser | `sax` npm package streaming API verified; multer diskStorage → sax stream pipeline documented |
-| HLT-04 | XML import reports progress via WebSocket during processing | Socket.io `io.emit` pattern confirmed from backup.js; `req.app.get('io')` is the access pattern |
-| HLT-05 | MeatSpace dashboard cards for steps, heart rate, sleep, HRV trends | `recharts` v3 already installed; LineChart, ComposedChart (dual-axis), stacked BarChart all confirmed |
-| HLT-06 | Correlate Apple Health data with existing MeatSpace data (alcohol vs HRV, activity vs blood work) | `getDailyAlcohol()` and blood test services exist; correlation math is pure JS; recharts ComposedChart dual-axis confirmed |
-</phase_requirements>
-
----
-
-## Summary
-
-Phase 3 requires three distinct subsystems: (1) an ingest API for Health Auto Export JSON push, (2) a streaming SAX XML importer for bulk Apple Health exports, and (3) a Health tab on the MeatSpace dashboard with trend charts and correlation views.
-
-The technical stack is well-matched to existing PortOS patterns. The `sax` npm package (v1.4.4, actively maintained) provides Node.js streaming XML parsing via `createStream()` and is the correct tool for 500MB+ files — multer diskStorage saves the upload to a temp file, which is then piped to the SAX stream without loading the file into memory. Health Auto Export pushes JSON with a documented schema (`data.metrics[]` array), and Zod validation follows the established project pattern. WebSocket progress events follow the exact same pattern as `backup.js` (`req.app.get('io')`, `io.emit(event, payload)`). `recharts` v3 is already installed in the client and supports all required chart types.
-
-The key unknowns are: (a) the exact metric `name` strings used in Health Auto Export JSON v7 for steps/HRV (confirmed: `step_count`, `heart_rate`, `heart_rate_variability_sdnn`, `sleep_analysis` — but app version naming may vary), and (b) Apple Health XML `type` attribute values for the four core metrics (confirmed: `HKQuantityTypeIdentifierStepCount`, `HKQuantityTypeIdentifierHeartRate`, `HKQuantityTypeIdentifierHeartRateVariabilitySDNN`, `HKCategoryTypeIdentifierSleepAnalysis`). Sleep XML records have text values (`HKCategoryValueSleepAnalysisAsleepREM` etc.) not numeric, requiring separate handling.
-
-**Primary recommendation:** Use `sax` npm for XML streaming, `multer` with diskStorage for file upload, `recharts` ComposedChart for dual-axis correlation charts, and follow the backup.js pattern for WebSocket progress.
-
----
-
-## Standard Stack
-
-### Core
-
-| Library | Version | Purpose | Why Standard |
-|---------|---------|---------|--------------|
-| `sax` | 1.4.4 | Streaming SAX XML parser | 1896 dependents, actively maintained (published ~1 month ago), the de-facto Node.js SAX parser; supports `createStream()` for pipe-based parsing |
-| `multer` | latest | Multipart file upload middleware | Standard Express file upload; diskStorage keeps 500MB files off heap |
-| `recharts` | 3.7.0 | Chart rendering | **Already installed** in client; supports LineChart, ComposedChart, stacked BarChart |
-| `zod` | 3.24.1 | Input validation | **Already installed** in server; all routes use it |
-| `socket.io` | 4.8.3 | WebSocket progress events | **Already installed** and wired; `io.emit` pattern confirmed |
-
-### Supporting
-
-| Library | Version | Purpose | When to Use |
-|---------|---------|---------|-------------|
-| `fs` (Node built-in) | — | `createReadStream` for pipe to SAX | Pipe temp file into SAX parser |
-| `fs/promises` | — | Day-partition file read/write | Read existing day file, merge, write back |
-| `path` | — | `join(PATHS.health, dateStr + '.json')` | Build file paths |
-| `os.tmpdir()` | — | Temp dir for multer diskStorage | Safe temp location for XML upload |
-
-### Alternatives Considered
-
-| Instead of | Could Use | Tradeoff |
-|------------|-----------|----------|
-| `sax` | `saxes` | saxes is faster but last published 4 years ago; sax is actively maintained |
-| `sax` | `fast-xml-parser` | fast-xml-parser loads DOM; not suitable for 500MB streaming |
-| `multer diskStorage` | `multer memoryStorage` | memoryStorage would load 500MB into RAM — causes OOM |
-| `recharts` | `chart.js` | recharts is already installed; no reason to add chart.js |
-
-**Installation (new packages only):**
-```bash
-# In server/
-npm install sax multer
-```
-
----
-
-## Architecture Patterns
-
-### Recommended Project Structure
-
-New files following PortOS conventions:
-
-```
-server/
-├── routes/
-│ └── appleHealth.js # POST /api/health/ingest, POST /api/health/import/xml
-├── services/
-│ ├── appleHealthIngest.js # JSON ingest: parse, dedup, write day files
-│ ├── appleHealthXml.js # SAX XML streaming: parse export.xml, write day files
-│ └── appleHealthQuery.js # Read day-partitioned files for dashboard queries
-├── lib/
-│ └── appleHealthValidation.js # Zod schemas for ingest payload
-
-client/src/components/meatspace/
-├── tabs/
-│ └── HealthTab.jsx # New Health tab (steps, HR, sleep, HRV cards + correlations)
-├── AppleHealthImport.jsx # XML upload UI with WebSocket progress bar
-├── StepsCard.jsx # Steps trend (LineChart)
-├── HeartRateCard.jsx # Heart rate trend (LineChart avg/min/max)
-├── SleepCard.jsx # Sleep stacked bar + total hours
-├── HrvCard.jsx # HRV trend (LineChart)
-├── AlcoholHrvCorrelation.jsx # Dual-axis ComposedChart
-└── ActivityBloodCorrelation.jsx # Steps + blood markers ComposedChart
-```
-
-### Pattern 1: SAX Streaming XML Import
-
-**What:** Pipe uploaded file through SAX parser event-by-event; accumulate records in memory one batch at a time; write day files; emit progress every N records via WebSocket.
-**When to use:** Any import of Apple Health XML export (potentially 500MB+)
-
-```javascript
-// Source: sax npm docs (https://github.com/isaacs/sax-js)
-import sax from 'sax';
-import { createReadStream, unlink } from 'fs';
-import { writeFile, readFile } from 'fs/promises';
-
-export async function importAppleHealthXml(filePath, io = null) {
- const saxStream = sax.createStream(false, { lowercase: true });
-
- let totalRecords = 0;
- let processedRecords = 0;
- const dayBuckets = {}; // { 'YYYY-MM-DD': { metrics: { type: [...] } } }
-
- saxStream.on('opentag', (node) => {
- // node.name is 'record' (lowercase because lowercase: true)
- // node.attributes has: type, value, startdate, enddate, unit, sourcename
- if (node.name !== 'record') return;
-
- const { type, value, startdate, unit } = node.attributes;
- if (!startdate) return;
-
- const dateStr = startdate.split(' ')[0]; // 'YYYY-MM-DD HH:mm:ss +0000' -> 'YYYY-MM-DD'
- if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) return;
-
- if (!dayBuckets[dateStr]) dayBuckets[dateStr] = { metrics: {} };
- if (!dayBuckets[dateStr].metrics[type]) dayBuckets[dateStr].metrics[type] = [];
-
- dayBuckets[dateStr].metrics[type].push({
- ts: startdate,
- end: node.attributes.enddate ?? null,
- val: value,
- unit: unit ?? null,
- src: node.attributes.sourcename ?? null
- });
-
- processedRecords++;
- if (processedRecords % 10000 === 0 && io) {
- io.emit('health:xml:progress', { processed: processedRecords });
- console.log(`🍎 XML import progress: ${processedRecords} records`);
- }
- });
-
- saxStream.on('error', function (e) {
- // Clear error and resume — Apple Health XML sometimes has minor malformations
- console.error(`❌ XML parse error at record ${processedRecords}: ${e.message}`);
- this._parser.error = null;
- this._parser.resume();
- });
-
- await new Promise((resolve, reject) => {
- saxStream.on('end', resolve);
- saxStream.on('error', reject); // Only catastrophic errors reach here
- createReadStream(filePath).pipe(saxStream);
- });
-
- // Write day files
- const days = Object.keys(dayBuckets);
- for (const dateStr of days) {
- await writeDayFile(dateStr, dayBuckets[dateStr]);
- }
-
- // Cleanup temp file
- unlink(filePath, () => {});
-
- if (io) io.emit('health:xml:complete', { days: days.length, records: processedRecords });
- console.log(`🍎 XML import complete: ${processedRecords} records across ${days.length} days`);
- return { days: days.length, records: processedRecords };
-}
-```
-
-### Pattern 2: multer diskStorage Upload (500MB-safe)
-
-**What:** Store uploaded file to temp dir on disk (not memory), return path to route handler.
-**When to use:** XML file upload endpoint.
-
-```javascript
-// Source: multer docs (https://www.npmjs.com/package/multer)
-import multer from 'multer';
-import { tmpdir } from 'os';
-import { join } from 'path';
-
-const upload = multer({
- storage: multer.diskStorage({
- destination: (req, file, cb) => cb(null, tmpdir()),
- filename: (req, file, cb) => cb(null, `apple-health-${Date.now()}.xml`)
- }),
- limits: { fileSize: 2 * 1024 * 1024 * 1024 } // 2GB max
-});
-
-// In route:
-router.post('/import/xml', upload.single('file'), asyncHandler(async (req, res) => {
- const io = req.app.get('io');
- const filePath = req.file?.path;
- if (!filePath) throw new ServerError('No file uploaded', 400);
-
- const result = await importAppleHealthXml(filePath, io);
- res.json(result);
-}));
-```
-
-### Pattern 3: Health Auto Export JSON Ingest with Zod + Dedup
-
-**What:** Accept POST body with `data.metrics[]` array; validate with Zod; dedup by metric_name+timestamp; write to day files.
-
-Health Auto Export JSON schema (confirmed from official wiki):
-```json
-{
- "data": {
- "metrics": [
- {
- "name": "step_count",
- "units": "count",
- "data": [{ "qty": 8432, "date": "2024-01-15 08:30:00 -0800" }]
- },
- {
- "name": "heart_rate",
- "units": "bpm",
- "data": [{ "date": "2024-01-15 08:30:00 -0800", "Min": 68, "Avg": 72, "Max": 85 }]
- },
- {
- "name": "sleep_analysis",
- "units": "hr",
- "data": [{ "date": "2024-01-15", "totalSleep": 7.2, "deep": 1.1, "rem": 1.8, "core": 4.1, "awake": 0.2 }]
- },
- {
- "name": "heart_rate_variability_sdnn",
- "units": "ms",
- "data": [{ "qty": 42.3, "date": "2024-01-15 06:00:00 -0800" }]
- }
- ]
- }
-}
-```
-
-Zod schema pattern (following `lib/meatspaceValidation.js` style):
-```javascript
-// Source: project pattern from server/lib/meatspaceValidation.js
-import { z } from 'zod';
-
-const healthDataPointSchema = z.object({
- date: z.string(),
- qty: z.number().optional(),
- Min: z.number().optional(),
- Avg: z.number().optional(),
- Max: z.number().optional(),
- totalSleep: z.number().optional(),
- deep: z.number().optional(),
- rem: z.number().optional(),
- core: z.number().optional(),
- awake: z.number().optional(),
- hrv: z.number().optional()
-}).passthrough(); // Allow additional fields from future app versions
-
-const healthMetricSchema = z.object({
- name: z.string().min(1),
- units: z.string().optional(),
- data: z.array(healthDataPointSchema)
-});
-
-export const healthIngestSchema = z.object({
- data: z.object({
- metrics: z.array(healthMetricSchema).default([]),
- workouts: z.array(z.unknown()).default([])
- }).passthrough()
-});
-```
-
-Deduplication pattern:
-```javascript
-// Dedup key: metricName + date string (normalize to YYYY-MM-DD HH:mm:ss)
-function dedupKey(metricName, dataPoint) {
- return `${metricName}::${dataPoint.date}`;
-}
-
-// On write: load existing day file, merge new records, skip duplicates
-async function mergeIntoDay(dateStr, metricName, newPoints) {
- const existing = await readDayFile(dateStr);
- const existingKeys = new Set(
- (existing.metrics?.[metricName] ?? []).map(p => p.date)
- );
- const unique = newPoints.filter(p => !existingKeys.has(p.date));
- existing.metrics ??= {};
- existing.metrics[metricName] ??= [];
- existing.metrics[metricName].push(...unique);
- await writeDayFile(dateStr, existing);
- return unique.length;
-}
-```
-
-### Pattern 4: Day-Partitioned File Schema
-
-**What:** One JSON file per day at `data/health/YYYY-MM-DD.json`. All metric types for that day stored together.
-
-```json
-{
- "date": "2024-01-15",
- "metrics": {
- "step_count": [
- { "date": "2024-01-15 08:30:00 -0800", "qty": 4211, "unit": "count" },
- { "date": "2024-01-15 18:00:00 -0800", "qty": 4221, "unit": "count" }
- ],
- "heart_rate": [
- { "date": "2024-01-15 08:30:00 -0800", "Min": 62, "Avg": 71, "Max": 88 }
- ],
- "heart_rate_variability_sdnn": [
- { "date": "2024-01-15 06:00:00 -0800", "qty": 42.3, "unit": "ms" }
- ],
- "sleep_analysis": [
- { "date": "2024-01-15", "totalSleep": 7.2, "deep": 1.1, "rem": 1.8, "core": 4.1, "awake": 0.2 }
- ]
- },
- "updated": "2024-01-16T10:00:00.000Z"
-}
-```
-
-PATHS constant to add to `server/lib/fileUtils.js`:
-```javascript
-health: join(__lib_dirname, '../../data/health'),
-```
-
-### Pattern 5: WebSocket Progress (following backup.js)
-
-**What:** Route gets `io` from `req.app.get('io')`, passes to service, service emits events.
-
-```javascript
-// Route (matches backup.js pattern exactly)
-router.post('/import/xml', upload.single('file'), asyncHandler(async (req, res) => {
- const io = req.app.get('io');
- const result = await importAppleHealthXml(req.file.path, io);
- res.json(result);
-}));
-
-// Service emits (matches backup.js pattern):
-if (io) io.emit('health:xml:progress', { processed: N, total: estimatedTotal });
-if (io) io.emit('health:xml:complete', { days: N, records: M });
-```
-
-Client subscribes:
-```javascript
-// In AppleHealthImport.jsx
-import socket from '../../../services/socket';
-useEffect(() => {
- socket.on('health:xml:progress', ({ processed }) => setProgress(processed));
- socket.on('health:xml:complete', (result) => { setResult(result); setImporting(false); });
- return () => {
- socket.off('health:xml:progress');
- socket.off('health:xml:complete');
- };
-}, []);
-```
-
-### Pattern 6: Recharts Dual-Axis Chart (Alcohol vs HRV)
-
-**What:** `ComposedChart` with two `YAxis` components — one for HRV (ms), one for alcohol (grams).
-**Already installed:** recharts v3.7.0
-
-```jsx
-// Source: recharts docs + verified from project's existing AlcoholChart.jsx patterns
-import { ComposedChart, Line, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';
-
-<ComposedChart data={correlationData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
- <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />
- <XAxis dataKey="date" tick={{ fill: '#9ca3af', fontSize: 11 }} />
- <YAxis yAxisId="hrv" orientation="left" tick={{ fill: '#9ca3af', fontSize: 11 }} />
- <YAxis yAxisId="alcohol" orientation="right" tick={{ fill: '#9ca3af', fontSize: 11 }} />
- <Tooltip contentStyle={{ background: '#1a1a1a', border: '1px solid #2a2a2a' }} />
- <Legend />
- <Line yAxisId="hrv" type="monotone" dataKey="hrv" stroke="#3b82f6" dot={false} />
- <Bar yAxisId="alcohol" dataKey="alcoholGrams" fill="#f59e0b" opacity={0.7} />
-</ComposedChart>
-```
-
-### Pattern 7: Sleep Stacked Horizontal Bar (per day)
-
-**What:** Single `BarChart layout="vertical"` with stacked `Bar` components for sleep stages.
-
-```jsx
-import { BarChart, Bar, XAxis, YAxis, Tooltip, Legend } from 'recharts';
-
-// One entry per day: { date, deep, rem, core, awake }
-<BarChart layout="vertical" data={sleepData} height={60 * sleepData.length}>
- <XAxis type="number" tick={{ fill: '#9ca3af', fontSize: 11 }} />
- <YAxis type="category" dataKey="date" tick={{ fill: '#9ca3af', fontSize: 11 }} width={70} />
- <Tooltip contentStyle={{ background: '#1a1a1a', border: '1px solid #2a2a2a' }} />
- <Legend />
- <Bar dataKey="deep" stackId="sleep" fill="#3b82f6" />
- <Bar dataKey="rem" stackId="sleep" fill="#8b5cf6" />
- <Bar dataKey="core" stackId="sleep" fill="#06b6d4" />
- <Bar dataKey="awake" stackId="sleep" fill="#6b7280" />
-</BarChart>
-```
-
-### Anti-Patterns to Avoid
-
-- **Loading the full XML into memory:** Never use `fs.readFile()` on the upload — always pipe via `createReadStream()` to `sax.createStream()`.
-- **multer memoryStorage for XML:** Will cause OOM on 500MB files — always use diskStorage.
-- **DOM/SAX confusion:** Never use `DOMParser` or `xml2js` (loads full DOM) — use SAX stream only.
-- **Hardcoding metric names:** Health Auto Export metric name strings differ from Apple's `HKQuantityTypeIdentifier*` XML type strings — maintain separate maps for each ingest path.
-- **Single monolithic health file:** Never write all health data to one file — day-partitioned layout is required (and locked).
-- **Blocking event loop during write:** Day file writes should be sequential per day or use `Promise.all` with a concurrency limit (< 50 concurrent writes) to avoid fs exhaustion.
-- **Storing `io` in module scope from routes:** Follow backup.js pattern — pass `io` as function argument, get it from `req.app.get('io')` in the route.
-
----
-
-## Don't Hand-Roll
-
-| Problem | Don't Build | Use Instead | Why |
-|---------|-------------|-------------|-----|
-| Streaming XML parsing | Custom XML tokenizer | `sax` npm | SAX handles encoding, entity refs, malformed tags, attribute parsing — all edge cases handled |
-| Multipart file upload | Custom body parser | `multer` diskStorage | Handles chunked transfer, temp file cleanup, file size limits |
-| Chart rendering | Custom SVG charts | `recharts` (already installed) | Already in the project — line, bar, composed chart all ready to use |
-| Date parsing | String splitting | Use `date.split(' ')[0]` (YYYY-MM-DD) | Apple Health dates are consistently formatted `YYYY-MM-DD HH:mm:ss ±HHMM` |
-
-**Key insight:** The XML parsing domain has many edge cases (encoding, malformed tags, entity references). SAX handles them; hand-rolled parsers fail on real Apple Health exports.
-
----
-
-## Common Pitfalls
-
-### Pitfall 1: XML Not Strict-Mode Safe
-**What goes wrong:** Apple Health `export.xml` sometimes contains duplicate attributes or minor malformations that cause strict-mode SAX parsers to throw and halt.
-**Why it happens:** Apple's Health app generates the XML, and edge cases like workout metadata can produce slightly non-conformant XML.
-**How to avoid:** Use `sax.createStream(false, { lowercase: true })` (non-strict mode). In the `error` handler: clear `this._parser.error = null` and call `this._parser.resume()` to skip bad records and continue.
-**Warning signs:** Import halting at specific record counts; "duplicate attribute" errors in logs.
-
-### Pitfall 2: Sleep XML Records Are Text Values, Not Numbers
-**What goes wrong:** Sleep analysis records in XML have `value="HKCategoryValueSleepAnalysisAsleepREM"` (string), not a numeric value. Code expecting `parseFloat(value)` will produce NaN for all sleep records.
-**Why it happens:** Apple uses categorical enum values for sleep stages in the XML export. The JSON export from Health Auto Export aggregates these into numeric hours (much easier).
-**How to avoid:** In the XML parser, detect `type === 'HKCategoryTypeIdentifierSleepAnalysis'` and handle the `value` attribute as a stage name string. Map stage strings to bucket names:
-```javascript
-const SLEEP_STAGE_MAP = {
- 'HKCategoryValueSleepAnalysisAsleepDeep': 'deep',
- 'HKCategoryValueSleepAnalysisAsleepREM': 'rem',
- 'HKCategoryValueSleepAnalysisAsleepCore': 'core',
- 'HKCategoryValueSleepAnalysisAwake': 'awake',
- 'HKCategoryValueSleepAnalysisInBed': 'inBed',
- 'HKCategoryValueSleepAnalysisAsleep': 'asleep' // Legacy, pre-iOS 16
-};
-```
-Calculate stage duration from `enddate - startdate` (minutes), accumulate per day.
-**Warning signs:** Sleep dashboard showing zeros or NaN for all values.
-
-### Pitfall 3: Step Count Is High-Frequency in XML (Aggregation Required)
-**What goes wrong:** Steps in the XML are recorded every few seconds by the accelerometer — a single day may have thousands of step-count records. Storing each individually and then summing for the dashboard is correct but easy to do wrong (forgetting to sum per day).
-**Why it happens:** Apple records steps at sensor cadence, not daily aggregates.
-**How to avoid:** During XML import, sum step records per day before writing the day file, or store all records and sum during query. The simplest approach: accumulate `qty` values per day in the XML parser, write one aggregated `step_count` entry per day.
-**Warning signs:** Step counts that are 100x higher than reality (forgot to deduplicate overlapping source records), or counts that are tiny (truncated to last record only).
-
-### Pitfall 4: Health Auto Export Metric Names vs Apple HealthKit Type Names
-**What goes wrong:** The JSON push from Health Auto Export uses `"name": "step_count"` (snake_case strings), but the XML export uses `type="HKQuantityTypeIdentifierStepCount"` (HealthKit class names). Code written for one ingest path will fail on the other if names are treated as equivalent.
-**Why it happens:** Health Auto Export normalizes metric names to human-readable snake_case for its JSON API.
-**How to avoid:** Maintain a mapping in the service:
-```javascript
-const XML_TO_METRIC_NAME = {
- 'HKQuantityTypeIdentifierStepCount': 'step_count',
- 'HKQuantityTypeIdentifierHeartRate': 'heart_rate',
- 'HKQuantityTypeIdentifierHeartRateVariabilitySDNN': 'heart_rate_variability_sdnn',
- 'HKCategoryTypeIdentifierSleepAnalysis': 'sleep_analysis',
- // store all others verbatim or normalized
-};
-```
-**Warning signs:** Dashboard queries returning no data after XML import; metric names with `HKQuantityTypeIdentifier` prefix appearing in day files alongside snake_case names from JSON push.
-
-### Pitfall 5: Timezone Handling in Apple Health Dates
-**What goes wrong:** Apple Health timestamps include timezone offsets (e.g., `"2024-01-15 08:30:00 -0800"`). If you parse these naively as UTC or strip the offset, dates near midnight can land on the wrong day.
-**Why it happens:** The Health app records timestamps in the device's local timezone.
-**How to avoid:** Extract the `YYYY-MM-DD` portion from the original timestamp string before any parsing, not from a parsed Date object. The string prefix `date.split(' ')[0]` (or `.substring(0, 10)`) gives the local date without timezone conversion. Use this as the day-partition key.
-**Warning signs:** Some days showing no data while adjacent days have double data; late-night records appearing on the "next" day in UTC.
-
-### Pitfall 6: express.json() Limit for Large JSON Pushes
-**What goes wrong:** Health Auto Export can send large JSON payloads if syncing many days at once. The default Express JSON body parser limit is 100kb; the current `index.js` sets it to 50mb. Large batch syncs could still exceed this.
-**Why it happens:** Health Auto Export can send weeks or months of data in a single batch.
-**How to avoid:** The existing 50mb limit in `index.js` is probably sufficient for incremental pushes (the app syncs frequently). Document that batch syncs should be configured with smaller date ranges in the Health Auto Export app settings. If needed, the `/api/health/ingest` route can set its own limit via express-specific middleware.
-**Warning signs:** 413 Payload Too Large errors from the ingest endpoint.
-
-### Pitfall 7: Day File Write Races During XML Import
-**What goes wrong:** If SAX events fire faster than async file writes complete, multiple writes to the same day file can overlap and corrupt data.
-**Why it happens:** SAX parsing is synchronous but file writes are async; if you fire writes inside the opentag handler, multiple writes to the same day race.
-**How to avoid:** Accumulate all day buckets in-memory during SAX parse, then write all day files sequentially (or with capped concurrency) after the stream ends. Never write during the SAX event loop.
-**Warning signs:** JSON parse errors when reading day files; truncated files.
-
----
-
-## Code Examples
-
-Verified patterns from official sources and project codebase:
-
-### How io is accessed in routes (from backup.js)
-```javascript
-// Source: server/routes/backup.js line 20
-const io = req.app.get('io');
-const result = await backup.runBackup(settings.backup?.destPath, io);
-```
-
-### How app sets io (from index.js)
-```javascript
-// Source: server/index.js line 171
-app.set('io', io);
-```
-
-### Day-partitioned file read helper (follows meatspaceHealth.js pattern)
-```javascript
-// Source: pattern from server/services/meatspaceHealth.js
-import { readJSONFile, PATHS } from '../lib/fileUtils.js';
-import { join } from 'path';
-
-const HEALTH_DIR = join(PATHS.data, 'health'); // until PATHS.health is added
-
-export async function readDayFile(dateStr) {
- const filePath = join(HEALTH_DIR, `${dateStr}.json`);
- return readJSONFile(filePath, { date: dateStr, metrics: {} });
-}
-```
-
-### Recharts LineChart with dark theme (matching port-* tokens)
-```jsx
-// Pattern from client/src/components/meatspace/AlcoholChart.jsx style
-import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
-
-<ResponsiveContainer width="100%" height={200}>
- <LineChart data={data}>
- <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />
- <XAxis dataKey="date" tick={{ fill: '#9ca3af', fontSize: 11 }} />
- <YAxis tick={{ fill: '#9ca3af', fontSize: 11 }} />
- <Tooltip contentStyle={{ background: '#1a1a1a', border: '1px solid #2a2a2a', color: '#fff' }} />
- <Line type="monotone" dataKey="value" stroke="#3b82f6" dot={false} strokeWidth={2} />
- </LineChart>
-</ResponsiveContainer>
-```
-
-### MeatSpace tab addition pattern (from MeatSpace.jsx + constants.js)
-```javascript
-// Add to client/src/components/meatspace/constants.js TABS array
-{ id: 'health', label: 'Health', icon: HeartPulse }
-// 'health' sorts alphabetically between 'genome' and 'lifestyle' — correct order
-
-// Add to MeatSpace.jsx renderTabContent switch
-case 'health':
- return <HealthTab />;
-```
-
-### Apple Health XML Record element structure
-```xml
-<!-- Steps record (numeric value) -->
-<Record type="HKQuantityTypeIdentifierStepCount"
- sourceName="Adam's iPhone"
- sourceVersion="17.0"
- unit="count"
- creationDate="2024-01-15 10:05:32 -0800"
- startDate="2024-01-15 10:00:00 -0800"
- endDate="2024-01-15 10:05:00 -0800"
- value="432"/>
-
-<!-- Heart Rate Variability (numeric value, ms) -->
-<Record type="HKQuantityTypeIdentifierHeartRateVariabilitySDNN"
- unit="ms"
- startDate="2024-01-15 06:12:00 -0800"
- endDate="2024-01-15 06:17:00 -0800"
- value="42.3"/>
-
-<!-- Sleep (categorical value, not numeric) -->
-<Record type="HKCategoryTypeIdentifierSleepAnalysis"
- sourceName="Adam's Apple Watch"
- startDate="2024-01-15 00:30:00 -0800"
- endDate="2024-01-15 01:45:00 -0800"
- value="HKCategoryValueSleepAnalysisAsleepDeep"/>
-```
-
----
-
-## State of the Art
-
-| Old Approach | Current Approach | When Changed | Impact |
-|--------------|------------------|--------------|--------|
-| DOM-based XML parsers (xml2js) | SAX streaming | Established | DOM loads full file into memory — fatal for 500MB+ |
-| Single health data file | Day-partitioned files | User decision | Enables efficient date-range queries without loading all data |
-| Health Auto Export v1 format | v2 format with `data.metrics[]` wrapper | ~2022 | v1 used flat array without `data` wrapper; always validate for `data.metrics` existence |
-
-**Deprecated/outdated:**
-- Health Auto Export v1 JSON format: flat `{ metrics: [] }` without the `data` wrapper. The current format wraps in `data`: `{ data: { metrics: [] } }`. The Zod schema should validate `data.metrics` and return a clear error if payload is v1 format.
-- `HKCategoryValueSleepAnalysisAsleep` (legacy, pre-iOS 16): maps to "asleep generally" — newer exports split into `AsleepCore`, `AsleepDeep`, `AsleepREM`. Store both but prefer the specific stages.
-
----
-
-## Open Questions
-
-1. **Exact metric name strings in Health Auto Export JSON**
- - What we know: `step_count`, `heart_rate`, `sleep_analysis` confirmed from documentation and community usage; `heart_rate_variability_sdnn` is the documented HRV metric name
- - What's unclear: Whether the app sends `heart_rate_variability_sdnn` or `hrv` or another variant in the latest v7+ release
- - Recommendation: Write the Zod schema with `.passthrough()` so unknown metric names are stored without validation failure; query by exact name string; document the expected names in comments
-
-2. **Progress percentage for XML (total record count unknown before streaming)**
- - What we know: SAX streaming doesn't know total records before it starts; we can't show a true percentage without a pre-scan
- - What's unclear: Whether a pre-scan pass is worth the latency
- - Recommendation: Emit live record counts (`processed: N`) rather than percentage; the UI shows "N records processed" rather than "X%" — simpler and still informative
-
-3. **Apple Health export ZIP vs raw XML**
- - What we know: The Apple Health export from iOS is a `.zip` file containing `export.xml` inside
- - What's unclear: Whether users will upload the ZIP or extract the XML themselves
- - Recommendation: Accept raw `.xml` upload only (simpler); document in the UI that users must extract the ZIP first. The Import tab can show this instruction. Defer ZIP extraction support to Phase 4 if needed.
-
-4. **Nutrition overwrite behavior**
- - What we know: Decision is "Apple Health nutrition REPLACES existing daily-log nutrition for overlapping days"
- - What's unclear: Exactly which file gets overwritten — `data/meatspace/daily-log.json` (existing) vs the new `data/health/YYYY-MM-DD.json` (new)
- - Recommendation: The new health day files are the canonical store for Apple Health data (including nutrition from Apple Health). The existing `daily-log.json` is the canonical store for manually-entered TSV data. Do NOT overwrite `daily-log.json` with Apple Health nutrition — instead, when querying nutrition for the dashboard, prefer health day files over daily-log for overlapping dates. This is safer and reversible.
-
----
-
-## Validation Architecture
-
-> workflow.nyquist_validation not present in config.json — skipping this section per instructions.
-
----
-
-## Test Infrastructure
-
-**Framework:** Vitest (v4.0.16), confirmed in `server/package.json`
-**Test pattern:** Inline pure function copies to avoid complex mocking (see `meatspaceHealth.test.js` and `meatspaceImport.test.js`)
-**Run command:** `cd server && npm test`
-
-Tests to write for this phase follow the established project pattern:
-- `appleHealthIngest.test.js` — pure functions for dedup, metric parsing, date extraction
-- `appleHealthXml.test.js` — pure functions for XML record parsing, sleep stage mapping, step aggregation
-- `appleHealthQuery.test.js` — pure functions for date range filtering, aggregation for dashboard
-
-Mock pattern used in project: `vi.mock('fs/promises', ...)` and `vi.mock('../lib/fileUtils.js', ...)`
-
----
-
-## Sources
-
-### Primary (HIGH confidence)
-- `server/routes/backup.js` + `server/services/backup.js` — io access pattern (`req.app.get('io')`, `io.emit`)
-- `server/index.js` line 171 — `app.set('io', io)` pattern
-- `server/lib/fileUtils.js` — PATHS constants, readJSONFile helper
-- `server/services/meatspaceImport.js` — File write pattern, ensureDir usage
-- `server/services/meatspaceHealth.js` — Service pattern for health data CRUD
-- `client/package.json` — recharts v3.7.0 already installed
-- `server/package.json` — sax and multer NOT yet installed; zod, socket.io confirmed
-- https://github.com/Lybron/health-auto-export/wiki/API-Export---JSON-Format — JSON schema (HIGH confidence, official wiki)
-- https://github.com/isaacs/sax-js — SAX streaming API, createStream, opentag event structure
-
-### Secondary (MEDIUM confidence)
-- https://ladvien.com/syncing-apple-health-kit-data-postgres/ — Confirmed JSON payload structure with real implementation example
-- https://www.johngoldin.com/blog/apple-health-export/2023-02-sleep-export/ — Sleep XML value strings (HKCategoryValueSleepAnalysis*) confirmed
-- https://www.ryanpraski.com/apple-health-data-how-to-export-analyze-visualize-guide/ — XML Record element attributes confirmed
-- WebSearch results — SAX non-strict mode for Apple Health XML confirmed; multer diskStorage for large files confirmed
-
-### Tertiary (LOW confidence)
-- Exact metric name strings for Health Auto Export v7+ JSON (e.g., `heart_rate_variability_sdnn` vs `hrv`) — not directly verified against current app version; only confirmed from older documentation and community examples
-
----
-
-## Metadata
-
-**Confidence breakdown:**
-- Standard stack: HIGH — sax, multer, recharts, zod, socket.io all verified; sax and multer need installation
-- Architecture: HIGH — patterns confirmed from existing project files (backup.js, meatspaceImport.js, meatspaceHealth.js)
-- Apple Health data formats: HIGH for XML structure; MEDIUM for exact JSON metric names (app version variance)
-- Pitfalls: HIGH — XML non-strict mode, sleep categorical values, and timezone issues verified from multiple community sources
-- Recharts patterns: HIGH — library already installed; API verified
-
-**Research date:** 2026-02-26
-**Valid until:** 2026-03-28 (recharts and sax are stable; Health Auto Export schema may update with app releases)
diff --git a/.planning/phases/03-apple-health-integration/03-VERIFICATION.md b/.planning/phases/03-apple-health-integration/03-VERIFICATION.md
deleted file mode 100644
index c4dd2ba512..0000000000
--- a/.planning/phases/03-apple-health-integration/03-VERIFICATION.md
+++ /dev/null
@@ -1,163 +0,0 @@
----
-phase: 03-apple-health-integration
-verified: 2026-02-26T23:55:00Z
-status: passed
-score: 12/12 must-haves verified
-re_verification: false
-human_verification:
- - test: "Navigate to /meatspace/health and verify Health tab renders with four metric cards"
- expected: "Steps, Heart Rate, Sleep, and HRV cards render with hero numbers and charts (or empty states when no data ingested). Range selector (7d/30d/90d/1y) changes visible date range."
- why_human: "Visual rendering and interactive tab switching cannot be verified programmatically"
- - test: "Open Import tab in MeatSpace and verify Apple Health XML import section appears"
- expected: "Working file picker button labeled 'Choose XML File', accepts .xml files only. TSV section and Apple Health XML section both visible with distinct styling."
- why_human: "UI rendering and file picker behavior requires browser"
- - test: "POST /api/health/ingest with sample data, then verify day file created and dedup works"
- expected: "curl -X POST http://localhost:5554/api/health/ingest -H 'Content-Type: application/json' -d '{\"data\":{\"metrics\":[{\"name\":\"step_count\",\"units\":\"count\",\"data\":[{\"date\":\"2024-01-15 08:30:00 -0800\",\"qty\":8432}]}]}}' returns {recordsIngested:1,recordsSkipped:0}. Re-running returns {recordsIngested:0,recordsSkipped:1}. data/health/2024-01-15.json exists."
- why_human: "Requires running server with write access to data/health/ directory"
- - test: "Verify sleep stage stacked bar in SleepCard"
- expected: "If sleep data contains stage breakdown, stacked bars render. NOTE: the /daily endpoint returns { date, value } for sleep_analysis (value=totalSleep) — stage breakdowns (deep/rem/core/awake) are NOT returned by getDailyAggregates. The stacked bar will show 'Sleep stage breakdown not available' unless data happens to have those fields. Hero number (avg hrs) will render correctly."
- why_human: "Functional limitation requires human verification with real data to confirm UX impact"
----
-
-# Phase 3: Apple Health Integration Verification Report
-
-**Phase Goal:** Apple Health data flows into PortOS via JSON ingest and bulk XML import, with health metrics visible on the MeatSpace dashboard
-**Verified:** 2026-02-26T23:55:00Z
-**Status:** passed
-**Re-verification:** No — initial verification
-
-## Goal Achievement
-
-### Observable Truths
-
-| # | Truth | Status | Evidence |
-|----|-------------------------------------------------------------------------------------------------------------------|------------|-------------------------------------------------------------------------------------------------------------------|
-| 1 | POST /api/health/ingest accepts Health Auto Export JSON, validates with Zod, and returns success with record counts | VERIFIED | Route exists in `appleHealth.js` L35-39; `healthIngestSchema` validates and returns `{ metricsProcessed, recordsIngested, recordsSkipped, daysAffected }` |
-| 2 | Duplicate records (same metric name + timestamp) are silently skipped on re-ingest | VERIFIED | `mergeIntoDay()` builds `existingDates` Set, filters `uniquePoints`; skipped count returned in `recordsSkipped` |
-| 3 | Health data is persisted to day-partitioned files at data/health/YYYY-MM-DD.json | VERIFIED | `writeDayFile()` writes to `join(PATHS.health, dateStr + '.json')`; `PATHS.health` = `data/health/` |
-| 4 | GET /api/health/metrics returns aggregated metric data for a requested date range | VERIFIED | `getDailyAggregates()` and `getMetricSummary()` wired to `/metrics/:metricName/daily` and `/metrics/:metricName` |
-| 5 | Existing system health endpoints moved to /api/system/health and /api/system/health/details without breakage | VERIFIED | `systemHealth.js` routes at `/health` and `/health/details`; mounted at `/api/system` in `index.js` L175; test updated and passing |
-| 6 | Uploading 500MB+ Apple Health XML completes without OOM errors | VERIFIED | `multer.diskStorage` to `tmpdir()` (not memoryStorage); SAX streaming via `createReadStream().pipe(saxStream)` |
-| 7 | XML import progress updates in real-time via WebSocket during import | VERIFIED | `io?.emit('health:xml:progress', { processed })` every 10000 records in `appleHealthXml.js` L167-169 |
-| 8 | XML records are normalized to day-file format (metric names mapped from HK identifiers) | VERIFIED | `XML_TO_METRIC_NAME` map in `appleHealthXml.js`; `normalizeXmlRecord()` tested and returns correct `metricName='step_count'` |
-| 9 | Sleep XML records with categorical values are correctly parsed into duration-based stage data | VERIFIED | `SLEEP_STAGE_MAP` maps HK categories; `aggregateSleepAnalysis()` sums stage durations per day |
-| 10 | Import tab shows a working file picker and progress bar for Apple Health XML upload | VERIFIED | `ImportTab.jsx` has full XML import section with file picker, `health:xml:progress` WebSocket listener, progress bar, success/error states |
-| 11 | MeatSpace has a Health tab showing steps, heart rate, sleep, and HRV cards with trend charts | VERIFIED | `HealthTab.jsx` wired into `MeatSpace.jsx` case 'health'; `constants.js` has `{ id: 'health', label: 'Health', icon: Stethoscope }` |
-| 12 | Alcohol vs HRV and Activity vs blood work correlation charts render with auto-generated text summary | VERIFIED | `AlcoholHrvCorrelation.jsx` and `ActivityBloodCorrelation.jsx` exist, have computed summaries, 14-day threshold guard, wired into `HealthTab.jsx` |
-
-**Score:** 12/12 truths verified
-
-### Required Artifacts
-
-| Artifact | Expected | Status | Details |
-|-----------------------------------------------------------|---------------------------------------------------|-----------|--------------------------------------------------------------------------------|
-| `server/routes/systemHealth.js` | Renamed system health routes | VERIFIED | Exports default router; `/health` and `/health/details` routes present; 1 test passing |
-| `server/lib/appleHealthValidation.js` | Zod schemas for Health Auto Export JSON | VERIFIED | Exports `healthIngestSchema`, `healthMetricSchema`, `healthDataPointSchema`; schema validates correctly |
-| `server/services/appleHealthIngest.js` | JSON ingest, dedup, day-file merge | VERIFIED | Exports `ingestHealthData`, `extractDateStr`, `mergeIntoDay`, `readDayFile`, `writeDayFile` |
-| `server/services/appleHealthQuery.js` | Date-range queries for health metrics | VERIFIED | Exports `getMetrics`, `getMetricSummary`, `getDailyAggregates`, `getAvailableDateRange`, `getCorrelationData` |
-| `server/routes/appleHealth.js` | REST endpoints for ingest and query | VERIFIED | Exports default router; all 6 routes present including POST /import/xml with multer |
-| `server/services/appleHealthXml.js` | SAX streaming XML parser | VERIFIED | Exports `importAppleHealthXml` and `normalizeXmlRecord`; SAX non-strict mode; sax+multer in package.json |
-| `client/src/components/meatspace/tabs/ImportTab.jsx` | XML file picker with WebSocket progress | VERIFIED | `health:xml:progress` listener, `.xml` file filter, progress bar, success/error states |
-| `client/src/components/meatspace/tabs/HealthTab.jsx` | Health tab container with range selector | VERIFIED | Range selector (7d/30d/90d/1y), parallel fetch via Promise.all, 2-col card grid |
-| `client/src/components/meatspace/StepsCard.jsx` | Steps trend card with hero and LineChart | VERIFIED | Hero avg+localeString, LineChart stroke #3b82f6, empty state present |
-| `client/src/components/meatspace/HeartRateCard.jsx` | Heart rate card with avg/min/max | VERIFIED | Hero avg bpm, LineChart stroke #ef4444, empty state present |
-| `client/src/components/meatspace/SleepCard.jsx` | Sleep card with stacked horizontal bar | VERIFIED | Hero avg hrs, stacked BarChart layout="vertical", stage colors defined; see note on stage data availability |
-| `client/src/components/meatspace/HrvCard.jsx` | HRV trend card | VERIFIED | Hero avg ms, LineChart stroke #22c55e, empty state present |
-| `client/src/components/meatspace/AlcoholHrvCorrelation.jsx` | Dual-axis correlation chart | VERIFIED | ComposedChart with two YAxis, `computeSummary()` pure function, 14-day guard |
-| `client/src/components/meatspace/ActivityBloodCorrelation.jsx` | Activity vs blood work correlation | VERIFIED | 30-day rolling average, blood marker lines, 14-day guard, no-blood-tests state |
-
-### Key Link Verification
-
-| From | To | Via | Status | Details |
-|--------------------------------------|-------------------------------------------|------------------------------------------|----------|--------------------------------------------------------------------------------------|
-| `server/routes/appleHealth.js` | `server/services/appleHealthIngest.js` | `ingestHealthData(payload)` | WIRED | L7: import; L37: `ingestHealthData(validated)` in POST /ingest |
-| `server/routes/appleHealth.js` | `server/services/appleHealthQuery.js` | `getMetrics(metricName, from, to)` | WIRED | L9-14: all query functions imported; used in GET /metrics routes |
-| `server/index.js` | `server/routes/appleHealth.js` | `app.use('/api/health', appleHealthRoutes)` | WIRED | L8: import; L220: `app.use('/api/health', appleHealthRoutes)` |
-| `server/index.js` | `server/routes/systemHealth.js` | `app.use('/api/system', systemHealthRoutes)` | WIRED | L9: import; L175: `app.use('/api/system', systemHealthRoutes)` |
-| `server/routes/appleHealth.js` | `server/services/appleHealthXml.js` | `importAppleHealthXml(filePath, io)` | WIRED | L8: import; L80: `importAppleHealthXml(filePath, io)` in POST /import/xml |
-| `client/src/components/meatspace/tabs/ImportTab.jsx` | socket.io client | `socket.on('health:xml:progress')` | WIRED | L4: `import socket from '../../../services/socket'`; L25-35: useEffect listeners |
-| `server/services/appleHealthXml.js` | `server/services/appleHealthIngest.js` | `readDayFile/writeDayFile` | WIRED | L12: `import { extractDateStr, readDayFile, writeDayFile }` from ingest; used L206, L218 |
-| `client/src/components/meatspace/tabs/HealthTab.jsx` | `/api/health/metrics/:metricName/daily` | `api.getAppleHealthMetrics()` | WIRED | L2: `import * as api`; L39-42: `api.getAppleHealthMetrics(...)` in Promise.all |
-| `client/src/components/meatspace/tabs/HealthTab.jsx` | `/api/health/correlation` | `api.getAppleHealthCorrelation()` | WIRED | L43: `api.getAppleHealthCorrelation(from, to)` in Promise.all |
-| `client/src/pages/MeatSpace.jsx` | `HealthTab.jsx` | `case 'health' in renderTabContent` | WIRED | L10: import; L33: `case 'health': return <HealthTab />` |
-
-### Requirements Coverage
-
-| Requirement | Source Plan | Description | Status | Evidence |
-|-------------|-------------|---------------------------------------------------------------------------------------|-----------|---------------------------------------------------------------------------------------------|
-| HLT-01 | 03-01 | POST /api/health/ingest accepts Health Auto Export JSON, validates with Zod, deduplicates | SATISFIED | Route at L35-39 of `appleHealth.js`; `healthIngestSchema` validation; dedup via `mergeIntoDay()` |
-| HLT-02 | 03-01 | Health data persists to day-partitioned data/health/YYYY-MM-DD.json files | SATISFIED | `writeDayFile()` writes to `PATHS.health`; `PATHS.health = data/health/` |
-| HLT-03 | 03-02 | Bulk XML import streams 500MB+ without OOM via SAX parser | SATISFIED | SAX streaming with `createReadStream.pipe(saxStream)`; `multer.diskStorage` to tmpdir |
-| HLT-04 | 03-02 | XML import reports progress via WebSocket | SATISFIED | `io?.emit('health:xml:progress', { processed })` every 10k records; `health:xml:complete` on finish |
-| HLT-05 | 03-03 | MeatSpace dashboard cards for steps, heart rate, sleep, HRV trends | SATISFIED | Four card components wired to HealthTab; route `/meatspace/health` via constants.js TABS |
-| HLT-06 | 03-03 | Correlate Apple Health with MeatSpace data (alcohol vs HRV, activity vs blood work) | SATISFIED | `AlcoholHrvCorrelation.jsx` and `ActivityBloodCorrelation.jsx` with computed text summaries and real data merge via `getCorrelationData()` |
-
-All 6 phase requirements (HLT-01 through HLT-06) are satisfied. No orphaned requirements.
-
-### Anti-Patterns Found
-
-| File | Line | Pattern | Severity | Impact |
-|---------------------------------------------------------------------|------|--------------|----------|----------------------------------------------------------------------------------------------------------------------|
-| `server/services/appleHealthXml.js` | 20 | Duplicate key in object literal (`hkquantitytypeidentifierheartratevariancessdnn` listed twice) | Warning | The second definition shadows the first — no bug since both map to the same value, but shows a copy-paste artifact |
-| `client/src/components/meatspace/SleepCard.jsx` | 37 | Stage data unavailable at runtime | Warning | `getAppleHealthMetrics('sleep_analysis')` calls `/daily` endpoint which returns `{ date, value }` not `{ deep, rem, core, awake }`. Stacked bar will always show "Sleep stage breakdown not available". Hero avg works. |
-
-**Duplicate HRV key (line 20):** Not a bug — both entries map to `'heart_rate_variability_sdnn'` — but is an artifact that could be cleaned up.
-
-**Sleep stage data gap:** The stacked BarChart in SleepCard requires `{ deep, rem, core, awake }` fields, but `getDailyAggregates('sleep_analysis')` returns only `{ date, value }` (value = totalSleep). This means the stage proportion visualization will never render when using the current API call. The hero number (avg hours) will display correctly. This is a functional limitation that reduces the richness of HLT-05 but does not prevent the sleep card from displaying useful data. The fix would be to call `getAppleHealthSummary` for sleep or add a dedicated sleep stage endpoint.
-
-### Human Verification Required
-
-#### 1. Health tab visual rendering
-
-**Test:** Navigate to `http://localhost:5555/meatspace/health`
-**Expected:** Health tab appears in the tab bar (between Genome and Lifestyle). Four cards visible: Steps, Heart Rate, Sleep, HRV. Range selector buttons (7d/30d/90d/1y) visible. Clicking a range button changes displayed dates. Empty states show when no health data has been ingested. URL is deep-linkable (refreshing stays on Health tab).
-**Why human:** Visual appearance, tab interaction, and deep-link behavior require browser.
-
-#### 2. Import tab XML section
-
-**Test:** Navigate to MeatSpace > Import tab (if accessible via tab, or `http://localhost:5555/meatspace/import`)
-**Expected:** Apple Health XML Import section visible below TSV section, with a "Choose XML File" button. File picker accepts only `.xml` files. Instructions tell user to extract ZIP and upload export.xml.
-**Why human:** UI rendering requires browser.
-
-#### 3. JSON ingest end-to-end (with dedup)
-
-**Test:** Run the following curl commands:
-```bash
-# First ingest
-curl -X POST http://localhost:5554/api/health/ingest \
- -H 'Content-Type: application/json' \
- -d '{"data":{"metrics":[{"name":"step_count","units":"count","data":[{"date":"2024-01-15 08:30:00 -0800","qty":8432}]}]}}'
-
-# Verify day file created
-ls data/health/2024-01-15.json
-
-# Dedup check — same record
-curl -X POST http://localhost:5554/api/health/ingest \
- -H 'Content-Type: application/json' \
- -d '{"data":{"metrics":[{"name":"step_count","units":"count","data":[{"date":"2024-01-15 08:30:00 -0800","qty":8432}]}]}}'
-```
-**Expected:** First call returns `{"recordsIngested":1,"recordsSkipped":0,...}`. Day file `data/health/2024-01-15.json` exists. Second call returns `{"recordsIngested":0,"recordsSkipped":1,...}`.
-**Why human:** Requires live server with write access to `data/health/`.
-
-#### 4. Sleep stage stacked bar limitation
-
-**Test:** After ingesting XML data with sleep records, check if the stacked bar chart shows sleep stages.
-**Expected:** The hero average hours will display correctly. The stacked bar chart is likely to show "Sleep stage breakdown not available" because `getAppleHealthMetrics('sleep_analysis')` calls `/daily` which returns `{ date, value }` not `{ deep, rem, core, awake }`. Confirm whether this is acceptable or needs a fix.
-**Why human:** Requires real sleep data and browser to observe rendering behavior.
-
-### Notes on Implementation Quality
-
-- **Timezone safety:** `extractDateStr()` uses `substring(0, 10)` not `Date()` — correct approach for Apple Health timestamps to avoid UTC shift.
-- **Dedup key:** Uses full date string (not extracted date) — correctly distinguishes multiple same-day readings (e.g., multiple heart rate readings).
-- **Schema future-proofing:** `healthDataPointSchema` and the `data` object use `.passthrough()` — handles future Health Auto Export app fields without breakage.
-- **SAX error handling:** Error handler clears `_parser.error` and resumes — correctly handles Apple Health's occasionally malformed XML.
-- **Post-parse aggregation:** Step and sleep aggregation happens outside SAX event loop — avoids complexity in callbacks.
-- **Multer configuration:** `diskStorage` to `tmpdir()` with 2GB limit — prevents OOM on large files.
-- **All 1192 server tests pass** — zero regressions.
-- **Client builds cleanly** — 3332 modules compiled in 4.45s.
-- **7 phase commits verified:** `7c2a592`, `200a0d2`, `2cd855f`, `8967415`, `a4b2d20`, `11cc0ea`, `81bd182`.
-
----
-
-_Verified: 2026-02-26T23:55:00Z_
-_Verifier: Claude (gsd-verifier)_
diff --git a/.planning/phases/04-cross-domain-insights-engine/04-01-PLAN.md b/.planning/phases/04-cross-domain-insights-engine/04-01-PLAN.md
deleted file mode 100644
index ff5140a7b3..0000000000
--- a/.planning/phases/04-cross-domain-insights-engine/04-01-PLAN.md
+++ /dev/null
@@ -1,355 +0,0 @@
----
-phase: 04-cross-domain-insights-engine
-plan: 01
-type: execute
-wave: 1
-depends_on: []
-files_modified:
- - server/services/insightsService.js
- - server/routes/insights.js
- - server/index.js
- - server/lib/validation.js
- - client/src/services/api.js
-autonomous: true
-requirements:
- - INS-01
- - INS-02
- - INS-04
-
-must_haves:
- truths:
- - "GET /api/insights/genome-health returns genome markers grouped by clinical category with matched blood test values and confidence levels"
- - "GET /api/insights/themes returns cached LLM-generated taste-identity themes or triggers generation"
- - "POST /api/insights/themes/refresh regenerates theme analysis from current taste profile data"
- - "GET /api/insights/narrative returns cached cross-domain narrative with previous text for diff"
- - "POST /api/insights/narrative/refresh generates new narrative preserving previous text"
- - "All endpoints degrade gracefully when source data is missing (genome, blood tests, taste profile)"
- artifacts:
- - path: "server/services/insightsService.js"
- provides: "Insights engine with correlation, theme, and narrative functions"
- exports: ["getGenomeHealthCorrelations", "getThemeAnalysis", "generateThemeAnalysis", "getCrossDomainNarrative", "refreshCrossDomainNarrative"]
- - path: "server/routes/insights.js"
- provides: "REST API routes for insights"
- exports: ["default (Router)"]
- - path: "client/src/services/api.js"
- provides: "Client API functions for insights endpoints"
- exports: ["getGenomeHealthCorrelations", "getInsightThemes", "refreshInsightThemes", "getInsightNarrative", "refreshInsightNarrative"]
- key_links:
- - from: "server/routes/insights.js"
- to: "server/services/insightsService.js"
- via: "import * as insightsService"
- pattern: "insightsService\\."
- - from: "server/index.js"
- to: "server/routes/insights.js"
- via: "app.use('/api/insights')"
- pattern: "app\\.use.*insights"
- - from: "server/services/insightsService.js"
- to: "server/services/genome.js"
- via: "getGenomeSummary()"
- pattern: "getGenomeSummary"
- - from: "server/services/insightsService.js"
- to: "server/services/meatspaceHealth.js"
- via: "getBloodTests(), getBodyHistory()"
- pattern: "getBloodTests|getBodyHistory"
- - from: "server/services/insightsService.js"
- to: "server/services/taste-questionnaire.js"
- via: "getTasteProfile()"
- pattern: "getTasteProfile"
----
-
-<objective>
-Build the insights engine backend: a service layer that correlates genome markers with blood test data (rule-based), generates LLM taste-to-identity themes, and produces cross-domain narrative summaries. Wire up REST routes and client API functions.
-
-Purpose: Establish the complete data and API layer for the Insights dashboard. All three insight domains (genome-health, taste-identity, cross-domain narrative) are served from this backend — the frontend plan consumes these endpoints.
-
-Output: `insightsService.js` with 5 exported functions, `routes/insights.js` with 5 endpoints, Zod validation schemas, client API helpers, `data/insights/` cache directory.
-</objective>
-
-<execution_context>
-@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
-@/Users/antic/.claude/get-shit-done/templates/summary.md
-</execution_context>
-
-<context>
-
-<interfaces>
-<!-- Key types and contracts the executor needs. Extracted from codebase. -->
-
-From server/services/genome.js:
-```javascript
-export async function getGenomeSummary()
-// Returns: { uploaded: bool, savedMarkers: { [uuid]: { rsid, gene, category, status, name, description, implications, references } }, ... }
-// status values: 'beneficial', 'typical', 'concern', 'major_concern', 'not_found'
-```
-
-From server/lib/curatedGenomeMarkers.js:
-```javascript
-export const MARKER_CATEGORIES = {
- longevity: { label: 'Longevity', icon: 'Sparkles', color: 'purple' },
- cardiovascular: { label: 'Cardiovascular', icon: 'HeartPulse', color: 'rose' },
- iron: { label: 'Iron Metabolism', icon: 'Droplet', color: 'red' },
- methylation: { label: 'Methylation', icon: 'Zap', color: 'blue' },
- nutrient: { label: 'Nutrient Metabolism', icon: 'Apple', color: 'emerald' },
- caffeine: { label: 'Caffeine', icon: 'Coffee', color: 'amber' },
- detox: { label: 'Detoxification', icon: 'Shield', color: 'green' },
- inflammation: { label: 'Inflammation', icon: 'Flame', color: 'orange' },
- tumor_suppression: { label: 'Tumor Suppression', icon: 'ShieldCheck', color: 'indigo' },
- cognitive: { label: 'Cognitive', icon: 'Brain', color: 'cyan' },
- cognitive_decline: { label: 'Cognitive Decline & Dementia Risk', icon: 'BrainCog', color: 'rose' },
- sleep: { label: 'Sleep & Circadian', icon: 'Moon', color: 'violet' },
- athletic: { label: 'Athletic Performance', icon: 'Dumbbell', color: 'sky' },
- skin: { label: 'Skin & UV Response', icon: 'Sun', color: 'yellow' },
- diabetes: { label: 'Blood Sugar & Diabetes', icon: 'Droplets', color: 'amber' },
- gut_health: { label: 'Gut Health & Digestion', icon: 'Salad', color: 'lime' },
- autoimmune: { label: 'Autoimmune Risk', icon: 'ShieldAlert', color: 'pink' },
- thyroid: { label: 'Thyroid & Hormones', icon: 'Activity', color: 'teal' },
- eye_health: { label: 'Eye Health', icon: 'Eye', color: 'sky' },
- mental_health: { label: 'Mental Health', icon: 'Brain', color: 'violet' },
- bone_health: { label: 'Bone Health', icon: 'Bone', color: 'stone' },
- pharmacogenomics: { label: 'Pharmacogenomics', icon: 'Pill', color: 'fuchsia' },
- // ... plus cancer-specific categories
-};
-// 117 total markers across these categories
-```
-
-From server/services/meatspaceHealth.js:
-```javascript
-export async function getBloodTests()
-// Returns: { tests: [{ date, ...analytes }], referenceRanges: {} }
-
-export async function getBodyHistory()
-// Returns: [{ date, weight, bodyFat, ... }]
-```
-
-From server/services/taste-questionnaire.js:
-```javascript
-export async function getTasteProfile()
-// Returns: { sections: [{ id, label, status, summary, progress }], completedCount, profileSummary }
-
-// LLM call pattern (local to taste-questionnaire.js, must be replicated):
-async function callProviderAISimple(provider, model, prompt, { temperature, max_tokens })
-// Returns: { text: string } on success, { error: string } on failure
-```
-
-From server/services/providers.js:
-```javascript
-export async function getActiveProvider()
-export async function getProviderById(id)
-```
-
-From server/services/appleHealthQuery.js:
-```javascript
-export async function getCorrelationData(from, to)
-export async function getDailyAggregates(metricName, from, to)
-```
-
-From server/lib/fileUtils.js:
-```javascript
-export const PATHS = { data: '...', health: '...', meatspace: '...', ... };
-export async function ensureDir(dir)
-export async function readJSONFile(filePath, defaultValue)
-```
-
-From server/lib/errorHandler.js:
-```javascript
-export function asyncHandler(fn)
-```
-
-From client/src/services/api.js:
-```javascript
-async function request(endpoint, options = {})
-// Base: /api, auto JSON headers, toast on error, returns parsed JSON
-```
-</interfaces>
-</context>
-
-<tasks>
-
-<task type="auto">
- <name>Task 1: Create insightsService.js with genome-health correlation engine and LLM analysis functions</name>
- <files>server/services/insightsService.js</files>
- <action>
-Create `server/services/insightsService.js` with 5 exported functions:
-
-**1. `getGenomeHealthCorrelations()`** (INS-01 — pure rule-based, no LLM):
-- Import `getGenomeSummary` from `genome.js`, `getBloodTests` and `getBodyHistory` from `meatspaceHealth.js`, `getCorrelationData` from `appleHealthQuery.js`, `MARKER_CATEGORIES` from `curatedGenomeMarkers.js`
-- Call `getGenomeSummary()` — if `!summary.uploaded` return `{ available: false, reason: 'no_genome' }`
-- Extract `savedMarkers` from summary, filter out `status === 'not_found'` markers
-- Call `getBloodTests()` in parallel — extract latest value per analyte from `tests` array using a `getLatestBloodValues(tests)` helper that normalizes analyte names (lowercase, trim, common abbreviation mapping)
-- Define `CATEGORY_BLOOD_MAP` object mapping marker categories to blood analyte names:
- ```
- cardiovascular: ['total_cholesterol', 'ldl', 'hdl', 'triglycerides', 'homocysteine']
- iron: ['ferritin', 'serum_iron', 'transferrin_saturation', 'tibc']
- methylation: ['homocysteine', 'b12', 'folate']
- diabetes: ['fasting_glucose', 'hba1c', 'insulin']
- thyroid: ['tsh', 't3', 't4']
- nutrient: ['vitamin_d', 'b12', 'folate', 'magnesium', 'zinc']
- ```
- (Other categories like longevity, cognitive, sleep, athletic, etc. have no direct blood analyte mapping — include them with `matchedBloodValues: []`)
-- Define `CONFIDENCE_FROM_STATUS` mapping:
- ```
- beneficial: { level: 'strong', color: 'green', label: 'Strong Evidence' }
- typical: { level: 'moderate', color: 'yellow', label: 'Moderate Evidence' }
- concern: { level: 'weak', color: 'red', label: 'Elevated Risk Marker' }
- major_concern: { level: 'significant', color: 'red', label: 'Significant Risk Marker' }
- ```
-- Group markers by `category` key. For each category group, produce:
- ```
- {
- category: key,
- label: MARKER_CATEGORIES[key].label,
- icon: MARKER_CATEGORIES[key].icon,
- color: MARKER_CATEGORIES[key].color,
- markers: [{ rsid, gene, name, status, description, implications, confidence: CONFIDENCE_FROM_STATUS[status], matchedBloodValues: [...], references }],
- notFoundCount: N
- }
- ```
- where `matchedBloodValues` is an array of `{ analyte, value, date, unit }` objects from the latest blood test data for that category's mapped analytes
-- Return `{ available: true, categories: [...], totalMarkers: N, matchedMarkers: N, sources: ['23andMe', ...conditionally 'Apple Health', 'Blood Tests'] }`
-- IMPORTANT: Never use language implying causation. Status labels show correlation strength, not causal claims.
-
-**2. `getThemeAnalysis()`** (INS-02 — returns cached themes):
-- Read `data/insights/themes.json` using `readJSONFile(path, null)`
-- If null (no cached themes), return `{ available: false, reason: 'not_generated' }`
-- Otherwise return the cached object as-is: `{ themes: [...], generatedAt, model }`
-
-**3. `generateThemeAnalysis(providerId, model)`** (INS-02 — LLM generation):
-- Import `getTasteProfile` from `taste-questionnaire.js`, `getActiveProvider`/`getProviderById` from `providers.js`
-- Get taste profile, filter sections that have `summary` populated
-- If no completed sections, return `{ available: false, reason: 'no_taste_data' }`
-- Get provider (by ID or active). Get model (passed or `provider.defaultModel`)
-- Build prompt: provide all section summaries as context, request JSON array of 3-5 theme objects with `title`, `narrative`, `evidence` (array of `{ preference, domain, connection }`), `strength` ("strong"/"moderate"/"tentative")
-- Use analytical third-person tone instruction: "The data indicates a pattern of..."
-- Replicate `callProviderAISimple` pattern inline (fetch to `provider.endpoint/chat/completions` with Authorization header, temperature 0.4, max_tokens 2000)
-- Strip markdown code fences before JSON.parse: `raw.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '')`
-- Persist to `data/insights/themes.json` with `{ themes, generatedAt: ISO string, model }`
-- Use `ensureDir` before writing
-- Log: `console.log(\`🧠 Taste-identity themes generated: ${themes.length} themes\`)`
-- Return `{ themes, generatedAt }`
-
-**4. `getCrossDomainNarrative()`** (INS-04 — returns cached narrative):
-- Read `data/insights/narrative.json` using `readJSONFile(path, null)`
-- If null, return `{ available: false, reason: 'not_generated' }`
-- Return cached: `{ text, previousText, generatedAt, previousGeneratedAt, model }`
-
-**5. `refreshCrossDomainNarrative(providerId, model)`** (INS-04 — LLM generation with diff support):
-- Load existing narrative from `data/insights/narrative.json` if it exists
-- Gather context from all domains:
- - Genome correlations via `getGenomeHealthCorrelations()` — summarize top findings by category
- - Taste themes via `getThemeAnalysis()` — include theme titles and summaries
- - Apple Health summary via `getCorrelationData()` (if available)
-- Build prompt requesting 2-3 paragraph analytical narrative with personal framing: "Your data shows..."
-- Use `callProviderAISimple` pattern (temperature 0.5, max_tokens 2000)
-- Strip markdown code fences from response
-- Persist to `data/insights/narrative.json`:
- ```
- {
- text: newText,
- previousText: existingNarrative?.text ?? null,
- generatedAt: new Date().toISOString(),
- previousGeneratedAt: existingNarrative?.generatedAt ?? null,
- model
- }
- ```
-- Log: `console.log(\`🔮 Cross-domain narrative generated (${newText.length} chars)\`)`
-- Return the persisted object
-
-**Helper: `callProviderAISimple(provider, model, prompt, options)`** — local async function:
-- Copy pattern exactly from `taste-questionnaire.js` lines 951-986
-- Handles API-type providers only, returns `{ text }` or `{ error }`
-
-**Helper: `getLatestBloodValues(tests)`** — pure function:
-- Takes array of blood test objects, returns Map of normalized analyte name → `{ value, date, unit }`
-- Normalizes keys: lowercase, trim, replace common abbreviations (e.g., "LDL Cholesterol" → "ldl")
-- Returns the latest (most recent date) value for each analyte
-
-All file I/O uses `PATHS.data` + 'insights' for the cache directory. Use `ensureDir` before writes. Use `readJSONFile` for reads.
- </action>
- <verify>
- <automated>cd /Users/antic/github.com/atomantic/PortOS/server && node -e "import('./services/insightsService.js').then(m => { const fns = ['getGenomeHealthCorrelations','getThemeAnalysis','generateThemeAnalysis','getCrossDomainNarrative','refreshCrossDomainNarrative']; const missing = fns.filter(f => typeof m[f] !== 'function'); if (missing.length) { console.error('Missing exports:', missing); process.exit(1); } console.log('All 5 functions exported'); })"</automated>
- </verify>
- <done>insightsService.js exports 5 functions. getGenomeHealthCorrelations returns categorized markers with blood value matching. Theme and narrative functions handle cache read, LLM generation, and file persistence. All functions degrade gracefully with { available: false, reason } when source data is missing.</done>
-</task>
-
-<task type="auto">
- <name>Task 2: Create insights routes, Zod validation, mount in index.js, and add client API functions</name>
- <files>server/routes/insights.js, server/lib/validation.js, server/index.js, client/src/services/api.js</files>
- <action>
-**1. Create `server/routes/insights.js`:**
-- Import `Router` from express, `asyncHandler` from `../lib/errorHandler.js`, `* as insightsService` from `../services/insightsService.js`
-- Import `validateRequest` and relevant schemas from `../lib/validation.js`
-
-5 routes:
-
-```
-GET /genome-health → insightsService.getGenomeHealthCorrelations()
-GET /themes → insightsService.getThemeAnalysis()
-POST /themes/refresh → insightsService.generateThemeAnalysis(req.body.providerId, req.body.model)
- - Validate body with insightRefreshSchema (optional providerId string, optional model string)
-GET /narrative → insightsService.getCrossDomainNarrative()
-POST /narrative/refresh → insightsService.refreshCrossDomainNarrative(req.body.providerId, req.body.model)
- - Validate body with insightRefreshSchema
-```
-
-All routes wrapped in `asyncHandler`. POST routes use `validateRequest(insightRefreshSchema)` middleware.
-Export default router.
-
-**2. Add Zod schema to `server/lib/validation.js`:**
-- Add `insightRefreshSchema` (z.object with optional `providerId` as z.string().optional() and `model` as z.string().optional())
-- Export alongside existing schemas
-
-**3. Mount in `server/index.js`:**
-- Import `insightsRoutes` from `'./routes/insights.js'`
-- Add `app.use('/api/insights', insightsRoutes);` — place alphabetically among existing route mounts (after `/api/instances` and before `/api/jira`)
-
-**4. Add client API functions to `client/src/services/api.js`:**
-- Add these exports (place in an `// Insights` section, alphabetically positioned among existing sections):
-```javascript
-// Insights
-export const getGenomeHealthCorrelations = () => request('/insights/genome-health');
-export const getInsightThemes = () => request('/insights/themes');
-export const refreshInsightThemes = (providerId, model) => request('/insights/themes/refresh', {
- method: 'POST',
- body: JSON.stringify({ providerId, model })
-});
-export const getInsightNarrative = () => request('/insights/narrative');
-export const refreshInsightNarrative = (providerId, model) => request('/insights/narrative/refresh', {
- method: 'POST',
- body: JSON.stringify({ providerId, model })
-});
-```
- </action>
- <verify>
- <automated>cd /Users/antic/github.com/atomantic/PortOS/server && node -e "import('./routes/insights.js').then(m => { const r = m.default; if (!r || !r.stack) { console.error('No router exported'); process.exit(1); } const routes = r.stack.filter(l => l.route).map(l => l.route.path + ' ' + Object.keys(l.route.methods).join(',')); console.log('Routes:', routes); if (routes.length < 5) { console.error('Expected 5 routes'); process.exit(1); } console.log('All 5 routes registered'); })"</automated>
- </verify>
- <done>5 REST endpoints mounted at /api/insights/*, Zod validation on POST bodies, client API functions exported. Server starts without errors. GET endpoints return graceful { available: false } when no data exists. POST endpoints accept optional providerId and model.</done>
-</task>
-
-</tasks>
-
-<verification>
-1. Server starts without import errors: `cd server && node -e "import('./index.js')"`
-2. GET /api/insights/genome-health responds (200 with data or graceful degradation)
-3. GET /api/insights/themes responds with `{ available: false, reason: 'not_generated' }` initially
-4. GET /api/insights/narrative responds with `{ available: false, reason: 'not_generated' }` initially
-5. POST /api/insights/themes/refresh with empty body returns 200 or appropriate error if no taste data
-6. POST /api/insights/narrative/refresh with empty body returns 200 or appropriate error
-7. Client api.js exports all 5 insight functions
-</verification>
-
-<success_criteria>
-- insightsService.js exports 5 functions matching the interface contract
-- All 5 routes return valid JSON responses
-- Genome-health correlations group markers by MARKER_CATEGORIES with blood test value matching
-- LLM functions persist results to data/insights/*.json with generatedAt timestamps
-- Narrative refresh preserves previousText for client-side diff
-- Empty states return { available: false, reason: '...' } not errors
-- No causation language in genome correlation labels — only "evidence" and "risk marker"
-</success_criteria>
-
-<output>
-After completion, create `.planning/phases/04-cross-domain-insights-engine/04-01-SUMMARY.md`
-</output>
diff --git a/.planning/phases/04-cross-domain-insights-engine/04-01-SUMMARY.md b/.planning/phases/04-cross-domain-insights-engine/04-01-SUMMARY.md
deleted file mode 100644
index ad3e68879d..0000000000
--- a/.planning/phases/04-cross-domain-insights-engine/04-01-SUMMARY.md
+++ /dev/null
@@ -1,144 +0,0 @@
----
-phase: 04-cross-domain-insights-engine
-plan: 01
-subsystem: insights-backend
-tags: [insights, genome, blood-tests, taste-identity, llm, rest-api]
-dependency_graph:
- requires:
- - server/services/genome.js (getGenomeSummary)
- - server/services/meatspaceHealth.js (getBloodTests)
- - server/services/taste-questionnaire.js (getTasteProfile)
- - server/services/providers.js (getActiveProvider, getProviderById)
- - server/services/appleHealthQuery.js (getCorrelationData)
- - server/lib/curatedGenomeMarkers.js (MARKER_CATEGORIES)
- - server/lib/fileUtils.js (PATHS, ensureDir, readJSONFile)
- - server/lib/errorHandler.js (asyncHandler)
- provides:
- - server/services/insightsService.js
- - server/routes/insights.js
- - /api/insights/* (5 endpoints)
- - client insights API (5 functions)
- affects:
- - server/index.js
- - server/lib/validation.js
- - client/src/services/api.js
- - data/insights/ (cache directory)
-tech_stack:
- added: []
- patterns:
- - Cache-first reads with graceful degradation ({ available: false, reason })
- - callProviderAISimple inline LLM call pattern (replicated from taste-questionnaire.js)
- - Rule-based genome-blood correlation (no LLM, deterministic)
- - previousText diff support for narrative versioning
-key_files:
- created:
- - server/services/insightsService.js
- - server/routes/insights.js
- modified:
- - server/lib/validation.js
- - server/index.js
- - client/src/services/api.js
- - .changelog/v1.14.x.md
-decisions:
- - Correlation strength labels use "Evidence" and "Risk Marker" language — never causation language — per INS-01 requirement
- - CONFIDENCE_FROM_STATUS maps marker status to human-readable confidence level with color
- - CATEGORY_BLOOD_MAP covers 6 categories (cardiovascular, iron, methylation, diabetes, thyroid, nutrient); other categories get empty matchedBloodValues
- - Cache files written to data/insights/themes.json and data/insights/narrative.json using ensureDir before first write
- - narrativeRefresh preserves previousText and previousGeneratedAt for client-side diff
- - LLM generation functions return { available: false, reason } (not throw) when provider unavailable or no data
- - insightRefreshSchema uses optional() fields (not .optional().default(undefined)) to avoid presence side effects
-metrics:
- duration: 174s
- completed: 2026-02-26
- tasks_completed: 2
- files_created: 2
- files_modified: 4
----
-
-# Phase 4 Plan 1: Insights Engine Backend Summary
-
-**One-liner:** Cross-domain insights engine with genome-health correlation (rule-based), LLM taste-identity themes, and cross-domain narrative — all served via 5 REST endpoints with cache-first graceful degradation.
-
-## What Was Built
-
-### `server/services/insightsService.js`
-
-Five exported functions forming the insights engine core:
-
-1. **`getGenomeHealthCorrelations()`** — Pure rule-based. Loads genome markers, filters `not_found` entries, groups by `MARKER_CATEGORIES` key, looks up blood analyte values using `CATEGORY_BLOOD_MAP`, attaches `CONFIDENCE_FROM_STATUS` label per marker. Returns `{ available: true, categories, totalMarkers, matchedMarkers, sources }`. Degrades to `{ available: false, reason: 'no_genome' }` if genome not uploaded.
-
-2. **`getThemeAnalysis()`** — Cache-first. Reads `data/insights/themes.json`. Returns `{ available: false, reason: 'not_generated' }` if no cache.
-
-3. **`generateThemeAnalysis(providerId, model)`** — LLM generation. Gets completed taste profile sections, builds analytical third-person prompt requesting 3-5 theme objects (title, narrative, evidence array, strength). Strips code fences, parses JSON, persists to `data/insights/themes.json`.
-
-4. **`getCrossDomainNarrative()`** — Cache-first. Reads `data/insights/narrative.json`. Returns `{ available: false, reason: 'not_generated' }` if no cache.
-
-5. **`refreshCrossDomainNarrative(providerId, model)`** — LLM generation with diff support. Gathers genome category summaries, taste theme titles, and Apple Health availability. Builds second-person prompt. Persists to `data/insights/narrative.json` with `previousText` and `previousGeneratedAt` from existing cache for client-side diff rendering.
-
-### `server/routes/insights.js`
-
-Five REST endpoints, all wrapped in `asyncHandler`:
-
-| Method | Path | Handler |
-|--------|------|---------|
-| GET | /genome-health | getGenomeHealthCorrelations() |
-| GET | /themes | getThemeAnalysis() |
-| POST | /themes/refresh | generateThemeAnalysis(body.providerId, body.model) |
-| GET | /narrative | getCrossDomainNarrative() |
-| POST | /narrative/refresh | refreshCrossDomainNarrative(body.providerId, body.model) |
-
-POST routes validate body with `insightRefreshSchema` (optional providerId, optional model).
-
-### `server/lib/validation.js`
-
-Added `insightRefreshSchema`:
-```js
-export const insightRefreshSchema = z.object({
- providerId: z.string().optional(),
- model: z.string().optional()
-});
-```
-
-### `server/index.js`
-
-Mounted `insightsRoutes` at `/api/insights` — inserted alphabetically between `/api/instances` and `/api/jira`.
-
-### `client/src/services/api.js`
-
-Added `// Insights` section with 5 exported functions:
-- `getGenomeHealthCorrelations()`
-- `getInsightThemes()`
-- `refreshInsightThemes(providerId, model)`
-- `getInsightNarrative()`
-- `refreshInsightNarrative(providerId, model)`
-
-## Verification Results
-
-- All 5 insightsService.js functions exported and importable
-- All 5 routes registered in insights router
-- `insightRefreshSchema` exported from validation.js
-- `getThemeAnalysis()` returns `{ available: false, reason: 'not_generated' }` gracefully
-- `getCrossDomainNarrative()` returns `{ available: false, reason: 'not_generated' }` gracefully
-- Route mount confirmed in index.js at `/api/insights`
-- Client API functions confirmed in api.js
-
-## Commits
-
-| Task | Hash | Description |
-|------|------|-------------|
-| Task 1 | 0f20b69 | feat(04-01): create insightsService.js with genome-health correlation engine and LLM analysis functions |
-| Task 2 | e4dc2be | feat(04-01): create insights routes, Zod validation, mount in index.js, add client API functions |
-
-## Deviations from Plan
-
-None — plan executed exactly as written.
-
-## Self-Check: PASSED
-
-- server/services/insightsService.js: FOUND
-- server/routes/insights.js: FOUND
-- server/lib/validation.js (insightRefreshSchema): FOUND
-- server/index.js (/api/insights mount): FOUND
-- client/src/services/api.js (5 insight functions): FOUND
-- commit 0f20b69: FOUND
-- commit e4dc2be: FOUND
diff --git a/.planning/phases/04-cross-domain-insights-engine/04-02-PLAN.md b/.planning/phases/04-cross-domain-insights-engine/04-02-PLAN.md
deleted file mode 100644
index f39334d16f..0000000000
--- a/.planning/phases/04-cross-domain-insights-engine/04-02-PLAN.md
+++ /dev/null
@@ -1,355 +0,0 @@
----
-phase: 04-cross-domain-insights-engine
-plan: 02
-type: execute
-wave: 2
-depends_on: ["04-01"]
-files_modified:
- - client/src/pages/Insights.jsx
- - client/src/components/insights/GenomeHealthTab.jsx
- - client/src/components/insights/TasteIdentityTab.jsx
- - client/src/components/insights/CrossDomainTab.jsx
- - client/src/components/insights/InsightCard.jsx
- - client/src/components/insights/ConfidenceBadge.jsx
- - client/src/components/insights/ProvenancePanel.jsx
- - client/src/components/insights/EmptyState.jsx
- - client/src/App.jsx
- - client/src/components/Layout.jsx
- - client/package.json
-autonomous: false
-requirements:
- - INS-03
- - INS-01
- - INS-02
- - INS-04
-
-must_haves:
- truths:
- - "Navigating to /insights shows the overview landing page with domain summary cards"
- - "Clicking a domain summary card navigates to the corresponding deep-linked tab"
- - "/insights/genome-health displays genome markers grouped by clinical category with matched blood values and confidence badges"
- - "/insights/taste-identity displays LLM-generated theme cards with evidence lists and refresh button"
- - "/insights/cross-domain displays narrative text with refresh button and diff view showing changes"
- - "Each tab URL is deep-linkable — refreshing the page stays on the correct tab"
- - "Empty states show helpful messages with navigation links when data is missing"
- - "Insights nav entry appears in the sidebar in correct alphabetical position"
- - "Confidence badges are color-coded: green (strong), yellow (moderate), red (weak/significant)"
- artifacts:
- - path: "client/src/pages/Insights.jsx"
- provides: "Tabbed insights page with 4 sub-views"
- min_lines: 80
- - path: "client/src/components/insights/GenomeHealthTab.jsx"
- provides: "Genome-health correlation display grouped by category"
- min_lines: 80
- - path: "client/src/components/insights/TasteIdentityTab.jsx"
- provides: "Taste-identity theme cards with evidence lists"
- min_lines: 60
- - path: "client/src/components/insights/CrossDomainTab.jsx"
- provides: "Cross-domain narrative with diff display"
- min_lines: 60
- - path: "client/src/components/insights/InsightCard.jsx"
- provides: "Shared card component for insight display"
- min_lines: 20
- - path: "client/src/components/insights/ConfidenceBadge.jsx"
- provides: "Color-coded confidence badge component"
- min_lines: 15
- key_links:
- - from: "client/src/pages/Insights.jsx"
- to: "/api/insights/*"
- via: "api.js client functions"
- pattern: "getGenomeHealthCorrelations|getInsightThemes|getInsightNarrative"
- - from: "client/src/App.jsx"
- to: "client/src/pages/Insights.jsx"
- via: "Route path='insights/:tab'"
- pattern: "insights.*:tab"
- - from: "client/src/components/Layout.jsx"
- to: "/insights/overview"
- via: "nav entry with Lightbulb icon"
- pattern: "insights.*Lightbulb"
----
-
-<objective>
-Build the Insights dashboard UI: a tabbed page at `/insights/:tab` with four views — Overview (landing with domain summary cards), Genome-Health (category-grouped correlation cards), Taste-Identity (LLM theme cards), and Cross-Domain (narrative with diff display). Wire into App.jsx routes and Layout.jsx navigation.
-
-Purpose: Surface cross-domain insights in an accessible, deep-linkable UI. Users see genome-health correlations with confidence levels, taste-identity themes with evidence, and refreshable cross-domain narratives — all following established PortOS design patterns.
-
-Output: Insights page with 4 tab views, 4 shared components, route configuration, nav entry, react-diff-viewer-continued dependency.
-</objective>
-
-<execution_context>
-@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
-@/Users/antic/.claude/get-shit-done/templates/summary.md
-</execution_context>
-
-<context>
[email protected]/phases/04-cross-domain-insights-engine/04-01-SUMMARY.md
-
-<interfaces>
-<!-- API contract from Plan 01 -->
-
-From client/src/services/api.js (added in Plan 01):
-```javascript
-export const getGenomeHealthCorrelations = () => request('/insights/genome-health');
-// Returns: { available: true, categories: [...], totalMarkers, matchedMarkers, sources }
-// OR: { available: false, reason: 'no_genome' }
-// Category shape: { category, label, icon, color, markers: [...], notFoundCount }
-// Marker shape: { rsid, gene, name, status, description, implications, confidence: { level, color, label }, matchedBloodValues: [{ analyte, value, date, unit }], references }
-
-export const getInsightThemes = () => request('/insights/themes');
-// Returns: { themes: [...], generatedAt, model }
-// OR: { available: false, reason: 'not_generated' | 'no_taste_data' }
-// Theme shape: { title, narrative, evidence: [{ preference, domain, connection }], strength }
-
-export const refreshInsightThemes = (providerId, model) => request('/insights/themes/refresh', { method: 'POST', body: JSON.stringify({ providerId, model }) });
-// Returns: { themes: [...], generatedAt }
-
-export const getInsightNarrative = () => request('/insights/narrative');
-// Returns: { text, previousText, generatedAt, previousGeneratedAt, model }
-// OR: { available: false, reason: 'not_generated' }
-
-export const refreshInsightNarrative = (providerId, model) => request('/insights/narrative/refresh', { method: 'POST', body: JSON.stringify({ providerId, model }) });
-// Returns: { text, previousText, generatedAt, previousGeneratedAt, model }
-```
-
-From existing App.jsx route pattern (MeatSpace example):
-```jsx
-<Route path="meatspace" element={<Navigate to="/meatspace/overview" replace />} />
-<Route path="meatspace/:tab" element={<MeatSpace />} />
-```
-
-From existing Layout.jsx nav structure:
-```javascript
-// Current order after separator: AI Config, Apps, Brain, Chief of Staff, Dev Tools,
-// Digital Twin, Instances, MeatSpace, Security, Shell, Social Agents, Uploads
-// Insights goes after Instances, before MeatSpace (alphabetical)
-```
-
-Tailwind design tokens:
-```
-port-bg: #0f0f0f port-card: #1a1a1a
-port-border: #2a2a2a port-accent: #3b82f6
-port-success: #22c55e port-warning: #f59e0b
-port-error: #ef4444
-```
-</interfaces>
-</context>
-
-<tasks>
-
-<task type="auto">
- <name>Task 1: Install react-diff-viewer-continued, create shared insight components, and build all tab views</name>
- <files>
- client/package.json
- client/src/components/insights/ConfidenceBadge.jsx
- client/src/components/insights/ProvenancePanel.jsx
- client/src/components/insights/EmptyState.jsx
- client/src/components/insights/InsightCard.jsx
- client/src/components/insights/GenomeHealthTab.jsx
- client/src/components/insights/TasteIdentityTab.jsx
- client/src/components/insights/CrossDomainTab.jsx
- </files>
- <action>
-**0. Install dependency:**
-```bash
-cd client && npm install react-diff-viewer-continued
-```
-If `react-diff-viewer-continued` is not available on npm, fall back to hand-rolling a simple word-level diff using the `diff` npm package (`npm install diff`) — for 2-3 paragraph texts, a custom `<NarrativeDiff>` component using `diffWords()` from the `diff` package is sufficient.
-
-**1. `ConfidenceBadge.jsx`** — small presentational component:
-```jsx
-const BADGE_STYLES = {
- strong: 'bg-port-success/20 text-port-success border-port-success/30',
- moderate: 'bg-port-warning/20 text-port-warning border-port-warning/30',
- weak: 'bg-port-error/20 text-port-error border-port-error/30',
- significant: 'bg-port-error/30 text-port-error border-port-error/50',
- unknown: 'bg-gray-800 text-gray-400 border-gray-700'
-};
-```
-- Props: `{ level, label, sources }` — renders styled `<span>` with `title={sources?.join(', ')}`
-- Consistent across all insight types (genome-health and taste-identity)
-
-**2. `ProvenancePanel.jsx`** — collapsible provenance section:
-- Props: `{ references, expanded, onToggle }` — or use internal useState for expand/collapse
-- Default collapsed. Click to expand.
-- Renders list of references with study name, publication year, database source (ClinVar, PharmGKB, etc.)
-- If no references, renders nothing (return null)
-- Use ChevronDown/ChevronRight from lucide-react for expand indicator
-
-**3. `EmptyState.jsx`** — gentle empty state component:
-- Props: `{ message, linkTo, linkLabel }` (all optional except message)
-- Renders centered text in muted color with optional navigation Link
-- Examples: "No genome data uploaded yet" → link to `/meatspace/genome`; "No taste profile completed yet" → link to `/digital-twin/taste`
-- Use Lucide `Info` icon
-
-**4. `InsightCard.jsx`** — shared card shell:
-- Props: `{ title, subtitle, badge, children, sources, className }`
-- Card layout: `bg-port-card border border-port-border rounded-lg p-4`
-- Header row: title + badge (ConfidenceBadge). Subtitle below title.
-- `sources` rendered as inline tags: small pill-shaped spans showing "23andMe", "Apple Health", etc.
-- `children` for card body content
-
-**5. `GenomeHealthTab.jsx`** (INS-01, INS-03):
-- Fetch `getGenomeHealthCorrelations()` on mount (useEffect)
-- Loading state: skeleton cards (pulse animation placeholders)
-- If `!data.available` → render `<EmptyState message="No genome data uploaded yet" linkTo="/meatspace/genome" linkLabel="Upload Genome" />`
-- If available: render categories as collapsible sections
-- Each category section has:
- - Header: icon (from Lucide — map string icon names to Lucide components), category label, marker count, expand/collapse toggle
- - When expanded: grid of InsightCards for each marker
- - Each marker card shows: marker name as title, gene as subtitle, ConfidenceBadge with status-mapped level, description text, implications text (for the marker's status), matched blood values if any (analyte: value with date), collapsible ProvenancePanel for references
- - If `matchedBloodValues` is empty, show "No blood test on record" muted text with link to `/meatspace/blood`
- - Category header shows `notFoundCount` as "(N not in dataset)" note if > 0
-- Summary stats at top: total markers analyzed, matched with blood data count
-
-**6. `TasteIdentityTab.jsx`** (INS-02, INS-03):
-- Fetch `getInsightThemes()` on mount
-- If `!data?.available && data?.reason === 'not_generated'` → show EmptyState with "Generate" action description and explain what it does
-- If `data?.reason === 'no_taste_data'` → show EmptyState linking to `/digital-twin/taste`
-- If themes exist: show `generatedAt` timestamp, "Refresh" button (calls `refreshInsightThemes()`)
-- During refresh: button shows loading spinner, disable button
-- Staleness indicator: compare `generatedAt` against current time, show "Generated X ago" relative time
-- Theme cards layout: vertical stack or 2-column grid on lg screens
-- Each theme card (InsightCard): title = theme title, badge = ConfidenceBadge with strength mapped to level (strong→strong, moderate→moderate, tentative→weak), body = narrative paragraph
-- Below narrative: collapsible evidence list (similar to ProvenancePanel pattern). Each evidence item: `{preference}` from `{domain}` — `{connection}`
-- Tone: analytical, third-person as per CONTEXT.md decisions
-
-**7. `CrossDomainTab.jsx`** (INS-04, INS-03):
-- Fetch `getInsightNarrative()` on mount
-- If not generated → show EmptyState: "No cross-domain narrative generated yet. Click Refresh to analyze patterns across all your data."
-- If generated: show narrative text in a styled container (bg-port-card, prose-like typography)
-- Show `generatedAt` timestamp and model used
-- "Refresh" button: calls `refreshInsightNarrative()`, shows loading state
-- After refresh: if `previousText` exists and differs from `text`, show diff toggle
- - "Show changes" button toggles diff view on/off
- - Diff view uses `react-diff-viewer-continued` (or fallback diff component):
- - `oldValue={previousText}`, `newValue={text}`, `splitView={false}`, `useDarkTheme`, `hideLineNumbers`
- - If `previousText === text` (trimmed), show "No significant changes detected" instead of diff
-- Show `previousGeneratedAt` as "Previous analysis: {date}" when diff is shown
- </action>
- <verify>
- <automated>cd /Users/antic/github.com/atomantic/PortOS/client && ls src/components/insights/ConfidenceBadge.jsx src/components/insights/ProvenancePanel.jsx src/components/insights/EmptyState.jsx src/components/insights/InsightCard.jsx src/components/insights/GenomeHealthTab.jsx src/components/insights/TasteIdentityTab.jsx src/components/insights/CrossDomainTab.jsx && echo "All 7 component files exist"</automated>
- </verify>
- <done>7 insight component files created. ConfidenceBadge renders color-coded badges. GenomeHealthTab groups markers by clinical category with blood value matching. TasteIdentityTab shows theme cards with evidence lists and refresh. CrossDomainTab shows narrative with diff view. EmptyState handles missing data with navigation links.</done>
-</task>
-
-<task type="auto">
- <name>Task 2: Create Insights page, wire App.jsx routes and Layout.jsx navigation</name>
- <files>
- client/src/pages/Insights.jsx
- client/src/App.jsx
- client/src/components/Layout.jsx
- </files>
- <action>
-**1. Create `client/src/pages/Insights.jsx`:**
-- Import `useParams`, `useNavigate` from react-router-dom
-- Import tab components: GenomeHealthTab, TasteIdentityTab, CrossDomainTab
-- Import API functions: `getGenomeHealthCorrelations`, `getInsightThemes`, `getInsightNarrative`
-- Import Lucide icons: `Dna`, `Palette`, `Link2`, `Lightbulb`, `ArrowRight`
-
-Tab configuration:
-```javascript
-const TABS = [
- { id: 'overview', label: 'Overview', icon: Lightbulb },
- { id: 'genome-health', label: 'Genome-Health', icon: Dna },
- { id: 'taste-identity', label: 'Taste & Identity', icon: Palette },
- { id: 'cross-domain', label: 'Cross-Domain Patterns', icon: Link2 }
-];
-```
-
-Page structure:
-- Read `tab` from `useParams()`. Default to 'overview' if not in TABS.
-- Tab bar at top: horizontal list of tab buttons, active tab highlighted with `border-b-2 border-port-accent text-white`, inactive tabs `text-gray-400 hover:text-white`. Each tab is a button that calls `navigate(\`/insights/${tab.id}\`)`.
-- Below tab bar: render the appropriate component based on active tab ID.
-
-**Overview tab** (landing view, rendered inline in Insights.jsx):
-- Fetch summary data from all three endpoints on mount (parallel: `Promise.allSettled`)
-- 3 domain summary cards in a responsive grid (1 col mobile, 3 cols lg):
- - **Genome-Health**: key stat = `{matchedMarkers} markers analyzed`, top insight = highest-confidence finding or "Upload genome to get started", confidence indicator = ConfidenceBadge of top marker
- - **Taste & Identity**: key stat = `{themes.length} themes identified` or "Not yet generated", top insight = first theme title or prompt to complete taste profile
- - **Cross-Domain Patterns**: key stat = "Last analyzed {relativeTime}" or "Not yet generated", top insight = first sentence of narrative text
-- Each summary card: bg-port-card, border, rounded-lg, p-6, clickable → navigates to the detail tab
-- Source tags on each card: inline pills showing data sources
-- Show loading skeletons while fetching
-
-**2. Update `client/src/App.jsx`:**
-- Import `Insights` from `./pages/Insights`
-- Add routes (follow existing MeatSpace pattern):
-```jsx
-<Route path="insights" element={<Navigate to="/insights/overview" replace />} />
-<Route path="insights/:tab" element={<Insights />} />
-```
-Place alphabetically among existing routes (after `instances`, before `jira`).
-
-**3. Update `client/src/components/Layout.jsx`:**
-- Import `Lightbulb` icon from lucide-react (add to existing import destructure)
-- Add Insights nav entry after the `Instances` entry and before the `MeatSpace` entry (alphabetical order):
-```javascript
-{ to: '/insights/overview', label: 'Insights', icon: Lightbulb, single: true },
-```
-This keeps it as a single nav item (not expandable section) that links to the overview landing. Users navigate sub-tabs from within the page.
- </action>
- <verify>
- <automated>cd /Users/antic/github.com/atomantic/PortOS/client && npx vite build 2>&1 | tail -5</automated>
- </verify>
- <done>Insights.jsx page renders 4 tabs at /insights/:tab with deep-linked routes. Overview shows domain summary cards. App.jsx has route entries. Layout.jsx has Insights nav entry between Instances and MeatSpace. Client builds without errors.</done>
-</task>
-
-<task type="checkpoint:human-verify" gate="blocking">
- <name>Task 3: Verify Insights dashboard UI</name>
- <files>client/src/pages/Insights.jsx</files>
- <action>
-Human verification of the complete Insights dashboard. No automated changes — verify the UI built in Tasks 1-2:
-
-1. Navigate to http://localhost:5555/insights — should redirect to /insights/overview
-2. Overview tab: 3 domain summary cards should render (may show empty states if no data uploaded)
-3. Click "Genome-Health" tab or summary card — URL changes to /insights/genome-health
-4. If genome data exists: markers grouped by clinical category with confidence badges, collapsible provenance panels, matched blood values
-5. If no genome data: empty state with link to /meatspace/genome
-6. Click "Taste & Identity" tab — URL changes to /insights/taste-identity
-7. If taste profile completed: click Refresh to generate themes, verify theme cards appear with evidence lists
-8. Click "Cross-Domain Patterns" tab — URL changes to /insights/cross-domain
-9. Click Refresh to generate narrative, verify text appears with timestamp
-10. Click Refresh again — verify diff view shows changes between old and new narrative
-11. Refresh browser on any tab URL — should stay on correct tab (deep-linking works)
-12. Check sidebar: "Insights" nav item appears between "Instances" and "MeatSpace"
-13. Verify confidence badges: green (strong evidence), yellow (moderate), red (elevated/significant risk)
- </action>
- <verify>
- <automated>curl -s http://localhost:5555/insights/overview | grep -q "html" && echo "Page serves" || echo "Page not found"</automated>
- </verify>
- <done>All 4 insight tabs render correctly. Deep-linked URLs work. Empty states guide to data import. Confidence badges use correct color coding. Nav entry is alphabetically positioned. Diff view works on narrative refresh.</done>
-</task>
-
-</tasks>
-
-<verification>
-1. `npm run build` in client succeeds — no import errors, no missing dependencies
-2. All 4 tab routes work: /insights/overview, /insights/genome-health, /insights/taste-identity, /insights/cross-domain
-3. Each route is deep-linkable (direct URL access works)
-4. Empty states render correctly when data is missing
-5. Genome-health markers are grouped by clinical category with MARKER_CATEGORIES metadata
-6. Confidence badges are consistent across genome-health and taste-identity tabs
-7. Theme analysis generates and caches via LLM
-8. Narrative refresh preserves previous text and shows diff view
-9. Nav entry "Insights" appears in correct alphabetical position in sidebar
-</verification>
-
-<success_criteria>
-- /insights/:tab renders the correct sub-view for all 4 tab values
-- Overview shows 3 clickable domain summary cards
-- Genome-Health groups 117 markers by clinical category with collapsible sections
-- Each marker card shows confidence badge, description, implications, matched blood values
-- Taste-Identity shows LLM theme cards with title, narrative, evidence list, strength badge
-- Cross-Domain shows refreshable narrative with before/after diff view
-- Empty states guide users to relevant data import pages
-- Sidebar nav entry is alphabetically correct
-- All URLs are deep-linkable (no modal-only views)
-- No window.alert or window.confirm used (CLAUDE.md mandate)
-</success_criteria>
-
-<output>
-After completion, create `.planning/phases/04-cross-domain-insights-engine/04-02-SUMMARY.md`
-</output>
diff --git a/.planning/phases/04-cross-domain-insights-engine/04-02-SUMMARY.md b/.planning/phases/04-cross-domain-insights-engine/04-02-SUMMARY.md
deleted file mode 100644
index 7bdeb8079e..0000000000
--- a/.planning/phases/04-cross-domain-insights-engine/04-02-SUMMARY.md
+++ /dev/null
@@ -1,181 +0,0 @@
----
-phase: 04-cross-domain-insights-engine
-plan: 02
-subsystem: insights-ui
-tags: [insights, genome, taste-identity, cross-domain, react, ui, diff-viewer]
-dependency_graph:
- requires:
- - client/src/services/api.js (getGenomeHealthCorrelations, getInsightThemes, getInsightNarrative, refreshInsightThemes, refreshInsightNarrative)
- - /api/insights/* (5 endpoints from Plan 01)
- - client/src/pages/MeatSpace.jsx (structural pattern reference)
- - client/src/components/Layout.jsx (nav entry)
- - client/src/App.jsx (route configuration)
- provides:
- - client/src/pages/Insights.jsx
- - client/src/components/insights/ConfidenceBadge.jsx
- - client/src/components/insights/InsightCard.jsx
- - client/src/components/insights/ProvenancePanel.jsx
- - client/src/components/insights/EmptyState.jsx
- - client/src/components/insights/GenomeHealthTab.jsx
- - client/src/components/insights/TasteIdentityTab.jsx
- - client/src/components/insights/CrossDomainTab.jsx
- - /insights/:tab routes (4 deep-linked sub-views)
- affects:
- - client/src/App.jsx (2 new routes)
- - client/src/components/Layout.jsx (Insights nav entry, isFullWidth)
- - client/package.json (react-diff-viewer-continued dependency)
- - .changelog/v1.14.x.md
-tech_stack:
- added:
- - react-diff-viewer-continued (narrative before/after diff display)
- patterns:
- - Tabbed page at /:page/:tab with useParams for deep-linked URLs
- - Promise.allSettled for parallel multi-domain data fetching in Overview
- - Cache-first API with { available: false, reason } graceful degradation
- - Collapsible sections pattern (CategorySection, ProvenancePanel, EvidenceList)
- - MeatSpace structural pattern replicated for Insights (header + tab bar + scrollable content)
-key_files:
- created:
- - client/src/pages/Insights.jsx
- - client/src/components/insights/ConfidenceBadge.jsx
- - client/src/components/insights/InsightCard.jsx
- - client/src/components/insights/ProvenancePanel.jsx
- - client/src/components/insights/EmptyState.jsx
- - client/src/components/insights/GenomeHealthTab.jsx
- - client/src/components/insights/TasteIdentityTab.jsx
- - client/src/components/insights/CrossDomainTab.jsx
- modified:
- - client/src/App.jsx
- - client/src/components/Layout.jsx
- - client/package.json
- - .changelog/v1.14.x.md
-decisions:
- - Insights nav entry placed as single item (not expandable) — sub-tabs navigate from within the page
- - /insights added to isFullWidth paths in Layout.jsx to match MeatSpace full-height rendering pattern
- - STRENGTH_TO_LEVEL maps tentative->weak, moderate->moderate, strong->strong for ConfidenceBadge consistency
- - Overview tab uses Promise.allSettled so any single domain failure does not block the other cards
- - CrossDomainTab diff view only appears after a refresh has been triggered and previousText differs from text (trimmed)
- - Summary cards use navigate() (not Link) so the entire card area is clickable without nested link issues
-metrics:
- duration: 238s
- completed: 2026-02-26
- tasks_completed: 3
- files_created: 8
- files_modified: 4
----
-
-# Phase 4 Plan 2: Insights Dashboard UI Summary
-
-**One-liner:** Tabbed Insights dashboard at `/insights/:tab` with genome-health correlation cards, LLM taste-identity theme cards, and cross-domain narrative with ReactDiffViewer diff toggle — all deep-linked and following established PortOS design patterns.
-
-## What Was Built
-
-### Dependency Added
-
-`react-diff-viewer-continued` installed in `client/package.json` for the narrative before/after diff display in CrossDomainTab.
-
-### Shared Components (`client/src/components/insights/`)
-
-**`ConfidenceBadge.jsx`** — Presentational badge with 5 confidence levels:
-- `strong` → green (`port-success`)
-- `moderate` → yellow (`port-warning`)
-- `weak` → red (`port-error`)
-- `significant` → deeper red
-- `unknown` → gray
-
-**`InsightCard.jsx`** — Shared card shell with `bg-port-card border border-port-border rounded-lg p-4` layout, header row with title + badge, subtitle, inline source pills, and `children` slot.
-
-**`ProvenancePanel.jsx`** — Collapsed by default. Click ChevronRight/Down to expand. Renders reference list with study name, publication year, database source badge.
-
-**`EmptyState.jsx`** — Centered Info icon + message + optional NavLink button. Guides users to relevant data import pages.
-
-### Tab Components
-
-**`GenomeHealthTab.jsx`** (INS-01, INS-03):
-- Fetches `getGenomeHealthCorrelations()` on mount
-- Loading: skeleton cards with pulse animation
-- Empty state: links to `/meatspace/genome` for upload
-- Available: summary stats bar + collapsible CategorySection components
-- Each category section: icon, label, marker count, expand/collapse toggle
-- Each marker card: name + gene subtitle, confidence badge mapped from marker status, description, implications, matched blood values or "No blood test on record" link, collapsible ProvenancePanel
-
-**`TasteIdentityTab.jsx`** (INS-02, INS-03):
-- Fetches `getInsightThemes()` on mount
-- Empty state `no_taste_data` → links to `/digital-twin/taste`
-- Empty state `not_generated` → explanation + Generate Themes button
-- Available: header bar with theme count, relative time, model, Refresh button
-- Theme cards in 2-column grid on lg screens with EvidenceList (collapsible)
-
-**`CrossDomainTab.jsx`** (INS-04, INS-03):
-- Fetches `getInsightNarrative()` on mount
-- Not generated → explanation + Generate Narrative button
-- Available: narrative text rendered paragraph-by-paragraph, generatedAt relative time, model badge
-- Refresh button: calls `refreshInsightNarrative()`, shows loading spinner
-- After refresh: "Show changes" button appears if `previousText` differs from `text` (trimmed comparison)
-- Diff view: ReactDiffViewer with `splitView=false, useDarkTheme, hideLineNumbers` and port-* color overrides
-
-### Page: `client/src/pages/Insights.jsx`
-
-Four-tab page with `TABS` config array and `VALID_TAB_IDS` Set for safe param validation.
-
-**Overview tab** (inline in Insights.jsx):
-- Parallel fetches via `Promise.allSettled` — 3 domains load independently
-- 3 clickable domain summary cards in responsive grid (1 col mobile, 3 cols lg)
-- Each card: icon, label, ArrowRight (highlights on hover), key stat, top insight text, confidence badge, source tags
-- Card content degrades gracefully when data unavailable
-
-**Routing** (`client/src/App.jsx`):
-```jsx
-<Route path="insights" element={<Navigate to="/insights/overview" replace />} />
-<Route path="insights/:tab" element={<Insights />} />
-```
-Inserted alphabetically between `instances` and `meatspace`.
-
-**Navigation** (`client/src/components/Layout.jsx`):
-```javascript
-{ to: '/insights/overview', label: 'Insights', icon: Lightbulb, single: true }
-```
-Positioned between Instances and MeatSpace (alphabetical).
-`/insights` added to `isFullWidth` check for full-height layout rendering.
-
-## Verification Results
-
-- Vite build: success (✓ 3388 modules transformed, 4.42s)
-- All 7 component files: FOUND
-- Insights.jsx: FOUND
-- commits 832c561 and 4cd9ee9: FOUND
-
-## Commits
-
-| Task | Hash | Description |
-|------|------|-------------|
-| Task 1 | 832c561 | feat(04-02): install react-diff-viewer-continued and create shared insight components and tab views |
-| Task 2 | 4cd9ee9 | feat(04-02): create Insights page with 4 tabs, wire App.jsx routes and Layout.jsx navigation |
-
-## Deviations from Plan
-
-### Auto-added Missing Feature
-
-**[Rule 2 - Missing functionality] Added /insights to isFullWidth in Layout.jsx**
-- **Found during:** Task 2
-- **Issue:** Without adding `/insights` to the `isFullWidth` path check, the Insights page would have rendered in the constrained `max-w-7xl` wrapper with padding, not the full-height flex layout matching MeatSpace (which is the referenced structural pattern)
-- **Fix:** Added `location.pathname.startsWith('/insights')` to the isFullWidth check
-- **Files modified:** `client/src/components/Layout.jsx`
-- **Commit:** 4cd9ee9
-
-## Self-Check: PASSED
-
-- client/src/components/insights/ConfidenceBadge.jsx: FOUND
-- client/src/components/insights/ProvenancePanel.jsx: FOUND
-- client/src/components/insights/EmptyState.jsx: FOUND
-- client/src/components/insights/InsightCard.jsx: FOUND
-- client/src/components/insights/GenomeHealthTab.jsx: FOUND
-- client/src/components/insights/TasteIdentityTab.jsx: FOUND
-- client/src/components/insights/CrossDomainTab.jsx: FOUND
-- client/src/pages/Insights.jsx: FOUND
-- commit 832c561: FOUND
-- commit 4cd9ee9: FOUND
-
-## Status
-
-All 3 tasks complete. Tasks 1-2 committed. Task 3 (human-verify checkpoint) approved by user — all 4 insight tabs verified to render correctly with proper empty states, confidence badge color coding, and alphabetical sidebar nav positioning. Plan 04-02 fully complete.
diff --git a/.planning/phases/04-cross-domain-insights-engine/04-CONTEXT.md b/.planning/phases/04-cross-domain-insights-engine/04-CONTEXT.md
deleted file mode 100644
index 0fb73e0884..0000000000
--- a/.planning/phases/04-cross-domain-insights-engine/04-CONTEXT.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# Phase 4: Cross-Domain Insights Engine - Context
-
-**Gathered:** 2026-02-26
-**Status:** Ready for planning
-
-<domain>
-## Phase Boundary
-
-PortOS surfaces actionable cross-domain patterns by correlating genome markers with health data and taste preferences with identity themes. This phase builds the insights engine and dashboard — it does NOT add new data import capabilities or modify existing genome/health pipelines from prior phases.
-
-</domain>
-
-<decisions>
-## Implementation Decisions
-
-### Correlation Display
-- Card-based layout grouped by health domain (Cardiovascular, Metabolism, Pharmacogenomics, Cancer Risk, Nutrigenomics, etc.)
-- Each card shows: genome variant + actual health value + correlation strength
-- Color-coded confidence badges: green (strong evidence), yellow (moderate), red (weak/preliminary) — hover for study source details
-- Expandable provenance section per card (collapsed by default): study name, publication year, database source (ClinVar, PharmGKB, etc.)
-- 117 curated markers grouped by clinical category into card groups
-
-### Taste-Identity Themes
-- Theme cards with narrative: title (e.g., "Comfort-Seeking Explorer"), short narrative paragraph, list of supporting preferences
-- All available preference data feeds the analysis (music, food, aesthetics, media, travel, etc.) — LLM finds patterns across whatever's available
-- Supporting evidence list under each theme card (collapsible): which preferences contributed and why they map to this theme
-- Analytical and neutral tone — third-person, research-flavored: "The data indicates a pattern of..."
-
-### Insights Dashboard
-- Tabbed by domain: Genome-Health, Taste-Identity, Cross-Domain Patterns — deep-linkable routes (/insights/genome-health, etc.)
-- Landing view shows domain summary cards: key stat, top insight, confidence indicator per domain — click to enter domain tab
-- Inline source tags on each card/insight: "23andMe", "Apple Health", "Spotify", etc.
-- Gentle empty states for domains with no data: "No health data imported yet" with link to relevant import
-
-### Narrative Summaries
-- 2-3 paragraph summaries of cross-domain patterns — concise but substantive, readable in under a minute
-- Refresh button with diff: re-analysis shows what changed since last generation (new patterns, confidence changes)
-- Analytical with personal framing tone: neutral, evidence-based but framed around "your data shows..."
-- Cross-domain narratives live in the dedicated Cross-Domain Patterns tab
-
-### Claude's Discretion
-- Exact card dimensions, spacing, and responsive breakpoints
-- LLM prompt engineering for theme analysis and narrative generation
-- Caching strategy for LLM-generated content
-- Loading states and skeleton designs during LLM processing
-- How to handle edge cases where genome and health data have no meaningful correlation
-
-</decisions>
-
-<specifics>
-## Specific Ideas
-
-- Confidence badges should be consistent across all insight types (genome-health and taste-identity)
-- The diff on narrative refresh should highlight what's new, not just replace content — user should see how their insights evolve as more data comes in
-- Provenance is non-negotiable: every genome-to-health claim must trace back to a specific study or database
-
-</specifics>
-
-<deferred>
-## Deferred Ideas
-
-None — discussion stayed within phase scope
-
-</deferred>
-
----
-
-*Phase: 04-cross-domain-insights-engine*
-*Context gathered: 2026-02-26*
diff --git a/.planning/phases/04-cross-domain-insights-engine/04-RESEARCH.md b/.planning/phases/04-cross-domain-insights-engine/04-RESEARCH.md
deleted file mode 100644
index 41da344272..0000000000
--- a/.planning/phases/04-cross-domain-insights-engine/04-RESEARCH.md
+++ /dev/null
@@ -1,604 +0,0 @@
-# Phase 4: Cross-Domain Insights Engine - Research
-
-**Researched:** 2026-02-26
-**Domain:** LLM-driven analytics UI — genome-health correlation display, taste-to-identity theme analysis, insights dashboard with tabbed deep-linked routing
-**Confidence:** HIGH (codebase patterns verified; LLM prompt strategy MEDIUM; diff display LOW — library selection open)
-
----
-
-<user_constraints>
-## User Constraints (from CONTEXT.md)
-
-### Locked Decisions
-
-**Correlation Display**
-- Card-based layout grouped by health domain (Cardiovascular, Metabolism, Pharmacogenomics, Cancer Risk, Nutrigenomics, etc.)
-- Each card shows: genome variant + actual health value + correlation strength
-- Color-coded confidence badges: green (strong evidence), yellow (moderate), red (weak/preliminary) — hover for study source details
-- Expandable provenance section per card (collapsed by default): study name, publication year, database source (ClinVar, PharmGKB, etc.)
-- 117 curated markers grouped by clinical category into card groups
-
-**Taste-Identity Themes**
-- Theme cards with narrative: title (e.g., "Comfort-Seeking Explorer"), short narrative paragraph, list of supporting preferences
-- All available preference data feeds the analysis (music, food, aesthetics, media, travel, etc.) — LLM finds patterns across whatever's available
-- Supporting evidence list under each theme card (collapsible): which preferences contributed and why they map to this theme
-- Analytical and neutral tone — third-person, research-flavored: "The data indicates a pattern of..."
-
-**Insights Dashboard**
-- Tabbed by domain: Genome-Health, Taste-Identity, Cross-Domain Patterns — deep-linkable routes (/insights/genome-health, etc.)
-- Landing view shows domain summary cards: key stat, top insight, confidence indicator per domain — click to enter domain tab
-- Inline source tags on each card/insight: "23andMe", "Apple Health", "Spotify", etc.
-- Gentle empty states for domains with no data: "No health data imported yet" with link to relevant import
-
-**Narrative Summaries**
-- 2-3 paragraph summaries of cross-domain patterns — concise but substantive, readable in under a minute
-- Refresh button with diff: re-analysis shows what changed since last generation (new patterns, confidence changes)
-- Analytical with personal framing tone: neutral, evidence-based but framed around "your data shows..."
-- Cross-domain narratives live in the dedicated Cross-Domain Patterns tab
-
-### Claude's Discretion
-- Exact card dimensions, spacing, and responsive breakpoints
-- LLM prompt engineering for theme analysis and narrative generation
-- Caching strategy for LLM-generated content
-- Loading states and skeleton designs during LLM processing
-- How to handle edge cases where genome and health data have no meaningful correlation
-
-### Deferred Ideas (OUT OF SCOPE)
-None — discussion stayed within phase scope
-</user_constraints>
-
----
-
-<phase_requirements>
-## Phase Requirements
-
-| ID | Description | Research Support |
-|----|-------------|-----------------|
-| INS-01 | Rule-based genome-to-health correlations using curated 117 markers against actual blood/body data | `scanCuratedMarkers()` in `genome.js` already classifies all 117 markers with status+category; `getBloodTests()` in `meatspaceHealth.js` returns blood test history; mapping logic is server-side pure function work |
-| INS-02 | LLM-generated taste-to-identity theme analysis connecting preferences to preference identity patterns | `getTasteProfile()` from `taste-questionnaire.js` returns section summaries and responses; `callProviderAISimple()` pattern in same service is the established LLM call pattern; needs new `insightsService.js` with `generateThemeAnalysis()` |
-| INS-03 | Insights dashboard UI with confidence levels, source attribution, and domain grouping | New `/insights` route + `Insights.jsx` page + three sub-components; follows MeatSpace/:tab and DigitalTwin/:tab pattern (useParams, useNavigate, deep-linked routes); sidebar nav entry added to Layout.jsx |
-| INS-04 | LLM narrative summaries of cross-domain patterns refreshable on demand | New `generateCrossDomainNarrative()` in insightsService; persisted to `data/insights/narrative.json` with `generatedAt` timestamp; diff display compares current vs previous narrative text |
-</phase_requirements>
-
----
-
-## Summary
-
-Phase 4 builds an Insights Engine that surfaces two classes of analysis: (1) rule-based genome-health correlations that match the 117 curated SNP markers already classified by `scanCuratedMarkers()` against the blood/body data already persisted by `meatspaceHealth.js`, and (2) LLM-generated taste-to-identity theme analysis that reads the completed taste profile sections and produces personality theme cards. Both classes feed a new `/insights` dashboard that follows established PortOS routing and component conventions exactly.
-
-The entire data layer for this phase is already in place. Genome markers are classified with `status` (beneficial/typical/concern/major_concern), `category`, `gene`, `description`, and `implications`. Blood tests are stored in `data/meatspace/blood-tests.json` with `date`, test name, and value. Apple Health data is queryable by metric and date range. The insights engine is fundamentally a correlation + formatting layer on top of these existing data sources — no new data pipelines are needed.
-
-LLM work in this phase (INS-02, INS-04) follows the established `callProviderAISimple()` pattern from `taste-questionnaire.js` and `digital-twin.js`: get active provider, call `/chat/completions` directly with a structured prompt, store result in a JSON file under `data/insights/`. Caching is file-based with a `generatedAt` timestamp — the UI shows when last generated and provides a Refresh button.
-
-**Primary recommendation:** Build the phase as two parallel workstreams — (A) backend service `insightsService.js` with four functions: `getGenomeHealthCorrelations()`, `generateThemeAnalysis()`, `getCrossDomainNarrative()`, `refreshCrossDomainNarrative()`; and (B) frontend `Insights.jsx` page with three sub-tabs following the MeatSpace/:tab pattern. The genome-health correlation function requires no LLM — it is pure rule matching.
-
----
-
-## Standard Stack
-
-### Core
-
-| Library | Version | Purpose | Why Standard |
-|---------|---------|---------|--------------|
-| Express.js Router | (project: ^4.21.2) | `/api/insights` route module | All PortOS routes follow this pattern |
-| Zod | (project: ^3.24.1) | Route input validation via `lib/validation.js` | CLAUDE.md mandate: Zod validation on all route inputs |
-| React Router v6 | (project version) | `/insights/:tab` deep-linked tabs | CLAUDE.md mandate: linkable routes, not local state |
-| Tailwind CSS | (project version) | Card layout, badges, spacing | Project design token system |
-| Lucide React | (project version) | Icons in cards and tabs | Established icon library across all components |
-
-### Supporting
-
-| Library | Version | Purpose | When to Use |
-|---------|---------|---------|-------------|
-| `diff` (npm) | ^7.0.0 | Text diff for narrative comparison before/after refresh | When rendering the narrative diff view |
-| `react-diff-viewer` | ^3.1.1 | React component for before/after text diff display | Narrative diff display; lightweight, no heavy deps |
-
-### Alternatives Considered
-
-| Instead of | Could Use | Tradeoff |
-|------------|-----------|----------|
-| `react-diff-viewer` | `@hackler/react-diff-viewer` | Actively maintained fork but adds complexity — standard package is sufficient for 2-3 paragraph diffs |
-| File-based cache (`data/insights/`) | In-memory cache | In-memory is lost on restart; file-based is consistent with ALL other PortOS data storage |
-| `callProviderAISimple()` inline | `buildPrompt()` stage templates | Stage templates are great for multi-stage pipelines; single-shot narrative generation does not need the overhead |
-
-**Installation (new deps only):**
-```bash
-cd client && npm install react-diff-viewer
-```
-
-The `diff` package may already be a transitive dependency — verify with `npm ls diff` before installing separately. No new server-side npm packages needed.
-
----
-
-## Architecture Patterns
-
-### Recommended Project Structure
-
-```
-server/
-├── routes/insights.js # GET /api/insights/genome-health
-│ # GET /api/insights/themes
-│ # GET /api/insights/narrative
-│ # POST /api/insights/narrative/refresh
-│
-├── services/insightsService.js # Four functions: correlations, themes, narrative, refresh
-│
-data/
-└── insights/
- ├── themes.json # { themes: [...], generatedAt, model }
- └── narrative.json # { text: "...", previousText: "...", generatedAt, model }
-
-client/src/
-├── pages/Insights.jsx # Route: /insights/:tab — three tabs
-├── components/insights/
-│ ├── GenomeHealthTab.jsx # INS-01: card groups by clinical domain
-│ ├── TasteIdentityTab.jsx # INS-02: theme cards + evidence lists
-│ └── CrossDomainTab.jsx # INS-04: narrative + diff display
-│ └── InsightCard.jsx # Shared card shell with confidence badge
-│ └── ConfidenceBadge.jsx # Green/yellow/red badge with hover tooltip
-│ └── ProvenancePanel.jsx # Collapsible provenance section
-│ └── EmptyState.jsx # Gentle empty state with navigation link
-```
-
-### Pattern 1: Genome-Health Correlation (Pure Rule-Based, No LLM)
-
-**What:** Match each saved genome marker's `status` and `category` to corresponding blood test values. Produce correlation objects with strength indicator.
-
-**When to use:** INS-01. No LLM call needed — this is deterministic mapping.
-
-**Data sources that already exist:**
-- Genome: `genomeService.getGenomeSummary()` returns `savedMarkers` (object keyed by UUID) — each marker has `rsid`, `gene`, `category`, `status`, `name`, `description`, `implications`, `references`
-- Blood tests: `meatspaceHealth.getBloodTests()` returns `{ tests: [], referenceRanges: {} }` — each test has `date`, and test-specific fields
-- Body composition: `meatspaceHealth.getBodyHistory()` returns daily entries with weight/body fat
-
-**Mapping approach:** The `MARKER_CATEGORIES` in `curatedGenomeMarkers.js` already defines clinical groupings (cardiovascular, iron, methylation, nutrient, pharmacogenomics, etc.). Map each marker category to its corresponding blood panel analyte.
-
-**Example correlation mapping (implemented in `insightsService.js`):**
-```javascript
-// Source: codebase analysis of curatedGenomeMarkers.js + meatspaceHealth.js
-
-// Category-to-blood-analyte mapping (partial examples)
-const CATEGORY_BLOOD_MAP = {
- cardiovascular: ['total_cholesterol', 'ldl', 'hdl', 'triglycerides', 'homocysteine'],
- iron: ['ferritin', 'serum_iron', 'transferrin_saturation', 'tibc'],
- methylation: ['homocysteine', 'b12', 'folate'],
- diabetes: ['fasting_glucose', 'hba1c', 'insulin'],
- thyroid: ['tsh', 't3', 't4'],
- nutrient: ['vitamin_d', 'b12', 'folate', 'magnesium', 'zinc']
-};
-
-export async function getGenomeHealthCorrelations() {
- const [summary, bloodData] = await Promise.all([
- genomeService.getGenomeSummary(),
- meatspaceHealth.getBloodTests()
- ]);
-
- if (!summary.uploaded) return { available: false, reason: 'no_genome' };
-
- const markers = Object.values(summary.savedMarkers || {});
- const latestBlood = getLatestBloodValues(bloodData.tests); // map analyte → latest value
-
- return groupMarkersByCategory(markers, latestBlood, CATEGORY_BLOOD_MAP);
-}
-```
-
-**Confidence badge mapping from marker status:**
-```javascript
-const CONFIDENCE_FROM_STATUS = {
- beneficial: { level: 'strong', color: 'green', label: 'Strong Evidence' },
- typical: { level: 'moderate', color: 'yellow', label: 'Moderate Evidence' },
- concern: { level: 'weak', color: 'red', label: 'Elevated Risk Marker' },
- major_concern: { level: 'significant', color: 'red', label: 'Significant Risk Marker' },
- not_found: { level: 'unknown', color: 'gray', label: 'Not in Dataset' }
-};
-```
-
-### Pattern 2: LLM Taste-to-Identity Theme Analysis
-
-**What:** Pass all taste profile section summaries to the LLM, request structured theme cards with title, narrative paragraph, and supporting evidence list.
-
-**When to use:** INS-02. Only runs when taste sections have completed summaries.
-
-**Established LLM call pattern (from `taste-questionnaire.js` lines 636-688):**
-```javascript
-// Source: server/services/taste-questionnaire.js generateSectionSummary()
-
-export async function generateThemeAnalysis(providerId, model) {
- const tasteProfile = await tasteQuestionnaireService.getTasteProfile();
- const sections = tasteProfile.sections.filter(s => s.summary);
-
- if (sections.length === 0) {
- return { available: false, reason: 'no_taste_data' };
- }
-
- const provider = providerId
- ? await getProviderById(providerId)
- : await getActiveProvider();
- if (!provider) throw new Error('No AI provider available');
-
- const modelId = model || provider.defaultModel;
-
- // Build context from all completed section summaries
- const profileContext = sections
- .map(s => `## ${s.label}\n${s.summary}`)
- .join('\n\n');
-
- const prompt = `Analyze the following taste and aesthetic preference profiles and identify 3-5 distinct identity themes that emerge from the patterns across all domains.
-
-## Preference Data
-${profileContext}
-
-## Output Requirements
-
-Respond with a JSON array. Each theme object must have:
-- "title": string — a concise evocative label (e.g., "Comfort-Seeking Explorer", "Analytical Aesthete")
-- "narrative": string — 2-3 sentences, analytical third-person tone: "The data indicates a pattern of..."
-- "evidence": array of objects: { "preference": string, "domain": string, "connection": string }
-- "strength": "strong" | "moderate" | "tentative"
-
-Return ONLY the JSON array, no markdown wrapping.`;
-
- const result = await callProviderAISimple(provider, modelId, prompt, {
- temperature: 0.4,
- max_tokens: 2000
- });
-
- if (result.error) throw new Error(`Theme analysis failed: ${result.error}`);
-
- const themes = JSON.parse(result.text.trim());
-
- // Persist to data/insights/themes.json
- await writeFile(
- join(PATHS.data, 'insights/themes.json'),
- JSON.stringify({ themes, generatedAt: new Date().toISOString(), model: modelId }, null, 2)
- );
-
- console.log(`🧠 Taste-identity themes generated: ${themes.length} themes`);
- return { themes, generatedAt: new Date().toISOString() };
-}
-```
-
-### Pattern 3: Cross-Domain Narrative with Diff
-
-**What:** Generate 2-3 paragraph narrative. On refresh, store previous text, generate new text, return both so client can diff.
-
-**Storage schema (`data/insights/narrative.json`):**
-```json
-{
- "text": "Your data indicates a distinctive...",
- "previousText": "...",
- "generatedAt": "2026-02-26T12:00:00Z",
- "previousGeneratedAt": "2026-02-10T08:00:00Z",
- "model": "claude-3-5-sonnet"
-}
-```
-
-**Refresh endpoint pattern:**
-```javascript
-// POST /api/insights/narrative/refresh
-router.post('/narrative/refresh', asyncHandler(async (req, res) => {
- const result = await insightsService.refreshCrossDomainNarrative();
- res.json(result);
-}));
-```
-
-### Pattern 4: Tabbed Page Component (matches existing MeatSpace/:tab pattern)
-
-**What:** New `Insights.jsx` page using `useParams`/`useNavigate` with three deep-linkable tabs.
-
-**Route structure (`App.jsx` additions):**
-```jsx
-// Source: client/src/App.jsx existing MeatSpace pattern
-<Route path="insights" element={<Navigate to="/insights/overview" replace />} />
-<Route path="insights/:tab" element={<Insights />} />
-```
-
-**Tab IDs and routes:**
-- `/insights/overview` — landing with domain summary cards
-- `/insights/genome-health` — INS-01 genome-health correlations
-- `/insights/taste-identity` — INS-02 theme cards
-- `/insights/cross-domain` — INS-04 narrative + diff
-
-**Sidebar nav entry (`Layout.jsx` — alphabetically ordered in top-level nav):**
-```jsx
-// Alphabetically: Insights comes after Instances, before MeatSpace
-{ to: '/insights/overview', label: 'Insights', icon: Lightbulb, single: true }
-// OR as expandable section if sub-navigation desired:
-{
- label: 'Insights',
- icon: Lightbulb,
- children: [
- { to: '/insights/cross-domain', label: 'Cross-Domain', icon: Link2 },
- { to: '/insights/genome-health', label: 'Genome-Health', icon: Dna },
- { to: '/insights/overview', label: 'Overview', icon: LayoutDashboard },
- { to: '/insights/taste-identity', label: 'Taste & Identity', icon: Palette }
- ]
-}
-```
-
-### Anti-Patterns to Avoid
-
-- **Calling LLM on every page load:** LLM results are expensive. Cache in `data/insights/*.json`. Return cached results immediately; refresh only on explicit user action.
-- **Rendering all 117 marker cards flat:** Group by `category` using `MARKER_CATEGORIES` from `curatedGenomeMarkers.js`. Each category becomes a collapsible section or tab within the Genome-Health view.
-- **Modal without URL for tabs:** CLAUDE.md prohibits this. All three Insights tabs MUST be URL-parameterized routes.
-- **Using `window.alert` for errors:** CLAUDE.md prohibition. Use existing toast notification pattern via `useErrorNotifications` hook.
-- **Hardcoding localhost in fetch calls:** CLAUDE.md prohibition. All API calls go through `client/src/services/api.js` `request()` helper which uses `window.location.hostname`.
-- **Claiming causation from genome markers:** REQUIREMENTS.md out-of-scope note: "Insights show correlations with confidence, never claim causation."
-
----
-
-## Don't Hand-Roll
-
-| Problem | Don't Build | Use Instead | Why |
-|---------|-------------|-------------|-----|
-| Text diff display | Custom before/after diff renderer | `react-diff-viewer` npm package | Handles word-level diff, highlight, split/unified modes — complex to replicate correctly |
-| LLM provider routing | New provider call mechanism | `callProviderAISimple()` pattern from `taste-questionnaire.js` | Already handles API key headers, timeout, abort controller, error extraction |
-| SNP status classification | Re-implement marker logic | `classifyGenotype()` + `CURATED_MARKERS` from `curatedGenomeMarkers.js` | Already handles 117 markers with all rules — data is in `meta.savedMarkers` post-scan |
-| Blood test data access | New DB or parsing | `getBloodTests()` from `meatspaceHealth.js` | Already returns structured blood test history |
-| Apple Health data access | New file scanning | `getDailyAggregates()` / `getCorrelationData()` from `appleHealthQuery.js` | Already handles day-partitioned health files |
-| Route validation | Manual validation | Zod + `validateRequest()` from `lib/validation.js` | CLAUDE.md mandate |
-| Toast notifications | Custom error UI | `useErrorNotifications` hook + centralized error middleware | Errors bubble to middleware per CLAUDE.md convention |
-
-**Key insight:** The genome and health data layers are complete. Phase 4 is a presentation and analysis layer, not a data layer. The most complex work is the blood-test-to-genome-category mapping table and the LLM prompt engineering for themes.
-
----
-
-## Common Pitfalls
-
-### Pitfall 1: Empty Blood Data Breaking Correlation Display
-**What goes wrong:** User has genome data but no blood tests yet. Correlation cards try to show "Actual value: N/A" but the absence breaks the card layout or renders cryptically.
-**Why it happens:** `getBloodTests()` returns `{ tests: [], referenceRanges: {} }` when no tests exist. Code that tries to find the latest value will return `undefined`.
-**How to avoid:** Implement `getLatestBloodValues()` that returns an empty Map when no tests exist. Cards for markers with no matching blood data show "No blood test on record" with a link to `/meatspace/blood`. Use the `EmptyState` component pattern.
-**Warning signs:** `undefined` showing in rendered card values during development.
-
-### Pitfall 2: LLM JSON Parse Failure for Theme Analysis
-**What goes wrong:** LLM returns markdown-wrapped JSON (```json ... ```) despite the prompt saying "Return ONLY the JSON array." This breaks `JSON.parse()`.
-**Why it happens:** Many LLMs include code fencing even when instructed not to. The `callProviderAISimple()` pattern has no JSON extraction step.
-**How to avoid:** Strip markdown code fences before parsing:
-```javascript
-const raw = result.text.trim();
-const cleaned = raw.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '');
-const themes = JSON.parse(cleaned);
-```
-**Warning signs:** `SyntaxError: Unexpected token` in server logs when themes generate.
-
-### Pitfall 3: Treating "not_found" Markers as Meaningful Correlations
-**What goes wrong:** Many markers will have `status: 'not_found'` if the genome file doesn't include those rsids. Showing these as correlation cards produces noise.
-**Why it happens:** `scanCuratedMarkers()` returns all 117 markers, including those not in the dataset.
-**How to avoid:** Filter `savedMarkers` to exclude `status === 'not_found'` before grouping into correlation cards. Show a category-level "N markers not found in your dataset" count instead.
-**Warning signs:** Cards showing "Not in Dataset" outnumber informative cards.
-
-### Pitfall 4: Stale Theme Data Displayed as Current
-**What goes wrong:** User adds more taste profile sections after themes were generated. The cached `themes.json` reflects old data but shows no indication it's stale.
-**Why it happens:** File-based cache has no invalidation signal.
-**How to avoid:** Compare `themes.json` `generatedAt` against `tasteProfile.updatedAt`. If `updatedAt` is newer, show a "Data updated since last analysis — refresh to regenerate" notice above the theme cards.
-**Warning signs:** User reports theme cards don't reflect recent questionnaire answers.
-
-### Pitfall 5: Diff Display for Identical Narratives Confusing Users
-**What goes wrong:** User refreshes narrative when no meaningful new data has arrived. Diff shows no changes, which looks like a failure.
-**Why it happens:** LLM narrative text changes slightly on every generation even with same input (temperature > 0). Or no new data means nearly identical output.
-**How to avoid:** If `previousText` equals `text` after trimming, show "No significant changes detected" instead of a diff view. Also show `generatedAt` timestamp prominently so users understand recency.
-**Warning signs:** Empty diff being reported as an error.
-
-### Pitfall 6: Nav Entry Alphabetical Order in Layout.jsx
-**What goes wrong:** Insights nav entry added at the bottom or out of alphabetical order, violating CLAUDE.md alphabetical nav mandate.
-**Why it happens:** Developer appends to the nav array without checking order.
-**How to avoid:** Check CLAUDE.md: "sidebar nav items in Layout.jsx are alphabetically ordered after the Dashboard+CyberCity top section and separator." Current order: CoS → Dev Tools → Digital Twin → Instances → **Insights** → MeatSpace → Security → Shell → Social Agents → Uploads.
-**Warning signs:** PR review catching the ordering issue.
-
----
-
-## Code Examples
-
-Verified patterns from existing codebase:
-
-### Loading Taste Profile Data (existing API)
-```javascript
-// Source: server/services/taste-questionnaire.js getTasteProfile()
-// Returns: { sections: [{ id, label, status, summary, progress }], completedCount, profileSummary }
-const tasteProfile = await getTasteProfile();
-const completedSections = tasteProfile.sections.filter(s => s.summary);
-```
-
-### Accessing All Saved Genome Markers (existing API)
-```javascript
-// Source: server/services/genome.js getGenomeSummary()
-// Returns: { uploaded: bool, savedMarkers: { [uuid]: { rsid, category, status, gene, name, description, implications } } }
-const summary = await getGenomeSummary();
-const markers = Object.values(summary.savedMarkers || {});
-const classified = markers.filter(m => m.status !== 'not_found');
-```
-
-### Writing Insights Cache to Disk
-```javascript
-// Source: pattern from server/services/appleHealthIngest.js writeDayFile()
-import { writeFile } from 'fs/promises';
-import { join } from 'path';
-import { PATHS, ensureDir } from '../lib/fileUtils.js';
-
-const INSIGHTS_DIR = join(PATHS.data, 'insights');
-
-async function saveNarrative(text, previousText, model) {
- await ensureDir(INSIGHTS_DIR);
- const data = {
- text,
- previousText: previousText ?? null,
- generatedAt: new Date().toISOString(),
- previousGeneratedAt: null, // set from previous file if exists
- model
- };
- await writeFile(join(INSIGHTS_DIR, 'narrative.json'), JSON.stringify(data, null, 2));
- console.log(`🔮 Cross-domain narrative generated (${text.length} chars)`);
-}
-```
-
-### Reading Cached Insights
-```javascript
-// Source: pattern from server/lib/fileUtils.js readJSONFile()
-import { readJSONFile } from '../lib/fileUtils.js';
-
-async function getNarrative() {
- return readJSONFile(join(INSIGHTS_DIR, 'narrative.json'), null);
-}
-```
-
-### Insights Route Module (Express pattern)
-```javascript
-// Source: server/routes/appleHealth.js structure
-import { Router } from 'express';
-import { asyncHandler } from '../lib/errorHandler.js';
-import * as insightsService from '../services/insightsService.js';
-
-const router = Router();
-
-// GET /api/insights/genome-health
-router.get('/genome-health', asyncHandler(async (req, res) => {
- const data = await insightsService.getGenomeHealthCorrelations();
- res.json(data);
-}));
-
-// GET /api/insights/themes
-router.get('/themes', asyncHandler(async (req, res) => {
- const data = await insightsService.getThemeAnalysis();
- res.json(data);
-}));
-
-// POST /api/insights/themes/refresh
-router.post('/themes/refresh', asyncHandler(async (req, res) => {
- const result = await insightsService.generateThemeAnalysis();
- res.json(result);
-}));
-
-// GET /api/insights/narrative
-router.get('/narrative', asyncHandler(async (req, res) => {
- const data = await insightsService.getCrossDomainNarrative();
- res.json(data);
-}));
-
-// POST /api/insights/narrative/refresh
-router.post('/narrative/refresh', asyncHandler(async (req, res) => {
- const result = await insightsService.refreshCrossDomainNarrative();
- res.json(result);
-}));
-
-export default router;
-```
-
-### Confidence Badge Component (Tailwind pattern matching project tokens)
-```jsx
-// Source: pattern from existing StatusBadge.jsx + project design tokens
-const BADGE_STYLES = {
- strong: 'bg-port-success/20 text-port-success border-port-success/30',
- moderate: 'bg-port-warning/20 text-port-warning border-port-warning/30',
- weak: 'bg-port-error/20 text-port-error border-port-error/30',
- significant: 'bg-port-error/30 text-port-error border-port-error/50',
- unknown: 'bg-gray-800 text-gray-400 border-gray-700'
-};
-
-function ConfidenceBadge({ level, label, sources }) {
- return (
- <span
- title={sources?.join(', ')}
- className={`text-xs px-2 py-0.5 rounded border ${BADGE_STYLES[level]}`}
- >
- {label}
- </span>
- );
-}
-```
-
-### Diff Display (react-diff-viewer integration)
-```jsx
-// Source: react-diff-viewer npm package (github.com/praneshravi/react-diff-viewer)
-import ReactDiffViewer from 'react-diff-viewer-continued'; // maintained fork
-
-function NarrativeDiff({ previousText, currentText }) {
- if (!previousText) return null;
- return (
- <div className="rounded-lg overflow-hidden border border-port-border">
- <ReactDiffViewer
- oldValue={previousText}
- newValue={currentText}
- splitView={false}
- useDarkTheme
- hideLineNumbers
- />
- </div>
- );
-}
-```
-
----
-
-## State of the Art
-
-| Old Approach | Current Approach | When Changed | Impact |
-|--------------|------------------|--------------|--------|
-| Modal-based multi-step insight views | Deep-linked route tabs (/insights/:tab) | PortOS convention (CLAUDE.md) | Every view is bookmarkable and sharable |
-| LLM calls on every render | File-cached generation with explicit refresh | PortOS convention (taste-questionnaire, digital-twin) | Avoids repeated LLM costs; predictable latency |
-| Flat list of all markers | Grouped by clinical category (MARKER_CATEGORIES from curatedGenomeMarkers.js) | Phase 1 groundwork | Clinically meaningful organization already exists |
-| Free-text genome implications | Structured status field + implications string per status | Phase 1 groundwork | Machine-readable for correlation logic |
-
-**Deprecated/outdated:**
-- `/api/digital-twin/genome/`: Renamed to `/api/meatspace/genome/` in Phase 1 — do not reference old path.
-
----
-
-## Open Questions
-
-1. **Blood test analyte naming conventions**
- - What we know: `getBloodTests()` returns `{ tests: [] }` but analyte field names are user-entered (no schema enforcement currently)
- - What's unclear: Whether blood test analytes have consistent names across users' manually entered data (e.g., "LDL", "ldl", "LDL Cholesterol" all for the same thing)
- - Recommendation: Implement loose matching with normalization (lowercase, trim, common abbreviations) in `getLatestBloodValues()`. Show marker-to-blood pairing debug info during development.
-
-2. **Apple Health data availability for Phase 4**
- - What we know: Phase 3 (HLT-03 through HLT-06) are Pending — XML import, health dashboard cards, and HRV correlation aren't complete yet
- - What's unclear: At planning time for Phase 4 plans, how much Apple Health data will be in `data/health/`
- - Recommendation: Genome-health correlation (INS-01) should degrade gracefully if no Apple Health data exists — only show blood test correlations if that's all that's available. Apple Health data can be layered in as Phase 3 completes.
-
-3. **Optimal temperature for identity theme generation**
- - What we know: `taste-questionnaire.js` uses temperature 0.3 for section summaries
- - What's unclear: Identity theme generation is more creative — higher temperature (0.5-0.6) may produce richer themes but less consistent JSON structure
- - Recommendation: Default to 0.4 with the JSON fence-stripping safeguard. Make temperature a service-level constant that can be adjusted.
-
-4. **React diff viewer package choice**
- - What we know: `react-diff-viewer` (praneshravi) exists but has maintenance concerns; `react-diff-viewer-continued` is the maintained community fork
- - What's unclear: Whether either is actively maintained in 2026
- - Recommendation: Use `react-diff-viewer-continued` (npm: `react-diff-viewer-continued`) — verify install and dark theme support before committing to it in the plan. Alternative: hand-roll a simple word-level highlighter using the `diff` npm package since narratives are short (2-3 paragraphs).
-
----
-
-## Sources
-
-### Primary (HIGH confidence)
-- Codebase: `server/lib/curatedGenomeMarkers.js` — 117 markers with MARKER_CATEGORIES, status rules, implications
-- Codebase: `server/services/genome.js` — `scanCuratedMarkers()`, `getGenomeSummary()`, `savedMarkers` schema
-- Codebase: `server/services/meatspaceHealth.js` — `getBloodTests()`, `getBodyHistory()` APIs
-- Codebase: `server/services/appleHealthQuery.js` — `getDailyAggregates()`, `getCorrelationData()`
-- Codebase: `server/services/taste-questionnaire.js` — `getTasteProfile()`, `callProviderAISimple()` LLM pattern
-- Codebase: `client/src/App.jsx` — route structure, MeatSpace/:tab pattern confirmed
-- Codebase: `client/src/components/Layout.jsx` — nav entry order and structure confirmed
-- Codebase: `server/lib/fileUtils.js` — PATHS constants, `readJSONFile()`, `ensureDir()`
-- CLAUDE.md — Tailwind design tokens, alphabetical nav, no-try/catch, no-window.alert, linkable routes mandates
-- `.planning/REQUIREMENTS.md` — INS-01 through INS-04 definitions and out-of-scope (no causation claims)
-- `.planning/phases/04-cross-domain-insights-engine/04-CONTEXT.md` — locked decisions
-
-### Secondary (MEDIUM confidence)
-- WebSearch: `react-diff-viewer-continued` (maintained fork of `react-diff-viewer`) — multiple npm references, dark theme support documented
-- WebSearch: LLM JSON code fence stripping pattern — widely documented community workaround for prompt non-compliance
-
-### Tertiary (LOW confidence)
-- WebSearch: `react-diff-viewer` maintenance status in 2026 — unverified, may need manual npm check at planning time
-
----
-
-## Metadata
-
-**Confidence breakdown:**
-- Standard stack: HIGH — all dependencies verified in package.json or existing service patterns
-- Architecture: HIGH — all patterns traced to existing PortOS code; no speculative additions
-- Pitfalls: HIGH for codebase-sourced (empty data, not_found markers, alphabetical nav); MEDIUM for LLM behavior (JSON fencing widely documented but not verified in this specific provider setup)
-- Diff display: MEDIUM — react-diff-viewer-continued identified but not verified against current npm registry
-
-**Research date:** 2026-02-26
-**Valid until:** 2026-04-26 (stable stack, 60 days)
diff --git a/.planning/phases/04-cross-domain-insights-engine/04-VERIFICATION.md b/.planning/phases/04-cross-domain-insights-engine/04-VERIFICATION.md
deleted file mode 100644
index fe37157906..0000000000
--- a/.planning/phases/04-cross-domain-insights-engine/04-VERIFICATION.md
+++ /dev/null
@@ -1,140 +0,0 @@
----
-phase: 04-cross-domain-insights-engine
-verified: 2026-02-26T22:00:00Z
-status: passed
-score: 11/11 must-haves verified
-gaps:
- - truth: "Navigating to /insights shows the overview landing page with domain summary cards"
- status: resolved
- reason: "Overview tab summary cards for Taste-Identity and Cross-Domain Patterns display 'Not yet generated' even when data exists. The API returns { themes, generatedAt, model } without an 'available: true' field, but the Overview OverviewTab checks themesData?.available and narrativeData?.available — both are undefined (falsy) when data IS present. Only the Genome-Health card works correctly because getGenomeHealthCorrelations() explicitly returns { available: true }."
- artifacts:
- - path: "client/src/pages/Insights.jsx"
- issue: "Lines 85-91: const themesAvailable = themesData?.available and const narrativeAvailable = narrativeData?.available are always falsy when themes/narrative exist, because the cached response objects have no 'available' field. Stat text and topInsight fall through to the empty-state branches."
- - path: "server/services/insightsService.js"
- issue: "getThemeAnalysis() (line 304) and getCrossDomainNarrative() (line 386) return raw cached objects without an 'available: true' property. The empty-state branch returns { available: false } but the success branch returns the raw file contents."
- missing:
- - "Either add 'available: true' to the cached objects returned by getThemeAnalysis() and getCrossDomainNarrative(), OR change the OverviewTab checks to use a presence test (e.g., themesData?.themes?.length > 0) instead of themesData?.available"
-human_verification:
- - test: "Navigate to /insights/genome-health with genome data uploaded. Verify markers grouped by clinical category with collapsible category sections, confidence badges, matched blood values (or 'No blood test on record' link), and collapsed provenance panels."
- expected: "Category sections are visible and collapsible. Each marker card shows confidence badge color-coded: green for beneficial, yellow for typical, red for concern/major_concern. ProvenancePanel expands on click."
- why_human: "Requires genome data to be uploaded; cannot verify dynamic UI rendering programmatically."
- - test: "Navigate to /insights/taste-identity. Click 'Generate Themes'. Verify theme cards appear after LLM response with title, narrative, and collapsible evidence list. Then navigate to /insights/overview and verify the Taste-Identity summary card shows the first theme title and theme count."
- expected: "After fix: Overview card shows '{N} themes identified' and first theme title. Tab shows theme cards in 2-column grid. Evidence list is collapsible."
- why_human: "Requires LLM provider active; the Overview card bug (gap above) needs fix first."
- - test: "Navigate to /insights/cross-domain. Click 'Generate Narrative'. Click 'Refresh' a second time. Verify 'Show changes' button appears and diff view highlights additions/removals between old and new narrative."
- expected: "ReactDiffViewer renders with dark theme, split=false, port-* color overrides. Previous analysis date shown above diff."
- why_human: "Requires two LLM generations and real text comparison to validate diff rendering."
----
-
-# Phase 4: Cross-Domain Insights Engine Verification Report
-
-**Phase Goal:** PortOS surfaces actionable cross-domain patterns by correlating genome markers with health data and taste preferences with identity themes
-**Verified:** 2026-02-26
-**Status:** gaps_found
-**Re-verification:** No — initial verification
-
-## Goal Achievement
-
-### Observable Truths
-
-| # | Truth | Status | Evidence |
-| --- | ----- | ------ | -------- |
-| 1 | GET /api/insights/genome-health returns genome markers grouped by clinical category with matched blood test values and confidence levels | VERIFIED | insightsService.js exports getGenomeHealthCorrelations() (line 191). Groups by MARKER_CATEGORIES, matches via CATEGORY_BLOOD_MAP, applies CONFIDENCE_FROM_STATUS. Returns { available: true, categories, totalMarkers, matchedMarkers, sources }. Route wired at insights.js line 20. |
-| 2 | GET /api/insights/themes returns cached LLM-generated taste-identity themes or triggers generation | VERIFIED | getThemeAnalysis() (line 299) reads themes.json, returns { available: false, reason: 'not_generated' } if absent, else returns cached object. Route at insights.js line 25. |
-| 3 | POST /api/insights/themes/refresh regenerates theme analysis from current taste profile data | VERIFIED | generateThemeAnalysis() (line 314) fetches taste profile, builds LLM prompt, parses response, persists to data/insights/themes.json. Route POST /themes/refresh at insights.js line 32 with insightRefreshSchema validation. |
-| 4 | GET /api/insights/narrative returns cached cross-domain narrative with previous text for diff | VERIFIED | getCrossDomainNarrative() (line 381) reads narrative.json. Returns { available: false } if absent, else returns { text, previousText, generatedAt, previousGeneratedAt, model }. Route at insights.js line 39. |
-| 5 | POST /api/insights/narrative/refresh generates new narrative preserving previous text | VERIFIED | refreshCrossDomainNarrative() (line 397) preserves previousText and previousGeneratedAt from existing cache before overwriting. Route POST /narrative/refresh at insights.js line 45. |
-| 6 | All endpoints degrade gracefully when source data is missing | VERIFIED | All service functions return { available: false, reason } rather than throwing. genome: 'no_genome', themes: 'not_generated', narrative: 'not_generated', LLM unavailable: 'no_provider', no taste data: 'no_taste_data'. |
-| 7 | Navigating to /insights shows the overview landing page with domain summary cards | PARTIAL | Route exists (App.jsx line 71-72). OverviewTab renders 3 clickable cards. Genome card works. Taste-Identity and Cross-Domain cards use themesData?.available / narrativeData?.available — these are undefined (not false) when data exists, causing cards to always show empty-state text even when themes/narrative are generated. See gap below. |
-| 8 | /insights/genome-health displays genome markers grouped by clinical category with confidence badges | VERIFIED | GenomeHealthTab.jsx fetches getGenomeHealthCorrelations() on mount, renders CategorySection for each category with expand/collapse, MarkerCard per marker with ConfidenceBadge and ProvenancePanel. |
-| 9 | /insights/taste-identity displays LLM-generated theme cards with evidence lists and refresh button | VERIFIED | TasteIdentityTab.jsx (177 lines) fetches getInsightThemes(), handles both empty states (not_generated, no_taste_data), renders ThemeCard with EvidenceList (collapsible). Refresh button calls refreshInsightThemes(). |
-| 10 | /insights/cross-domain displays narrative text with refresh button and diff view showing changes | VERIFIED | CrossDomainTab.jsx (178 lines) uses ReactDiffViewer from react-diff-viewer-continued. hasPrevious checks data.previousText !== data.text (trimmed). Show/hide diff toggle present. |
-| 11 | Insights nav entry appears in the sidebar in correct alphabetical position | VERIFIED | Layout.jsx line 129: { to: '/insights/overview', label: 'Insights', icon: Lightbulb, single: true }. Positioned before Instances (line 130) and before MeatSpace (line 131). Alphabetically correct: "Insights" < "Instances" < "MeatSpace". /insights added to isFullWidth check (line 531). |
-
-**Score:** 10/11 truths verified (1 partial — Overview tab cards for themes and narrative show incorrect empty state when data exists)
-
-### Required Artifacts
-
-| Artifact | Min Lines | Actual Lines | Status | Details |
-| -------- | --------- | ------------ | ------ | ------- |
-| `server/services/insightsService.js` | — | 480 | VERIFIED | 5 exported functions: getGenomeHealthCorrelations, getThemeAnalysis, generateThemeAnalysis, getCrossDomainNarrative, refreshCrossDomainNarrative |
-| `server/routes/insights.js` | — | 51 | VERIFIED | 5 routes, all asyncHandler-wrapped, POST routes use validateRequest(insightRefreshSchema) |
-| `client/src/services/api.js` | — | — | VERIFIED | Lines 1400-1411: // Insights section with 5 exported functions confirmed |
-| `client/src/pages/Insights.jsx` | 80 | 244 | VERIFIED | 4-tab page with TABS config, VALID_TAB_IDS Set, OverviewTab inline, useParams routing |
-| `client/src/components/insights/GenomeHealthTab.jsx` | 80 | 195 | VERIFIED | CategorySection + MarkerCard + SkeletonCard, fetches on mount, empty state wired |
-| `client/src/components/insights/TasteIdentityTab.jsx` | 60 | 177 | VERIFIED | EvidenceList collapsible, ThemeCard with ConfidenceBadge, refresh handler, dual empty states |
-| `client/src/components/insights/CrossDomainTab.jsx` | 60 | 178 | VERIFIED | ReactDiffViewer integrated, hasPrevious check, show/hide diff toggle, loading skeleton |
-| `client/src/components/insights/InsightCard.jsx` | 20 | 30 | VERIFIED | Shared card shell with title, subtitle, badge, sources, children |
-| `client/src/components/insights/ConfidenceBadge.jsx` | 15 | 22 | VERIFIED | 5 levels: strong (green), moderate (yellow), weak (red), significant (deeper red), unknown (gray) |
-| `client/src/components/insights/ProvenancePanel.jsx` | — | 36 | VERIFIED | Collapsed by default, ChevronDown/Right toggle, renders ref name, year, source badge |
-| `client/src/components/insights/EmptyState.jsx` | — | 19 | VERIFIED | Info icon, message, optional NavLink button |
-
-### Key Link Verification
-
-| From | To | Via | Status | Details |
-| ---- | -- | --- | ------ | ------- |
-| server/routes/insights.js | server/services/insightsService.js | import * as insightsService | WIRED | Line 15: `import * as insightsService from '../services/insightsService.js'`. Used at lines 21, 27, 33, 40, 46. |
-| server/index.js | server/routes/insights.js | app.use('/api/insights') | WIRED | Line 42: import insightsRoutes. Line 224: app.use('/api/insights', insightsRoutes). |
-| server/services/insightsService.js | server/services/genome.js | getGenomeSummary() | WIRED | Line 17: import { getGenomeSummary }. Called at line 192 inside getGenomeHealthCorrelations(). |
-| server/services/insightsService.js | server/services/meatspaceHealth.js | getBloodTests() | WIRED | Line 18: import { getBloodTests }. Called at line 206. |
-| server/services/insightsService.js | server/services/taste-questionnaire.js | getTasteProfile() | WIRED | Line 20: import { getTasteProfile }. Called at line 315 inside generateThemeAnalysis(). |
-| client/src/pages/Insights.jsx | /api/insights/* | api.js client functions | WIRED | Lines 5-8: imports getGenomeHealthCorrelations, getInsightThemes, getInsightNarrative. All 3 called inside OverviewTab useEffect (lines 54-64). |
-| client/src/App.jsx | client/src/pages/Insights.jsx | Route path='insights/:tab' | WIRED | Line 19: import Insights. Lines 71-72: Route path="insights" redirect + Route path="insights/:tab". |
-| client/src/components/Layout.jsx | /insights/overview | nav entry with Lightbulb icon | WIRED | Line 51: Lightbulb imported. Line 129: { to: '/insights/overview', label: 'Insights', icon: Lightbulb, single: true }. |
-
-### Requirements Coverage
-
-| Requirement | Source Plan | Description | Status | Evidence |
-| ----------- | ----------- | ----------- | ------ | -------- |
-| INS-01 | 04-01-PLAN.md, 04-02-PLAN.md | Rule-based genome-to-health correlations using curated 117 markers against actual blood/body data | SATISFIED | getGenomeHealthCorrelations() implements CATEGORY_BLOOD_MAP for 6 categories, CONFIDENCE_FROM_STATUS per marker status, groups by MARKER_CATEGORIES (117 markers). GenomeHealthTab.jsx renders with provenance citations via ProvenancePanel. |
-| INS-02 | 04-01-PLAN.md, 04-02-PLAN.md | LLM-generated taste-to-identity theme analysis connecting preferences to identity patterns | SATISFIED | generateThemeAnalysis() builds analytical third-person prompt from taste profile sections, persists { themes, generatedAt, model } to data/insights/themes.json. TasteIdentityTab renders theme cards with evidence lists and strength-mapped ConfidenceBadge. |
-| INS-03 | 04-02-PLAN.md | Insights dashboard UI with confidence levels, source attribution, and domain grouping | SATISFIED | /insights/:tab routes to 4 sub-views. ConfidenceBadge consistent across genome and taste tabs. Source attribution via inline source pills. Domain grouping via category sections. EmptyState guides to data import. Note: Overview summary cards for themes/narrative have a wiring bug (gap found). |
-| INS-04 | 04-01-PLAN.md, 04-02-PLAN.md | LLM narrative summaries of cross-domain patterns refreshable on demand | SATISFIED | refreshCrossDomainNarrative() gathers genome + taste + Apple Health context, generates 2-3 paragraph narrative, preserves previousText for diff. CrossDomainTab has Refresh button, show/hide diff toggle, ReactDiffViewer with dark theme. |
-
-All 4 INS requirements are satisfied. INS-03 has a partial issue in the Overview tab's summary cards (see gap), but the core dashboard functionality — tabbed views, confidence levels, source attribution, domain grouping — is fully present.
-
-### Anti-Patterns Found
-
-| File | Line | Pattern | Severity | Impact |
-| ---- | ---- | ------- | -------- | ------ |
-| server/services/insightsService.js | 205, 209, 274 | Typo: `hasBlooodData` (triple 'o') | Info | Variable is declared and used consistently within the same function scope — no runtime bug, but a code quality issue. |
-| client/src/pages/Insights.jsx | 85, 89 | `themesData?.available` / `narrativeData?.available` with mismatched API contract | Blocker | When themes/narrative exist, the API returns objects without `available: true`, so these checks are always falsy. Overview tab summary cards for Taste-Identity and Cross-Domain always show empty-state content even when data exists. |
-
-### Human Verification Required
-
-### 1. Genome-Health Tab UI
-
-**Test:** With genome data uploaded (23andMe file in /meatspace/genome), navigate to /insights/genome-health. Verify category sections are collapsible, confidence badges are color-coded (green/yellow/red), blood values appear where matched, and ProvenancePanel expands on click.
-**Expected:** All 20+ categories render with expand/collapse. ConfidenceBadge colors match: green for beneficial (strong evidence), yellow for typical (moderate evidence), red for concern/major_concern (elevated/significant risk marker). "No blood test on record" link appears for unmatched analytes.
-**Why human:** Requires live genome data and visual color verification.
-
-### 2. Taste-Identity Theme Generation (After Gap Fix)
-
-**Test:** After applying the Overview card fix, navigate to /insights/taste-identity, click "Generate Themes", verify theme cards appear. Then navigate to /insights/overview and verify the Taste-Identity summary card shows theme count and first theme title.
-**Expected:** Theme cards display with InsightCard wrapper, ConfidenceBadge mapped from strength, collapsible EvidenceList. Overview card shows correct stat.
-**Why human:** Requires active LLM provider and the gap fix to be applied first.
-
-### 3. Cross-Domain Diff View
-
-**Test:** Navigate to /insights/cross-domain, generate narrative twice. After second generation, verify "Show changes" button appears (if text differs) and ReactDiffViewer renders with dark theme colors (green additions, red deletions), port-* color overrides, and previous analysis date in header.
-**Expected:** Diff view uses dark theme with correct PortOS color tokens. "Show changes" toggles between narrative text and diff view. "No significant changes detected" appears if texts are identical.
-**Why human:** Requires two LLM generations with different outputs to verify diff rendering.
-
-## Gaps Summary
-
-One gap blocks complete goal achievement:
-
-**Overview tab `available` field mismatch (Blocker):** The OverviewTab in `Insights.jsx` checks `themesData?.available` and `narrativeData?.available` to determine if data is present. However, `getThemeAnalysis()` and `getCrossDomainNarrative()` return the raw cached JSON objects (`{ themes, generatedAt, model }` and `{ text, previousText, ... }`) without an `available: true` property when data exists — only the empty-state branch returns `{ available: false }`. This means the Overview summary cards for Taste-Identity and Cross-Domain always render as if no data exists.
-
-**Fix options (either works):**
-1. In `insightsService.js`, wrap the cached return in both functions: `return { available: true, ...cached };`
-2. In `Insights.jsx` OverviewTab, change availability checks to: `const themesAvailable = !!(themesData?.themes?.length)` and `const narrativeAvailable = !!(narrativeData?.text)`
-
-The individual tabs (`TasteIdentityTab`, `CrossDomainTab`) are NOT affected because they check `!data?.available` — `undefined` is falsy, so they correctly treat data-present responses as available.
-
-The fix is minimal (2-4 lines) and isolated to either the service layer or the Overview component.
-
----
-
-_Verified: 2026-02-26_
-_Verifier: Claude (gsd-verifier)_
diff --git a/.planning/phases/05-unified-search/05-01-PLAN.md b/.planning/phases/05-unified-search/05-01-PLAN.md
deleted file mode 100644
index 45a76a1f24..0000000000
--- a/.planning/phases/05-unified-search/05-01-PLAN.md
+++ /dev/null
@@ -1,318 +0,0 @@
----
-phase: 05-unified-search
-plan: 01
-type: execute
-wave: 1
-depends_on: []
-files_modified:
- - server/lib/validation.js
- - server/services/search.js
- - server/routes/search.js
- - server/index.js
- - client/src/services/api.js
-autonomous: true
-requirements:
- - SRC-02
- - SRC-03
-
-must_haves:
- truths:
- - "GET /api/search?q=foo returns categorized results from Brain, Memory, Apps, History, and Health sources"
- - "Each source result includes id, title, snippet, url, and type fields"
- - "Failed source adapters return empty results instead of failing the entire request"
- - "Query param q is validated (min 2 chars, max 200, trimmed)"
- - "Snippets contain ~100 char window around the keyword match"
- - "Sources with zero results are omitted from the response"
- artifacts:
- - path: "server/services/search.js"
- provides: "Fan-out search engine with source adapters"
- exports: ["fanOutSearch"]
- - path: "server/routes/search.js"
- provides: "GET /api/search route handler"
- - path: "server/lib/validation.js"
- provides: "searchQuerySchema export"
- contains: "searchQuerySchema"
- - path: "client/src/services/api.js"
- provides: "search() client API function"
- contains: "search"
- key_links:
- - from: "server/routes/search.js"
- to: "server/services/search.js"
- via: "import fanOutSearch"
- pattern: "fanOutSearch"
- - from: "server/routes/search.js"
- to: "server/lib/validation.js"
- via: "import searchQuerySchema"
- pattern: "searchQuerySchema"
- - from: "server/index.js"
- to: "server/routes/search.js"
- via: "app.use('/api/search', searchRoutes)"
- pattern: "api/search"
- - from: "client/src/services/api.js"
- to: "server/routes/search.js"
- via: "request('/search?q=')"
- pattern: "/search"
----
-
-<objective>
-Build the server-side unified search engine and client API function. A single GET /api/search?q= endpoint fans out keyword queries to all PortOS data sources (Brain inbox/people/projects/ideas/links, CoS Memory via BM25, Apps, History, Health metrics) using Promise.allSettled for fault isolation. Each source adapter performs case-insensitive substring matching, returns categorized results with deep-link URLs, and extracts ~100-char snippets around keyword matches. The client API function is added to api.js for consumption by the overlay component (Plan 05-02).
-
-Purpose: SRC-02 (server fan-out search) and SRC-03 (categorized results with icons/snippets) — backend foundation
-Output: search.js service, search.js route, searchQuerySchema in validation.js, search() in api.js
-</objective>
-
-<execution_context>
-@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
-@/Users/antic/.claude/get-shit-done/templates/summary.md
-</execution_context>
-
-<context>
[email protected]/phases/05-unified-search/05-RESEARCH.md
-
-<interfaces>
-<!-- Key types and contracts the executor needs. Extracted from codebase. -->
-
-From server/services/brainStorage.js:
-```js
-export async function getInboxLog(options = {}) // options: { limit, offset, status }
-// Returns: { entries: [...], total, hasMore }
-// Each entry: { id, text, timestamp, status, ... }
-
-export async function getAll(type) // type: 'people'|'projects'|'ideas'|'links'
-// Returns: array of records
-// people: { id, name, notes, ... }
-// projects: { id, name, description, ... }
-// ideas: { id, title, description, ... }
-// links: { id, title, url, description, ... }
-
-export const getPeople = (filters) => ...
-export const getProjects = (filters) => ...
-export const getIdeas = (filters) => ...
-export const getLinks = (filters) => ...
-```
-
-From server/services/memoryBM25.js:
-```js
-async function searchBM25(query, options = {}) // options: { limit, threshold }
-// Returns: [{ id, score }] — no content, no summary
-// Must load summary from memory index for snippet
-```
-
-From server/services/memory.js:
-```js
-export async function getMemory(id) // Returns full memory object with content
-export async function getMemories(options = {}) // Returns { memories: [...], total }
-// Each memory has: id, content, summary (150 char), category, tags, status, ...
-```
-
-From server/services/apps.js:
-```js
-export async function getAllApps({ includeArchived = true } = {})
-// Returns: [{ id, name, description, type, repoPath, ... }]
-```
-
-From server/services/history.js:
-```js
-export async function getHistory(options = {})
-// options: { limit, offset, action, target, success }
-// Returns: { entries: [...], total }
-// Each entry: { id, action, target, targetName, details, timestamp, ... }
-```
-
-From server/services/appleHealthQuery.js:
-```js
-export async function listDayFiles()
-// Returns: ['2024-01-15', '2024-01-16', ...] sorted date strings
-```
-
-From server/lib/validation.js:
-```js
-// Uses Zod schemas — add searchQuerySchema to existing exports
-// Pattern: export const {name}Schema = z.object({ ... });
-```
-
-From server/index.js route registration pattern:
-```js
-import searchRoutes from './routes/search.js';
-app.use('/api/search', searchRoutes);
-```
-
-From client/src/services/api.js:
-```js
-// request(endpoint, options) — internal helper
-// Pattern: export const fnName = (params) => request('/path', { ... });
-```
-</interfaces>
-</context>
-
-<tasks>
-
-<task type="auto">
- <name>Task 1: Create search service with source adapters and fan-out engine</name>
- <files>server/services/search.js</files>
- <action>
-Create `server/services/search.js` with the following structure:
-
-1. **Import source services:**
- - `brainStorage` (getInboxLog, getAll for people/projects/ideas/links)
- - `memoryBM25` (searchBM25) and `memory` (getMemories for summary lookup)
- - `apps` (getAllApps)
- - `history` (getHistory)
- - `appleHealthQuery` (listDayFiles)
-
-2. **extractSnippet(text, query, maxLen = 100) helper function:**
- - If text is falsy, return empty string
- - Find first case-insensitive occurrence of query in text
- - Extract ~100 char window centered around the match (30 chars before match start)
- - Prepend '...' if excerpt doesn't start at beginning, append '...' if it doesn't reach end
- - If no match found, return first maxLen chars of text
-
-3. **Create source adapter functions** — each returns `{ id, label, icon, results }`:
-
- **searchBrain(query):**
- - Fan out to getInboxLog({ limit: 200 }), getPeople(), getProjects(), getIdeas(), getLinks() using Promise.allSettled
- - For inbox: filter entries where `text` includes query (case-insensitive), map to `{ id, title: text.substring(0, 60), snippet: extractSnippet(text, query), url: '/brain/inbox', type: 'inbox' }`
- - For people: filter on `name` or `notes`, map to `{ id, title: name, snippet: extractSnippet(notes, query), url: '/brain/inbox', type: 'person' }`
- - For projects: filter on `name` or `description`, map to `{ id, title: name, snippet: extractSnippet(description, query), url: '/brain/inbox', type: 'project' }`
- - For ideas: filter on `title` or `description`, map to `{ id, title, snippet: extractSnippet(description, query), url: '/brain/inbox', type: 'idea' }`
- - For links: filter on `title`, `url`, or `description`, map to `{ id, title: title || url, snippet: extractSnippet(description || url, query), url: '/brain/inbox', type: 'link' }`
- - Combine all matches, sort by most recent, take first 5
- - Return `{ id: 'brain', label: 'Brain', icon: 'Brain', results }`
-
- **searchMemory(query):**
- - Call searchBM25(query, { limit: 10, threshold: 0.1 })
- - Use getMemories() to load the full index, then map BM25 result IDs to their summary from the index
- - Map to `{ id, title: summary.substring(0, 60), snippet: summary, url: '/cos/memory', type: 'memory' }`
- - Take first 5 results
- - Return `{ id: 'memory', label: 'Memory', icon: 'Cpu', results }`
-
- **searchApps(query):**
- - Call getAllApps({ includeArchived: false })
- - Filter where `name` or `description` includes query (case-insensitive)
- - Map to `{ id, title: name, snippet: extractSnippet(description, query), url: '/apps', type: 'app' }`
- - Take first 5
- - Return `{ id: 'apps', label: 'Apps', icon: 'Package', results }`
-
- **searchHistory(query):**
- - Call getHistory({ limit: 500 })
- - Filter entries where `targetName` or `action` includes query (case-insensitive)
- - Map to `{ id, title: targetName || action, snippet: extractSnippet(action + ' ' + (targetName || ''), query), url: '/devtools/history', type: 'history' }`
- - Take first 5
- - Return `{ id: 'history', label: 'History', icon: 'History', results }`
-
- **searchHealth(query):**
- - Define known metric names: `['step_count', 'heart_rate', 'sleep_analysis', 'hrv', 'blood_pressure', 'body_mass', 'respiratory_rate', 'blood_glucose', 'body_temperature']`
- - Also define display-friendly aliases: `{ step_count: 'Steps', heart_rate: 'Heart Rate', sleep_analysis: 'Sleep', hrv: 'HRV', blood_pressure: 'Blood Pressure', body_mass: 'Body Mass', respiratory_rate: 'Respiratory Rate', blood_glucose: 'Blood Glucose', body_temperature: 'Body Temperature' }`
- - Filter metrics where either the key or the display name includes query (case-insensitive)
- - Map to `{ id: metricKey, title: displayName, snippet: displayName + ' health metric data', url: '/meatspace/health', type: 'health-metric' }`
- - Return `{ id: 'health', label: 'Health', icon: 'HeartPulse', results }`
-
-4. **fanOutSearch(query) export:**
- - Call all 5 adapters via `Promise.allSettled([searchBrain(q), searchMemory(q), searchApps(q), searchHistory(q), searchHealth(q)])`
- - Map settled results: fulfilled => value, rejected => source with empty results array (use a fallback array of empty source objects keyed by index)
- - Filter out sources where `results.length === 0`
- - Return the array of non-empty sources
-
-Use single-line logging per CLAUDE.md: `console.log(\`🔍 Search fan-out for "${query}" across ${adapters.length} sources\`)` at start, and log count of total results at end.
-
-Do NOT use try/catch — per CLAUDE.md, errors bubble to centralized middleware. The Promise.allSettled pattern naturally handles per-adapter failures.
- </action>
- <verify>
- <automated>cd server && node -e "import('./services/search.js').then(m => console.log('✅ search.js loads, exports:', Object.keys(m)))"</automated>
- </verify>
- <done>search.js exports fanOutSearch function; imports compile; all 5 source adapters defined</done>
-</task>
-
-<task type="auto">
- <name>Task 2: Create search route, Zod schema, register in index.js, and add client API function</name>
- <files>server/routes/search.js, server/lib/validation.js, server/index.js, client/src/services/api.js</files>
- <action>
-**1. Add searchQuerySchema to server/lib/validation.js:**
-
-Add to the existing file (find an appropriate location near other query schemas, or at the end before the closing section):
-
-```js
-// =============================================================================
-// SEARCH SCHEMAS
-// =============================================================================
-
-export const searchQuerySchema = z.object({
- q: z.string().min(2).max(200).trim()
-});
-```
-
-**2. Create server/routes/search.js:**
-
-```js
-import { Router } from 'express';
-import { asyncHandler } from '../lib/errorHandler.js';
-import { validateRequest, searchQuerySchema } from '../lib/validation.js';
-import { fanOutSearch } from '../services/search.js';
-
-const router = Router();
-
-router.get('/', asyncHandler(async (req, res) => {
- const { data } = validateRequest(searchQuerySchema, req.query);
- const sources = await fanOutSearch(data.q);
- res.json({ query: data.q, sources });
-}));
-
-export default router;
-```
-
-Follow the exact pattern from existing routes (e.g., history.js). Use `asyncHandler` wrapper. Use `validateRequest` for Zod validation. Return `{ query, sources }` response shape.
-
-**3. Register route in server/index.js:**
-
-Add import at top with other route imports:
-```js
-import searchRoutes from './routes/search.js';
-```
-
-Add route registration. Place it alphabetically among the existing `app.use('/api/...')` lines — it should go near `/api/screenshots` and `/api/settings`:
-```js
-app.use('/api/search', searchRoutes);
-```
-
-**4. Add search function to client/src/services/api.js:**
-
-Add near the top of the export functions (or in a logical location with other utility endpoints):
-
-```js
-export const search = (q) => request(`/search?q=${encodeURIComponent(q)}`);
-```
-
-This follows the exact pattern of existing API functions (e.g., `getAppleHealthRange`).
- </action>
- <verify>
- <automated>cd server && node -e "import('./lib/validation.js').then(m => { if (!m.searchQuerySchema) throw new Error('missing searchQuerySchema'); console.log('✅ searchQuerySchema exists'); })" && node -e "import('./routes/search.js').then(m => console.log('✅ search route loads'))"</automated>
- </verify>
- <done>GET /api/search?q=test is a registered route; searchQuerySchema validates q param; client api.js exports search() function</done>
-</task>
-
-</tasks>
-
-<verification>
-1. Server starts without errors after changes: `cd server && node -e "import('./index.js')"`
-2. Search route responds: `curl "http://localhost:5554/api/search?q=test"` returns JSON with `query` and `sources` fields
-3. Validation rejects short queries: `curl "http://localhost:5554/api/search?q=a"` returns 400
-4. Empty query rejected: `curl "http://localhost:5554/api/search"` returns 400
-5. Failed adapters don't crash the entire request — if one service has no data, the response still returns other sources
-</verification>
-
-<success_criteria>
-- GET /api/search?q=foo returns `{ query, sources: [...] }` with results from all available data sources
-- Each source has { id, label, icon, results } structure
-- Each result has { id, title, snippet, url, type } structure
-- Sources with zero results are omitted from response
-- Query validation enforces min 2 chars, max 200
-- client api.js exports search(q) function
-- Server starts cleanly with no import errors
-</success_criteria>
-
-<output>
-After completion, create `.planning/phases/05-unified-search/05-01-SUMMARY.md`
-</output>
diff --git a/.planning/phases/05-unified-search/05-01-SUMMARY.md b/.planning/phases/05-unified-search/05-01-SUMMARY.md
deleted file mode 100644
index eb3d9236e6..0000000000
--- a/.planning/phases/05-unified-search/05-01-SUMMARY.md
+++ /dev/null
@@ -1,115 +0,0 @@
----
-phase: 05-unified-search
-plan: 01
-subsystem: api
-tags: [search, fan-out, bm25, express, zod, promise-allsettled]
-
-# Dependency graph
-requires:
- - phase: 03-apple-health-integration
- provides: appleHealthQuery.listDayFiles referenced for health source adapter
- - phase: 04-cross-domain-insights-engine
- provides: memory BM25 index and brainStorage services used as search sources
-
-provides:
- - fanOutSearch engine in server/services/search.js
- - GET /api/search?q= route with Zod validation
- - searchQuerySchema in server/lib/validation.js
- - search(q) client API function in client/src/services/api.js
-
-affects: [05-02-search-overlay-ui]
-
-# Tech tracking
-tech-stack:
- added: []
- patterns:
- - Promise.allSettled for fault-isolated fan-out search across multiple data sources
- - extractSnippet helper for keyword-centered 100-char excerpts with ellipsis trimming
- - Source adapters return { id, label, icon, results } with results as { id, title, snippet, url, type }
- - Sources with zero results filtered from response before return
-
-key-files:
- created:
- - server/services/search.js
- - server/routes/search.js
- modified:
- - server/lib/validation.js
- - server/index.js
- - client/src/services/api.js
-
-key-decisions:
- - "Health adapter is synchronous (no I/O) — searches known metric names + display aliases in-memory, no file reads needed"
- - "Memory adapter uses Promise.allSettled internally to isolate BM25 failures from memory index failures"
- - "Brain adapter fans out to all 5 sub-types (inbox/people/projects/ideas/links) via Promise.allSettled and aggregates into one source block"
- - "fanOutSearch returns only non-empty sources — zero-result sources are omitted from the response"
-
-patterns-established:
- - "Search route pattern: asyncHandler + validateRequest(searchQuerySchema, req.query) + service call"
- - "Source adapter contract: async fn(query) => { id, label, icon, results[] } where results are { id, title, snippet, url, type }"
-
-requirements-completed: [SRC-02, SRC-03]
-
-# Metrics
-duration: 8min
-completed: 2026-02-26
----
-
-# Phase 5 Plan 01: Unified Search — Server Foundation Summary
-
-**Fan-out keyword search engine with 5 source adapters (Brain/Memory/Apps/History/Health), GET /api/search?q= route, Zod schema, and client search() function**
-
-## Performance
-
-- **Duration:** ~8 min
-- **Started:** 2026-02-26T23:54:25Z
-- **Completed:** 2026-02-27T00:01:05Z
-- **Tasks:** 2
-- **Files modified:** 5
-
-## Accomplishments
-- Built `server/services/search.js` with `fanOutSearch()` engine and 5 source adapters using Promise.allSettled for complete fault isolation
-- Implemented `extractSnippet()` helper that finds keyword match position and extracts a ~100-char window with `...` padding
-- Created `GET /api/search` route with Zod min-2/max-200 query validation and structured `{ query, sources }` response
-- Added `search(q)` client API function to `client/src/services/api.js` for use by the overlay component in Plan 05-02
-
-## Task Commits
-
-Each task was committed atomically:
-
-1. **Task 1: Create search service with source adapters and fan-out engine** - `226b850` (feat)
-2. **Task 2: Create search route, Zod schema, register in index.js, and add client API function** - `ea077ee` (feat)
-
-**Plan metadata:** (docs commit — see state update)
-
-## Files Created/Modified
-- `server/services/search.js` - Fan-out search engine with 5 source adapters and extractSnippet helper
-- `server/routes/search.js` - GET /api/search route handler with asyncHandler + Zod validation
-- `server/lib/validation.js` - Added searchQuerySchema (q: min 2, max 200, trimmed)
-- `server/index.js` - Registered searchRoutes at /api/search (alphabetically after /api/screenshots)
-- `client/src/services/api.js` - Added search(q) function using encodeURIComponent
-
-## Decisions Made
-- Health adapter has no I/O — it matches keyword against a static list of known metric names and display aliases (e.g., "step_count" / "Steps"), making it synchronous and zero-latency
-- Memory adapter guards both BM25 and memory index calls with Promise.allSettled internally, returns empty results if either fails
-- Brain adapter fans out to 5 sub-sources (inbox/people/projects/ideas/links) via Promise.allSettled and merges into a single "Brain" source block, takes first 5 across all sub-types
-- `fanOutSearch` filters out sources with zero results before returning, keeping the response lean
-
-## Deviations from Plan
-
-None - plan executed exactly as written.
-
-## Issues Encountered
-None.
-
-## User Setup Required
-None - no external service configuration required.
-
-## Next Phase Readiness
-- `GET /api/search?q=` is live and ready for the overlay UI component in Plan 05-02
-- `search(q)` client function available in `api.js` for immediate import
-- Response shape `{ query, sources: [{ id, label, icon, results: [{ id, title, snippet, url, type }] }] }` is stable
-- All 5 source adapters operational; Health is always synchronous, others degrade gracefully on empty data
-
----
-*Phase: 05-unified-search*
-*Completed: 2026-02-26*
diff --git a/.planning/phases/05-unified-search/05-02-PLAN.md b/.planning/phases/05-unified-search/05-02-PLAN.md
deleted file mode 100644
index a3068a6463..0000000000
--- a/.planning/phases/05-unified-search/05-02-PLAN.md
+++ /dev/null
@@ -1,319 +0,0 @@
----
-phase: 05-unified-search
-plan: 02
-type: execute
-wave: 2
-depends_on:
- - 05-01
-files_modified:
- - client/src/hooks/useCmdKSearch.js
- - client/src/components/CmdKSearch.jsx
- - client/src/components/Layout.jsx
-autonomous: false
-requirements:
- - SRC-01
- - SRC-03
- - SRC-04
-
-must_haves:
- truths:
- - "Pressing Cmd+K or Ctrl+K from any page opens a search overlay"
- - "Typing 2+ characters triggers debounced search-as-you-type"
- - "Results are grouped by source with section headers, icons, and text snippets"
- - "Keyword matches are highlighted in result snippets"
- - "Arrow keys move selection highlight, Enter navigates to result URL, Escape closes overlay"
- - "Clicking a result navigates to its deep-linked location and closes the overlay"
- - "Clicking the backdrop dismisses the overlay"
- - "Before typing, empty area shows placeholder hint"
- - "No-results state shows centered message"
- - "Input auto-focuses when overlay opens"
- - "Body scroll is locked when overlay is open"
- artifacts:
- - path: "client/src/hooks/useCmdKSearch.js"
- provides: "Global Cmd+K keyboard shortcut hook"
- exports: ["useCmdKSearch"]
- - path: "client/src/components/CmdKSearch.jsx"
- provides: "Search overlay modal component with results display"
- - path: "client/src/components/Layout.jsx"
- provides: "CmdKSearch mounted in layout shell"
- contains: "CmdKSearch"
- key_links:
- - from: "client/src/components/Layout.jsx"
- to: "client/src/components/CmdKSearch.jsx"
- via: "import and render <CmdKSearch />"
- pattern: "CmdKSearch"
- - from: "client/src/components/CmdKSearch.jsx"
- to: "client/src/hooks/useCmdKSearch.js"
- via: "import useCmdKSearch"
- pattern: "useCmdKSearch"
- - from: "client/src/components/CmdKSearch.jsx"
- to: "client/src/services/api.js"
- via: "import { search } from api.js"
- pattern: "search"
- - from: "client/src/components/CmdKSearch.jsx"
- to: "react-router-dom"
- via: "useNavigate() for deep-link navigation"
- pattern: "navigate"
----
-
-<objective>
-Build the Cmd+K search overlay UI — a Spotlight/Raycast-style modal that appears on Cmd+K/Ctrl+K from any page, displays categorized search results with keyboard navigation, and navigates to deep-linked locations on selection. The overlay uses a React portal for z-index isolation, debounced search-as-you-type, arrow key navigation, and highlighted keyword matches in snippets.
-
-Purpose: SRC-01 (Cmd+K opens overlay), SRC-03 (categorized results with icons/snippets), SRC-04 (deep-link navigation)
-Output: useCmdKSearch.js hook, CmdKSearch.jsx overlay component, Layout.jsx updated with mount point
-</objective>
-
-<execution_context>
-@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
-@/Users/antic/.claude/get-shit-done/templates/summary.md
-</execution_context>
-
-<context>
[email protected]/phases/05-unified-search/05-RESEARCH.md
[email protected]/phases/05-unified-search/05-01-SUMMARY.md
-
-<interfaces>
-<!-- Key contracts from Plan 05-01 that this plan consumes -->
-
-From client/src/services/api.js (added by Plan 05-01):
-```js
-export const search = (q) => request(`/search?q=${encodeURIComponent(q)}`);
-// Returns: { query: string, sources: Source[] }
-// Source: { id: string, label: string, icon: string, results: Result[] }
-// Result: { id: string, title: string, snippet: string, url: string, type: string }
-```
-
-From client/src/components/Layout.jsx (existing):
-```jsx
-// Layout is the root shell wrapping all pages via <Outlet />
-// Import lucide-react icons already present: Brain, Package, History, HeartPulse, Cpu, Search, etc.
-// CmdKSearch should be mounted as a sibling to the main content area
-// Layout uses Tailwind classes with port-* design tokens
-```
-
-From client/src/App.jsx route patterns:
-```
-/brain/inbox — Brain captures
-/cos/memory — CoS memory entries
-/apps — App registry
-/devtools/history — Activity history
-/meatspace/health — Health metrics
-```
-</interfaces>
-</context>
-
-<tasks>
-
-<task type="auto">
- <name>Task 1: Create Cmd+K hook and search overlay component</name>
- <files>client/src/hooks/useCmdKSearch.js, client/src/components/CmdKSearch.jsx</files>
- <action>
-**1. Create client/src/hooks/useCmdKSearch.js:**
-
-```js
-import { useState, useEffect } from 'react';
-
-export function useCmdKSearch() {
- const [open, setOpen] = useState(false);
-
- useEffect(() => {
- const handler = (e) => {
- if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
- e.preventDefault();
- setOpen(prev => !prev);
- }
- };
- document.addEventListener('keydown', handler);
- return () => document.removeEventListener('keydown', handler);
- }, []);
-
- return { open, setOpen };
-}
-```
-
-Note on Pitfall 6 from research: The global Cmd+K handler fires even when an input/textarea is focused. This is the correct behavior — Spotlight and Raycast both override Cmd+K in inputs. The search overlay is the highest-priority action for this shortcut.
-
-**2. Create client/src/components/CmdKSearch.jsx:**
-
-Build a Spotlight-style search overlay using React portal. Key specifications from CONTEXT.md (locked decisions):
-
-**Overlay appearance:**
-- Spotlight-style centered modal, ~800px wide (use `max-w-3xl` which is 768px, close to 800)
-- Semi-transparent dark backdrop (`bg-black/60`) — click backdrop to dismiss
-- Subtle fade+scale animation (~150ms): use Tailwind `transition-all duration-150`
-- Use `createPortal(document.body)` to render above sidebar z-index
-
-**Result presentation:**
-- Results grouped by source under section headers with icon + label
-- Top 3 results per source category initially, with "Show more" button to expand to all
-- Each result row: source icon + title (bold) + 1-line text snippet with keyword highlighted
-- Categories with zero results hidden (server already omits them)
-
-**Search interaction:**
-- Full keyboard navigation: ArrowDown/ArrowUp move highlight, Enter navigates, Escape closes
-- Search-as-you-type after 2+ characters with 300ms debounce
-- Before typing: empty results area with placeholder hint "Search Brain, Memory, Health..."
-- No-results state: subtle centered "No results for 'xyz'" message
-
-**Implementation details:**
-
-Import `{ search }` from `../services/api.js` for the API call.
-Import `{ useNavigate }` from `react-router-dom` for deep-link navigation.
-Import `{ createPortal }` from `react-dom`.
-Import Lucide icons: `Brain, Cpu, Package, History, HeartPulse, Search, Loader2` from `lucide-react`.
-
-**Component state:**
-- `query` (string) — current search input
-- `results` (array of source objects) — from API response
-- `loading` (boolean) — true while fetching
-- `focusedIndex` (number) — currently highlighted result in flat list
-- `expandedSources` (Set) — source IDs where "Show more" is clicked
-
-**Debounce logic:**
-- Use a `useEffect` with `setTimeout`/`clearTimeout` pattern (no external library)
-- When `query.length >= 2`, set 300ms timeout, then call `search(query)` and update results
-- When `query.length < 2`, clear results immediately
-
-**Flat result list for keyboard navigation:**
-- Compute `flatResults` from sources: iterate sources, for each source take first 3 results (or all if source is in expandedSources), flatten into a single array
-- Each flat item gets a reference to its source id for rendering
-
-**Reset focusedIndex to 0 whenever results change** (Pitfall 5 from research).
-
-**Auto-focus input on open** (Pitfall 1): `useEffect(() => { if (open) inputRef.current?.focus(); }, [open])`.
-
-**Lock body scroll when open** (Pitfall 2): `useEffect(() => { document.body.style.overflow = open ? 'hidden' : ''; return () => { document.body.style.overflow = ''; }; }, [open])`.
-
-**Clear query and results when overlay closes** so it starts fresh each time.
-
-**Keyboard handler** (on the overlay container div, not the input):
-- ArrowDown: increment focusedIndex (clamp to flatResults.length - 1)
-- ArrowUp: decrement focusedIndex (clamp to 0)
-- Enter: if flatResults[focusedIndex] exists, call `navigate(flatResults[focusedIndex].url)` and close overlay
-- Escape: close overlay
-
-**Highlight component** (inline helper):
-- Split snippet text on the search query (case-insensitive regex with special char escaping)
-- Wrap matched parts with `<mark className="bg-port-accent/30 text-white rounded px-0.5">`
-
-**Icon mapping:**
-Create a map from icon string to Lucide component:
-```js
-const ICON_MAP = { Brain, Cpu, Package, History, HeartPulse };
-```
-Look up `source.icon` in the map; fallback to `Search` icon.
-
-**Rendering structure (inside portal):**
-
-```
-backdrop (fixed inset-0, bg-black/60, onClick close)
- container (centered, max-w-3xl, bg-port-card, rounded-xl, border border-port-border, shadow-2xl)
- search input row (flex, border-b border-port-border, p-4)
- Search icon (text-gray-400)
- input (flex-1, bg-transparent, text-white, placeholder, ref=inputRef)
- Cmd+K badge (text-xs text-gray-500 border border-port-border rounded px-1.5)
- results area (max-h-96 overflow-y-auto p-2)
- if loading: centered Loader2 spinner (animate-spin)
- if query.length >= 2 && !loading && results.length === 0: "No results for 'query'"
- if query.length < 2: placeholder hint
- for each source in results:
- source header (flex items-center gap-2, text-xs text-gray-400 uppercase, px-3 py-2)
- SourceIcon (size=14)
- source.label
- for each result (first 3 or all if expanded):
- result row (flex items-start gap-3, px-3 py-2, rounded-lg, cursor-pointer)
- highlight bg if focusedIndex matches this flat index (bg-port-accent/10)
- hover state (hover:bg-white/5)
- title (text-sm font-medium text-white, truncate)
- snippet (text-xs text-gray-400, with Highlight component)
- if source has >3 results and not expanded:
- "Show more" button (text-xs text-port-accent, px-3 py-1)
-```
-
-Use Tailwind design tokens from CLAUDE.md: port-bg, port-card, port-border, port-accent.
-
-On result click: `navigate(result.url)` then `setOpen(false)`.
-
-Scroll the focused result into view: on the result row div, use `ref` callback and `scrollIntoView({ block: 'nearest' })` when it becomes focused.
- </action>
- <verify>
- <automated>cd client && node -e "import('./src/hooks/useCmdKSearch.js').then(() => console.log('✅ hook imports ok'))" && node -e "import('./src/components/CmdKSearch.jsx').then(() => console.log('✅ CmdKSearch imports ok'))" 2>&1 || echo "Note: JSX import may fail in plain node — verify via dev server build"</automated>
- </verify>
- <done>useCmdKSearch hook handles Cmd+K/Ctrl+K toggle; CmdKSearch component renders portal overlay with debounced search, grouped results, keyboard navigation, highlighted snippets, and deep-link navigation</done>
-</task>
-
-<task type="auto">
- <name>Task 2: Mount CmdKSearch in Layout.jsx</name>
- <files>client/src/components/Layout.jsx</files>
- <action>
-Edit `client/src/components/Layout.jsx` to mount the CmdKSearch overlay:
-
-1. Add import at the top with other component imports:
-```js
-import CmdKSearch from './CmdKSearch';
-```
-
-2. Inside the Layout component's return JSX, add `<CmdKSearch />` as a sibling — place it just before the closing `</div>` of the outermost wrapper (or at the end of the return). Since CmdKSearch renders via a portal to document.body, its placement in the JSX tree doesn't affect layout, but placing it in Layout ensures it's always mounted regardless of which page route is active.
-
-The component is self-contained — it uses the useCmdKSearch hook internally for open/close state and renders via portal. No props needed.
-
-Verify the dev server builds without errors after the change.
- </action>
- <verify>
- <automated>cd client && npx vite build 2>&1 | tail -5</automated>
- </verify>
- <done>CmdKSearch is mounted in Layout.jsx; client builds without errors; overlay is available on every page</done>
-</task>
-
-<task type="checkpoint:human-verify" gate="blocking">
- <name>Task 3: Verify Cmd+K search overlay end-to-end</name>
- <files>none</files>
- <action>
-Human verifies the complete Cmd+K search overlay:
-1. Open PortOS in browser (http://localhost:5555 or Tailscale URL)
-2. Press Cmd+K (Mac) or Ctrl+K (other) — search overlay should appear centered with ~800px width, dark backdrop
-3. Type "test" (or any 2+ char query) — results should appear grouped by source (Brain, Memory, Apps, History, Health)
-4. Verify each result shows: icon, bold title, snippet text with keyword highlighted
-5. Press ArrowDown/ArrowUp — selection highlight should move between results
-6. Press Enter on a highlighted result — should navigate to the deep-linked page and close overlay
-7. Reopen with Cmd+K, type a query, click a result — should navigate and close
-8. Click the dark backdrop — overlay should dismiss
-9. Press Escape — overlay should dismiss
-10. Try a query with no results — should show "No results for 'xyz'" message
-11. Verify overlay feels fast and responsive (300ms debounce, no lag)
-12. Verify body scroll is locked when overlay is open
- </action>
- <verify>Human approves the overlay appearance, keyboard navigation, result categorization, and deep-link navigation</verify>
- <done>User types "approved" confirming the Cmd+K search overlay works correctly end-to-end</done>
-</task>
-
-</tasks>
-
-<verification>
-1. Cmd+K/Ctrl+K opens overlay from any page (Dashboard, Brain, Apps, etc.)
-2. Search returns results from all data sources that have matching content
-3. Results are visually grouped by source with icons and highlighted snippets
-4. Keyboard navigation (arrows + Enter + Escape) works fluidly
-5. Click navigation closes overlay and lands on correct deep-linked page
-6. Empty and loading states render correctly
-7. Client build succeeds: `cd client && npx vite build`
-</verification>
-
-<success_criteria>
-- Cmd+K / Ctrl+K opens search overlay from any page in PortOS
-- Typing 2+ chars triggers debounced search, results appear grouped by source
-- Each result shows icon, title, snippet with keyword highlighted
-- Arrow keys navigate results, Enter opens deep link, Escape closes
-- Clicking result navigates to URL and closes overlay
-- Clicking backdrop dismisses overlay
-- No-results and loading states render appropriately
-- Client builds without errors
-- Human verification approved
-</success_criteria>
-
-<output>
-After completion, create `.planning/phases/05-unified-search/05-02-SUMMARY.md`
-</output>
diff --git a/.planning/phases/05-unified-search/05-02-SUMMARY.md b/.planning/phases/05-unified-search/05-02-SUMMARY.md
deleted file mode 100644
index e7c9ca5eef..0000000000
--- a/.planning/phases/05-unified-search/05-02-SUMMARY.md
+++ /dev/null
@@ -1,126 +0,0 @@
----
-phase: 05-unified-search
-plan: 02
-subsystem: ui
-tags: [react, tailwind, lucide-react, react-portal, keyboard-navigation, debounce]
-
-# Dependency graph
-requires:
- - phase: 05-unified-search plan 01
- provides: fanOutSearch service, GET /api/search route, search() client function returning grouped Source[] results
-
-provides:
- - Cmd+K / Ctrl+K global keyboard shortcut opens search overlay from any page
- - CmdKSearch.jsx portal-based Spotlight-style modal with debounced search-as-you-type
- - useCmdKSearch.js hook for open/close state and keyboard shortcut registration
- - Grouped results display with icons, bold titles, keyword-highlighted snippets
- - Full keyboard navigation (ArrowDown/ArrowUp/Enter/Escape) and click navigation
- - Body scroll lock when overlay is open
- - No-results and loading states
- - "Show more" per-source expansion (3 results collapsed, all on expand)
-
-affects:
- - Any future search enhancements (semantic, filtering, recents)
- - Layout.jsx (CmdKSearch mounted here permanently)
-
-# Tech tracking
-tech-stack:
- added: []
- patterns:
- - React portal for z-index-isolated overlay rendering (createPortal to document.body)
- - useEffect + setTimeout/clearTimeout debounce pattern (no external library)
- - Flat result list computed from grouped API response for keyboard navigation index tracking
- - Inline Highlight component using case-insensitive regex to wrap matched text in <mark>
-
-key-files:
- created:
- - client/src/hooks/useCmdKSearch.js
- - client/src/components/CmdKSearch.jsx
- modified:
- - client/src/components/Layout.jsx
- - .changelog/v1.14.x.md
-
-key-decisions:
- - "CmdKSearch renders via createPortal(document.body) for z-index isolation above sidebar"
- - "Flat result list derived from grouped sources to track focusedIndex across categories"
- - "300ms debounce threshold, 2+ character minimum — matches Spotlight/Raycast UX conventions"
- - "Top 3 results per source shown by default with Show More to expand — avoids overwhelming long lists"
- - "focusedIndex resets to 0 on every new results update to prevent stale selection"
- - "Cmd+K fires even when an input is focused — deliberate Spotlight-parity behavior"
-
-patterns-established:
- - "Portal overlay pattern: render via createPortal to escape stacking context, onClick backdrop to dismiss"
- - "Debounce pattern: useEffect cleanup with clearTimeout, no lodash/external lib needed"
- - "Keyboard navigation: flat index over grouped data, ArrowDown/Up clamp to bounds, Enter navigates"
-
-requirements-completed: [SRC-01, SRC-03, SRC-04]
-
-# Metrics
-duration: ~15min
-completed: 2026-02-27
----
-
-# Phase 5 Plan 02: Cmd+K Search Overlay UI Summary
-
-**Spotlight-style Cmd+K search overlay with grouped results, keyword highlighting, full keyboard navigation, and React portal rendering — wired into the Layout shell and backed by the Phase 05-01 fan-out search API**
-
-## Performance
-
-- **Duration:** ~15 min
-- **Started:** 2026-02-27T00:01:05Z
-- **Completed:** 2026-02-27T00:20:00Z
-- **Tasks:** 3 (2 auto + 1 human-verify checkpoint)
-- **Files modified:** 4
-
-## Accomplishments
-- Built `useCmdKSearch.js` hook registering global Cmd+K / Ctrl+K shortcut to toggle overlay open state
-- Built `CmdKSearch.jsx` — full Spotlight-style modal with debounced search, grouped source results, inline keyword highlighting, body scroll lock, and deep-link navigation via `useNavigate`
-- Mounted `<CmdKSearch />` in `Layout.jsx` so the overlay is available on every page route
-
-## Task Commits
-
-Each task was committed atomically:
-
-1. **Task 1: Create Cmd+K hook and search overlay component** - `8cdbee1` (feat)
-2. **Task 2: Mount CmdKSearch in Layout.jsx** - `22484ed` (feat)
-3. **Task 3: Human-verify checkpoint** - approved by user
-
-## Files Created/Modified
-- `client/src/hooks/useCmdKSearch.js` - Global Cmd+K/Ctrl+K keyboard shortcut hook returning `{ open, setOpen }`
-- `client/src/components/CmdKSearch.jsx` - Spotlight-style search overlay: portal, debounce, grouped results, highlights, keyboard navigation
-- `client/src/components/Layout.jsx` - Added `<CmdKSearch />` mount point
-- `.changelog/v1.14.x.md` - Documented Cmd+K unified search feature
-
-## Decisions Made
-- `createPortal(document.body)` used for z-index isolation so the overlay renders above the sidebar regardless of stacking context
-- Flat result list derived from grouped `sources[]` response to keep `focusedIndex` as a simple number across all categories
-- 2-character minimum + 300ms debounce matches Spotlight/Raycast conventions (fast enough to feel instant, avoids noise on single char)
-- Default 3 results per source with "Show more" keeps the overlay compact — full expansion available per-source
-- Cmd+K fires in input context intentionally — search is a global action with highest priority (Spotlight parity)
-- `focusedIndex` resets to 0 on every results change to prevent stale selection after query changes
-
-## Deviations from Plan
-
-None — plan executed exactly as written.
-
-## Issues Encountered
-
-None.
-
-## User Setup Required
-
-None — no external service configuration required.
-
-## Next Phase Readiness
-- Phase 5 is now fully complete: server fan-out search (Plan 01) + Cmd+K overlay UI (Plan 02) are both shipped
-- All five phases of the PortOS milestone are complete
-- Future search enhancements (semantic search, recent queries, filter by source) can be layered onto the existing `/api/search` route and `CmdKSearch.jsx` component
-
----
-*Phase: 05-unified-search*
-*Completed: 2026-02-27*
-
-## Self-Check: PASSED
-- FOUND: .planning/phases/05-unified-search/05-02-SUMMARY.md
-- FOUND: commit 8cdbee1 (Task 1: Cmd+K hook and overlay component)
-- FOUND: commit 22484ed (Task 2: Mount CmdKSearch in Layout.jsx)
diff --git a/.planning/phases/05-unified-search/05-CONTEXT.md b/.planning/phases/05-unified-search/05-CONTEXT.md
deleted file mode 100644
index 4a15323db8..0000000000
--- a/.planning/phases/05-unified-search/05-CONTEXT.md
+++ /dev/null
@@ -1,65 +0,0 @@
-# Phase 5: Unified Search (Cmd+K) - Context
-
-**Gathered:** 2026-02-26
-**Status:** Ready for planning
-
-<domain>
-## Phase Boundary
-
-Global search overlay accessible from any page via Cmd+K / Ctrl+K. Fans out keyword queries server-side to all data sources (Brain, Memory, Apps, History, Health, etc.), displays categorized results with icons and snippets, and navigates to deep-linked locations on click. Semantic/vector search and search history are deferred to v2.
-
-</domain>
-
-<decisions>
-## Implementation Decisions
-
-### Overlay appearance
-- Spotlight-style centered modal (like macOS Spotlight / VS Code Cmd+P)
-- ~800px wide for comfortable snippet display
-- Semi-transparent dark backdrop — click backdrop to dismiss
-- Subtle fade+scale animation (~150ms) on open/close
-
-### Result presentation
-- Results grouped by source under section headers (Brain, Memory, Apps, Health, etc.)
-- Top 3 results per source category, with "Show more" to expand
-- Each result row: source icon + title (bold) + 1-line text snippet with keyword highlighted
-- Categories with zero results are hidden entirely
-
-### Search interaction
-- Full keyboard navigation: arrow keys move highlight, Enter navigates, Escape closes
-- Search-as-you-type after 2+ characters with 300ms debounce
-- Before typing: empty results area with placeholder hint ("Search Brain, Memory, Health...")
-- No-results state: subtle centered "No results for 'xyz'" message
-
-### Claude's Discretion
-- Deep-link navigation behavior (close overlay on click, scroll-to-item, cross-page handling)
-- Loading/spinner state while results are fetching
-- Exact source icons per category
-- Result highlight/hover styling
-- Which existing service search functions to fan out to
-
-</decisions>
-
-<specifics>
-## Specific Ideas
-
-- Overlay should feel like Raycast/Spotlight — fast, focused, keyboard-first
-- Source grouping similar to Raycast's category sections with clear headers
-- Keep it simple for v1 — no filters, no tabs, just type and find
-
-</specifics>
-
-<deferred>
-## Deferred Ideas
-
-- Semantic/vector search layered on keyword search (SRC-05, v2)
-- Recent searches and search history (SRC-06, v2)
-- Quick actions or recent items shown before typing
-- Source filtering tabs or toggles
-
-</deferred>
-
----
-
-*Phase: 05-unified-search*
-*Context gathered: 2026-02-26*
diff --git a/.planning/phases/05-unified-search/05-RESEARCH.md b/.planning/phases/05-unified-search/05-RESEARCH.md
deleted file mode 100644
index a815159a8a..0000000000
--- a/.planning/phases/05-unified-search/05-RESEARCH.md
+++ /dev/null
@@ -1,498 +0,0 @@
-# Phase 5: Unified Search (Cmd+K) - Research
-
-**Researched:** 2026-02-26
-**Domain:** Global keyboard shortcut overlay, server-side fan-out search, React keyboard event handling, deep-link navigation
-**Confidence:** HIGH
-
-## Summary
-
-Phase 5 adds a Spotlight/Raycast-style Cmd+K search overlay that fans out keyword queries to all PortOS data sources server-side and navigates to deep-linked results. The core technology challenge is trivially solved by existing PortOS infrastructure: BM25 keyword search already exists in `memoryBM25.js`, all data services expose list/query functions that can be text-filtered, and React Router already provides the deep-link URLs for every page. There is zero new library dependency required.
-
-The overlay UI is a straightforward React portal with a global `keydown` listener on `document`, debounced input, and result rendering. The server-side route is a single `GET /api/search?q=...` endpoint that fans out to five source adapters using `Promise.allSettled` for fault isolation. Each adapter performs case-insensitive substring matching against the relevant service data, returning up to 3 results with a `url` deep-link field the client navigates to with `react-router-dom`'s `useNavigate`.
-
-**Primary recommendation:** Build one new route file (`server/routes/search.js`), one new service file (`server/services/search.js`), one overlay component (`client/src/components/CmdKSearch.jsx`), and one custom hook (`client/src/hooks/useCmdKSearch.js`). Wire the overlay into `Layout.jsx` using a portal. Total new code is under 400 lines.
-
----
-
-<user_constraints>
-## User Constraints (from CONTEXT.md)
-
-### Locked Decisions
-
-**Overlay appearance**
-- Spotlight-style centered modal (like macOS Spotlight / VS Code Cmd+P)
-- ~800px wide for comfortable snippet display
-- Semi-transparent dark backdrop — click backdrop to dismiss
-- Subtle fade+scale animation (~150ms) on open/close
-
-**Result presentation**
-- Results grouped by source under section headers (Brain, Memory, Apps, History, Health, etc.)
-- Top 3 results per source category, with "Show more" to expand
-- Each result row: source icon + title (bold) + 1-line text snippet with keyword highlighted
-- Categories with zero results are hidden entirely
-
-**Search interaction**
-- Full keyboard navigation: arrow keys move highlight, Enter navigates, Escape closes
-- Search-as-you-type after 2+ characters with 300ms debounce
-- Before typing: empty results area with placeholder hint ("Search Brain, Memory, Health...")
-- No-results state: subtle centered "No results for 'xyz'" message
-
-### Claude's Discretion
-- Deep-link navigation behavior (close overlay on click, scroll-to-item, cross-page handling)
-- Loading/spinner state while results are fetching
-- Exact source icons per category
-- Result highlight/hover styling
-- Which existing service search functions to fan out to
-
-### Deferred Ideas (OUT OF SCOPE)
-- Semantic/vector search layered on keyword search (SRC-05, v2)
-- Recent searches and search history (SRC-06, v2)
-- Quick actions or recent items shown before typing
-- Source filtering tabs or toggles
-</user_constraints>
-
----
-
-<phase_requirements>
-## Phase Requirements
-
-| ID | Description | Research Support |
-|----|-------------|-----------------|
-| SRC-01 | Cmd+K / Ctrl+K opens search overlay from any page | Global `keydown` listener in `Layout.jsx` via custom hook; React portal for overlay rendering above all page content |
-| SRC-02 | Server-side `/api/search` endpoint fans out keyword queries to existing service search functions | `GET /api/search?q=` route with `Promise.allSettled` fan-out to adapters wrapping brain, memory, apps, history, and health services |
-| SRC-03 | Results categorized by source with icons and snippets | Server returns `{ sources: [{ id, label, icon, results: [{id, title, snippet, url}] }] }`; client renders grouped sections using Lucide icons already imported in Layout |
-| SRC-04 | Click result navigates to deep-linked location | Each result carries a `url` field; client calls `navigate(url)` from `react-router-dom` and closes overlay |
-</phase_requirements>
-
----
-
-## Standard Stack
-
-### Core
-| Library | Version | Purpose | Why Standard |
-|---------|---------|---------|--------------|
-| React 18 | ^18.3.1 (installed) | Overlay component, hooks, portal | Already in project |
-| react-router-dom | ^7.1.1 (installed) | `useNavigate` for deep-link navigation | Already in project |
-| lucide-react | ^0.562.0 (installed) | Source icons per category | Already in project |
-| Zod | installed | Validate `q` query param in search route | Already used throughout server |
-| Vitest + supertest | installed | Unit tests for search service and route | Already in project (`cd server && npm test`) |
-
-### Supporting
-| Library | Version | Purpose | When to Use |
-|---------|---------|---------|-------------|
-| `react-hot-toast` | ^2.6.0 (installed) | Error toasts if search API fails | Already in project |
-
-### Alternatives Considered
-| Instead of | Could Use | Tradeoff |
-|------------|-----------|----------|
-| Custom keyword filter functions | Fuse.js / MiniSearch | No new dependency needed; substring match is sufficient for v1 keyword search |
-| React portal | Modal inside page tree | Portal ensures overlay renders above sidebar/header z-index without CSS escalation |
-| `Promise.allSettled` | `Promise.all` | `allSettled` prevents one failing source from hiding all others |
-
-**Installation:**
-```bash
-# No new dependencies required — all libraries already installed
-```
-
----
-
-## Architecture Patterns
-
-### Recommended Project Structure
-```
-server/
-├── routes/search.js # GET /api/search?q= — fan-out route (NEW)
-├── services/search.js # Source adapters with keyword matching (NEW)
-└── lib/validation.js # Add searchQuerySchema (existing file, add export)
-
-client/src/
-├── components/CmdKSearch.jsx # Overlay modal component (NEW)
-├── hooks/useCmdKSearch.js # Keyboard shortcut + open/close state (NEW)
-├── services/api.js # Add search() function (existing file, add export)
-└── components/Layout.jsx # Mount <CmdKSearch /> + call useCmdKSearch (existing file, add lines)
-```
-
-### Pattern 1: Server Fan-out with Promise.allSettled
-
-**What:** A single endpoint calls all source adapters in parallel. Each adapter returns `{ id, label, icon, results }`. Failed adapters return empty results, not errors.
-
-**When to use:** When querying heterogeneous sources that may have independent failure modes.
-
-**Example:**
-```js
-// server/services/search.js
-export async function fanOutSearch(query) {
- const adapters = [
- searchBrainInbox(query),
- searchBrainEntities(query),
- searchMemory(query),
- searchApps(query),
- searchHistory(query),
- searchHealth(query),
- ];
- const settled = await Promise.allSettled(adapters);
- return settled
- .map((r, i) => r.status === 'fulfilled' ? r.value : { ...EMPTY_SOURCE[i] })
- .filter(s => s.results.length > 0);
-}
-```
-
-### Pattern 2: Keyword Snippet Extraction
-
-**What:** Extract a 80-100 char snippet around the first keyword match, bolding the matched term client-side.
-
-**When to use:** For all text fields where a result title alone lacks context.
-
-**Example:**
-```js
-// server/services/search.js
-function extractSnippet(text, query, maxLen = 100) {
- if (!text) return '';
- const lower = text.toLowerCase();
- const idx = lower.indexOf(query.toLowerCase());
- if (idx === -1) return text.substring(0, maxLen);
- const start = Math.max(0, idx - 30);
- const end = Math.min(text.length, start + maxLen);
- const snippet = text.substring(start, end);
- return (start > 0 ? '...' : '') + snippet + (end < text.length ? '...' : '');
-}
-```
-
-### Pattern 3: React Portal Overlay with Global Keydown
-
-**What:** Mount overlay via `createPortal(document.body)` so it renders above sidebar z-index. Register a single `keydown` listener on `document` in a hook.
-
-**When to use:** Global keyboard shortcut modals that must render above all page structure.
-
-**Example:**
-```jsx
-// client/src/hooks/useCmdKSearch.js
-import { useState, useEffect } from 'react';
-
-export function useCmdKSearch() {
- const [open, setOpen] = useState(false);
-
- useEffect(() => {
- const handler = (e) => {
- if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
- e.preventDefault();
- setOpen(prev => !prev);
- }
- };
- document.addEventListener('keydown', handler);
- return () => document.removeEventListener('keydown', handler);
- }, []);
-
- return { open, setOpen };
-}
-```
-
-```jsx
-// client/src/components/CmdKSearch.jsx (mount point in Layout.jsx)
-import { createPortal } from 'react-dom';
-// ... render portal into document.body
-```
-
-### Pattern 4: Keyword Highlight in React
-
-**What:** Split result snippet on the search query and wrap matched spans with highlight styling.
-
-**When to use:** All result snippet display.
-
-**Example:**
-```jsx
-// Highlight component — no external library needed
-function Highlight({ text, query }) {
- if (!query || !text) return <span>{text}</span>;
- const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
- const parts = text.split(regex);
- return (
- <span>
- {parts.map((part, i) =>
- regex.test(part)
- ? <mark key={i} className="bg-port-accent/30 text-white rounded px-0.5">{part}</mark>
- : <span key={i}>{part}</span>
- )}
- </span>
- );
-}
-```
-
-### Pattern 5: Keyboard Navigation in Result List
-
-**What:** Track `focusedIndex` state; ArrowDown/ArrowUp increment/decrement; Enter calls `navigate(results[focusedIndex].url)`.
-
-**When to use:** Command palette-style overlays.
-
-**Example:**
-```jsx
-const [focusedIndex, setFocusedIndex] = useState(0);
-
-const handleKeyDown = (e) => {
- const total = flatResults.length;
- if (e.key === 'ArrowDown') { e.preventDefault(); setFocusedIndex(i => Math.min(i + 1, total - 1)); }
- if (e.key === 'ArrowUp') { e.preventDefault(); setFocusedIndex(i => Math.max(i - 1, 0)); }
- if (e.key === 'Enter' && flatResults[focusedIndex]) {
- navigate(flatResults[focusedIndex].url);
- setOpen(false);
- }
- if (e.key === 'Escape') setOpen(false);
-};
-```
-
-### Anti-Patterns to Avoid
-- **Mounting overlay inside a page component:** Results in z-index battles with sidebar and header. Always use a portal.
-- **Using `window.location.href` for navigation:** Violates CLAUDE.md (no hardcoded localhost). Use `useNavigate()` and relative paths.
-- **`Promise.all` for fan-out:** One failing service throws, swallowing all results. Use `Promise.allSettled`.
-- **Showing raw IDs as titles:** Health data (day-partitioned files) has no "title" — synthesize a title from metric name + date.
-- **Firing search on every keystroke:** Debounce 300ms after 2+ chars per CONTEXT.md decision.
-
----
-
-## Don't Hand-Roll
-
-| Problem | Don't Build | Use Instead | Why |
-|---------|-------------|-------------|-----|
-| BM25 keyword scoring for memory | Custom text search | `memoryBM25.searchBM25()` already in `server/services/memoryBM25.js` | Full BM25 implementation with inverted index already exists |
-| Deep-link URL construction | Custom URL builder | Existing route patterns from `App.jsx` (e.g., `/brain/inbox`, `/cos/memory`) | All routes are already documented in the existing router |
-| Overlay animation | CSS transition library | Tailwind `transition transform duration-150` classes | No animation library needed; project already uses Tailwind |
-| Fuzzy matching | Fuse.js | Simple `toLowerCase().includes()` | v1 uses keyword match per CONTEXT.md; semantic search is deferred |
-
-**Key insight:** Every required primitive already exists in the codebase. This phase is purely assembly work.
-
----
-
-## Common Pitfalls
-
-### Pitfall 1: Forgetting `inputRef.focus()` when overlay opens
-**What goes wrong:** User presses Cmd+K, overlay appears, but focus is still on the previous element — user starts typing and nothing happens.
-**Why it happens:** The input doesn't auto-focus on mount.
-**How to avoid:** `useEffect(() => { if (open) inputRef.current?.focus(); }, [open])` in the overlay component.
-**Warning signs:** Manual tab-to-input required after opening.
-
-### Pitfall 2: Body scroll not locked when overlay is open
-**What goes wrong:** User can scroll the page behind the overlay, causing disorientation.
-**Why it happens:** Overlay doesn't set `document.body.style.overflow = 'hidden'`.
-**How to avoid:** `useEffect(() => { document.body.style.overflow = open ? 'hidden' : ''; return () => { document.body.style.overflow = ''; }; }, [open])`.
-**Warning signs:** Background page scrolls when user presses arrow keys in overlay.
-
-### Pitfall 3: Health data has no "item title" for deep-linking
-**What goes wrong:** Health data is partitioned by date file (`data/health/YYYY-MM-DD.json`); there are no individual "health entries" with IDs to navigate to.
-**Why it happens:** Health is metric-series data, not document data.
-**How to avoid:** Health search results deep-link to `/meatspace/health` (the tab) with the metric name as context, not to a specific entry. Title = "{MetricName} on {date}". URL = `/meatspace/health` (or the closest tab with that data visible).
-**Warning signs:** Attempting to navigate to a non-existent `/health/entry/:id` route.
-
-### Pitfall 4: Memory search returns IDs; need full content for snippets
-**What goes wrong:** `memoryBM25.searchBM25(query)` returns `[{id, score}]` — no content for snippet display.
-**Why it happens:** BM25 index stores only document IDs and inverted index terms, not original content.
-**How to avoid:** After BM25 returns IDs, fetch memory content from `memory.getMemory(id)` or from the index (which stores `summary` but not full content). Use `summary` field from the memory index as the snippet — it's already truncated to 150 chars.
-**Warning signs:** Blank snippets in Memory results.
-
-### Pitfall 5: Arrow key navigation must reset `focusedIndex` on new query
-**What goes wrong:** User types query, navigates to index 5, types more, but focused item is still index 5 even though results changed.
-**Why it happens:** `focusedIndex` isn't reset when `results` change.
-**How to avoid:** `useEffect(() => { setFocusedIndex(0); }, [results])`.
-**Warning signs:** Enter navigates to wrong result after editing the search query.
-
-### Pitfall 6: Cmd+K fires inside `<input>` or `<textarea>` elements
-**What goes wrong:** User presses Cmd+K while typing in Brain capture or a form field and the search overlay interrupts their work.
-**Why it happens:** Global `keydown` listener doesn't check the event target.
-**How to avoid:** In the handler, skip if `e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable` — OR check if the user has the QuickBrainCapture input focused. VS Code and Raycast do NOT suppress Cmd+K in inputs; it is a reasonable tradeoff to open the overlay anyway for consistency. Either approach is valid; document the choice.
-**Warning signs:** Unexpected overlay opening during form interaction.
-
----
-
-## Code Examples
-
-Verified patterns from project codebase:
-
-### Existing BM25 search (server/services/memoryBM25.js)
-```js
-// Already exists — call directly from search adapter
-const memoryIds = await searchBM25(query, { limit: 20, threshold: 0.1 });
-// Returns: [{ id: string, score: number }]
-// Then load summary from memory index for snippet
-```
-
-### Existing brain entities (server/services/brainStorage.js)
-```js
-// All entity stores exposed via storage functions
-const people = await storage.getPeople(); // { records: { [id]: {..., name, notes} } }
-const projects = await storage.getProjects(); // { records: { [id]: {..., name, description} } }
-const ideas = await storage.getIdeas(); // { records: { [id]: {..., title, description} } }
-// Inline keyword filter:
-const q = query.toLowerCase();
-const matches = Object.values(store.records)
- .filter(r => r.name?.toLowerCase().includes(q) || r.description?.toLowerCase().includes(q));
-```
-
-### Existing history service (server/services/history.js)
-```js
-// getHistory already returns entries array — just filter client-side in the adapter
-const { entries } = await getHistory({ limit: 500 });
-const matches = entries.filter(e =>
- e.targetName?.toLowerCase().includes(q) || e.action?.toLowerCase().includes(q)
-);
-// Deep-link: /devtools/history (no per-entry deep link exists — link to history page)
-```
-
-### Existing apps service (server/services/apps.js)
-```js
-const apps = await getAllApps({ includeArchived: false });
-const matches = apps.filter(a =>
- a.name?.toLowerCase().includes(q) || a.description?.toLowerCase().includes(q)
-);
-// Deep-link: /apps (no per-app route exists without app ID in URL param)
-```
-
-### Server route registration pattern (server/index.js)
-```js
-// Pattern to follow when adding search route:
-import searchRoutes from './routes/search.js';
-// ...
-app.use('/api/search', searchRoutes);
-```
-
-### API service client pattern (client/src/services/api.js)
-```js
-// Pattern to follow for search() function:
-export const search = (q) => request(`/search?q=${encodeURIComponent(q)}`);
-```
-
-### Layout.jsx portal mount point
-```jsx
-// Layout.jsx already imports hooks and renders children via <Outlet />
-// Add CmdKSearch just before </div> that wraps the main content area:
-import CmdKSearch from './CmdKSearch';
-// ...inside Layout return:
-<CmdKSearch /> {/* renders via portal, no layout impact */}
-```
-
----
-
-## Source Adapter Map
-
-This is the complete map of data sources, their search functions, and their deep-link URLs:
-
-| Source | Category Label | Icon | Service Function | Filter Strategy | Deep-Link URL Pattern |
-|--------|---------------|------|-----------------|----------------|----------------------|
-| Brain Inbox | Brain | `Brain` | `brainStorage.getInboxLog({ limit: 200 })` | filter on `text` field | `/brain/inbox` |
-| Brain People | Brain | `Brain` | `brainStorage.getPeople()` | filter on `name`, `notes` | `/brain/inbox` (no per-person route in current App.jsx) |
-| Brain Projects | Brain | `Brain` | `brainStorage.getProjects()` | filter on `name`, `description` | `/brain/inbox` (no per-project route) |
-| Brain Ideas | Brain | `Brain` | `brainStorage.getIdeas()` | filter on `title`, `description` | `/brain/inbox` (no per-idea route) |
-| Brain Links | Brain | `Brain` | `brainStorage.getLinks()` | filter on `title`, `url`, `description` | `/brain/inbox` |
-| CoS Memory | Memory | `Brain` (or `Cpu`) | `memoryBM25.searchBM25(q, {limit: 10})` then `memory.getMemory(id)` for summary | BM25 scoring | `/cos/memory` |
-| Apps | Apps | `Package` | `apps.getAllApps({includeArchived: false})` | substring on `name`, `description` | `/apps` |
-| History | History | `History` | `history.getHistory({limit: 500})` | substring on `targetName`, `action` | `/devtools/history` |
-| Health | Health | `HeartPulse` | `appleHealthQuery.listDayFiles()` then filter by metric names in day files | metric name match | `/meatspace/health` |
-
-**Note:** Brain People/Projects/Ideas/Links all fall under the "Brain" category header and share the icon. The deep-link for all brain sub-entities currently routes to `/brain/inbox` since the Brain page uses tab-based routing but no per-entity URL scheme (items are modal-less, opened inline within lists). This is correct per CLAUDE.md ("Linkable routes for all views" — but the entities don't currently have per-item deep URLs).
-
----
-
-## Data Structures
-
-### Server response shape for `GET /api/search?q=foo`
-```json
-{
- "query": "foo",
- "sources": [
- {
- "id": "brain",
- "label": "Brain",
- "icon": "Brain",
- "results": [
- {
- "id": "abc-123",
- "title": "Project: Foo App",
- "snippet": "...working on foo app to solve...",
- "url": "/brain/inbox",
- "type": "project"
- }
- ]
- },
- {
- "id": "memory",
- "label": "Memory",
- "icon": "Cpu",
- "results": [...]
- }
- ]
-}
-```
-
-### Zod validation for search route
-```js
-// server/lib/validation.js (add to existing file)
-export const searchQuerySchema = z.object({
- q: z.string().min(2).max(200).trim()
-});
-```
-
----
-
-## State of the Art
-
-| Old Approach | Current Approach | When Changed | Impact |
-|--------------|------------------|--------------|--------|
-| Client-side search index | Server fan-out | Per REQUIREMENTS.md decision (2026-02-26) | Simpler, consistent with data living server-side; per Out of Scope: "Client-side search indexing: Data lives server-side; server fan-out is simpler and consistent" |
-| Semantic/vector search | Keyword-first (BM25 + substring) | Per REQUIREMENTS.md decision (2026-02-26) | Ships faster; semantic layers on later via existing infra |
-
-**Deprecated/outdated:**
-- None applicable to this phase.
-
----
-
-## Open Questions
-
-1. **Brain entity deep-links: currently no per-item routes in App.jsx**
- - What we know: Brain page (`/brain/:tab`) uses tab-based routing. Individual inbox entries, people, projects, ideas are expanded/edited inline within the tab, not at unique URLs.
- - What's unclear: Should a brain search result link to `/brain/inbox?id=abc-123` (a new URL pattern we'd need to support in Brain.jsx) or just `/brain/inbox`?
- - Recommendation: For v1, link all brain results to `/brain/inbox` (no per-item URL). The user lands on Brain Inbox and can search there. If deep-linking to specific items is desired, that's a Brain page enhancement orthogonal to this phase.
-
-2. **Memory results: summary vs full content for snippets**
- - What we know: `memoryBM25.searchBM25(q)` returns `[{id, score}]`. The memory index stores `summary` (150 char truncated) per item but the full content requires loading the per-item file.
- - What's unclear: Whether loading 3-10 full memory files per search is acceptable latency.
- - Recommendation: Use `summary` from the index. It's already 150 chars and purpose-built for preview display. No extra file reads needed.
-
-3. **Health search semantics: no text content to match**
- - What we know: Health data is numeric time-series. Day files contain metric name strings (e.g., `step_count`, `heart_rate`).
- - What's unclear: What query would a user type to find health data? Probably the metric name or a synonym.
- - Recommendation: Match the query against known metric names (`step_count`, `heart_rate`, `sleep_analysis`, `hrv`). Return one result per matched metric name, linking to `/meatspace/health`. This is a simple hardcoded metric name list or dynamic from `listDayFiles()` scanning.
-
----
-
-## Validation Architecture
-
-> `workflow.nyquist_validation` is not set to `true` in `.planning/config.json` — this section is omitted.
-
----
-
-## Sources
-
-### Primary (HIGH confidence)
-- Direct codebase inspection — `server/services/memoryBM25.js`, `server/services/brain.js`, `server/services/memory.js`, `server/services/history.js`, `server/services/apps.js`, `server/services/appleHealthQuery.js` — confirmed existing search/list functions and data structures
-- `client/src/App.jsx` — confirmed all deep-link URL patterns
-- `client/src/components/Layout.jsx` — confirmed icon imports, hook patterns, portal mount approach
-- `server/index.js` — confirmed route registration pattern
-- `client/src/services/api.js` — confirmed client API helper pattern
-- `client/package.json` — confirmed React 18, react-router-dom 7, lucide-react, tailwindcss versions
-
-### Secondary (MEDIUM confidence)
-- React 18 `createPortal` pattern for global overlays — standard React docs pattern, widely verified
-- `document.addEventListener('keydown', handler)` for global Cmd+K — standard browser API, no verification needed
-
-### Tertiary (LOW confidence)
-- None — all findings verified against live codebase
-
----
-
-## Metadata
-
-**Confidence breakdown:**
-- Standard stack: HIGH — all libraries already installed, versions confirmed from package.json
-- Architecture: HIGH — all service functions confirmed via direct file reads, patterns match existing project conventions
-- Pitfalls: HIGH — identified from actual data structure constraints (BM25 returns IDs not content, health has no entity URLs, etc.)
-
-**Research date:** 2026-02-26
-**Valid until:** 2026-03-28 (stable — no fast-moving dependencies)
diff --git a/.planning/phases/05-unified-search/05-VERIFICATION.md b/.planning/phases/05-unified-search/05-VERIFICATION.md
deleted file mode 100644
index 879ebd82e2..0000000000
--- a/.planning/phases/05-unified-search/05-VERIFICATION.md
+++ /dev/null
@@ -1,186 +0,0 @@
----
-phase: 05-unified-search
-verified: 2026-02-27T00:30:00Z
-status: human_needed
-score: 15/15 must-haves verified
-human_verification:
- - test: "Press Cmd+K (Mac) or Ctrl+K from any page — Dashboard, Brain, Apps, etc."
- expected: "Spotlight-style search overlay opens centered with dark backdrop and ~800px modal"
- why_human: "Cannot verify visual appearance, animation (fade+scale 150ms), or z-index rendering above sidebar programmatically"
- - test: "Type 2+ characters, observe results"
- expected: "Results appear grouped by source (Brain, Memory, Apps, History, Health) each with section header, icon, bold title, and 1-line snippet with keyword highlighted in blue"
- why_human: "Cannot verify visual grouping, highlighting color correctness, or layout quality programmatically"
- - test: "Type 1 character, observe state"
- expected: "Placeholder hint 'Type 2+ characters to search...' is visible — no results shown"
- why_human: "UI state rendering requires browser"
- - test: "Press ArrowDown/ArrowUp while overlay is open with results"
- expected: "Blue highlight moves between result rows; focused row scrolls into view"
- why_human: "Cannot verify keyboard navigation visual feedback or scroll behavior programmatically"
- - test: "Press Enter on a highlighted result"
- expected: "Navigates to the result's deep-linked URL and closes the overlay"
- why_human: "Requires browser router navigation to verify end-to-end"
- - test: "Click a result row"
- expected: "Navigates to the result's deep-linked URL and overlay closes"
- why_human: "Requires browser interaction"
- - test: "Click the dark backdrop"
- expected: "Overlay dismisses"
- why_human: "Requires browser click interaction"
- - test: "Type a query with no matching data (e.g., 'zzznonexistent')"
- expected: "Centered 'No results for \"zzznonexistent\"' message is shown"
- why_human: "Requires live data and browser"
- - test: "Open overlay, verify page behind cannot scroll"
- expected: "Body scroll is locked while overlay is open; scrolling restores on close"
- why_human: "CSS overflow behavior requires browser verification"
- - test: "Type query with source returning 4+ results, observe Show more button"
- expected: "'Show N more' button appears; clicking it reveals all results for that source"
- why_human: "Requires live data with enough results to trigger expansion"
----
-
-# Phase 5: Unified Search — Verification Report
-
-**Phase Goal:** Any piece of information in PortOS is one keystroke away via a global search overlay
-**Verified:** 2026-02-27T00:30:00Z
-**Status:** human_needed (all automated checks passed; UI/UX behaviors require browser)
-**Re-verification:** No — initial verification
-
-## Goal Achievement
-
-### Observable Truths
-
-| # | Truth | Status | Evidence |
-|---|-------|--------|----------|
-| 1 | GET /api/search?q=foo returns categorized results from Brain, Memory, Apps, History, and Health sources | VERIFIED | `server/services/search.js` implements all 5 source adapters; `fanOutSearch` exports confirmed via Node import; `server/routes/search.js` wires the handler |
-| 2 | Each source result includes id, title, snippet, url, and type fields | VERIFIED | All 5 adapters map to `{ id, title, snippet, url, type }` — verified in `search.js` lines 59-64, 71-76, 83-88, 95-100, 110-117, 147-153, 168-173, 183-190, 228-236 |
-| 3 | Failed source adapters return empty results instead of failing the entire request | VERIFIED | `Promise.allSettled` used at `fanOutSearch` level (line 257) and within `searchBrain` (line 48) and `searchMemory` (line 132); `FALLBACKS` array provides empty-result objects on rejection |
-| 4 | Query param q is validated (min 2 chars, max 200, trimmed) | VERIFIED | `searchQuerySchema = z.object({ q: z.string().min(2).max(200).trim() })` confirmed at `server/lib/validation.js` line 414; Node import confirmed export exists |
-| 5 | Snippets contain ~100 char window around the keyword match | VERIFIED | `extractSnippet()` at `search.js` line 26 finds first match index, extracts `start = max(0, idx-30)`, `end = min(text.length, start+100)`, prepends/appends `...` as needed |
-| 6 | Sources with zero results are omitted from the response | VERIFIED | `const nonEmpty = sources.filter(s => s.results.length > 0)` at `search.js` line 275; only `nonEmpty` is returned |
-| 7 | Pressing Cmd+K or Ctrl+K from any page opens a search overlay | VERIFIED (logic) | `useCmdKSearch.js` listens on `document.addEventListener('keydown', handler)` checking `(e.metaKey || e.ctrlKey) && e.key === 'k'`; `CmdKSearch` is mounted in `Layout.jsx` (line 544) so it is present on every route |
-| 8 | Typing 2+ characters triggers debounced search-as-you-type | VERIFIED (logic) | `CmdKSearch.jsx` uses `useEffect` with `setTimeout`/`clearTimeout` at 300ms when `query.length >= 2` (lines 59-74) |
-| 9 | Results are grouped by source with section headers, icons, and text snippets | VERIFIED (logic) | `results.map(source => ...)` renders source header with `SourceIcon` + `source.label` then iterates `visible` results; `ICON_MAP` maps icon string to Lucide component |
-| 10 | Keyword matches are highlighted in result snippets | VERIFIED (logic) | `Highlight` component (lines 10-23) splits on case-insensitive regex and wraps matches in `<mark className="bg-port-accent/30 ...">` |
-| 11 | Arrow keys move selection highlight, Enter navigates to result URL, Escape closes overlay | VERIFIED (logic) | `handleKeyDown` at lines 101-114 handles `ArrowDown`, `ArrowUp`, `Enter` (calls `handleNavigate(item.url)`), `Escape` (calls `close()`) |
-| 12 | Clicking a result navigates to its deep-linked location and closes the overlay | VERIFIED (logic) | `onClick={() => handleNavigate(result.url)}` at line 197; `handleNavigate` calls `navigate(url)` then `close()` (lines 96-99) |
-| 13 | Clicking the backdrop dismisses the overlay | VERIFIED (logic) | Backdrop div has `onClick={close}` at line 130 |
-| 14 | Input auto-focuses when overlay opens | VERIFIED (logic) | `useEffect(() => { if (open) inputRef.current?.focus(); }, [open])` at lines 38-40 |
-| 15 | Body scroll is locked when overlay is open | VERIFIED (logic) | `useEffect(() => { document.body.style.overflow = open ? 'hidden' : ''; ... }, [open])` at lines 43-46 |
-
-**Score:** 15/15 truths verified (automated logic checks — browser validation listed in human verification section)
-
-### Required Artifacts
-
-| Artifact | Expected | Status | Details |
-|----------|----------|--------|---------|
-| `server/services/search.js` | Fan-out search engine with source adapters, exports `fanOutSearch` | VERIFIED | 248 lines, substantive; exports confirmed via Node import; 5 source adapters, `extractSnippet`, `fanOutSearch` |
-| `server/routes/search.js` | GET /api/search route handler | VERIFIED | 19 lines, wired to `fanOutSearch` and `searchQuerySchema`; registered in `server/index.js` |
-| `server/lib/validation.js` | Contains `searchQuerySchema` export | VERIFIED | `searchQuerySchema` at line 414; Node import confirms export exists |
-| `client/src/services/api.js` | `search(q)` client API function | VERIFIED | Line 44: `export const search = (q) => request('/search?q=${encodeURIComponent(q)}')` |
-| `client/src/hooks/useCmdKSearch.js` | Global Cmd+K keyboard shortcut hook, exports `useCmdKSearch` | VERIFIED | 15 lines, registers `keydown` listener, returns `{ open, setOpen }` |
-| `client/src/components/CmdKSearch.jsx` | Search overlay modal component with results display | VERIFIED | 234 lines, substantive; portal, debounce, grouped results, Highlight, keyboard nav, scroll lock |
-| `client/src/components/Layout.jsx` | Contains `CmdKSearch` mount | VERIFIED | Imports `CmdKSearch` (line 60); renders `<CmdKSearch />` (line 544) as sibling in root shell |
-
-### Key Link Verification
-
-| From | To | Via | Status | Details |
-|------|----|-----|--------|---------|
-| `server/routes/search.js` | `server/services/search.js` | `import fanOutSearch` | WIRED | Line 12: `import { fanOutSearch } from '../services/search.js'`; used at line 19 |
-| `server/routes/search.js` | `server/lib/validation.js` | `import searchQuerySchema` | WIRED | Line 11: `import { validateRequest, searchQuerySchema } from '../lib/validation.js'`; used at line 18 |
-| `server/index.js` | `server/routes/search.js` | `app.use('/api/search', searchRoutes)` | WIRED | Line 46 import; line 194 registration — placed alphabetically after `/api/screenshots` |
-| `client/src/components/Layout.jsx` | `client/src/components/CmdKSearch.jsx` | `import and render <CmdKSearch />` | WIRED | Import at line 60; render at line 544 |
-| `client/src/components/CmdKSearch.jsx` | `client/src/hooks/useCmdKSearch.js` | `import useCmdKSearch` | WIRED | Line 5: `import { useCmdKSearch } from '../hooks/useCmdKSearch'`; destructured at line 26 |
-| `client/src/components/CmdKSearch.jsx` | `client/src/services/api.js` | `import { search }` | WIRED | Line 6: `import { search } from '../services/api'`; called inside `setTimeout` at line 67 |
-| `client/src/components/CmdKSearch.jsx` | `react-router-dom` | `useNavigate()` for deep-link navigation | WIRED | Line 3 import; `navigate(url)` called at line 97 in `handleNavigate`; `handleNavigate` called on click (line 197) and Enter key (line 110) |
-
-### Requirements Coverage
-
-| Requirement | Source Plan | Description | Status | Evidence |
-|-------------|------------|-------------|--------|----------|
-| SRC-01 | 05-02-PLAN.md | Cmd+K / Ctrl+K opens search overlay from any page | SATISFIED | `useCmdKSearch.js` registers global `keydown` handler; `CmdKSearch` mounted in `Layout.jsx` for all routes |
-| SRC-02 | 05-01-PLAN.md | Server-side `/api/search` endpoint fans out keyword queries to existing service search functions | SATISFIED | `GET /api/search` route registered; `fanOutSearch` fans out to `brainStorage`, `memoryBM25`, `memory`, `apps`, `history` services via `Promise.allSettled` |
-| SRC-03 | 05-01-PLAN.md, 05-02-PLAN.md | Results categorized by source with icons and snippets | SATISFIED | Server returns `{ id, label, icon, results[] }`; client renders grouped by source with `ICON_MAP`, section headers, and `Highlight` component on snippets |
-| SRC-04 | 05-02-PLAN.md | Click result navigates to deep-linked location | SATISFIED | `handleNavigate(result.url)` called on click and Enter; each adapter assigns route-specific `url` (e.g., `/brain/inbox`, `/cos/memory`, `/apps`, `/devtools/history`, `/meatspace/health`) |
-
-All four phase requirements (SRC-01 through SRC-04) are claimed by plans and have verified implementation evidence. No orphaned requirements found.
-
-### Anti-Patterns Found
-
-| File | Line | Pattern | Severity | Impact |
-|------|------|---------|----------|--------|
-| `CmdKSearch.jsx` | 144-145 | HTML attribute named `placeholder` | Info | This is a legitimate HTML input `placeholder` attribute — not a stub pattern. No concern. |
-| `search.js` | 148 | `return null` inside `.map()` filter | Info | Used correctly to handle missing memory entries before `.filter(Boolean)` — not a stub. |
-| `CmdKSearch.jsx` | 116 | `if (!open) return null` | Info | Correct early-return pattern when overlay is closed — not a stub. |
-
-No blocker or warning anti-patterns found. All three flagged items are correct usage, not stubs.
-
-### Human Verification Required
-
-Ten items need browser verification. All automated logic checks passed — the implementations are substantive and wired. Human verification confirms the visual and interactive behaviors.
-
-**1. Overlay Opens on Cmd+K from Any Page**
-**Test:** Navigate to Dashboard, then press Cmd+K (Mac) or Ctrl+K (other OS)
-**Expected:** Centered dark-backdrop modal appears with ~800px width, visible search input, and Cmd+K badge in the top-right of the input row
-**Why human:** Visual appearance, animation quality (fade+scale), and z-index stacking above sidebar cannot be verified programmatically
-
-**2. Search Results Render Correctly**
-**Test:** Type "app" or "brain" (2+ chars) and observe results
-**Expected:** Results grouped by source with section header (icon + uppercase label), each result showing bold title and 1-line snippet with the matched keyword highlighted in blue
-**Why human:** Visual grouping layout, highlight color rendering, and text truncation require browser
-
-**3. Placeholder / Empty State**
-**Test:** Open overlay without typing
-**Expected:** Centered gray hint text "Type 2+ characters to search across Brain, Memory, Apps, History, and Health"
-**Why human:** Requires browser rendering
-
-**4. Keyboard Navigation Visual**
-**Test:** Open overlay, type 2+ chars, press ArrowDown repeatedly
-**Expected:** Blue accent highlight moves down result rows; row scrolls into view when off-screen
-**Why human:** CSS highlight class application and scroll behavior require browser
-
-**5. Enter Key Navigation**
-**Test:** Arrow-navigate to a result, press Enter
-**Expected:** Browser navigates to the result's deep-linked page (e.g., `/brain/inbox`, `/apps`) and overlay closes
-**Why human:** Requires live React Router navigation
-
-**6. Click Result Navigation**
-**Test:** Click any result row
-**Expected:** Navigates to the result's URL and overlay closes
-**Why human:** Requires browser click and router interaction
-
-**7. Backdrop Click Dismiss**
-**Test:** Click the dark area outside the modal
-**Expected:** Overlay closes immediately
-**Why human:** Requires browser click interaction
-
-**8. No-Results State**
-**Test:** Type a nonsense query like "zzzxyznonexistent"
-**Expected:** Centered message "No results for 'zzzxyznonexistent'" appears
-**Why human:** Requires live API call with real data returning empty
-
-**9. Body Scroll Lock**
-**Test:** Open overlay on a page with scrollable content; attempt to scroll
-**Expected:** Page scroll is locked while overlay is open; scrolling resumes after Escape or backdrop click
-**Why human:** CSS `overflow: hidden` on body needs browser verification
-
-**10. Show More Expansion**
-**Test:** Search for a term that returns more than 3 results in one source (e.g., search for a common app name or "brain")
-**Expected:** "Show N more" button appears below first 3 results; clicking it reveals all results for that source
-**Why human:** Requires live data with sufficient results to trigger the expansion threshold
-
-### Commit Verification
-
-All four task commits referenced in SUMMARY files are present in git history:
-- `226b850` — feat(05-01): create unified search service with fan-out adapters
-- `ea077ee` — feat(05-01): add search route, schema, index registration, and client API function
-- `8cdbee1` — feat(05-02): create Cmd+K search hook and overlay component
-- `22484ed` — feat(05-02): mount CmdKSearch in Layout.jsx
-
-### Summary
-
-Phase 5 goal is achieved at the code level. All 15 observable truths have verified logic implementations. All 7 required artifacts exist and are substantive (no stubs). All 7 key links are wired (imports used, connections functional). All 4 requirements (SRC-01 through SRC-04) are satisfied with implementation evidence.
-
-The 10 human verification items are standard browser/visual checks expected for any UI feature. No blockers, gaps, or orphaned requirements were found.
-
----
-
-_Verified: 2026-02-27T00:30:00Z_
-_Verifier: Claude (gsd-verifier)_
diff --git a/.planning/research/ARCHITECTURE.md b/.planning/research/ARCHITECTURE.md
deleted file mode 100644
index 875aafa646..0000000000
--- a/.planning/research/ARCHITECTURE.md
+++ /dev/null
@@ -1,367 +0,0 @@
-# Architecture Research
-
-**Domain:** Monorepo feature integration (backup, health ingest, cross-domain insights, unified search) into Express.js + React + PM2 + JSON file architecture
-**Researched:** 2026-02-26
-**Confidence:** HIGH — all five features follow well-established patterns and align with the existing PortOS architecture
-
-## System Overview
-
-```
-┌──────────────────────────────────────────────────────────────────────────────┐
-│ Client (React/Vite :5555) │
-│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌────────────────┐ │
-│ │ Cmd+K │ │ MeatSpace │ │ Insights │ │ Backup │ │
-│ │ Overlay │ │ Health Tab │ │ Page/Panel │ │ Status Widget │ │
-│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ └───────┬────────┘ │
-│ │ HTTP/WS │ HTTP │ HTTP │ HTTP │
-├─────────┴──────────────────┴─────────────────┴──────────────────┴───────────┤
-│ Express API Server (:5554) │
-│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌────────────────┐ │
-│ │ /api/search │ │ /api/ │ │ /api/ │ │ /api/backup │ │
-│ │ (fan-out) │ │ meatspace/ │ │ insights │ │ (CRUD + │ │
-│ │ │ │ health │ │ (read-only) │ │ trigger) │ │
-│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ └───────┬────────┘ │
-│ │ │ │ │ │
-│ ┌──────┴───────┐ ┌──────┴───────┐ ┌──────┴───────┐ ┌───────┴────────┐ │
-│ │ searchSvc │ │ appleHealth │ │ insightsSvc │ │ backupSvc │ │
-│ │ (aggregator)│ │ Svc (parse │ │ (correlate │ │ (scheduler + │ │
-│ │ │ │ + store) │ │ + derive) │ │ rsync/cp) │ │
-│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ └───────┬────────┘ │
-│ │ │ │ │ │
-├─────────┴──────────────────┴─────────────────┴──────────────────┴───────────┤
-│ Data Layer (./data/) │
-│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐ │
-│ │ brain/ │ │ meatspace│ │ digital- │ │ cos/ │ │ External │ │
-│ │ memory/ │ │ /health/ │ │ twin/ │ │ agents/ │ │ Drive Mount │ │
-│ │ apps.json│ │ genome/ │ │ │ │ runs/ │ │ │ │
-│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────────┘ │
-└──────────────────────────────────────────────────────────────────────────────┘
-```
-
-## Component Boundaries
-
-### New Components
-
-| Component | Responsibility | Communicates With | Files |
-|-----------|---------------|-------------------|-------|
-| **Backup Service** | Schedule and execute incremental backup of `./data/` to external drive; track run history and status | fileUtils, PM2 ecosystem (optional cron), Socket.IO for status | `server/services/backup.js`, `server/routes/backup.js` |
-| **Apple Health Ingest** | Accept POST with XML body from Health Auto Export app; stream-parse Apple Health XML; normalize and persist to JSON | meatspace data files, Zod validation, meatspaceHealth service | `server/services/appleHealth.js`, `server/routes/appleHealth.js` (or nested under meatspace routes) |
-| **Cross-Insights Engine** | Read from genome, health, taste, personality, and body data; compute derived correlations; cache results | genome service, digital-twin service, meatspace services, taste-questionnaire service (read-only consumers) | `server/services/insights.js`, `server/routes/insights.js` |
-| **Unified Search API** | Receive query, fan out to domain-specific search functions, merge and rank results, return unified response | memory service (BM25 + vector), brain service, genome service, apps service, history service, digital-twin service, meatspace services | `server/services/search.js`, `server/routes/search.js` |
-| **Cmd+K Overlay** | Client-side keyboard-triggered modal; debounced input; call unified search API; render categorized results with navigation | `services/api.js` (HTTP), React Router (for navigation to results) | `client/src/components/CommandPalette.jsx`, `client/src/hooks/useCommandPalette.js` |
-
-### Existing Components Touched
-
-| Component | Change | Impact |
-|-----------|--------|--------|
-| `server/index.js` | Mount 3-4 new route files | Minimal — follows existing import + `app.use()` pattern |
-| `client/src/components/Layout.jsx` | Render `<CommandPalette />` as a sibling to `<Outlet />` | Minimal — one component addition, global keyboard listener |
-| `server/lib/fileUtils.js` | No changes needed — `PATHS.meatspace` already exists | None |
-| `server/lib/meatspaceValidation.js` | Add Zod schemas for Apple Health ingest payloads | Additive |
-| `ecosystem.config.cjs` | No new ports needed — all features run within the existing Express server process | None |
-| MeatSpace routes/services | Add health sub-routes or a sibling route file for Apple Health | Additive |
-
-## Data Flow
-
-### 1. Backup Flow
-
-```
-Timer/Manual Trigger
- ↓
-backupService.runBackup()
- ↓
-rsync ./data/ → /Volumes/[external-drive]/portos-backup/
- ↓
-Record result to data/backup-history.json
- ↓
-Socket.IO emit('backup:status', { ... })
- ↓
-Client backup widget updates
-```
-
-**Key decisions:**
-- Use `rsync --archive --delete --exclude` (or `cp -a` as fallback) for incremental copy. rsync is already available on macOS.
-- Scheduler uses the same `setInterval` + time-check pattern as `brainScheduler.js` — not a new PM2 process, not node-cron. This keeps consistency with existing scheduling patterns (brainScheduler checks every 60s against a target time).
-- Backup state (last run, next scheduled, history) persists to `data/backup-history.json`.
-- Mount path for external drive is stored in a config file (`data/backup-config.json`) — user configures once.
-
-### 2. Apple Health Ingest Flow
-
-```
-Health Auto Export App (HTTP POST)
- ↓
-POST /api/meatspace/health/import
- ↓
-Zod validates wrapper (metadata, content-type)
- ↓
-appleHealthService.ingestXML(xmlBuffer)
- ↓
-sax/expat stream parser (NOT full DOM parse — files can be 500MB+)
- ↓
-Normalize records → { type, date, value, unit, source }
- ↓
-Batch-write to data/meatspace/health/{type}.json
- ↓
-Return import stats { imported: N, skipped: N, errors: N }
-```
-
-**Key decisions:**
-- Stream parsing is essential. Apple Health XML exports are regularly 200-500MB. A DOM parser would OOM the 500MB memory limit on portos-server. Use `sax` (event-based XML parser, zero dependencies, 15+ years mature) or `@oozcitak/saxes` (maintained fork).
-- Split ingested data by record type (e.g., `heart-rate.json`, `steps.json`, `weight.json`, `sleep.json`) rather than one giant file. This matches the existing meatspace pattern of domain-specific JSON files.
-- Deduplication by `(type, date, source)` composite key — Apple Health exports contain historical data on every export.
-- Express already has `express.json({ limit: '50mb' })` and `express.urlencoded({ limit: '50mb' })` configured. For raw XML, add `express.raw({ type: 'application/xml', limit: '600mb' })` on the specific route, or accept base64-encoded XML inside a JSON POST (matching the existing TSV import pattern).
-- Alternatively, accept the XML as multipart upload via the existing `uploads` infrastructure.
-
-### 3. Cross-Insights Engine Flow
-
-```
-GET /api/insights (or GET /api/insights/:domain)
- ↓
-insightsService.computeInsights()
- ↓
-Read (parallel):
- ├── genome service → SNP markers, longevity
- ├── meatspace services → blood, body, alcohol, lifestyle
- ├── digital-twin → taste, personality traits, soul profile
- └── (future) apple health → heart rate trends, sleep patterns
- ↓
-Correlation rules (declarative):
- genome(APOE ε4) + blood(LDL) → cardiovascular risk insight
- genome(CYP1A2) + lifestyle(caffeine) → caffeine sensitivity insight
- taste(flavor profiles) + personality(openness) → identity theme insight
- body(BMI trend) + lifestyle(exercise) → fitness trajectory insight
- ↓
-Cache in data/insights-cache.json (TTL: 1 hour)
- ↓
-Return { insights: [...], generatedAt, domains }
-```
-
-**Key decisions:**
-- Insights are computed on-demand (not scheduled) because the underlying data changes infrequently. A 1-hour TTL cache avoids repeated computation.
-- Correlation rules are declarative data structures (not hardcoded if/else chains). Each rule specifies: `{ id, name, domains: ['genome', 'blood'], condition: fn, compute: fn, category }`. This makes it easy to add new correlations without touching engine logic.
-- The engine is read-only — it never writes to source domains. It only reads from existing service exports.
-- Start with genome-to-health and taste-to-identity correlations (user's stated priority), then expand the rule set.
-- No AI provider needed for initial insights — these are deterministic rule-based correlations. AI-powered narrative summaries can layer on later.
-
-### 4. Unified Search Flow
-
-```
-Client: Cmd+K input → debounce 300ms → GET /api/search?q=...&limit=20
- ↓
-searchService.search(query, options)
- ↓
-Fan-out (parallel):
- ├── brain: capturedThoughts.filter(match) → { type: 'thought', ... }
- ├── memory: BM25 search (existing memoryBM25.js) → { type: 'memory', ... }
- ├── apps: apps.json name/description match → { type: 'app', ... }
- ├── history: activity log keyword match → { type: 'activity', ... }
- ├── digital-twin: document content match → { type: 'document', ... }
- ├── genome: SNP rsid match → { type: 'snp', ... }
- ├── agents: personality name/description match → { type: 'agent', ... }
- └── meatspace: health record label match → { type: 'health', ... }
- ↓
-Merge results, assign category, sort by relevance score
- ↓
-Return { results: [{ type, title, snippet, url, score }], timing }
-```
-
-**Key decisions:**
-- Keyword-first (project constraint: semantic search is out of scope for v1). Each domain adapter does simple string matching or delegates to existing search (memory already has BM25).
-- Fan-out is `Promise.allSettled()` — a failing domain must not break the entire search. Failed domains return empty results with a warning.
-- Each domain adapter is a small function: `(query, limit) => [{ type, title, snippet, url, score }]`. This is the interface contract.
-- Results include a `url` field (React Router path) so the Cmd+K overlay can navigate directly: e.g., `/brain/inbox`, `/meatspace/genome`, `/apps`.
-- Response includes `timing` object so the UI can show "Searched 8 domains in 45ms".
-
-### 5. Cmd+K Overlay Flow
-
-```
-User presses Cmd+K (or Ctrl+K)
- ↓
-CommandPalette opens (modal overlay, z-50)
- ↓
-User types query → debounce 300ms → api.get('/api/search?q=...')
- ↓
-Results render in categories:
- 🧠 Thoughts (2) 📱 Apps (1) 🧬 Genome (1) ...
- ↓
-Arrow keys navigate, Enter activates
- ↓
-React Router navigate(result.url)
- ↓
-CommandPalette closes
-```
-
-**Key decisions:**
-- Global keyboard listener in `useCommandPalette.js` hook, rendered via `CommandPalette.jsx` inside `Layout.jsx` — wraps `<Outlet />`.
-- No external dependency (cmdk, kbar). The component is straightforward: input + list + keyboard nav. External libraries add bundle weight for minimal gain in a single-user app.
-- Empty state shows recent navigation or suggested actions (not blank).
-- Escape closes. Clicking outside closes. Focus traps inside while open.
-
-## Patterns to Follow
-
-### Pattern 1: Service-per-Domain with Route Mounting
-
-**What:** Each new feature gets its own service file and route file, mounted in `server/index.js`.
-**When:** Always — this is the universal pattern in PortOS.
-**Trade-offs:** More files, but clear boundaries. Every feature has exactly two touchpoints in `index.js` (import + mount).
-
-```javascript
-// server/index.js additions:
-import backupRoutes from './routes/backup.js';
-import insightsRoutes from './routes/insights.js';
-import searchRoutes from './routes/search.js';
-
-app.use('/api/backup', backupRoutes);
-app.use('/api/insights', insightsRoutes);
-app.use('/api/search', searchRoutes);
-
-// Apple Health routes nest under existing meatspace mount:
-// server/routes/meatspace.js — add health import routes
-// OR mount separately: app.use('/api/meatspace/health', appleHealthRoutes);
-```
-
-### Pattern 2: Interval Scheduler (brainScheduler Pattern)
-
-**What:** Use `setInterval` with a 60-second check loop that compares current time to target schedule. No cron dependency.
-**When:** Backup scheduling.
-**Trade-offs:** 60-second granularity (fine for daily backups). Avoids adding node-cron dependency. Consistent with brainScheduler.js which already does daily + weekly scheduling.
-
-```javascript
-// Same pattern as brainScheduler.js
-const CHECK_INTERVAL_MS = 60000;
-let schedulerInterval = null;
-
-export function startBackupScheduler() {
- schedulerInterval = setInterval(checkSchedule, CHECK_INTERVAL_MS);
- console.log('💾 Backup scheduler started');
-}
-```
-
-### Pattern 3: Aggregator Service (Fan-out + Merge)
-
-**What:** A service that calls multiple other services in parallel and merges results.
-**When:** Unified search and cross-insights engine.
-**Trade-offs:** Creates a dependency on multiple services, but only read dependencies. Using `Promise.allSettled` ensures resilience.
-
-```javascript
-// server/services/search.js
-const adapters = [
- { domain: 'brain', search: searchBrain },
- { domain: 'memory', search: searchMemory },
- { domain: 'apps', search: searchApps },
- // ...
-];
-
-export async function search(query, options = {}) {
- const results = await Promise.allSettled(
- adapters.map(a => a.search(query, options.limit))
- );
- // Merge fulfilled results, log rejected
- return mergeResults(results, adapters);
-}
-```
-
-## Anti-Patterns to Avoid
-
-### Anti-Pattern 1: DOM-Parsing Large XML
-
-**What people do:** Use `DOMParser` or `xml2js` to parse the entire Apple Health XML into memory.
-**Why it's wrong:** Apple Health exports are 200-500MB. Full DOM parse will exceed the 500MB memory limit and crash the process.
-**Do this instead:** Use SAX/event-based streaming parser. Process records one at a time, write in batches.
-
-### Anti-Pattern 2: Monolithic Search Function
-
-**What people do:** Write one giant function that knows how to search every domain.
-**Why it's wrong:** Tightly couples search to every data model. Adding a new searchable domain requires modifying the core function.
-**Do this instead:** Use adapter pattern. Each domain registers a `(query, limit) => results[]` function. The search service only knows the adapter interface.
-
-### Anti-Pattern 3: Synchronous Backup Blocking Server
-
-**What people do:** Run rsync synchronously or await the entire copy in the request handler.
-**Why it's wrong:** Backup can take minutes. Blocks the Express event loop or times out the HTTP request.
-**Do this instead:** Spawn rsync as a child process. Return immediately with a job ID. Report progress via Socket.IO events.
-
-### Anti-Pattern 4: Circular Service Dependencies in Insights
-
-**What people do:** Have the insights service import from and write back to source services.
-**Why it's wrong:** Creates bidirectional coupling. Source services should not know about insights.
-**Do this instead:** Insights engine is strictly read-only. It imports from source services but never writes to them. Insights cache is its own data file.
-
-## Integration Points
-
-### Internal Boundaries
-
-| Boundary | Communication | Notes |
-|----------|---------------|-------|
-| Search API ↔ Domain Services | Direct function import (in-process) | Each adapter imports the relevant service. No HTTP between them. |
-| Backup Service ↔ File System | `child_process.spawn('rsync', [...])` | Async child process. Not blocking. |
-| Apple Health Route ↔ appleHealth Service | Direct function call (standard route→service pattern) | XML parsing happens in service layer, not route. |
-| Insights Engine ↔ Domain Services | Direct function import (read-only) | Insights never mutate source data. |
-| Cmd+K ↔ Search API | HTTP GET `/api/search` | Standard client→API pattern via `services/api.js`. |
-| Backup/Search ↔ Client | Socket.IO for real-time status | Backup progress events. Search uses HTTP (short-lived). |
-
-### External Integrations
-
-| Service | Integration Pattern | Notes |
-|---------|---------------------|-------|
-| External Drive | Mount path in `data/backup-config.json` | User configures once. Service validates mount exists before backup. |
-| Health Auto Export App | HTTP POST to `/api/meatspace/health/import` | Third-party iOS app sends XML via HTTP. PortOS is the server. |
-| rsync | `child_process.spawn` | macOS built-in. No npm dependency needed. |
-| SAX XML Parser | npm dependency (`sax` or `saxes`) | Only new npm dependency across all five features. |
-
-## Build Order and Dependencies
-
-The five features have the following dependency graph:
-
-```
-M44 P6 (Cleanup) ← No dependencies, pure cleanup
- ↓
-M45 (Backup) ← No dependencies on other new features
- CRITICAL: protects ./data/ before adding more data
- ↓
-M44 P7 (Apple Health) ← Depends on meatspace infrastructure (already exists)
- Should happen after backup is in place
- ↓
-M42 P5 (Cross-Insights) ← Depends on genome + health + taste data existing
- Benefits from Apple Health data being available
- ↓
-M46 (Unified Search) ← Benefits from all data sources existing
- Depends on no specific feature but searches everything
-```
-
-### Suggested Build Order Rationale
-
-1. **M44 P6 (Cleanup)** — First because it fixes existing technical debt before building on top. Zero risk, zero dependencies.
-
-2. **M45 (Backup)** — Second because it protects the single copy of all data in `./data/`. Every subsequent feature adds more data. Having backup in place before adding Apple Health bulk imports and insights caches is prudent.
-
-3. **M44 P7 (Apple Health)** — Third because it adds a new data source that enriches the insights engine. The meatspace infrastructure already exists (routes, services, validation). This is additive.
-
-4. **M42 P5 (Cross-Insights)** — Fourth because it benefits from having both genome data (already present) and Apple Health data (just added) to correlate. Building it before Apple Health would mean fewer correlations to ship.
-
-5. **M46 (Unified Search)** — Last because it benefits from all data sources existing. Each domain adapter is independent, so search can ship incrementally, but the experience is richest when all domains are populated.
-
-**Parallelism opportunity:** M44 P6 (cleanup) and M45 (backup) have zero overlap and can be built simultaneously. M44 P7 and M42 P5 are also parallelizable if the insights engine starts with genome-only correlations and adds health correlations when available. M46 is naturally incremental (add adapters one at a time).
-
-## Scaling Considerations
-
-| Concern | Current Scale (Single User) | If Data Grows 10x |
-|---------|----------------------------|--------------------|
-| Search latency | Fan-out across 8 JSON files, <100ms total | Add BM25 indexes for large domains (brain, health). Memory BM25 already exists. |
-| Apple Health ingest | Stream parse handles 500MB+ files | Already using streaming — no change needed |
-| Backup duration | rsync incremental on ~10MB of JSON | rsync handles this natively. Only changed files copy. |
-| Insights computation | Read 5-6 JSON files, apply rules, <50ms | Cache TTL already handles this. No change needed. |
-| Search index staleness | Keyword search reads live data on each query | Add in-memory caches with short TTL (2-5s) matching existing `appsCache` pattern |
-
-PortOS is single-user, so horizontal scaling is not a concern. The bottleneck sequence is: (1) Apple Health file size during ingest, (2) search fan-out latency if data files grow very large. Both are addressed by the streaming and caching patterns already described.
-
-## Sources
-
-- PortOS codebase analysis: `server/index.js`, `ecosystem.config.cjs`, `server/services/brainScheduler.js`, `server/lib/bm25.js`, `server/services/memoryBM25.js` — HIGH confidence (direct code inspection)
-- PortOS architecture docs: `.planning/codebase/ARCHITECTURE.md`, `.planning/codebase/STRUCTURE.md` — HIGH confidence
-- SAX XML parsing: established Node.js pattern for large XML processing — HIGH confidence (training data + long-standing community practice)
-- rsync incremental backup: macOS built-in utility, well-documented — HIGH confidence
-
----
-*Architecture research for: PortOS next actions batch*
-*Researched: 2026-02-26*
diff --git a/.planning/research/FEATURES.md b/.planning/research/FEATURES.md
deleted file mode 100644
index 2919730e34..0000000000
--- a/.planning/research/FEATURES.md
+++ /dev/null
@@ -1,291 +0,0 @@
-# Feature Research
-
-**Domain:** Personal OS dashboard -- JSON backup, Apple Health integration, cross-domain insight engine, Cmd+K search overlay
-**Researched:** 2026-02-26
-**Confidence:** MEDIUM-HIGH (based on established patterns in each subdomain; Apple Health payload schema not yet verified against current app version)
-
-## Feature Landscape
-
-This research covers five planned milestones (M44 P6/P7, M42 P5, M45, M46) across four distinct feature domains. Each domain is analyzed independently, then dependencies are mapped across all five.
-
----
-
-## 1. JSON Backup Systems (M45)
-
-### Table Stakes
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| Incremental copy by mtime | Full copy of 800+ files on every run is wasteful; users expect only changed files transfer | LOW | `fs.stat()` mtime comparison against manifest is trivial |
-| Backup manifest with checksums | Without integrity verification, a corrupted backup is worse than no backup -- silent data loss | MEDIUM | SHA-256 per file; store in `manifest.json` at backup root |
-| Configurable schedule | Must not require manual trigger every time; daily default with override | LOW | Leverage existing automation scheduler (M26) |
-| Retention policy (N daily + N weekly) | Unbounded backups fill drives; users expect automatic pruning | LOW | Date-based directory naming + prune logic |
-| Manual trigger button | "Back up now" before risky operations is a fundamental expectation | LOW | POST /api/backup/trigger, button in dashboard widget |
-| Backup health indicator | User must know at a glance if backups are current | LOW | Green/yellow/red based on last backup age |
-| Atomic writes / temp-then-rename | A crash mid-backup must not corrupt the target; partial writes are the #1 backup failure mode | MEDIUM | Write to `.tmp` dir, rename on success |
-
-### Differentiators
-
-| Feature | Value Proposition | Complexity | Notes |
-|---------|-------------------|------------|-------|
-| Dry-run restore preview | Shows what would change before restoring -- reduces fear of restore destroying current state | MEDIUM | Diff manifest checksums between backup and current `data/` |
-| Per-directory selective restore | Restore only `data/brain/` without touching `data/cos/` -- granular recovery | MEDIUM | Directory-scoped manifest filtering |
-| Pre-backup validation | Verify JSON parse-ability of critical files before backing up -- don't back up corruption | LOW | `JSON.parse()` guard on key files |
-| Socket.IO progress during backup/restore | Long operations (especially restore) need real-time progress feedback | LOW | Emit progress events through existing Socket.IO infra |
-| Backup size tracking over time | Trend of data growth informs when to add more storage | LOW | Store size in manifest history |
-
-### Anti-Features
-
-| Feature | Why Requested | Why Problematic | Alternative |
-|---------|---------------|-----------------|-------------|
-| Cloud backup (S3, GCS, etc.) | "What if the house burns down" | Adds cloud credentials, network dependency, cost, and complexity; out of scope per PROJECT.md | Local external drive now; cloud can layer later via rsync to a cloud-mounted volume |
-| Versioned file-level history (git-style) | "Roll back a single file to 3 versions ago" | JSON files change frequently; versioning every write creates enormous storage overhead and complex diff UI | Snapshot-level retention (daily/weekly) is sufficient; individual file recovery comes from picking the right snapshot |
-| Encryption at rest | Protect backup from physical theft | Single-user system on private network; encryption adds key management complexity and slows backup/restore | Rely on macOS FileVault for disk encryption |
-| Database migration to SQLite | "JSON files are fragile" | Massive rewrite of entire data layer for marginal benefit; JSON-per-file is the established pattern | Backup system protects against the fragility concern directly |
-| Real-time continuous backup (inotify/fsevents) | "Never lose a write" | High CPU/IO overhead; PortOS writes to data/ on every API call; continuous sync creates thundering herd on the external drive | Scheduled incremental (daily + manual trigger) covers 99% of risk |
-
----
-
-## 2. Apple Health Integration (M44 P7)
-
-### Table Stakes
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| POST /api/health/ingest endpoint | Health Auto Export app needs a URL to POST to; this is the entire integration surface | MEDIUM | Zod validation of the Health Auto Export JSON schema |
-| Deduplication by metric+timestamp | App sends overlapping windows; without dedup, data doubles on every sync | MEDIUM | Composite key: `metricName + startDate` or hash-based |
-| Day-partitioned JSON storage | `data/health/YYYY-MM-DD.json` matches existing PortOS pattern; keeps files manageable | LOW | One file per day, merge on write |
-| Bulk XML import (Apple Health export.zip) | Users have years of historical data in Apple's XML export; without bulk import the feature starts empty | HIGH | Stream-parse 500MB+ XML; `xml-stream` or `sax` parser; progress via WebSocket |
-| Zod schema validation | Reject malformed payloads; consistent with all other PortOS routes | LOW | Define schema from Health Auto Export docs |
-| Basic dashboard cards (steps, heart rate, sleep) | Ingested data with no visualization is useless | MEDIUM | Time-series line charts for key metrics; reuse existing chart patterns |
-
-### Differentiators
-
-| Feature | Value Proposition | Complexity | Notes |
-|---------|-------------------|------------|-------|
-| Health-to-MeatSpace correlation views | Overlay HRV with alcohol intake, sleep quality with exercise -- the unique PortOS value is connecting siloed data | HIGH | Depends on M42 P5 cross-insights engine for full value; can start with simple overlay charts |
-| Metric category browser | 150+ Apple Health metric types; let user browse/search available metrics and pin favorites | MEDIUM | Catalog ingested metric types, show latest values |
-| Import progress via WebSocket | XML imports take minutes; real-time progress bar prevents "is it stuck?" anxiety | LOW | Existing Socket.IO infra; emit count/total during parse |
-| Configurable sync interval display | Show when last sync happened and expected next sync from the iOS app | LOW | Track last ingest timestamp per source |
-| Workout route maps | Health Auto Export includes GPS routes for workouts; rendering on a map is compelling | HIGH | Requires Leaflet/MapLibre, GPS coordinate parsing; defer to post-MVP |
-
-### Anti-Features
-
-| Feature | Why Requested | Why Problematic | Alternative |
-|---------|---------------|-----------------|-------------|
-| Apple HealthKit direct API | "Skip the middleman app" | HealthKit is iOS-only SDK; PortOS is a Node.js server with no iOS runtime | Health Auto Export app bridges the gap for ~$4 |
-| Real-time live sync from watch/phone | "I want instant updates" | Health Auto Export batches on configurable intervals (15-60 min); real-time would require custom iOS app development | 15-min interval from Health Auto Export is plenty for dashboard use |
-| Write-back to Apple Health | "Let PortOS update my health records" | HealthKit write access requires an iOS app with entitlements; massive scope increase | PortOS is read-only consumer of health data |
-| Medical-grade analytics / diagnosis | "Tell me if my HRV means I'm sick" | Liability risk; PortOS is not a medical device; LLM-generated health advice can be harmful | Show trends and correlations; let the user draw conclusions; flag "consult a doctor" |
-| Support for every health platform (Fitbit, Garmin, Oura) | "I might switch devices" | Each platform has different APIs, auth flows, and data formats; scope explosion | Apple Health is the aggregator -- most devices already sync into it |
-
----
-
-## 3. Cross-Domain Insight Engine (M42 P5)
-
-### Table Stakes
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| Genome-to-health correlation rules | Map specific SNP markers to health recommendations (e.g., MTHFR + folate, APOE + cardiovascular risk) | MEDIUM | Rule-based engine using existing 117 curated markers and their categories |
-| Taste-to-identity theme extraction | Derive personality themes from taste profile (e.g., preference for dark narratives + minimalist architecture = "introspective pragmatist") | MEDIUM | LLM-powered summarization over structured taste data |
-| Insight persistence | Generated insights must be saved and retrievable, not regenerated on every page load | LOW | `data/digital-twin/insights.json` |
-| Insight provenance / citations | Each insight must cite which data sources contributed (e.g., "Based on: rs762551 fast caffeine metabolism + evening chronotype") | MEDIUM | Store source references with each insight entry |
-| Manual refresh trigger | User should be able to regenerate insights when underlying data changes | LOW | Button in UI, POST endpoint |
-
-### Differentiators
-
-| Feature | Value Proposition | Complexity | Notes |
-|---------|-------------------|------------|-------|
-| Cross-domain contradiction detection | Flag when genome says one thing and behavior says another (e.g., genome says morning chronotype but user reports evening habits) | MEDIUM | Compare genetic predictions against behavioral/reported data |
-| Confidence scoring per insight | Not all correlations are equally supported; show confidence level | LOW | Derive from marker classification (beneficial/typical/concern) and number of supporting data points |
-| Temporal insight evolution | "Your taste profile has shifted toward warmer aesthetics since 6 months ago" -- track how insights change over time | HIGH | Requires snapshots of derived insights; defer to v2 |
-| LLM-generated narrative summaries | Paragraph-form "here is who you are" synthesizing genome, taste, personality, and goals | MEDIUM | Use existing AI provider infra; identity context injection from M42 |
-| Health-genome action items | Concrete recommendations: "Your MTHFR variant suggests supplementing methylfolate" | MEDIUM | Rule engine with pre-written recommendation templates per marker category |
-
-### Anti-Features
-
-| Feature | Why Requested | Why Problematic | Alternative |
-|---------|---------------|-----------------|-------------|
-| Fully autonomous insight generation | "Generate insights automatically on a schedule" | LLM calls are expensive; insights don't change unless underlying data changes; scheduled generation wastes tokens | Generate on-demand when user requests or when source data is updated |
-| Causal claims ("your genome causes X") | Users want definitive answers | SNP correlations are probabilistic, not causal; stating "causes" is scientifically wrong and potentially harmful | Use language like "associated with," "may influence," "research suggests" |
-| Cross-user comparison | "How do I compare to population averages?" | Single-user system; no population data available; would require external datasets with licensing concerns | Show the user's own data with published population frequencies from dbSNP/ClinVar |
-| Real-time streaming insights | "Update insights as I type/log data" | Insight generation requires multiple data sources and LLM calls; real-time is impractical and expensive | Batch on explicit trigger or on data change events |
-
----
-
-## 4. Unified Search / Cmd+K Overlay (M46)
-
-### Table Stakes
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| Cmd+K / Ctrl+K keyboard shortcut | Universal convention for launcher/search overlays (Slack, VS Code, Linear, Notion, Raycast) | LOW | Global keydown listener in Layout.jsx |
-| Instant overlay from any page | Search must be accessible everywhere without navigation | LOW | Portal-mounted component in Layout.jsx |
-| Categorized results | Results grouped by source type (Brain, Memory, Apps, History, Health) | MEDIUM | Fan-out to multiple search functions, tag results with source |
-| Deep-link to source | Clicking a result navigates to the exact item (brain capture, agent run, history entry) | MEDIUM | Each data source needs a canonical URL; most already have linkable routes |
-| Debounced type-ahead (200ms) | Without debounce, every keystroke fires a search; with too much delay, feels laggy | LOW | Standard `useDebounce` hook |
-| Escape to close | Universal overlay dismiss convention | LOW | Keyboard event handler |
-| Result snippets with highlighted match | Users need to see why a result matched, not just the title | MEDIUM | Return match context from search, highlight query terms in UI |
-
-### Differentiators
-
-| Feature | Value Proposition | Complexity | Notes |
-|---------|-------------------|------------|-------|
-| Recent searches / history | "I searched for this yesterday" -- reduces re-typing | LOW | localStorage array of last N queries |
-| Keyboard navigation (arrow keys + Enter) | Power users expect to never touch the mouse | MEDIUM | Focus management, active index state |
-| Source-type filtering | "Search only in Brain" or "Search only Health" -- scope narrows results | MEDIUM | Filter chips or prefix syntax (e.g., `brain: meditation`) |
-| Result ranking with source-type boosting | Brain captures and apps rank higher than old history entries for most queries | MEDIUM | Configurable weight per source type in search aggregator |
-| Quick actions in results | "Restart app X" or "Open agent Y" directly from search results | HIGH | Requires action registry per result type; defer to v2 |
-
-### Anti-Features
-
-| Feature | Why Requested | Why Problematic | Alternative |
-|---------|---------------|-----------------|-------------|
-| Semantic / vector search in Cmd+K v1 | "Keyword search misses meaning" | Existing vector+BM25 hybrid is only built for Memory system; extending to all data sources requires embedding every data type; large scope increase | Ship keyword-first (already decided in PROJECT.md); semantic can layer on later using existing vector infra |
-| Fuzzy matching everything | "Find even with typos" | Fuzzy across 10+ data sources with different schemas is complex; false positives degrade trust | Exact substring match + case-insensitive is sufficient for v1; add fuzzy for app names only |
-| Client-side indexing (Lunr, MiniSearch) | "Avoid server round-trips" | Data lives server-side in JSON files; duplicating to client creates stale data and memory bloat on mobile | Server-side search with fast response time (<200ms target) |
-| Natural language queries | "Show me what I captured about meditation last week" | Requires NLP date parsing, intent classification -- this is a full search product | Keyword search with date range filter is 80/20 |
-| Indexing external content (web bookmarks, emails) | "Search everything I've ever seen" | Scope explosion; each external source needs its own ingestion pipeline | PortOS searches PortOS data; external ingestion is a separate feature |
-
----
-
-## 5. Genome/Epigenetic Migration Cleanup (M44 P6)
-
-### Table Stakes
-
-| Feature | Why Expected | Complexity | Notes |
-|---------|--------------|------------|-------|
-| Fix route comments referencing old paths | Comments still say `/api/digital-twin/genome/`; these mislead developers | LOW | Find-and-replace in route files |
-| Fix IdentityTab Genome card link | Card links to `/digital-twin/genome` which no longer exists; should link to `/meatspace/genome` or be removed | LOW | Update href or remove the card |
-| Verify no other stale references | Other UI components or services may still reference old genome routes | LOW | Grep for `digital-twin/genome` across codebase |
-
-### Differentiators
-
-| Feature | Value Proposition | Complexity | Notes |
-|---------|-------------------|------------|-------|
-| Redirect from old route to new | If anyone bookmarked the old URL, redirect gracefully | LOW | Express redirect middleware |
-
-### Anti-Features
-
-| Feature | Why Requested | Why Problematic | Alternative |
-|---------|---------------|-----------------|-------------|
-| Duplicate genome data in both locations | "Keep backward compatibility" | Two sources of truth; data drift guaranteed | Single canonical location in MeatSpace |
-
----
-
-## Feature Dependencies
-
-```
-M44 P6 (Genome Cleanup)
- └──enables──> M42 P5 (Cross-Insights Engine)
- genome routes must be correct for insight engine to read genome data
-
-M44 P7 (Apple Health Integration)
- └──enhances──> M42 P5 (Cross-Insights Engine)
- health data enables genome-to-health correlations (HRV vs APOE, etc.)
-
-M45 (Data Backup)
- └──protects──> ALL features
- zero redundancy means backup should ship before or alongside new data writers
-
-M46 (Unified Search)
- └──requires──> existing search infrastructure (BM25 in memory system)
- └──enhanced-by──> M44 P7 (more data sources to search)
- └──enhanced-by──> M42 P5 (insights become searchable)
-
-M42 P5 (Cross-Insights Engine)
- └──requires──> M44 P6 (clean genome routes)
- └──enhanced-by──> M44 P7 (Apple Health data for health correlations)
- └──uses──> existing identity.js, genome.js, taste-questionnaire.js
-```
-
-### Dependency Notes
-
-- **M44 P6 before M42 P5:** Cross-Insights Engine reads genome data through genome.js; if route comments and IdentityTab still reference old paths, there is confusion about the canonical data location. Clean this up first.
-- **M45 independent but urgent:** Backup has no technical dependencies on other features, but its risk-reduction value means it should ship early. New data writers (M44 P7 health data) increase the blast radius of data loss.
-- **M44 P7 enhances M42 P5:** The most compelling cross-insights are genome-to-health correlations (e.g., APOE genotype vs. cardiovascular metrics from Apple Health). M42 P5 can ship with genome+taste insights first, then add health correlations when M44 P7 lands.
-- **M46 is additive:** Search works over whatever data exists at the time. It can ship at any point and gains value as more data sources are added.
-
----
-
-## MVP Definition
-
-### Launch With (v1 of each milestone)
-
-- [ ] **M44 P6:** Fix all stale genome route references and IdentityTab card -- 1-2 hours of cleanup
-- [ ] **M45:** Incremental backup with mtime comparison, SHA-256 manifest, configurable target path, daily schedule via existing scheduler, manual trigger button, green/yellow/red health widget
-- [ ] **M44 P7:** POST /api/health/ingest for Health Auto Export JSON, Zod validation, dedup by metric+timestamp, day-partitioned storage, basic dashboard cards for steps/heart rate/sleep
-- [ ] **M42 P5:** Genome-to-health rule engine (map curated markers to recommendations), taste-to-identity LLM summarization, insight persistence to JSON, provenance citations
-- [ ] **M46:** Cmd+K overlay, server-side fan-out search across brain/memory/apps/history, categorized results with source icons, debounced input, deep-link navigation, Escape to close
-
-### Add After Validation (v1.x)
-
-- [ ] **M45:** Dry-run restore preview, per-directory selective restore, backup size trending
-- [ ] **M44 P7:** Bulk XML import with WebSocket progress, metric category browser, health-to-MeatSpace correlation overlay charts
-- [ ] **M42 P5:** Contradiction detection (genome vs. behavior), LLM narrative summaries, confidence scoring
-- [ ] **M46:** Recent search history, keyboard navigation (arrows + Enter), source-type filter chips, result ranking with configurable boosts
-
-### Future Consideration (v2+)
-
-- [ ] **M44 P7:** Workout GPS route maps, support for additional health platforms
-- [ ] **M42 P5:** Temporal insight evolution (track changes over time), health-genome action items with recommendation templates
-- [ ] **M46:** Semantic search extension (extend existing vector+BM25 to all data sources), quick actions from search results, natural language date queries
-
----
-
-## Feature Prioritization Matrix
-
-| Feature | User Value | Implementation Cost | Priority |
-|---------|------------|---------------------|----------|
-| M44 P6: Genome route cleanup | LOW (housekeeping) | LOW | P1 -- do first, unblocks M42 P5 |
-| M45: Incremental backup + manifest | HIGH (data protection) | MEDIUM | P1 -- risk reduction for all data |
-| M45: Dashboard health widget | MEDIUM | LOW | P1 -- visibility into backup status |
-| M45: Dry-run restore | MEDIUM | MEDIUM | P2 -- ship after backup works |
-| M44 P7: Health ingest endpoint | HIGH | MEDIUM | P1 -- enables Apple Health data flow |
-| M44 P7: Day-partitioned storage + dedup | HIGH | MEDIUM | P1 -- required for ingest to be useful |
-| M44 P7: Bulk XML import | MEDIUM | HIGH | P2 -- historical data is valuable but complex |
-| M44 P7: Basic health dashboard cards | HIGH | MEDIUM | P1 -- visualization makes data actionable |
-| M42 P5: Genome-to-health rules | HIGH | MEDIUM | P1 -- core value proposition of cross-insights |
-| M42 P5: Taste-to-identity themes | MEDIUM | MEDIUM | P1 -- completes the identity picture |
-| M42 P5: LLM narrative summaries | MEDIUM | MEDIUM | P2 -- compelling but not essential for v1 |
-| M42 P5: Contradiction detection | MEDIUM | MEDIUM | P2 -- interesting differentiator |
-| M46: Cmd+K overlay + fan-out search | HIGH | MEDIUM | P1 -- immediate cross-cutting utility |
-| M46: Keyboard navigation | MEDIUM | MEDIUM | P2 -- power user feature |
-| M46: Source-type filtering | MEDIUM | MEDIUM | P2 -- useful once result volume grows |
-| M46: Semantic search extension | MEDIUM | HIGH | P3 -- existing keyword search is sufficient for v1 |
-
-**Priority key:**
-- P1: Must have for launch
-- P2: Should have, add when possible
-- P3: Nice to have, future consideration
-
----
-
-## Competitor Feature Analysis
-
-These are not direct competitors but reference implementations in each domain.
-
-| Feature Area | Reference Products | How They Do It | PortOS Approach |
-|---------|--------------|--------------|--------------|
-| JSON backup | Obsidian Sync, Logseq Git | Obsidian uses proprietary sync service; Logseq uses git auto-commit | File-level incremental copy with checksums; simpler and more transparent |
-| Apple Health integration | Exist.co, Gyroscope, Health Mate | Cloud services with OAuth to HealthKit; require account creation | Health Auto Export app as bridge; no cloud dependency; data stays local |
-| Cross-domain insights | Exist.co (mood+activity), Gyroscope (health+productivity) | Correlation dashboards with fixed insight types | LLM-powered insight generation; genome data is a unique dimension no competitor has |
-| Cmd+K search | Raycast, Alfred, Notion, Linear | Client-side indexing (Raycast/Alfred); server-side fan-out (Notion/Linear) | Server-side fan-out matching Linear/Notion pattern; data lives server-side so this is the natural fit |
-| Genome+health correlation | Promethease, SelfDecode, Nebula | Proprietary databases of SNP-phenotype associations; subscription model | Curated 117 markers with open ClinVar references; correlate with actual health data from Apple Health rather than just genetic risk scores |
-
----
-
-## Sources
-
-- PortOS codebase: `server/services/memoryBM25.js` (existing BM25 search infrastructure), `server/services/genome.js` (117 curated markers), `server/services/identity.js` (chronotype derivation, longevity markers), `ecosystem.config.cjs` (port allocation)
-- PLAN.md: Detailed specs for M44 P7, M45, M46
-- PROJECT.md: Scope boundaries, constraints, existing infrastructure
-- Health Auto Export app: [App Store listing](https://apps.apple.com/us/app/health-auto-export-json-csv/id1115567069), [GitHub reference server](https://github.com/HealthyApps/health-auto-export-server)
-- Apple Health XML export: [apple-health-parser reference](https://github.com/cvyl/apple-health-parser)
-- Cmd+K patterns: Observed in Raycast, VS Code, Linear, Notion, Slack -- universal convention
-- JSON backup patterns: rsync incremental, Time Machine snapshot model, Obsidian Sync
-
----
-*Feature research for: PortOS next actions batch (M44 P6/P7, M42 P5, M45, M46)*
-*Researched: 2026-02-26*
diff --git a/.planning/research/PITFALLS.md b/.planning/research/PITFALLS.md
deleted file mode 100644
index bc36bd18f2..0000000000
--- a/.planning/research/PITFALLS.md
+++ /dev/null
@@ -1,265 +0,0 @@
-# Pitfalls Research
-
-**Domain:** Personal OS monorepo — JSON file persistence, health data ingestion, cross-domain intelligence, global search
-**Researched:** 2026-02-26
-**Confidence:** HIGH (based on codebase analysis and established patterns in similar systems)
-
-## Critical Pitfalls
-
-### Pitfall 1: Backup Copies Corrupt Mid-Write JSON Files
-
-**What goes wrong:**
-Incremental backup copies a JSON file while the server is writing to it. The backup contains a truncated or half-written file. On restore, that file fails to parse and the service crashes or loses data. This is already a known concern — CONCERNS.md documents that `cos.js` does write-via-temp-file but catch handlers swallow errors, and multiple services write without coordinated locking.
-
-**Why it happens:**
-Node.js `writeFile` is not atomic. The backup scheduler reads file modification timestamps to decide what to copy, but the file could be mid-write at the exact moment of copy. With 7+ top-level JSON files and nested directories (`cos/`, `brain/`, `digital-twin/`), the window for collision is non-trivial — especially during CoS daemon cycles that write `state.json` on every tick.
-
-**How to avoid:**
-1. Snapshot-then-copy: Before copying, create hard links (macOS/Linux) or use `fs.copyFile` with `COPYFILE_EXCL` to a staging directory, then move the staging directory to the backup target. Hard links are instant and capture a point-in-time view.
-2. Coordinate with write locks: Emit a Socket.IO event (`backup:starting`) so services can flush pending writes and hold new writes until `backup:complete`. Use the existing mutex pattern from `memory.js`.
-3. Validate after copy: Read every `.json` file in the backup and attempt `JSON.parse`. If any file fails validation, re-copy it. Log validation results to the backup manifest.
-
-**Warning signs:**
-- Backup manifest shows files copied in under 1ms (may indicate zero-byte copies)
-- Restored files that `JSON.parse` rejects
-- Backup size varies wildly between runs (indicates partial copies)
-
-**Phase to address:**
-M45 (Data Backup & Recovery) — implement as core backup correctness guarantee before adding scheduling or retention.
-
----
-
-### Pitfall 2: Apple Health XML Parsing Blows Up Memory on 500MB+ Files
-
-**What goes wrong:**
-The naive approach to parsing Apple Health XML exports is `fs.readFile` + DOM parser, which loads the entire 500MB-1GB file into memory as a string, then doubles or triples it during DOM construction. Node.js process exceeds `max_memory_restart` (500M for portos-server) and PM2 kills it mid-parse, leaving partial data written to `data/health/`.
-
-**Why it happens:**
-Apple Health XML exports contain millions of `<Record>` elements. A typical 2-3 year export is 500MB-1.5GB of XML. DOM-based parsing requires the entire document in memory. Even SAX/stream parsers must be configured carefully — if you accumulate parsed records in an array before writing, you recreate the same memory problem.
-
-**How to avoid:**
-1. Use `xml-stream` or `sax` in true streaming mode: parse record-by-record, writing each day's batch to `data/health/YYYY-MM-DD.json` as you encounter it. Never accumulate more than one day's records in memory.
-2. Process in a separate worker or PM2 process (not the main API server) so memory spikes don't affect other routes.
-3. Set a dedicated `max_memory_restart` higher for the import worker, or use `--max-old-space-size=2048` for the import subprocess.
-4. Report progress via WebSocket as planned — but use record count, not byte offset, since XML parsing position doesn't map linearly to progress.
-
-**Warning signs:**
-- Node.js process memory exceeding 400MB during import
-- PM2 restart logs during XML processing
-- Partial `data/health/` files (some days present, later days missing)
-
-**Phase to address:**
-M44 P7 (Apple Health Integration) — streaming parser is the foundational architecture choice, not an optimization to add later.
-
----
-
-### Pitfall 3: Cross-Insights Engine Produces Spurious Correlations
-
-**What goes wrong:**
-Genome-to-health and taste-to-identity correlations sound compelling but without proper methodology, the engine generates confident-sounding but meaningless insights. Example: "Your MTHFR C677T variant correlates with your preference for dark chocolate" — a coincidence dressed up as an insight. Users lose trust in the entire system.
-
-**Why it happens:**
-With enough data dimensions (genome markers, taste preferences, personality traits, health metrics), any two variables will appear correlated by chance. LLMs are particularly prone to generating plausible-sounding causal narratives from coincidental associations. The genome service already has curated markers with known clinical significance, but crossing domains (genome x taste x personality) invites fabrication.
-
-**How to avoid:**
-1. Ground insights in established science: Only generate genome-to-health correlations for markers with ClinVar clinical significance or well-documented SNPedia associations. The existing `curatedGenomeMarkers.js` and ClinVar sync already provide this foundation.
-2. Use the LLM to synthesize, not discover: Feed the LLM pre-validated correlations (e.g., "APOE e4 + family history + high LDL = elevated Alzheimer's risk") rather than asking it to find patterns.
-3. Label confidence tiers explicitly in the UI: "Established" (peer-reviewed), "Suggested" (multiple genome markers align), "Speculative" (pattern-matched, not validated).
-4. Taste-to-identity: These are legitimate personality psychology connections (Big Five traits predict aesthetic preferences). Use established mappings, not LLM inference.
-
-**Warning signs:**
-- Insights reference genome markers not in the curated set
-- The same insight appears for different genotypes (templated, not data-driven)
-- Users report insights that contradict known medical information
-
-**Phase to address:**
-M42 P5 (Cross-Insights Engine) — the insight taxonomy and confidence labeling must be designed before any correlation logic runs.
-
----
-
-### Pitfall 4: Cmd+K Search Fan-Out Creates Cascading Latency
-
-**What goes wrong:**
-The search endpoint fans out to 7+ data sources (brain, memory, history, agents, apps, digital-twin, meatspace). Each source has different search characteristics — memory uses vector+BM25, brain does text matching, history scans a JSON array. One slow source (e.g., memory with embedding provider offline) blocks the entire response. The 200ms debounce feels snappy until the server takes 3 seconds to respond.
-
-**Why it happens:**
-`Promise.all` with heterogeneous data sources means the slowest source determines total latency. Memory search with BM25 fallback already has known latency issues (CONCERNS.md). History file grows unbounded (CONCERNS.md). Agent data requires reading date-bucketed directories.
-
-**How to avoid:**
-1. `Promise.allSettled` with per-source timeouts (300ms per source). Return whatever results arrive in time; show a "still searching..." indicator for slow sources.
-2. Priority ordering: Search apps and brain first (fast, in-memory or small files). Memory and history last (potentially slow). Return results progressively via WebSocket if HTTP streaming isn't viable.
-3. Pre-index searchable fields on startup: Build in-memory keyword indexes for brain captures, apps, agent names/descriptions. Only hit disk for full-text or embedding search.
-4. Cap history search to recent N entries (last 30 days or 1000 entries) for Cmd+K — full history search can be a dedicated DevTools feature.
-
-**Warning signs:**
-- Search response time exceeds 500ms for simple keywords
-- Results from one source consistently missing (timeout, not empty)
-- Memory usage spikes on search queries (loading full history into memory)
-
-**Phase to address:**
-M46 (Unified Search) — per-source timeouts and progressive results must be in the initial architecture, not patched on after.
-
----
-
-### Pitfall 5: Backup to External Drive Fails Silently When Drive Unmounted
-
-**What goes wrong:**
-The backup target path (e.g., `/Volumes/Backup/portos/`) exists when configured but the external drive disconnects or unmounts between backups. The next scheduled backup writes to a local path that macOS auto-creates under `/Volumes/` (or fails with ENOENT), and the user believes backups are running successfully. Weeks later when they need to restore, the "backup" is either missing or on the boot disk consuming space.
-
-**Why it happens:**
-macOS doesn't error when writing to `/Volumes/ExternalDrive/` if the mount point directory still exists after unmount — it just writes to local disk. Or the directory doesn't exist and the backup fails silently because error handling only logs, doesn't alert.
-
-**How to avoid:**
-1. Before each backup run, verify the target is an actual mounted volume: check `os.platform() === 'darwin'` and validate with `diskutil info <path>` or verify the volume appears in `fs.statfs()` with a different device ID than the root filesystem.
-2. Write a `.portos-backup-probe` sentinel file with a timestamp after each backup. On the next run, read it back and verify the timestamp matches. If it doesn't match (or file is missing), the drive was likely remounted fresh or replaced.
-3. Surface backup failures prominently: Dashboard widget should show red status, not just log. Emit a notification event for M47 integration later.
-4. Never `mkdir -p` the backup target — if the directory doesn't exist, that's a signal the drive isn't mounted.
-
-**Warning signs:**
-- Backup target path exists but `df <path>` shows the root filesystem
-- Backup completes in milliseconds (writing to fast local SSD instead of external drive)
-- Backup size on target doesn't grow over time
-
-**Phase to address:**
-M45 (Data Backup & Recovery) — mount verification is day-one logic, not a nice-to-have.
-
----
-
-### Pitfall 6: Genome Data Still Lives in `data/digital-twin/` After Route Migration
-
-**What goes wrong:**
-Routes were moved from `/api/digital-twin/genome/` to `/api/meatspace/genome/` (M44 P5), and the client `api.js` calls the new endpoints. But the genome service (`server/services/genome.js` line 7) still reads/writes to `PATHS.digitalTwin` (`data/digital-twin/`). The genome data physically lives in the digital-twin directory while being served under meatspace routes. If a future cleanup moves or deletes `data/digital-twin/`, genome data is lost. The IdentityTab also still navigates to `/digital-twin/genome` (a dead route).
-
-**Why it happens:**
-The migration moved the API route mounting point but didn't move the physical data directory or update the service's path constants. This is a classic incomplete migration — the API surface changed but the storage layer didn't follow.
-
-**How to avoid:**
-1. M44 P6 must update `genome.js` to use `PATHS.meatspace` for genome data storage, and include a one-time data migration that moves files from `data/digital-twin/genome-*` to `data/meatspace/genome-*`.
-2. Update `IdentityTab.jsx` line 190 to navigate to `/meatspace` (the genome tab within MeatSpace) instead of `/digital-twin/genome`.
-3. Update route comments in `server/routes/genome.js` that still reference `/api/digital-twin/genome/`.
-4. Verify `meatspace.js` service reads from the correct path for genome cross-references (it imports `getSnpIndex` from `genome.js`).
-
-**Warning signs:**
-- `data/digital-twin/` contains `genome-raw.txt` and `genome.json` while `data/meatspace/` has no genome files
-- Clicking "Genome" in IdentityTab navigates to a 404 page
-- Genome route comments reference the old `/api/digital-twin/genome/` path
-
-**Phase to address:**
-M44 P6 (Migration Cleanup) — this is the explicit scope of this phase.
-
----
-
-### Pitfall 7: Health Auto Export JSON Schema Changes Break Ingestion Silently
-
-**What goes wrong:**
-The Health Auto Export app updates its JSON payload format (field renames, nested structure changes, new metric types). The Zod validation schema on `POST /api/health/ingest` rejects the new format, and the iOS app silently fails to deliver data. Since the app runs in the background on the phone, there's no visible error — data just stops arriving. The user discovers weeks later that health data has a gap.
-
-**Why it happens:**
-Third-party app APIs evolve without notice. The Health Auto Export app has had multiple major versions. The PortOS endpoint is a receiver, so it must handle whatever the app sends. Zod's strict validation (the project convention) rejects unknown fields by default, which is the opposite of what you want for a third-party data receiver.
-
-**How to avoid:**
-1. Use Zod's `.passthrough()` on the ingest schema — validate known fields but preserve unknown ones. New metric types shouldn't cause rejection.
-2. Log the raw payload to `data/health/raw/` before validation, so even if parsing fails, the data isn't lost.
-3. Implement a "last heard from" timestamp. If the ingest endpoint hasn't received data in 2x the expected interval, surface a warning on the MeatSpace dashboard.
-4. Pin the expected schema version but handle gracefully: if the payload has an unexpected structure, store it raw and flag for review rather than rejecting.
-
-**Warning signs:**
-- Ingest endpoint returning 400 errors (check server logs)
-- `data/health/` stops receiving new daily files
-- Health Auto Export app shows delivery failures in its logs
-
-**Phase to address:**
-M44 P7 (Apple Health Integration) — permissive ingestion with raw logging must be the default from the start.
-
-## Technical Debt Patterns
-
-| Shortcut | Immediate Benefit | Long-term Cost | When Acceptable |
-|----------|-------------------|----------------|-----------------|
-| Backup copies files without write coordination | Simpler implementation, no service changes | Occasional corrupt backups, silent data loss on restore | Never — corrupt backups are worse than no backups because they create false confidence |
-| Parse Apple Health XML into memory, then batch write | Simpler code, easier to test | OOM kills on 500MB+ files, partial data writes | Only for testing with sample files <10MB |
-| LLM generates cross-domain insights without grounding | Faster to build, more "interesting" outputs | Spurious correlations erode user trust, potentially dangerous health misinformation | Never for genome-health correlations; acceptable for taste-personality (lower stakes) |
-| Search fans out synchronously with no timeouts | Simpler Promise.all, guaranteed completeness | One slow source blocks all results, bad UX on every keystroke | Only during initial prototype; replace before shipping |
-| Store genome data in digital-twin directory after route move | No data migration needed | Confusing directory structure, data loss if digital-twin dir cleaned up | Only during the migration transition (M44 P6 should resolve immediately) |
-
-## Integration Gotchas
-
-| Integration | Common Mistake | Correct Approach |
-|-------------|----------------|------------------|
-| Health Auto Export app | Strict Zod schema rejects new fields from app updates | Use `.passthrough()` on Zod schema; log raw payloads before validation; store unknown metrics rather than rejecting |
-| Apple Health XML export | Using `xml2js` or similar DOM parser that loads entire file into memory | Use `sax` or `xml-stream` with per-record streaming; write day files incrementally; process in worker |
-| External backup drive (macOS) | Assuming mount path existence means drive is mounted | Verify with `diskutil` or filesystem device ID check; write and read sentinel file; never `mkdir -p` the target |
-| ClinVar database sync | Downloading full ClinVar VCF on every sync (1.5GB) | Already implemented in `clinvar.js` — but ensure backup system excludes or handles large downloaded reference files |
-| Cross-insights LLM calls | Passing raw genome data to LLM and asking "what insights?" | Pre-filter to curated markers with known significance; use structured prompt with established associations; label confidence tiers |
-
-## Performance Traps
-
-| Trap | Symptoms | Prevention | When It Breaks |
-|------|----------|------------|----------------|
-| Full `history.json` scan on every Cmd+K search | Search latency >1s, grows linearly with history size | Index recent history on startup; cap Cmd+K to last 30 days; full search in DevTools only | History exceeds ~5000 entries (already noted as unbounded in CONCERNS.md) |
-| Loading all `data/health/YYYY-MM-DD.json` files for dashboard charts | Dashboard load time spikes after months of Apple Health data | Pre-aggregate daily summaries into `data/health/summary.json`; load individual days only on drill-down | After ~90 days of health data (~90 files to read and merge) |
-| In-memory genome SNP index (600K+ entries) kept alive during search | 50-100MB memory overhead for genome data during search fan-out | Genome search should be opt-in for Cmd+K (most searches aren't about SNPs); lazy-load index only when genome category selected | Always — the index is large by design (line 11 of genome.js: in-memory Map with TTL) |
-| Backup scanning entire `data/` tree for modification timestamps | Backup scheduling takes seconds, blocks event loop | Use `fs.watch` or maintain a change manifest that services update on write; scan only on first backup or after restart | `data/runs/` has 815+ directories; `data/cos/` has deep nested structures |
-| Cross-insights engine running all correlation checks on every data change | API lag on meatspace or digital-twin updates | Compute insights on schedule (daily) or on explicit user request, not reactively on every data mutation | When genome markers + health metrics + taste dimensions exceed ~100 data points |
-
-## UX Pitfalls
-
-| Pitfall | User Impact | Better Approach |
-|---------|-------------|-----------------|
-| Search results with no source context | User sees "MTHFR C677T" but doesn't know if it's from genome, brain, or memory | Every search result card must show source icon + category label + timestamp + deep link |
-| Backup "success" with no verification | User trusts backup is working; discovers corrupt backup during emergency restore | Show last verified restore test date on dashboard; backup widget should distinguish "copied" from "verified" |
-| Apple Health import with no progress indication | User uploads 500MB XML, sees spinner for 10+ minutes, assumes it crashed | Stream progress via WebSocket: "Parsed 45,000 of ~2,000,000 records (2.3%)" with ETA |
-| Cross-insights showing genome health risks without context | User sees "elevated Alzheimer's risk" without understanding relative risk or actionability | Always show: what the marker means, population frequency, what's actionable, link to source study |
-| Cmd+K results mixing high-value and low-value matches | First 10 results are all history entries instead of the brain capture the user wanted | Source-type boosting with configurable weights; apps and brain captures ranked higher than raw history entries |
-
-## "Looks Done But Isn't" Checklist
-
-- [ ] **Backup system:** Often missing restore verification — verify by actually restoring to a temp directory and running JSON.parse on every file
-- [ ] **Backup system:** Often missing drive-unmount detection — test with drive unplugged, verify backup fails loudly
-- [ ] **Apple Health import:** Often missing deduplication — uploading the same XML twice should not create duplicate records (deduplicate by metric + timestamp)
-- [ ] **Apple Health import:** Often missing timezone handling — Apple Health XML records use local timezone; PortOS data uses UTC (per ecosystem.config.cjs `TZ: 'UTC'`)
-- [ ] **Cross-insights:** Often missing "no data" states — what does the engine show when genome is uploaded but no health data exists yet, or vice versa?
-- [ ] **Cmd+K search:** Often missing empty-state and error-state UX — what happens when search returns zero results? When one source errors?
-- [ ] **Cmd+K search:** Often missing keyboard navigation — up/down arrow to select results, Enter to navigate, Escape to close
-- [ ] **Migration cleanup:** Often missing route redirect for old URLs — bookmarks and browser history pointing to `/digital-twin/genome` should redirect to `/meatspace`
-- [ ] **Backup manifest:** Often missing checksums — a file list without SHA-256 hashes can't detect bit rot or partial writes
-
-## Recovery Strategies
-
-| Pitfall | Recovery Cost | Recovery Steps |
-|---------|---------------|----------------|
-| Corrupt backup (mid-write copy) | MEDIUM | Re-run backup with write coordination; validate existing backups by parsing all JSON files; discard corrupt snapshots |
-| OOM during Apple Health XML import | LOW | Restart PM2 process; switch to streaming parser; re-run import (idempotent if deduplication works) |
-| Spurious cross-domain insights shipped to UI | MEDIUM | Add confidence tier labels retroactively; clear cached insights; rebuild correlation engine with grounded-only mode |
-| Search fan-out timeout causing missing results | LOW | Add per-source timeouts; results appear incrementally; no data loss, just UX degradation |
-| Silent backup failure (unmounted drive) | HIGH if data loss occurs | If original data intact: fix mount detection, re-run backup. If original data lost: no recovery possible — this is the pitfall that justifies M45's priority |
-| Genome data in wrong directory | LOW | One-time migration script: `mv data/digital-twin/genome-* data/meatspace/`; update service path constant |
-| Health Auto Export schema change breaks ingestion | MEDIUM | Retrieve raw payloads from app's internal cache (if available); update Zod schema; re-ingest; implement `.passthrough()` to prevent recurrence |
-
-## Pitfall-to-Phase Mapping
-
-| Pitfall | Prevention Phase | Verification |
-|---------|------------------|--------------|
-| Backup copies corrupt mid-write JSON | M45 (Backup) | Restore test passes JSON.parse on 100% of backed-up files |
-| External drive unmount goes undetected | M45 (Backup) | Unplug drive, trigger backup, verify red status on dashboard within 1 minute |
-| Apple Health XML OOM | M44 P7 (Apple Health) | Import 500MB+ XML file while monitoring `process.memoryUsage().heapUsed` stays under 300MB |
-| Health Auto Export schema drift | M44 P7 (Apple Health) | Add unknown fields to test payload; verify they're stored, not rejected |
-| Cross-insights spurious correlations | M42 P5 (Cross-Insights) | Every displayed insight traces back to a ClinVar entry or curated marker; no LLM-fabricated associations |
-| Search fan-out cascading latency | M46 (Cmd+K Search) | Disable one search source (e.g., memory); verify other results still return within 500ms |
-| Genome data in wrong directory | M44 P6 (Migration Cleanup) | `ls data/meatspace/genome*` shows genome files; `ls data/digital-twin/genome*` returns nothing |
-| IdentityTab broken genome link | M44 P6 (Migration Cleanup) | Click Genome card in IdentityTab; verify it navigates to MeatSpace genome view, not 404 |
-| Apple Health timezone mismatch | M44 P7 (Apple Health) | Import record with known local timestamp; verify stored UTC timestamp is correct offset |
-
-## Sources
-
-- Codebase analysis: `server/services/genome.js` (line 7: `GENOME_DIR = PATHS.digitalTwin`), `server/services/meatspace.js` (line 11: imports from genome.js), `client/src/components/digital-twin/tabs/IdentityTab.jsx` (line 190: dead `/digital-twin/genome` link)
-- `.planning/codebase/CONCERNS.md` — race conditions in file writes, missing mutex in CoS, unbounded history, memory embeddings out-of-sync
-- `PLAN.md` M44 P7 spec — references `xml-stream` for streaming parse, Health Auto Export server reference repos
-- `PLAN.md` M45 spec — incremental backup with checksums, retention policy
-- `PLAN.md` M46 spec — fan-out to 7+ sources, `Promise.all` pattern
-- `ecosystem.config.cjs` — `TZ: 'UTC'` base env, `max_memory_restart: '500M'` for server
-- Apple Health export XML format: records use device-local timezone, not UTC (established behavior since iOS 8)
-- macOS volume mounting behavior: `/Volumes/<name>/` directory persists briefly after unmount on APFS
-
----
-*Pitfalls research for: PortOS next actions batch (M44 P6-P7, M42 P5, M45, M46)*
-*Researched: 2026-02-26*
diff --git a/.planning/research/STACK.md b/.planning/research/STACK.md
deleted file mode 100644
index 924f1041b0..0000000000
--- a/.planning/research/STACK.md
+++ /dev/null
@@ -1,233 +0,0 @@
-# Stack Research
-
-**Domain:** Personal OS -- JSON backup, Apple Health ingestion, unified search, cross-domain insights, route cleanup
-**Researched:** 2026-02-26
-**Confidence:** HIGH (versions verified via npm registry; patterns verified against existing codebase)
-
-## Recommended Stack
-
-### Core Technologies
-
-| Technology | Version | Purpose | Why Recommended |
-|------------|---------|---------|-----------------|
-| Node.js `child_process.execFile` | built-in | Invoke `rsync` for incremental backup | rsync is the gold standard for incremental file sync. Using execFile (not exec) avoids shell injection. Already a pattern in PortOS (shell.js uses child_process). No npm wrapper needed -- the `rsync` npm package (0.6.1) is unmaintained since 2014 and just shells out anyway. |
-| `fast-xml-parser` | ^5.4.1 | Parse Apple Health XML exports | Zero-dependency, fastest pure-JS XML parser. Handles 500MB+ Apple Health exports via streaming mode (v5 added SAX-like event API). xml2js is slower, heavier, and hasn't had a major release since 2023. sax/saxes are lower-level and require manual tree building. |
-| `cmdk` | ^1.1.1 | Cmd+K command palette overlay | Purpose-built for exactly this pattern. Built on Radix primitives (Dialog, Compose Refs). 4 deps, 82KB unpacked. React 18 compatible. Used by Vercel, Linear, Raycast web. The alternative (building from scratch with @radix-ui/react-dialog + custom input) takes 3x longer for the same result. |
-| `fuse.js` | ^7.1.0 | Client-side fuzzy search for Cmd+K | Zero-dependency, 456KB unpacked, works in browser. Handles typo-tolerant matching across heterogeneous data (app names, brain items, health metrics). Already proven in the fuzzy-search category -- most downloaded client-side search library on npm. |
-| `tinykeys` | ^3.0.0 | Global keyboard shortcut binding | 650 bytes, zero dependencies. Binds Cmd+K globally without conflicting with input fields. The alternative (hotkeys-js at 4.0.2) is 10x larger and has a jQuery-era API. mousetrap (1.6.5) is unmaintained since 2020. |
-
-### Supporting Libraries
-
-| Library | Version | Purpose | When to Use |
-|---------|---------|---------|-------------|
-| `chokidar` | ^5.0.0 | Watch `data/` directory for changes to trigger backup | Only needed if implementing "backup on change" mode. For scheduled-only backup, use the existing eventScheduler.js. v5 is a complete rewrite -- ESM-native, no binary deps. |
-| `fflate` | ^0.8.2 | Compress backup snapshots | **Already in the project.** Use for optional gzip of JSON snapshots before rsync. Faster than Node's built-in zlib for single-file operations. |
-| `saxes` | ^6.0.0 | Streaming XML parser (fallback) | Only if fast-xml-parser v5 SAX mode proves insufficient for edge cases. saxes is a maintained fork of sax with better spec compliance. Not needed unless fast-xml-parser fails on malformed Apple Health XML. |
-
-### Development Tools
-
-| Tool | Purpose | Notes |
-|------|---------|-------|
-| Sample Apple Health XML | Test data for M44 P7 | Generate a minimal `export.xml` with `<HealthData>`, `<Record>`, `<Workout>`, `<ActivitySummary>` elements. Real exports are 200MB-2GB; test with 1000 records. |
-| `vitest` (existing) | Test backup/restore, XML parsing, search index | Already in project at ^4.0.16. Add test cases for each new service. |
-
-## Feature-Specific Stack Decisions
-
-### M45: Data Backup & Recovery
-
-**Strategy:** `rsync` via `child_process.execFile` with the existing `eventScheduler.js` for scheduling.
-
-**Why rsync:**
-- Incremental by default (only copies changed bytes via delta algorithm)
-- Handles the `data/` directory tree (nested JSON, screenshots, uploads) without custom logic
-- Already installed on macOS (ships with the OS)
-- `--link-dest` flag enables space-efficient historical snapshots (hardlinks to unchanged files)
-- `--exclude` patterns for temp files, locks, etc.
-
-**Why NOT a JS backup library:**
-- No maintained Node.js backup library exists that rivals rsync's capabilities
-- `archiver` (npm) creates full archives, not incremental
-- Custom JS file-diff would be slower and buggier than rsync's battle-tested C implementation
-- `node-rsync` npm package is abandoned; just call rsync directly
-
-**Scheduling:** Use the existing `eventScheduler.js` cron system (already handles cron expressions and timeout-safe timers). No need for `node-cron` or `node-schedule` -- PortOS already has this solved.
-
-**Backup manifest:** Write a `backup-manifest.json` alongside each backup with timestamp, file count, byte count, and duration for the restore UI to read.
-
-### M44 P7: Apple Health Data Ingestion
-
-**Two ingest paths:**
-
-1. **Health Auto Export app (JSON)** -- The app POSTs JSON via webhook or the user uploads exported JSON files. Structure:
- ```json
- {
- "data": {
- "metrics": [{ "name": "...", "units": "...", "data": [{ "date": "...", "qty": ... }] }],
- "workouts": [{ "name": "...", "duration": ..., "energyBurned": ... }],
- "stateOfMind": [...],
- "medications": [...],
- "symptoms": [...]
- }
- }
- ```
- Parse with plain `JSON.parse()` -- no library needed. Validate with Zod schemas.
-
-2. **Apple Health XML export** -- User exports from iPhone Health app, produces `export.xml` (200MB-2GB). Structure:
- ```xml
- <HealthData locale="en_US">
- <ExportDate value="2026-01-01"/>
- <Me HKCharacteristicTypeIdentifierBiologicalSex="HKBiologicalSexMale" .../>
- <Record type="HKQuantityTypeIdentifierStepCount" value="1234" startDate="..." endDate="..." sourceName="iPhone"/>
- <Record type="HKQuantityTypeIdentifierHeartRate" value="72" .../>
- <Workout workoutActivityType="HKWorkoutActivityTypeRunning" duration="30.5" .../>
- <ActivitySummary dateComponents="2026-01-01" activeEnergyBurned="500" .../>
- </HealthData>
- ```
- **Must use streaming** -- loading 2GB into memory will crash. `fast-xml-parser` v5 supports SAX-style event parsing. Process `<Record>` elements one at a time, aggregate by type, write to `data/meatspace/apple-health/` as categorized JSON files.
-
-**Why fast-xml-parser over alternatives:**
-- `xml2js`: DOM-based, loads entire file into memory. Will OOM on 2GB Apple Health exports.
-- `sax`: Works but unmaintained (last release 2024, no ESM support). Lower-level API requires manual tree construction.
-- `saxes`: Good alternative but fast-xml-parser v5 covers both DOM and SAX modes in one package.
-- `htmlparser2`: Designed for HTML, not strict XML. Overkill and wrong tool.
-
-### M46: Unified Search (Cmd+K)
-
-**Architecture:** Client-side search overlay backed by a server search API.
-
-**Client-side:**
-- `cmdk` for the overlay UI (dialog, input, result list, keyboard navigation)
-- `tinykeys` to bind Cmd+K globally (register in Layout.jsx, unregister on unmount)
-- `fuse.js` for instant client-side fuzzy matching of recently fetched results + static items (page navigation, quick actions)
-
-**Server-side:**
-- New `GET /api/search?q=...&sources=...` endpoint
-- Fans out to existing services in parallel:
- - Brain: query `brainStorage.js` (ideas, projects, people, admin)
- - Memory: use existing `searchBM25()` from `memoryBM25.js`
- - Apps: filter `apps.json` by name/description
- - History: filter `history.json` by command
- - Health: search meatspace data by metric name/date
- - Agents: filter agent configs by name/description
- - Digital Twin: search document titles/content
-- Each source returns `{ id, title, subtitle, type, url }` for uniform rendering
-- Response within 200ms target (all sources searched in parallel via `Promise.all`)
-
-**Why cmdk over building from scratch:**
-- Keyboard navigation (up/down/enter/escape) is non-trivial to get right for a11y
-- cmdk handles focus management, scroll-into-view, empty states, loading states
-- Radix Dialog underneath provides proper portal, focus trap, scroll lock
-- 82KB unpacked is negligible for the functionality delivered
-
-**Why NOT MiniSearch on the server:**
-- PortOS already has BM25 search (`lib/bm25.js`) and vector search (`memoryEmbeddings.js`). Adding MiniSearch would create a third search engine for no benefit.
-- The server search API should delegate to existing search implementations per source, not build a new unified index.
-
-**Why fuse.js on the client (not server):**
-- Client-side fuzzy matching provides instant results for navigation items and recently viewed data while server search is in-flight
-- Fuse.js handles heterogeneous result types (different field structures) with configurable keys
-- Zero latency for "go to page" type searches
-
-### M42 P5: Cross-Insights Engine
-
-**No new libraries needed.** This is a data correlation service that reads from existing JSON stores and produces derived insights.
-
-**Pattern:** A new `server/services/crossInsights.js` that:
-1. Reads genome markers from `data/digital-twin/genome.json` (savedMarkers)
-2. Reads health data from meatspace (blood, body, epigenetic, lifestyle)
-3. Reads taste profile from digital-twin
-4. Reads personality data from digital-twin
-5. Applies rule-based correlations (e.g., MTHFR genotype + folate blood levels)
-6. Caches results in `data/digital-twin/cross-insights.json`
-7. Refreshes when source data changes (listen to file writes or service events)
-
-**Why rule-based over ML:**
-- The correlations are well-documented in medical literature (e.g., APOE4 + cholesterol, MTHFR + homocysteine)
-- The user has a single genome -- not a dataset to train on
-- Rules are transparent, auditable, and explainable
-- Can extend to LLM-generated narrative summaries later using existing portos-ai-toolkit
-
-### M44 P6: Route/Reference Cleanup
-
-**No new libraries needed.** This is a code cleanup task:
-- Remove stale route comments referencing old digital-twin genome paths
-- Fix IdentityTab Genome card to point to MeatSpace genome
-- Grep for old `/api/digital-twin/genome` references and update to `/api/meatspace/genome` or `/api/genome`
-
-## Installation
-
-```bash
-# Server dependencies (M44 P7 + M45)
-cd server && npm install fast-xml-parser@^5.4.1
-
-# Client dependencies (M46)
-cd client && npm install cmdk@^1.1.1 fuse.js@^7.1.0 tinykeys@^3.0.0
-
-# Optional: only if implementing watch-based backup triggers
-cd server && npm install chokidar@^5.0.0
-```
-
-## Alternatives Considered
-
-| Recommended | Alternative | When to Use Alternative |
-|-------------|-------------|-------------------------|
-| `rsync` via execFile | `archiver` npm package | If target is cloud storage (S3/GCS) instead of mounted drive -- archiver creates zip/tar for upload. Not needed for local drive backup. |
-| `fast-xml-parser` v5 SAX mode | `saxes` ^6.0.0 | If fast-xml-parser chokes on malformed Apple Health XML (some exports have encoding issues). saxes is more lenient with bad XML. |
-| `cmdk` | Custom Radix Dialog + input | If cmdk's opinionated styling clashes with PortOS design tokens. But cmdk is unstyled by default -- it's just behavior. |
-| `fuse.js` client-side | Server-side unified search only | If data volume exceeds browser memory (~10K+ items). For PortOS single-user with ~hundreds of items per source, client-side is fine. |
-| `tinykeys` | `hotkeys-js` | If you need key sequence combos (e.g., `g then i` for "go to inbox"). tinykeys supports this too, so no reason to switch. |
-| `eventScheduler.js` (existing) | `node-cron` or `node-schedule` | Never for this project. PortOS already has a robust scheduler. Adding another creates confusion over which scheduler to use. |
-
-## What NOT to Use
-
-| Avoid | Why | Use Instead |
-|-------|-----|-------------|
-| `xml2js` | DOM-based parser that loads entire XML into memory. Apple Health exports are 200MB-2GB. Will OOM. | `fast-xml-parser` v5 with SAX/streaming mode |
-| `node-rsync` (npm) | Last published 2014, unmaintained, just a wrapper around exec anyway | Direct `child_process.execFile('rsync', [...args])` |
-| `node-cron` / `node-schedule` | PortOS already has `eventScheduler.js` with cron support. Adding a second scheduler creates maintenance burden and confusion. | Existing `eventScheduler.js` |
-| `MiniSearch` server-side | Would be a third search engine alongside BM25 and vector search. Unnecessary complexity. | Existing `memoryBM25.js` for text search; per-source filtering for other data |
-| `mousetrap` | Unmaintained since 2020. No ESM support. 10KB vs tinykeys' 650 bytes. | `tinykeys` ^3.0.0 |
-| `@headlessui/react` | 2.2.9 is Tailwind Labs' component library, but cmdk already bundles Radix Dialog. Adding both creates two dialog systems. | `cmdk` (includes Radix Dialog) |
-| `electron-store` / `conf` | Designed for Electron config, not web app data backup | `rsync` + JSON file operations |
-| SQLite / LevelDB | Adds database dependency to a JSON-file architecture. Violates project constraint. | Keep JSON files; use BM25 index for search |
-
-## Stack Patterns by Feature
-
-**If adding more health data sources later (e.g., Oura, Whoop, Garmin):**
-- Use the same ingest pattern: Zod schema per source, normalize to internal format, write to `data/meatspace/{source}/`
-- fast-xml-parser handles any XML-based exports; JSON.parse for JSON APIs
-- The cross-insights engine reads from normalized meatspace data regardless of source
-
-**If search needs semantic/vector capability later:**
-- The existing `memoryEmbeddings.js` + `memoryRetriever.js` already implements hybrid BM25+vector search
-- Extend the search API to use embeddings for brain/memory sources
-- Keep fuse.js on client for instant navigation; server handles semantic search
-
-**If backup target changes from local drive to NAS/cloud:**
-- rsync works over SSH (NAS: `rsync -az data/ user@nas:/backups/portos/`)
-- For S3/GCS, switch to `archiver` to create tar.gz, then upload via AWS SDK or `gsutil`
-- The backup service abstraction (schedule, manifest, status) stays the same
-
-## Version Compatibility
-
-| Package | Compatible With | Notes |
-|---------|-----------------|-------|
-| cmdk@^1.1.1 | React ^18, ^19 | Peer dependency explicitly supports React 18 (PortOS uses 18.3.1) |
-| fuse.js@^7.1.0 | Any (no framework dependency) | Zero dependencies, works anywhere |
-| tinykeys@^3.0.0 | Any (vanilla JS) | Framework-agnostic; use in useEffect cleanup |
-| fast-xml-parser@^5.4.1 | Node.js 14+ | v5 is ESM-native, matches PortOS's ES module setup |
-| chokidar@^5.0.0 | Node.js 16+ | v5 is a full rewrite, ESM-native, drops fsevents binary |
-
-## Sources
-
-- npm registry (verified 2026-02-26) -- all version numbers confirmed via `npm view [package] version`
-- cmdk peer dependencies: `react ^18 || ^19` (confirmed via `npm view cmdk peerDependencies`)
-- fast-xml-parser v5 SAX mode: confirmed in package description and v5 changelog
-- Health Auto Export JSON format: GitHub wiki at github.com/Lybron/health-auto-export/wiki/API-Export---JSON-Format
-- Apple Health XML structure: confirmed via community documentation and existing parser projects
-- Existing PortOS codebase: `memoryBM25.js`, `eventScheduler.js`, `bm25.js`, `genome.js` -- confirmed patterns already in use
-- rsync availability on macOS: ships with Darwin (PortOS runs on Darwin 23.5.0)
-
----
-*Stack research for: PortOS next actions batch (M44 P6-P7, M42 P5, M45, M46)*
-*Researched: 2026-02-26*
diff --git a/.planning/research/SUMMARY.md b/.planning/research/SUMMARY.md
deleted file mode 100644
index 4033795057..0000000000
--- a/.planning/research/SUMMARY.md
+++ /dev/null
@@ -1,182 +0,0 @@
-# Project Research Summary
-
-**Project:** PortOS -- Next Actions Batch (M44 P6/P7, M42 P5, M45, M46)
-**Domain:** Personal OS monorepo -- data protection, health ingestion, cross-domain intelligence, unified search
-**Researched:** 2026-02-26
-**Confidence:** HIGH
-
-## Executive Summary
-
-PortOS is a mature single-user personal OS with 44+ milestones of existing functionality spanning app management, AI orchestration, knowledge capture, digital identity, and health tracking. The next batch of five features transforms it from powerful but siloed into connected, protected, and searchable. Experts building these feature categories (incremental backup, health data ingestion, cross-domain correlation, command palette search) follow well-established patterns: rsync for file-level incremental backup, SAX streaming for large XML parsing, declarative rule engines for data correlation, and fan-out aggregation for multi-source search. Every feature maps cleanly onto the existing Express.js + React + JSON-file architecture with no new infrastructure required.
-
-The recommended approach is to build in strict dependency order: cleanup stale genome references first (unblocks insights), then backup (protects all data before adding new data writers), then Apple Health ingestion (adds the richest new data source), then cross-domain insights (correlates genome with health data), and finally unified search (benefits from all data sources existing). The only new npm dependencies are `fast-xml-parser` on the server (streaming XML parsing for Apple Health) and `cmdk`, `fuse.js`, `tinykeys` on the client (command palette UI). Everything else leverages existing PortOS infrastructure: `eventScheduler.js` for scheduling, `memoryBM25.js` for search, `child_process.execFile` for rsync, and Socket.IO for real-time progress.
-
-The key risks are (1) backup copying mid-write JSON files produces corrupt backups that give false confidence, (2) Apple Health XML exports at 500MB-2GB will OOM the server if not streamed, (3) cross-domain insights generating spurious correlations that erode trust, and (4) search fan-out latency cascading when one source is slow. All four have concrete prevention strategies: write coordination before backup, mandatory streaming parser, grounded-only correlation rules, and `Promise.allSettled` with per-source timeouts. The most dangerous pitfall is silent backup failure when an external drive unmounts -- the user believes data is protected when it is not.
-
-## Key Findings
-
-### Recommended Stack
-
-The stack is deliberately minimal. Three new client packages (`cmdk`, `fuse.js`, `tinykeys`) and one new server package (`fast-xml-parser`) cover all five features. Everything else uses existing PortOS infrastructure or macOS built-ins.
-
-**Core technologies:**
-- **rsync via child_process.execFile**: Incremental backup -- battle-tested C implementation, ships with macOS, handles delta sync and hardlinked snapshots
-- **fast-xml-parser ^5.4.1**: Apple Health XML parsing -- only parser supporting both DOM and SAX modes in one package; v5 SAX handles 500MB+ files without OOM
-- **cmdk ^1.1.1**: Cmd+K command palette -- built on Radix primitives, handles keyboard navigation/focus/scroll, unstyled by default
-- **fuse.js ^7.1.0**: Client-side fuzzy search -- zero dependencies, instant results for navigation while server search is in-flight
-- **tinykeys ^3.0.0**: Global keyboard shortcuts -- 650 bytes, binds Cmd+K without conflicting with input fields
-
-**What NOT to use:** xml2js (OOM on large files), node-rsync (abandoned), node-cron (duplicates existing scheduler), MiniSearch (third search engine alongside BM25 + vector), mousetrap (unmaintained).
-
-See `.planning/research/STACK.md` for version compatibility matrix and alternatives analysis.
-
-### Expected Features
-
-**Must have (table stakes):**
-- Incremental backup with SHA-256 manifest, configurable schedule, manual trigger, and health indicator widget
-- POST /api/health/ingest endpoint with Zod validation, deduplication, and day-partitioned storage
-- Basic health dashboard cards (steps, heart rate, sleep)
-- Genome-to-health correlation rules with provenance citations
-- Cmd+K overlay with categorized results, debounced input, deep-link navigation
-
-**Should have (ship after v1 validation):**
-- Dry-run restore preview and selective per-directory restore
-- Bulk Apple Health XML import with WebSocket progress
-- LLM narrative summaries and contradiction detection in insights
-- Search history, keyboard navigation, source-type filtering
-
-**Defer (v2+):**
-- Workout GPS route maps, additional health platform support
-- Temporal insight evolution, semantic search across all sources
-- Quick actions from search results, natural language date queries
-
-See `.planning/research/FEATURES.md` for full prioritization matrix, anti-features, and dependency graph.
-
-### Architecture Approach
-
-All five features follow the existing service-per-domain pattern: each gets a service file and route file, mounted in `server/index.js`. The backup service uses the brainScheduler interval pattern for scheduling. The search service uses an adapter/fan-out pattern with `Promise.allSettled`. The insights engine is strictly read-only, reading from genome/health/taste services but never writing back. Apple Health routes nest under the existing meatspace mount. The Cmd+K overlay is a single component in Layout.jsx with a global keyboard hook. No new PM2 processes, no new ports, no new data stores.
-
-**Major components:**
-1. **Backup Service** (`server/services/backup.js`) -- schedules rsync to external drive, writes manifest, emits status via Socket.IO
-2. **Apple Health Service** (`server/services/appleHealth.js`) -- stream-parses XML, normalizes records, deduplicates, writes to `data/meatspace/health/`
-3. **Cross-Insights Engine** (`server/services/insights.js`) -- reads genome + health + taste data, applies declarative correlation rules, caches results
-4. **Unified Search API** (`server/services/search.js`) -- fans out to domain-specific adapters, merges and ranks results, returns uniform response
-5. **Command Palette** (`client/src/components/CommandPalette.jsx`) -- keyboard-triggered modal, calls search API, renders categorized results
-
-See `.planning/research/ARCHITECTURE.md` for data flow diagrams, pattern catalog, and integration point map.
-
-### Critical Pitfalls
-
-1. **Backup copies mid-write JSON files** -- Use write coordination (Socket.IO flush signal + mutex) and post-copy JSON.parse validation on every backed-up file. Corrupt backups are worse than no backups.
-2. **Apple Health XML OOM on 500MB+ files** -- Mandatory SAX/streaming parser from day one. Never accumulate records in memory. Process in worker or subprocess if possible.
-3. **External drive unmount goes undetected** -- Verify mount with filesystem device ID check before each backup. Write sentinel file. Never mkdir -p the backup target. Surface failures prominently on dashboard.
-4. **Cross-insights produce spurious correlations** -- Ground all genome-health insights in ClinVar/SNPedia. Use LLM to synthesize pre-validated correlations, not discover new ones. Label confidence tiers in UI.
-5. **Search fan-out cascading latency** -- Use `Promise.allSettled` with 300ms per-source timeouts. Return partial results fast. Cap history search to recent entries.
-6. **Health Auto Export schema drift** -- Use Zod `.passthrough()` on ingest schema. Log raw payloads before validation. Implement "last heard from" staleness warning.
-7. **Genome data physically in wrong directory** -- M44 P6 must migrate files from `data/digital-twin/genome-*` to `data/meatspace/genome-*` and update service path constants.
-
-See `.planning/research/PITFALLS.md` for recovery strategies, verification tests, and "looks done but isn't" checklist.
-
-## Implications for Roadmap
-
-Based on combined research, the five milestones have a clear dependency chain that dictates build order. Two can be parallelized.
-
-### Phase 1: Genome Migration Cleanup (M44 P6)
-
-**Rationale:** Zero-risk housekeeping that unblocks the cross-insights engine. Genome data currently lives in `data/digital-twin/` while served under meatspace routes -- a ticking time bomb if anyone cleans up the digital-twin directory.
-**Delivers:** Correct genome data location, fixed IdentityTab navigation, clean route comments, redirect from old URLs.
-**Addresses:** Table stakes from FEATURES.md (fix stale references, fix dead links).
-**Avoids:** Pitfall 6 (genome data in wrong directory), Pitfall of insights engine reading from incorrect path.
-**Effort:** Small (1-2 hours). Includes data migration script.
-
-### Phase 2: Data Backup and Recovery (M45)
-
-**Rationale:** Every subsequent phase adds new data writers (health data, insight caches). Backup must be in place before the blast radius of data loss increases. This is the highest-risk-reduction feature in the batch.
-**Delivers:** Incremental rsync backup, SHA-256 manifest, configurable schedule, manual trigger, dashboard health widget, restore capability.
-**Uses:** rsync via execFile, existing eventScheduler.js, Socket.IO for status.
-**Implements:** Backup Service component with interval scheduler pattern.
-**Avoids:** Pitfall 1 (corrupt mid-write copies), Pitfall 5 (silent unmount failure).
-**Note:** Can be built in parallel with Phase 1 (zero overlap).
-
-### Phase 3: Apple Health Integration (M44 P7)
-
-**Rationale:** Adds the richest new data source, which dramatically enhances the cross-insights engine. The meatspace infrastructure already exists. Must use streaming parser from the start -- retrofitting is impractical.
-**Delivers:** POST /api/health/ingest for Health Auto Export JSON, Zod validation with .passthrough(), dedup by metric+timestamp, day-partitioned storage, basic dashboard cards.
-**Uses:** fast-xml-parser v5 (SAX mode for bulk XML), plain JSON.parse for Health Auto Export JSON.
-**Implements:** Apple Health Service with stream parser and meatspace data integration.
-**Avoids:** Pitfall 2 (XML OOM), Pitfall 7 (schema drift breaking ingestion).
-
-### Phase 4: Cross-Domain Insights Engine (M42 P5)
-
-**Rationale:** Depends on clean genome routes (Phase 1) and benefits enormously from Apple Health data (Phase 3). Building earlier means fewer correlations to ship. The rule engine itself is straightforward; the hard part is curating scientifically grounded rules.
-**Delivers:** Genome-to-health correlation rules, taste-to-identity theme extraction, insight persistence with provenance citations, manual refresh trigger.
-**Uses:** Existing genome.js curated markers, existing AI provider infra (for narrative summaries later), declarative rule engine pattern.
-**Implements:** Cross-Insights Engine with read-only aggregation pattern.
-**Avoids:** Pitfall 3 (spurious correlations), anti-pattern of circular service dependencies.
-
-### Phase 5: Unified Search / Cmd+K (M46)
-
-**Rationale:** Benefits from all data sources existing. Each domain adapter is independent so search can ship incrementally, but the experience is richest with all domains populated. Naturally the last feature.
-**Delivers:** Cmd+K overlay, server-side fan-out search across 7+ sources, categorized results with source icons, debounced input, deep-link navigation.
-**Uses:** cmdk, fuse.js, tinykeys on client. Existing BM25 + per-source filtering on server.
-**Implements:** Unified Search API (fan-out aggregator) + Command Palette component.
-**Avoids:** Pitfall 4 (cascading latency from slow sources).
-
-### Phase Ordering Rationale
-
-- **Phase 1 before Phase 4:** Cross-insights reads genome data through genome.js. If data is in the wrong directory, insights silently fail or read stale data.
-- **Phase 2 before Phase 3:** Apple Health bulk imports add hundreds of MB of new data. Backup must protect existing data before adding new data writers.
-- **Phase 3 before Phase 4:** The most compelling cross-insights are genome-to-health correlations. Without health data, the engine can only do genome+taste (less valuable).
-- **Phase 5 last:** Search is additive. It works over whatever data exists. Shipping it last means maximum searchable content from day one.
-- **Phases 1+2 in parallel:** Zero overlap in files touched, zero dependency between them. Ship both before moving to Phase 3.
-- **Phases 3+4 partially parallelizable:** Insights engine can start with genome-only correlations while health data ingestion is built. Add health correlations when Phase 3 completes.
-
-### Research Flags
-
-Phases likely needing deeper research during planning:
-- **Phase 3 (Apple Health):** Health Auto Export JSON schema is documented but not verified against the current app version (v7+). Test with actual payload before finalizing Zod schema. Also: timezone handling between Apple Health (local TZ) and PortOS (UTC) needs careful attention.
-- **Phase 4 (Cross-Insights):** Curating scientifically grounded correlation rules requires reviewing the 117 markers in curatedGenomeMarkers.js against ClinVar/SNPedia for actionable health correlations. This is domain expertise, not engineering.
-
-Phases with standard patterns (skip research-phase):
-- **Phase 1 (Cleanup):** Pure find-and-replace + data migration. No research needed.
-- **Phase 2 (Backup):** rsync incremental backup is a decades-old pattern. Architecture decisions are clear.
-- **Phase 5 (Search):** Fan-out search aggregation and command palette are well-documented patterns. cmdk handles the hard parts.
-
-## Confidence Assessment
-
-| Area | Confidence | Notes |
-|------|------------|-------|
-| Stack | HIGH | All package versions verified via npm registry 2026-02-26. Compatibility confirmed against existing React 18.3.1 and Node.js versions. No speculative choices. |
-| Features | MEDIUM-HIGH | Table stakes are clear and well-grounded in codebase analysis. Health Auto Export JSON schema specifics need validation against current app version. |
-| Architecture | HIGH | All five features follow existing PortOS patterns. No new infrastructure. Data flow diagrams align with codebase inspection. |
-| Pitfalls | HIGH | Pitfalls grounded in specific codebase findings (genome.js line 7, CONCERNS.md race conditions, ecosystem.config.cjs memory limits). Verification tests are concrete. |
-
-**Overall confidence:** HIGH
-
-### Gaps to Address
-
-- **Health Auto Export payload schema:** Feature research cites the app's GitHub wiki for JSON format, but the schema may have changed in recent app versions. Validate with an actual POST from the iOS app before finalizing the Zod schema. Mitigate with `.passthrough()` to accept unknown fields.
-- **Apple Health XML timezone handling:** Records use device-local timezone; PortOS runs in UTC. The conversion logic needs to be specified during Phase 3 planning. This is a known pitfall but the exact offset strategy (store original + UTC? convert on ingest?) is not decided.
-- **External drive mount path:** The backup target configuration assumes a macOS `/Volumes/` mount. The specific validation approach (diskutil vs. statfs device ID comparison) should be prototyped during Phase 2 planning.
-- **Cross-insights rule curation:** The 117 curated genome markers exist, but which ones have actionable health correlations (vs. purely informational) needs domain review. This is content work, not engineering, and may take longer than the code.
-- **Fuse.js vs. server-only search:** Architecture research suggests building the Cmd+K overlay without cmdk (custom component), while Stack research recommends cmdk. Recommendation: use cmdk -- it solves keyboard navigation and focus management, which are non-trivial to get right for accessibility.
-
-## Sources
-
-### Primary (HIGH confidence)
-- PortOS codebase: `server/services/genome.js`, `server/services/memoryBM25.js`, `server/services/brainScheduler.js`, `ecosystem.config.cjs`, `server/lib/bm25.js`
-- PortOS planning docs: `PLAN.md`, `PROJECT.md`, `.planning/codebase/CONCERNS.md`, `.planning/codebase/ARCHITECTURE.md`
-- npm registry (verified 2026-02-26): fast-xml-parser, cmdk, fuse.js, tinykeys, chokidar version and peer dependency checks
-
-### Secondary (MEDIUM confidence)
-- Health Auto Export app: GitHub wiki (github.com/Lybron/health-auto-export), App Store listing -- JSON schema documentation
-- Apple Health XML format: community parser projects (github.com/cvyl/apple-health-parser), established format since iOS 8
-- Cmd+K UX patterns: observed in Raycast, VS Code, Linear, Notion, Slack
-
-### Tertiary (LOW confidence)
-- Apple Health XML timezone behavior: inferred from community documentation. Needs validation with actual export file.
-- macOS volume unmount persistence behavior on APFS: observed but edge cases may vary by macOS version.
-
----
-*Research completed: 2026-02-26*
-*Ready for roadmap: yes*