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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(insights): polarity-aware genome-health labels + show genotype
Adam Eivy647566ec352d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f1892b78ad..37b5378a84 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -43,6 +43,10 @@## Fixed+- **Lifestyle tab — biological sex is now editable and round-trips to MortalLoom iCloud sync** — `/meatspace/lifestyle` previously showed Biological Sex as a read-only text label, so users had no way to correct an auto-genome-detected sex or set it manually when no genome was uploaded. The Profile card now renders a Male/Female/Unknown segmented picker in the same style as the other lifestyle buttons, and Save now uses `PUT /api/meatspace/config` (instead of `/lifestyle`) so sex, sexSource, and the questionnaire write in one round-trip. `sexSource` is stamped to `'questionnaire'` whenever the user sets it manually so the next `getConfig()` call doesn't silently overwrite it via the auto-detect-from-genome code path. **MortalLoom iCloud parity**: `getConfig()` now treats `store.profile` in the iCloud MortalLoom.json as authoritative when sync is enabled — `biologicalSex`, `birthDate`, and the `lifestyle` subset of fields (smoking/exercise/sleep/diet/stress/BMI — the keys MortalLoom's Swift `LifestyleData` struct defines) get merged into the returned config so edits made in the iOS/macOS app show up in PortOS without a manual import. Writes mirror the other direction too: `updateConfig()`, `updateLifestyle()`, and `updateBirthDate()` now patch `store.profile.biologicalSex` / `store.profile.lifestyle` / `store.profile.birthDate` via a new `mlPatchProfileIfEnabled()` helper, which deep-merges nested objects so lifestyle can be patched field-by-field without clobbering siblings. PortOS-only lifestyle fields (`alcoholDrinksPerDay`, `chronicConditions`) are filtered out of the MortalLoom write via a `MORTALLOOM_LIFESTYLE_KEYS` allowlist so the store only gains keys MortalLoom's Swift decoder accepts. `configSchema.sex` now allows `null` so clearing the sex from the UI validates.++- **Genome-Health cards mislabeled longevity/protective markers as "Elevated Risk Marker"** — the `/insights/genome-health` tab tagged every `concern` status with the risk language `CONFIDENCE_FROM_STATUS` produced ("Elevated Risk Marker", "Significant Risk Marker"), which was wrong for protective-variant markers like FOXO3A/rs2802292 where `concern` just means "doesn't carry the longevity G allele" — not an elevated risk, just a typical population outcome. The card also hid the user's genotype so you couldn't tell whether you carried the marker at all. Fix: added a polarity inference on `CuratedMarker` — rules containing `major_concern` describe a risk marker, rules going beneficial→typical→concern describe a protective marker — and two separate confidence tables (`CONFIDENCE_PROTECTIVE` = "Beneficial Variant / Partial Variant / No Benefit Variant" in neutral grays, `CONFIDENCE_RISK` = "No Risk Variant / Typical / Carrier / Risk Variant" in green→yellow→orange→red). The server now stamps each enriched marker with its `polarity` and `genotype`; the client card shows a "Your result" row with the genotype rendered in a color-coded pill (neutral gray when a protective marker's status is just "no variant"), surfaces a subtle "protective variant" hint with a tooltip explaining the framing, and prefixes the implication text with "What this means:". Added a new `neutral` level to `ConfidenceBadge` for the no-variant-on-protective-marker case. MortalLoom parity: `CuratedMarker` gained the same inferred `polarity` extension and `GenomeView.swift`'s `colorForStatus`/`iconForStatus`/`statusLabel` helpers now accept a polarity argument and return protective-aware labels ("Beneficial Variant" / "No Benefit Variant" in `.secondary` gray with a `minus.circle.fill` icon) so a FOXO3A T/T result no longer shows an orange warning triangle. Scanned all 116 curated markers — the inference holds: longevity/tumor_suppression/cognitive markers use protective polarity, disease-risk markers (iron, cardiovascular, autoimmune) use risk polarity.+- **Voice agent looped repeating itself because Web Speech STT was transcribing the bot's own TTS as user turns** — with the default `stt.engine: 'web-speech'`, the browser's SpeechRecognition kept listening while TTS played through the speaker, so short fragments of the reply ("specific block", "activity", "or") came back in as new user finals and `sendText()` routed them to the LLM — which re-ran the last tool and produced another TTS reply, which echoed again. Unlike continuous-VAD mode, Web Speech mode had NO echo rejection. `voiceClient.js` now tracks recently-spoken TTS sentences (8s ring buffer, normalized) and drops Web Speech finals on two gates: (1) time-based — TTS currently playing or within the existing echo-tail cooldown, or (2) content-based — the final is a substring of a recent TTS sentence. Late echoes that arrive after the time window (slow STT finalize, long reverb) still get rejected by the content gate. Dropped echoes log `🔇 [voice] dropping TTS echo "..."` so the pattern is visible if it recurs. Barge-in via voice while TTS plays is now disabled in Web Speech mode (the mic has no way to distinguish user voice from speaker bleed) — users can still interrupt via the dedicated interrupt button that appears while the bot is speaking.- **Voice agent said "I opened that" / "Added to your inbox" but nothing actually happened** — small tool-use models (Qwen3-4B class) occasionally narrate an action as their spoken reply without ever issuing the matching `tool_call`. The system-prompt biasing (enumerated trigger phrases, NEVER-echo directives) catches most of these, but leaks remain on long tool lists and fuzzy phrasings. The user heard a confident confirmation but no navigation/capture/fill happened. `pipeline.js` now detects the pattern after the turn completes — when no tool ran, the final reply is non-empty, and the reply matches a narrow action-claim regex ("I opened", "I've saved", "Navigating to", "Adding that", etc.) — and emits a `voice:error` toast ("I said I'd do that but didn't actually call the tool. Try rephrasing — e.g. 'open my daily log' or 'go to tasks'.") so the user knows the action didn't land and can rephrase. The regex is intentionally narrow on first-person past/progressive action-claim phrasings to avoid false-positives on conversational replies that mention the same verbs ("You saved that yesterday", "Your daily log is a good habit"). Also logs `🎙️ [turnId] narrate-without-call user="..." reply="..."` so we can grep server logs for recurrences. New `detectNarrationWithoutCall` helper is exported for unit testing; 6 new tests cover first-person past, progressive tense, confirmed-by-tool-run (no flag), empty reply (no flag), conversational false-negative cases, and missing-input tolerance.diff --git a/client/src/components/insights/ConfidenceBadge.jsx b/client/src/components/insights/ConfidenceBadge.jsxindex bd2ec28685..105adc7047 100644--- a/client/src/components/insights/ConfidenceBadge.jsx+++ b/client/src/components/insights/ConfidenceBadge.jsx@@ -1,8 +1,9 @@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',+ weak: 'bg-orange-500/20 text-orange-300 border-orange-500/30',significant: 'bg-port-error/30 text-port-error border-port-error/50',+ neutral: 'bg-gray-800/70 text-gray-300 border-gray-600',unknown: 'bg-gray-800 text-gray-400 border-gray-700'};diff --git a/client/src/components/insights/GenomeHealthTab.jsx b/client/src/components/insights/GenomeHealthTab.jsxindex ea8ff9a3b5..cf24263c38 100644--- a/client/src/components/insights/GenomeHealthTab.jsx+++ b/client/src/components/insights/GenomeHealthTab.jsx@@ -25,15 +25,42 @@ const COLOR_CLASS_MAP = {slate: 'text-slate-400', zinc: 'text-zinc-400', gray: 'text-gray-400'};-// Map marker status to confidence level key+// Fallback status→level mapping (used when server omits confidence.level).+// The server's polarity-aware `confidence` object is preferred.const STATUS_TO_LEVEL = {- elevated_risk: 'significant',- moderate_risk: 'moderate',- typical: 'strong',- protective: 'strong',+ beneficial: 'strong',+ typical: 'moderate',+ concern: 'weak',+ major_concern: 'significant',+ not_found: 'unknown',unknown: 'unknown'};+// Short, neutral label fallback. Server sends polarity-aware labels in confidence.label.+const STATUS_LABEL_FALLBACK = {+ beneficial: 'Beneficial',+ typical: 'Typical',+ concern: 'Concern',+ major_concern: 'Major Concern',+ not_found: 'Not Found'+};++const NEUTRAL_GENOTYPE_STYLE = 'border-gray-600 bg-gray-800/60 text-gray-400';+const GENOTYPE_COLOR_BY_STATUS = {+ beneficial: 'border-green-500/30 bg-green-500/10 text-green-300',+ typical: 'border-yellow-500/30 bg-yellow-500/10 text-yellow-300',+ concern: 'border-orange-500/30 bg-orange-500/10 text-orange-300',+ major_concern: 'border-red-500/40 bg-red-500/10 text-red-300'+};++function genotypeStyleFor(status, polarity) {+ // Protective-marker "concern" means "lacks beneficial variant" — render neutral, not orange.+ if (polarity === 'protective' && (status === 'concern' || status === 'major_concern')) {+ return NEUTRAL_GENOTYPE_STYLE;+ }+ return GENOTYPE_COLOR_BY_STATUS[status] ?? NEUTRAL_GENOTYPE_STYLE;+}+function CategorySection({ category }) {const [expanded, setExpanded] = useState(true);const Icon = ICON_MAP[category.icon] ?? Dna;@@ -72,7 +99,14 @@ function CategorySection({ category }) {function MarkerCard({ marker }) {const level = STATUS_TO_LEVEL[marker.status] ?? 'unknown';- const implications = marker.implications?.[marker.status] ?? marker.description;+ // `implications` can arrive as either a per-status map (legacy) or a pre-resolved string.+ const implications = typeof marker.implications === 'string'+ ? marker.implications+ : (marker.implications?.[marker.status] ?? null);++ const badgeLabel = marker.confidence?.label ?? STATUS_LABEL_FALLBACK[marker.status] ?? marker.status;+ const isProtective = marker.polarity === 'protective';+ const genotypeStyle = genotypeStyleFor(marker.status, marker.polarity);return (<InsightCard@@ -81,16 +115,41 @@ function MarkerCard({ marker }) {badge={<ConfidenceBadgelevel={marker.confidence?.level ?? level}- label={marker.confidence?.label ?? marker.status}+ label={badgeLabel}/>}>+ {/* Your result: genotype pill + one-line status */}+ <div className="flex items-center gap-2 mt-2">+ <span className="text-[10px] text-gray-500 uppercase tracking-wide font-medium">+ Your result+ </span>+ {marker.genotype ? (+ <span className={`font-mono text-xs font-bold px-2 py-0.5 rounded border ${genotypeStyle}`}>+ {marker.genotype}+ </span>+ ) : (+ <span className="text-xs text-gray-500 italic">not in dataset</span>+ )}+ {isProtective && (+ <span+ className="text-[10px] text-gray-500 italic"+ title="This marker flags a rare beneficial variant. Not carrying it means standard (typical) — no elevated risk."+ >+ protective variant+ </span>+ )}+ </div>+{marker.description && (<p className="text-xs text-gray-400 mt-2 leading-relaxed">{marker.description}</p>)}{implications && implications !== marker.description && (- <p className="text-xs text-gray-500 mt-1 italic leading-relaxed">{implications}</p>+ <p className="text-xs text-gray-300 mt-2 leading-relaxed">+ <span className="text-gray-500">What this means: </span>+ {implications}+ </p>)}{/* Matched blood values */}diff --git a/server/services/insightsService.js b/server/services/insightsService.jsindex 067223bc94..dd85400cfa 100644--- a/server/services/insightsService.js+++ b/server/services/insightsService.js@@ -16,12 +16,14 @@ import { join } from 'path';import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';import { getGenomeSummary } from './genome.js';import { getBloodTests } from './meatspaceHealth.js';-import { MARKER_CATEGORIES } from '../lib/curatedGenomeMarkers.js';+import { MARKER_CATEGORIES, CURATED_MARKERS } from '../lib/curatedGenomeMarkers.js';import { getTasteProfile } from './taste-questionnaire.js';import { getActiveProvider, getProviderById } from './providers.js';import { getCorrelationData } from './appleHealthQuery.js';import { stripCodeFences, parseLLMJSON } from '../lib/aiProvider.js';+const MARKER_BY_RSID = new Map(CURATED_MARKERS.map(m => [m.rsid, m]));+const INSIGHTS_DIR = join(PATHS.data, 'insights');const THEMES_FILE = join(INSIGHTS_DIR, 'themes.json');const NARRATIVE_FILE = join(INSIGHTS_DIR, 'narrative.json');@@ -40,16 +42,41 @@ const CATEGORY_BLOOD_MAP = {};// =============================================================================-// CONFIDENCE LEVELS (correlation strength labels — not causal claims)+// CONFIDENCE LEVELS (contextual labels — not causal claims)// =============================================================================+// Two marker polarities:+// - "protective" : rare variant is desirable (e.g. FOXO3A longevity)+// `concern` just means "no benefit variant" — not a risk+// - "risk" : rare variant is undesirable (e.g. HFE iron overload)+// `concern` means carrier, `major_concern` means homozygous risk+//+// Inference: if a marker's rules contain `major_concern`, it's a risk marker.+// Otherwise it's treated as protective (only beneficial/typical/concern rules).++function inferMarkerPolarity(rules = []) {+ return rules.some(r => r.status === 'major_concern') ? 'risk' : 'protective';+}++const CONFIDENCE_PROTECTIVE = {+ beneficial: { level: 'strong', color: 'green', label: 'Beneficial Variant' },+ typical: { level: 'moderate', color: 'yellow', label: 'Partial Variant' },+ concern: { level: 'neutral', color: 'gray', label: 'No Benefit Variant' },+ major_concern: { level: 'neutral', color: 'gray', label: 'No Benefit Variant' }+};-const CONFIDENCE_FROM_STATUS = {- beneficial: { level: 'strong', color: 'green', label: 'Strong Evidence' },- typical: { level: 'moderate', color: 'yellow', label: 'Moderate Evidence' },- concern: { level: 'weak', color: 'red', label: 'Elevated Risk Marker' },- major_concern: { level: 'significant', color: 'red', label: 'Significant Risk Marker' }+const CONFIDENCE_RISK = {+ beneficial: { level: 'strong', color: 'green', label: 'No Risk Variant' },+ typical: { level: 'moderate', color: 'yellow', label: 'Typical' },+ concern: { level: 'weak', color: 'orange', label: 'Carrier' },+ major_concern: { level: 'significant', color: 'red', label: 'Risk Variant' }};+function confidenceForStatus(status, polarity) {+ const table = polarity === 'protective' ? CONFIDENCE_PROTECTIVE : CONFIDENCE_RISK;+ const entry = table[status];+ return entry ? { ...entry, polarity } : null;+}+// =============================================================================// HELPERS// =============================================================================@@ -231,7 +258,8 @@ export async function getGenomeHealthCorrelations() {const mappedAnalytes = CATEGORY_BLOOD_MAP[catKey] ?? [];const enrichedMarkers = catData.markers.map(marker => {- const confidence = CONFIDENCE_FROM_STATUS[marker.status] ?? null;+ const polarity = inferMarkerPolarity(MARKER_BY_RSID.get(marker.rsid)?.rules);+ const confidence = confidenceForStatus(marker.status, polarity);const matchedBloodValues = mappedAnalytes.map(analyte => {@@ -244,7 +272,9 @@ export async function getGenomeHealthCorrelations() {rsid: marker.rsid,gene: marker.gene,name: marker.name,+ genotype: marker.genotype ?? null,status: marker.status,+ polarity,description: marker.description,implications: marker.implications,confidence,