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(04-01): complete insights engine backend plan

Adam Eivy4bf07493b3c4
diff --git a/.planning/REQUIREMENTS.md b/.planning/REQUIREMENTS.md
index fd68fe9ba8..d178f7dc20 100644
--- a/.planning/REQUIREMENTS.md
+++ b/.planning/REQUIREMENTS.md
@@ -34,10 +34,10 @@ Requirements for this milestone batch. Each maps to roadmap phases.
### Cross-Insights
-- [ ] **INS-01**: Rule-based genome-to-health correlations using curated 117 markers against actual blood/body data
-- [ ] **INS-02**: LLM-generated taste-to-identity theme analysis connecting preferences to identity patterns
+- [x] **INS-01**: Rule-based genome-to-health correlations using curated 117 markers against actual blood/body data
+- [x] **INS-02**: LLM-generated taste-to-identity theme analysis connecting preferences to identity patterns
- [ ] **INS-03**: Insights dashboard UI with confidence levels, source attribution, and domain grouping
-- [ ] **INS-04**: LLM narrative summaries of cross-domain patterns refreshable on demand
+- [x] **INS-04**: LLM narrative summaries of cross-domain patterns refreshable on demand
### Unified Search
@@ -105,10 +105,10 @@ Which phases cover which requirements. Updated during roadmap creation.
| HLT-04 | Phase 3 | Complete |
| HLT-05 | Phase 3 | Complete |
| HLT-06 | Phase 3 | Complete |
-| INS-01 | Phase 4 | Pending |
-| INS-02 | Phase 4 | Pending |
+| INS-01 | Phase 4 | Complete |
+| INS-02 | Phase 4 | Complete |
| INS-03 | Phase 4 | Pending |
-| INS-04 | Phase 4 | Pending |
+| INS-04 | Phase 4 | Complete |
| SRC-01 | Phase 5 | Pending |
| SRC-02 | Phase 5 | Pending |
| SRC-03 | Phase 5 | Pending |
diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md
index 3fee828709..23d8f13684 100644
--- a/.planning/ROADMAP.md
+++ b/.planning/ROADMAP.md
@@ -106,5 +106,5 @@ Note: Phases 1 and 2 have no dependency on each other and can execute in paralle
| 1. Genome Migration Cleanup | 1/1 | Complete | 2026-02-26 |
| 2. Data Backup & Recovery | 2/2 | Complete | 2026-02-26 |
| 3. Apple Health Integration | 2/3 | Complete | 2026-02-26 |
-| 4. Cross-Domain Insights Engine | 0/2 | Planned | - |
+| 4. Cross-Domain Insights Engine | 1/2 | In Progress| |
| 5. Unified Search (Cmd+K) | 0/2 | Not started | - |
diff --git a/.planning/STATE.md b/.planning/STATE.md
index 4674fe53be..d0316ee558 100644
--- a/.planning/STATE.md
+++ b/.planning/STATE.md
@@ -3,12 +3,12 @@ gsd_state_version: 1.0
milestone: v1.0
milestone_name: milestone
status: unknown
-last_updated: "2026-02-26T23:46:18.374Z"
+last_updated: "2026-02-26T23:53:00.000Z"
progress:
total_phases: 5
completed_phases: 3
total_plans: 8
- completed_plans: 6
+ completed_plans: 7
---
# Project State
@@ -18,16 +18,16 @@ progress:
See: .planning/PROJECT.md (updated 2026-02-26)
**Core value:** Ship five next actions that transform PortOS from siloed features into a connected, protected, and searchable system
-**Current focus:** Phase 3 complete — Phase 4 (health insights) next
+**Current focus:** Phase 4 (cross-domain insights engine) — Plan 01 complete, dashboard frontend next
## Current Position
-Phase: 3 of 5 (Apple Health Integration) — COMPLETE
-Plan: 3 of 3 in current phase (all plans done)
-Status: Plan 03-03 complete — MeatSpace Health tab with metric cards and correlation charts shipped
-Last activity: 2026-02-26 -- Plan 03-03 complete (Health tab UI with four metric cards and two correlation charts)
+Phase: 4 of 5 (Cross-Domain Insights Engine) — IN PROGRESS
+Plan: 1 of 2 in current phase (04-01 complete)
+Status: Plan 04-01 complete — insights engine backend with 5 endpoints and client API functions
+Last activity: 2026-02-26 -- Plan 04-01 complete (insights service, routes, validation, client API)
-Progress: [██████░░░░] 60%
+Progress: [███████░░░] 70%
## Performance Metrics
@@ -45,9 +45,10 @@ Progress: [██████░░░░] 60%
| 03-apple-health-integration | 1 | 210s | 210s |
| 03-apple-health-integration | 2 | 180s | 180s |
| 03-apple-health-integration | 3 | ~15min | ~15min |
+| 04-cross-domain-insights-engine | 1 | 174s | 174s |
**Recent Trend:**
-- Last 5 plans: 02-01 (135s), 02-02 (~10min), 03-01 (210s), 03-02 (180s), 03-03 (~15min)
+- Last 5 plans: 02-02 (~10min), 03-01 (210s), 03-02 (180s), 03-03 (~15min), 04-01 (174s)
- Trend: stable (~2-15 min/plan)
*Updated after each plan completion*
@@ -82,6 +83,10 @@ Recent decisions affecting current work:
- [Phase 03-apple-health-integration plan 03]: Correlation text summaries computed via pure data math (no LLM) — zero latency, deterministic
- [Phase 03-apple-health-integration plan 03]: 14-day minimum threshold guard prevents misleading correlations with sparse data
- [Phase 03-apple-health-integration plan 03]: Stethoscope icon chosen for Health tab — Activity used by Overview, HeartPulse used by Blood & Body
+- [Phase 04-cross-domain-insights-engine plan 01]: CONFIDENCE_FROM_STATUS uses "Evidence" and "Risk Marker" language — never causation language — per INS-01 requirement
+- [Phase 04-cross-domain-insights-engine plan 01]: CATEGORY_BLOOD_MAP covers 6 categories; other genome categories get empty matchedBloodValues (no blood analyte mapping available)
+- [Phase 04-cross-domain-insights-engine plan 01]: LLM generation functions return { available: false, reason } (not throw) when provider unavailable or no taste data
+- [Phase 04-cross-domain-insights-engine plan 01]: narrativeRefresh preserves previousText + previousGeneratedAt for client-side diff rendering
### Pending Todos
@@ -94,5 +99,5 @@ None yet.
## Session Continuity
Last session: 2026-02-26
-Stopped at: Completed 03-03-PLAN.md — MeatSpace Health tab with four metric cards and correlation charts complete
+Stopped at: Completed 04-01-PLAN.md — Insights engine backend (insightsService.js, routes, validation, client API)
Resume file: None
diff --git a/.planning/phases/04-cross-domain-insights-engine/04-01-SUMMARY.md b/.planning/phases/04-cross-domain-insights-engine/04-01-SUMMARY.md
new file mode 100644
index 0000000000..ad3e68879d
--- /dev/null
+++ b/.planning/phases/04-cross-domain-insights-engine/04-01-SUMMARY.md
@@ -0,0 +1,144 @@
+---
+phase: 04-cross-domain-insights-engine
+plan: 01
+subsystem: insights-backend
+tags: [insights, genome, blood-tests, taste-identity, llm, rest-api]
+dependency_graph:
+ requires:
+ - server/services/genome.js (getGenomeSummary)
+ - server/services/meatspaceHealth.js (getBloodTests)
+ - server/services/taste-questionnaire.js (getTasteProfile)
+ - server/services/providers.js (getActiveProvider, getProviderById)
+ - server/services/appleHealthQuery.js (getCorrelationData)
+ - server/lib/curatedGenomeMarkers.js (MARKER_CATEGORIES)
+ - server/lib/fileUtils.js (PATHS, ensureDir, readJSONFile)
+ - server/lib/errorHandler.js (asyncHandler)
+ provides:
+ - server/services/insightsService.js
+ - server/routes/insights.js
+ - /api/insights/* (5 endpoints)
+ - client insights API (5 functions)
+ affects:
+ - server/index.js
+ - server/lib/validation.js
+ - client/src/services/api.js
+ - data/insights/ (cache directory)
+tech_stack:
+ added: []
+ patterns:
+ - Cache-first reads with graceful degradation ({ available: false, reason })
+ - callProviderAISimple inline LLM call pattern (replicated from taste-questionnaire.js)
+ - Rule-based genome-blood correlation (no LLM, deterministic)
+ - previousText diff support for narrative versioning
+key_files:
+ created:
+ - server/services/insightsService.js
+ - server/routes/insights.js
+ modified:
+ - server/lib/validation.js
+ - server/index.js
+ - client/src/services/api.js
+ - .changelog/v1.14.x.md
+decisions:
+ - Correlation strength labels use "Evidence" and "Risk Marker" language — never causation language — per INS-01 requirement
+ - CONFIDENCE_FROM_STATUS maps marker status to human-readable confidence level with color
+ - CATEGORY_BLOOD_MAP covers 6 categories (cardiovascular, iron, methylation, diabetes, thyroid, nutrient); other categories get empty matchedBloodValues
+ - Cache files written to data/insights/themes.json and data/insights/narrative.json using ensureDir before first write
+ - narrativeRefresh preserves previousText and previousGeneratedAt for client-side diff
+ - LLM generation functions return { available: false, reason } (not throw) when provider unavailable or no data
+ - insightRefreshSchema uses optional() fields (not .optional().default(undefined)) to avoid presence side effects
+metrics:
+ duration: 174s
+ completed: 2026-02-26
+ tasks_completed: 2
+ files_created: 2
+ files_modified: 4
+---
+
+# Phase 4 Plan 1: Insights Engine Backend Summary
+
+**One-liner:** Cross-domain insights engine with genome-health correlation (rule-based), LLM taste-identity themes, and cross-domain narrative — all served via 5 REST endpoints with cache-first graceful degradation.
+
+## What Was Built
+
+### `server/services/insightsService.js`
+
+Five exported functions forming the insights engine core:
+
+1. **`getGenomeHealthCorrelations()`** — Pure rule-based. Loads genome markers, filters `not_found` entries, groups by `MARKER_CATEGORIES` key, looks up blood analyte values using `CATEGORY_BLOOD_MAP`, attaches `CONFIDENCE_FROM_STATUS` label per marker. Returns `{ available: true, categories, totalMarkers, matchedMarkers, sources }`. Degrades to `{ available: false, reason: 'no_genome' }` if genome not uploaded.
+
+2. **`getThemeAnalysis()`** — Cache-first. Reads `data/insights/themes.json`. Returns `{ available: false, reason: 'not_generated' }` if no cache.
+
+3. **`generateThemeAnalysis(providerId, model)`** — LLM generation. Gets completed taste profile sections, builds analytical third-person prompt requesting 3-5 theme objects (title, narrative, evidence array, strength). Strips code fences, parses JSON, persists to `data/insights/themes.json`.
+
+4. **`getCrossDomainNarrative()`** — Cache-first. Reads `data/insights/narrative.json`. Returns `{ available: false, reason: 'not_generated' }` if no cache.
+
+5. **`refreshCrossDomainNarrative(providerId, model)`** — LLM generation with diff support. Gathers genome category summaries, taste theme titles, and Apple Health availability. Builds second-person prompt. Persists to `data/insights/narrative.json` with `previousText` and `previousGeneratedAt` from existing cache for client-side diff rendering.
+
+### `server/routes/insights.js`
+
+Five REST endpoints, all wrapped in `asyncHandler`:
+
+| Method | Path | Handler |
+|--------|------|---------|
+| GET | /genome-health | getGenomeHealthCorrelations() |
+| GET | /themes | getThemeAnalysis() |
+| POST | /themes/refresh | generateThemeAnalysis(body.providerId, body.model) |
+| GET | /narrative | getCrossDomainNarrative() |
+| POST | /narrative/refresh | refreshCrossDomainNarrative(body.providerId, body.model) |
+
+POST routes validate body with `insightRefreshSchema` (optional providerId, optional model).
+
+### `server/lib/validation.js`
+
+Added `insightRefreshSchema`:
+```js
+export const insightRefreshSchema = z.object({
+ providerId: z.string().optional(),
+ model: z.string().optional()
+});
+```
+
+### `server/index.js`
+
+Mounted `insightsRoutes` at `/api/insights` — inserted alphabetically between `/api/instances` and `/api/jira`.
+
+### `client/src/services/api.js`
+
+Added `// Insights` section with 5 exported functions:
+- `getGenomeHealthCorrelations()`
+- `getInsightThemes()`
+- `refreshInsightThemes(providerId, model)`
+- `getInsightNarrative()`
+- `refreshInsightNarrative(providerId, model)`
+
+## Verification Results
+
+- All 5 insightsService.js functions exported and importable
+- All 5 routes registered in insights router
+- `insightRefreshSchema` exported from validation.js
+- `getThemeAnalysis()` returns `{ available: false, reason: 'not_generated' }` gracefully
+- `getCrossDomainNarrative()` returns `{ available: false, reason: 'not_generated' }` gracefully
+- Route mount confirmed in index.js at `/api/insights`
+- Client API functions confirmed in api.js
+
+## Commits
+
+| Task | Hash | Description |
+|------|------|-------------|
+| Task 1 | 0f20b69 | feat(04-01): create insightsService.js with genome-health correlation engine and LLM analysis functions |
+| Task 2 | e4dc2be | feat(04-01): create insights routes, Zod validation, mount in index.js, add client API functions |
+
+## Deviations from Plan
+
+None — plan executed exactly as written.
+
+## Self-Check: PASSED
+
+- server/services/insightsService.js: FOUND
+- server/routes/insights.js: FOUND
+- server/lib/validation.js (insightRefreshSchema): FOUND
+- server/index.js (/api/insights mount): FOUND
+- client/src/services/api.js (5 insight functions): FOUND
+- commit 0f20b69: FOUND
+- commit e4dc2be: FOUND