Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-2100]): POST launcher goals, "up next" recommendations, interleaved sessions

Adam Eivyfca6950d15bc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 596f9f2d46..cc14412b3b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -31,7 +31,7 @@
## POST Training
-- **[issue-2096] POST now checks whether you *still* know a skill, not just that you once did.** Element and chunk mastery is now decay-aware: it reads your most recent attempts (a rolling window) instead of an all-time tally, so a recent run of misses actually lowers your mastery and an unlucky early wrong answer no longer haunts you forever. On top of that, POST tracks the skills you've mastered but stopped practicing — multiplication rungs below your current level, cognitive rungs you've passed — and schedules a light "maintenance rep" for them on an expanding 7 → 30 → 90-day cadence. When one comes due, a Quick session quietly mixes in one or two labeled review reps; passing pushes the next check further out, while failing marks the skill "needs refresh" and re-checks it sooner (it never demotes a level you've earned). The Progress dashboard gains a Skill Retention panel showing each skill as fresh / due for review / needs refresh, plus a 90-day retention percentage. Nothing appears until you've actually mastered something, so fresh installs and existing data stay quiet until there's a skill worth re-verifying.
+- **[issue-2100] POST now tells you what to practice next — and works toward goals you set.** The launcher gained an **"Up next"** panel: a prioritized list of what to work on — memory items due for review, mastered skills due for a maintenance rep, your weakest recent skill, and laddered drills you're close to leveling up (e.g. "2 more clean reps to reach 2-back", "advance to Koch level 6") — each a one-click deep link into the exact drill or mode. You can set optional **goals** (daily minutes, sessions per week, streak length, Morse WPM) on the config page; the launcher and the dashboard's Daily POST widget show your progress against them, and everything hides cleanly if you set none. A **Full POST** now interleaves your drills across domains (math → cognitive → memory → verbal) instead of running all of one type in a row, and a **Quick 5 Min** session leads with your top recommendation instead of a purely random pick. As always, AI-backed wordplay drills are never auto-added to a default session — those stay opt-in. Element and chunk mastery is now decay-aware: it reads your most recent attempts (a rolling window) instead of an all-time tally, so a recent run of misses actually lowers your mastery and an unlucky early wrong answer no longer haunts you forever. On top of that, POST tracks the skills you've mastered but stopped practicing — multiplication rungs below your current level, cognitive rungs you've passed — and schedules a light "maintenance rep" for them on an expanding 7 → 30 → 90-day cadence. When one comes due, a Quick session quietly mixes in one or two labeled review reps; passing pushes the next check further out, while failing marks the skill "needs refresh" and re-checks it sooner (it never demotes a level you've earned). The Progress dashboard gains a Skill Retention panel showing each skill as fresh / due for review / needs refresh, plus a 90-day retention percentage. Nothing appears until you've actually mastered something, so fresh installs and existing data stay quiet until there's a skill worth re-verifying.
- **[issue-2098] POST sessions survive a refresh, are shareable by link, and can't double-record.** A POST session no longer lives only in the current page: refreshing mid-drill now resumes the same run (same drill queue, same completed results, right where you left off), and refreshing on the results screen keeps your results. Every saved session gets its own shareable, bookmarkable address (`/post/session/<id>`) — History rows open it, and it shows the same per-drill mistake review as the just-finished screen; a stale or deleted link shows a clear "session not found" message. Wordplay game modes now live in the URL too (`/post/wordplay/<mode>`), so a mode is deep-linkable and refresh-safe. Saving a session is now idempotent: if the network drops and the app retries, you get one record, not two — and a hiccup in the after-save bookkeeping (spaced-repetition scheduling for memory drills) can never fail an already-saved session.
- **[issue-2095] Cognitive drills now level up as you master them, instead of training at one fixed difficulty forever.** N-back, digit span, Schulte table, mental rotation, and Stroop each climb their own mastery-gated ladder: n-back ramps 1-back → 2-back → 3-back and then squeezes the flash speed (2500 → 2000 → 1600ms); digit span grows its span and adds backward recall; Schulte grows the grid 4×4 → 6×6; mental rotation and Stroop add trials. You advance a rung only after sustained high accuracy at the current one (n-back uses the fair signal-detection accuracy, so never-pressing can't bank a level), and you're never demoted below a rung you've earned. Each drill now stamps its difficulty into your saved results, so progress is tracked per level (a 2-back run no longer pools with a 3-back run). The config page shows each drill's current rung and progress toward the next, with a per-drill "Progressive" toggle (on by default) — turn it off to set the knobs by hand, including the previously-hidden n-back stimulus speed and digit-span show time. Reaction time stays a fixed measurement. On by default for existing installs with no migration.
- **[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. Your practice streak is now a single number counting *any* active day — a scored session **or** a Morse/memory practice — so the launcher, the Morse trainer, the Progress page, and the dashboard widgets all show the same streak instead of three different ones. 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.
diff --git a/client/src/components/DailyPostWidget.jsx b/client/src/components/DailyPostWidget.jsx
index 8d4cb0815a..b25261ddf1 100644
--- a/client/src/components/DailyPostWidget.jsx
+++ b/client/src/components/DailyPostWidget.jsx
@@ -1,20 +1,35 @@
import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
-import { Brain, ArrowRight } from 'lucide-react';
+import { Brain, ArrowRight, Compass } from 'lucide-react';
import * as api from '../services/api';
import { streakGlyph } from '../lib/streakGlyph.js';
+import { computeGoalProgress } from './meatspace/post/constants';
// 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
-// launcher. Self-fetches its stats (the dashboardState payload doesn't carry
-// POST data), mirroring DeathClockWidget.
+// completion status, the current practice streak, the top "what to practice
+// next" recommendation, and goal progress — plus a one-click way into the
+// launcher. Self-fetches (the dashboardState payload doesn't carry POST data),
+// mirroring DeathClockWidget.
export default function DailyPostWidget() {
const [stats, setStats] = useState(null);
+ const [statsWeek, setStatsWeek] = useState(null);
+ const [config, setConfig] = useState(null);
+ const [topRec, setTopRec] = useState(null);
const [loaded, setLoaded] = useState(false);
const fetchData = useCallback(async () => {
- const data = await api.getPostStats().catch(() => null);
+ // Recommendations/config/week-stats are best-effort — a failure just hides
+ // the extra rows; the streak card still renders from `stats`.
+ const [data, week, cfg, recs] = await Promise.all([
+ api.getPostStats().catch(() => null),
+ api.getPostStats(7).catch(() => null),
+ api.getPostConfig().catch(() => null),
+ api.getPostRecommendations(1).catch(() => null),
+ ]);
setStats(data);
+ setStatsWeek(week);
+ setConfig(cfg);
+ setTopRec(recs?.recommendations?.[0] || null);
setLoaded(true);
}, []);
@@ -29,6 +44,14 @@ export default function DailyPostWidget() {
const completedToday = !!stats?.completedToday;
const todayScore = stats?.todayScore;
+ // Widget goal metrics: streak + this week's sessions (no today-minutes /
+ // Morse-WPM fetch here — computeGoalProgress omits goals whose metric is
+ // unavailable, so those simply don't render on the compact widget).
+ const goalRows = computeGoalProgress(config?.goals, {
+ currentStreak: streak,
+ weekSessions: statsWeek?.sessionCount ?? 0,
+ }).slice(0, 2);
+
return (
<Link
to="/post/launcher"
@@ -70,6 +93,28 @@ export default function DailyPostWidget() {
</div>
)}
</div>
+
+ {/* Top "what to practice next" recommendation (issue #2100). */}
+ {topRec && (
+ <div className="mt-3 flex items-start gap-2 pt-3 border-t border-port-border">
+ <Compass size={14} className="text-port-accent mt-0.5 shrink-0" />
+ <div className="min-w-0">
+ <div className="text-xs font-medium text-gray-400">Up next</div>
+ <div className="text-sm text-white truncate">{topRec.title}</div>
+ </div>
+ </div>
+ )}
+
+ {/* Goal progress chips (issue #2100) — only goals with a known metric. */}
+ {goalRows.length > 0 && (
+ <div className="mt-3 flex flex-wrap gap-x-3 gap-y-1 text-xs">
+ {goalRows.map(g => (
+ <span key={g.key} className={g.met ? 'text-port-success' : 'text-gray-400'}>
+ {g.label}: <span className="font-mono">{g.current}/{g.target}</span>
+ </span>
+ ))}
+ </div>
+ )}
</Link>
);
}
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsx
index b12d665285..9ab6803b56 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx
@@ -1,11 +1,46 @@
import { useState, useEffect } from 'react';
-import { Zap, History, Settings, Play, Brain, BookOpen, Dumbbell, Timer, Radio, Target, TrendingUp, TrendingDown, Minus } from 'lucide-react';
-import { getProviders, getPostReviewReps } from '../../../services/api';
+import { Link } from 'react-router-dom';
+import { Zap, History, Settings, Play, Brain, BookOpen, Dumbbell, Timer, Radio, Target, TrendingUp, TrendingDown, Minus, Compass, ArrowRight } from 'lucide-react';
+import { getProviders, getPostReviewReps, getPostRecommendations } from '../../../services/api';
import { FormField } from '../../ui/FormField';
import { isApiProvider } from '../../../utils/providers';
-import { DOMAINS, DRILL_TO_DOMAIN, DRILL_LABELS, computeDomainAverages } from './constants';
+import { DOMAINS, DRILL_TO_DOMAIN, DRILL_LABELS, computeDomainAverages, computeGoalProgress } from './constants';
import { streakGlyph } from '../../../lib/streakGlyph.js';
+// Canonical domain visiting order for interleaved "Full POST" composition
+// (issue #2100): alternate domains — math → cognitive → memory → verbal — so a
+// session is spaced/varied rather than blocked (all math, then all cognitive).
+// Domains not listed here interleave after, in first-seen order.
+export const INTERLEAVE_DOMAIN_ORDER = ['math', 'cognitive', 'memory', 'verbal', 'wordplay', 'imagination'];
+
+/**
+ * Round-robin interleave drill configs by their `domain` tag: one drill from
+ * each domain per round, in INTERLEAVE_DOMAIN_ORDER, until every drill is
+ * placed. Preserves per-domain input order. Pure — exported for unit tests.
+ */
+export function interleaveByDomain(drills, order = INTERLEAVE_DOMAIN_ORDER) {
+ const groups = new Map();
+ for (const d of drills || []) {
+ const key = d.domain || 'other';
+ if (!groups.has(key)) groups.set(key, []);
+ groups.get(key).push(d);
+ }
+ const domainOrder = [
+ ...order.filter(k => groups.has(k)),
+ ...[...groups.keys()].filter(k => !order.includes(k)),
+ ];
+ const lengths = [...groups.values()].map(g => g.length);
+ const maxLen = lengths.length ? Math.max(...lengths) : 0;
+ const result = [];
+ for (let round = 0; round < maxLen; round++) {
+ for (const key of domainOrder) {
+ const list = groups.get(key);
+ if (round < list.length) result.push(list[round]);
+ }
+ }
+ return result;
+}
+
const scoreColorClass = (score) =>
score >= 80 ? 'text-port-success' : score >= 50 ? 'text-port-warning' : 'text-port-error';
@@ -40,10 +75,15 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
// until a skill is mastered and its review interval elapses; a load failure
// silently degrades to a plain Quick session.
const [reviewReps, setReviewReps] = useState([]);
+ // Ordered "what to practice next" recommendations (issue #2100). A load
+ // failure silently degrades to an empty list (the panel hides). The top
+ // recommendation also biases the Quick session's drill picks.
+ const [recommendations, setRecommendations] = useState([]);
useEffect(() => {
getProviders().then(p => setProviders((p || []).filter(pr => pr.enabled && isApiProvider(pr)))).catch(err => console.warn('⚠️ Failed to load providers: ' + err.message));
getPostReviewReps(2).then(r => setReviewReps(r?.reps || [])).catch(() => setReviewReps([]));
+ getPostRecommendations().then(r => setRecommendations(r?.recommendations || [])).catch(() => setRecommendations([]));
}, []);
if (!config) {
@@ -93,6 +133,7 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
function handleStart() {
const mathConfigs = enabledMathDrills.map(([type, cfg]) => ({
type,
+ domain: DRILL_TO_DOMAIN[type],
config: {
steps: cfg.steps,
count: cfg.count,
@@ -108,6 +149,7 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
const llmConfigs = enabledLlmDrills.map(([type, cfg]) => ({
type,
+ domain: DRILL_TO_DOMAIN[type],
config: { count: cfg.count || 5 },
timeLimitSec: cfg.timeLimitSec || 120,
providerId: cfg.providerId || llmProviderId,
@@ -116,12 +158,17 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
const cognitiveConfigs = enabledCognitiveDrills.map(([type, cfg]) => ({
type,
+ domain: DRILL_TO_DOMAIN[type],
config: cognitiveDrillConfig(cfg)
// No timeLimitSec — cognitive drills are self-paced/stimulus-driven and
// never enforce a countdown (see PostCognitiveDrillRunner.jsx).
}));
- const drillConfigs = [...mathConfigs, ...llmConfigs, ...cognitiveConfigs];
+ // Interleave across domains (math → cognitive → memory → verbal …) rather
+ // than running each module blocked, so a full session spaces varied work
+ // for better retention (issue #2100). Full coverage is preserved — every
+ // enabled drill still runs, just reordered.
+ const drillConfigs = interleaveByDomain([...mathConfigs, ...llmConfigs, ...cognitiveConfigs]);
onStart(drillConfigs, buildCleanTags(tags), mode === 'train');
}
@@ -141,11 +188,26 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
}
function handleQuickSession() {
+ // Bias toward the top recommendation instead of pure random (issue #2100):
+ // if it names a drill type in an enabled domain, run that domain first and
+ // pick that exact drill; every other domain still gets a random pick.
+ const topRec = recommendations[0] || null;
+ const recDrill = topRec?.drillType || null;
+ const recDomain = recDrill ? DRILL_TO_DOMAIN[recDrill] : null;
+ const domainKeys = Object.keys(enabledDomains);
+ const orderedKeys = recDomain && enabledDomains[recDomain]
+ ? [recDomain, ...domainKeys.filter(k => k !== recDomain)]
+ : domainKeys;
+
const drillConfigs = [];
- for (const [domainKey, drills] of Object.entries(enabledDomains)) {
+ for (const domainKey of orderedKeys) {
+ const drills = enabledDomains[domainKey];
const domain = DOMAINS[domainKey];
- // Pick one random drill from this domain
- const pick = drills[Math.floor(Math.random() * drills.length)];
+ // Prefer the recommended drill in its domain; otherwise pick at random.
+ const recommendedPick = domainKey === recDomain
+ ? drills.find(d => d.type === recDrill)
+ : null;
+ const pick = recommendedPick || drills[Math.floor(Math.random() * drills.length)];
const cfg = pick.cfg;
let quickConfig;
@@ -259,6 +321,16 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
.filter(d => enabledDomains[d.key])
.reduce((weakest, d) => (!weakest || d.score < weakest.score ? d : weakest), null);
+ // Goal progress (issue #2100). Metrics come from data already on hand — no
+ // extra fetch: today's minutes from today's sessions, week sessions from the
+ // 7-day stats window, streak from the unified streak. Morse WPM has no metric
+ // here (would need a Morse fetch), so a morseWpmTarget goal is simply omitted
+ // — computeGoalProgress skips goals whose metric is unavailable.
+ const todaysSessions = (recentSessions || []).filter(s => s.date === today);
+ const todayMinutes = Math.round(todaysSessions.reduce((sum, s) => sum + (s.durationMs || 0), 0) / 60000);
+ const weekSessions = statsWeek?.sessionCount ?? 0;
+ const goalRows = computeGoalProgress(config.goals, { todayMinutes, weekSessions, currentStreak });
+
return (
<div className="space-y-6 max-w-6xl mx-auto">
{/* Header */}
@@ -317,6 +389,59 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
</div>
</div>
+ {/* Goals — progress vs the user's configured targets (issue #2100).
+ Hidden entirely until at least one goal is set. */}
+ {goalRows.length > 0 && (
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-3">Goals</h3>
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
+ {goalRows.map(g => (
+ <div key={g.key}>
+ <div className="flex items-baseline justify-between gap-1">
+ <span className="text-xs text-gray-500 truncate">{g.label}</span>
+ {g.met && <span className="text-xs text-port-success" aria-hidden="true">✓</span>}
+ </div>
+ <div className={`text-sm font-mono ${g.met ? 'text-port-success' : 'text-white'}`}>
+ {g.current}/{g.target}{g.unit ? ` ${g.unit}` : ''}
+ </div>
+ <div className="h-1.5 mt-1 rounded-full bg-port-bg overflow-hidden">
+ <div
+ className={`h-full rounded-full ${g.met ? 'bg-port-success' : 'bg-port-accent'}`}
+ style={{ width: `${g.pct}%` }}
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* "Up next" — prioritized recommendations with deep links into the
+ exact drill/mode (issue #2100). Hidden if none loaded. */}
+ {recommendations.length > 0 && (
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex items-center gap-2 mb-3">
+ <Compass size={16} className="text-port-accent" />
+ <h3 className="text-sm font-medium text-gray-300">Up next</h3>
+ </div>
+ <div className="space-y-2">
+ {recommendations.map(rec => (
+ <Link
+ key={rec.id}
+ to={rec.deepLink}
+ className="flex items-center gap-3 px-3 py-2 rounded-lg bg-port-bg border border-port-border hover:border-port-accent/60 transition-colors group"
+ >
+ <div className="min-w-0 flex-1">
+ <div className="text-sm text-white truncate">{rec.title}</div>
+ {rec.detail && <div className="text-xs text-gray-500 truncate">{rec.detail}</div>}
+ </div>
+ <ArrowRight size={14} className="text-gray-600 group-hover:text-port-accent shrink-0" />
+ </Link>
+ ))}
+ </div>
+ </div>
+ )}
+
{/* Progress analytics — streak, 7-vs-30-day trend, weakest-domain focus.
Degrades to nothing until there's scored history to summarize. */}
{hasStats && (
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
index efea2c5389..6569771f33 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
@@ -1,5 +1,17 @@
-import { describe, it, expect } from 'vitest';
-import { buildCleanTags, cognitiveSummary } from './PostSessionLauncher';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+// Mock the API surface the launcher touches on mount (providers + review reps +
+// recommendations) so the render tests are deterministic and offline.
+vi.mock('../../../services/api', () => ({
+ getProviders: vi.fn().mockResolvedValue([]),
+ getPostReviewReps: vi.fn().mockResolvedValue({ reps: [] }),
+ getPostRecommendations: vi.fn().mockResolvedValue({ recommendations: [] }),
+}));
+
+import PostSessionLauncher, { buildCleanTags, cognitiveSummary, interleaveByDomain } from './PostSessionLauncher';
+import { getPostRecommendations } from '../../../services/api';
// Pure-function tests for PostSessionLauncher's pre-submit helpers (issue
// #2102 gap #10). Both were lifted from component-body closures to module
@@ -61,3 +73,96 @@ describe('cognitiveSummary', () => {
expect(cognitiveSummary('mental-rotation', {})).toBe('');
});
});
+
+describe('interleaveByDomain (issue #2100)', () => {
+ it('round-robins one drill per domain in canonical order', () => {
+ const drills = [
+ { type: 'multiplication', domain: 'math' },
+ { type: 'powers', domain: 'math' },
+ { type: 'n-back', domain: 'cognitive' },
+ { type: 'memory-sequence', domain: 'memory' },
+ ];
+ const out = interleaveByDomain(drills).map(d => d.type);
+ // Round 0: math, cognitive, memory; round 1: math (the second math drill).
+ expect(out).toEqual(['multiplication', 'n-back', 'memory-sequence', 'powers']);
+ });
+
+ it('preserves per-domain input order', () => {
+ const drills = [
+ { type: 'a', domain: 'math' },
+ { type: 'b', domain: 'math' },
+ { type: 'c', domain: 'math' },
+ ];
+ expect(interleaveByDomain(drills).map(d => d.type)).toEqual(['a', 'b', 'c']);
+ });
+
+ it('interleaves unranked domains after the canonical ones, deterministically', () => {
+ const drills = [
+ { type: 'mystery', domain: 'zzz' },
+ { type: 'multiplication', domain: 'math' },
+ ];
+ expect(interleaveByDomain(drills).map(d => d.type)).toEqual(['multiplication', 'mystery']);
+ });
+
+ it('returns an empty array for empty input', () => {
+ expect(interleaveByDomain([])).toEqual([]);
+ expect(interleaveByDomain()).toEqual([]);
+ });
+});
+
+describe('PostSessionLauncher render (issue #2100)', () => {
+ const baseConfig = {
+ mentalMath: { enabled: true, drillTypes: { multiplication: { enabled: true, count: 10, timeLimitSec: 120 } } },
+ llmDrills: { enabled: false, drillTypes: {} },
+ cognitive: { enabled: false, drillTypes: {} },
+ goals: { streakTarget: 10 },
+ };
+ const stats = { sessionCount: 3, overall: 70, currentStreak: 4, longestStreak: 8, byDrill: { 'mental-math:multiplication': 70 } };
+
+ const renderLauncher = (props = {}) => render(
+ <MemoryRouter>
+ <PostSessionLauncher
+ config={baseConfig}
+ recentSessions={[]}
+ stats={stats}
+ statsWeek={{ sessionCount: 2 }}
+ onStart={vi.fn()}
+ onViewHistory={vi.fn()}
+ onViewConfig={vi.fn()}
+ onViewMemory={vi.fn()}
+ onViewMorse={vi.fn()}
+ {...props}
+ />
+ </MemoryRouter>,
+ );
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getPostRecommendations.mockResolvedValue({ recommendations: [] });
+ });
+
+ it('renders the "Up next" panel with working deep links', async () => {
+ getPostRecommendations.mockResolvedValue({ recommendations: [
+ { id: 'memory-due:song', kind: 'memory-due', title: 'Review "Elements"', detail: 'Due', deepLink: '/post/memory', priority: 0 },
+ { id: 'stalled:morse-copy', kind: 'stalled-progression', title: 'Morse: keep climbing', detail: 'Koch 6', deepLink: '/post/morse/copy', priority: 1 },
+ ] });
+ const { container } = renderLauncher();
+ await waitFor(() => expect(screen.getByText('Up next')).toBeTruthy());
+ expect(screen.getByText('Review "Elements"')).toBeTruthy();
+ expect(container.querySelector('a[href="/post/memory"]')).toBeTruthy();
+ expect(container.querySelector('a[href="/post/morse/copy"]')).toBeTruthy();
+ });
+
+ it('renders goal progress against a configured goal', async () => {
+ renderLauncher();
+ await waitFor(() => expect(screen.getByText('Goals')).toBeTruthy());
+ // streakTarget 10 with a 4-day streak → "4/10 d".
+ expect(screen.getByText(/4\/10/)).toBeTruthy();
+ });
+
+ it('hides the goals panel when no goals are set', async () => {
+ renderLauncher({ config: { ...baseConfig, goals: {} } });
+ await waitFor(() => expect(getPostRecommendations).toHaveBeenCalled());
+ expect(screen.queryByText('Goals')).toBeNull();
+ });
+});
diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.js
index 02f42544a8..e177a24432 100644
--- a/client/src/components/meatspace/post/constants.js
+++ b/client/src/components/meatspace/post/constants.js
@@ -152,6 +152,49 @@ export function computeDomainAverages(byDrill = {}) {
.sort((a, b) => b.score - a.score);
}
+// Practice goals (issue #2100). A goal is "set" only when its target is a
+// positive number, so an absent/legacy `goals` object (or `{}`) yields no goal
+// rows and the UI hides cleanly.
+export const GOAL_DEFS = [
+ { key: 'dailyMinutes', label: 'Minutes today', unit: 'min', metric: 'todayMinutes' },
+ { key: 'weeklySessions', label: 'Sessions this week', unit: '', metric: 'weekSessions' },
+ { key: 'streakTarget', label: 'Streak', unit: 'd', metric: 'currentStreak' },
+ { key: 'morseWpmTarget', label: 'Morse WPM', unit: 'wpm', metric: 'morseWpm' },
+];
+
+export function hasGoals(goals) {
+ if (!goals || typeof goals !== 'object') return false;
+ return GOAL_DEFS.some(({ key }) => typeof goals[key] === 'number' && goals[key] > 0);
+}
+
+/**
+ * Progress toward each set goal. `goals` is the config's `goals` block; `metrics`
+ * supplies the current values (`todayMinutes`, `weekSessions`, `currentStreak`,
+ * `morseWpm`). Returns one row per goal that's actually set AND whose current
+ * metric is available (a goal whose metric is unknown — e.g. Morse WPM with no
+ * Morse data — is skipped rather than shown as 0). Pure.
+ */
+export function computeGoalProgress(goals = {}, metrics = {}) {
+ const rows = [];
+ for (const def of GOAL_DEFS) {
+ const target = goals?.[def.key];
+ if (typeof target !== 'number' || !(target > 0)) continue;
+ const current = metrics?.[def.metric];
+ if (typeof current !== 'number' || Number.isNaN(current)) continue;
+ const pct = Math.max(0, Math.min(100, Math.round((current / target) * 100)));
+ rows.push({
+ key: def.key,
+ label: def.label,
+ unit: def.unit,
+ current: Math.round(current * 10) / 10,
+ target,
+ pct,
+ met: current >= target,
+ });
+ }
+ return rows;
+}
+
// Difficulty badge color helper
export const getDifficultyColor = (difficulty) => {
if (difficulty === 'hard') return 'bg-port-error/20 text-port-error';
diff --git a/client/src/components/meatspace/post/constants.test.js b/client/src/components/meatspace/post/constants.test.js
index 4291f2abe8..1a35ed858e 100644
--- a/client/src/components/meatspace/post/constants.test.js
+++ b/client/src/components/meatspace/post/constants.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { computeDomainAverages, domainLabel } from './constants';
+import { computeDomainAverages, domainLabel, computeGoalProgress, hasGoals } from './constants';
describe('domainLabel', () => {
it('maps known domain keys to their human label', () => {
@@ -59,3 +59,50 @@ describe('computeDomainAverages', () => {
expect(computeDomainAverages()).toEqual([]);
});
});
+
+describe('hasGoals (issue #2100)', () => {
+ it('is false for absent/empty/legacy goals', () => {
+ expect(hasGoals(undefined)).toBe(false);
+ expect(hasGoals(null)).toBe(false);
+ expect(hasGoals({})).toBe(false);
+ expect(hasGoals({ dailyMinutes: 0 })).toBe(false);
+ });
+
+ it('is true once any positive target is set', () => {
+ expect(hasGoals({ streakTarget: 10 })).toBe(true);
+ });
+});
+
+describe('computeGoalProgress (issue #2100)', () => {
+ it('reports progress for each set goal whose metric is known', () => {
+ const rows = computeGoalProgress(
+ { dailyMinutes: 20, weeklySessions: 5, streakTarget: 10 },
+ { todayMinutes: 14, weekSessions: 5, currentStreak: 6 },
+ );
+ const byKey = Object.fromEntries(rows.map(r => [r.key, r]));
+ expect(byKey.dailyMinutes.pct).toBe(70);
+ expect(byKey.dailyMinutes.met).toBe(false);
+ expect(byKey.weeklySessions.met).toBe(true);
+ expect(byKey.weeklySessions.pct).toBe(100);
+ expect(byKey.streakTarget.current).toBe(6);
+ });
+
+ it('skips goals whose metric is unavailable (e.g. Morse WPM with no data)', () => {
+ const rows = computeGoalProgress(
+ { morseWpmTarget: 15, streakTarget: 5 },
+ { currentStreak: 3 }, // no morseWpm
+ );
+ expect(rows.map(r => r.key)).toEqual(['streakTarget']);
+ });
+
+ it('clamps pct to 100 when the target is exceeded', () => {
+ const rows = computeGoalProgress({ streakTarget: 5 }, { currentStreak: 12 });
+ expect(rows[0].pct).toBe(100);
+ expect(rows[0].met).toBe(true);
+ });
+
+ it('returns no rows for absent goals', () => {
+ expect(computeGoalProgress({}, { currentStreak: 5 })).toEqual([]);
+ expect(computeGoalProgress(undefined, {})).toEqual([]);
+ });
+});
diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.js
index b08a0c15a7..e8efc7cd99 100644
--- a/client/src/services/apiMeatspace.js
+++ b/client/src/services/apiMeatspace.js
@@ -198,6 +198,12 @@ export const getPostReviewReps = (limit, options = {}) => request(
`/meatspace/post/review/reps${limit != null ? `?limit=${limit}` : ''}`,
{ silent: true, ...options }
);
+// Ordered "what to practice next" recommendations (issue #2100). Silent — the
+// launcher/widget degrade gracefully (hide the panel) if this fails.
+export const getPostRecommendations = (limit, options = {}) => request(
+ `/meatspace/post/recommendations${limit != null ? `?limit=${limit}` : ''}`,
+ { silent: true, ...options }
+);
export const getPostMultiplicationProgress = () => request('/meatspace/post/multiplication-progress');
export const getPostCognitiveProgress = () => request('/meatspace/post/cognitive-progress');
export const generatePostDrill = (type, config = {}, providerId, model, options = {}) => request('/meatspace/post/drill', {
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index 027587b462..c65b5e5eeb 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -212,6 +212,17 @@ const llmDrillTypeConfigSchema = z.object({
model: z.string().optional()
});
+// Optional practice goals (issue #2100). Every field is optional so a config
+// with no goals — or a legacy config that predates this block entirely — stays
+// valid; bounds keep a hand-edited config from persisting a nonsensical target.
+// Exported so the settings route / tests can validate a `goals` slice directly.
+export const postGoalsSchema = z.object({
+ dailyMinutes: z.number().int().min(1).max(1440).optional(),
+ weeklySessions: z.number().int().min(1).max(100).optional(),
+ streakTarget: z.number().int().min(1).max(3650).optional(),
+ morseWpmTarget: z.number().min(1).max(100).optional(),
+}).partial();
+
// Config update (partial)
export const postConfigUpdateSchema = z.object({
mentalMath: z.object({
@@ -230,6 +241,8 @@ export const postConfigUpdateSchema = z.object({
drillTypes: z.record(z.enum(COGNITIVE_DRILL_TYPES), drillTypeConfigSchema).optional()
}).optional(),
sessionModules: z.array(z.enum(POST_MODULES)).optional(),
+ // Optional practice goals (issue #2100) — see postGoalsSchema above.
+ goals: postGoalsSchema.optional(),
scoring: z.object({
weights: z.record(z.number().min(0).max(1)).optional()
}).optional(),
diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.js
index 5b5b07c415..fad0649a24 100644
--- a/server/lib/postValidation.test.js
+++ b/server/lib/postValidation.test.js
@@ -254,6 +254,34 @@ describe('postSessionSubmitSchema.modules — enum of known modules (issue #2099
});
});
+describe('postConfigUpdateSchema goals (issue #2100)', () => {
+ it('accepts a full goals block within bounds', () => {
+ const parsed = postConfigUpdateSchema.parse({
+ goals: { dailyMinutes: 20, weeklySessions: 5, streakTarget: 30, morseWpmTarget: 15 },
+ });
+ expect(parsed.goals).toEqual({ dailyMinutes: 20, weeklySessions: 5, streakTarget: 30, morseWpmTarget: 15 });
+ });
+
+ it('accepts a partial goals block (any subset of targets)', () => {
+ expect(postConfigUpdateSchema.parse({ goals: { streakTarget: 10 } }).goals).toEqual({ streakTarget: 10 });
+ expect(postConfigUpdateSchema.parse({ goals: {} }).goals).toEqual({});
+ });
+
+ it('stays valid for a legacy config with no goals key', () => {
+ // Back-compat: a config that predates goals must not 400.
+ expect(() => postConfigUpdateSchema.parse({ sessionModules: ['mental-math'] })).not.toThrow();
+ expect(postConfigUpdateSchema.parse({ mentalMath: { enabled: true } }).goals).toBeUndefined();
+ });
+
+ it('rejects out-of-bounds or wrong-typed goal values', () => {
+ expect(() => postConfigUpdateSchema.parse({ goals: { dailyMinutes: 0 } })).toThrow();
+ expect(() => postConfigUpdateSchema.parse({ goals: { dailyMinutes: 5000 } })).toThrow();
+ expect(() => postConfigUpdateSchema.parse({ goals: { streakTarget: 1.5 } })).toThrow();
+ expect(() => postConfigUpdateSchema.parse({ goals: { morseWpmTarget: 200 } })).toThrow();
+ expect(() => postConfigUpdateSchema.parse({ goals: { weeklySessions: 'lots' } })).toThrow();
+ });
+});
+
describe('POST_SUPPORTED_MEMORY_TYPES (issue #2099, fix #1)', () => {
// Regression: memory-fill-blank used to be absent, which forced its score
// to 0 and skipped schedule/mastery advancement in submitPostSession.
diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.js
index 9c149a6dc4..1ac504596d 100644
--- a/server/routes/meatspacePostRoutes.js
+++ b/server/routes/meatspacePostRoutes.js
@@ -122,6 +122,20 @@ router.get('/post/progress', asyncHandler(async (req, res) => {
res.json(progress);
}));
+/**
+ * GET /api/meatspace/post/recommendations
+ * Ordered "what to practice next" list (issue #2100): due memory items, due
+ * skill re-verifications, the weakest recent skill, and stalled ladder
+ * progressions — each with a deep link into the exact drill/mode. Never empty
+ * (falls back to a sensible default when nothing specific is actionable).
+ */
+router.get('/post/recommendations', asyncHandler(async (req, res) => {
+ const rawLimit = req.query.limit != null ? parseInt(req.query.limit, 10) : undefined;
+ const limit = Number.isNaN(rawLimit) || rawLimit == null ? undefined : Math.max(1, Math.min(10, rawLimit));
+ const result = await postService.getPostRecommendations(limit != null ? { limit } : {});
+ res.json(result);
+}));
+
/**
* POST /api/meatspace/post/drill
* Generate a drill with questions and expected answers.
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index 952bc19b24..976654bf42 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -24,6 +24,7 @@ import { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } fr
import { applySessionToMemoryItems, getMemoryItems, getDueMemoryItems, isStatMastered, MASTERY_TARGET_ACCURACY } from './meatspacePostMemory.js';
import { applySessionToReviewSchedule, getDueReviews, getRetentionReport } from './meatspacePostReview.js';
import { getAllTrainingEntries } from './meatspacePostTraining.js';
+import { getMorseProgress, MAX_KOCH_LEVEL } from './meatspacePostMorse.js';
import { computePostStreaks, computeUnifiedStreak, ymdToUTC } from '../lib/postStreak.js';
// Re-export the shared streak helper so existing importers of
@@ -91,7 +92,21 @@ const DEFAULT_CONFIG = {
'reaction-time': { enabled: true, mode: 'simple', count: 15, minDelayMs: 1000, maxDelayMs: 3000, choices: 3 }
}
},
- sessionModules: ['mental-math'],
+ // Default session composition is a balanced, interleaved mix of the free
+ // (no-provider) modules — mental math, deterministic cognitive drills, and
+ // memory (issue #2100). LLM drills are deliberately excluded from the default:
+ // auto-enabling them would queue provider calls the user hasn't consented to
+ // (see CLAUDE.md's AI Provider Usage Policy). A user who wants wit/verbal
+ // drills in every session adds `llm-drills` here explicitly.
+ sessionModules: ['mental-math', 'cognitive', 'memory'],
+ // Optional practice goals (issue #2100). All fields absent by default so a
+ // fresh/legacy install shows no goal UI until the user sets one. Bounds are
+ // enforced by postGoalsSchema (server/lib/postValidation.js).
+ // dailyMinutes? — minutes trained today target
+ // weeklySessions? — scored sessions per rolling 7 days target
+ // streakTarget? — unified activity-streak (days) target
+ // morseWpmTarget? — Morse effective-WPM target
+ goals: {},
// Per-module weight applied to a session's blended score (issue #2099).
// Uniform 1.0 defaults reproduce the old unweighted-mean behavior exactly —
// a user only sees a change once they actually adjust a weight.
@@ -806,6 +821,224 @@ export async function getPostProgress({ days = 90 } = {}) {
};
}
+// =============================================================================
+// RECOMMENDATIONS ("what to practice next") — issue #2100
+// =============================================================================
+
+// Cap on how many recommendations the launcher/widget surface — enough to fill
+// an "Up next" panel without becoming a wall of tasks.
+const RECOMMENDATION_LIMIT = 5;
+// Coarse module → domain routing for weak-skill recommendations. Only the
+// domains a weak-skill rec can name are needed here; the full map lives on the
+// client (constants.js DRILL_TO_DOMAIN). Prettify falls back to the drill type.
+const DRILL_LABEL = (type) =>
+ String(type || '').replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
+
+/**
+ * The single weakest scored drill by recent (windowed) accuracy — the drill
+ * whose `byDrillAccuracy` is lowest among drills with at least one sample.
+ * Pure; reads the shape `getPostStats` returns. `null` when there's no
+ * accuracy signal yet (fresh install / all drills without derivable accuracy).
+ * Returns `{ key, module, type, accuracy, samples }` where `key` is
+ * `"<module>:<type>"`.
+ */
+export function weakestSkillFromStats(stats) {
+ const acc = stats?.byDrillAccuracy || {};
+ const counts = stats?.byDrillCount || {};
+ let worst = null;
+ for (const [key, a] of Object.entries(acc)) {
+ if (typeof a !== 'number' || Number.isNaN(a)) continue;
+ const samples = counts[key] || 0;
+ if (samples < 1) continue;
+ if (!worst || a < worst.accuracy) {
+ const sep = key.indexOf(':');
+ worst = {
+ key,
+ module: sep >= 0 ? key.slice(0, sep) : null,
+ type: sep >= 0 ? key.slice(sep + 1) : key,
+ accuracy: a,
+ samples,
+ };
+ }
+ }
+ return worst;
+}
+
+/**
+ * Stalled-progression descriptors from the resolved multiplication + cognitive
+ * ladders: a laddered drill the user is partway up but not yet advancing, with
+ * how many more clean/fast reps remain to reach the next rung. Pure — takes the
+ * already-resolved progress objects. A ladder that's mastered-and-advancing or
+ * at its hardest rung contributes nothing.
+ *
+ * @param {object} mulProgress - getMultiplicationProgress() result
+ * @param {Record<string,object>} cogProgress - getCognitiveProgress() result
+ * @param {{kochLevel:number, kochLevelSet:boolean, maxKochLevel:number}} morse
+ */
+export function stalledProgressions(mulProgress, cogProgress, morse) {
+ const out = [];
+
+ const ladderStall = (prog, drillType, label, deepLink) => {
+ if (!prog || prog.atHardest || prog.currentMastered) return null;
+ const cur = (prog.levels || []).find((r) => r.level === prog.level);
+ if (!cur) return null;
+ const next = (prog.levels || []).find((r) => r.level === prog.level + 1);
+ const minSamples = prog.thresholds?.minSamples ?? 0;
+ const remaining = Math.max(1, minSamples - (cur.samples || 0));
+ return {
+ drillType,
+ label,
+ remaining,
+ nextLabel: next?.label || null,
+ deepLink,
+ };
+ };
+
+ const mul = ladderStall(mulProgress, 'multiplication', 'Multiplication', '/post/launcher');
+ if (mul) out.push(mul);
+
+ for (const [type, prog] of Object.entries(cogProgress || {})) {
+ const stall = ladderStall(prog, type, DRILL_LABEL(type), '/post/launcher');
+ if (stall) out.push(stall);
+ }
+
+ // Morse Koch progression: surface only once the user has engaged with Morse
+ // (a level has been set) and isn't already at the final Koch level — so a
+ // fresh install is never nagged about a track it hasn't started.
+ if (morse?.kochLevelSet && morse.kochLevel < (morse.maxKochLevel ?? Infinity)) {
+ out.push({
+ drillType: 'morse-copy',
+ label: 'Morse',
+ remaining: null,
+ nextLabel: `Koch level ${morse.kochLevel + 1}`,
+ deepLink: '/post/morse/copy',
+ });
+ }
+
+ return out;
+}
+
+/**
+ * Compose the ordered "what to practice next" list from already-gathered
+ * signals. PURE + fully unit-testable — the async `getPostRecommendations`
+ * gathers the inputs and delegates here. Priority order (highest first):
+ * 1. Due memory items (spaced-repetition overdue)
+ * 2. Due skill re-verifications (mastered-but-inactive skills, issue #2096)
+ * 3. Weakest scored skill by recent accuracy
+ * 4. Stalled ladder progressions (N more reps to advance)
+ * When nothing is actionable (e.g. a fresh install with no history), a single
+ * sensible default ("run a full POST") is returned so the panel is never empty.
+ */
+export function composePostRecommendations({
+ dueMemoryItems = [],
+ dueReviews = [],
+ weakestSkill = null,
+ stalled = [],
+ hasHistory = false,
+ limit = RECOMMENDATION_LIMIT,
+} = {}) {
+ const recs = [];
+
+ for (const item of dueMemoryItems) {
+ recs.push({
+ id: `memory-due:${item.id}`,
+ kind: 'memory-due',
+ title: `Review "${item.title}"`,
+ detail: 'Due for spaced-repetition practice',
+ deepLink: '/post/memory',
+ drillType: 'memory-sequence',
+ });
+ }
+
+ for (const review of dueReviews) {
+ recs.push({
+ id: `skill-review:${review.skillId}`,
+ kind: 'skill-review',
+ title: `Re-verify ${review.label}`,
+ detail: review.status === 'needs-refresh'
+ ? 'Needs a refresh — last review slipped'
+ : 'Maintenance rep due',
+ deepLink: '/post/launcher',
+ drillType: review.drillType || null,
+ });
+ }
+
+ if (weakestSkill) {
+ recs.push({
+ id: `weak-skill:${weakestSkill.key}`,
+ kind: 'weak-skill',
+ title: `Shore up ${DRILL_LABEL(weakestSkill.type)}`,
+ detail: `Weakest skill lately — ${Math.round((weakestSkill.accuracy || 0) * 100)}% accuracy`,
+ deepLink: '/post/launcher',
+ drillType: weakestSkill.type,
+ });
+ }
+
+ for (const stall of stalled) {
+ const remainText = stall.remaining != null
+ ? `${stall.remaining} more clean rep${stall.remaining === 1 ? '' : 's'} to reach ${stall.nextLabel || 'the next level'}`
+ : `Advance to ${stall.nextLabel || 'the next level'}`;
+ recs.push({
+ id: `stalled:${stall.drillType}`,
+ kind: 'stalled-progression',
+ title: `${stall.label}: keep climbing`,
+ detail: remainText,
+ deepLink: stall.deepLink,
+ drillType: stall.drillType,
+ });
+ }
+
+ if (recs.length === 0) {
+ recs.push({
+ id: 'default:full-post',
+ kind: 'default',
+ title: hasHistory ? 'Keep your streak going' : 'Run your first POST',
+ detail: hasHistory
+ ? 'No specific gaps right now — run a full self-test to stay sharp.'
+ : 'Complete a full self-test to start tracking what to practice next.',
+ deepLink: '/post/launcher',
+ drillType: null,
+ });
+ }
+
+ return recs.slice(0, Math.max(1, limit)).map((r, i) => ({ ...r, priority: i }));
+}
+
+/**
+ * Gather the recommendation signals and compose the ordered "Up next" list
+ * (issue #2100). Reads due memory items, due skill re-verifications, recent
+ * stats (weakest skill), and the resolved ladders (stalled progressions).
+ */
+export async function getPostRecommendations({ limit = RECOMMENDATION_LIMIT } = {}) {
+ const [dueMemoryItems, dueReviews, stats, mulProgress, cogProgress, morse, sessions] = await Promise.all([
+ getDueMemoryItems(),
+ getDueReviews(new Date(), Infinity),
+ getPostStats(MASTERY_DEFAULTS.windowDays),
+ getMultiplicationProgress(),
+ getCognitiveProgress(),
+ getMorseProgress(MASTERY_DEFAULTS.windowDays),
+ getPostSessions(),
+ ]);
+
+ const weakestSkill = weakestSkillFromStats(stats);
+ const stalled = stalledProgressions(mulProgress, cogProgress, {
+ kochLevel: morse?.kochLevel,
+ kochLevelSet: morse?.kochLevelSet,
+ maxKochLevel: MAX_KOCH_LEVEL,
+ });
+
+ return {
+ recommendations: composePostRecommendations({
+ dueMemoryItems,
+ dueReviews,
+ weakestSkill,
+ stalled,
+ hasHistory: sessions.length > 0,
+ limit,
+ }),
+ };
+}
+
// =============================================================================
// DRILL GENERATORS (pure functions)
// =============================================================================
diff --git a/server/services/meatspacePostRecommendations.test.js b/server/services/meatspacePostRecommendations.test.js
new file mode 100644
index 0000000000..17c70377c8
--- /dev/null
+++ b/server/services/meatspacePostRecommendations.test.js
@@ -0,0 +1,174 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Recommendation composition (issue #2100). The pure functions
+// (composePostRecommendations / weakestSkillFromStats / stalledProgressions)
+// need no mocks; getPostRecommendations is exercised through the same
+// mocked-fileUtils harness the other POST service tests use.
+const state = { sessions: [], memoryItems: [], reviewSchedule: { skills: {} }, morse: { kochLevel: null, settings: null, rounds: [] } };
+
+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: [] });
+ if (path.includes('memory-items')) return Promise.resolve({ items: state.memoryItems });
+ if (path.includes('post-review-schedule')) return Promise.resolve(state.reviewSchedule);
+ if (path.includes('post-morse')) return Promise.resolve(state.morse);
+ if (path.includes('post-config')) return Promise.resolve({});
+ }
+ return Promise.resolve(defaultValue);
+ }),
+}));
+
+import {
+ composePostRecommendations,
+ weakestSkillFromStats,
+ stalledProgressions,
+ getPostRecommendations,
+} from './meatspacePost.js';
+
+beforeEach(() => {
+ state.sessions = [];
+ state.memoryItems = [];
+ state.reviewSchedule = { skills: {} };
+ state.morse = { kochLevel: null, settings: null, rounds: [] };
+});
+
+describe('weakestSkillFromStats', () => {
+ it('returns the lowest-accuracy drill with samples', () => {
+ const stats = {
+ byDrillAccuracy: { 'mental-math:multiplication': 0.9, 'cognitive:n-back': 0.5 },
+ byDrillCount: { 'mental-math:multiplication': 4, 'cognitive:n-back': 3 },
+ };
+ const w = weakestSkillFromStats(stats);
+ expect(w.type).toBe('n-back');
+ expect(w.module).toBe('cognitive');
+ expect(w.accuracy).toBe(0.5);
+ });
+
+ it('ignores drills with zero samples', () => {
+ const stats = {
+ byDrillAccuracy: { 'cognitive:n-back': 0.2, 'mental-math:powers': 0.8 },
+ byDrillCount: { 'cognitive:n-back': 0, 'mental-math:powers': 5 },
+ };
+ expect(weakestSkillFromStats(stats).type).toBe('powers');
+ });
+
+ it('returns null when there is no accuracy signal', () => {
+ expect(weakestSkillFromStats({ byDrillAccuracy: {}, byDrillCount: {} })).toBeNull();
+ expect(weakestSkillFromStats(null)).toBeNull();
+ });
+});
+
+describe('stalledProgressions', () => {
+ const stalledLadder = { level: 1, atHardest: false, currentMastered: false, thresholds: { minSamples: 12 }, levels: [
+ { level: 0, label: '1×1-digit', samples: 20, mastered: true },
+ { level: 1, label: '1×2-digit', samples: 4, mastered: false },
+ { level: 2, label: '1×1×1-digit', samples: 0, mastered: false },
+ ] };
+
+ it('reports remaining reps to the next multiplication rung', () => {
+ const out = stalledProgressions(stalledLadder, {}, {});
+ expect(out).toHaveLength(1);
+ expect(out[0].drillType).toBe('multiplication');
+ expect(out[0].remaining).toBe(8); // 12 - 4
+ expect(out[0].nextLabel).toBe('1×1×1-digit');
+ });
+
+ it('omits a ladder that is mastered-and-advancing or at its hardest rung', () => {
+ expect(stalledProgressions({ ...stalledLadder, currentMastered: true }, {}, {})).toHaveLength(0);
+ expect(stalledProgressions({ ...stalledLadder, atHardest: true }, {}, {})).toHaveLength(0);
+ });
+
+ it('includes cognitive ladders and a Morse Koch step once level is set', () => {
+ const cog = { 'n-back': { level: 0, atHardest: false, currentMastered: false, thresholds: { minSamples: 3 }, levels: [
+ { level: 0, label: '1-back @ 2500ms', samples: 1, mastered: false },
+ { level: 1, label: '2-back @ 2500ms', samples: 0, mastered: false },
+ ] } };
+ const out = stalledProgressions(null, cog, { kochLevel: 5, kochLevelSet: true, maxKochLevel: 41 });
+ const nback = out.find(o => o.drillType === 'n-back');
+ expect(nback.remaining).toBe(2); // 3 - 1
+ const morse = out.find(o => o.drillType === 'morse-copy');
+ expect(morse.deepLink).toBe('/post/morse/copy');
+ expect(morse.nextLabel).toBe('Koch level 6');
+ });
+
+ it('does not surface Morse for a fresh install (level not set)', () => {
+ const out = stalledProgressions(null, {}, { kochLevel: 2, kochLevelSet: false, maxKochLevel: 41 });
+ expect(out.find(o => o.drillType === 'morse-copy')).toBeUndefined();
+ });
+});
+
+describe('composePostRecommendations priority + composition', () => {
+ it('orders due memory items ahead of weak skills and stalled progressions', () => {
+ const recs = composePostRecommendations({
+ dueMemoryItems: [{ id: 'song', title: 'Elements' }],
+ weakestSkill: { key: 'cognitive:n-back', type: 'n-back', accuracy: 0.5 },
+ stalled: [{ drillType: 'multiplication', label: 'Multiplication', remaining: 5, nextLabel: '2×2-digit', deepLink: '/post/launcher' }],
+ hasHistory: true,
+ });
+ expect(recs.map(r => r.kind)).toEqual(['memory-due', 'weak-skill', 'stalled-progression']);
+ expect(recs[0].deepLink).toBe('/post/memory');
+ expect(recs.map(r => r.priority)).toEqual([0, 1, 2]);
+ });
+
+ it('places due skill re-verifications above weak skills', () => {
+ const recs = composePostRecommendations({
+ dueReviews: [{ skillId: 'multiplication:L1', label: 'Multiplication 1×2', drillType: 'multiplication', status: 'due' }],
+ weakestSkill: { key: 'cognitive:n-back', type: 'n-back', accuracy: 0.5 },
+ hasHistory: true,
+ });
+ expect(recs[0].kind).toBe('skill-review');
+ expect(recs[1].kind).toBe('weak-skill');
+ });
+
+ it('returns a sensible default for an empty (fresh) history', () => {
+ const recs = composePostRecommendations({ hasHistory: false });
+ expect(recs).toHaveLength(1);
+ expect(recs[0].kind).toBe('default');
+ expect(recs[0].deepLink).toBe('/post/launcher');
+ expect(recs[0].title).toMatch(/first POST/i);
+ });
+
+ it('defaults to a keep-sharp prompt when history exists but nothing is actionable', () => {
+ const recs = composePostRecommendations({ hasHistory: true });
+ expect(recs[0].kind).toBe('default');
+ expect(recs[0].title).toMatch(/streak/i);
+ });
+
+ it('caps the list at the limit', () => {
+ const recs = composePostRecommendations({
+ dueMemoryItems: Array.from({ length: 8 }, (_, i) => ({ id: `m${i}`, title: `Item ${i}` })),
+ limit: 3,
+ });
+ expect(recs).toHaveLength(3);
+ });
+});
+
+describe('getPostRecommendations (integration)', () => {
+ it('surfaces a due memory item as the top recommendation', async () => {
+ // A memory item overdue for review: nextReview in the past.
+ state.memoryItems = [{
+ id: 'song', title: 'Elements', type: 'song', content: { chunks: [] },
+ schedule: { ease: 2.5, intervalDays: 1, nextReview: new Date(Date.now() - 86400000).toISOString() },
+ mastery: { overallPct: 40, chunks: {} },
+ }];
+ const { recommendations } = await getPostRecommendations();
+ expect(recommendations[0].kind).toBe('memory-due');
+ expect(recommendations[0].deepLink).toBe('/post/memory');
+ });
+
+ it('never returns an empty list on a fresh install', async () => {
+ // A fresh install still has the built-in Elements Song memory item (which
+ // may be due) so the list is never empty; every entry carries a deep link.
+ const { recommendations } = await getPostRecommendations();
+ expect(recommendations.length).toBeGreaterThanOrEqual(1);
+ for (const rec of recommendations) {
+ expect(typeof rec.deepLink).toBe('string');
+ expect(rec.deepLink.startsWith('/post')).toBe(true);
+ }
+ });
+});