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

feat: digital-twin taste + chronotype enrichment from observed behavior (#2156)

Adam Eivy207d1feee1bf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ab3c1a29ec..4410eef3da 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,7 @@
# Unreleased Changes
+- **[issue-2156] Digital-twin enrichment from observed behavior — taste + chronotype evidence (Human Activity Tracking Phase 7).** The second federated output of the activity timeline: the Digital Twin now learns from what you actually listen to, watch, and when you're active — LLM-free — instead of only from questionnaires. A new `server/services/twinEnrichment.js` rolls up `media.listen`/`media.watch` events into a **taste-profile evidence record** (`data/digital-twin/taste-observed.json`): top artists, genres, channels, and topics per week + month, with a novelty-vs-repeat ratio (distinct plays ÷ total). An hourly activity histogram (outbound messages, meetings, media by **local** hour — received messages are excluded as they reflect others' timing) produces a **chronotype evidence record** (`chronotype-observed.json`) with per-category peak hours and an observed morning/intermediate/evening classification derived from a circular-mean center-of-mass (so a midnight-wrapping night owl isn't averaged to noon). Every evidence record carries `source: 'observed'` provenance and lives beside — never overwrites — the stated questionnaire/genome records; the two are kept in separate files and the Taste tab surfaces both, flagging stated-vs-observed chronotype divergence as **signal, not error** (an underived default chronotype is treated as "no stated value" so it can't fake a divergence). Both evidence files federate via `digital-twin-sync.js` as LWW-on-`derivedAt` (newest observation wins wholesale; a peer that sends none can't blank the local record). Aggregation is deterministic and provider-free, so it runs with no consent — incrementally after each Spotify/YouTube sync (a self-guarded `refreshTwinEvidenceAfterSync()` hook fired only when new events landed) and on a daily backstop rollup (`twinEnrichmentScheduler.js`, started from `server/index.js`). The ONLY provider call is an explicit **"What does this say about me?"** button on the Taste tab that names the provider before running (per the AI policy — no cold-bootstrap LLM calls) and persists the narrative onto the evidence record without touching the numbers. New Zod-validated routes: `GET /twin-evidence`, `POST /twin-evidence/recompute` (LLM-free), `POST /twin-evidence/interpret` (explicit). (`server/services/twinEnrichment.js`, `server/services/twinEnrichmentScheduler.js`, `server/services/digital-twin-sync.js`, `server/services/{spotifySync,youtubeSync}.js`, `server/routes/digital-twin.js`, `server/lib/digitalTwinValidation.js`, `server/index.js`, `client/src/components/digital-twin/ObservedTasteEvidence.jsx`, `client/src/components/digital-twin/tabs/TasteTab.jsx`, `client/src/services/apiDigitalTwin.js`)
+
- **[issue-2155] Daily-log auto-drafts from the activity timeline (Human Activity Tracking Phase 6).** An evening scheduled job drafts a "what actually happened today" section into that day's Brain daily log — the first federated output of the activity timeline. `server/services/activityDigest.js` summarizes a day's `human_activity_events` (conversations grouped with sent/received tallies, meetings with attendee names, media consumed — tribe-person names resolved from participants + the tribe registry) into a deterministic structured bullet list. That list is useful on its own AND is the template fed to an LLM: when the user has configured a provider/model, an opt-in narrative is generated on top of the bullets; otherwise the structured summary ships with **zero provider calls**. Per the AI policy the feature is silent until enabled — a dedicated scheduler (`activityDigestScheduler.js`, patterned on `brainScheduler.js` with an evening time-of-day trigger + missed-day catch-up, started from `server/index.js`, NOT `taskSchedule.js`) no-ops entirely when disabled and never fires a cold-bootstrap LLM call. The draft is spliced into the journal as a clearly-marked, marker-delimited section via a new `brainJournal.upsertAutoSection()` (rides `brainStorage.upsertWithId` so it federates + re-embeds through `brainMemoryBridge`); user-typed/dictated content and segment history are never touched, and a re-run replaces only the auto section (stable HTML-comment markers via the pure, unit-tested `server/lib/markedSection.js`). A "Draft" button on the Daily Log tab runs it on demand (direct user action — names the provider, no extra consent modal), and the tab's settings drawer gains the enable toggle + provider/model/run-time config. (`server/services/activityDigest.js`, `server/services/activityDigestScheduler.js`, `server/services/brainJournal.js`, `server/lib/markedSection.js`, `server/lib/brainValidation.js`, `server/routes/brainDailyLog.js`, `client/src/components/brain/tabs/DailyLogTab.jsx`, `client/src/services/apiBrain.js`)
## CoS Agents
diff --git a/client/src/components/digital-twin/ObservedTasteEvidence.jsx b/client/src/components/digital-twin/ObservedTasteEvidence.jsx
new file mode 100644
index 0000000000..a91435864d
--- /dev/null
+++ b/client/src/components/digital-twin/ObservedTasteEvidence.jsx
@@ -0,0 +1,282 @@
+import { useState, useEffect, useCallback } from 'react';
+import { Telescope, RefreshCw, Sparkles, Music, Tv, Clock, AlertTriangle, CheckCircle } from 'lucide-react';
+import * as api from '../../services/api';
+import toast from '../ui/Toast';
+import BrailleSpinner from '../BrailleSpinner';
+import MarkdownOutput from '../cos/MarkdownOutput';
+
+// Divergence badge: divergence is SIGNAL, not error — stated and observed
+// chronotypes differing is a legitimate insight, so we frame it neutrally.
+function DivergenceBadge({ comparison }) {
+ if (!comparison || comparison.divergence === 'unknown') return null;
+ const { divergence, statedType, observedType } = comparison;
+ if (divergence === 'none') {
+ return (
+ <span className="inline-flex items-center gap-1.5 text-xs px-2 py-0.5 rounded bg-port-success/15 text-port-success border border-port-success/30">
+ <CheckCircle size={12} /> Stated &amp; observed agree ({statedType})
+ </span>
+ );
+ }
+ const tone = divergence === 'strong'
+ ? 'bg-port-warning/15 text-port-warning border-port-warning/30'
+ : 'bg-port-accent/15 text-port-accent border-port-accent/30';
+ return (
+ <span className={`inline-flex items-center gap-1.5 text-xs px-2 py-0.5 rounded border ${tone}`}>
+ <AlertTriangle size={12} /> Stated {statedType} vs observed {observedType} — {divergence} divergence
+ </span>
+ );
+}
+
+function TopList({ title, items }) {
+ if (!Array.isArray(items) || items.length === 0) return null;
+ return (
+ <div>
+ <div className="text-xs uppercase tracking-wider text-gray-500 mb-1">{title}</div>
+ <div className="flex flex-wrap gap-1.5">
+ {items.map((x) => (
+ <span key={x.name} className="text-xs px-2 py-0.5 rounded-full bg-port-bg border border-port-border text-gray-300">
+ {x.name} <span className="text-gray-500">×{x.count}</span>
+ </span>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function fmtHour(h) {
+ if (h == null) return '—';
+ const suffix = h < 12 ? 'am' : 'pm';
+ const hr = h % 12 === 0 ? 12 : h % 12;
+ return `${hr}${suffix}`;
+}
+
+function fmtNovelty(nv) {
+ if (!nv || nv.noveltyRatio == null) return null;
+ return `${Math.round(nv.noveltyRatio * 100)}% novel · ${nv.distinct}/${nv.total} distinct`;
+}
+
+// A tiny CSS-only 24-bar histogram so chronotype timing reads at a glance
+// (mobile-friendly, no chart lib). Bars scale to the busiest hour.
+function HourBars({ histogram }) {
+ if (!Array.isArray(histogram) || histogram.length === 0) return null;
+ const max = Math.max(1, ...histogram.map((s) => s.total || 0));
+ return (
+ <div className="flex items-end gap-[2px] h-16" aria-hidden="true">
+ {histogram.map((s) => (
+ <div
+ key={s.hour}
+ title={`${fmtHour(s.hour)}: ${s.total} event(s)`}
+ className="flex-1 bg-port-accent-2/60 rounded-t"
+ style={{ height: `${Math.max(3, ((s.total || 0) / max) * 100)}%` }}
+ />
+ ))}
+ </div>
+ );
+}
+
+/**
+ * Observed-behavior evidence for the taste profile (Phase 7, #2156). Surfaces
+ * the LLM-free rollups (top artists/genres/channels/topics + novelty) and the
+ * stated-vs-observed chronotype divergence, with a "Recompute" (LLM-free) and an
+ * explicit "Interpret with AI" action that names the provider before it runs.
+ */
+export default function ObservedTasteEvidence() {
+ const [evidence, setEvidence] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [recomputing, setRecomputing] = useState(false);
+ const [interpreting, setInterpreting] = useState(false);
+ const [providers, setProviders] = useState([]);
+ const [selected, setSelected] = useState(null);
+
+ const load = useCallback(async () => {
+ const [ev, provData] = await Promise.all([
+ api.getTwinEvidence({ silent: true }).catch(() => null),
+ api.getProviders().catch(() => ({ providers: [] })),
+ ]);
+ if (ev) setEvidence(ev);
+ const enabled = (provData.providers || []).filter((p) => p.enabled);
+ setProviders(enabled);
+ if (enabled.length > 0) setSelected({ providerId: enabled[0].id, model: enabled[0].defaultModel || '' });
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ const handleRecompute = async () => {
+ setRecomputing(true);
+ const res = await api.recomputeTwinEvidence().catch(() => null);
+ setRecomputing(false);
+ if (!res) { toast('Recompute failed', { icon: '⚠️' }); return; }
+ setEvidence(res.evidence);
+ toast('Observed evidence recomputed', { icon: '🧭' });
+ };
+
+ const handleInterpret = async () => {
+ if (!selected?.providerId) { toast('Select an AI provider first', { icon: '⚠️' }); return; }
+ setInterpreting(true);
+ const res = await api.interpretTwinConsumption(selected.providerId, selected.model || undefined)
+ .catch((err) => { toast(err?.message || 'Interpretation failed', { icon: '⚠️' }); return null; });
+ setInterpreting(false);
+ if (!res?.interpretation) return;
+ // Reactively splice the new interpretation into local state (no refetch).
+ setEvidence((prev) => ({
+ ...(prev || {}),
+ taste: { ...(prev?.taste || {}), interpretation: res.interpretation },
+ }));
+ toast('Interpretation generated', { icon: '✨' });
+ };
+
+ if (loading) {
+ return (
+ <div className="bg-port-card rounded-lg border border-port-border p-6 flex items-center justify-center h-24">
+ <BrailleSpinner text="Loading evidence" />
+ </div>
+ );
+ }
+
+ const taste = evidence?.taste;
+ const chronotype = evidence?.chronotype;
+ const month = taste?.windows?.month;
+ const week = taste?.windows?.week;
+ const interpretation = taste?.interpretation;
+ const hasEvidence = Boolean(taste || chronotype);
+ const selectedProvider = providers.find((p) => p.id === selected?.providerId);
+
+ return (
+ <div className="bg-port-card rounded-lg border border-port-border p-4 sm:p-6 space-y-4">
+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
+ <div className="flex items-center gap-3">
+ <Telescope className="w-5 h-5 text-port-accent-2 shrink-0" />
+ <div>
+ <h3 className="text-base font-semibold text-white">Observed from your behavior</h3>
+ <p className="text-xs text-gray-500">
+ LLM-free rollups of what you actually listen to, watch, and when you&apos;re active — supplements (never overwrites) your stated answers.
+ </p>
+ </div>
+ </div>
+ <button
+ onClick={handleRecompute}
+ disabled={recomputing}
+ className="flex items-center justify-center gap-2 px-3 py-2 min-h-[40px] text-sm bg-port-bg border border-port-border rounded-lg text-gray-300 hover:text-white hover:border-port-accent/50 disabled:opacity-50"
+ >
+ {recomputing ? <BrailleSpinner /> : <RefreshCw size={15} />}
+ Recompute
+ </button>
+ </div>
+
+ {!hasEvidence && (
+ <div className="text-sm text-gray-400 bg-port-bg border border-port-border rounded-lg p-4">
+ No observed evidence yet. Once you&apos;ve synced Spotify / YouTube history (or logged activity), hit
+ {' '}<span className="text-gray-300">Recompute</span> to build your evidence profile.
+ </div>
+ )}
+
+ {/* Media taste rollups */}
+ {(month?.listen?.total > 0 || month?.watch?.total > 0) && (
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
+ <div className="bg-port-bg rounded-lg border border-port-border p-4 space-y-3">
+ <div className="flex items-center gap-2 text-sm text-white">
+ <Music size={15} className="text-green-400" /> Listening
+ <span className="text-gray-500 text-xs">
+ {week?.listen?.total || 0}/wk · {month?.listen?.total || 0}/mo
+ </span>
+ </div>
+ <TopList title="Top artists (30d)" items={month?.listen?.topArtists} />
+ <TopList title="Top genres (30d)" items={month?.listen?.topGenres} />
+ {fmtNovelty(month?.listen?.novelty) && (
+ <div className="text-xs text-gray-500">{fmtNovelty(month.listen.novelty)}</div>
+ )}
+ </div>
+ <div className="bg-port-bg rounded-lg border border-port-border p-4 space-y-3">
+ <div className="flex items-center gap-2 text-sm text-white">
+ <Tv size={15} className="text-red-400" /> Watching
+ <span className="text-gray-500 text-xs">
+ {week?.watch?.total || 0}/wk · {month?.watch?.total || 0}/mo
+ </span>
+ </div>
+ <TopList title="Top channels (30d)" items={month?.watch?.topChannels} />
+ <TopList title="Top topics (30d)" items={month?.watch?.topTopics} />
+ {fmtNovelty(month?.watch?.novelty) && (
+ <div className="text-xs text-gray-500">{fmtNovelty(month.watch.novelty)}</div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Chronotype: stated vs observed */}
+ {chronotype && (
+ <div className="bg-port-bg rounded-lg border border-port-border p-4 space-y-3">
+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
+ <div className="flex items-center gap-2 text-sm text-white">
+ <Clock size={15} className="text-port-accent-2" /> Daily rhythm (observed chronotype)
+ </div>
+ <DivergenceBadge comparison={evidence?.chronotypeComparison} />
+ </div>
+ <HourBars histogram={chronotype.histogram} />
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs text-gray-400">
+ <div>Observed: <span className="text-white">{chronotype.observedType || '—'}</span></div>
+ <div>Peak messages: <span className="text-white">{fmtHour(chronotype.peakHours?.messages)}</span></div>
+ <div>Peak media: <span className="text-white">{fmtHour(chronotype.peakHours?.media)}</span></div>
+ <div>Peak overall: <span className="text-white">{fmtHour(chronotype.peakHours?.overall)}</span></div>
+ </div>
+ {evidence?.statedChronotype?.type && (
+ <div className="text-xs text-gray-500">
+ Stated (genome/behavioral): <span className="text-gray-300">{evidence.statedChronotype.type}</span>
+ {evidence.statedChronotype.confidence != null && ` (${Math.round(evidence.statedChronotype.confidence * 100)}% confidence)`}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Explicit AI interpretation — names the provider before running (AI policy). */}
+ {hasEvidence && (
+ <div className="border-t border-port-border pt-4 space-y-3">
+ <div className="flex flex-col sm:flex-row sm:items-end gap-3">
+ <div className="flex-1">
+ <label htmlFor="twin-interpret-provider" className="block text-xs text-gray-500 mb-1">
+ Interpret with AI provider
+ </label>
+ {providers.length === 0 ? (
+ <p className="text-xs text-gray-500">No AI provider configured — add one in AI Providers.</p>
+ ) : (
+ <select
+ id="twin-interpret-provider"
+ value={selected?.providerId || ''}
+ onChange={(e) => {
+ const p = providers.find((x) => x.id === e.target.value);
+ setSelected({ providerId: e.target.value, model: p?.defaultModel || '' });
+ }}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white focus:outline-hidden focus:border-port-accent"
+ >
+ {providers.map((p) => (
+ <option key={p.id} value={p.id}>{p.name || p.id}{p.defaultModel ? ` · ${p.defaultModel}` : ''}</option>
+ ))}
+ </select>
+ )}
+ </div>
+ <button
+ onClick={handleInterpret}
+ disabled={interpreting || providers.length === 0}
+ className="flex items-center justify-center gap-2 px-4 py-2 min-h-[40px] text-sm bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
+ title={selectedProvider ? `Runs ${selectedProvider.name || selectedProvider.id}` : undefined}
+ >
+ {interpreting ? <BrailleSpinner /> : <Sparkles size={15} />}
+ What does this say about me?
+ </button>
+ </div>
+
+ {interpretation?.text && (
+ <div className="bg-port-bg rounded-lg border border-port-accent-2/30 p-4">
+ <div className="text-sm"><MarkdownOutput content={interpretation.text} /></div>
+ <div className="text-xs text-gray-500 mt-2">
+ {interpretation.providerName || interpretation.provider}
+ {interpretation.model ? ` · ${interpretation.model}` : ''}
+ {interpretation.generatedAt ? ` · ${new Date(interpretation.generatedAt).toLocaleString()}` : ''}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/digital-twin/tabs/TasteTab.jsx b/client/src/components/digital-twin/tabs/TasteTab.jsx
index 1102eaefaf..85d0e62e84 100644
--- a/client/src/components/digital-twin/tabs/TasteTab.jsx
+++ b/client/src/components/digital-twin/tabs/TasteTab.jsx
@@ -26,6 +26,7 @@ import toast from '../../ui/Toast';
import Banner from '../../ui/Banner';
import MarkdownOutput from '../../cos/MarkdownOutput';
import { isApiProvider } from '../../../utils/providers';
+import ObservedTasteEvidence from '../ObservedTasteEvidence';
const SECTION_ICONS = {
movies: Film,
@@ -615,6 +616,9 @@ export default function TasteTab({ onRefresh }) {
)}
</div>
+ {/* Observed-behavior evidence (stated vs observed, #2156) */}
+ <ObservedTasteEvidence />
+
{/* Section Grid */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
{(profile?.sections || []).map((section) => {
diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.js
index cc4f042df8..1de76eefac 100644
--- a/client/src/services/apiDigitalTwin.js
+++ b/client/src/services/apiDigitalTwin.js
@@ -310,6 +310,17 @@ export const compareTimeCapsuleSnapshots = (id1, id2) => request('/digital-twin/
body: JSON.stringify({ id1, id2 })
});
+// Twin enrichment — observed taste + chronotype evidence (Phase 7, #2156)
+export const getTwinEvidence = (options) => request('/digital-twin/twin-evidence', options);
+export const recomputeTwinEvidence = () => request('/digital-twin/twin-evidence/recompute', {
+ method: 'POST',
+ body: JSON.stringify({})
+});
+export const interpretTwinConsumption = (providerId, model) => request('/digital-twin/twin-evidence/interpret', {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model })
+});
+
// Soul aliases (used by digital-twin UI components)
export const createSoulDocument = createDigitalTwinDocument;
export const updateSoulDocument = updateDigitalTwinDocument;
diff --git a/server/index.js b/server/index.js
index b1c4333529..bea6cb4d1b 100644
--- a/server/index.js
+++ b/server/index.js
@@ -186,6 +186,7 @@ import { captureBootCommit } from './services/installState.js';
import { restoreLoops } from './services/loops.js';
import { startBrainScheduler } from './services/brainScheduler.js';
import { startActivityDigestScheduler } from './services/activityDigestScheduler.js';
+import { startTwinEnrichmentScheduler } from './services/twinEnrichmentScheduler.js';
import { recoverStuckClassifications } from './services/brain.js';
import { recoverStuckAnalyses } from './services/writersRoom/evaluator.js';
import { recoverStuckAutoRuns } from './services/pipeline/autoRunner.js';
@@ -599,6 +600,10 @@ startBrainScheduler();
// auto-summaries from the Human Activity timeline only when the user enables it
// (Settings → Daily Log → Activity Digest). Silent + no LLM calls until then.
startActivityDigestScheduler();
+// Initialize twin-enrichment scheduler — LLM-free daily rollup of observed
+// taste + chronotype evidence from the Human Activity timeline (#2156). No
+// provider calls; the AI interpretation is a separate explicit-button action.
+startTwinEnrichmentScheduler();
// Initialize brain→memory bridge (mirrors brain data into CoS memory for semantic search)
initBrainMemoryBridge();
// Load any on-disk POST drill cache into memory. Does NOT trigger LLM calls —
diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.js
index 978a60f476..32ca12ed0a 100644
--- a/server/lib/digitalTwinValidation.js
+++ b/server/lib/digitalTwinValidation.js
@@ -637,3 +637,19 @@ export const compareSnapshotsInputSchema = z.object({
id1: z.string().guid(),
id2: z.string().guid()
});
+
+// =============================================================================
+// TWIN ENRICHMENT SCHEMAS (Phase 7, #2156)
+// Observed-behavior taste + chronotype evidence. Recompute is LLM-free (empty
+// body); interpret is an explicit user-triggered provider call.
+// =============================================================================
+
+// Recompute the LLM-free rollups. No inputs — the body is ignored, but validate
+// it as an (optionally empty) object so a stray payload is rejected cleanly.
+export const twinEvidenceRecomputeInputSchema = z.object({}).strict().optional().default({});
+
+// "What does my consumption say about me" — explicit provider call.
+export const twinEvidenceInterpretInputSchema = z.object({
+ providerId: z.string().min(1),
+ model: z.string().min(1).optional()
+});
diff --git a/server/routes/digital-twin.js b/server/routes/digital-twin.js
index 806d9ebd75..292a772e54 100644
--- a/server/routes/digital-twin.js
+++ b/server/routes/digital-twin.js
@@ -48,8 +48,11 @@ import {
compareSnapshotsInputSchema,
createPersonaInputSchema,
updatePersonaInputSchema,
- setActivePersonaInputSchema
+ setActivePersonaInputSchema,
+ twinEvidenceRecomputeInputSchema,
+ twinEvidenceInterpretInputSchema
} from '../lib/digitalTwinValidation.js';
+import * as twinEnrichment from '../services/twinEnrichment.js';
import * as timeCapsuleService from '../services/timeCapsule.js';
import { UUID_RE } from '../lib/fileUtils.js';
import { z } from 'zod';
@@ -946,4 +949,42 @@ router.post('/snapshots/compare', asyncHandler(async (req, res) => {
res.json(diff);
}));
+// =============================================================================
+// TWIN ENRICHMENT — observed taste + chronotype evidence (Phase 7, #2156)
+// =============================================================================
+
+/**
+ * GET /api/digital-twin/twin-evidence
+ * Observed taste + chronotype evidence, plus the stated-vs-observed chronotype
+ * divergence flag. Read-only, LLM-free. `taste`/`chronotype` are null until the
+ * first aggregation runs (sentinel: null = never computed, not empty).
+ */
+router.get('/twin-evidence', asyncHandler(async (req, res) => {
+ const evidence = await twinEnrichment.getObservedEvidence();
+ res.json(evidence);
+}));
+
+/**
+ * POST /api/digital-twin/twin-evidence/recompute
+ * Recompute the LLM-free rollups from the activity timeline. No provider calls.
+ */
+router.post('/twin-evidence/recompute', asyncHandler(async (req, res) => {
+ validateRequest(twinEvidenceRecomputeInputSchema, req.body ?? {});
+ const summary = await twinEnrichment.aggregateTwinEvidence();
+ const evidence = await twinEnrichment.getObservedEvidence();
+ res.json({ summary, evidence });
+}));
+
+/**
+ * POST /api/digital-twin/twin-evidence/interpret
+ * Generate an AI interpretation of the observed evidence — EXPLICIT user action
+ * only (per the AI-provider policy). Persists the narrative onto the taste
+ * evidence record.
+ */
+router.post('/twin-evidence/interpret', asyncHandler(async (req, res) => {
+ const { providerId, model } = validateRequest(twinEvidenceInterpretInputSchema, req.body);
+ const interpretation = await twinEnrichment.interpretConsumption({ providerId, model });
+ res.json({ interpretation });
+}));
+
export default router;
diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.js
index 67f8b70af5..ed227dd084 100644
--- a/server/services/digital-twin-sync.js
+++ b/server/services/digital-twin-sync.js
@@ -46,6 +46,12 @@ const CHRONOTYPE_FILE = join(DIR, 'chronotype.json');
const LONGEVITY_FILE = join(DIR, 'longevity.json');
const FEEDBACK_FILE = join(DIR, 'feedback.json');
const TASTE_FILE = join(DIR, 'taste-profile.json');
+// Observed-behavior evidence records (Phase 7, #2156) — supplement, never
+// overwrite, the questionnaire/genome twin. Regenerated on each aggregation, so
+// they federate LWW on `derivedAt` (newest observation wins wholesale — a
+// per-key union would splice one machine's top-artists into another's).
+const TASTE_OBSERVED_FILE = join(DIR, 'taste-observed.json');
+const CHRONOTYPE_OBSERVED_FILE = join(DIR, 'chronotype-observed.json');
const META_FILE = join(DIR, 'meta.json');
const AUTOBIO_DIR = join(DIR, 'autobiography');
const AUTOBIO_STORIES_FILE = join(AUTOBIO_DIR, 'stories.json');
@@ -402,19 +408,21 @@ export async function getDigitalTwinSnapshot() {
// lastPromptAt) is deliberately NOT in the snapshot — it is machine-local
// scheduling state, and a fresh peer must not inherit another machine's
// cadence or have prompts enabled without local opt-in. Only the stories sync.
- const [identity, chronotype, longevity, feedback, taste, meta, documents, stories, socialAccounts] =
+ const [identity, chronotype, longevity, feedback, taste, tasteObserved, chronotypeObserved, meta, documents, stories, socialAccounts] =
await Promise.all([
readJSONFile(IDENTITY_FILE, null),
readJSONFile(CHRONOTYPE_FILE, null),
readJSONFile(LONGEVITY_FILE, null),
readJSONFile(FEEDBACK_FILE, null),
readJSONFile(TASTE_FILE, null),
+ readJSONFile(TASTE_OBSERVED_FILE, null),
+ readJSONFile(CHRONOTYPE_OBSERVED_FILE, null),
readJSONFile(META_FILE, null),
readMarkdownDocuments(),
readJSONFile(AUTOBIO_STORIES_FILE, null),
readJSONFile(SOCIAL_ACCOUNTS_FILE, null),
]);
- const data = { identity, chronotype, longevity, feedback, taste, meta, documents, autobiography: { stories }, socialAccounts };
+ const data = { identity, chronotype, longevity, feedback, taste, tasteObserved, chronotypeObserved, meta, documents, autobiography: { stories }, socialAccounts };
return { data, checksum: computeChecksum(data) };
}
@@ -501,6 +509,9 @@ export async function applyDigitalTwinRemote(remoteData) {
count += await applyMerge(LONGEVITY_FILE, remoteData.longevity, (l, r) => mergeDeepUnion(l, r, 'derivedAt'));
count += await applyMerge(FEEDBACK_FILE, remoteData.feedback, (l, r) => mergeObjectLWW(l, r, 'updatedAt'));
count += await applyTaste(remoteData.taste);
+ // Observed evidence (Phase 7): regenerated derived records — newest wins.
+ count += await applyMerge(TASTE_OBSERVED_FILE, remoteData.tasteObserved, (l, r) => mergeObjectLWW(l, r, 'derivedAt'));
+ count += await applyMerge(CHRONOTYPE_OBSERVED_FILE, remoteData.chronotypeObserved, (l, r) => mergeObjectLWW(l, r, 'derivedAt'));
// Meta BEFORE documents: applyMeta()'s loadMeta() rebuilds meta from a disk
// .md scan when no meta.json exists, creating DEFAULT document entries. If the
// peer's .md files were written first, that rebuild would manufacture default
diff --git a/server/services/digital-twin-sync.test.js b/server/services/digital-twin-sync.test.js
index 1655606d0b..8c8f3bf9c8 100644
--- a/server/services/digital-twin-sync.test.js
+++ b/server/services/digital-twin-sync.test.js
@@ -27,6 +27,16 @@ describe('mergeObjectLWW', () => {
expect(mergeObjectLWW(local, { v: 'R', updatedAt: '2026-01-03' }).merged.v).toBe('R');
expect(mergeObjectLWW(local, { v: 'R', updatedAt: '2026-01-02' }).changed).toBe(false);
});
+ it('federates observed evidence (#2156) LWW on derivedAt — newest observation wins', () => {
+ // taste-observed.json / chronotype-observed.json are regenerated derived
+ // records, so the sync merges them wholesale on the derivedAt stamp.
+ const local = { source: 'observed', derivedAt: '2026-07-01T00:00:00Z', observedType: 'morning' };
+ const remote = { source: 'observed', derivedAt: '2026-07-05T00:00:00Z', observedType: 'evening' };
+ expect(mergeObjectLWW(local, remote, 'derivedAt').merged.observedType).toBe('evening');
+ expect(mergeObjectLWW(remote, local, 'derivedAt').merged.observedType).toBe('evening');
+ // A peer that sends no observed evidence can't blank the local record.
+ expect(mergeObjectLWW(local, null, 'derivedAt')).toEqual({ merged: local, changed: false });
+ });
});
describe('mergeDeepUnion', () => {
diff --git a/server/services/spotifySync.js b/server/services/spotifySync.js
index b2fb025974..940d8941e7 100644
--- a/server/services/spotifySync.js
+++ b/server/services/spotifySync.js
@@ -206,6 +206,13 @@ async function doRunSync() {
return { recorded: 0, skipped: candidates.length };
});
+ // Incrementally refresh observed twin evidence when new listens landed (#2156).
+ // LLM-free + self-guarded — never blocks or fails the sync.
+ if (!persistFailed && recordResult.recorded > 0) {
+ const { refreshTwinEvidenceAfterSync } = await import('./twinEnrichment.js');
+ await refreshTwinEvidenceAfterSync();
+ }
+
// Prefer the response's own `cursors.after` (Spotify's canonical next cursor),
// falling back to the computed max — but never regress below the stored cursor.
const responseCursor = Number(payload?.cursors?.after);
diff --git a/server/services/twinEnrichment.js b/server/services/twinEnrichment.js
new file mode 100644
index 0000000000..b78cfcba64
--- /dev/null
+++ b/server/services/twinEnrichment.js
@@ -0,0 +1,498 @@
+/**
+ * Digital-Twin Enrichment from observed behavior (Human Activity Tracking
+ * Phase 7, #2156).
+ *
+ * Turns the machine-local Human Activity timeline (#2150) into LLM-free
+ * *evidence* records that supplement — never overwrite — the questionnaire-based
+ * digital twin:
+ *
+ * - `media.listen` / `media.watch` rollups (top artists / genres / channels /
+ * topics per week + month, novelty-vs-repeat ratio) → `taste-observed.json`,
+ * a taste-profile evidence record with `source: 'observed'` provenance.
+ * - An hourly activity histogram (messages sent, meetings, media consumed by
+ * LOCAL hour) → `chronotype-observed.json`, chronotype evidence sitting
+ * alongside the stated `chronotype.json`.
+ *
+ * Both files carry `source: 'observed'` and a `derivedAt` stamp, live under
+ * `data/digital-twin/`, and federate via `digital-twin-sync.js` (LWW on
+ * `derivedAt` — newest observation wins). The *stated* records (taste-profile
+ * questionnaire, genome/behavioral chronotype) are never touched here: the UI
+ * surfaces both side-by-side and flags divergence, which is signal, not error.
+ *
+ * Aggregation is deterministic and LLM-free — safe to run incrementally after
+ * each source sync or on a daily rollup tick with no user consent (no provider
+ * calls). The ONLY provider call is `interpretConsumption()`, invoked strictly
+ * from an explicit user-action route (the "what does my consumption say about
+ * me" button), per CLAUDE.md's AI-provider policy (no cold-bootstrap calls).
+ */
+
+import { join } from 'path';
+import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { query, ensureSchema } from '../lib/db.js';
+import { getLocalParts, getUserTimezone } from '../lib/timezone.js';
+import { getProviderById } from './providers.js';
+import { runPromptThroughProvider } from '../lib/promptRunner.js';
+
+const DIR = PATHS.digitalTwin;
+const TASTE_OBSERVED_FILE = join(DIR, 'taste-observed.json');
+const CHRONOTYPE_OBSERVED_FILE = join(DIR, 'chronotype-observed.json');
+
+// How far back each rollup window reaches, in days.
+const WEEK_DAYS = 7;
+const MONTH_DAYS = 30;
+// Chronotype histogram window — a month of activity smooths day-to-day noise.
+const CHRONOTYPE_WINDOW_DAYS = 30;
+// Safety cap on a single windowed fetch. A month of media + messages is well
+// under this; the ceiling only guards a pathological backfill from loading the
+// whole table into memory.
+const FETCH_CAP = 50000;
+
+const MEDIA_LISTEN = 'media.listen';
+const MEDIA_WATCH = 'media.watch';
+
+// ---------------------------------------------------------------------------
+// Pure helpers (exported for unit tests — no DB, no side effects).
+// ---------------------------------------------------------------------------
+
+// Tally an array of string keys into a sorted [{ name, count }] top-N list.
+// Blank/nullish keys are skipped. Ties break alphabetically for a stable order
+// (the file feeds the federation checksum — unstable order never converges).
+export function topCounts(keys, limit = 10) {
+ const counts = new Map();
+ for (const raw of keys || []) {
+ const name = String(raw ?? '').trim();
+ if (!name) continue;
+ counts.set(name, (counts.get(name) || 0) + 1);
+ }
+ return Array.from(counts.entries())
+ .sort((a, b) => (b[1] - a[1]) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
+ .slice(0, Math.max(0, limit))
+ .map(([name, count]) => ({ name, count }));
+}
+
+// Novelty vs repeat for a window of plays. `keys` is one entry per play (e.g.
+// each track id every time it was played). Distinct items are the "novel" set;
+// plays beyond the first of each item are "repeats". noveltyRatio = distinct /
+// total (1.0 = never repeats anything; →0 = heavy repetition). total 0 → nulls
+// so an empty window reads as "no signal", not "0% novel".
+export function noveltyRatio(keys) {
+ const list = (keys || []).map((k) => String(k ?? '').trim()).filter(Boolean);
+ const total = list.length;
+ if (total === 0) return { total: 0, distinct: 0, repeats: 0, noveltyRatio: null };
+ const distinct = new Set(list).size;
+ const ratio = Math.round((distinct / total) * 1000) / 1000;
+ return { total, distinct, repeats: total - distinct, noveltyRatio: ratio };
+}
+
+// Flatten a listen event's artist names. Accepts metadata.artists as
+// [{ name }] or [string], falling back to the summary line (spotifySync stores
+// the comma-joined artist names there) so a leaner event still contributes.
+export function listenArtistNames(ev) {
+ const artists = ev?.metadata?.artists;
+ if (Array.isArray(artists)) {
+ const names = artists.map((a) => String((typeof a === 'string' ? a : a?.name) || '').trim()).filter(Boolean);
+ if (names.length) return names;
+ }
+ const summary = String(ev?.summary || '').trim();
+ return summary ? summary.split(',').map((s) => s.trim()).filter(Boolean) : [];
+}
+
+// Genre names for a listen event (metadata.genres: [string] | [{ name }]).
+// Spotify's recently-played endpoint omits genres today, so this is usually
+// empty — supported now so a future genre-enriched source flows straight in.
+export function listenGenreNames(ev) {
+ const genres = ev?.metadata?.genres;
+ if (!Array.isArray(genres)) return [];
+ return genres.map((g) => String((typeof g === 'string' ? g : g?.name) || '').trim()).filter(Boolean);
+}
+
+// A stable per-play key for novelty counting (track id preferred, title fallback).
+function listenNoveltyKey(ev) {
+ return ev?.metadata?.trackId || ev?.metadata?.isrc || ev?.title || ev?.dedupeKey || '';
+}
+function watchNoveltyKey(ev) {
+ return ev?.metadata?.videoId || ev?.url || ev?.title || ev?.dedupeKey || '';
+}
+
+// Roll up media.listen events into taste evidence: top artists, top genres,
+// novelty. `topN` bounds each list.
+export function rollupListen(events, topN = 10) {
+ const listens = (events || []).filter((e) => e?.kind === MEDIA_LISTEN);
+ const artistKeys = [];
+ const genreKeys = [];
+ for (const ev of listens) {
+ artistKeys.push(...listenArtistNames(ev));
+ genreKeys.push(...listenGenreNames(ev));
+ }
+ return {
+ total: listens.length,
+ topArtists: topCounts(artistKeys, topN),
+ topGenres: topCounts(genreKeys, topN),
+ novelty: noveltyRatio(listens.map(listenNoveltyKey)),
+ };
+}
+
+// Roll up media.watch events into taste evidence: top channels, top topics,
+// novelty.
+export function rollupWatch(events, topN = 10) {
+ const watches = (events || []).filter((e) => e?.kind === MEDIA_WATCH);
+ const channelKeys = [];
+ const topicKeys = [];
+ for (const ev of watches) {
+ const channel = ev?.metadata?.channel || ev?.summary;
+ if (channel) channelKeys.push(channel);
+ const topics = ev?.metadata?.topics;
+ if (Array.isArray(topics)) topicKeys.push(...topics.map((t) => String(t ?? '').trim()).filter(Boolean));
+ }
+ return {
+ total: watches.length,
+ topChannels: topCounts(channelKeys, topN),
+ topTopics: topCounts(topicKeys, topN),
+ novelty: noveltyRatio(watches.map(watchNoveltyKey)),
+ };
+}
+
+const MESSAGE_SENT = 'message.sent';
+const MEETING = 'calendar.event';
+
+// Bucket events into a 24-slot local-hour histogram with per-category counts:
+// [{ hour, messages, meetings, media, total }]. Only OUTBOUND messages
+// (message.sent) count toward the chronotype signal — received messages reflect
+// others' schedules, not the user's. Media = listen + watch. Timezone drives the
+// local hour so an event at 23:30 UTC lands in the user's evening, not UTC's.
+export function chronotypeHistogram(events, timezone) {
+ const slots = Array.from({ length: 24 }, (_, hour) => ({ hour, messages: 0, meetings: 0, media: 0, total: 0 }));
+ for (const ev of events || []) {
+ const d = new Date(ev?.happenedAt ?? ev?.happened_at);
+ if (Number.isNaN(d.getTime())) continue;
+ const { hour } = getLocalParts(d, timezone);
+ if (!(hour >= 0 && hour < 24)) continue;
+ const slot = slots[hour];
+ if (ev.kind === MESSAGE_SENT) slot.messages += 1;
+ else if (ev.kind === MEETING) slot.meetings += 1;
+ else if (ev.kind === MEDIA_LISTEN || ev.kind === MEDIA_WATCH) slot.media += 1;
+ else continue; // received messages / unknown kinds aren't a self-timing signal
+ slot.total = slot.messages + slot.meetings + slot.media;
+ }
+ return slots;
+}
+
+// The hour with the highest count for a histogram field, or null when there's
+// no activity in that field (sentinel: absent signal ≠ midnight).
+export function peakHour(histogram, field = 'total') {
+ let best = null;
+ let bestCount = 0;
+ for (const slot of histogram || []) {
+ const count = slot?.[field] || 0;
+ if (count > bestCount) { bestCount = count; best = slot.hour; }
+ }
+ return best;
+}
+
+// Classify an observed chronotype from the histogram's activity center-of-mass.
+// A circular mean over active hours handles the midnight wrap (a night owl
+// active 22:00–02:00 shouldn't average to noon). Returns morning / intermediate
+// / evening, or null when there isn't enough signal. Thresholds mirror the
+// stated-chronotype classifier's spirit (early center = morning, late = evening).
+export function classifyObservedChronotype(histogram) {
+ let sumX = 0;
+ let sumY = 0;
+ let total = 0;
+ for (const slot of histogram || []) {
+ const count = slot?.total || 0;
+ if (!count) continue;
+ const angle = (slot.hour / 24) * 2 * Math.PI;
+ sumX += Math.cos(angle) * count;
+ sumY += Math.sin(angle) * count;
+ total += count;
+ }
+ if (total < 5) return { type: null, centerHour: null, sampleSize: total };
+ let meanAngle = Math.atan2(sumY, sumX);
+ if (meanAngle < 0) meanAngle += 2 * Math.PI;
+ const centerHour = Math.round((meanAngle / (2 * Math.PI)) * 24) % 24;
+ // Center-of-mass hour → type. Daytime activity clusters, so a center before
+ // ~11:00 skews morning, after ~15:00 skews evening, between is intermediate.
+ let type;
+ if (centerHour < 11) type = 'morning';
+ else if (centerHour >= 15) type = 'evening';
+ else type = 'intermediate';
+ return { type, centerHour, sampleSize: total };
+}
+
+const DIVERGENCE_RANK = { morning: 0, intermediate: 1, evening: 2 };
+
+// Compare a stated chronotype type against the observed one. Distance of 0 =
+// agree, 1 = mild (adjacent), 2 = strong (morning vs evening). Either side null
+// → 'unknown' (not enough signal / no stated value yet), never a false divergence.
+export function compareChronotype(statedType, observedType) {
+ const s = DIVERGENCE_RANK[statedType];
+ const o = DIVERGENCE_RANK[observedType];
+ if (s === undefined || o === undefined) {
+ return { statedType: statedType ?? null, observedType: observedType ?? null, agree: null, divergence: 'unknown' };
+ }
+ const dist = Math.abs(s - o);
+ const divergence = dist === 0 ? 'none' : dist === 1 ? 'mild' : 'strong';
+ return { statedType, observedType, agree: dist === 0, divergence, distance: dist };
+}
+
+// ---------------------------------------------------------------------------
+// DB fetch (thin — the analysis lives in the pure helpers above).
+// ---------------------------------------------------------------------------
+
+function rowToLite(row) {
+ return {
+ kind: row.kind,
+ source: row.source,
+ happenedAt: row.happened_at instanceof Date ? row.happened_at.toISOString() : row.happened_at,
+ title: row.title,
+ summary: row.summary,
+ dedupeKey: row.dedupe_key,
+ metadata: row.metadata || {},
+ };
+}
+
+// Fetch a window of events (happened_at >= sinceIso), optionally filtered to a
+// set of kinds. Lightweight columns only — enrichment never needs participants.
+async function fetchWindow(sinceIso, kinds = null) {
+ await ensureSchema();
+ const params = [sinceIso];
+ let where = 'happened_at >= $1';
+ if (Array.isArray(kinds) && kinds.length) {
+ params.push(kinds);
+ where += ` AND kind = ANY($${params.length})`;
+ }
+ params.push(FETCH_CAP);
+ const result = await query(
+ `SELECT kind, source, happened_at, title, summary, metadata, dedupe_key
+ FROM human_activity_events
+ WHERE ${where}
+ ORDER BY happened_at DESC
+ LIMIT $${params.length}`,
+ params,
+ );
+ return result.rows.map(rowToLite);
+}
+
+function daysAgoIso(days, now) {
+ return new Date(now - days * 24 * 60 * 60 * 1000).toISOString();
+}
+
+// ---------------------------------------------------------------------------
+// Evidence read (sentinel: null = never computed, not empty).
+// ---------------------------------------------------------------------------
+
+export async function getTasteEvidence() {
+ return readJSONFile(TASTE_OBSERVED_FILE, null);
+}
+
+export async function getChronotypeEvidence() {
+ return readJSONFile(CHRONOTYPE_OBSERVED_FILE, null);
+}
+
+// ---------------------------------------------------------------------------
+// Aggregation (LLM-free — no provider calls, safe to run unattended).
+// ---------------------------------------------------------------------------
+
+/**
+ * Recompute both observed-evidence records from the activity timeline and
+ * persist them under `data/digital-twin/`. Deterministic and provider-free.
+ * Returns a small summary for logging / the API response. The stored records
+ * preserve any prior `interpretation` block (an LLM narrative is only added by
+ * `interpretConsumption`, and a plain recompute must not wipe it — the evidence
+ * numbers refreshed, but the last interpretation is still the user's).
+ */
+export async function aggregateTwinEvidence({ now = Date.now() } = {}) {
+ const timezone = await getUserTimezone();
+ const derivedAt = new Date(now).toISOString();
+
+ // Media windows for taste (listen + watch only).
+ const monthMedia = await fetchWindow(daysAgoIso(MONTH_DAYS, now), [MEDIA_LISTEN, MEDIA_WATCH]);
+ const weekCutoff = daysAgoIso(WEEK_DAYS, now);
+ const weekMedia = monthMedia.filter((e) => e.happenedAt >= weekCutoff);
+
+ const priorTaste = await getTasteEvidence();
+ const taste = {
+ source: 'observed',
+ derivedAt,
+ timezone,
+ windows: {
+ week: { days: WEEK_DAYS, listen: rollupListen(weekMedia), watch: rollupWatch(weekMedia) },
+ month: { days: MONTH_DAYS, listen: rollupListen(monthMedia), watch: rollupWatch(monthMedia) },
+ },
+ // Preserve a prior AI interpretation across LLM-free recomputes.
+ ...(priorTaste?.interpretation ? { interpretation: priorTaste.interpretation } : {}),
+ };
+ await ensureDir(DIR);
+ await atomicWrite(TASTE_OBSERVED_FILE, taste);
+
+ // Chronotype window: outbound messages + meetings + media by local hour.
+ const chronoEvents = await fetchWindow(
+ daysAgoIso(CHRONOTYPE_WINDOW_DAYS, now),
+ [MESSAGE_SENT, MEETING, MEDIA_LISTEN, MEDIA_WATCH],
+ );
+ const histogram = chronotypeHistogram(chronoEvents, timezone);
+ const observed = classifyObservedChronotype(histogram);
+ const chronotype = {
+ source: 'observed',
+ derivedAt,
+ timezone,
+ windowDays: CHRONOTYPE_WINDOW_DAYS,
+ histogram,
+ observedType: observed.type,
+ centerHour: observed.centerHour,
+ sampleSize: observed.sampleSize,
+ peakHours: {
+ messages: peakHour(histogram, 'messages'),
+ meetings: peakHour(histogram, 'meetings'),
+ media: peakHour(histogram, 'media'),
+ overall: peakHour(histogram, 'total'),
+ },
+ };
+ await atomicWrite(CHRONOTYPE_OBSERVED_FILE, chronotype);
+
+ console.log(`🧭 Twin evidence aggregated: ${monthMedia.length} media / ${chronoEvents.length} activity event(s), observed chronotype ${observed.type || 'n/a'}`);
+ return {
+ taste: { week: weekMedia.length, month: monthMedia.length },
+ chronotype: { events: chronoEvents.length, observedType: observed.type, sampleSize: observed.sampleSize },
+ derivedAt,
+ };
+}
+
+/**
+ * Incremental refresh hook for source syncs (Spotify / YouTube). Fire-and-guard:
+ * called after a media sync records new events so the observed evidence stays
+ * fresh without waiting for the daily tick. LLM-free. Never throws — it runs
+ * outside the request lifecycle (scheduler / sync path), so a failure is logged
+ * and swallowed rather than crashing the caller.
+ */
+export async function refreshTwinEvidenceAfterSync() {
+ return aggregateTwinEvidence().catch((err) => {
+ console.error(`🧭 Twin evidence refresh after sync failed: ${err.message}`);
+ return null;
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Stated-vs-observed comparison (pure I/O composition — no provider calls).
+// ---------------------------------------------------------------------------
+
+/**
+ * Assemble the Digital-Twin UI's "observed evidence" payload: the observed
+ * taste + chronotype records, and a chronotype divergence flag against the
+ * stated (genome/behavioral) chronotype. Stated taste lives in the existing
+ * taste-profile endpoint, so the UI overlays that separately; here we only need
+ * the chronotype divergence (a single classifiable dimension).
+ */
+export async function getObservedEvidence() {
+ const [taste, chronotype, statedChronotype] = await Promise.all([
+ getTasteEvidence(),
+ getChronotypeEvidence(),
+ readJSONFile(join(DIR, 'chronotype.json'), null),
+ ]);
+ // Only treat the stated chronotype as a real answer once it's been derived —
+ // an underived record carries DEFAULT_CHRONOTYPE's 'intermediate', which would
+ // otherwise fake a stated value and produce a spurious divergence flag.
+ const stated = statedChronotype?.derivedAt ? statedChronotype : null;
+ const statedType = stated?.type ?? null;
+ const observedType = chronotype?.observedType ?? null;
+ return {
+ taste,
+ chronotype,
+ chronotypeComparison: compareChronotype(statedType, observedType),
+ statedChronotype: stated
+ ? { type: statedType, confidence: stated.confidence ?? null }
+ : null,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// LLM interpretation — EXPLICIT USER ACTION ONLY (per AI-provider policy).
+// Never called from boot, a scheduler, or a sync hook.
+// ---------------------------------------------------------------------------
+
+// Render the observed evidence into a compact deterministic brief for the LLM —
+// numbers only, no raw event bodies (privacy) and no invented interpretation.
+export function buildConsumptionBrief(taste, chronotype) {
+ const lines = [];
+ const fmtTop = (list) => (Array.isArray(list) && list.length
+ ? list.map((x) => `${x.name} (${x.count})`).join(', ')
+ : 'none');
+ const month = taste?.windows?.month;
+ if (month) {
+ const days = month.days || 30;
+ lines.push(`Listening (last ${days}d): ${month.listen?.total || 0} plays.`);
+ lines.push(` Top artists: ${fmtTop(month.listen?.topArtists)}.`);
+ if (month.listen?.topGenres?.length) lines.push(` Top genres: ${fmtTop(month.listen.topGenres)}.`);
+ const nv = month.listen?.novelty;
+ if (nv?.noveltyRatio != null) lines.push(` Novelty ratio: ${nv.noveltyRatio} (${nv.distinct} distinct of ${nv.total}).`);
+ lines.push(`Watching (last ${days}d): ${month.watch?.total || 0} videos.`);
+ lines.push(` Top channels: ${fmtTop(month.watch?.topChannels)}.`);
+ if (month.watch?.topTopics?.length) lines.push(` Top topics: ${fmtTop(month.watch.topTopics)}.`);
+ }
+ if (chronotype) {
+ lines.push(`Observed chronotype: ${chronotype.observedType || 'unknown'} (activity center-of-mass hour ${chronotype.centerHour ?? 'n/a'}, ${chronotype.sampleSize || 0} events).`);
+ const pk = chronotype.peakHours || {};
+ lines.push(` Peak hours — messages: ${pk.messages ?? 'n/a'}, media: ${pk.media ?? 'n/a'}, overall: ${pk.overall ?? 'n/a'}.`);
+ }
+ return lines.join('\n');
+}
+
+function buildInterpretationPrompt(brief) {
+ return [
+ 'Below is a factual, anonymized summary of my recent media consumption and daily-activity timing, derived from my own listening/watching history.',
+ 'Reflect back what this pattern suggests about my tastes, interests, and daily rhythm. Write 3–5 short first-person sentences ("My ...", "I tend to ..."). Ground every claim in the numbers below — do NOT invent artists, genres, or facts not present. No heading, no preamble, no disclaimers.',
+ '',
+ 'Consumption summary:',
+ brief,
+ ].join('\n');
+}
+
+/**
+ * Generate an AI interpretation of the observed evidence and persist it into
+ * `taste-observed.json` under `interpretation`. EXPLICIT user action only — the
+ * route handler is the sole caller, gated behind a UI button that names the
+ * provider/model. Throws when no evidence exists yet or the provider is missing
+ * (the route surfaces a clean error); the provider call itself never throws (it
+ * runs a child process — failures return null and we raise a friendly error).
+ */
+export async function interpretConsumption({ providerId, model } = {}) {
+ const taste = await getTasteEvidence();
+ const chronotype = await getChronotypeEvidence();
+ if (!taste && !chronotype) {
+ throw new Error('No observed evidence yet — recompute the rollups first.');
+ }
+ const provider = await getProviderById(providerId).catch(() => null);
+ if (!provider || !provider.enabled) {
+ throw new Error('Selected AI provider is not available. Configure one in AI Providers.');
+ }
+ const brief = buildConsumptionBrief(taste, chronotype);
+ const chosenModel = model || provider.defaultModel;
+ // Headless run — a CLI provider shouldn't persist a session transcript.
+ const providerForCall = provider.headlessArgs?.length
+ ? { ...provider, args: [...(provider.args || []), ...provider.headlessArgs] }
+ : provider;
+ const result = await runPromptThroughProvider({
+ provider: providerForCall,
+ prompt: buildInterpretationPrompt(brief),
+ source: 'twin-enrichment-interpret',
+ model: chosenModel,
+ }).catch((err) => {
+ console.error(`🧭 Twin interpretation failed: ${err.message}`);
+ return null;
+ });
+ const text = (result?.text || '').trim();
+ if (!text) throw new Error('The AI provider returned no interpretation. Try again or pick another provider.');
+
+ const interpretation = {
+ text,
+ provider: provider.id,
+ providerName: provider.name || provider.id,
+ model: chosenModel || null,
+ generatedAt: new Date().toISOString(),
+ };
+ const merged = { ...(taste || { source: 'observed', derivedAt: interpretation.generatedAt }), interpretation };
+ await ensureDir(DIR);
+ await atomicWrite(TASTE_OBSERVED_FILE, merged);
+ console.log(`🧭 Twin interpretation generated via ${interpretation.providerName} (${text.length} chars)`);
+ return interpretation;
+}
diff --git a/server/services/twinEnrichment.test.js b/server/services/twinEnrichment.test.js
new file mode 100644
index 0000000000..b85e196505
--- /dev/null
+++ b/server/services/twinEnrichment.test.js
@@ -0,0 +1,235 @@
+/**
+ * Pure-logic tests for twin enrichment (Phase 7, #2156). No DB, no provider
+ * calls — these cover the deterministic rollup math, novelty ratio, hourly
+ * histogram bucketing (with timezone edge cases), observed-chronotype
+ * classification, and the stated-vs-observed comparison (divergence is signal,
+ * observed never clobbers stated). The DB fetch + file persistence + LLM
+ * interpretation paths are thin wrappers over these helpers.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ topCounts,
+ noveltyRatio,
+ listenArtistNames,
+ listenGenreNames,
+ rollupListen,
+ rollupWatch,
+ chronotypeHistogram,
+ peakHour,
+ classifyObservedChronotype,
+ compareChronotype,
+ buildConsumptionBrief,
+} from './twinEnrichment.js';
+
+describe('topCounts', () => {
+ it('counts and sorts by frequency, then alphabetically for ties', () => {
+ const out = topCounts(['b', 'a', 'b', 'c', 'a', 'a']);
+ expect(out).toEqual([
+ { name: 'a', count: 3 },
+ { name: 'b', count: 2 },
+ { name: 'c', count: 1 },
+ ]);
+ });
+ it('skips blank/nullish keys and trims', () => {
+ expect(topCounts([' x ', '', null, undefined, 'x'])).toEqual([{ name: 'x', count: 2 }]);
+ });
+ it('respects the limit', () => {
+ expect(topCounts(['a', 'b', 'c', 'd'], 2)).toHaveLength(2);
+ });
+ it('breaks equal-count ties by name (stable federation order)', () => {
+ // z and a both appear once — alphabetical keeps checksums convergent.
+ expect(topCounts(['z', 'a']).map((x) => x.name)).toEqual(['a', 'z']);
+ });
+});
+
+describe('noveltyRatio', () => {
+ it('returns null ratio for an empty window (no signal ≠ 0% novel)', () => {
+ expect(noveltyRatio([])).toEqual({ total: 0, distinct: 0, repeats: 0, noveltyRatio: null });
+ });
+ it('is 1.0 when nothing repeats', () => {
+ expect(noveltyRatio(['a', 'b', 'c'])).toEqual({ total: 3, distinct: 3, repeats: 0, noveltyRatio: 1 });
+ });
+ it('drops as items repeat', () => {
+ // 4 plays, 2 distinct → 0.5 novel, 2 repeats.
+ expect(noveltyRatio(['a', 'a', 'b', 'b'])).toEqual({ total: 4, distinct: 2, repeats: 2, noveltyRatio: 0.5 });
+ });
+});
+
+describe('listenArtistNames / listenGenreNames', () => {
+ it('reads structured artist objects', () => {
+ expect(listenArtistNames({ metadata: { artists: [{ name: 'Boards of Canada' }, { name: 'Aphex Twin' }] } }))
+ .toEqual(['Boards of Canada', 'Aphex Twin']);
+ });
+ it('accepts bare-string artists', () => {
+ expect(listenArtistNames({ metadata: { artists: ['Solo'] } })).toEqual(['Solo']);
+ });
+ it('falls back to the comma-joined summary line when metadata is lean', () => {
+ expect(listenArtistNames({ summary: 'A, B , C' })).toEqual(['A', 'B', 'C']);
+ });
+ it('returns [] when there is nothing usable', () => {
+ expect(listenArtistNames({})).toEqual([]);
+ expect(listenGenreNames({})).toEqual([]);
+ });
+ it('reads genres when present (future-proof)', () => {
+ expect(listenGenreNames({ metadata: { genres: ['ambient', { name: 'idm' }] } })).toEqual(['ambient', 'idm']);
+ });
+});
+
+describe('rollupListen / rollupWatch', () => {
+ const listens = [
+ { kind: 'media.listen', title: 'T1', metadata: { trackId: 't1', artists: [{ name: 'A' }], genres: ['ambient'] } },
+ { kind: 'media.listen', title: 'T1', metadata: { trackId: 't1', artists: [{ name: 'A' }], genres: ['ambient'] } },
+ { kind: 'media.listen', title: 'T2', metadata: { trackId: 't2', artists: [{ name: 'B' }] } },
+ { kind: 'media.watch', title: 'V1', metadata: { videoId: 'v1', channel: 'Chan' } }, // ignored by listen rollup
+ ];
+ it('rolls up only media.listen events', () => {
+ const r = rollupListen(listens);
+ expect(r.total).toBe(3);
+ expect(r.topArtists).toEqual([{ name: 'A', count: 2 }, { name: 'B', count: 1 }]);
+ expect(r.topGenres).toEqual([{ name: 'ambient', count: 2 }]);
+ // 3 plays, t1 twice → 2 distinct.
+ expect(r.novelty).toEqual({ total: 3, distinct: 2, repeats: 1, noveltyRatio: 0.667 });
+ });
+ it('rolls up only media.watch events with channels + novelty', () => {
+ const watches = [
+ { kind: 'media.watch', title: 'V1', metadata: { videoId: 'v1', channel: 'Chan', topics: ['tech'] } },
+ { kind: 'media.watch', title: 'V2', metadata: { videoId: 'v2', channel: 'Chan' } },
+ { kind: 'media.listen', title: 'T', metadata: { trackId: 't' } },
+ ];
+ const r = rollupWatch(watches);
+ expect(r.total).toBe(2);
+ expect(r.topChannels).toEqual([{ name: 'Chan', count: 2 }]);
+ expect(r.topTopics).toEqual([{ name: 'tech', count: 1 }]);
+ expect(r.novelty.distinct).toBe(2);
+ });
+});
+
+describe('chronotypeHistogram — timezone bucketing', () => {
+ it('buckets by LOCAL hour, not UTC', () => {
+ // 2026-07-04T02:30:00Z = 19:30 the previous day in America/Los_Angeles (-07).
+ const events = [{ kind: 'message.sent', happenedAt: '2026-07-04T02:30:00Z' }];
+ const hist = chronotypeHistogram(events, 'America/Los_Angeles');
+ expect(hist[19].messages).toBe(1);
+ expect(hist[19].total).toBe(1);
+ // Same instant in UTC lands at hour 2.
+ const utc = chronotypeHistogram(events, 'UTC');
+ expect(utc[2].messages).toBe(1);
+ });
+ it('separates categories and counts only outbound messages', () => {
+ const events = [
+ { kind: 'message.sent', happenedAt: '2026-07-04T15:00:00Z' },
+ { kind: 'message.received', happenedAt: '2026-07-04T15:00:00Z' }, // not a self-timing signal
+ { kind: 'calendar.event', happenedAt: '2026-07-04T15:00:00Z' },
+ { kind: 'media.listen', happenedAt: '2026-07-04T15:00:00Z' },
+ { kind: 'media.watch', happenedAt: '2026-07-04T15:00:00Z' },
+ ];
+ const hist = chronotypeHistogram(events, 'UTC');
+ expect(hist[15]).toMatchObject({ messages: 1, meetings: 1, media: 2 });
+ // message.received is excluded entirely (reflects others' timing, not the
+ // user's) — total is the sum of the three signal categories.
+ expect(hist[15].total).toBe(4);
+ });
+ it('handles a DST spring-forward instant without crashing', () => {
+ // 2026-03-08 09:30Z is ~01:30 local before the 02:00 PST→PDT jump.
+ const events = [{ kind: 'media.listen', happenedAt: '2026-03-08T09:30:00Z' }];
+ const hist = chronotypeHistogram(events, 'America/Los_Angeles');
+ const active = hist.filter((s) => s.total > 0);
+ expect(active).toHaveLength(1);
+ expect(active[0].media).toBe(1);
+ });
+ it('skips invalid timestamps', () => {
+ const hist = chronotypeHistogram([{ kind: 'message.sent', happenedAt: 'nonsense' }], 'UTC');
+ expect(hist.every((s) => s.total === 0)).toBe(true);
+ });
+});
+
+describe('peakHour', () => {
+ it('returns the busiest hour for a field, or null when empty', () => {
+ const hist = chronotypeHistogram([
+ { kind: 'message.sent', happenedAt: '2026-07-04T09:00:00Z' },
+ { kind: 'message.sent', happenedAt: '2026-07-04T09:30:00Z' },
+ { kind: 'message.sent', happenedAt: '2026-07-04T14:00:00Z' },
+ ], 'UTC');
+ expect(peakHour(hist, 'messages')).toBe(9);
+ expect(peakHour(hist, 'media')).toBe(null);
+ });
+});
+
+describe('classifyObservedChronotype', () => {
+ const at = (hourUtc, kind = 'media.listen') => ({ kind, happenedAt: `2026-07-04T${String(hourUtc).padStart(2, '0')}:00:00Z` });
+ it('returns null type below the minimum sample size', () => {
+ const hist = chronotypeHistogram([at(9), at(9)], 'UTC');
+ expect(classifyObservedChronotype(hist).type).toBe(null);
+ });
+ it('classifies an early cluster as morning', () => {
+ const events = [6, 7, 7, 8, 8, 9].map((h) => at(h));
+ const hist = chronotypeHistogram(events, 'UTC');
+ expect(classifyObservedChronotype(hist).type).toBe('morning');
+ });
+ it('classifies a late cluster as evening', () => {
+ const events = [18, 19, 20, 20, 21, 22].map((h) => at(h));
+ const hist = chronotypeHistogram(events, 'UTC');
+ expect(classifyObservedChronotype(hist).type).toBe('evening');
+ });
+ it('uses a circular mean so a midnight-wrapped night-owl is not averaged to noon', () => {
+ // Active 22:00–02:00 — a linear mean would land near noon (wrong); circular
+ // mean keeps the center in the late/early band, never 'morning' midday.
+ const events = [22, 23, 0, 1, 2, 23].map((h) => at(h));
+ const hist = chronotypeHistogram(events, 'UTC');
+ const { type, centerHour } = classifyObservedChronotype(hist);
+ expect(centerHour).not.toBeGreaterThan(3); // wrapped near midnight, not ~12
+ expect(type).not.toBe('intermediate');
+ });
+});
+
+describe('compareChronotype — divergence is signal, not error', () => {
+ it('agrees when both match', () => {
+ expect(compareChronotype('morning', 'morning')).toMatchObject({ agree: true, divergence: 'none' });
+ });
+ it('flags adjacent types as mild divergence', () => {
+ expect(compareChronotype('morning', 'intermediate')).toMatchObject({ agree: false, divergence: 'mild', distance: 1 });
+ });
+ it('flags morning-vs-evening as strong divergence', () => {
+ expect(compareChronotype('morning', 'evening')).toMatchObject({ agree: false, divergence: 'strong', distance: 2 });
+ });
+ it('returns unknown (never a false divergence) when a side is missing', () => {
+ expect(compareChronotype(null, 'evening')).toMatchObject({ agree: null, divergence: 'unknown' });
+ expect(compareChronotype('morning', null)).toMatchObject({ agree: null, divergence: 'unknown' });
+ });
+});
+
+describe('provenance — observed evidence supplements, never overwrites stated', () => {
+ it('observed evidence records carry source: observed and never mutate a stated object', () => {
+ // The comparison surfaces both values side by side; the stated value is
+ // passed through untouched regardless of what was observed.
+ const stated = Object.freeze({ type: 'morning' });
+ const cmp = compareChronotype(stated.type, 'evening');
+ expect(stated.type).toBe('morning'); // unchanged (frozen would throw on mutation)
+ expect(cmp.statedType).toBe('morning');
+ expect(cmp.observedType).toBe('evening');
+ });
+});
+
+describe('buildConsumptionBrief', () => {
+ it('renders numbers only — no invented interpretation', () => {
+ const taste = {
+ windows: {
+ month: {
+ days: 30,
+ listen: { total: 5, topArtists: [{ name: 'A', count: 3 }], topGenres: [], novelty: { noveltyRatio: 0.6, distinct: 3, total: 5 } },
+ watch: { total: 2, topChannels: [{ name: 'Chan', count: 2 }], topTopics: [] },
+ },
+ },
+ };
+ const chronotype = { observedType: 'evening', centerHour: 20, sampleSize: 40, peakHours: { messages: 21, media: 22, overall: 21 } };
+ const brief = buildConsumptionBrief(taste, chronotype);
+ expect(brief).toContain('A (3)');
+ expect(brief).toContain('Chan (2)');
+ expect(brief).toContain('Observed chronotype: evening');
+ expect(brief).toContain('Novelty ratio: 0.6');
+ });
+ it('is safe on empty/absent evidence', () => {
+ expect(() => buildConsumptionBrief(null, null)).not.toThrow();
+ expect(buildConsumptionBrief(null, null)).toBe('');
+ });
+});
diff --git a/server/services/twinEnrichmentScheduler.js b/server/services/twinEnrichmentScheduler.js
new file mode 100644
index 0000000000..2d087b77a2
--- /dev/null
+++ b/server/services/twinEnrichmentScheduler.js
@@ -0,0 +1,64 @@
+/**
+ * Twin Enrichment Scheduler (Human Activity Tracking Phase 7, #2156).
+ *
+ * Backstop daily rollup for the observed taste + chronotype evidence. The
+ * evidence is normally kept fresh incrementally by each media sync (Spotify /
+ * YouTube call `refreshTwinEvidenceAfterSync()` after recording events), but a
+ * machine whose media sources are idle can still accumulate message/calendar
+ * activity that shifts the chronotype histogram — so we recompute once per local
+ * day regardless.
+ *
+ * ZERO provider calls — aggregation is deterministic and LLM-free, so this runs
+ * unattended with no user consent (the AI-provider policy only gates the
+ * explicit "interpret" button, which lives on the Digital Twin UI). The issue's
+ * design explicitly sanctions running the rollup with no consent "since no
+ * provider calls," so an initial recompute at boot is fine; thereafter it
+ * recomputes once per local calendar day.
+ */
+
+import { todayInTimezone, getUserTimezone } from '../lib/timezone.js';
+import { aggregateTwinEvidence } from './twinEnrichment.js';
+
+let schedulerInterval = null;
+let running = false;
+// Local calendar day (YYYY-MM-DD) we last recomputed for. Module-level: a
+// restart re-runs at most once (cheap, idempotent) — not worth a state file.
+let lastRunDate = null;
+const CHECK_INTERVAL_MS = 60 * 60 * 1000; // hourly — a daily rollup needs no finer cadence
+
+async function checkSchedule() {
+ if (running) return;
+ const timezone = await getUserTimezone();
+ const today = todayInTimezone(timezone);
+ if (today === lastRunDate) return; // already rolled up for this local day
+
+ running = true;
+ try {
+ await aggregateTwinEvidence();
+ lastRunDate = today;
+ } finally {
+ running = false;
+ }
+}
+
+export function startTwinEnrichmentScheduler() {
+ if (schedulerInterval) {
+ console.log('🧭 Twin enrichment scheduler: already running');
+ return;
+ }
+ console.log('🧭 Twin enrichment scheduler: starting');
+ // Wrapped so an early throw (e.g. DB not ready at boot) can't crash the
+ // process — this runs outside the request lifecycle.
+ checkSchedule().catch((err) => console.error(`🧭 Twin enrichment initial rollup failed: ${err.message}`));
+ schedulerInterval = setInterval(() => {
+ checkSchedule().catch((err) => console.error(`🧭 Twin enrichment rollup check failed: ${err.message}`));
+ }, CHECK_INTERVAL_MS);
+}
+
+export function stopTwinEnrichmentScheduler() {
+ if (schedulerInterval) {
+ clearInterval(schedulerInterval);
+ schedulerInterval = null;
+ console.log('🧭 Twin enrichment scheduler: stopped');
+ }
+}
diff --git a/server/services/youtubeSync.js b/server/services/youtubeSync.js
index 0703fdd978..1a1a857ad4 100644
--- a/server/services/youtubeSync.js
+++ b/server/services/youtubeSync.js
@@ -364,6 +364,13 @@ async function doRunSync() {
return { recorded: 0, skipped: candidates.length };
});
+ // Incrementally refresh observed twin evidence when new watches landed (#2156).
+ // LLM-free + self-guarded — never blocks or fails the sync.
+ if (!persistFailed && recordResult.recorded > 0) {
+ const { refreshTwinEvidenceAfterSync } = await import('./twinEnrichment.js');
+ await refreshTwinEvidenceAfterSync();
+ }
+
const result = {
ok: !persistFailed,
status: persistFailed ? 'persist-failed' : 'ok',