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-cross-domain-insights-engine): create phase plan

Adam Eivya0e876ebb326
diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md
index fc38119522..3ceccbcdbd 100644
--- a/.planning/ROADMAP.md
+++ b/.planning/ROADMAP.md
@@ -74,11 +74,11 @@ Plans:
2. LLM-generated taste-to-identity theme analysis connects user preferences to identity patterns
3. Insights dashboard groups results by domain with confidence levels and source attribution
4. LLM narrative summaries of cross-domain patterns can be refreshed on demand
-**Plans**: TBD
+**Plans**: 2 plans
Plans:
-- [ ] 04-01: TBD
-- [ ] 04-02: TBD
+- [ ] 04-01-PLAN.md -- Backend insights engine: insightsService.js with genome-health correlations, LLM taste-identity themes, cross-domain narrative; REST routes, Zod validation, client API functions (INS-01, INS-02, INS-04)
+- [ ] 04-02-PLAN.md -- Insights dashboard UI: /insights/:tab page with Overview, Genome-Health, Taste-Identity, Cross-Domain tabs; shared components, App.jsx routes, Layout.jsx nav entry (INS-03, INS-01, INS-02, INS-04)
### Phase 5: Unified Search (Cmd+K)
**Goal**: Any piece of information in PortOS is one keystroke away via a global search overlay
@@ -105,5 +105,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 | In Progress| |
-| 4. Cross-Domain Insights Engine | 0/2 | Not started | - |
+| 4. Cross-Domain Insights Engine | 0/2 | Planned | - |
| 5. Unified Search (Cmd+K) | 0/1 | Not started | - |
diff --git a/.planning/phases/04-cross-domain-insights-engine/04-01-PLAN.md b/.planning/phases/04-cross-domain-insights-engine/04-01-PLAN.md
new file mode 100644
index 0000000000..ff5140a7b3
--- /dev/null
+++ b/.planning/phases/04-cross-domain-insights-engine/04-01-PLAN.md
@@ -0,0 +1,355 @@
+---
+phase: 04-cross-domain-insights-engine
+plan: 01
+type: execute
+wave: 1
+depends_on: []
+files_modified:
+ - server/services/insightsService.js
+ - server/routes/insights.js
+ - server/index.js
+ - server/lib/validation.js
+ - client/src/services/api.js
+autonomous: true
+requirements:
+ - INS-01
+ - INS-02
+ - INS-04
+
+must_haves:
+ truths:
+ - "GET /api/insights/genome-health returns genome markers grouped by clinical category with matched blood test values and confidence levels"
+ - "GET /api/insights/themes returns cached LLM-generated taste-identity themes or triggers generation"
+ - "POST /api/insights/themes/refresh regenerates theme analysis from current taste profile data"
+ - "GET /api/insights/narrative returns cached cross-domain narrative with previous text for diff"
+ - "POST /api/insights/narrative/refresh generates new narrative preserving previous text"
+ - "All endpoints degrade gracefully when source data is missing (genome, blood tests, taste profile)"
+ artifacts:
+ - path: "server/services/insightsService.js"
+ provides: "Insights engine with correlation, theme, and narrative functions"
+ exports: ["getGenomeHealthCorrelations", "getThemeAnalysis", "generateThemeAnalysis", "getCrossDomainNarrative", "refreshCrossDomainNarrative"]
+ - path: "server/routes/insights.js"
+ provides: "REST API routes for insights"
+ exports: ["default (Router)"]
+ - path: "client/src/services/api.js"
+ provides: "Client API functions for insights endpoints"
+ exports: ["getGenomeHealthCorrelations", "getInsightThemes", "refreshInsightThemes", "getInsightNarrative", "refreshInsightNarrative"]
+ key_links:
+ - from: "server/routes/insights.js"
+ to: "server/services/insightsService.js"
+ via: "import * as insightsService"
+ pattern: "insightsService\\."
+ - from: "server/index.js"
+ to: "server/routes/insights.js"
+ via: "app.use('/api/insights')"
+ pattern: "app\\.use.*insights"
+ - from: "server/services/insightsService.js"
+ to: "server/services/genome.js"
+ via: "getGenomeSummary()"
+ pattern: "getGenomeSummary"
+ - from: "server/services/insightsService.js"
+ to: "server/services/meatspaceHealth.js"
+ via: "getBloodTests(), getBodyHistory()"
+ pattern: "getBloodTests|getBodyHistory"
+ - from: "server/services/insightsService.js"
+ to: "server/services/taste-questionnaire.js"
+ via: "getTasteProfile()"
+ pattern: "getTasteProfile"
+---
+
+<objective>
+Build the insights engine backend: a service layer that correlates genome markers with blood test data (rule-based), generates LLM taste-to-identity themes, and produces cross-domain narrative summaries. Wire up REST routes and client API functions.
+
+Purpose: Establish the complete data and API layer for the Insights dashboard. All three insight domains (genome-health, taste-identity, cross-domain narrative) are served from this backend — the frontend plan consumes these endpoints.
+
+Output: `insightsService.js` with 5 exported functions, `routes/insights.js` with 5 endpoints, Zod validation schemas, client API helpers, `data/insights/` cache directory.
+</objective>
+
+<execution_context>
+@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
+@/Users/antic/.claude/get-shit-done/templates/summary.md
+</execution_context>
+
+<context>
+
+<interfaces>
+<!-- Key types and contracts the executor needs. Extracted from codebase. -->
+
+From server/services/genome.js:
+```javascript
+export async function getGenomeSummary()
+// Returns: { uploaded: bool, savedMarkers: { [uuid]: { rsid, gene, category, status, name, description, implications, references } }, ... }
+// status values: 'beneficial', 'typical', 'concern', 'major_concern', 'not_found'
+```
+
+From server/lib/curatedGenomeMarkers.js:
+```javascript
+export const MARKER_CATEGORIES = {
+ longevity: { label: 'Longevity', icon: 'Sparkles', color: 'purple' },
+ cardiovascular: { label: 'Cardiovascular', icon: 'HeartPulse', color: 'rose' },
+ iron: { label: 'Iron Metabolism', icon: 'Droplet', color: 'red' },
+ methylation: { label: 'Methylation', icon: 'Zap', color: 'blue' },
+ nutrient: { label: 'Nutrient Metabolism', icon: 'Apple', color: 'emerald' },
+ caffeine: { label: 'Caffeine', icon: 'Coffee', color: 'amber' },
+ detox: { label: 'Detoxification', icon: 'Shield', color: 'green' },
+ inflammation: { label: 'Inflammation', icon: 'Flame', color: 'orange' },
+ tumor_suppression: { label: 'Tumor Suppression', icon: 'ShieldCheck', color: 'indigo' },
+ cognitive: { label: 'Cognitive', icon: 'Brain', color: 'cyan' },
+ cognitive_decline: { label: 'Cognitive Decline & Dementia Risk', icon: 'BrainCog', color: 'rose' },
+ sleep: { label: 'Sleep & Circadian', icon: 'Moon', color: 'violet' },
+ athletic: { label: 'Athletic Performance', icon: 'Dumbbell', color: 'sky' },
+ skin: { label: 'Skin & UV Response', icon: 'Sun', color: 'yellow' },
+ diabetes: { label: 'Blood Sugar & Diabetes', icon: 'Droplets', color: 'amber' },
+ gut_health: { label: 'Gut Health & Digestion', icon: 'Salad', color: 'lime' },
+ autoimmune: { label: 'Autoimmune Risk', icon: 'ShieldAlert', color: 'pink' },
+ thyroid: { label: 'Thyroid & Hormones', icon: 'Activity', color: 'teal' },
+ eye_health: { label: 'Eye Health', icon: 'Eye', color: 'sky' },
+ mental_health: { label: 'Mental Health', icon: 'Brain', color: 'violet' },
+ bone_health: { label: 'Bone Health', icon: 'Bone', color: 'stone' },
+ pharmacogenomics: { label: 'Pharmacogenomics', icon: 'Pill', color: 'fuchsia' },
+ // ... plus cancer-specific categories
+};
+// 117 total markers across these categories
+```
+
+From server/services/meatspaceHealth.js:
+```javascript
+export async function getBloodTests()
+// Returns: { tests: [{ date, ...analytes }], referenceRanges: {} }
+
+export async function getBodyHistory()
+// Returns: [{ date, weight, bodyFat, ... }]
+```
+
+From server/services/taste-questionnaire.js:
+```javascript
+export async function getTasteProfile()
+// Returns: { sections: [{ id, label, status, summary, progress }], completedCount, profileSummary }
+
+// LLM call pattern (local to taste-questionnaire.js, must be replicated):
+async function callProviderAISimple(provider, model, prompt, { temperature, max_tokens })
+// Returns: { text: string } on success, { error: string } on failure
+```
+
+From server/services/providers.js:
+```javascript
+export async function getActiveProvider()
+export async function getProviderById(id)
+```
+
+From server/services/appleHealthQuery.js:
+```javascript
+export async function getCorrelationData(from, to)
+export async function getDailyAggregates(metricName, from, to)
+```
+
+From server/lib/fileUtils.js:
+```javascript
+export const PATHS = { data: '...', health: '...', meatspace: '...', ... };
+export async function ensureDir(dir)
+export async function readJSONFile(filePath, defaultValue)
+```
+
+From server/lib/errorHandler.js:
+```javascript
+export function asyncHandler(fn)
+```
+
+From client/src/services/api.js:
+```javascript
+async function request(endpoint, options = {})
+// Base: /api, auto JSON headers, toast on error, returns parsed JSON
+```
+</interfaces>
+</context>
+
+<tasks>
+
+<task type="auto">
+ <name>Task 1: Create insightsService.js with genome-health correlation engine and LLM analysis functions</name>
+ <files>server/services/insightsService.js</files>
+ <action>
+Create `server/services/insightsService.js` with 5 exported functions:
+
+**1. `getGenomeHealthCorrelations()`** (INS-01 — pure rule-based, no LLM):
+- Import `getGenomeSummary` from `genome.js`, `getBloodTests` and `getBodyHistory` from `meatspaceHealth.js`, `getCorrelationData` from `appleHealthQuery.js`, `MARKER_CATEGORIES` from `curatedGenomeMarkers.js`
+- Call `getGenomeSummary()` — if `!summary.uploaded` return `{ available: false, reason: 'no_genome' }`
+- Extract `savedMarkers` from summary, filter out `status === 'not_found'` markers
+- Call `getBloodTests()` in parallel — extract latest value per analyte from `tests` array using a `getLatestBloodValues(tests)` helper that normalizes analyte names (lowercase, trim, common abbreviation mapping)
+- Define `CATEGORY_BLOOD_MAP` object mapping marker categories to blood analyte names:
+ ```
+ cardiovascular: ['total_cholesterol', 'ldl', 'hdl', 'triglycerides', 'homocysteine']
+ iron: ['ferritin', 'serum_iron', 'transferrin_saturation', 'tibc']
+ methylation: ['homocysteine', 'b12', 'folate']
+ diabetes: ['fasting_glucose', 'hba1c', 'insulin']
+ thyroid: ['tsh', 't3', 't4']
+ nutrient: ['vitamin_d', 'b12', 'folate', 'magnesium', 'zinc']
+ ```
+ (Other categories like longevity, cognitive, sleep, athletic, etc. have no direct blood analyte mapping — include them with `matchedBloodValues: []`)
+- Define `CONFIDENCE_FROM_STATUS` mapping:
+ ```
+ beneficial: { level: 'strong', color: 'green', label: 'Strong Evidence' }
+ typical: { level: 'moderate', color: 'yellow', label: 'Moderate Evidence' }
+ concern: { level: 'weak', color: 'red', label: 'Elevated Risk Marker' }
+ major_concern: { level: 'significant', color: 'red', label: 'Significant Risk Marker' }
+ ```
+- Group markers by `category` key. For each category group, produce:
+ ```
+ {
+ category: key,
+ label: MARKER_CATEGORIES[key].label,
+ icon: MARKER_CATEGORIES[key].icon,
+ color: MARKER_CATEGORIES[key].color,
+ markers: [{ rsid, gene, name, status, description, implications, confidence: CONFIDENCE_FROM_STATUS[status], matchedBloodValues: [...], references }],
+ notFoundCount: N
+ }
+ ```
+ where `matchedBloodValues` is an array of `{ analyte, value, date, unit }` objects from the latest blood test data for that category's mapped analytes
+- Return `{ available: true, categories: [...], totalMarkers: N, matchedMarkers: N, sources: ['23andMe', ...conditionally 'Apple Health', 'Blood Tests'] }`
+- IMPORTANT: Never use language implying causation. Status labels show correlation strength, not causal claims.
+
+**2. `getThemeAnalysis()`** (INS-02 — returns cached themes):
+- Read `data/insights/themes.json` using `readJSONFile(path, null)`
+- If null (no cached themes), return `{ available: false, reason: 'not_generated' }`
+- Otherwise return the cached object as-is: `{ themes: [...], generatedAt, model }`
+
+**3. `generateThemeAnalysis(providerId, model)`** (INS-02 — LLM generation):
+- Import `getTasteProfile` from `taste-questionnaire.js`, `getActiveProvider`/`getProviderById` from `providers.js`
+- Get taste profile, filter sections that have `summary` populated
+- If no completed sections, return `{ available: false, reason: 'no_taste_data' }`
+- Get provider (by ID or active). Get model (passed or `provider.defaultModel`)
+- Build prompt: provide all section summaries as context, request JSON array of 3-5 theme objects with `title`, `narrative`, `evidence` (array of `{ preference, domain, connection }`), `strength` ("strong"/"moderate"/"tentative")
+- Use analytical third-person tone instruction: "The data indicates a pattern of..."
+- Replicate `callProviderAISimple` pattern inline (fetch to `provider.endpoint/chat/completions` with Authorization header, temperature 0.4, max_tokens 2000)
+- Strip markdown code fences before JSON.parse: `raw.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '')`
+- Persist to `data/insights/themes.json` with `{ themes, generatedAt: ISO string, model }`
+- Use `ensureDir` before writing
+- Log: `console.log(\`🧠 Taste-identity themes generated: ${themes.length} themes\`)`
+- Return `{ themes, generatedAt }`
+
+**4. `getCrossDomainNarrative()`** (INS-04 — returns cached narrative):
+- Read `data/insights/narrative.json` using `readJSONFile(path, null)`
+- If null, return `{ available: false, reason: 'not_generated' }`
+- Return cached: `{ text, previousText, generatedAt, previousGeneratedAt, model }`
+
+**5. `refreshCrossDomainNarrative(providerId, model)`** (INS-04 — LLM generation with diff support):
+- Load existing narrative from `data/insights/narrative.json` if it exists
+- Gather context from all domains:
+ - Genome correlations via `getGenomeHealthCorrelations()` — summarize top findings by category
+ - Taste themes via `getThemeAnalysis()` — include theme titles and summaries
+ - Apple Health summary via `getCorrelationData()` (if available)
+- Build prompt requesting 2-3 paragraph analytical narrative with personal framing: "Your data shows..."
+- Use `callProviderAISimple` pattern (temperature 0.5, max_tokens 2000)
+- Strip markdown code fences from response
+- Persist to `data/insights/narrative.json`:
+ ```
+ {
+ text: newText,
+ previousText: existingNarrative?.text ?? null,
+ generatedAt: new Date().toISOString(),
+ previousGeneratedAt: existingNarrative?.generatedAt ?? null,
+ model
+ }
+ ```
+- Log: `console.log(\`🔮 Cross-domain narrative generated (${newText.length} chars)\`)`
+- Return the persisted object
+
+**Helper: `callProviderAISimple(provider, model, prompt, options)`** — local async function:
+- Copy pattern exactly from `taste-questionnaire.js` lines 951-986
+- Handles API-type providers only, returns `{ text }` or `{ error }`
+
+**Helper: `getLatestBloodValues(tests)`** — pure function:
+- Takes array of blood test objects, returns Map of normalized analyte name → `{ value, date, unit }`
+- Normalizes keys: lowercase, trim, replace common abbreviations (e.g., "LDL Cholesterol" → "ldl")
+- Returns the latest (most recent date) value for each analyte
+
+All file I/O uses `PATHS.data` + 'insights' for the cache directory. Use `ensureDir` before writes. Use `readJSONFile` for reads.
+ </action>
+ <verify>
+ <automated>cd /Users/antic/github.com/atomantic/PortOS/server && node -e "import('./services/insightsService.js').then(m => { const fns = ['getGenomeHealthCorrelations','getThemeAnalysis','generateThemeAnalysis','getCrossDomainNarrative','refreshCrossDomainNarrative']; const missing = fns.filter(f => typeof m[f] !== 'function'); if (missing.length) { console.error('Missing exports:', missing); process.exit(1); } console.log('All 5 functions exported'); })"</automated>
+ </verify>
+ <done>insightsService.js exports 5 functions. getGenomeHealthCorrelations returns categorized markers with blood value matching. Theme and narrative functions handle cache read, LLM generation, and file persistence. All functions degrade gracefully with { available: false, reason } when source data is missing.</done>
+</task>
+
+<task type="auto">
+ <name>Task 2: Create insights routes, Zod validation, mount in index.js, and add client API functions</name>
+ <files>server/routes/insights.js, server/lib/validation.js, server/index.js, client/src/services/api.js</files>
+ <action>
+**1. Create `server/routes/insights.js`:**
+- Import `Router` from express, `asyncHandler` from `../lib/errorHandler.js`, `* as insightsService` from `../services/insightsService.js`
+- Import `validateRequest` and relevant schemas from `../lib/validation.js`
+
+5 routes:
+
+```
+GET /genome-health → insightsService.getGenomeHealthCorrelations()
+GET /themes → insightsService.getThemeAnalysis()
+POST /themes/refresh → insightsService.generateThemeAnalysis(req.body.providerId, req.body.model)
+ - Validate body with insightRefreshSchema (optional providerId string, optional model string)
+GET /narrative → insightsService.getCrossDomainNarrative()
+POST /narrative/refresh → insightsService.refreshCrossDomainNarrative(req.body.providerId, req.body.model)
+ - Validate body with insightRefreshSchema
+```
+
+All routes wrapped in `asyncHandler`. POST routes use `validateRequest(insightRefreshSchema)` middleware.
+Export default router.
+
+**2. Add Zod schema to `server/lib/validation.js`:**
+- Add `insightRefreshSchema` (z.object with optional `providerId` as z.string().optional() and `model` as z.string().optional())
+- Export alongside existing schemas
+
+**3. Mount in `server/index.js`:**
+- Import `insightsRoutes` from `'./routes/insights.js'`
+- Add `app.use('/api/insights', insightsRoutes);` — place alphabetically among existing route mounts (after `/api/instances` and before `/api/jira`)
+
+**4. Add client API functions to `client/src/services/api.js`:**
+- Add these exports (place in an `// Insights` section, alphabetically positioned among existing sections):
+```javascript
+// Insights
+export const getGenomeHealthCorrelations = () => request('/insights/genome-health');
+export const getInsightThemes = () => request('/insights/themes');
+export const refreshInsightThemes = (providerId, model) => request('/insights/themes/refresh', {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model })
+});
+export const getInsightNarrative = () => request('/insights/narrative');
+export const refreshInsightNarrative = (providerId, model) => request('/insights/narrative/refresh', {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model })
+});
+```
+ </action>
+ <verify>
+ <automated>cd /Users/antic/github.com/atomantic/PortOS/server && node -e "import('./routes/insights.js').then(m => { const r = m.default; if (!r || !r.stack) { console.error('No router exported'); process.exit(1); } const routes = r.stack.filter(l => l.route).map(l => l.route.path + ' ' + Object.keys(l.route.methods).join(',')); console.log('Routes:', routes); if (routes.length < 5) { console.error('Expected 5 routes'); process.exit(1); } console.log('All 5 routes registered'); })"</automated>
+ </verify>
+ <done>5 REST endpoints mounted at /api/insights/*, Zod validation on POST bodies, client API functions exported. Server starts without errors. GET endpoints return graceful { available: false } when no data exists. POST endpoints accept optional providerId and model.</done>
+</task>
+
+</tasks>
+
+<verification>
+1. Server starts without import errors: `cd server && node -e "import('./index.js')"`
+2. GET /api/insights/genome-health responds (200 with data or graceful degradation)
+3. GET /api/insights/themes responds with `{ available: false, reason: 'not_generated' }` initially
+4. GET /api/insights/narrative responds with `{ available: false, reason: 'not_generated' }` initially
+5. POST /api/insights/themes/refresh with empty body returns 200 or appropriate error if no taste data
+6. POST /api/insights/narrative/refresh with empty body returns 200 or appropriate error
+7. Client api.js exports all 5 insight functions
+</verification>
+
+<success_criteria>
+- insightsService.js exports 5 functions matching the interface contract
+- All 5 routes return valid JSON responses
+- Genome-health correlations group markers by MARKER_CATEGORIES with blood test value matching
+- LLM functions persist results to data/insights/*.json with generatedAt timestamps
+- Narrative refresh preserves previousText for client-side diff
+- Empty states return { available: false, reason: '...' } not errors
+- No causation language in genome correlation labels — only "evidence" and "risk marker"
+</success_criteria>
+
+<output>
+After completion, create `.planning/phases/04-cross-domain-insights-engine/04-01-SUMMARY.md`
+</output>
diff --git a/.planning/phases/04-cross-domain-insights-engine/04-02-PLAN.md b/.planning/phases/04-cross-domain-insights-engine/04-02-PLAN.md
new file mode 100644
index 0000000000..f39334d16f
--- /dev/null
+++ b/.planning/phases/04-cross-domain-insights-engine/04-02-PLAN.md
@@ -0,0 +1,355 @@
+---
+phase: 04-cross-domain-insights-engine
+plan: 02
+type: execute
+wave: 2
+depends_on: ["04-01"]
+files_modified:
+ - client/src/pages/Insights.jsx
+ - client/src/components/insights/GenomeHealthTab.jsx
+ - client/src/components/insights/TasteIdentityTab.jsx
+ - client/src/components/insights/CrossDomainTab.jsx
+ - client/src/components/insights/InsightCard.jsx
+ - client/src/components/insights/ConfidenceBadge.jsx
+ - client/src/components/insights/ProvenancePanel.jsx
+ - client/src/components/insights/EmptyState.jsx
+ - client/src/App.jsx
+ - client/src/components/Layout.jsx
+ - client/package.json
+autonomous: false
+requirements:
+ - INS-03
+ - INS-01
+ - INS-02
+ - INS-04
+
+must_haves:
+ truths:
+ - "Navigating to /insights shows the overview landing page with domain summary cards"
+ - "Clicking a domain summary card navigates to the corresponding deep-linked tab"
+ - "/insights/genome-health displays genome markers grouped by clinical category with matched blood values and confidence badges"
+ - "/insights/taste-identity displays LLM-generated theme cards with evidence lists and refresh button"
+ - "/insights/cross-domain displays narrative text with refresh button and diff view showing changes"
+ - "Each tab URL is deep-linkable — refreshing the page stays on the correct tab"
+ - "Empty states show helpful messages with navigation links when data is missing"
+ - "Insights nav entry appears in the sidebar in correct alphabetical position"
+ - "Confidence badges are color-coded: green (strong), yellow (moderate), red (weak/significant)"
+ artifacts:
+ - path: "client/src/pages/Insights.jsx"
+ provides: "Tabbed insights page with 4 sub-views"
+ min_lines: 80
+ - path: "client/src/components/insights/GenomeHealthTab.jsx"
+ provides: "Genome-health correlation display grouped by category"
+ min_lines: 80
+ - path: "client/src/components/insights/TasteIdentityTab.jsx"
+ provides: "Taste-identity theme cards with evidence lists"
+ min_lines: 60
+ - path: "client/src/components/insights/CrossDomainTab.jsx"
+ provides: "Cross-domain narrative with diff display"
+ min_lines: 60
+ - path: "client/src/components/insights/InsightCard.jsx"
+ provides: "Shared card component for insight display"
+ min_lines: 20
+ - path: "client/src/components/insights/ConfidenceBadge.jsx"
+ provides: "Color-coded confidence badge component"
+ min_lines: 15
+ key_links:
+ - from: "client/src/pages/Insights.jsx"
+ to: "/api/insights/*"
+ via: "api.js client functions"
+ pattern: "getGenomeHealthCorrelations|getInsightThemes|getInsightNarrative"
+ - from: "client/src/App.jsx"
+ to: "client/src/pages/Insights.jsx"
+ via: "Route path='insights/:tab'"
+ pattern: "insights.*:tab"
+ - from: "client/src/components/Layout.jsx"
+ to: "/insights/overview"
+ via: "nav entry with Lightbulb icon"
+ pattern: "insights.*Lightbulb"
+---
+
+<objective>
+Build the Insights dashboard UI: a tabbed page at `/insights/:tab` with four views — Overview (landing with domain summary cards), Genome-Health (category-grouped correlation cards), Taste-Identity (LLM theme cards), and Cross-Domain (narrative with diff display). Wire into App.jsx routes and Layout.jsx navigation.
+
+Purpose: Surface cross-domain insights in an accessible, deep-linkable UI. Users see genome-health correlations with confidence levels, taste-identity themes with evidence, and refreshable cross-domain narratives — all following established PortOS design patterns.
+
+Output: Insights page with 4 tab views, 4 shared components, route configuration, nav entry, react-diff-viewer-continued dependency.
+</objective>
+
+<execution_context>
+@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
+@/Users/antic/.claude/get-shit-done/templates/summary.md
+</execution_context>
+
+<context>
[email protected]/phases/04-cross-domain-insights-engine/04-01-SUMMARY.md
+
+<interfaces>
+<!-- API contract from Plan 01 -->
+
+From client/src/services/api.js (added in Plan 01):
+```javascript
+export const getGenomeHealthCorrelations = () => request('/insights/genome-health');
+// Returns: { available: true, categories: [...], totalMarkers, matchedMarkers, sources }
+// OR: { available: false, reason: 'no_genome' }
+// Category shape: { category, label, icon, color, markers: [...], notFoundCount }
+// Marker shape: { rsid, gene, name, status, description, implications, confidence: { level, color, label }, matchedBloodValues: [{ analyte, value, date, unit }], references }
+
+export const getInsightThemes = () => request('/insights/themes');
+// Returns: { themes: [...], generatedAt, model }
+// OR: { available: false, reason: 'not_generated' | 'no_taste_data' }
+// Theme shape: { title, narrative, evidence: [{ preference, domain, connection }], strength }
+
+export const refreshInsightThemes = (providerId, model) => request('/insights/themes/refresh', { method: 'POST', body: JSON.stringify({ providerId, model }) });
+// Returns: { themes: [...], generatedAt }
+
+export const getInsightNarrative = () => request('/insights/narrative');
+// Returns: { text, previousText, generatedAt, previousGeneratedAt, model }
+// OR: { available: false, reason: 'not_generated' }
+
+export const refreshInsightNarrative = (providerId, model) => request('/insights/narrative/refresh', { method: 'POST', body: JSON.stringify({ providerId, model }) });
+// Returns: { text, previousText, generatedAt, previousGeneratedAt, model }
+```
+
+From existing App.jsx route pattern (MeatSpace example):
+```jsx
+<Route path="meatspace" element={<Navigate to="/meatspace/overview" replace />} />
+<Route path="meatspace/:tab" element={<MeatSpace />} />
+```
+
+From existing Layout.jsx nav structure:
+```javascript
+// Current order after separator: AI Config, Apps, Brain, Chief of Staff, Dev Tools,
+// Digital Twin, Instances, MeatSpace, Security, Shell, Social Agents, Uploads
+// Insights goes after Instances, before MeatSpace (alphabetical)
+```
+
+Tailwind design tokens:
+```
+port-bg: #0f0f0f port-card: #1a1a1a
+port-border: #2a2a2a port-accent: #3b82f6
+port-success: #22c55e port-warning: #f59e0b
+port-error: #ef4444
+```
+</interfaces>
+</context>
+
+<tasks>
+
+<task type="auto">
+ <name>Task 1: Install react-diff-viewer-continued, create shared insight components, and build all tab views</name>
+ <files>
+ client/package.json
+ client/src/components/insights/ConfidenceBadge.jsx
+ client/src/components/insights/ProvenancePanel.jsx
+ client/src/components/insights/EmptyState.jsx
+ client/src/components/insights/InsightCard.jsx
+ client/src/components/insights/GenomeHealthTab.jsx
+ client/src/components/insights/TasteIdentityTab.jsx
+ client/src/components/insights/CrossDomainTab.jsx
+ </files>
+ <action>
+**0. Install dependency:**
+```bash
+cd client && npm install react-diff-viewer-continued
+```
+If `react-diff-viewer-continued` is not available on npm, fall back to hand-rolling a simple word-level diff using the `diff` npm package (`npm install diff`) — for 2-3 paragraph texts, a custom `<NarrativeDiff>` component using `diffWords()` from the `diff` package is sufficient.
+
+**1. `ConfidenceBadge.jsx`** — small presentational component:
+```jsx
+const BADGE_STYLES = {
+ strong: 'bg-port-success/20 text-port-success border-port-success/30',
+ moderate: 'bg-port-warning/20 text-port-warning border-port-warning/30',
+ weak: 'bg-port-error/20 text-port-error border-port-error/30',
+ significant: 'bg-port-error/30 text-port-error border-port-error/50',
+ unknown: 'bg-gray-800 text-gray-400 border-gray-700'
+};
+```
+- Props: `{ level, label, sources }` — renders styled `<span>` with `title={sources?.join(', ')}`
+- Consistent across all insight types (genome-health and taste-identity)
+
+**2. `ProvenancePanel.jsx`** — collapsible provenance section:
+- Props: `{ references, expanded, onToggle }` — or use internal useState for expand/collapse
+- Default collapsed. Click to expand.
+- Renders list of references with study name, publication year, database source (ClinVar, PharmGKB, etc.)
+- If no references, renders nothing (return null)
+- Use ChevronDown/ChevronRight from lucide-react for expand indicator
+
+**3. `EmptyState.jsx`** — gentle empty state component:
+- Props: `{ message, linkTo, linkLabel }` (all optional except message)
+- Renders centered text in muted color with optional navigation Link
+- Examples: "No genome data uploaded yet" → link to `/meatspace/genome`; "No taste profile completed yet" → link to `/digital-twin/taste`
+- Use Lucide `Info` icon
+
+**4. `InsightCard.jsx`** — shared card shell:
+- Props: `{ title, subtitle, badge, children, sources, className }`
+- Card layout: `bg-port-card border border-port-border rounded-lg p-4`
+- Header row: title + badge (ConfidenceBadge). Subtitle below title.
+- `sources` rendered as inline tags: small pill-shaped spans showing "23andMe", "Apple Health", etc.
+- `children` for card body content
+
+**5. `GenomeHealthTab.jsx`** (INS-01, INS-03):
+- Fetch `getGenomeHealthCorrelations()` on mount (useEffect)
+- Loading state: skeleton cards (pulse animation placeholders)
+- If `!data.available` → render `<EmptyState message="No genome data uploaded yet" linkTo="/meatspace/genome" linkLabel="Upload Genome" />`
+- If available: render categories as collapsible sections
+- Each category section has:
+ - Header: icon (from Lucide — map string icon names to Lucide components), category label, marker count, expand/collapse toggle
+ - When expanded: grid of InsightCards for each marker
+ - Each marker card shows: marker name as title, gene as subtitle, ConfidenceBadge with status-mapped level, description text, implications text (for the marker's status), matched blood values if any (analyte: value with date), collapsible ProvenancePanel for references
+ - If `matchedBloodValues` is empty, show "No blood test on record" muted text with link to `/meatspace/blood`
+ - Category header shows `notFoundCount` as "(N not in dataset)" note if > 0
+- Summary stats at top: total markers analyzed, matched with blood data count
+
+**6. `TasteIdentityTab.jsx`** (INS-02, INS-03):
+- Fetch `getInsightThemes()` on mount
+- If `!data?.available && data?.reason === 'not_generated'` → show EmptyState with "Generate" action description and explain what it does
+- If `data?.reason === 'no_taste_data'` → show EmptyState linking to `/digital-twin/taste`
+- If themes exist: show `generatedAt` timestamp, "Refresh" button (calls `refreshInsightThemes()`)
+- During refresh: button shows loading spinner, disable button
+- Staleness indicator: compare `generatedAt` against current time, show "Generated X ago" relative time
+- Theme cards layout: vertical stack or 2-column grid on lg screens
+- Each theme card (InsightCard): title = theme title, badge = ConfidenceBadge with strength mapped to level (strong→strong, moderate→moderate, tentative→weak), body = narrative paragraph
+- Below narrative: collapsible evidence list (similar to ProvenancePanel pattern). Each evidence item: `{preference}` from `{domain}` — `{connection}`
+- Tone: analytical, third-person as per CONTEXT.md decisions
+
+**7. `CrossDomainTab.jsx`** (INS-04, INS-03):
+- Fetch `getInsightNarrative()` on mount
+- If not generated → show EmptyState: "No cross-domain narrative generated yet. Click Refresh to analyze patterns across all your data."
+- If generated: show narrative text in a styled container (bg-port-card, prose-like typography)
+- Show `generatedAt` timestamp and model used
+- "Refresh" button: calls `refreshInsightNarrative()`, shows loading state
+- After refresh: if `previousText` exists and differs from `text`, show diff toggle
+ - "Show changes" button toggles diff view on/off
+ - Diff view uses `react-diff-viewer-continued` (or fallback diff component):
+ - `oldValue={previousText}`, `newValue={text}`, `splitView={false}`, `useDarkTheme`, `hideLineNumbers`
+ - If `previousText === text` (trimmed), show "No significant changes detected" instead of diff
+- Show `previousGeneratedAt` as "Previous analysis: {date}" when diff is shown
+ </action>
+ <verify>
+ <automated>cd /Users/antic/github.com/atomantic/PortOS/client && ls src/components/insights/ConfidenceBadge.jsx src/components/insights/ProvenancePanel.jsx src/components/insights/EmptyState.jsx src/components/insights/InsightCard.jsx src/components/insights/GenomeHealthTab.jsx src/components/insights/TasteIdentityTab.jsx src/components/insights/CrossDomainTab.jsx && echo "All 7 component files exist"</automated>
+ </verify>
+ <done>7 insight component files created. ConfidenceBadge renders color-coded badges. GenomeHealthTab groups markers by clinical category with blood value matching. TasteIdentityTab shows theme cards with evidence lists and refresh. CrossDomainTab shows narrative with diff view. EmptyState handles missing data with navigation links.</done>
+</task>
+
+<task type="auto">
+ <name>Task 2: Create Insights page, wire App.jsx routes and Layout.jsx navigation</name>
+ <files>
+ client/src/pages/Insights.jsx
+ client/src/App.jsx
+ client/src/components/Layout.jsx
+ </files>
+ <action>
+**1. Create `client/src/pages/Insights.jsx`:**
+- Import `useParams`, `useNavigate` from react-router-dom
+- Import tab components: GenomeHealthTab, TasteIdentityTab, CrossDomainTab
+- Import API functions: `getGenomeHealthCorrelations`, `getInsightThemes`, `getInsightNarrative`
+- Import Lucide icons: `Dna`, `Palette`, `Link2`, `Lightbulb`, `ArrowRight`
+
+Tab configuration:
+```javascript
+const TABS = [
+ { id: 'overview', label: 'Overview', icon: Lightbulb },
+ { id: 'genome-health', label: 'Genome-Health', icon: Dna },
+ { id: 'taste-identity', label: 'Taste & Identity', icon: Palette },
+ { id: 'cross-domain', label: 'Cross-Domain Patterns', icon: Link2 }
+];
+```
+
+Page structure:
+- Read `tab` from `useParams()`. Default to 'overview' if not in TABS.
+- Tab bar at top: horizontal list of tab buttons, active tab highlighted with `border-b-2 border-port-accent text-white`, inactive tabs `text-gray-400 hover:text-white`. Each tab is a button that calls `navigate(\`/insights/${tab.id}\`)`.
+- Below tab bar: render the appropriate component based on active tab ID.
+
+**Overview tab** (landing view, rendered inline in Insights.jsx):
+- Fetch summary data from all three endpoints on mount (parallel: `Promise.allSettled`)
+- 3 domain summary cards in a responsive grid (1 col mobile, 3 cols lg):
+ - **Genome-Health**: key stat = `{matchedMarkers} markers analyzed`, top insight = highest-confidence finding or "Upload genome to get started", confidence indicator = ConfidenceBadge of top marker
+ - **Taste & Identity**: key stat = `{themes.length} themes identified` or "Not yet generated", top insight = first theme title or prompt to complete taste profile
+ - **Cross-Domain Patterns**: key stat = "Last analyzed {relativeTime}" or "Not yet generated", top insight = first sentence of narrative text
+- Each summary card: bg-port-card, border, rounded-lg, p-6, clickable → navigates to the detail tab
+- Source tags on each card: inline pills showing data sources
+- Show loading skeletons while fetching
+
+**2. Update `client/src/App.jsx`:**
+- Import `Insights` from `./pages/Insights`
+- Add routes (follow existing MeatSpace pattern):
+```jsx
+<Route path="insights" element={<Navigate to="/insights/overview" replace />} />
+<Route path="insights/:tab" element={<Insights />} />
+```
+Place alphabetically among existing routes (after `instances`, before `jira`).
+
+**3. Update `client/src/components/Layout.jsx`:**
+- Import `Lightbulb` icon from lucide-react (add to existing import destructure)
+- Add Insights nav entry after the `Instances` entry and before the `MeatSpace` entry (alphabetical order):
+```javascript
+{ to: '/insights/overview', label: 'Insights', icon: Lightbulb, single: true },
+```
+This keeps it as a single nav item (not expandable section) that links to the overview landing. Users navigate sub-tabs from within the page.
+ </action>
+ <verify>
+ <automated>cd /Users/antic/github.com/atomantic/PortOS/client && npx vite build 2>&1 | tail -5</automated>
+ </verify>
+ <done>Insights.jsx page renders 4 tabs at /insights/:tab with deep-linked routes. Overview shows domain summary cards. App.jsx has route entries. Layout.jsx has Insights nav entry between Instances and MeatSpace. Client builds without errors.</done>
+</task>
+
+<task type="checkpoint:human-verify" gate="blocking">
+ <name>Task 3: Verify Insights dashboard UI</name>
+ <files>client/src/pages/Insights.jsx</files>
+ <action>
+Human verification of the complete Insights dashboard. No automated changes — verify the UI built in Tasks 1-2:
+
+1. Navigate to http://localhost:5555/insights — should redirect to /insights/overview
+2. Overview tab: 3 domain summary cards should render (may show empty states if no data uploaded)
+3. Click "Genome-Health" tab or summary card — URL changes to /insights/genome-health
+4. If genome data exists: markers grouped by clinical category with confidence badges, collapsible provenance panels, matched blood values
+5. If no genome data: empty state with link to /meatspace/genome
+6. Click "Taste & Identity" tab — URL changes to /insights/taste-identity
+7. If taste profile completed: click Refresh to generate themes, verify theme cards appear with evidence lists
+8. Click "Cross-Domain Patterns" tab — URL changes to /insights/cross-domain
+9. Click Refresh to generate narrative, verify text appears with timestamp
+10. Click Refresh again — verify diff view shows changes between old and new narrative
+11. Refresh browser on any tab URL — should stay on correct tab (deep-linking works)
+12. Check sidebar: "Insights" nav item appears between "Instances" and "MeatSpace"
+13. Verify confidence badges: green (strong evidence), yellow (moderate), red (elevated/significant risk)
+ </action>
+ <verify>
+ <automated>curl -s http://localhost:5555/insights/overview | grep -q "html" && echo "Page serves" || echo "Page not found"</automated>
+ </verify>
+ <done>All 4 insight tabs render correctly. Deep-linked URLs work. Empty states guide to data import. Confidence badges use correct color coding. Nav entry is alphabetically positioned. Diff view works on narrative refresh.</done>
+</task>
+
+</tasks>
+
+<verification>
+1. `npm run build` in client succeeds — no import errors, no missing dependencies
+2. All 4 tab routes work: /insights/overview, /insights/genome-health, /insights/taste-identity, /insights/cross-domain
+3. Each route is deep-linkable (direct URL access works)
+4. Empty states render correctly when data is missing
+5. Genome-health markers are grouped by clinical category with MARKER_CATEGORIES metadata
+6. Confidence badges are consistent across genome-health and taste-identity tabs
+7. Theme analysis generates and caches via LLM
+8. Narrative refresh preserves previous text and shows diff view
+9. Nav entry "Insights" appears in correct alphabetical position in sidebar
+</verification>
+
+<success_criteria>
+- /insights/:tab renders the correct sub-view for all 4 tab values
+- Overview shows 3 clickable domain summary cards
+- Genome-Health groups 117 markers by clinical category with collapsible sections
+- Each marker card shows confidence badge, description, implications, matched blood values
+- Taste-Identity shows LLM theme cards with title, narrative, evidence list, strength badge
+- Cross-Domain shows refreshable narrative with before/after diff view
+- Empty states guide users to relevant data import pages
+- Sidebar nav entry is alphabetically correct
+- All URLs are deep-linkable (no modal-only views)
+- No window.alert or window.confirm used (CLAUDE.md mandate)
+</success_criteria>
+
+<output>
+After completion, create `.planning/phases/04-cross-domain-insights-engine/04-02-SUMMARY.md`
+</output>