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
feat: goal effectiveness scorecard — weekly time vs goals (#2157)
Adam Eivya5717e375db4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5c60928ba3..30da09b752 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,7 @@# Unreleased Changes+- **[issue-2157] Goal effectiveness scorecard — weekly time-allocation vs stated goals (Human Activity Tracking Phase 8).** The third federated output of the activity timeline: a new **Goal Scorecard** tab on the Insights page correlates where a week's tracked time/attention actually went (conversations, meetings, media from `human_activity_events`) against your stated goals (`data/digital-twin/goals.json`) — deterministically and **LLM-free**. `server/services/goalScorecard.js` maps each timeline event to goals via three deterministic, user-editable rules — keyword (goal title/tags/category tokens, stopword-filtered, matched against event text + participant names), linked-person (`goal.linkedActivities` ↔ event participant `personId`), and linked-calendar (`goal.linkedCalendars` ↔ event `subcalendarId`) — then rolls up hours aligned per goal vs unaligned time, an aligned-share trend over the last 4 weeks, and distinct-contact counts per goal (tribe touch cadence vs relationship goals). Events without a real duration get a small per-kind nominal weight so a chatty day doesn't vanish from a time-allocation view. The numeric scorecard persists as an artifact under `data/insights/goal-scorecard.json` and renders as totals cards + a per-goal breakdown + a trend sparkline; a collapsible "Mapping" editor lets you add extra keywords per goal (stored locally in `data/insights/goal-scorecard-rules.json`, never federated). Week bucketing is timezone-anchored on the same source-of-truth local-day range as the rest of the timeline (DST-correct 7-day spans, configurable Monday/Sunday start). Per the AI policy the numeric scorecard is always provider-free and computed only on an explicit user action; an **optional** plain-language narrative ("this week you said X mattered but spent 6× more time on Y") sits behind the same opt-in provider config as the Phase 6 activity digest — silent until you enable a provider and click Generate — and only annotates the deterministic artifact. When enabled, a one-line slice can also be spliced into the week-anchor day's Brain daily-log. New Zod-validated routes under `/api/insights/goal-scorecard` (`GET` cached read, `POST /compute` LLM-free, `POST /narrative` opt-in, `GET/PUT /rules`, `GET/PUT /settings`). (`server/services/goalScorecard.js`, `server/routes/insights.js`, `server/lib/validation.js`, `server/lib/navManifest.js`, `client/src/pages/Insights.jsx`, `client/src/components/insights/GoalScorecardTab.jsx`, `client/src/services/apiSystem.js`)+- **[issue-2176] Foundation-quality gate in Series Autopilot (CWQE Phase 11) — judge the world/characters/arc BEFORE drafting.** Autopilot previously verified only arc *structure* (`verifyArc`) and then drafted against a completely unscored universe and cast, so a thin magic system or a flat-Lie protagonist sailed into the expensive text stages and the editorial phase paid to detect problems that were cheap to fix up front. A new `foundationGate` step now runs after arc/episode generation + arc verify and BEFORE beat sheets: a calibrated LLM judge (`pipeline-judge-foundation`, writer/judge split off `pipeline-arc-overview` via `resolveJudgeForStage`) scores the whole foundation against a weighted rubric mirroring the Phase 10 doctrine — **worldbuilding 40%, character 30%, structure 20%, craft 10%** — naming a gap AND a fix per dimension under an anti-inflation calibration ladder. A bounded improve loop (mirrors `verifyArc`/`arcVerify`: `MAX_FOUNDATION_ROUNDS`=3, divergence guard, per-round cos-budget charge) targets the highest-leverage weakest dimension and applies the fix through the OWNING service — universe world refine (`expandWorldTemplate`→`updateUniverse`, echoing locked entries) for worldbuilding/craft, `expandUniverseCharacter` on the thinnest unlocked character for character, arc resolve (`resolveVerifyIssues`) for structure — never a raw write, `force:false` everywhere so human-locked canon is a constraint, not a fix target. The run proceeds to `beatSheet` once the weighted score clears a configurable threshold (default 7.5); on non-convergence (ran out of rounds, stopped improving, or the weakest dimension can't be auto-fixed) it pauses with the residual per-dimension findings for human review — the same failure contract as the arc/editorial gates. The judged inputs (universe canon + character records + arc) are content-hash-pinned on the snapshot, so an already-clean foundation re-reached after unrelated steps returns the cached verdict with no LLM call and can't loop. Config surface (enable flag default ON, threshold, max rounds) is per-run and persisted (`pipelineEditorialChecks`), overridable from the Autopilot Options drawer, and Zod-validated on both the settings and start-run paths. (`server/services/pipeline/foundationJudge.js`, `server/services/pipeline/seriesAutopilot.js`, `data.reference/prompts/stages/pipeline-judge-foundation.md`, `data.reference/prompts/stage-config.json`, `server/lib/pipelineValidation.js`, `server/routes/pipeline/autopilot.js`, `client/src/components/pipeline/AutopilotPanel.jsx`)- **[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`)diff --git a/client/src/components/insights/GoalScorecardTab.jsx b/client/src/components/insights/GoalScorecardTab.jsxnew file mode 100644index 0000000000..c28e82e984--- /dev/null+++ b/client/src/components/insights/GoalScorecardTab.jsx@@ -0,0 +1,312 @@+import { useState, useEffect, useCallback } from 'react';+import { RefreshCw, Target, TrendingUp, TrendingDown, Minus, Sparkles, SlidersHorizontal, Users } from 'lucide-react';+import {+ getGoalScorecard,+ computeGoalScorecard,+ refreshGoalScorecardNarrative,+ getGoalScorecardRules,+ saveGoalScorecardRules,+ getGoalScorecardSettings,+} from '../../services/api';+import { timeAgo } from '../../utils/formatters';++const fmtHours = (h) => `${Number(h ?? 0).toFixed(1)}h`;++function TrendIcon({ direction }) {+ if (direction === 'up') return <TrendingUp size={16} className="text-port-success" />;+ if (direction === 'down') return <TrendingDown size={16} className="text-port-error" />;+ return <Minus size={16} className="text-gray-500" />;+}++// A tiny aligned-share sparkline over the trend weeks.+function TrendSparkline({ trend }) {+ const weeks = Array.isArray(trend) ? trend : [];+ if (weeks.length === 0) return null;+ return (+ <div className="flex items-end gap-1 h-12" aria-hidden="true">+ {weeks.map((w) => {+ const pct = Math.round((w.alignedShare ?? 0) * 100);+ return (+ <div key={w.weekStart} className="flex flex-col items-center gap-1 flex-1">+ <div+ className="w-full bg-port-accent/70 rounded-t"+ style={{ height: `${Math.max(4, pct)}%` }}+ title={`${w.weekStart}: ${pct}% aligned`}+ />+ </div>+ );+ })}+ </div>+ );+}++function RulesEditor({ onClose }) {+ const [data, setData] = useState(null);+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [drafts, setDrafts] = useState({});++ useEffect(() => {+ getGoalScorecardRules().then((res) => {+ setData(res);+ const initial = {};+ for (const [id, ov] of Object.entries(res?.overrides ?? {})) {+ initial[id] = (ov.keywords ?? []).join(', ');+ }+ setDrafts(initial);+ }).finally(() => setLoading(false));+ }, []);++ const handleSave = () => {+ setSaving(true);+ const overrides = { ...(data?.overrides ?? {}) };+ for (const [id, csv] of Object.entries(drafts)) {+ const keywords = csv.split(',').map((k) => k.trim()).filter(Boolean);+ overrides[id] = { ...(overrides[id] ?? {}), keywords };+ }+ saveGoalScorecardRules(overrides)+ .then((res) => { setData(res); onClose?.(); })+ .finally(() => setSaving(false));+ };++ if (loading) return <div className="text-sm text-gray-500 p-4">Loading mapping rules…</div>;++ const rules = data?.rules ?? [];+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="flex items-center justify-between">+ <h3 className="text-sm font-semibold text-white">Goal → activity mapping</h3>+ <button onClick={onClose} className="text-xs text-gray-500 hover:text-white">Close</button>+ </div>+ <p className="text-xs text-gray-500">+ Activities map to a goal when a keyword appears in the event, a linked person participates, or a linked calendar matches.+ Add extra keywords (comma-separated) to catch more of a goal's activity.+ </p>+ <div className="space-y-3 max-h-80 overflow-y-auto pr-1">+ {rules.length === 0 && <p className="text-xs text-gray-500">No active goals found.</p>}+ {rules.map((rule) => (+ <div key={rule.id} className="border-b border-port-border/60 pb-2 last:border-0">+ <div className="flex items-center gap-2 mb-1">+ <span className="text-sm text-white">{rule.title}</span>+ {rule.category && <span className="text-[10px] text-gray-600 bg-gray-800 px-1.5 py-0.5 rounded">{rule.category}</span>}+ </div>+ <div className="text-[11px] text-gray-500 mb-1">+ Auto keywords: {rule.keywords.length ? rule.keywords.join(', ') : '(none)'}+ </div>+ <input+ type="text"+ value={drafts[rule.id] ?? ''}+ onChange={(e) => setDrafts((prev) => ({ ...prev, [rule.id]: e.target.value }))}+ placeholder="extra keywords, comma-separated"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-200 focus:border-port-accent/60 focus:outline-none"+ />+ </div>+ ))}+ </div>+ <button+ onClick={handleSave}+ disabled={saving}+ className="px-3 py-1.5 bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 disabled:opacity-50 transition-colors"+ >+ {saving ? 'Saving…' : 'Save keywords'}+ </button>+ </div>+ );+}++export default function GoalScorecardTab() {+ const [data, setData] = useState(null);+ const [settings, setSettings] = useState(null);+ const [loading, setLoading] = useState(true);+ const [computing, setComputing] = useState(false);+ const [generating, setGenerating] = useState(false);+ const [showRules, setShowRules] = useState(false);++ const load = useCallback(() => {+ Promise.allSettled([getGoalScorecard(), getGoalScorecardSettings()])+ .then(([sc, st]) => {+ setData(sc.status === 'fulfilled' ? sc.value : null);+ setSettings(st.status === 'fulfilled' ? st.value : null);+ })+ .finally(() => setLoading(false));+ }, []);++ useEffect(() => { load(); }, [load]);++ const handleCompute = () => {+ setComputing(true);+ computeGoalScorecard()+ .then((res) => setData(res))+ .finally(() => setComputing(false));+ };++ const handleNarrative = () => {+ setGenerating(true);+ refreshGoalScorecardNarrative()+ .then((res) => { if (res?.available) setData(res); })+ .finally(() => setGenerating(false));+ };++ if (loading) {+ return (+ <div className="animate-pulse space-y-3">+ <div className="h-5 bg-gray-800 rounded w-1/3 mb-4" />+ <div className="h-24 bg-gray-800 rounded w-full" />+ <div className="h-4 bg-gray-700 rounded w-full" />+ <div className="h-4 bg-gray-700 rounded w-5/6" />+ </div>+ );+ }++ if (!data?.available) {+ return (+ <div className="flex flex-col items-center justify-center py-16 text-center">+ <Target size={28} className="text-gray-600 mb-3" />+ <p className="text-gray-400 text-sm max-w-sm mb-2">No goal scorecard computed yet.</p>+ <p className="text-gray-500 text-xs max-w-sm mb-6">+ Compute a weekly scorecard correlating where your tracked time actually went — conversations, meetings, media —+ against your stated goals. Deterministic and fully local; no AI required.+ </p>+ <button+ onClick={handleCompute}+ disabled={computing}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 disabled:opacity-50 transition-colors"+ >+ <RefreshCw size={16} className={computing ? 'animate-spin' : ''} />+ {computing ? 'Computing…' : 'Compute this week'}+ </button>+ </div>+ );+ }++ const { totals, goals = [], trend = [], trendDirection } = data;+ const alignedPct = Math.round((totals?.alignedShare ?? 0) * 100);+ const narrativeEnabled = Boolean(settings?.enabled && settings?.provider);+ const topGoalHours = goals.find((g) => g.alignedSeconds > 0)?.alignedHours ?? 0;++ return (+ <div className="space-y-4">+ {/* Header */}+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex items-center gap-3">+ <span className="text-sm text-white font-semibold">Week of {data.weekStart}</span>+ {data.generatedAt && <span className="text-xs text-gray-500">computed {timeAgo(data.generatedAt)}</span>}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => setShowRules((v) => !v)}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-card border border-port-border rounded-lg text-sm text-gray-400 hover:text-white hover:border-port-accent/50 transition-colors"+ >+ <SlidersHorizontal size={14} />+ Mapping+ </button>+ <button+ onClick={handleCompute}+ disabled={computing}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-card border border-port-border rounded-lg text-sm text-gray-400 hover:text-white hover:border-port-accent/50 disabled:opacity-50 transition-colors"+ >+ <RefreshCw size={14} className={computing ? 'animate-spin' : ''} />+ {computing ? 'Computing…' : 'Recompute'}+ </button>+ </div>+ </div>++ {showRules && <RulesEditor onClose={() => setShowRules(false)} />}++ {/* Totals cards */}+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="text-xs text-gray-500 mb-1">Goal-aligned time</div>+ <div className="text-2xl font-bold text-port-success">{fmtHours(totals?.alignedHours)}</div>+ <div className="text-xs text-gray-600 mt-1">{alignedPct}% of tracked time</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="text-xs text-gray-500 mb-1">Unaligned time</div>+ <div className="text-2xl font-bold text-port-warning">{fmtHours(totals?.unalignedHours)}</div>+ <div className="text-xs text-gray-600 mt-1">{totals?.eventCount ?? 0} events tracked</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between mb-1">+ <span className="text-xs text-gray-500">Trend vs prior weeks</span>+ <TrendIcon direction={trendDirection} />+ </div>+ <TrendSparkline trend={trend} />+ </div>+ </div>++ {/* Aligned vs unaligned bar */}+ {totals?.totalSeconds > 0 && (+ <div className="w-full h-2 rounded-full overflow-hidden bg-port-warning/40 flex">+ <div className="h-full bg-port-success" style={{ width: `${alignedPct}%` }} title={`${alignedPct}% aligned`} />+ </div>+ )}++ {/* Per-goal breakdown */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-sm font-semibold text-white mb-3">Time by goal</h3>+ {goals.filter((g) => g.alignedSeconds > 0).length === 0 ? (+ <p className="text-xs text-gray-500">No tracked activity mapped to a goal this week. Add keywords under “Mapping” to catch more.</p>+ ) : (+ <div className="space-y-3">+ {goals.filter((g) => g.alignedSeconds > 0).map((g) => (+ <div key={g.id}>+ <div className="flex items-center justify-between text-sm mb-1">+ <div className="flex items-center gap-2 min-w-0">+ <span className="text-gray-200 truncate">{g.title}</span>+ {g.category && <span className="text-[10px] text-gray-600 bg-gray-800 px-1.5 py-0.5 rounded shrink-0">{g.category}</span>}+ </div>+ <div className="flex items-center gap-3 shrink-0 text-xs">+ {g.contactCount > 0 && (+ <span className="flex items-center gap-1 text-gray-500" title={`${g.contactCount} distinct contacts`}>+ <Users size={12} />{g.contactCount}+ </span>+ )}+ <span className="text-gray-300 tabular-nums">{fmtHours(g.alignedHours)}</span>+ </div>+ </div>+ <div className="w-full h-1.5 rounded-full bg-port-bg overflow-hidden">+ <div+ className="h-full bg-port-accent"+ style={{ width: `${topGoalHours > 0 ? Math.round((g.alignedHours / topGoalHours) * 100) : 0}%` }}+ />+ </div>+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Optional LLM narrative */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between mb-2">+ <h3 className="text-sm font-semibold text-white flex items-center gap-2"><Sparkles size={14} className="text-port-accent" /> Narrative</h3>+ <button+ onClick={handleNarrative}+ disabled={generating || !narrativeEnabled || totals?.totalSeconds === 0}+ title={narrativeEnabled ? '' : 'Enable a provider in scorecard settings to generate a narrative'}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 disabled:opacity-50 transition-colors"+ >+ <RefreshCw size={14} className={generating ? 'animate-spin' : ''} />+ {generating ? 'Generating…' : data.narrative ? 'Regenerate' : 'Generate'}+ </button>+ </div>+ {data.narrative ? (+ <div className="prose prose-sm prose-invert max-w-none">+ {data.narrative.split('\n').filter(Boolean).map((p, i) => (+ <p key={i} className="text-gray-300 leading-relaxed mb-2 last:mb-0">{p}</p>+ ))}+ {data.narrativeGeneratedAt && (+ <p className="text-[11px] text-gray-600 mt-2">Generated {timeAgo(data.narrativeGeneratedAt)}{data.narrativeModel ? ` · ${data.narrativeModel}` : ''}</p>+ )}+ </div>+ ) : (+ <p className="text-xs text-gray-500">+ {narrativeEnabled+ ? 'Generate an optional plain-language summary of this week’s goal alignment. The numeric scorecard above is always AI-free.'+ : 'Optional AI narrative is off. Enable a provider in scorecard settings to summarize the week in plain language. The numeric scorecard is always AI-free.'}+ </p>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/pages/Insights.jsx b/client/src/pages/Insights.jsxindex 03f2965bd9..5bfb7324a7 100644--- a/client/src/pages/Insights.jsx+++ b/client/src/pages/Insights.jsx@@ -1,7 +1,7 @@import { useState, useEffect } from 'react';import { useNavigate } from 'react-router-dom';import { useValidTab } from '../hooks/useValidTab';-import { Dna, Palette, Link2, Lightbulb, ArrowRight } from 'lucide-react';+import { Dna, Palette, Link2, Lightbulb, ArrowRight, Target } from 'lucide-react';import {getGenomeHealthCorrelations,getInsightThemes,@@ -10,6 +10,7 @@ import {import GenomeHealthTab from '../components/insights/GenomeHealthTab';import TasteIdentityTab from '../components/insights/TasteIdentityTab';import CrossDomainTab from '../components/insights/CrossDomainTab';+import GoalScorecardTab from '../components/insights/GoalScorecardTab';import ConfidenceBadge from '../components/insights/ConfidenceBadge';import PageHeader from '../components/PageHeader';import TabPills from '../components/ui/TabPills';@@ -20,7 +21,8 @@ export 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 }+ { id: 'cross-domain', label: 'Cross-Domain Patterns', icon: Link2 },+ { id: 'goal-scorecard', label: 'Goal Scorecard', icon: Target }];function SummaryCardSkeleton() {@@ -191,6 +193,8 @@ export default function Insights() {return <TasteIdentityTab />;case 'cross-domain':return <CrossDomainTab />;+ case 'goal-scorecard':+ return <GoalScorecardTab />;default:return <OverviewTab />;}diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 7dc74e036c..34a63e5446 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -315,6 +315,27 @@ export const refreshInsightNarrative = (providerId, model) => request('/insightsbody: JSON.stringify({ providerId, model })});+// Goal effectiveness scorecard (#2157)+export const getGoalScorecard = () => request('/insights/goal-scorecard');+export const computeGoalScorecard = (weekStart) => request('/insights/goal-scorecard/compute', {+ method: 'POST',+ body: JSON.stringify(weekStart ? { weekStart } : {})+});+export const refreshGoalScorecardNarrative = (providerId, model) => request('/insights/goal-scorecard/narrative', {+ method: 'POST',+ body: JSON.stringify({ providerId, model })+});+export const getGoalScorecardRules = () => request('/insights/goal-scorecard/rules');+export const saveGoalScorecardRules = (overrides) => request('/insights/goal-scorecard/rules', {+ method: 'PUT',+ body: JSON.stringify(overrides ?? {})+});+export const getGoalScorecardSettings = () => request('/insights/goal-scorecard/settings');+export const updateGoalScorecardSettings = (partial) => request('/insights/goal-scorecard/settings', {+ method: 'PUT',+ body: JSON.stringify(partial ?? {})+});+// Media - Server media devicesexport const getMediaDevices = () => request('/media/devices');export const getMediaStatus = () => request('/media/status');diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex f529830475..a66d976228 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -62,6 +62,7 @@ export const NAV_COMMANDS = [{ id: 'nav.insights.genome-health', path: '/insights/genome-health', label: 'Genome-Health', section: 'Brain', aliases: ['genome-health', 'insights-genome-health'], keywords: ['genome', 'dna', 'health', 'longevity', 'genetic'] },{ id: 'nav.insights.taste-identity', path: '/insights/taste-identity', label: 'Taste & Identity', section: 'Brain', aliases: ['taste-identity', 'insights-taste-identity'], keywords: ['taste', 'identity', 'preferences', 'aesthetic'] },{ id: 'nav.insights.cross-domain', path: '/insights/cross-domain', label: 'Cross-Domain Patterns', section: 'Brain', aliases: ['cross-domain', 'insights-cross-domain', 'cross-domain-patterns'], keywords: ['cross domain', 'patterns', 'correlations', 'connections'] },+ { id: 'nav.insights.goal-scorecard', path: '/insights/goal-scorecard', label: 'Goal Scorecard', section: 'Brain', aliases: ['goal-scorecard', 'insights-goal-scorecard', 'scorecard'], keywords: ['goal', 'scorecard', 'time allocation', 'effectiveness', 'goal alignment', 'time vs goals'] },{ id: 'nav.brain.links', path: '/brain/links', label: 'Links', section: 'Brain', aliases: ['brain-links'] },{ id: 'nav.brain.memory', path: '/brain/memory', label: 'Memory', section: 'Brain', aliases: ['brain-memory', 'memory'] },{ id: 'nav.brain.notes', path: '/brain/notes', label: 'Notes', section: 'Brain', aliases: ['brain-notes', 'notes'] },diff --git a/server/lib/validation.js b/server/lib/validation.jsindex ba6b9c9e06..50a5c51a93 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -324,6 +324,28 @@ export const insightRefreshSchema = z.object({model: z.string().optional()});+// Goal effectiveness scorecard (#2157).+export const scorecardComputeSchema = z.object({+ weekStart: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional()+});++export const scorecardSettingsSchema = z.object({+ enabled: z.boolean().optional(),+ provider: z.string().nullable().optional(),+ model: z.string().nullable().optional(),+ feedBrainDigest: z.boolean().optional(),+ weekStartsOn: z.number().int().min(1).max(7).optional()+});++// Per-goal mapping overrides: { [goalId]: { keywords?, personIds?, subcalendarIds?, enabled? } }.+const scorecardRuleOverrideSchema = z.object({+ keywords: z.array(z.string()).optional(),+ personIds: z.array(z.string()).optional(),+ subcalendarIds: z.array(z.string()).optional(),+ enabled: z.boolean().optional()+});+export const scorecardRulesSchema = z.record(z.string(), scorecardRuleOverrideSchema);+// =============================================================================// SEARCH SCHEMAS// =============================================================================diff --git a/server/routes/insights.js b/server/routes/insights.jsindex ec67e075b2..95099610f7 100644--- a/server/routes/insights.js+++ b/server/routes/insights.js@@ -7,12 +7,28 @@* POST /api/insights/themes/refresh — (re)generate taste-identity themes via LLM* GET /api/insights/narrative — cached cross-domain narrative* POST /api/insights/narrative/refresh — (re)generate narrative via LLM+ *+ * Goal effectiveness scorecard (#2157 — Human Activity Tracking Phase 8):+ * GET /api/insights/goal-scorecard — cached weekly scorecard (disk-only)+ * POST /api/insights/goal-scorecard/compute — recompute (deterministic, LLM-free)+ * POST /api/insights/goal-scorecard/narrative— optional LLM narrative (user-triggered)+ * GET /api/insights/goal-scorecard/rules — effective goal→activity mapping rules+ * PUT /api/insights/goal-scorecard/rules — save per-goal mapping overrides+ * GET /api/insights/goal-scorecard/settings — scorecard settings (opt-in narrative)+ * PUT /api/insights/goal-scorecard/settings — update scorecard settings*/import { Router } from 'express';import { asyncHandler } from '../lib/errorHandler.js';-import { validateRequest, insightRefreshSchema } from '../lib/validation.js';+import {+ validateRequest,+ insightRefreshSchema,+ scorecardComputeSchema,+ scorecardSettingsSchema,+ scorecardRulesSchema,+} from '../lib/validation.js';import * as insightsService from '../services/insightsService.js';+import * as goalScorecard from '../services/goalScorecard.js';const router = Router();@@ -48,4 +64,46 @@ router.post('/narrative/refresh', asyncHandler(async (req, res) => {res.json(result);}));+// ─── Goal effectiveness scorecard (#2157) ────────────────────────────────────++// GET /api/insights/goal-scorecard — cached weekly scorecard (disk-only read).+router.get('/goal-scorecard', asyncHandler(async (_req, res) => {+ res.json(await goalScorecard.getScorecard());+}));++// POST /api/insights/goal-scorecard/compute — recompute (deterministic, LLM-free).+router.post('/goal-scorecard/compute', asyncHandler(async (req, res) => {+ const { weekStart } = validateRequest(scorecardComputeSchema, req.body ?? {});+ res.json(await goalScorecard.computeWeeklyScorecard({ weekStart }));+}));++// POST /api/insights/goal-scorecard/narrative — optional LLM narrative (user-triggered).+router.post('/goal-scorecard/narrative', asyncHandler(async (req, res) => {+ const { providerId, model } = validateRequest(insightRefreshSchema, req.body ?? {});+ res.json(await goalScorecard.refreshScorecardNarrative(providerId, model));+}));++// GET /api/insights/goal-scorecard/rules — effective goal→activity mapping rules.+router.get('/goal-scorecard/rules', asyncHandler(async (_req, res) => {+ res.json(await goalScorecard.getEffectiveRules());+}));++// PUT /api/insights/goal-scorecard/rules — save per-goal mapping overrides.+router.put('/goal-scorecard/rules', asyncHandler(async (req, res) => {+ const overrides = validateRequest(scorecardRulesSchema, req.body ?? {});+ await goalScorecard.saveRuleOverrides(overrides);+ res.json(await goalScorecard.getEffectiveRules());+}));++// GET /api/insights/goal-scorecard/settings — scorecard settings.+router.get('/goal-scorecard/settings', asyncHandler(async (_req, res) => {+ res.json(await goalScorecard.getSettings());+}));++// PUT /api/insights/goal-scorecard/settings — update scorecard settings.+router.put('/goal-scorecard/settings', asyncHandler(async (req, res) => {+ const partial = validateRequest(scorecardSettingsSchema, req.body ?? {});+ res.json(await goalScorecard.updateSettings(partial));+}));+export default router;diff --git a/server/services/goalScorecard.js b/server/services/goalScorecard.jsnew file mode 100644index 0000000000..983554a0b8--- /dev/null+++ b/server/services/goalScorecard.js@@ -0,0 +1,551 @@+/**+ * Goal Effectiveness Scorecard — weekly time-allocation vs stated goals+ * (Human Activity Tracking Phase 8, #2157).+ *+ * Correlates where a week's tracked time/attention actually went (the Human+ * Activity timeline — conversations, meetings, media) against the user's stated+ * goals (`data/digital-twin/goals.json`) and produces a weekly scorecard:+ *+ * - Hours aligned to each goal vs unaligned time.+ * - Trend vs prior weeks (aligned share over the last N weeks).+ * - Contact-vs-goal alignment (distinct people touched per goal — e.g. tribe+ * touch cadence against relationship goals).+ *+ * Two layers, matching the Phase 6 activity-digest split:+ * 1. **Numeric scorecard — always LLM-free, deterministic.** Events map to+ * goals via keyword / participant / calendar rules (user-editable, stored+ * locally). The rollup is pure arithmetic. This is the artifact rendered on+ * the Insights page.+ * 2. **Optional LLM narrative (opt-in).** "This week you said X mattered but+ * spent 6× more time on Y." Behind the same provider config as the activity+ * digest (#2155) — silent until the user configures a provider AND clicks+ * Refresh. See CLAUDE.md "AI Provider Usage Policy".+ *+ * The scorecard artifact lives under `data/insights/` alongside the cross-domain+ * insights caches. All reads are disk-only; compute is an explicit user action.+ */++import { join } from 'path';+import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';+import { localDayRangeUtc, localDayKey, listEvents } from './humanActivity.js';+import * as journal from './brainJournal.js';+import { buildMarkers } from '../lib/markedSection.js';+import { getProviderById } from './providers.js';+import { runPromptThroughProvider } from '../lib/promptRunner.js';++const GOALS_FILE = join(PATHS.digitalTwin, 'goals.json');+const INSIGHTS_DIR = join(PATHS.data, 'insights');+const SCORECARD_FILE = join(INSIGHTS_DIR, 'goal-scorecard.json');+const RULES_FILE = join(INSIGHTS_DIR, 'goal-scorecard-rules.json');+const SETTINGS_FILE = join(INSIGHTS_DIR, 'goal-scorecard-settings.json');++// Marker pair for the one-line slice spliced into the week-anchor day's Brain+// daily-log entry (checkbox 4 — feed a slice into the digest).+export const SCORECARD_DIGEST_MARKERS = buildMarkers('goal-scorecard');++// How many weeks (including the current one) the trend series spans.+export const TREND_WEEKS = 4;++// Deterministic time-allocation proxy per event kind. The timeline stores real+// durations for calendar/media events; conversations are point-in-time, so a+// small nominal cost keeps them from vanishing from a time-allocation view+// without letting a chatty day dwarf an all-day meeting.+export const NOMINAL_SECONDS = {+ 'message.sent': 120,+ 'message.received': 60,+ 'calendar.event': 1800,+ 'media.listen': 180,+ 'media.watch': 600,+ default: 300,+};++const DEFAULT_SETTINGS = {+ // Opt-in for the LLM narrative + scheduled/digest side effects. When false the+ // numeric scorecard still computes on demand (it is LLM-free); only the+ // narrative and the Brain digest slice stay silent.+ enabled: false,+ // Provider/model for the optional narrative. null → numeric scorecard only.+ provider: null,+ model: null,+ // When true (and enabled), computing a scorecard also splices a one-line slice+ // into the week-anchor day's Brain daily-log entry.+ feedBrainDigest: false,+ // ISO day the week starts on (1 = Monday, per ISO-8601).+ weekStartsOn: 1,+};++const CLIENT_SETTABLE = ['enabled', 'provider', 'model', 'feedBrainDigest', 'weekStartsOn'];++// Tokens too generic to be useful goal keywords.+const STOPWORDS = new Set([+ 'the', 'and', 'for', 'with', 'from', 'that', 'this', 'have', 'make', 'made',+ 'your', 'you', 'get', 'got', 'more', 'less', 'into', 'onto', 'over', 'been',+ 'about', 'goal', 'goals', 'real', 'another', 'again', 'keep', 'stay', 'remain',+ 'long', 'possible', 'first', 'finish', 'create', 'creating', 'build', 'buy',+]);++// ─── Pure helpers (exported for unit tests — no I/O) ─────────────────────────++const isoRe = /^\d{4}-\d{2}-\d{2}$/;+const isIso = (d) => typeof d === 'string' && isoRe.test(d);++// Shift a YYYY-MM-DD calendar date by N days (UTC math — a calendar day is not+// an instant, so DST doesn't apply). Returns YYYY-MM-DD.+export function shiftIsoDate(date, days) {+ const [y, m, d] = String(date).split('-').map(Number);+ const dt = new Date(Date.UTC(y, m - 1, d));+ dt.setUTCDate(dt.getUTCDate() + days);+ return dt.toISOString().slice(0, 10);+}++// The calendar date (YYYY-MM-DD) of the start of the week containing `dateStr`.+// `weekStartsOn` uses ISO day numbers (1 = Monday … 7 = Sunday); default Monday.+// Operates on the calendar date only, so it is timezone-agnostic.+export function isoWeekStart(dateStr, weekStartsOn = 1) {+ if (!isIso(dateStr)) return null;+ const [y, m, d] = dateStr.split('-').map(Number);+ const dow = new Date(Date.UTC(y, m - 1, d)).getUTCDay(); // 0=Sun … 6=Sat+ const isoDow = dow === 0 ? 7 : dow; // 1=Mon … 7=Sun+ const start = ((weekStartsOn - 1 + 7) % 7);+ const offset = (isoDow - 1 - start + 7) % 7;+ return shiftIsoDate(dateStr, -offset);+}++// UTC [start, end) instants bounding a local week that begins on `weekStartIso`.+// Anchors on the source-of-truth local-day range so DST transitions inside the+// week keep their true length (end is the NEXT week's local midnight, not +7×24h).+export function weekRangeUtc(weekStartIso, timezone) {+ const startRange = localDayRangeUtc(weekStartIso, timezone);+ if (!startRange) return null;+ const endRange = localDayRangeUtc(shiftIsoDate(weekStartIso, 7), timezone);+ return { start: startRange.start, end: endRange.start };+}++// Extract lowercase keyword tokens from a goal's title/tags/category. Tags and+// category pass through verbatim (already meaningful); title words are split,+// length-filtered, and stopword-filtered so a title like "Buy Estate Property"+// yields ["estate", "property"], not ["buy"].+export function goalKeywords(goal) {+ const words = String(goal?.title || '')+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter((w) => w.length >= 4 && !STOPWORDS.has(w));+ const tags = Array.isArray(goal?.tags)+ ? goal.tags.map((t) => String(t).toLowerCase().trim()).filter(Boolean)+ : [];+ const category = goal?.category ? [String(goal.category).toLowerCase()] : [];+ return Array.from(new Set([...words, ...tags, ...category]));+}++// Build the deterministic goal→match ruleset. Each active goal gets a rule with+// derived keywords plus any explicitly-linked personIds / calendar ids. A+// per-goal override (keyed by goal id) can add keywords, replace personIds /+// subcalendarIds, or disable the goal from the scorecard entirely.+export function buildMappingRules(goals = [], overrides = {}) {+ const rules = [];+ for (const goal of goals || []) {+ if (!goal?.id) continue;+ if (goal.status && goal.status !== 'active') continue;+ const override = overrides[goal.id] || {};+ if (override.enabled === false) continue;+ const keywords = Array.from(new Set([+ ...goalKeywords(goal),+ ...((Array.isArray(override.keywords) ? override.keywords : []).map((k) => String(k).toLowerCase().trim()).filter(Boolean)),+ ]));+ rules.push({+ id: goal.id,+ title: goal.title || '(untitled goal)',+ category: goal.category || null,+ keywords,+ personIds: Array.isArray(override.personIds) ? override.personIds.map(String)+ : (Array.isArray(goal.linkedActivities) ? goal.linkedActivities.map(String) : []),+ subcalendarIds: Array.isArray(override.subcalendarIds) ? override.subcalendarIds.map(String)+ : (Array.isArray(goal.linkedCalendars) ? goal.linkedCalendars.map(String) : []),+ });+ }+ return rules;+}++// The searchable text of an event (title + summary + participant names), lowercased.+function eventText(event) {+ const parts = [event?.title, event?.summary];+ for (const p of event?.participants || []) {+ if (p?.name) parts.push(p.name);+ }+ return parts.filter(Boolean).join(' ').toLowerCase();+}++// The goal ids a single event maps to. An event aligns to a goal when ANY of:+// - a goal keyword appears in the event's text (title/summary/participant name)+// - an event participant's personId is in the goal's linked personIds+// - the event's calendar subcalendarId is in the goal's linked calendars+// Returns a de-duplicated array of goal ids (possibly empty = unaligned).+export function eventGoalMatches(event, rules = []) {+ if (!event) return [];+ const text = eventText(event);+ const personIds = new Set((event.participants || []).map((p) => p?.personId).filter(Boolean).map(String));+ const subcal = event?.metadata?.subcalendarId != null ? String(event.metadata.subcalendarId) : null;+ const matched = [];+ for (const rule of rules) {+ const byKeyword = rule.keywords.some((k) => k && text.includes(k));+ const byPerson = rule.personIds.some((id) => personIds.has(String(id)));+ const byCalendar = subcal != null && rule.subcalendarIds.some((id) => String(id) === subcal);+ if (byKeyword || byPerson || byCalendar) matched.push(rule.id);+ }+ return Array.from(new Set(matched));+}++// Deterministic time-allocation weight (seconds) for an event: its real duration+// when present, otherwise the per-kind nominal proxy.+export function eventSeconds(event, nominal = NOMINAL_SECONDS) {+ const d = Number(event?.durationS);+ if (Number.isFinite(d) && d > 0) return Math.round(d);+ return nominal[event?.kind] ?? nominal.default;+}++// Bucket events into local weeks. Returns a Map of weekStartIso → events[].+// Events with an unparseable timestamp are dropped.+export function bucketEventsByWeek(events = [], timezone, weekStartsOn = 1) {+ const buckets = new Map();+ for (const ev of events || []) {+ const day = localDayKey(ev.happenedAt ?? ev.happened_at, timezone);+ if (!day) continue;+ const wk = isoWeekStart(day, weekStartsOn);+ if (!wk) continue;+ if (!buckets.has(wk)) buckets.set(wk, []);+ buckets.get(wk).push(ev);+ }+ return buckets;+}++// Lightweight aligned/unaligned/total seconds for a set of events — the unit the+// trend series is built from (no per-goal breakdown).+export function weekTotals(events = [], rules = [], nominal = NOMINAL_SECONDS) {+ let aligned = 0;+ let unaligned = 0;+ for (const ev of events || []) {+ const seconds = eventSeconds(ev, nominal);+ if (eventGoalMatches(ev, rules).length > 0) aligned += seconds;+ else unaligned += seconds;+ }+ return { alignedSeconds: aligned, unalignedSeconds: unaligned, totalSeconds: aligned + unaligned, eventCount: (events || []).length };+}++const secondsToHours = (s) => Math.round((s / 3600) * 100) / 100;++// A distinct-person key for contact-cadence counting: prefer personId, then+// email, then phone, then name. Returns null when the participant is anonymous.+function contactKey(p) {+ if (!p) return null;+ return p.personId ? `id:${p.personId}` : p.email ? `email:${p.email}` : p.phone ? `phone:${p.phone}` : p.name ? `name:${p.name}` : null;+}++/**+ * Compute the detailed single-week scorecard. Pure — the caller supplies just+ * that week's events plus the prior-week totals for the trend series.+ *+ * @param {object} args+ * @param {string} args.weekStart — YYYY-MM-DD (the local week's first day)+ * @param {object[]} args.events — timeline events for that week only+ * @param {object[]} args.rules — output of buildMappingRules()+ * @param {string} [args.timezone]+ * @param {Array<{weekStart,alignedSeconds,unalignedSeconds,totalSeconds}>} [args.trend]+ * — ascending prior→current weekly totals (current week last).+ * @param {object} [args.nominal]+ */+export function computeScorecard({ weekStart, events = [], rules = [], timezone = null, trend = [], nominal = NOMINAL_SECONDS }) {+ const perGoal = new Map(rules.map((r) => [r.id, {+ id: r.id, title: r.title, category: r.category,+ alignedSeconds: 0, eventCount: 0, contacts: new Set(),+ }]));++ let alignedSeconds = 0;+ let unalignedSeconds = 0;+ for (const ev of events || []) {+ const seconds = eventSeconds(ev, nominal);+ const matches = eventGoalMatches(ev, rules);+ if (matches.length === 0) {+ unalignedSeconds += seconds;+ continue;+ }+ alignedSeconds += seconds;+ for (const goalId of matches) {+ const g = perGoal.get(goalId);+ if (!g) continue;+ g.alignedSeconds += seconds;+ g.eventCount += 1;+ for (const p of ev.participants || []) {+ const key = contactKey(p);+ if (key) g.contacts.add(key);+ }+ }+ }++ const totalSeconds = alignedSeconds + unalignedSeconds;+ const goals = Array.from(perGoal.values())+ .map((g) => ({+ id: g.id,+ title: g.title,+ category: g.category,+ alignedSeconds: g.alignedSeconds,+ alignedHours: secondsToHours(g.alignedSeconds),+ eventCount: g.eventCount,+ contactCount: g.contacts.size,+ // Share of ALIGNED time this goal claims (goals can overlap on one event,+ // so goal shares need not sum to 1 — this ranks focus, not a partition).+ share: alignedSeconds > 0 ? Math.round((g.alignedSeconds / alignedSeconds) * 1000) / 1000 : 0,+ }))+ .sort((a, b) => b.alignedSeconds - a.alignedSeconds);++ // Trend direction: this week's aligned SHARE of total vs the mean aligned+ // share of the prior weeks in the series.+ const priorWeeks = trend.slice(0, -1);+ const priorShares = priorWeeks+ .filter((w) => w.totalSeconds > 0)+ .map((w) => w.alignedSeconds / w.totalSeconds);+ const currentShare = totalSeconds > 0 ? alignedSeconds / totalSeconds : 0;+ const priorMean = priorShares.length ? priorShares.reduce((a, b) => a + b, 0) / priorShares.length : null;+ let direction = 'flat';+ if (priorMean != null) {+ if (currentShare > priorMean + 0.05) direction = 'up';+ else if (currentShare < priorMean - 0.05) direction = 'down';+ }++ return {+ weekStart,+ timezone,+ generatedAt: new Date().toISOString(),+ totals: {+ alignedSeconds,+ unalignedSeconds,+ totalSeconds,+ alignedHours: secondsToHours(alignedSeconds),+ unalignedHours: secondsToHours(unalignedSeconds),+ alignedShare: totalSeconds > 0 ? Math.round(currentShare * 1000) / 1000 : 0,+ eventCount: (events || []).length,+ },+ goals,+ trend: trend.map((w) => ({+ weekStart: w.weekStart,+ alignedSeconds: w.alignedSeconds,+ unalignedSeconds: w.unalignedSeconds,+ alignedShare: w.totalSeconds > 0 ? Math.round((w.alignedSeconds / w.totalSeconds) * 1000) / 1000 : 0,+ })),+ trendDirection: direction,+ narrative: null,+ narrativeGeneratedAt: null,+ };+}++// One-line digest slice for the Brain daily/weekly log. Pure — LLM-free.+export function formatScorecardDigestLine(scorecard) {+ if (!scorecard?.totals || scorecard.totals.totalSeconds === 0) return null;+ const { alignedHours, unalignedHours, alignedShare } = scorecard.totals;+ const top = scorecard.goals?.find((g) => g.alignedSeconds > 0);+ const topPart = top ? ` Most-aligned: ${top.title} (${top.alignedHours}h).` : '';+ const pct = Math.round((alignedShare || 0) * 100);+ return `**Goal scorecard (week of ${scorecard.weekStart})** — ${alignedHours}h aligned to goals vs ${unalignedHours}h unaligned (${pct}% goal-aligned).${topPart}`;+}++// ─── Settings / rules I/O ────────────────────────────────────────────────────++export async function getSettings() {+ await ensureDir(INSIGHTS_DIR);+ const loaded = await readJSONFile(SETTINGS_FILE, null);+ return loaded ? { ...DEFAULT_SETTINGS, ...loaded } : { ...DEFAULT_SETTINGS };+}++export async function updateSettings(partial = {}) {+ const current = await getSettings();+ const next = { ...current };+ for (const key of CLIENT_SETTABLE) {+ if (partial[key] !== undefined) next[key] = partial[key];+ }+ await ensureDir(INSIGHTS_DIR);+ await atomicWrite(SETTINGS_FILE, next);+ return next;+}++// User-editable per-goal mapping overrides. Shape: { [goalId]: { keywords?,+// personIds?, subcalendarIds?, enabled? } }. Stored locally, never federated.+export async function getRuleOverrides() {+ const loaded = await readJSONFile(RULES_FILE, null);+ return loaded && typeof loaded === 'object' ? loaded : {};+}++export async function saveRuleOverrides(overrides = {}) {+ const clean = overrides && typeof overrides === 'object' ? overrides : {};+ await ensureDir(INSIGHTS_DIR);+ await atomicWrite(RULES_FILE, clean);+ return clean;+}++// Load active goals from digital-twin. Returns [] when the file is missing.+async function loadGoals() {+ const data = await readJSONFile(GOALS_FILE, null);+ return Array.isArray(data?.goals) ? data.goals : [];+}++// The current effective ruleset (goals × user overrides) — powers the rules+// editor UI so the user sees the derived keywords they can extend.+export async function getEffectiveRules() {+ const [goals, overrides] = await Promise.all([loadGoals(), getRuleOverrides()]);+ return { rules: buildMappingRules(goals, overrides), overrides };+}++// ─── Read path (disk-only) ───────────────────────────────────────────────────++export async function getScorecard() {+ const cached = await readJSONFile(SCORECARD_FILE, null);+ if (!cached) return { available: false, reason: 'not_computed' };+ return { ...cached, available: true };+}++// ─── Compute (LLM-free) ──────────────────────────────────────────────────────++/**+ * Compute (and persist) the weekly goal-effectiveness scorecard. Deterministic+ * and LLM-free — safe to call on any user action. Queries the last TREND_WEEKS+ * of timeline events once, buckets them, computes the detailed target week plus+ * the trend series, persists the artifact, and (opt-in) splices a one-line slice+ * into the week-anchor day's Brain daily-log.+ *+ * @param {object} [opts]+ * @param {string} [opts.weekStart] — YYYY-MM-DD; defaults to the current week.+ * @returns {Promise<object>} the scorecard artifact (with available: true).+ */+export async function computeWeeklyScorecard({ weekStart } = {}) {+ const started = Date.now();+ const timezone = await getUserTimezone();+ const settings = await getSettings();+ const weekStartsOn = Number.isFinite(settings.weekStartsOn) ? settings.weekStartsOn : 1;++ const today = todayInTimezone(timezone);+ const targetWeek = isIso(weekStart) ? isoWeekStart(weekStart, weekStartsOn) : isoWeekStart(today, weekStartsOn);++ const [goals, overrides] = await Promise.all([loadGoals(), getRuleOverrides()]);+ const rules = buildMappingRules(goals, overrides);++ // Query the whole trend span in one pass: [oldest week start, target week end).+ const oldestWeek = shiftIsoDate(targetWeek, -(TREND_WEEKS - 1) * 7);+ const span = {+ start: weekRangeUtc(oldestWeek, timezone)?.start,+ end: weekRangeUtc(targetWeek, timezone)?.end,+ };+ const EVENT_CAP = 2000;+ const events = span.start && span.end+ ? await listEvents({ from: span.start.toISOString(), to: span.end.toISOString(), limit: EVENT_CAP })+ : [];+ // listEvents returns newest-first capped at EVENT_CAP — the target (current)+ // week is always fully covered, but a very active user could truncate the+ // OLDEST trend weeks. Surface it rather than silently under-counting a trend bar.+ if (events.length >= EVENT_CAP) {+ console.warn(`🎯 Goal scorecard hit the ${EVENT_CAP}-event query cap for ${targetWeek}; oldest trend weeks may under-count`);+ }++ const buckets = bucketEventsByWeek(events, timezone, weekStartsOn);+ const trend = [];+ for (let i = TREND_WEEKS - 1; i >= 0; i -= 1) {+ const wk = shiftIsoDate(targetWeek, -i * 7);+ trend.push({ weekStart: wk, ...weekTotals(buckets.get(wk) || [], rules) });+ }++ const scorecard = computeScorecard({+ weekStart: targetWeek,+ events: buckets.get(targetWeek) || [],+ rules,+ timezone,+ trend,+ });++ await ensureDir(INSIGHTS_DIR);+ await atomicWrite(SCORECARD_FILE, scorecard);++ if (settings.enabled && settings.feedBrainDigest) {+ const line = formatScorecardDigestLine(scorecard);+ // Splice into the week-anchor day's daily-log entry. Best-effort — a journal+ // failure must not fail the scorecard compute.+ await journal.upsertAutoSection(targetWeek, line || '', SCORECARD_DIGEST_MARKERS)+ .catch((err) => console.error(`🎯 Goal scorecard digest slice failed for ${targetWeek}: ${err.message}`));+ }++ console.log(`🎯 Goal scorecard computed for week ${targetWeek}: ${scorecard.totals.alignedHours}h aligned / ${scorecard.totals.unalignedHours}h unaligned (${goals.length} goals, ${events.length} events) in ${Date.now() - started}ms`);+ return { ...scorecard, available: true };+}++// ─── Optional LLM narrative (opt-in, user-triggered) ─────────────────────────++// Build the narrative prompt from the numeric scorecard. LLM-free callers never+// reach this.+function buildNarrativePrompt(scorecard) {+ const goalLines = (scorecard.goals || [])+ .filter((g) => g.alignedSeconds > 0)+ .slice(0, 8)+ .map((g) => `- ${g.title}${g.category ? ` (${g.category})` : ''}: ${g.alignedHours}h, ${g.eventCount} events, ${g.contactCount} distinct contacts`)+ .join('\n');+ const trendLine = (scorecard.trend || [])+ .map((w) => `${w.weekStart}: ${Math.round((w.alignedShare || 0) * 100)}% aligned`)+ .join(' → ');+ return [+ 'You are an accountability coach reviewing how someone spent their week against their stated goals.',+ 'Below is a deterministic scorecard of tracked time. Write 2–4 sentences, second person ("You spent…"), factual — do not invent activities or goals not listed. Call out the biggest mismatch between stated priority and time spent, if any.',+ 'Do not add a heading or preamble. Do not use markdown.',+ '',+ `Week of ${scorecard.weekStart}.`,+ `Aligned to goals: ${scorecard.totals.alignedHours}h. Unaligned: ${scorecard.totals.unalignedHours}h (${Math.round((scorecard.totals.alignedShare || 0) * 100)}% aligned).`,+ '',+ 'Time by goal:',+ goalLines || '(no time mapped to any goal this week)',+ '',+ `Aligned-share trend: ${trendLine}`,+ ].join('\n');+}++/**+ * Generate the optional LLM narrative for the current scorecard and persist it+ * onto the artifact. User-triggered only (a "Generate narrative" click). The+ * numeric scorecard itself is never regenerated here — the narrative is an+ * annotation on top of the deterministic artifact.+ *+ * @param {string} [providerId] — override the configured provider.+ * @param {string} [model]+ */+export async function refreshScorecardNarrative(providerId, model) {+ const scorecard = await readJSONFile(SCORECARD_FILE, null);+ if (!scorecard) return { available: false, reason: 'not_computed' };+ if (!scorecard.totals || scorecard.totals.totalSeconds === 0) {+ return { available: false, reason: 'no_activity' };+ }++ const settings = await getSettings();+ const resolvedProviderId = providerId || settings.provider;+ if (!resolvedProviderId) return { available: false, reason: 'no_provider' };++ const provider = await getProviderById(resolvedProviderId).catch(() => null);+ if (!provider || provider.enabled === false) return { available: false, reason: 'no_provider' };++ const selectedModel = model || settings.model || provider.defaultModel;+ const providerForCall = provider.headlessArgs?.length+ ? { ...provider, args: [...(provider.args || []), ...provider.headlessArgs] }+ : provider;++ const result = await runPromptThroughProvider({+ provider: providerForCall,+ prompt: buildNarrativePrompt(scorecard),+ source: 'goal-scorecard',+ model: selectedModel,+ }).catch((err) => {+ console.error(`🎯 Goal scorecard narrative failed: ${err.message}`);+ return null;+ });++ const text = (result?.text || '').trim();+ if (!text) return { available: false, reason: 'generation_failed' };++ const updated = { ...scorecard, narrative: text, narrativeGeneratedAt: new Date().toISOString(), narrativeModel: selectedModel };+ await ensureDir(INSIGHTS_DIR);+ await atomicWrite(SCORECARD_FILE, updated);+ console.log(`🎯 Goal scorecard narrative generated (${text.length} chars, model ${selectedModel})`);+ return { ...updated, available: true };+}diff --git a/server/services/goalScorecard.test.js b/server/services/goalScorecard.test.jsnew file mode 100644index 0000000000..2ea0e61ea7--- /dev/null+++ b/server/services/goalScorecard.test.js@@ -0,0 +1,292 @@+import { describe, it, expect } from 'vitest';+import {+ shiftIsoDate,+ isoWeekStart,+ weekRangeUtc,+ goalKeywords,+ buildMappingRules,+ eventGoalMatches,+ eventSeconds,+ bucketEventsByWeek,+ weekTotals,+ computeScorecard,+ formatScorecardDigestLine,+ NOMINAL_SECONDS,+ TREND_WEEKS,+} from './goalScorecard.js';++const UTC = 'UTC';++const ev = (over = {}) => ({+ kind: over.kind ?? 'message.sent',+ title: over.title ?? null,+ summary: over.summary ?? null,+ durationS: over.durationS ?? null,+ participants: over.participants ?? [],+ metadata: over.metadata ?? {},+ happenedAt: over.happenedAt ?? '2026-07-06T12:00:00.000Z',+ ...over,+});++describe('shiftIsoDate', () => {+ it('shifts forward and back across month/year boundaries', () => {+ expect(shiftIsoDate('2026-07-06', 7)).toBe('2026-07-13');+ expect(shiftIsoDate('2026-07-06', -7)).toBe('2026-06-29');+ expect(shiftIsoDate('2026-12-31', 1)).toBe('2027-01-01');+ expect(shiftIsoDate('2026-03-01', -1)).toBe('2026-02-28');+ });+});++describe('isoWeekStart (week bucketing)', () => {+ it('maps every day of a week to its Monday (default)', () => {+ // 2026-07-06 is a Monday. Mon..Sun all resolve to 2026-07-06.+ for (let i = 0; i < 7; i += 1) {+ expect(isoWeekStart(shiftIsoDate('2026-07-06', i))).toBe('2026-07-06');+ }+ // The next day (Mon 2026-07-13) starts a new bucket.+ expect(isoWeekStart('2026-07-13')).toBe('2026-07-13');+ });++ it('honors a Sunday week start (weekStartsOn=7)', () => {+ // 2026-07-05 is a Sunday. With Sunday-start, Sun..Sat resolve to 2026-07-05.+ expect(isoWeekStart('2026-07-05', 7)).toBe('2026-07-05');+ expect(isoWeekStart('2026-07-06', 7)).toBe('2026-07-05'); // Monday still in that week+ expect(isoWeekStart('2026-07-11', 7)).toBe('2026-07-05'); // Saturday+ expect(isoWeekStart('2026-07-12', 7)).toBe('2026-07-12'); // next Sunday+ });++ it('returns null for a non-ISO date', () => {+ expect(isoWeekStart('not-a-date')).toBeNull();+ expect(isoWeekStart(null)).toBeNull();+ });+});++describe('weekRangeUtc', () => {+ it('spans exactly 7 days in UTC', () => {+ const range = weekRangeUtc('2026-07-06', UTC);+ expect(range.start.toISOString()).toBe('2026-07-06T00:00:00.000Z');+ expect(range.end.toISOString()).toBe('2026-07-13T00:00:00.000Z');+ expect((range.end - range.start) / (24 * 3600 * 1000)).toBe(7);+ });+});++describe('goalKeywords', () => {+ it('drops stopwords and short tokens, keeps meaningful title words', () => {+ expect(goalKeywords({ title: 'Buy Estate Property' })).toEqual(+ expect.arrayContaining(['estate', 'property']),+ );+ // "Buy" is a stopword; nothing shorter than 4 chars survives.+ expect(goalKeywords({ title: 'Buy Estate Property' })).not.toContain('buy');+ });++ it('includes tags and category verbatim (lowercased)', () => {+ const kw = goalKeywords({ title: 'Musical Fluency', tags: ['Piano', 'practice'], category: 'creative' });+ expect(kw).toEqual(expect.arrayContaining(['musical', 'fluency', 'piano', 'practice', 'creative']));+ });++ it('de-duplicates overlap between title/tags/category', () => {+ const kw = goalKeywords({ title: 'Creative Legacy', tags: ['legacy'], category: 'creative' });+ expect(kw.filter((k) => k === 'legacy')).toHaveLength(1);+ expect(kw.filter((k) => k === 'creative')).toHaveLength(1);+ });+});++describe('buildMappingRules', () => {+ const goals = [+ { id: 'g1', title: 'Musical Fluency', category: 'creative', status: 'active' },+ { id: 'g2', title: 'Buy Humanoid Robot', category: 'financial', status: 'active', linkedCalendars: ['cal-x'] },+ { id: 'g3', title: 'Archived goal', category: 'health', status: 'archived' },+ ];++ it('builds one rule per active goal, skipping non-active', () => {+ const rules = buildMappingRules(goals);+ expect(rules.map((r) => r.id)).toEqual(['g1', 'g2']);+ });++ it('carries linkedCalendars into subcalendarIds', () => {+ const rules = buildMappingRules(goals);+ expect(rules.find((r) => r.id === 'g2').subcalendarIds).toEqual(['cal-x']);+ });++ it('merges override keywords and can disable a goal', () => {+ const rules = buildMappingRules(goals, {+ g1: { keywords: ['guitar', 'GUITAR'] },+ g2: { enabled: false },+ });+ expect(rules.map((r) => r.id)).toEqual(['g1']);+ expect(rules[0].keywords).toContain('guitar');+ // de-duped case-insensitively+ expect(rules[0].keywords.filter((k) => k === 'guitar')).toHaveLength(1);+ });++ it('override personIds/subcalendarIds replace the goal defaults', () => {+ const rules = buildMappingRules(goals, { g2: { personIds: ['p9'], subcalendarIds: ['cal-y'] } });+ const r = rules.find((x) => x.id === 'g2');+ expect(r.personIds).toEqual(['p9']);+ expect(r.subcalendarIds).toEqual(['cal-y']);+ });+});++describe('eventGoalMatches', () => {+ const rules = buildMappingRules([+ { id: 'music', title: 'Musical Fluency', category: 'creative', status: 'active' },+ { id: 'robot', title: 'Buy Humanoid Robot', category: 'financial', status: 'active', linkedActivities: ['p-bob'], linkedCalendars: ['cal-robot'] },+ ]);++ it('matches by keyword in title/summary/participant name', () => {+ expect(eventGoalMatches(ev({ title: 'piano and musical practice' }), rules)).toEqual(['music']);+ expect(eventGoalMatches(ev({ summary: 'ordered a humanoid arm' }), rules)).toEqual(['robot']);+ expect(eventGoalMatches(ev({ participants: [{ name: 'Robot Lab' }] }), rules)).toEqual(['robot']);+ });++ it('matches by linked personId', () => {+ expect(eventGoalMatches(ev({ participants: [{ personId: 'p-bob' }] }), rules)).toEqual(['robot']);+ });++ it('matches by linked calendar subcalendarId', () => {+ expect(eventGoalMatches(ev({ kind: 'calendar.event', metadata: { subcalendarId: 'cal-robot' } }), rules)).toEqual(['robot']);+ });++ it('returns empty for an unaligned event', () => {+ expect(eventGoalMatches(ev({ title: 'random chatter' }), rules)).toEqual([]);+ });++ it('can match multiple goals at once (de-duplicated)', () => {+ const out = eventGoalMatches(ev({ title: 'musical robot jam', summary: 'humanoid' }), rules);+ expect(out.sort()).toEqual(['music', 'robot']);+ });+});++describe('eventSeconds', () => {+ it('uses the real duration when present', () => {+ expect(eventSeconds(ev({ kind: 'calendar.event', durationS: 3600 }))).toBe(3600);+ });++ it('falls back to the per-kind nominal when duration is absent/zero', () => {+ expect(eventSeconds(ev({ kind: 'message.sent' }))).toBe(NOMINAL_SECONDS['message.sent']);+ expect(eventSeconds(ev({ kind: 'calendar.event', durationS: 0 }))).toBe(NOMINAL_SECONDS['calendar.event']);+ expect(eventSeconds(ev({ kind: 'unknown.kind' }))).toBe(NOMINAL_SECONDS.default);+ });+});++describe('bucketEventsByWeek', () => {+ it('groups events into their local weeks and drops unparseable timestamps', () => {+ const events = [+ ev({ happenedAt: '2026-07-06T10:00:00Z' }), // Mon week A+ ev({ happenedAt: '2026-07-12T23:00:00Z' }), // Sun week A+ ev({ happenedAt: '2026-07-13T01:00:00Z' }), // Mon week B+ ev({ happenedAt: 'garbage' }),+ ];+ const buckets = bucketEventsByWeek(events, UTC);+ expect(buckets.get('2026-07-06')).toHaveLength(2);+ expect(buckets.get('2026-07-13')).toHaveLength(1);+ expect([...buckets.keys()].sort()).toEqual(['2026-07-06', '2026-07-13']);+ });+});++describe('weekTotals', () => {+ const rules = buildMappingRules([{ id: 'music', title: 'Musical Fluency', category: 'creative', status: 'active' }]);++ it('splits aligned vs unaligned seconds', () => {+ const events = [+ ev({ kind: 'calendar.event', durationS: 3600, title: 'musical practice' }), // aligned 3600+ ev({ kind: 'message.sent', title: 'lunch plans' }), // unaligned 120+ ];+ const t = weekTotals(events, rules);+ expect(t.alignedSeconds).toBe(3600);+ expect(t.unalignedSeconds).toBe(NOMINAL_SECONDS['message.sent']);+ expect(t.totalSeconds).toBe(3600 + NOMINAL_SECONDS['message.sent']);+ expect(t.eventCount).toBe(2);+ });+});++describe('computeScorecard (rollup math)', () => {+ const rules = buildMappingRules([+ { id: 'music', title: 'Musical Fluency', category: 'creative', status: 'active' },+ { id: 'fitness', title: 'Ten Pull Ups', category: 'health', status: 'active' },+ ]);++ it('aggregates per-goal hours, share, and distinct contacts', () => {+ const events = [+ ev({ kind: 'calendar.event', durationS: 3600, title: 'musical rehearsal', participants: [{ personId: 'p1' }, { name: 'Ana' }] }),+ ev({ kind: 'calendar.event', durationS: 1800, title: 'more musical time', participants: [{ personId: 'p1' }] }),+ ev({ kind: 'calendar.event', durationS: 1800, title: 'pull ups session' }),+ ev({ kind: 'message.sent', title: 'unrelated' }), // unaligned+ ];+ const sc = computeScorecard({ weekStart: '2026-07-06', events, rules, timezone: UTC });++ expect(sc.totals.alignedSeconds).toBe(3600 + 1800 + 1800);+ expect(sc.totals.unalignedSeconds).toBe(NOMINAL_SECONDS['message.sent']);+ expect(sc.totals.alignedHours).toBe(2); // 7200s++ const music = sc.goals.find((g) => g.id === 'music');+ expect(music.alignedSeconds).toBe(5400);+ expect(music.alignedHours).toBe(1.5);+ expect(music.eventCount).toBe(2);+ // p1 twice + Ana once = 2 distinct contacts+ expect(music.contactCount).toBe(2);++ // Goals sorted by aligned seconds desc: music (5400) before fitness (1800).+ expect(sc.goals[0].id).toBe('music');+ // Share is fraction of aligned time (5400 / 7200 = 0.75).+ expect(music.share).toBeCloseTo(0.75, 3);+ });++ it('counts an event under every goal it maps to (overlap allowed)', () => {+ const events = [ev({ kind: 'calendar.event', durationS: 3600, title: 'musical pull ups mashup' })];+ const sc = computeScorecard({ weekStart: '2026-07-06', events, rules, timezone: UTC });+ expect(sc.goals.find((g) => g.id === 'music').alignedSeconds).toBe(3600);+ expect(sc.goals.find((g) => g.id === 'fitness').alignedSeconds).toBe(3600);+ // Aligned total counts the event once, not double.+ expect(sc.totals.alignedSeconds).toBe(3600);+ });++ it('reports trend direction from aligned share vs prior weeks', () => {+ const events = [ev({ kind: 'calendar.event', durationS: 3600, title: 'musical' })]; // 100% aligned this week+ const trend = [+ { weekStart: '2026-06-15', alignedSeconds: 10, unalignedSeconds: 90, totalSeconds: 100 }, // 10%+ { weekStart: '2026-06-22', alignedSeconds: 20, unalignedSeconds: 80, totalSeconds: 100 }, // 20%+ { weekStart: '2026-06-29', alignedSeconds: 30, unalignedSeconds: 70, totalSeconds: 100 }, // 30%+ { weekStart: '2026-07-06', alignedSeconds: 3600, unalignedSeconds: 0, totalSeconds: 3600 }, // current+ ];+ const sc = computeScorecard({ weekStart: '2026-07-06', events, rules, timezone: UTC, trend });+ expect(sc.trendDirection).toBe('up');+ expect(sc.trend).toHaveLength(4);+ expect(sc.trend[0].alignedShare).toBeCloseTo(0.1, 3);+ });++ it('is flat with no prior weeks and empty when there is no activity', () => {+ const empty = computeScorecard({ weekStart: '2026-07-06', events: [], rules, timezone: UTC });+ expect(empty.trendDirection).toBe('flat');+ expect(empty.totals.totalSeconds).toBe(0);+ expect(empty.totals.alignedShare).toBe(0);+ expect(empty.goals.every((g) => g.alignedSeconds === 0)).toBe(true);+ });+});++describe('formatScorecardDigestLine', () => {+ it('renders a one-line slice with the top goal', () => {+ const sc = {+ weekStart: '2026-07-06',+ totals: { alignedHours: 5, unalignedHours: 3, alignedShare: 0.625, totalSeconds: 28800 },+ goals: [{ title: 'Musical Fluency', alignedSeconds: 18000, alignedHours: 5 }],+ };+ const line = formatScorecardDigestLine(sc);+ expect(line).toContain('week of 2026-07-06');+ expect(line).toContain('5h aligned');+ expect(line).toContain('3h unaligned');+ expect(line).toContain('63% goal-aligned');+ expect(line).toContain('Musical Fluency');+ });++ it('returns null when there is no tracked time', () => {+ expect(formatScorecardDigestLine({ weekStart: '2026-07-06', totals: { totalSeconds: 0 }, goals: [] })).toBeNull();+ expect(formatScorecardDigestLine(null)).toBeNull();+ });+});++describe('constants', () => {+ it('exposes a sane trend window', () => {+ expect(TREND_WEEKS).toBeGreaterThanOrEqual(2);+ });+});