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([issue-2091]): POST time-series progress API + unified dashboard
Adam Eivy853e01310bc8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e4bdf09513..19270dbce1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -25,6 +25,7 @@## POST Training+- **[issue-2091] A unified Progress dashboard shows whether you're actually improving.** POST has a new **Progress** page (in the POST sidebar section, ⌘K, and voice nav) that pulls scored sessions, Morse/memory practice, and mastery into one view. It charts your score, accuracy, and response-time trends over time — so "am I getting faster?" finally has an answer — with same-day sessions rolled into one point (no more overlapping dots), a per-domain focus selector, and time-in-training cards. A single practice streak now counts *any* active day (a scored session **or** a Morse/memory practice), so the launcher, the Morse trainer, and the dashboard widgets can no longer disagree about your streak. A mastery panel shows your multiplication ladder rung and each memory item's mastery and due status. The full session-history table lives on as a sub-view.- **[issue-2092] Morse progress now lives on the server, with WPM/accuracy trends and a per-character confusion matrix.** Your Koch level and every completed drill round are now saved server-side instead of only in the browser — so clearing browser data or switching devices (over Tailscale) no longer wipes your Morse mastery, and your level is identical everywhere. The first time you open the trainer it adopts your existing browser level once, then keeps both in sync. A new **Morse Progress** panel on `/post/morse` charts accuracy and effective-WPM trends per mode (Copy / Head Copy / Send), highlights your most-confused character pairs (E↔I and friends), and lists your weakest characters worst-first so you know exactly which to drill next. Send-mode rounds record per-character keying accuracy and timing too.## Roundsdiff --git a/client/src/components/DailyPostWidget.jsx b/client/src/components/DailyPostWidget.jsxindex 4c868699c7..8d4cb0815a 100644--- a/client/src/components/DailyPostWidget.jsx+++ b/client/src/components/DailyPostWidget.jsx@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback } from 'react';import { Link } from 'react-router-dom';import { Brain, ArrowRight } from 'lucide-react';import * as api from '../services/api';+import { streakGlyph } from '../lib/streakGlyph.js';// Surfaces the daily POST cognitive self-test on the dashboard: today's// completion status, the current practice streak, and a one-click way into the@@ -27,7 +28,6 @@ export default function DailyPostWidget() {const longest = stats?.longestStreak ?? 0;const completedToday = !!stats?.completedToday;const todayScore = stats?.todayScore;- const streakGlyph = streak >= 7 ? '🔥' : streak >= 3 ? '⚡' : '✨';return (<Link@@ -49,7 +49,7 @@ export default function DailyPostWidget() {</div><div className="flex items-center gap-3">- <div className="text-2xl" aria-hidden="true">{streakGlyph}</div>+ <div className="text-2xl" aria-hidden="true">{streakGlyph(streak)}</div><div><div className="text-xl font-bold text-white">{streak} day{streak !== 1 ? 's' : ''}diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 8bec717685..866423b445 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -70,6 +70,7 @@ import {FilePen,MessageCircle,Radio,+ TrendingUp,Swords,HardDrive,Layers,@@ -329,6 +330,7 @@ const navItems = [{ to: '/post/launcher', label: 'Launcher', icon: Play },{ to: '/post/memory', label: 'Memory', icon: Brain },{ to: '/post/morse', label: 'Morse', icon: Radio },+ { to: '/post/progress', label: 'Progress', icon: TrendingUp },{ to: '/post/wordplay', label: 'Wordplay', icon: MessageCircle },],},diff --git a/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.jsx b/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.jsxindex 69a0ef25c3..34c81a8a66 100644--- a/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.jsx+++ b/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.jsx@@ -1,5 +1,6 @@import { Link } from 'react-router-dom';import { HeartPulse, ArrowRight } from 'lucide-react';+import { streakGlyph } from '../../../lib/streakGlyph.js';// Health-logging habit loop. Reads the `meatspaceLogging` slice of// dashboardState (cross-domain streak + this-week counts computed server-side)@@ -11,7 +12,6 @@ export default function MeatSpaceStreakWidget({ dashboardState }) {const streak = stats.currentStreak ?? 0;const longest = stats.longestStreak ?? 0;- const streakGlyph = streak >= 7 ? '🔥' : streak >= 3 ? '⚡' : '✨';const activeDomains = (stats.domains || []).filter((d) => d.thisWeek > 0);return (@@ -28,7 +28,7 @@ export default function MeatSpaceStreakWidget({ dashboardState }) {</div><div className="flex items-center gap-3">- <div className="text-2xl" aria-hidden="true">{streakGlyph}</div>+ <div className="text-2xl" aria-hidden="true">{streakGlyph(streak)}</div><div><div className="text-xl font-bold text-white">{streak} day{streak !== 1 ? 's' : ''}diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsxindex 74c5a40349..e741b034fe 100644--- a/client/src/components/meatspace/post/MorseTrainer.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.jsx@@ -3,6 +3,7 @@ import { ArrowLeft, Radio, Headphones, Hand, EyeOff, CheckCircle, XCircle, Play,import useDrawerTab from '../../../hooks/useDrawerTab';import { submitTrainingEntry, getTrainingStats, submitMorseRound, getMorseProgress, updateMorseLevel } from '../../../services/api';import MorseProgressPanel from './MorseProgressPanel';+import { streakGlyph } from '../../../lib/streakGlyph.js';export const MORSE_TABLE = {A: '.-', B: '-...', C: '-.-.', D: '-..', E: '.', F: '..-.',@@ -132,10 +133,6 @@ export const MODES = [// under one key regardless of which mode logged it.const TRAINING_MODULE = 'morse';-// Mirrors the streakGlyph helper in PostSessionLauncher.jsx/DailyPostWidget.jsx-// (small enough that a shared util would be more indirection than reuse).-const streakGlyph = (streak) => (streak >= 7 ? '🔥' : streak >= 3 ? '⚡' : '✨');-function loadPrefs() {const raw = typeof window !== 'undefined' ? window.localStorage.getItem(PREFS_KEY) : null;if (!raw) return { ...DEFAULT_PREFS };diff --git a/client/src/components/meatspace/post/PostProgress.jsx b/client/src/components/meatspace/post/PostProgress.jsxnew file mode 100644index 0000000000..d1e89ad80d--- /dev/null+++ b/client/src/components/meatspace/post/PostProgress.jsx@@ -0,0 +1,373 @@+import { useState, useEffect, useCallback, useMemo } from 'react';+import { ArrowLeft, Flame, Trophy, Clock, Gauge } from 'lucide-react';+import {+ LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid+} from 'recharts';+import { useNavigate } from 'react-router-dom';+import { getPostProgress } from '../../../services/api';+import useChartColors from '../../../hooks/useChartColors.js';+import { formatDurationMin } from '../../../utils/formatters';+import { DRILL_TO_DOMAIN, domainLabel } from './constants';+import { streakGlyph } from '../../../lib/streakGlyph.js';+import PostHistory from './PostHistory';++const RANGES = [+ { label: '7d', days: 7 },+ { label: '30d', days: 30 },+ { label: '90d', days: 90 },+ { label: 'All', days: 0 }+];++// Same domain palette PostHistory uses so the two views read as one system.+const DOMAIN_HEX = {+ math: '#60a5fa',+ memory: '#4ade80',+ wordplay: '#c084fc',+ verbal: '#fbbf24',+ imagination: '#22d3ee',+ cognitive: '#fb7185'+};+const domainHex = (key) => DOMAIN_HEX[key] || '#a3a3a3';++const mean = (list) => (list.length ? list.reduce((a, b) => a + b, 0) / list.length : null);++// Build per-DOMAIN per-day series client-side from the server's per-DRILL+// series (keyed by drill type), mapping each type to its domain via+// DRILL_TO_DOMAIN — the same type→domain resolution PostHistory uses, which is+// finer-grained than the server's coarse module buckets.+function buildDomainSeries(byDrill) {+ const domains = {}; // domainKey -> Map(date -> {scores, accs, resp})+ for (const [type, points] of Object.entries(byDrill || {})) {+ const domain = DRILL_TO_DOMAIN[type] || 'other';+ const dmap = domains[domain] || (domains[domain] = new Map());+ for (const p of points || []) {+ const b = dmap.get(p.date) || { scores: [], accs: [], resp: [] };+ if (typeof p.score === 'number') b.scores.push(p.score);+ if (p.accuracy != null) b.accs.push(p.accuracy);+ if (p.avgResponseMs != null) b.resp.push(p.avgResponseMs);+ dmap.set(p.date, b);+ }+ }+ const out = {};+ for (const [domain, dmap] of Object.entries(domains)) {+ out[domain] = Array.from(dmap.entries())+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([date, b]) => ({+ date,+ score: b.scores.length ? Math.round(mean(b.scores)) : null,+ accuracy: b.accs.length ? mean(b.accs) : null,+ avgResponseMs: b.resp.length ? Math.round(mean(b.resp)) : null,+ }));+ }+ return out;+}++export default function PostProgress({ subtab, onBack }) {+ const navigate = useNavigate();+ const chartColors = useChartColors();+ const [progress, setProgress] = useState(null);+ const [range, setRange] = useState(90);+ const [domain, setDomain] = useState('all');+ const [loaded, setLoaded] = useState(false);++ const loadData = useCallback(async () => {+ // The Sessions sub-view renders PostHistory (its own fetch) — no need to+ // pull the progress payload for it.+ if (subtab === 'sessions') return;+ const p = await getPostProgress(range, { silent: true })+ .catch((err) => { console.warn('⚠️ Failed to load POST progress: ' + err.message); return null; });+ setProgress(p);+ setLoaded(true);+ }, [range, subtab]);++ useEffect(() => { loadData(); }, [loadData]);++ const domainSeries = useMemo(+ () => buildDomainSeries(progress?.series?.byDrill),+ [progress]+ );+ const domainKeys = useMemo(() => Object.keys(domainSeries).sort(), [domainSeries]);++ // The active series drives all three trend charts: overall per-day buckets, or+ // one domain's per-day series when a domain is selected.+ const activeSeries = useMemo(() => {+ if (domain !== 'all' && domainSeries[domain]) return domainSeries[domain];+ return progress?.series?.byDay || [];+ }, [domain, domainSeries, progress]);++ const scoreData = useMemo(+ () => activeSeries.filter(p => p.score != null).map(p => ({ date: p.date, score: p.score })),+ [activeSeries]+ );+ const accuracyData = useMemo(+ () => activeSeries.filter(p => p.accuracy != null).map(p => ({ date: p.date, accuracy: Math.round(p.accuracy * 100) })),+ [activeSeries]+ );+ const speedData = useMemo(+ () => activeSeries.filter(p => p.avgResponseMs != null).map(p => ({ date: p.date, seconds: +(p.avgResponseMs / 1000).toFixed(2) })),+ [activeSeries]+ );+ const minutesData = useMemo(+ () => (progress?.series?.byDay || []).map(p => ({ date: p.date, minutes: p.minutes })),+ [progress]+ );++ // Sub-view: the full session-list table (reuses PostHistory), deep-linked at+ // /post/progress/sessions.+ if (subtab === 'sessions') {+ return (+ <div className="space-y-4">+ <ProgressTabs subtab="sessions" navigate={navigate} />+ <PostHistory onBack={onBack} />+ </div>+ );+ }++ const streak = progress?.streak || { current: 0, longest: 0 };+ const totals = progress?.totals || { minutesTrained: 0, sessions: 0, practiceEntries: 0 };+ const mastery = progress?.mastery || { multiplication: null, memoryItems: [] };+ const dueTotal = (mastery.memoryItems || []).reduce((n, m) => n + (m.dueCount || 0), 0);+ const hasAny = totals.sessions > 0 || totals.practiceEntries > 0;++ return (+ <div className="space-y-6">+ {/* Header */}+ <div className="flex items-center justify-between gap-3 flex-wrap">+ <div className="flex items-center gap-3">+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors" aria-label="Back">+ <ArrowLeft size={20} />+ </button>+ <h2 className="text-xl font-bold text-white">Progress</h2>+ </div>+ <div className="flex gap-1">+ {RANGES.map(r => (+ <button+ key={r.label}+ onClick={() => setRange(r.days)}+ className={`px-3 py-1 text-xs rounded-lg transition-colors ${+ range === r.days ? 'bg-port-accent/20 text-port-accent' : 'text-gray-500 hover:text-white'+ }`}+ >+ {r.label}+ </button>+ ))}+ </div>+ </div>++ <ProgressTabs subtab={undefined} navigate={navigate} />++ {loaded && !hasAny && (+ <div className="bg-port-card border border-port-border rounded-lg text-center text-gray-500 py-12 text-sm">+ No training activity yet. Complete a POST session or a practice drill to start tracking your progress.+ </div>+ )}++ {hasAny && (+ <>+ {/* Stat cards */}+ <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-5 gap-3 sm:gap-4">+ <StatCard+ label="Current Streak"+ value={streak.current}+ suffix={streak.current === 1 ? 'day' : 'days'}+ icon={<span aria-hidden="true">{streakGlyph(streak.current)}</span>}+ />+ <StatCard+ label="Longest Streak"+ value={streak.longest}+ suffix={streak.longest === 1 ? 'day' : 'days'}+ icon={<Trophy size={14} className="text-port-accent" />}+ />+ <StatCard+ label="Time in Training"+ value={formatDurationMin(totals.minutesTrained) || '0m'}+ icon={<Clock size={14} className="text-port-success" />}+ />+ <StatCard label="Sessions" value={totals.sessions} />+ <StatCard label="Practice Drills" value={totals.practiceEntries} />+ </div>++ {/* Domain selector */}+ <div className="flex items-center gap-2 flex-wrap">+ <span className="text-xs text-gray-500 flex items-center gap-1"><Gauge size={12} /> Trend focus:</span>+ <button+ onClick={() => setDomain('all')}+ className={`px-3 py-1 text-xs rounded-lg transition-colors ${+ domain === 'all' ? 'bg-port-accent/20 text-port-accent' : 'text-gray-500 hover:text-white'+ }`}+ >+ All domains+ </button>+ {domainKeys.map(key => (+ <button+ key={key}+ onClick={() => setDomain(key)}+ className={`px-3 py-1 text-xs rounded-lg transition-colors flex items-center gap-1.5 ${+ domain === key ? 'bg-port-accent/20 text-port-accent' : 'text-gray-500 hover:text-white'+ }`}+ >+ <span className="w-2 h-2 rounded-full" style={{ backgroundColor: domainHex(key) }} />+ {domainLabel(key)}+ </button>+ ))}+ </div>++ {/* Trend charts */}+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">+ <TrendChart+ title="Score Trend"+ data={scoreData}+ dataKey="score"+ domainRange={[0, 100]}+ stroke={domain === 'all' ? chartColors.accent : domainHex(domain)}+ chartColors={chartColors}+ emptyText="Complete more sessions to chart your score."+ />+ <TrendChart+ title="Accuracy Trend"+ data={accuracyData}+ dataKey="accuracy"+ domainRange={[0, 100]}+ unit="%"+ stroke={chartColors.success}+ chartColors={chartColors}+ emptyText="No accuracy data yet."+ />+ <TrendChart+ title="Response Time (getting faster)"+ data={speedData}+ dataKey="seconds"+ domainRange={[0, 'auto']}+ unit="s"+ stroke={chartColors.warning}+ chartColors={chartColors}+ emptyText="No response-time data yet."+ />+ <TrendChart+ title="Time in Training (min/day)"+ data={minutesData}+ dataKey="minutes"+ domainRange={[0, 'auto']}+ unit="m"+ stroke={chartColors.chart2 || chartColors.success}+ chartColors={chartColors}+ emptyText="No training time logged yet."+ />+ </div>++ {/* Mastery panel */}+ <div className="grid grid-cols-1 xl:grid-cols-2 gap-4 sm:gap-6">+ {mastery.multiplication && (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3">Multiplication Ladder</h3>+ <div className="flex items-baseline gap-2">+ <span className="text-2xl font-mono font-bold text-white">L{mastery.multiplication.level}</span>+ <span className="text-sm text-gray-400">{mastery.multiplication.description}</span>+ </div>+ <div className="text-xs text-gray-500 mt-1">+ Earned floor: L{mastery.multiplication.floorLevel}+ </div>+ </div>+ )}++ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between mb-3">+ <h3 className="text-sm font-medium text-gray-400">Memory Mastery</h3>+ {dueTotal > 0 && (+ <span className="px-2 py-0.5 bg-port-warning/20 text-port-warning text-xs rounded-full">+ {dueTotal} due+ </span>+ )}+ </div>+ {(mastery.memoryItems || []).length > 0 ? (+ <div className="space-y-2">+ {mastery.memoryItems.map(item => (+ <div key={item.id} className="flex items-center gap-3">+ <span className="text-xs text-gray-400 w-32 shrink-0 truncate" title={item.title}>{item.title}</span>+ <div className="flex-1 h-2 bg-port-bg rounded-full overflow-hidden">+ <div+ className="h-full rounded-full bg-port-success"+ style={{ width: `${Math.min(100, Math.max(0, item.overallPct))}%` }}+ />+ </div>+ <span className="text-xs font-mono w-10 text-right text-gray-400">{Math.round(item.overallPct)}%</span>+ {item.dueCount > 0 && <Flame size={12} className="text-port-warning shrink-0" aria-label="Due for review" />}+ </div>+ ))}+ </div>+ ) : (+ <div className="text-center text-gray-500 py-6 text-sm">No memory items yet.</div>+ )}+ </div>+ </div>+ </>+ )}+ </div>+ );+}++function ProgressTabs({ subtab, navigate }) {+ const tabs = [+ { id: undefined, label: 'Trends', to: '/post/progress' },+ { id: 'sessions', label: 'Sessions', to: '/post/progress/sessions' },+ ];+ return (+ <div className="flex gap-1 border-b border-port-border">+ {tabs.map(t => (+ <button+ key={t.label}+ onClick={() => navigate(t.to)}+ className={`px-4 py-2 text-sm transition-colors border-b-2 -mb-px ${+ subtab === t.id+ ? 'border-port-accent text-white'+ : 'border-transparent text-gray-500 hover:text-white'+ }`}+ >+ {t.label}+ </button>+ ))}+ </div>+ );+}++function TrendChart({ title, data, dataKey, domainRange, unit, stroke, chartColors, emptyText }) {+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3">{title}</h3>+ {data.length > 1 ? (+ <ResponsiveContainer width="100%" height={200}>+ <LineChart data={data}>+ <CartesianGrid stroke={chartColors.grid} strokeDasharray="3 3" />+ <XAxis dataKey="date" tick={{ fontSize: 11, fill: chartColors.axis }} />+ <YAxis+ domain={domainRange}+ tick={{ fontSize: 11, fill: chartColors.axis }}+ tickFormatter={unit ? (v) => `${v}${unit}` : undefined}+ />+ <Tooltip+ contentStyle={{ backgroundColor: chartColors.tooltipBg, border: `1px solid ${chartColors.tooltipBorder}`, borderRadius: 8 }}+ labelStyle={{ color: chartColors.axis }}+ formatter={(v) => [`${v}${unit || ''}`, title]}+ />+ <Line type="monotone" dataKey={dataKey} stroke={stroke} strokeWidth={2} dot={{ r: 3 }} connectNulls />+ </LineChart>+ </ResponsiveContainer>+ ) : (+ <div className="text-center text-gray-500 py-12 text-sm">{emptyText}</div>+ )}+ </div>+ );+}++function StatCard({ label, value, suffix, valueClass = 'text-white', icon }) {+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-3 text-center">+ <div className={`text-2xl font-mono font-bold flex items-center justify-center gap-1.5 ${valueClass}`}>+ {icon}+ {value}+ {suffix && <span className="text-xs font-normal text-gray-500 self-end mb-1">{suffix}</span>}+ </div>+ <div className="text-xs text-gray-500">{label}</div>+ </div>+ );+}diff --git a/client/src/components/meatspace/post/PostProgress.test.jsx b/client/src/components/meatspace/post/PostProgress.test.jsxnew file mode 100644index 0000000000..a20ee8b3d4--- /dev/null+++ b/client/src/components/meatspace/post/PostProgress.test.jsx@@ -0,0 +1,96 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';++vi.mock('../../../services/api', () => ({+ getPostProgress: vi.fn(),+ // PostHistory (the Sessions sub-view) imports these from the same module.+ getPostSessions: vi.fn().mockResolvedValue([]),+ getPostStats: vi.fn().mockResolvedValue(null),+}));++import PostProgress from './PostProgress';+import { getPostProgress } from '../../../services/api';++const PROGRESS = {+ days: 90,+ series: {+ byDay: [+ { date: '2026-06-01', score: 70, accuracy: 0.7, avgResponseMs: 3000, minutes: 5, sessions: 1 },+ { date: '2026-06-02', score: 82, accuracy: 0.85, avgResponseMs: 2500, minutes: 6, sessions: 1 },+ { date: '2026-06-03', score: 90, accuracy: 0.9, avgResponseMs: 2000, minutes: 4, sessions: 1 },+ ],+ byDomain: { 'mental-math': [] },+ byDrill: {+ multiplication: [+ { date: '2026-06-01', score: 70, accuracy: 0.7, avgResponseMs: 3000 },+ { date: '2026-06-02', score: 82, accuracy: 0.85, avgResponseMs: 2500 },+ ],+ },+ },+ totals: { minutesTrained: 135, sessions: 3, practiceEntries: 2 },+ streak: { current: 3, longest: 5, lastActiveDate: '2026-06-03' },+ mastery: {+ multiplication: { level: 2, description: '1×1×1-digit', floorLevel: 1 },+ memoryItems: [{ id: 'm1', title: 'Elements', overallPct: 42, dueCount: 1 }],+ },+};++function renderProgress(subtab) {+ return render(+ <MemoryRouter>+ <PostProgress subtab={subtab} onBack={() => {}} />+ </MemoryRouter>+ );+}++beforeEach(() => {+ vi.clearAllMocks();+ getPostProgress.mockResolvedValue(PROGRESS);+});++describe('PostProgress', () => {+ it('renders stat cards, trend charts, and the mastery panel', async () => {+ renderProgress();+ await waitFor(() => expect(screen.getByText('Time in Training')).toBeInTheDocument());+ // Unified streak + time in training cards.+ expect(screen.getByText('Current Streak')).toBeInTheDocument();+ expect(screen.getByText('2h 15m')).toBeInTheDocument(); // 135 minutes+ // Trend chart headings.+ expect(screen.getByText('Score Trend')).toBeInTheDocument();+ expect(screen.getByText('Accuracy Trend')).toBeInTheDocument();+ expect(screen.getByText(/Response Time/)).toBeInTheDocument();+ // Mastery panel: multiplication rung + memory item.+ expect(screen.getByText('Multiplication Ladder')).toBeInTheDocument();+ expect(screen.getByText('L2')).toBeInTheDocument();+ expect(screen.getByText('Elements')).toBeInTheDocument();+ });++ it('offers a per-domain trend selector', async () => {+ renderProgress();+ await waitFor(() => expect(screen.getByText('Trend focus:')).toBeInTheDocument());+ // The "All domains" focus button plus the domain derived from byDrill (Mental Math).+ expect(screen.getByRole('button', { name: 'All domains' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Mental Math/ })).toBeInTheDocument();+ });++ it('shows an empty state when there is no activity', async () => {+ getPostProgress.mockResolvedValue({+ days: 90,+ series: { byDay: [], byDomain: {}, byDrill: {} },+ totals: { minutesTrained: 0, sessions: 0, practiceEntries: 0 },+ streak: { current: 0, longest: 0, lastActiveDate: null },+ mastery: { multiplication: null, memoryItems: [] },+ });+ renderProgress();+ await waitFor(() => expect(screen.getByText(/No training activity yet/)).toBeInTheDocument());+ });++ it('renders the session-list sub-view when subtab is "sessions"', async () => {+ renderProgress('sessions');+ // PostHistory renders its own "POST History" heading.+ await waitFor(() => expect(screen.getByText('POST History')).toBeInTheDocument());+ // The progress endpoint is not fetched on the sessions sub-view.+ expect(getPostProgress).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex 0be92a27ef..247075c2c3 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -4,9 +4,7 @@ import { getProviders } from '../../../services/api';import { FormField } from '../../ui/FormField';import { isApiProvider } from '../../../utils/providers';import { DOMAINS, DRILL_TO_DOMAIN, DRILL_LABELS, computeDomainAverages } from './constants';--// Streak glyph tiers mirror DailyPostWidget so the launcher and dashboard agree.-const streakGlyph = (streak) => (streak >= 7 ? '🔥' : streak >= 3 ? '⚡' : '✨');+import { streakGlyph } from '../../../lib/streakGlyph.js';const scoreColorClass = (score) =>score >= 80 ? 'text-port-success' : score >= 50 ? 'text-port-warning' : 'text-port-error';diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsxindex af1d03e5a0..010f0924fc 100644--- a/client/src/components/meatspace/tabs/PostTab.jsx+++ b/client/src/components/meatspace/tabs/PostTab.jsx@@ -9,6 +9,7 @@ import PostLlmDrillRunner from '../post/PostLlmDrillRunner';import PostCognitiveDrillRunner from '../post/PostCognitiveDrillRunner';import PostSessionResults from '../post/PostSessionResults';import PostHistory from '../post/PostHistory';+import PostProgress from '../post/PostProgress';import PostDrillConfig from '../post/PostDrillConfig';import MemoryBuilder from '../post/MemoryBuilder';import ElementsSong from '../post/ElementsSong';@@ -154,6 +155,8 @@ export default function PostTab({ tab = 'launcher', subtab }) {switch (tab) {case 'history':return <PostHistory onBack={() => navigate('/post/launcher')} />;+ case 'progress':+ return <PostProgress subtab={subtab} onBack={() => navigate('/post/launcher')} />;case 'config':// Wait for the async config load before mounting the editor: its state is// seeded once from the `config` prop, so mounting on a null/loading configdiff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 0231374f8e..72f8ed888e 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -118,6 +118,7 @@ grep -i "what you want to do" client/src/lib/README.md| `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. || `tribe.js` | Pure Tribe domain helpers shared by the Tribe page and its `TribeCircleMap` visualization: `RINGS` (support→core→tribe→village Dunbar rings + the uncapped `external` "outside the tribe" classification — caps, cadence defaults, Tailwind tones + `hex`), `TRIBE_RINGS` (the four inner rings the care queue/capacity/overdue counts operate over, excluding `external`), `ENERGY` (energy tiers + `hex`), `STATUS_HEX` (cadence-status → SVG stroke color), `contactStatus(contact)` (presentation wrapper over the shared `cadenceStatus` — attaches label/tone to the missing/overdue/soon/steady/`external` state) / `daysBetween(date)` (alias of the shared `daysSinceDate`), `ringFor` / `energyFor` lookups, `tagsToArray` / `tagsToInput`, and `initialsFor(name)` (node glyph). Ring `cadenceDays` mirror `DEFAULT_RING_CADENCE` in `server/services/tribe.js`; the cadence STATE MACHINE lives in `tribeCadence.js`. || `tribeCadence.js` | Mirror of `server/lib/tribeCadence.js` — the single authoritative Tribe care-cadence rules shared by the page, the Care dashboard widget, and the proactive alert: `cadenceStatus(entity)` → `{ state, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS`, `SOON_WINDOW_DAYS`. A cross-boundary contract test asserts it never drifts from the server copy. |+| `streakGlyph.js` | `streakGlyph(streak)` — the single POST streak emoji (✨ / ⚡ / 🔥 by day count) shared by the POST launcher, Morse trainer, daily widget, and dashboard streak widget. || `syncCounts.js` | Directional pending-sync counts for the Instances federation cards. `directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs })` → `{ toPull, toPush }` (each a non-negative Number, or `null` when unknown) from monotonic change-log seqs; `diffSeq(ahead, behind)` is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past `MAX_SAFE_INTEGER`); `describeDirectional({ toPull, toPush })` renders the plain-language `{ state, text }` ("in sync" / "N to pull · M to push" / "checking…"). No React — `SyncStatusBadge` drives it. || `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. || `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 1211550e9f..36e011eaba 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -83,6 +83,7 @@ export * from './singToScore.js';export * from './songCraft.js';export * from './songPlayback.js';export * from './songProgress.js';+export * from './streakGlyph.js';export * from './syncCounts.js';export * from './terminalTheme.js';export * from './tribe.js';diff --git a/client/src/lib/streakGlyph.js b/client/src/lib/streakGlyph.jsnew file mode 100644index 0000000000..e4e79fe9a0--- /dev/null+++ b/client/src/lib/streakGlyph.js@@ -0,0 +1,10 @@+/**+ * The single POST streak glyph used across the launcher, Morse trainer, daily+ * widget, and dashboard streak widget — one implementation instead of the four+ * copy-pasted ternaries that used to drift (issue #2091).+ *+ * ✨ under 3 days, ⚡ at 3–6, 🔥 at 7+.+ */+export function streakGlyph(streak) {+ return streak >= 7 ? '🔥' : streak >= 3 ? '⚡' : '✨';+}diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.jsindex bc1f119c5e..f9e089da16 100644--- a/client/src/services/apiMeatspace.js+++ b/client/src/services/apiMeatspace.js@@ -186,6 +186,10 @@ export const submitPostSession = (data, options = {}) => request('/meatspace/pos...options});export const getPostStats = (days) => request(`/meatspace/post/stats${days != null ? `?days=${days}` : ''}`);+export const getPostProgress = (days, options = {}) => request(+ `/meatspace/post/progress${days != null ? `?days=${days}` : ''}`,+ options+);export const getPostAdaptivePreview = () => request('/meatspace/post/adaptive-preview');export const getPostMultiplicationProgress = () => request('/meatspace/post/multiplication-progress');export const generatePostDrill = (type, config = {}, providerId, model, options = {}) => request('/meatspace/post/drill', {diff --git a/server/lib/README.md b/server/lib/README.mdindex ec50842515..8ac43852be 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -215,6 +215,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `pipelineIssueOrder.js` | Pure renumber algorithm for pipeline issues. || `postAdaptive.js` | Pure POST adaptive-difficulty policy — nudges a math drill's primary knob (`steps`/`maxDigits`/`maxExponent`/`tolerancePct`) up/down within clamped bounds from recent scored performance. Opt-in via the config Adaptive toggle. || `postMultiplicationLadder.js` | Pure progressive multiplication ladder — mastery-gated difficulty rungs (`[1,1]` → `[1,2]` → `[1,1,1]` → …). Resolves the user's current level from per-level speed+accuracy stats so the plain multiplication drill ramps up instead of starting at a fixed hard difficulty. On by default. |+| `postStreak.js` | Pure DST-safe POST practice-streak math — the single `computePostStreaks` implementation shared by scored sessions and the training log, plus `computeUnifiedStreak` (a day is active with EITHER a session or a practice entry). || `planIds.js` | Utilities for PLAN.md `[slug]` IDs. || `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. || `telegramClient.js` | Telegram bot client. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 76e9ba10af..418003eeac 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -190,6 +190,7 @@ export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';export * from './postAdaptive.js';export * from './postMultiplicationLadder.js';+export * from './postStreak.js';export * from './planIds.js';export * from './renderSlot.js';export * from './telegramClient.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 1c1301175e..784f63b72f 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -162,6 +162,7 @@ export const NAV_COMMANDS = [{ id: 'nav.post.morse.tree', path: '/post/morse?ref=tree', label: 'Morse Tree', section: 'POST', aliases: ['morse-tree', 'morse tree', 'morse-chart', 'dichotomic'], keywords: ['cw', 'binary tree', 'chart', 'reference', 'dit dah'] },{ id: 'nav.post.morse.length', path: '/post/morse?ref=length', label: 'Morse Length', section: 'POST', aliases: ['morse-length', 'morse length', 'morse-by-length'], keywords: ['cw', 'reference', 'symbol length', 'chart'] },{ id: 'nav.post.morse.list', path: '/post/morse?ref=list', label: 'Morse List', section: 'POST', aliases: ['morse-list', 'morse list', 'morse-table', 'morse-alphabet'], keywords: ['cw', 'reference', 'alphabet', 'table', 'chart'] },+ { id: 'nav.post.progress', path: '/post/progress', label: 'Progress', section: 'POST', aliases: ['post-progress', 'progress'], keywords: ['trends', 'stats', 'streak', 'dashboard', 'time in training', 'accuracy', 'speed'] },{ id: 'nav.post.wordplay', path: '/post/wordplay', label: 'Wordplay', section: 'POST', aliases: ['post-wordplay'] },{ id: 'nav.settings.ai-assignments', path: '/settings/ai-assignments', label: 'AI Assignments', section: 'Settings', aliases: ['ai-assignments', 'assignments', 'settings-ai-assignments', 'ai-inventory'], keywords: ['provider', 'model', 'pin', 'inventory', 'migration', 'llm'] },diff --git a/server/lib/postStreak.js b/server/lib/postStreak.jsnew file mode 100644index 0000000000..92a2470614--- /dev/null+++ b/server/lib/postStreak.js@@ -0,0 +1,91 @@+/**+ * POST practice-streak math (pure, side-effect-free).+ *+ * Extracted from meatspacePost.js so BOTH scored sessions and the training log+ * (Morse / memory practice) compute streaks with ONE implementation — the DST-+ * safe `computePostStreaks` — instead of the two divergent copies that used to+ * disagree (the training log previously rolled its own raw-`Date` streak with no+ * grace window and no longest-streak). Lives in `server/lib/` (rather than being+ * exported from a service) so meatspacePostTraining.js can import it without a+ * circular dependency back into meatspacePost.js.+ */++// A date key is always the local `YYYY-MM-DD` prefix. Session dates are stored+// that way already; some training-log entries (memory practice) store a full+// ISO timestamp, so normalize both to the day prefix before any set math.+function normalizeYmd(value) {+ if (!value) return null;+ return String(value).split('T')[0];+}++// Local-date arithmetic on `YYYY-MM-DD` strings via UTC midnight so day math+// never drifts across DST boundaries (the activity-streak bug class).+export function ymdToUTC(s) {+ const [y, m, d] = s.split('-').map(Number);+ return Date.UTC(y, m - 1, d);+}++export function ymdShift(s, deltaDays) {+ return new Date(ymdToUTC(s) + deltaDays * 86400000).toISOString().split('T')[0];+}++/**+ * Compute POST practice streaks from activity records. Pure (takes `todayStr`+ * explicitly) so it's unit-testable without faking the clock. Each record only+ * needs a `date` (`YYYY-MM-DD` or a full ISO timestamp — both normalized) and,+ * for `todayScore`, an optional numeric `score`.+ *+ * - `completedToday` — at least one record dated today+ * - `currentStreak` — consecutive days with a record counting back from+ * today; a not-yet-done today does NOT break the streak as long as yesterday+ * has one (grace window), mirroring `usage.js` `calculateStreak`+ * - `longestStreak` — longest consecutive-day run in all history+ * - `lastDate` — most recent record date (null if never active)+ * - `todayScore` — best record score recorded today (null if none)+ */+export function computePostStreaks(records, todayStr) {+ const dateSet = new Set((records || []).map(s => normalizeYmd(s?.date)).filter(Boolean));+ const dates = Array.from(dateSet).sort();+ const completedToday = dateSet.has(todayStr);+ const lastDate = dates.length ? dates[dates.length - 1] : null;++ const todayScores = (records || [])+ .filter(s => normalizeYmd(s?.date) === todayStr && typeof s?.score === 'number')+ .map(s => s.score);+ const todayScore = todayScores.length ? Math.max(...todayScores) : null;++ let longestStreak = 0;+ let run = 0;+ let prev = null;+ for (const d of dates) {+ run = prev && ymdToUTC(d) - ymdToUTC(prev) === 86400000 ? run + 1 : 1;+ if (run > longestStreak) longestStreak = run;+ prev = d;+ }++ // Anchor the current streak at today, or yesterday if today isn't done yet.+ let cursor = completedToday ? todayStr : ymdShift(todayStr, -1);+ let currentStreak = 0;+ while (dateSet.has(cursor)) {+ currentStreak += 1;+ cursor = ymdShift(cursor, -1);+ }++ return { completedToday, currentStreak, longestStreak, lastDate, todayScore };+}++/**+ * ONE unified streak across scored sessions AND the training log: a day counts+ * as active if it has EITHER a scored session or a training-log entry (Morse /+ * memory practice). Reuses `computePostStreaks` so the DST-safe grace-window+ * semantics are identical to the scored-session streak. Returns the progress-API+ * shape (`current` / `longest` / `lastActiveDate`).+ */+export function computeUnifiedStreak(sessions, trainingEntries, todayStr) {+ const activity = [+ ...(sessions || []).map(s => ({ date: s?.date })),+ ...(trainingEntries || []).map(e => ({ date: e?.date })),+ ];+ const { currentStreak, longestStreak, lastDate } = computePostStreaks(activity, todayStr);+ return { current: currentStreak, longest: longestStreak, lastActiveDate: lastDate };+}diff --git a/server/lib/postStreak.test.js b/server/lib/postStreak.test.jsnew file mode 100644index 0000000000..ca270fec57--- /dev/null+++ b/server/lib/postStreak.test.js@@ -0,0 +1,81 @@+import { describe, it, expect } from 'vitest';+import { computePostStreaks, computeUnifiedStreak, ymdShift } from './postStreak.js';++const rec = (date, score) => (score == null ? { date } : { date, score });++describe('computePostStreaks (shared helper)', () => {+ it('normalizes full-ISO record dates to the day prefix', () => {+ // Memory-practice entries store a full ISO timestamp, not YYYY-MM-DD.+ const r = computePostStreaks(+ [rec('2026-06-27T13:04:00.000Z'), rec('2026-06-28T09:00:00.000Z')],+ '2026-06-28'+ );+ expect(r.currentStreak).toBe(2);+ expect(r.lastDate).toBe('2026-06-28');+ });++ it('honors the grace window (today not done, yesterday done)', () => {+ const r = computePostStreaks([rec('2026-06-26'), rec('2026-06-27')], '2026-06-28');+ expect(r.completedToday).toBe(false);+ expect(r.currentStreak).toBe(2);+ });++ it('a gap breaks the current streak but longest survives', () => {+ const r = computePostStreaks(+ [rec('2026-06-20'), rec('2026-06-21'), rec('2026-06-22'), rec('2026-06-28')],+ '2026-06-28'+ );+ expect(r.currentStreak).toBe(1);+ expect(r.longestStreak).toBe(3);+ });+});++describe('computeUnifiedStreak (sessions OR training-log activity)', () => {+ it('session-only days count', () => {+ const r = computeUnifiedStreak(+ [rec('2026-06-27', 80), rec('2026-06-28', 90)],+ [],+ '2026-06-28'+ );+ expect(r).toEqual({ current: 2, longest: 2, lastActiveDate: '2026-06-28' });+ });++ it('practice-only days count (no scored session)', () => {+ // A Morse/memory practice day with NO scored session still extends the streak.+ const r = computeUnifiedStreak(+ [],+ [{ date: '2026-06-27' }, { date: '2026-06-28' }],+ '2026-06-28'+ );+ expect(r.current).toBe(2);+ expect(r.longest).toBe(2);+ });++ it('mixes sessions and practice on the same and different days', () => {+ // 26th: practice only, 27th: session only, 28th: both → 3 consecutive days.+ const r = computeUnifiedStreak(+ [rec('2026-06-27', 70), rec('2026-06-28', 88)],+ [{ date: '2026-06-26' }, { date: '2026-06-28T10:00:00.000Z' }],+ '2026-06-28'+ );+ expect(r.current).toBe(3);+ expect(r.lastActiveDate).toBe('2026-06-28');+ });++ it('is DST-safe across a spring-forward boundary', () => {+ // US DST 2026 begins 2026-03-08; day arithmetic must not drop/duplicate a day.+ const days = ['2026-03-06', '2026-03-07', '2026-03-08', '2026-03-09'];+ const r = computeUnifiedStreak(days.map(d => rec(d, 50)), [], '2026-03-09');+ expect(r.current).toBe(4);+ expect(r.longest).toBe(4);+ // ymdShift steps exactly one calendar day even across the transition.+ expect(ymdShift('2026-03-08', -1)).toBe('2026-03-07');+ expect(ymdShift('2026-03-08', 1)).toBe('2026-03-09');+ });++ it('empty activity yields a zero streak', () => {+ expect(computeUnifiedStreak([], [], '2026-06-28')).toEqual({+ current: 0, longest: 0, lastActiveDate: null,+ });+ });+});diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex b6ef7ceb44..de45e27a4a 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -373,6 +373,24 @@ export const morseLevelUpdateSchema = z.object({}).optional(),});+// =============================================================================+// PROGRESS DASHBOARD QUERY (issue #2091)+// =============================================================================++// GET /post/progress query params. `days` clamps like /post/stats: a NaN /+// missing value falls back to the 90-day default, a value >365 is clamped, and+// <=0 means all-time (0). `bucket` is forward-compat (only day buckets today).+export const postProgressQuerySchema = z.object({+ days: z.preprocess((v) => {+ if (v == null || v === '') return 90;+ const n = parseInt(v, 10);+ if (Number.isNaN(n)) return 90;+ if (n <= 0) return 0;+ return Math.min(n, 365);+ }, z.number().int()),+ bucket: z.enum(['day']).optional().default('day'),+});+// Training log entry submissionexport const trainingEntrySchema = z.object({module: z.string(),diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.jsindex d0211a1450..374e5338d6 100644--- a/server/routes/meatspacePostRoutes.js+++ b/server/routes/meatspacePostRoutes.js@@ -23,6 +23,7 @@ import {LLM_DRILL_TYPES,MEMORY_DRILL_TYPES,trainingEntrySchema,+ postProgressQuerySchema,} from '../lib/postValidation.js';import * as postService from '../services/meatspacePost.js';import * as memoryService from '../services/meatspacePostMemory.js';@@ -109,6 +110,18 @@ router.get('/post/stats', asyncHandler(async (req, res) => {res.json(stats);}));+/**+ * GET /api/meatspace/post/progress+ * Unified time-series progress: per-day score/accuracy/response-time/minutes+ * buckets, per-domain and per-drill series, totals, ONE unified streak (scored+ * sessions OR training-log activity), and a mastery block (issue #2091).+ */+router.get('/post/progress', asyncHandler(async (req, res) => {+ const { days, bucket } = validateRequest(postProgressQuerySchema, req.query);+ const progress = await postService.getPostProgress({ days, bucket });+ res.json(progress);+}));+/*** POST /api/meatspace/post/drill* Generate a drill with questions and expected answers.diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 20ea9806a5..01c656b8b6 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -14,7 +14,14 @@ import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } fromimport { adaptDrillConfig, ADAPTIVE_SPECS, ADAPTIVE_DEFAULTS } from '../lib/postAdaptive.js';import { resolveMultiplicationLevel, MASTERY_DEFAULTS } from '../lib/postMultiplicationLadder.js';import { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } from './meatspacePostCognitive.js';-import { advanceScheduleFromSession, mergeMasteryFromSession } from './meatspacePostMemory.js';+import { advanceScheduleFromSession, mergeMasteryFromSession, getMemoryItems, getDueMemoryItems } from './meatspacePostMemory.js';+import { getAllTrainingEntries } from './meatspacePostTraining.js';+import { computePostStreaks, computeUnifiedStreak, ymdToUTC } from '../lib/postStreak.js';++// Re-export the shared streak helper so existing importers of+// `computePostStreaks` from this module keep working after it moved to+// server/lib/postStreak.js (single implementation — see that file).+export { computePostStreaks };const MEATSPACE_DIR = PATHS.meatspace;const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');@@ -256,59 +263,6 @@ export async function submitPostSession(sessionData) {return session;}-// Local-date arithmetic on `YYYY-MM-DD` strings via UTC midnight so day math-// never drifts across DST boundaries (the activity-streak bug class).-function ymdToUTC(s) {- const [y, m, d] = s.split('-').map(Number);- return Date.UTC(y, m - 1, d);-}-function ymdShift(s, deltaDays) {- return new Date(ymdToUTC(s) + deltaDays * 86400000).toISOString().split('T')[0];-}--/**- * Compute POST practice streaks from session records. Pure (takes `todayStr`- * explicitly) so it's unit-testable without faking the clock.- *- * - `completedToday` — at least one session dated today- * - `currentStreak` — consecutive days with a session counting back from- * today; a not-yet-done today does NOT break the streak as long as yesterday- * has one (grace window), mirroring `usage.js` `calculateStreak`- * - `longestStreak` — longest consecutive-day run in all history- * - `lastDate` — most recent session date (null if never practiced)- * - `todayScore` — best session score recorded today (null if none)- */-export function computePostStreaks(sessions, todayStr) {- const dateSet = new Set((sessions || []).map(s => s?.date).filter(Boolean));- const dates = Array.from(dateSet).sort();- const completedToday = dateSet.has(todayStr);- const lastDate = dates.length ? dates[dates.length - 1] : null;-- const todayScores = (sessions || [])- .filter(s => s?.date === todayStr && typeof s?.score === 'number')- .map(s => s.score);- const todayScore = todayScores.length ? Math.max(...todayScores) : null;-- let longestStreak = 0;- let run = 0;- let prev = null;- for (const d of dates) {- run = prev && ymdToUTC(d) - ymdToUTC(prev) === 86400000 ? run + 1 : 1;- if (run > longestStreak) longestStreak = run;- prev = d;- }-- // Anchor the current streak at today, or yesterday if today isn't done yet.- let cursor = completedToday ? todayStr : ymdShift(todayStr, -1);- let currentStreak = 0;- while (dateSet.has(cursor)) {- currentStreak += 1;- cursor = ymdShift(cursor, -1);- }-- return { completedToday, currentStreak, longestStreak, lastDate, todayScore };-}-/*** Answered-only accuracy for a scored task, tolerant of legacy sessions that* predate the persisted `accuracy` field (issue #2094). Order: the stored value@@ -367,6 +321,21 @@ export function deriveTaskCompletion(task) {return qs.filter(q => q?.answered != null).length / qs.length;}+/**+ * Mean response time (ms) for a scored task, tolerant of legacy sessions that+ * predate the persisted `avgResponseMs` field (issue #2094): the stored value+ * first, else the mean of the answered questions' `responseMs` (>0 only), else+ * `null` — never NaN. Used by progress aggregation so the "getting faster"+ * trend reads cleanly across old and new session shapes.+ */+export function deriveTaskAvgResponseMs(task) {+ if (typeof task?.avgResponseMs === 'number' && !Number.isNaN(task.avgResponseMs)) return task.avgResponseMs;+ const qs = Array.isArray(task?.questions) ? task.questions : [];+ const timed = qs.filter(q => (q?.responseMs || 0) > 0);+ if (!timed.length) return null;+ return Math.round(timed.reduce((sum, q) => sum + q.responseMs, 0) / timed.length);+}+export async function getPostStats(days = 30) {const sessions = await getPostSessions();// Streaks are computed over ALL history, independent of the stats window.@@ -427,6 +396,182 @@ export async function getPostStats(days = 30) {return { days, sessionCount: recent.length, overall, byModule, byDrill, byDrillCount, byDrillAccuracy, byDrillCompletion, ...streaks };}+// =============================================================================+// PROGRESS (time-series) — issue #2091+// =============================================================================++function mean(list) {+ return list.length ? list.reduce((a, b) => a + b, 0) / list.length : null;+}++// Accumulate one task's metrics into a `key -> (date -> bucket)` map, so a+// domain/drill series can aggregate multiple same-day tasks into one point.+function pushMetricSeries(map, key, date, score, accuracy, avgResponseMs) {+ if (key == null) return;+ let byDate = map.get(key);+ if (!byDate) { byDate = new Map(); map.set(key, byDate); }+ let bucket = byDate.get(date);+ if (!bucket) { bucket = { scores: [], accs: [], resp: [] }; byDate.set(date, bucket); }+ if (typeof score === 'number' && !Number.isNaN(score)) bucket.scores.push(score);+ if (accuracy != null) bucket.accs.push(accuracy);+ if (avgResponseMs != null) bucket.resp.push(avgResponseMs);+}++// Finalize a `key -> (date -> bucket)` map into `key -> [{ date, score,+// accuracy, avgResponseMs }]`, chronologically sorted.+function finalizeMetricSeries(map) {+ const out = {};+ for (const [key, byDate] of map) {+ out[key] = Array.from(byDate.entries())+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([date, b]) => {+ const acc = mean(b.accs);+ const resp = mean(b.resp);+ const score = mean(b.scores);+ return {+ date,+ score: score == null ? null : Math.round(score),+ accuracy: acc == null ? null : acc,+ avgResponseMs: resp == null ? null : Math.round(resp),+ };+ });+ }+ return out;+}++/**+ * Time-series progress across scored sessions, the training log, and memory+ * mastery — the data behind the unified Progress dashboard (issue #2091).+ *+ * - `series.byDay` per-day buckets (same-day sessions aggregated) of score,+ * accuracy, avg response time, minutes, and session count.+ * - `series.byDomain` per-day series keyed by coarse module (`mental-math`, …).+ * - `series.byDrill` per-day series keyed by drill type (`multiplication`, …).+ * - `totals` minutes trained (sessions + practice), session count,+ * practice-entry count over the window.+ * - `streak` ONE unified streak (sessions OR training-log activity),+ * computed over ALL history like `getPostStats`.+ * - `mastery` multiplication ladder rung + memory items (mastery/due).+ *+ * Accuracy/speed are reported separately (issue #2094): the persisted per-task+ * `accuracy`/`avgResponseMs` are preferred, with a per-question derivation+ * fallback for legacy sessions.+ */+export async function getPostProgress({ days = 90 } = {}) {+ const todayStr = new Date().toISOString().split('T')[0];+ const window = Number.isFinite(days) && days > 0 ? Math.min(days, 365) : 0;++ const allSessions = await getPostSessions();+ const allTraining = await getAllTrainingEntries();++ // Unified streak is computed over ALL history, independent of the window.+ const streak = computeUnifiedStreak(allSessions, allTraining, todayStr);++ let cutoffStr = null;+ if (window > 0) {+ cutoffStr = new Date(ymdToUTC(todayStr) - window * 86400000).toISOString().split('T')[0];+ }+ const sessions = cutoffStr ? allSessions.filter(s => (s.date || '') >= cutoffStr) : allSessions;+ const training = cutoffStr ? allTraining.filter(e => String(e.date || '').split('T')[0] >= cutoffStr) : allTraining;++ // Per-day buckets for the headline trends, plus per-domain/per-drill series.+ const dayMap = new Map(); // date -> { scores, accs, resp, minutes, sessions }+ const domainMap = new Map(); // module -> Map(date -> metric bucket)+ const drillMap = new Map(); // type -> Map(date -> metric bucket)++ const ensureDay = (date) => {+ let d = dayMap.get(date);+ if (!d) { d = { scores: [], accs: [], resp: [], minutes: 0, sessions: 0 }; dayMap.set(date, d); }+ return d;+ };++ for (const s of sessions) {+ const date = s.date;+ if (!date) continue;+ const day = ensureDay(date);+ day.sessions += 1;+ day.minutes += (s.durationMs || 0) / 60000;+ if (typeof s.score === 'number' && !Number.isNaN(s.score)) day.scores.push(s.score);++ const sessionAccs = [];+ const sessionResp = [];+ for (const task of s.tasks || []) {+ const acc = deriveTaskAccuracy(task);+ const resp = deriveTaskAvgResponseMs(task);+ if (acc != null) sessionAccs.push(acc);+ if (resp != null) sessionResp.push(resp);+ pushMetricSeries(domainMap, task.module, date, task.score, acc, resp);+ pushMetricSeries(drillMap, task.type, date, task.score, acc, resp);+ }+ const sAcc = mean(sessionAccs);+ if (sAcc != null) day.accs.push(sAcc);+ const sResp = mean(sessionResp);+ if (sResp != null) day.resp.push(sResp);+ }++ // Practice time (Morse / memory) folds into each day's minutes — a practice-+ // only day still shows time-in-training even with no scored session.+ for (const e of training) {+ const date = String(e.date || '').split('T')[0];+ if (!date) continue;+ ensureDay(date).minutes += (e.totalMs || 0) / 60000;+ }++ const byDay = Array.from(dayMap.entries())+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([date, d]) => {+ const score = mean(d.scores);+ const acc = mean(d.accs);+ const resp = mean(d.resp);+ return {+ date,+ score: score == null ? null : Math.round(score),+ accuracy: acc == null ? null : acc,+ avgResponseMs: resp == null ? null : Math.round(resp),+ minutes: Math.round(d.minutes),+ sessions: d.sessions,+ };+ });++ const sessionMs = sessions.reduce((sum, s) => sum + (s.durationMs || 0), 0);+ const trainingMs = training.reduce((sum, e) => sum + (e.totalMs || 0), 0);++ // Mastery block: multiplication ladder rung + per-item memory mastery/due.+ const mulProgress = await getMultiplicationProgress();+ const memoryItems = await getMemoryItems();+ const dueItems = await getDueMemoryItems();+ const dueIds = new Set(dueItems.map(i => i.id));++ return {+ days: window,+ series: {+ byDay,+ byDomain: finalizeMetricSeries(domainMap),+ byDrill: finalizeMetricSeries(drillMap),+ },+ totals: {+ minutesTrained: Math.round((sessionMs + trainingMs) / 60000),+ sessions: sessions.length,+ practiceEntries: training.length,+ },+ streak,+ mastery: {+ multiplication: {+ level: mulProgress.level,+ description: mulProgress.label,+ floorLevel: mulProgress.floorLevel,+ },+ memoryItems: memoryItems.map(it => ({+ id: it.id,+ title: it.title,+ overallPct: it.mastery?.overallPct ?? 0,+ // 0/1 per item so the client can sum to a total "due" count.+ dueCount: dueIds.has(it.id) ? 1 : 0,+ })),+ },+ };+}+// =============================================================================// DRILL GENERATORS (pure functions)// =============================================================================diff --git a/server/services/meatspacePostProgress.test.js b/server/services/meatspacePostProgress.test.jsnew file mode 100644index 0000000000..6b64c786fa--- /dev/null+++ b/server/services/meatspacePostProgress.test.js@@ -0,0 +1,137 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Route file reads by path so getPostProgress sees sessions, the training log,+// and memory items independently (all share the same mocked fileUtils).+const state = { sessions: [], training: [], memoryItems: [] };++vi.mock('../lib/fileUtils.js', () => ({+ atomicWrite: vi.fn().mockResolvedValue(undefined),+ PATHS: { data: '/tmp/test-data', meatspace: '/tmp/test-meatspace' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ readJSONFile: vi.fn((path, defaultValue) => {+ if (typeof path === 'string') {+ if (path.includes('post-sessions')) return Promise.resolve({ sessions: state.sessions });+ if (path.includes('post-training-log')) return Promise.resolve({ entries: state.training });+ if (path.includes('memory-items')) return Promise.resolve({ items: state.memoryItems });+ }+ return Promise.resolve(defaultValue);+ }),+}));++import { getPostProgress } from './meatspacePost.js';+import { postProgressQuerySchema } from '../lib/postValidation.js';++const mathTask = (score, questions) => ({ module: 'mental-math', type: 'multiplication', score, questions });+const q = (correct, responseMs = 2000) => ({ prompt: '2 x 3', answered: correct ? 6 : 1, correct, responseMs });++function todayStr() { return new Date().toISOString().split('T')[0]; }+function daysAgo(n) { return new Date(Date.now() - n * 86400000).toISOString().split('T')[0]; }++beforeEach(() => {+ state.sessions = [];+ state.training = [];+ state.memoryItems = [];+});++describe('getPostProgress bucketing', () => {+ it('aggregates same-day sessions into one byDay bucket', async () => {+ const d = todayStr();+ state.sessions = [+ { date: d, durationMs: 60000, score: 80, tasks: [mathTask(80, [q(true), q(true), q(false)])] },+ { date: d, durationMs: 120000, score: 60, tasks: [mathTask(60, [q(true), q(false)])] },+ ];+ const p = await getPostProgress({ days: 90 });+ // Two sessions on one day collapse to a single point (no x-axis collision).+ expect(p.series.byDay).toHaveLength(1);+ const bucket = p.series.byDay[0];+ expect(bucket.date).toBe(d);+ expect(bucket.sessions).toBe(2);+ expect(bucket.score).toBe(70); // (80 + 60) / 2+ expect(bucket.minutes).toBe(3); // (1 + 2) minutes+ expect(bucket.accuracy).toBeGreaterThan(0);+ });++ it('respects the window cutoff', async () => {+ state.sessions = [+ { date: daysAgo(100), durationMs: 60000, score: 50, tasks: [mathTask(50, [q(true)])] },+ { date: daysAgo(2), durationMs: 60000, score: 90, tasks: [mathTask(90, [q(true)])] },+ ];+ const p = await getPostProgress({ days: 30 });+ expect(p.series.byDay).toHaveLength(1);+ expect(p.series.byDay[0].date).toBe(daysAgo(2));+ expect(p.totals.sessions).toBe(1);+ });++ it('returns an empty-but-shaped result for an empty window', async () => {+ const p = await getPostProgress({ days: 30 });+ expect(p.series.byDay).toEqual([]);+ expect(p.series.byDomain).toEqual({});+ expect(p.series.byDrill).toEqual({});+ expect(p.totals).toEqual({ minutesTrained: 0, sessions: 0, practiceEntries: 0 });+ expect(p.streak).toEqual({ current: 0, longest: 0, lastActiveDate: null });+ });++ it('counts practice-only days toward minutes and the unified streak', async () => {+ const d = todayStr();+ state.training = [+ { date: d, module: 'morse', drillType: 'morse-copy', questionCount: 5, correctCount: 4, totalMs: 90000 },+ ];+ const p = await getPostProgress({ days: 30 });+ expect(p.totals.practiceEntries).toBe(1);+ expect(p.totals.minutesTrained).toBe(2); // 90s ≈ 2 min (rounded)+ // A practice-only day (no scored session) still extends the streak.+ expect(p.streak.current).toBe(1);+ const day = p.series.byDay.find(b => b.date === d);+ expect(day.sessions).toBe(0);+ expect(day.score).toBeNull();+ expect(day.minutes).toBe(2);+ });++ it('builds per-domain and per-drill series keyed correctly', async () => {+ const d = todayStr();+ state.sessions = [+ { date: d, durationMs: 60000, score: 80, tasks: [mathTask(80, [q(true), q(true)])] },+ ];+ const p = await getPostProgress({ days: 90 });+ expect(p.series.byDomain['mental-math']).toBeDefined();+ expect(p.series.byDrill['multiplication']).toBeDefined();+ expect(p.series.byDrill['multiplication'][0].date).toBe(d);+ });++ it('includes a mastery block with the multiplication ladder and memory items', async () => {+ state.memoryItems = [+ { id: 'm1', title: 'Elements', mastery: { overallPct: 42 }, schedule: { nextReview: '2000-01-01T00:00:00.000Z' } },+ ];+ const p = await getPostProgress({ days: 90 });+ expect(p.mastery.multiplication).toHaveProperty('level');+ expect(p.mastery.multiplication).toHaveProperty('floorLevel');+ // The memory service prepends a built-in item, so find ours by id.+ const mine = p.mastery.memoryItems.find(i => i.id === 'm1');+ expect(mine).toMatchObject({ id: 'm1', title: 'Elements', overallPct: 42 });+ // Past-due nextReview → dueCount 1.+ expect(mine.dueCount).toBe(1);+ });+});++describe('postProgressQuerySchema clamping', () => {+ it('defaults days to 90 when missing or NaN', () => {+ expect(postProgressQuerySchema.parse({}).days).toBe(90);+ expect(postProgressQuerySchema.parse({ days: 'abc' }).days).toBe(90);+ expect(postProgressQuerySchema.parse({ days: '' }).days).toBe(90);+ });++ it('clamps days above 365', () => {+ expect(postProgressQuerySchema.parse({ days: '1000' }).days).toBe(365);+ });++ it('treats <=0 as all-time (0)', () => {+ expect(postProgressQuerySchema.parse({ days: '0' }).days).toBe(0);+ expect(postProgressQuerySchema.parse({ days: '-5' }).days).toBe(0);+ });++ it('passes through a valid in-range value and defaults bucket to day', () => {+ const parsed = postProgressQuerySchema.parse({ days: '30' });+ expect(parsed.days).toBe(30);+ expect(parsed.bucket).toBe('day');+ });+});diff --git a/server/services/meatspacePostTraining.js b/server/services/meatspacePostTraining.jsindex 098e272e71..6655149ef7 100644--- a/server/services/meatspacePostTraining.js+++ b/server/services/meatspacePostTraining.js@@ -8,6 +8,7 @@import { join } from 'path';import { randomUUID } from 'crypto';import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';+import { computePostStreaks } from '../lib/postStreak.js';const MEATSPACE_DIR = PATHS.meatspace;const TRAINING_LOG_FILE = join(MEATSPACE_DIR, 'post-training-log.json');@@ -49,53 +50,41 @@ export async function submitTrainingEntry(entry) {/*** Get training stats: per-drill practice counts, streaks, recent activity.+ *+ * Streaks come from the SHARED `computePostStreaks` (server/lib/postStreak.js) —+ * the same DST-safe helper the scored-session streak uses — so the training+ * streak can no longer disagree with the POST streak for identical activity+ * (issue #2091). Like `getPostStats`, the streak is computed over ALL history,+ * independent of the stats window; only the per-drill breakdown is windowed.*/export async function getTrainingStats(days = 30) {const data = await loadTrainingLog();- let entries = data.entries;+ const allEntries = data.entries;+ let entries = allEntries;if (days > 0) {const cutoff = new Date();cutoff.setDate(cutoff.getDate() - days);const cutoffStr = cutoff.toISOString().split('T')[0];- entries = entries.filter(e => e.date >= cutoffStr);+ entries = allEntries.filter(e => String(e.date || '').split('T')[0] >= cutoffStr);}- // Group by drill type+ // Group by drill type (windowed)const byDrill = {};for (const e of entries) {const key = `${e.module}:${e.drillType}`;if (!byDrill[key]) byDrill[key] = { practiceCount: 0, totalCorrect: 0, totalQuestions: 0, totalMs: 0, dates: new Set() };byDrill[key].practiceCount++;- byDrill[key].totalCorrect += e.correctCount;- byDrill[key].totalQuestions += e.questionCount;- byDrill[key].totalMs += e.totalMs;- byDrill[key].dates.add(e.date);+ byDrill[key].totalCorrect += e.correctCount || 0;+ byDrill[key].totalQuestions += e.questionCount || 0;+ byDrill[key].totalMs += e.totalMs || 0;+ byDrill[key].dates.add(String(e.date || '').split('T')[0]);}- // Compute streaks (consecutive days of practice)- const dateSet = new Set(entries.map(e => e.date));- let currentStreak = 0;- if (dateSet.size > 0) {- const today = new Date().toISOString().split('T')[0];- const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0];- // Count backwards from today/yesterday- let checkDate = dateSet.has(today) ? today : dateSet.has(yesterday) ? yesterday : null;- if (checkDate) {- currentStreak = 1;- let ts = new Date(checkDate + 'T00:00:00Z').getTime();- while (true) {- ts -= 86400000;- const prev = new Date(ts).toISOString().split('T')[0];- if (dateSet.has(prev)) {- currentStreak++;- } else {- break;- }- }- }- }- const activeDays = dateSet.size;+ // Unified streak semantics (shared helper, ALL history, grace window).+ const todayStr = new Date().toISOString().split('T')[0];+ const { currentStreak, longestStreak } = computePostStreaks(allEntries, todayStr);+ const activeDays = new Set(entries.map(e => String(e.date || '').split('T')[0])).size;// Summarizeconst summary = {};@@ -113,6 +102,7 @@ export async function getTrainingStats(days = 30) {activeDays,totalEntries: entries.length,currentStreak,+ longestStreak,byDrill: summary,};}@@ -125,3 +115,13 @@ export async function getTrainingEntries(limit = 20) {if (!limit) return data.entries.slice().reverse();return data.entries.slice(-limit).reverse();}++/**+ * All training-log entries in chronological (append) order — the raw feed the+ * unified progress aggregation reads (both meatspacePostTraining and+ * meatspacePostMemory practice write to the same `post-training-log.json`).+ */+export async function getAllTrainingEntries() {+ const data = await loadTrainingLog();+ return data.entries;+}