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

docs: complete project research for next actions batch

Adam Eivy6de3431161d7
diff --git a/.planning/research/ARCHITECTURE.md b/.planning/research/ARCHITECTURE.md
new file mode 100644
index 0000000000..875aafa646
--- /dev/null
+++ b/.planning/research/ARCHITECTURE.md
@@ -0,0 +1,367 @@
+# 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
new file mode 100644
index 0000000000..2919730e34
--- /dev/null
+++ b/.planning/research/FEATURES.md
@@ -0,0 +1,291 @@
+# 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
new file mode 100644
index 0000000000..bc36bd18f2
--- /dev/null
+++ b/.planning/research/PITFALLS.md
@@ -0,0 +1,265 @@
+# 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
new file mode 100644
index 0000000000..924f1041b0
--- /dev/null
+++ b/.planning/research/STACK.md
@@ -0,0 +1,233 @@
+# 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
new file mode 100644
index 0000000000..4033795057
--- /dev/null
+++ b/.planning/research/SUMMARY.md
@@ -0,0 +1,182 @@
+# 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*