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-2096]): decay-aware mastery + scheduled skill re-verification
Adam Eivy1eed465b0a33
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5ef618aeb4..596f9f2d46 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -31,6 +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-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/meatspace/post/PostProgress.jsx b/client/src/components/meatspace/post/PostProgress.jsxindex e4b7161ffa..8db4b84f3f 100644--- a/client/src/components/meatspace/post/PostProgress.jsx+++ b/client/src/components/meatspace/post/PostProgress.jsx@@ -131,8 +131,9 @@ export default function PostProgress({ subtab, onBack }) {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 mastery = progress?.mastery || { multiplication: null, memoryItems: [], reviews: null };const dueTotal = (mastery.memoryItems || []).reduce((n, m) => n + (m.dueCount || 0), 0);+ const reviews = mastery.reviews || null;const hasAny = totals.sessions > 0 || totals.practiceEntries > 0;return (@@ -306,12 +307,58 @@ export default function PostProgress({ subtab, onBack }) {)}</div></div>++ {/* Skill retention panel (issue #2096) — mastered skills' re-verification+ state + a 90-day retention %. Only shown once a skill is mastered. */}+ {reviews && reviews.trackedCount > 0 && (+ <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">Skill Retention</h3>+ <div className="flex items-center gap-2">+ {reviews.retentionPct != null && (+ <span className="text-xs text-gray-400">+ 90-day retention: <span className="font-mono text-white">{reviews.retentionPct}%</span>+ </span>+ )}+ {reviews.dueCount > 0 && (+ <span className="px-2 py-0.5 bg-port-warning/20 text-port-warning text-xs rounded-full">+ {reviews.dueCount} due+ </span>+ )}+ </div>+ </div>+ <div className="flex flex-wrap gap-2">+ {(reviews.skills || []).map(s => (+ <span+ key={s.skillId}+ className={`px-2 py-1 rounded-md text-xs border ${RETENTION_STATE_CLASS[s.state] || RETENTION_STATE_CLASS.fresh}`}+ title={RETENTION_STATE_LABEL[s.state] || s.state}+ >+ {s.label}+ <span className="ml-1 opacity-70">· {RETENTION_STATE_LABEL[s.state] || s.state}</span>+ </span>+ ))}+ </div>+ </div>+ )}</>)}</div>);}+// Retention-state → badge styling + human label (issue #2096).+const RETENTION_STATE_CLASS = {+ fresh: 'bg-port-success/10 border-port-success/30 text-port-success',+ due: 'bg-port-warning/10 border-port-warning/30 text-port-warning',+ 'needs-refresh': 'bg-port-error/10 border-port-error/30 text-port-error',+};+const RETENTION_STATE_LABEL = {+ fresh: 'fresh',+ due: 'due for review',+ 'needs-refresh': 'needs refresh',+};+function ProgressTabs({ subtab, navigate }) {const tabs = [{ id: undefined, label: 'Trends', to: '/post/progress' },diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex 36449321ce..b12d665285 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -1,6 +1,6 @@import { useState, useEffect } from 'react';import { Zap, History, Settings, Play, Brain, BookOpen, Dumbbell, Timer, Radio, Target, TrendingUp, TrendingDown, Minus } from 'lucide-react';-import { getProviders } from '../../../services/api';+import { getProviders, getPostReviewReps } from '../../../services/api';import { FormField } from '../../ui/FormField';import { isApiProvider } from '../../../utils/providers';import { DOMAINS, DRILL_TO_DOMAIN, DRILL_LABELS, computeDomainAverages } from './constants';@@ -35,9 +35,15 @@ export default function PostSessionLauncher({ config, recentSessions, stats, staconst [tags, setTags] = useState({ sleep: '', caffeine: '', stress: '' });const [mode, setMode] = useState('test'); // 'test' | 'train'const [providers, setProviders] = useState([]);+ // Mastered-but-inactive skills due for a maintenance review (issue #2096) —+ // the Quick session mixes up to 2 of these in as labeled review reps. Empty+ // until a skill is mastered and its review interval elapses; a load failure+ // silently degrades to a plain Quick session.+ const [reviewReps, setReviewReps] = 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([]));}, []);if (!config) {@@ -176,6 +182,21 @@ export default function PostSessionLauncher({ config, recentSessions, stats, stadrillConfigs.push(drillConfig);}+ // Mix in up to 2 maintenance reps for mastered-but-inactive skills that are+ // due for re-verification (issue #2096). Each carries the review markers so+ // the server re-verifies the specific rung and records the pass/fail.+ for (const rep of reviewReps.slice(0, 2)) {+ drillConfigs.push({+ type: rep.type,+ domain: DRILL_TO_DOMAIN[rep.type],+ config: rep.config,+ timeLimitSec: DOMAINS[DRILL_TO_DOMAIN[rep.type]]?.timeBudgetSec,+ isReview: true,+ reviewLabel: rep.label,+ ...(rep.providerId && { providerId: rep.providerId }),+ });+ }+onStart(drillConfigs, buildCleanTags(tags), mode === 'train');}@@ -417,6 +438,18 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta</div></div>}+ {/* Maintenance-review nudge (issue #2096) — mastered skills due for a+ refresh, mixed into the next Quick session as labeled review reps. */}+ {reviewReps.length > 0 && (+ <div className="flex items-start gap-2 px-3 py-2 rounded-lg bg-port-warning/10 border border-port-warning/30 text-sm text-port-warning">+ <Target size={16} className="mt-0.5 shrink-0" />+ <span>+ {reviewReps.length} skill{reviewReps.length > 1 ? 's' : ''} due for a maintenance rep+ {' '}— a Quick session will mix {reviewReps.length > 1 ? 'them' : 'it'} in: {reviewReps.slice(0, 2).map(r => r.label).join(', ')}+ </span>+ </div>+ )}+{/* Start Buttons */}<div className="flex flex-col sm:flex-row gap-3">{domainCount >= 2 && (diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.jsindex 99068b6de8..b08a0c15a7 100644--- a/client/src/services/apiMeatspace.js+++ b/client/src/services/apiMeatspace.js@@ -191,6 +191,13 @@ export const getPostProgress = (days, options = {}) => request(options);export const getPostAdaptivePreview = () => request('/meatspace/post/adaptive-preview');+// Mastered-but-inactive skills due for a maintenance review (issue #2096). The+// launcher mixes these into a Quick session as labeled review reps. Silent — the+// caller degrades to a normal Quick session if this fails.+export const getPostReviewReps = (limit, options = {}) => request(+ `/meatspace/post/review/reps${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.jsindex cc04ee44ed..027587b462 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -107,6 +107,13 @@ const drillTypeConfigSchema = z.object({progressive: z.boolean().optional(),level: z.number().int().min(0).max(50).optional(),factors: z.array(z.number().int().min(1).max(4)).min(2).max(6).optional(),+ // Maintenance-review rep (issue #2096): `review` bypasses the progression+ // override so a specific mastered-but-inactive rung is re-verified at its own+ // level; `reviewSkillId` ties the scored task back to the review scheduler so+ // session-submit records the pass/fail. Both survive validation on the drill+ // request AND the session-submit round-trip.+ review: z.boolean().optional(),+ reviewSkillId: z.string().max(200).optional(),bases: z.array(z.number().int().min(2).max(20)).min(1).optional(),maxExponent: z.number().int().min(2).max(20).optional(),tolerancePct: z.number().min(1).max(50).optional(),diff --git a/server/routes/meatspacePostRoutes.drill.test.js b/server/routes/meatspacePostRoutes.drill.test.jsindex 76b889cdf2..d16df3fa7d 100644--- a/server/routes/meatspacePostRoutes.drill.test.js+++ b/server/routes/meatspacePostRoutes.drill.test.js@@ -28,12 +28,13 @@ vi.mock('../services/meatspacePostMemory.js', () => ({vi.mock('../services/meatspacePost.js', () => ({resolveDrillConfig: vi.fn(),generateDrill: vi.fn(),+ getPostReviewReps: vi.fn(),}));import { getCachedDrill, triggerReplenish } from '../services/meatspacePostDrillCache.js';import { generateLlmDrill } from '../services/meatspacePostLlm.js';import { generateMemoryDrill } from '../services/meatspacePostMemory.js';-import { resolveDrillConfig, generateDrill } from '../services/meatspacePost.js';+import { resolveDrillConfig, generateDrill, getPostReviewReps } from '../services/meatspacePost.js';import { errorMiddleware } from '../lib/errorHandler.js';import meatspacePostRoutes from './meatspacePostRoutes.js';@@ -198,3 +199,57 @@ describe('POST /api/meatspace/post/drill', () => {expect(resolveDrillConfig).not.toHaveBeenCalled();});});++// =============================================================================+// Maintenance-review reps (issue #2096)+// =============================================================================++describe('POST /api/meatspace/post/drill — review re-stamp', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ });++ it('re-stamps review markers from the resolved config onto the generated drill', async () => {+ // The generators rebuild their own config and drop review/reviewSkillId, so+ // the route must re-attach them for the session-submit tie-back.+ resolveDrillConfig.mockResolvedValue({+ config: { count: 5, level: 0, factors: [1, 1], review: true, reviewSkillId: 'multiplication:L0' },+ adaptive: null,+ progression: null,+ });+ generateDrill.mockReturnValue({ type: 'multiplication', config: { count: 5, factors: [1, 1], level: 0 }, questions: [] });++ const r = await request(app).post('/api/meatspace/post/drill').send({+ type: 'multiplication',+ config: { review: true, reviewSkillId: 'multiplication:L0', level: 0, factors: [1, 1] },+ });+ expect(r.status).toBe(200);+ expect(r.body.config.review).toBe(true);+ expect(r.body.config.reviewSkillId).toBe('multiplication:L0');+ expect(r.body.isReview).toBe(true);+ });+});++describe('GET /api/meatspace/post/review/reps', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ });++ it('returns the due maintenance reps under a { reps } envelope', async () => {+ getPostReviewReps.mockResolvedValue([{ skillId: 'multiplication:L0', label: 'Multiplication 1×1-digit', type: 'multiplication', config: {} }]);+ const r = await request(app).get('/api/meatspace/post/review/reps');+ expect(r.status).toBe(200);+ expect(r.body.reps).toHaveLength(1);+ expect(getPostReviewReps).toHaveBeenCalledWith(expect.any(Date), 2);+ });++ it('clamps the limit query param to 0..5', async () => {+ getPostReviewReps.mockResolvedValue([]);+ await request(app).get('/api/meatspace/post/review/reps?limit=99');+ expect(getPostReviewReps).toHaveBeenCalledWith(expect.any(Date), 5);+ });+});diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.jsindex c05f2fca5e..9c149a6dc4 100644--- a/server/routes/meatspacePostRoutes.js+++ b/server/routes/meatspacePostRoutes.js@@ -171,6 +171,14 @@ router.post('/post/drill', asyncHandler(async (req, res) => {// Progressive multiplication ladder explainer (current level + per-rung mastery)// so the drill runner can show which rung the user is on and why.if (progression) drill.progression = progression;+ // Maintenance-review rep (issue #2096): the drill generators rebuild their own+ // config, so re-stamp the review markers from the requested config onto the+ // returned drill. This ties the scored task back to the review scheduler on+ // submit (getSessionSkillContext reads task.config.reviewSkillId).+ if (effectiveConfig?.review && effectiveConfig?.reviewSkillId) {+ drill.config = { ...(drill.config || {}), review: true, reviewSkillId: effectiveConfig.reviewSkillId };+ drill.isReview = true;+ }res.json(drill);}));@@ -195,6 +203,20 @@ router.get('/post/cognitive-progress', asyncHandler(async (req, res) => {res.json(progress);}));+/**+ * GET /api/meatspace/post/review/reps+ * Ready-to-run "maintenance rep" drill specs for mastered-but-inactive skills+ * currently due for re-verification (issue #2096). The launcher mixes 1–2 of+ * these into a Quick session as labeled review items. Empty until a skill is+ * mastered and its review interval elapses.+ */+router.get('/post/review/reps', asyncHandler(async (req, res) => {+ const rawLimit = req.query.limit != null ? parseInt(req.query.limit, 10) : 2;+ const limit = Number.isNaN(rawLimit) ? 2 : Math.max(0, Math.min(5, rawLimit));+ const reps = await postService.getPostReviewReps(new Date(), limit);+ res.json({ reps });+}));+/*** GET /api/meatspace/post/adaptive-preview* Transparent per-type preview of effective adaptive difficulty for math drills,diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 4cf1ff37ff..2ad4a7b508 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -21,7 +21,8 @@ import {COGNITIVE_MASTERY_DEFAULTS,} from '../lib/postProgression.js';import { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } from './meatspacePostCognitive.js';-import { applySessionToMemoryItems, getMemoryItems, getDueMemoryItems } from './meatspacePostMemory.js';+import { applySessionToMemoryItems, getMemoryItems, getDueMemoryItems, isStatMastered, MASTERY_TARGET_ACCURACY } from './meatspacePostMemory.js';+import { applySessionToReviewSchedule, getDueReviews, getRetentionReport } from './meatspacePostReview.js';import { getAllTrainingEntries } from './meatspacePostTraining.js';import { computePostStreaks, computeUnifiedStreak, ymdToUTC } from '../lib/postStreak.js';@@ -289,11 +290,163 @@ export async function submitPostSession(sessionData) {} catch (err) {console.error(`❌ POST session memory post-processing failed (session ${sessionId} still saved): ${err.message}`);}+ // Reconcile the skill re-verification schedule (issue #2096): upsert newly-+ // mastered skills, record any maintenance-review reps in this session, and+ // reset the staleness clock for mastered skills actively practiced here.+ // Runs AFTER the memory update above so mastery reflects this session.+ // Isolated so it can never 500 an already-persisted session.+ try {+ await syncReviewScheduleForSession(session, new Date(now));+ } catch (err) {+ console.error(`❌ POST session review-schedule sync failed (session ${sessionId} still saved): ${err.message}`);+ }}return session;}+// =============================================================================+// SKILL RE-VERIFICATION (issue #2096) — mastered-skill review scheduling+// =============================================================================++/**+ * Current mastered-but-inactive skills eligible for re-verification tracking:+ * - multiplication rungs strictly BELOW the resolved current level (you've+ * moved past them, so they're no longer actively drilled),+ * - cognitive rungs strictly below the current level, per laddered type,+ * - memory chunks whose windowed mastery clears the gate.+ * Returns opaque skill descriptors the review scheduler upserts + schedules.+ */+export async function getMasteredSkills() {+ const skills = [];++ const mul = await getMultiplicationProgress();+ for (const rung of mul.levels || []) {+ if (rung.mastered && rung.level < mul.level) {+ skills.push({+ skillId: `multiplication:L${rung.level}`,+ kind: 'multiplication',+ label: `Multiplication ${rung.label}`,+ drillType: 'multiplication',+ module: 'mental-math',+ level: rung.level,+ factors: rung.factors,+ });+ }+ }++ const cog = await getCognitiveProgress();+ for (const [type, prog] of Object.entries(cog)) {+ if (!prog) continue;+ for (const rung of prog.levels || []) {+ if (rung.mastered && rung.level < prog.level) {+ skills.push({+ skillId: `cognitive:${type}:L${rung.level}`,+ kind: 'cognitive',+ label: `${type} ${rung.label}`,+ drillType: type,+ module: 'cognitive',+ level: rung.level,+ config: cognitiveLevelConfig(type, rung.level),+ });+ }+ }+ }++ const memoryItems = await getMemoryItems();+ for (const item of memoryItems) {+ const chunkStats = item.mastery?.chunks || {};+ for (const chunk of item.content?.chunks || []) {+ const stat = chunkStats[chunk.id];+ if (stat && isStatMastered(stat)) {+ skills.push({+ skillId: `memory:${item.id}:${chunk.id}`,+ kind: 'memory',+ label: `${item.title} — ${chunk.label || chunk.id}`,+ drillType: 'memory-sequence',+ module: 'memory',+ memoryItemId: item.id,+ chunkId: chunk.id,+ });+ }+ }+ }++ return skills;+}++/**+ * Extract, from a scored session, which tracked skills were exercised:+ * - `reviewResults`: maintenance-review reps (tasks whose config carries a+ * `reviewSkillId`), pass/fail decided by the task's answered accuracy.+ * - `practicedSkillIds`: mastered skills a NORMAL (non-review) task drilled,+ * so their staleness clock resets (an actively-used skill never goes stale).+ */+export function getSessionSkillContext(session) {+ const practicedSkillIds = new Set();+ const reviewResults = [];+ for (const task of session?.tasks || []) {+ const cfg = task.config || {};+ if (cfg.reviewSkillId) {+ const acc = deriveTaskAccuracy(task);+ reviewResults.push({ skillId: cfg.reviewSkillId, passed: acc != null && acc >= MASTERY_TARGET_ACCURACY });+ continue;+ }+ if (task.type === 'multiplication' && Number.isInteger(cfg.level)) {+ practicedSkillIds.add(`multiplication:L${cfg.level}`);+ } else if (cognitiveLadder(task.type) && Number.isInteger(cfg.level)) {+ practicedSkillIds.add(`cognitive:${task.type}:L${cfg.level}`);+ } else if (task.memoryItemId) {+ for (const q of task.questions || []) {+ if (q?.chunkId) practicedSkillIds.add(`memory:${task.memoryItemId}:${q.chunkId}`);+ }+ }+ }+ return { practicedSkillIds: [...practicedSkillIds], reviewResults };+}++/** Reconcile the review schedule against a just-completed scored session. */+export async function syncReviewScheduleForSession(session, now = new Date()) {+ const masteredSkills = await getMasteredSkills();+ const { practicedSkillIds, reviewResults } = getSessionSkillContext(session);+ return applySessionToReviewSchedule({ masteredSkills, practicedSkillIds, reviewResults, now });+}++/**+ * Ready-to-run "maintenance rep" drill specs for the mastered skills currently+ * due for review — the labeled review items the launcher mixes into a Quick+ * session (issue #2096). Only multiplication + cognitive reps are generated (both+ * run through the standard /post/drill path); memory-chunk retention is served by+ * the existing spaced-repetition due-items flow. Each carries `review: true` ++ * `reviewSkillId` so the session-submit path records the pass/fail.+ */+export async function getPostReviewReps(now = new Date(), limit = 2) {+ const due = await getDueReviews(now, limit);+ const reps = [];+ for (const entry of due) {+ if (entry.kind === 'multiplication') {+ reps.push({+ skillId: entry.skillId,+ label: entry.label,+ state: entry.status === 'needs-refresh' ? 'needs-refresh' : 'due',+ module: 'mental-math',+ type: 'multiplication',+ config: { count: 5, level: entry.level, factors: entry.factors, review: true, reviewSkillId: entry.skillId },+ });+ } else if (entry.kind === 'cognitive') {+ reps.push({+ skillId: entry.skillId,+ label: entry.label,+ state: entry.status === 'needs-refresh' ? 'needs-refresh' : 'due',+ module: 'cognitive',+ type: entry.drillType,+ config: { ...(entry.config || cognitiveLevelConfig(entry.drillType, entry.level)), level: entry.level, review: true, reviewSkillId: entry.skillId },+ });+ }+ }+ return reps;+}+/*** Answered-only accuracy for a scored task, tolerant of legacy sessions that* predate the persisted `accuracy` field (issue #2094). Order: the stored value@@ -598,6 +751,10 @@ export async function getPostProgress({ days = 90 } = {}) {const memoryItems = await getMemoryItems();const dueItems = await getDueMemoryItems();const dueIds = new Set(dueItems.map(i => i.id));+ // Skill re-verification retention state (issue #2096): per-skill fresh / due /+ // needs-refresh + a 90-day retention %. Empty on fresh installs (nothing+ // tracked until the first skill is mastered).+ const reviews = await getRetentionReport(new Date());return {days: window,@@ -625,6 +782,7 @@ export async function getPostProgress({ days = 90 } = {}) {// 0/1 per item so the client can sum to a total "due" count.dueCount: dueIds.has(it.id) ? 1 : 0,})),+ reviews,},};}@@ -943,6 +1101,15 @@ export async function getCognitiveProgress() {export async function resolveDrillConfig(type, requestedConfig = {}) {const config = await getPostConfig();+ // Maintenance-review rep (issue #2096): a review rep targets a SPECIFIC lower+ // rung on purpose, so bypass the progression override entirely and run the+ // explicit level/factors the review scheduler chose. Without this the ladder+ // would silently re-resolve the level up to the user's current rung, defeating+ // the whole point of re-verifying a mastered-but-inactive skill.+ if (requestedConfig?.review) {+ return { config: requestedConfig, adaptive: null, progression: null };+ }+// Progressive multiplication ladder (default ON) — independent of the generic// Adaptive toggle. Selects the factor structure by speed-gated mastery so a// fresh user starts at single-digit × single-digit instead of a fixed harddiff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex e1cdfef52a..ce5e76a349 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -34,6 +34,7 @@ import {deriveTaskCompletion,getCognitiveProgress,generateDrill,+ getSessionSkillContext,} from './meatspacePost.js';// =============================================================================@@ -626,7 +627,7 @@ describe('submitPostSession — memory drill schedule advance', () => {expect(memoryWrites.length).toBe(1);const masteryWrite = memoryWrites[memoryWrites.length - 1];const updatedItem = masteryWrite[1].items.find(i => i.id === 'song-1');- expect(updatedItem.mastery.chunks['verse-1']).toEqual({ correct: 1, attempts: 2, lastPracticed: expect.any(String) });+ expect(updatedItem.mastery.chunks['verse-1']).toEqual({ correct: 1, attempts: 2, lastPracticed: expect.any(String), recent: [1, 0] });});it('buckets memory-element-flash answers into element mastery via the element attribution', async () => {@@ -649,7 +650,7 @@ describe('submitPostSession — memory drill schedule advance', () => {const memoryWrites = atomicWrite.mock.calls.filter(([path]) => String(path).includes('post-memory-items'));const masteryWrite = memoryWrites[memoryWrites.length - 1];const updatedItem = masteryWrite[1].items.find(i => i.id === 'song-1');- expect(updatedItem.mastery.elements.H).toEqual({ correct: 1, attempts: 1 });+ expect(updatedItem.mastery.elements.H).toEqual({ correct: 1, attempts: 1, recent: [1] });});it('does not touch memory items for a session with no memory tasks', async () => {@@ -723,7 +724,7 @@ describe('submitPostSession — memory drill schedule advance', () => {expect(updatedItem.schedule.intervalDays).toBeGreaterThan(0);const masteryWrite = memoryWrites[memoryWrites.length - 1];const updatedMastery = masteryWrite[1].items.find(i => i.id === 'song-1');- expect(updatedMastery.mastery.chunks['verse-1']).toEqual({ correct: 1, attempts: 1, lastPracticed: expect.any(String) });+ expect(updatedMastery.mastery.chunks['verse-1']).toEqual({ correct: 1, attempts: 1, lastPracticed: expect.any(String), recent: [1] });});});@@ -1782,3 +1783,59 @@ describe('submitPostSession — memory post-processing never 500s a saved sessioexpect(sessionWrite[1].sessions.length).toBe(1);});});++// =============================================================================+// SKILL RE-VERIFICATION HOOKS (issue #2096)+// =============================================================================++describe('getSessionSkillContext', () => {+ it('extracts a passed review rep from a task carrying reviewSkillId (accuracy >= 0.8)', () => {+ const session = { tasks: [{+ type: 'multiplication',+ config: { level: 1, factors: [1, 2], review: true, reviewSkillId: 'multiplication:L1' },+ questions: [+ { answered: 10, correct: true }, { answered: 20, correct: true },+ { answered: 30, correct: true }, { answered: 40, correct: true },+ { answered: 50, correct: false },+ ],+ }] };+ const { reviewResults, practicedSkillIds } = getSessionSkillContext(session);+ expect(reviewResults).toEqual([{ skillId: 'multiplication:L1', passed: true }]); // 4/5 = 0.8+ expect(practicedSkillIds).toEqual([]); // a review rep is NOT counted as practice+ });++ it('marks a review rep failed when answered accuracy < 0.8', () => {+ const session = { tasks: [{+ type: 'multiplication',+ config: { level: 1, review: true, reviewSkillId: 'multiplication:L1' },+ questions: [+ { answered: 10, correct: true }, { answered: 20, correct: false }, { answered: 30, correct: false },+ ],+ }] };+ expect(getSessionSkillContext(session).reviewResults).toEqual([{ skillId: 'multiplication:L1', passed: false }]);+ });++ it('collects practiced skill ids from normal (non-review) multiplication / cognitive / memory tasks', () => {+ const session = { tasks: [+ { type: 'multiplication', config: { level: 2 }, questions: [{ answered: 1, correct: true }] },+ { type: 'n-back', config: { level: 1 }, accuracy: 0.9, questions: [] },+ { type: 'memory-sequence', memoryItemId: 'song-1', questions: [{ chunkId: 'verse-1', correct: true }, { chunkId: 'verse-2', correct: true }] },+ ] };+ const { practicedSkillIds, reviewResults } = getSessionSkillContext(session);+ expect(reviewResults).toEqual([]);+ expect(practicedSkillIds.sort()).toEqual([+ 'cognitive:n-back:L1', 'memory:song-1:verse-1', 'memory:song-1:verse-2', 'multiplication:L2',+ ]);+ });+});++describe('resolveDrillConfig — maintenance-review bypass (issue #2096)', () => {+ it('a review request passes its explicit level/factors through untouched (no ladder override)', async () => {+ const requested = { count: 5, level: 0, factors: [1, 1], review: true, reviewSkillId: 'multiplication:L0' };+ const { config, progression } = await resolveDrillConfig('multiplication', requested);+ // Level 0 survives — the progression ladder did NOT re-resolve it to the+ // user's current (higher) rung, which is the whole point of a review rep.+ expect(config).toEqual(requested);+ expect(progression).toBeNull();+ });+});diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.jsindex fef41e6840..8db52186df 100644--- a/server/services/meatspacePostMemory.js+++ b/server/services/meatspacePostMemory.js@@ -27,6 +27,56 @@ const TRAINING_LOG_FILE = join(MEATSPACE_DIR, 'post-training-log.json');// due now (see `ensureSchedule`) and get a persisted default by migration 154.export const DEFAULT_EASE = 2.5;+// =============================================================================+// WINDOWED (DECAY-AWARE) MASTERY+// =============================================================================+//+// Element/chunk mastery is judged over a rolling window of the most-recent+// attempts, NOT cumulative all-time counts — so a run of recent misses lowers+// mastery (decay-aware) instead of an early wrong answer being permanently+// diluted, and mastery reflects whether you STILL know it. The cumulative+// `correct`/`attempts` counts are kept for history; the window rides alongside+// as a bounded `recent` array of per-attempt correctness (1/0, most-recent+// last, capped at MASTERY_WINDOW). Legacy items with no `recent` array fall back+// to the cumulative counts so old data still reports sensibly (issue #2096).+export const MASTERY_WINDOW = 10;+// Mastery gate: at least this many attempts (in the window) at ≥ this accuracy.+export const MASTERY_MIN_ATTEMPTS = 3;+export const MASTERY_TARGET_ACCURACY = 0.8;++/** Push a per-attempt correctness flag onto a mastery stat's rolling window. */+function pushRecent(stat, correct) {+ if (!Array.isArray(stat.recent)) stat.recent = [];+ stat.recent.push(correct ? 1 : 0);+ if (stat.recent.length > MASTERY_WINDOW) {+ stat.recent = stat.recent.slice(-MASTERY_WINDOW);+ }+}++/**+ * Recency-weighted accuracy for a mastery stat: uses the bounded `recent`+ * window when present (decay-aware — recent misses lower it), else falls back to+ * the cumulative all-time `correct`/`attempts` for legacy items with no window.+ * Returns `{ attempts, accuracy }` where `attempts` is the count the mastery+ * gate is judged against.+ */+export function windowedAccuracy(stat) {+ if (Array.isArray(stat?.recent) && stat.recent.length) {+ const attempts = stat.recent.length;+ const correct = stat.recent.reduce((sum, r) => sum + (r ? 1 : 0), 0);+ return { attempts, accuracy: attempts ? correct / attempts : 0 };+ }+ const attempts = Number.isFinite(stat?.attempts) ? stat.attempts : 0;+ const correct = Number.isFinite(stat?.correct) ? stat.correct : 0;+ return { attempts, accuracy: attempts ? correct / attempts : 0 };+}++/** True when a mastery stat clears the windowed gate (≥3 recent attempts, ≥0.8). */+export function isStatMastered(stat) {+ const { attempts, accuracy } = windowedAccuracy(stat);+ return attempts >= MASTERY_MIN_ATTEMPTS && accuracy >= MASTERY_TARGET_ACCURACY;+}+const MIN_EASE = 1.3;// Ceiling mirrors `memoryScheduleSchema.ease.max(5)` in postValidation.js — the// per-session +0.1 bumps are unbounded otherwise, so ~26 perfect reps would push@@ -411,6 +461,8 @@ export async function submitPractice(id, practiceData) {chunk.attempts += results.length;chunk.correct += results.filter(r => r.correct).length;chunk.lastPracticed = now;+ // Rolling window for decay-aware mastery (issue #2096) — one flag per result.+ for (const r of results) pushRecent(chunk, r.correct);}// Update element-level mastery (for elements song)@@ -420,8 +472,10 @@ export async function submitPractice(id, practiceData) {if (!item.mastery.elements[r.element]) {item.mastery.elements[r.element] = { correct: 0, attempts: 0 };}- item.mastery.elements[r.element].attempts++;- if (r.correct) item.mastery.elements[r.element].correct++;+ const el = item.mastery.elements[r.element];+ el.attempts++;+ if (r.correct) el.correct++;+ pushRecent(el, r.correct);}}}@@ -512,13 +566,16 @@ function applyMasteryMergeToItem(item, questions, now) {chunk.attempts += 1;if (q.correct) chunk.correct += 1;chunk.lastPracticed = nowIso;+ pushRecent(chunk, q.correct);}if (q.element) {if (!item.mastery.elements[q.element]) {item.mastery.elements[q.element] = { correct: 0, attempts: 0 };}- item.mastery.elements[q.element].attempts += 1;- if (q.correct) item.mastery.elements[q.element].correct += 1;+ const el = item.mastery.elements[q.element];+ el.attempts += 1;+ if (q.correct) el.correct += 1;+ pushRecent(el, q.correct);}}@@ -793,23 +850,26 @@ function generateElementFlash(item, count) {// HELPERS// =============================================================================-function computeOverallMastery(item) {- // For elements song: mastery is based on per-element accuracy+export function computeOverallMastery(item) {+ // For elements song: mastery is per-element, judged over the recency window+ // (decay-aware, issue #2096) — a recent run of misses lowers the count. The+ // ≥3-attempt gate is kept, but applied to the window (or the cumulative+ // fallback for legacy items with no window).if (item.id === 'elements-song' && item.content.elementMap) {const totalElements = Object.keys(item.content.elementMap).length;if (totalElements === 0) return 0;let masteredCount = 0;for (const sym of Object.keys(item.content.elementMap)) {const m = item.mastery.elements[sym];- if (m && m.attempts >= 3 && m.correct / m.attempts >= 0.8) masteredCount++;+ if (m && isStatMastered(m)) masteredCount++;}return Math.round((masteredCount / totalElements) * 100);}- // For generic items: mastery is based on chunk accuracy+ // For generic items: mastery is based on windowed chunk accuracy.const chunks = Object.values(item.mastery.chunks);if (!chunks.length) return 0;- const avgAccuracy = chunks.reduce((sum, c) => sum + (c.attempts > 0 ? c.correct / c.attempts : 0), 0) / chunks.length;+ const avgAccuracy = chunks.reduce((sum, c) => sum + windowedAccuracy(c).accuracy, 0) / chunks.length;return Math.round(avgAccuracy * 100);}diff --git a/server/services/meatspacePostMemory.test.js b/server/services/meatspacePostMemory.test.jsindex 37974e7cc9..b430f47dc0 100644--- a/server/services/meatspacePostMemory.test.js+++ b/server/services/meatspacePostMemory.test.js@@ -30,6 +30,10 @@ import {defaultSchedule,DEFAULT_EASE,ELEMENTS_SONG,+ windowedAccuracy,+ isStatMastered,+ computeOverallMastery,+ MASTERY_WINDOW,} from './meatspacePostMemory.js';// =============================================================================@@ -517,8 +521,8 @@ describe('mergeMasteryFromSession', () => {{ chunkId: 'verse-2', correct: true },], now);- expect(result.chunks['verse-1']).toEqual({ correct: 1, attempts: 2, lastPracticed: now.toISOString() });- expect(result.chunks['verse-2']).toEqual({ correct: 1, attempts: 1, lastPracticed: now.toISOString() });+ expect(result.chunks['verse-1']).toEqual({ correct: 1, attempts: 2, lastPracticed: now.toISOString(), recent: [1, 0] });+ expect(result.chunks['verse-2']).toEqual({ correct: 1, attempts: 1, lastPracticed: now.toISOString(), recent: [1] });expect(atomicWrite).toHaveBeenCalledTimes(1);});@@ -536,8 +540,8 @@ describe('mergeMasteryFromSession', () => {{ element: 'He', correct: false },], now);- expect(result.elements.H).toEqual({ correct: 2, attempts: 2 });- expect(result.elements.He).toEqual({ correct: 0, attempts: 1 });+ expect(result.elements.H).toEqual({ correct: 2, attempts: 2, recent: [1, 1] });+ expect(result.elements.He).toEqual({ correct: 0, attempts: 1, recent: [0] });});it('accumulates onto existing mastery counts rather than overwriting them', async () => {@@ -556,7 +560,7 @@ describe('mergeMasteryFromSession', () => {{ chunkId: 'verse-1', correct: true },], now);- expect(result.chunks['verse-1']).toEqual({ correct: 3, attempts: 4, lastPracticed: now.toISOString() });+ expect(result.chunks['verse-1']).toEqual({ correct: 3, attempts: 4, lastPracticed: now.toISOString(), recent: [1] });});it('ignores questions with neither chunkId nor element', async () => {@@ -800,3 +804,112 @@ describe('submitPractice — schedule advancement', () => {expect(result.schedule.intervalDays).toBe(0);});});++// =============================================================================+// DECAY-AWARE WINDOWED MASTERY (issue #2096)+// =============================================================================++describe('windowedAccuracy / isStatMastered', () => {+ it('uses the recent window when present (decay-aware)', () => {+ // Cumulative would read 8/10=80%, but the recent window is a run of misses.+ const stat = { correct: 8, attempts: 10, recent: [0, 0, 0, 1] };+ expect(windowedAccuracy(stat)).toEqual({ attempts: 4, accuracy: 0.25 });+ expect(isStatMastered(stat)).toBe(false);+ });++ it('falls back to cumulative counts for legacy stats with no recent window', () => {+ const stat = { correct: 9, attempts: 10 }; // no `recent`+ expect(windowedAccuracy(stat)).toEqual({ attempts: 10, accuracy: 0.9 });+ expect(isStatMastered(stat)).toBe(true);+ });++ it('enforces the >=3-attempt gate on the window', () => {+ expect(isStatMastered({ recent: [1, 1] })).toBe(false); // 2 attempts — gated+ expect(isStatMastered({ recent: [1, 1, 1] })).toBe(true); // 3 attempts, 100%+ expect(isStatMastered({ recent: [1, 1, 0] })).toBe(false); // 3 attempts, 67% < 0.8+ });++ it('masters at exactly the 0.8 window accuracy', () => {+ expect(isStatMastered({ recent: [1, 1, 1, 1, 0] })).toBe(true); // 4/5 = 0.8+ });+});++describe('computeOverallMastery — ratchet removed, decay-aware (issue #2096)', () => {+ const songWith = (elements) => ({+ id: 'elements-song',+ content: { elementMap: { H: {}, He: {} } },+ mastery: { chunks: {}, elements },+ });++ it('a recent run of misses LOWERS element mastery (no permanent ratchet)', () => {+ // Both elements were mastered all-time (high cumulative), but H just had a+ // window full of recent misses — mastery must drop, not ratchet.+ const before = songWith({+ H: { correct: 20, attempts: 20, recent: [1, 1, 1, 1, 1] },+ He: { correct: 20, attempts: 20, recent: [1, 1, 1, 1, 1] },+ });+ expect(computeOverallMastery(before)).toBe(100);++ const after = songWith({+ H: { correct: 20, attempts: 25, recent: [0, 0, 0, 0, 0] }, // recent decay+ He: { correct: 20, attempts: 20, recent: [1, 1, 1, 1, 1] },+ });+ expect(computeOverallMastery(after)).toBe(50); // H no longer mastered+ });++ it('early misses recover — an element answered wrong early is not permanently diluted', () => {+ // Cumulative 6/10 = 60% (would fail the old all-time >=0.8 gate forever), but+ // the recent window is clean, so it now reads as mastered.+ const item = songWith({+ H: { correct: 6, attempts: 10, recent: [1, 1, 1, 1, 1] },+ He: { correct: 10, attempts: 10, recent: [1, 1, 1, 1, 1] },+ });+ expect(computeOverallMastery(item)).toBe(100);+ });++ it('keeps the >=3-attempt gate (a barely-practiced element is not mastered)', () => {+ const item = songWith({+ H: { correct: 2, attempts: 2, recent: [1, 1] }, // only 2 attempts+ He: { correct: 10, attempts: 10, recent: [1, 1, 1] },+ });+ expect(computeOverallMastery(item)).toBe(50); // only He counts+ });++ it('legacy items with no recent window still report via cumulative counts', () => {+ const item = songWith({+ H: { correct: 9, attempts: 10 }, // legacy shape, 90% >= 0.8+ He: { correct: 5, attempts: 10 }, // 50% < 0.8+ });+ expect(computeOverallMastery(item)).toBe(50);+ });++ it('windows generic-item chunk mastery too', () => {+ const item = {+ id: 'custom',+ content: { chunks: [] },+ mastery: {+ elements: {},+ chunks: {+ a: { correct: 10, attempts: 10, recent: [0, 0, 0, 0] }, // recent decay → 0%+ b: { correct: 10, attempts: 10, recent: [1, 1, 1, 1] }, // 100%+ },+ },+ };+ expect(computeOverallMastery(item)).toBe(50); // (0 + 100) / 2+ });+});++describe('mastery window is bounded', () => {+ it('caps the recent array at MASTERY_WINDOW entries', async () => {+ readJSONFile.mockResolvedValueOnce({+ items: [{+ ...ELEMENTS_SONG,+ mastery: { overallPct: 0, chunks: {}, elements: {} },+ }],+ });+ const answers = Array.from({ length: MASTERY_WINDOW + 5 }, () => ({ element: 'H', correct: true }));+ const result = await mergeMasteryFromSession('elements-song', answers, new Date());+ expect(result.elements.H.recent.length).toBe(MASTERY_WINDOW);+ expect(result.elements.H.attempts).toBe(MASTERY_WINDOW + 5); // cumulative unbounded+ });+});diff --git a/server/services/meatspacePostReview.js b/server/services/meatspacePostReview.jsnew file mode 100644index 0000000000..05058863a7--- /dev/null+++ b/server/services/meatspacePostReview.js@@ -0,0 +1,312 @@+/**+ * MeatSpace POST — Skill re-verification scheduler (issue #2096)+ *+ * POST can detect when you've MASTERED a skill (a multiplication rung below your+ * current level, a cognitive rung you've passed, a mastered memory chunk) but+ * never checked whether you STILL know it. This service adds a lightweight,+ * SM-2-style review scheduler for those mastered-but-inactive skills:+ *+ * - When a skill first becomes mastered it's tracked with `masteredAt` and a+ * first review due 7 days out.+ * - Left un-practiced, it goes "due for review" on an expanding interval+ * (7 → 30 → 90 days). Passing a maintenance review pushes the next review+ * further out; failing one flips it to "needs refresh" and schedules a+ * sooner re-review — but NEVER demotes the underlying `floorLevel` (the+ * anti-frustration guard lives in the progression ladder, untouched here).+ * - Actively practicing a mastered skill (any non-review session at it) resets+ * its staleness clock, so only genuinely inactive skills ever surface.+ *+ * Storage: `data/meatspace/post-review-schedule.json` — a small sibling of the+ * other `data/meatspace/post-*.json` files. Meatspace is `file-primary` per+ * docs/STORAGE.md (an iCloud/file-sync store family), so a JSON sibling is the+ * classification-correct home; the schedule is created lazily on first mastery,+ * so a fresh install (or legacy data with no schedule) simply has nothing due.+ *+ * This module is a pure store + scheduler: it does NOT read session history or+ * compute mastery itself (that lives in meatspacePost.js / meatspacePostMemory.js+ * which already import both). Callers hand it skill descriptors; it owns the+ * review-schedule state machine and one load-modify-save per session.+ */++import { join } from 'path';+import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';++const MEATSPACE_DIR = PATHS.meatspace;+const REVIEW_SCHEDULE_FILE = join(MEATSPACE_DIR, 'post-review-schedule.json');++// Expanding review intervals (days) after mastery — SM-2-flavored per skill.+export const REVIEW_INTERVALS_DAYS = [7, 30, 90];+// A failed review schedules a much sooner re-review (and flips to needs-refresh).+export const REFRESH_INTERVAL_DAYS = 3;+// Retention % window (reviews passed / taken) reported in the progress dashboard.+export const RETENTION_WINDOW_DAYS = 90;+// Cap the per-skill review history so the file can't grow without bound.+const MAX_REVIEW_HISTORY = 25;+const DAY_MS = 24 * 60 * 60 * 1000;++function addDays(nowMs, days) {+ return new Date(nowMs + days * DAY_MS).toISOString();+}++function intervalForStage(stage) {+ const idx = Math.max(0, Math.min(REVIEW_INTERVALS_DAYS.length - 1, stage));+ return REVIEW_INTERVALS_DAYS[idx];+}++// =============================================================================+// STORE+// =============================================================================++async function loadReviewSchedule() {+ const data = await readJSONFile(REVIEW_SCHEDULE_FILE, { skills: {} }, { allowArray: false });+ const skills = data?.skills && typeof data.skills === 'object' ? data.skills : {};+ return { skills };+}++async function saveReviewSchedule(schedule) {+ await ensureDir(MEATSPACE_DIR);+ await atomicWrite(REVIEW_SCHEDULE_FILE, { skills: schedule.skills || {} });+}++// =============================================================================+// PURE STATE-MACHINE HELPERS (exported for unit tests)+// =============================================================================++/** Fresh entry for a newly-mastered skill — first review one interval out. */+export function defaultReviewEntry(skill, now = new Date()) {+ const nowMs = now.getTime();+ const nowIso = now.toISOString();+ return {+ skillId: skill.skillId,+ kind: skill.kind, // 'multiplication' | 'cognitive' | 'memory'+ label: skill.label,+ drillType: skill.drillType, // drill type to regenerate a review rep+ level: skill.level ?? null, // rung index (multiplication/cognitive)+ factors: skill.factors ?? null, // multiplication factor plan+ config: skill.config ?? null, // cognitive rung knobs for regeneration+ memoryItemId: skill.memoryItemId ?? null,+ chunkId: skill.chunkId ?? null,+ masteredAt: nowIso,+ lastPracticedAt: nowIso,+ lastReviewedAt: null,+ reviewStage: 0,+ nextReviewAt: addDays(nowMs, REVIEW_INTERVALS_DAYS[0]),+ status: 'fresh', // 'fresh' | 'needs-refresh'+ reviewsPassed: 0,+ reviewsTaken: 0,+ reviewHistory: [], // [{ date, passed }]+ };+}++/** True when a tracked skill's review is due (`nextReviewAt <= now`). */+export function isReviewDue(entry, now = new Date()) {+ const t = Date.parse(entry?.nextReviewAt ?? '');+ if (Number.isNaN(t)) return true;+ return t <= now.getTime();+}++/**+ * Retention state for reporting: `fresh` (mastered, not yet due), `due` (review+ * overdue), or `needs-refresh` (last review failed, awaiting a sooner re-review).+ */+export function reviewState(entry, now = new Date()) {+ if (entry?.status === 'needs-refresh') return 'needs-refresh';+ return isReviewDue(entry, now) ? 'due' : 'fresh';+}++/**+ * 90-day retention: reviews passed / reviews taken within the window. Returns+ * `null` when no reviews have been taken in the window (nothing to report yet).+ */+export function retentionForEntry(entry, now = new Date(), windowDays = RETENTION_WINDOW_DAYS) {+ const cutoff = now.getTime() - windowDays * DAY_MS;+ const history = Array.isArray(entry?.reviewHistory) ? entry.reviewHistory : [];+ let taken = 0;+ let passed = 0;+ for (const h of history) {+ const t = Date.parse(h?.date ?? '');+ if (Number.isNaN(t) || t < cutoff) continue;+ taken += 1;+ if (h.passed) passed += 1;+ }+ return { reviewsTaken: taken, reviewsPassed: passed, retentionPct: taken ? Math.round((passed / taken) * 100) : null };+}++/** Apply a passed/failed review to an entry (pure — returns a new entry). */+export function applyReviewResult(entry, passed, now = new Date()) {+ const nowMs = now.getTime();+ const nowIso = now.toISOString();+ const history = [...(Array.isArray(entry.reviewHistory) ? entry.reviewHistory : []), { date: nowIso, passed: !!passed }]+ .slice(-MAX_REVIEW_HISTORY);+ const next = {+ ...entry,+ lastReviewedAt: nowIso,+ lastPracticedAt: nowIso,+ reviewsTaken: (entry.reviewsTaken || 0) + 1,+ reviewsPassed: (entry.reviewsPassed || 0) + (passed ? 1 : 0),+ reviewHistory: history,+ };+ if (passed) {+ // Passed a maintenance rep — push the next review further out (expanding+ // interval) and clear any needs-refresh flag.+ next.reviewStage = Math.min(REVIEW_INTERVALS_DAYS.length - 1, (entry.reviewStage || 0) + 1);+ next.status = 'fresh';+ next.nextReviewAt = addDays(nowMs, intervalForStage(next.reviewStage));+ } else {+ // Failed — flip to needs-refresh and re-review much sooner. NEVER touches+ // floorLevel: the anti-frustration ladder guard is intentionally untouched.+ next.reviewStage = 0;+ next.status = 'needs-refresh';+ next.nextReviewAt = addDays(nowMs, REFRESH_INTERVAL_DAYS);+ }+ return next;+}++/**+ * Actively practicing a mastered skill (a normal, non-review session at it)+ * resets its staleness clock so it doesn't nag for a maintenance rep the user is+ * already doing. Refreshes `lastPracticedAt` and pushes `nextReviewAt` out by+ * the current stage's interval; does not count as a formal review.+ */+export function applyPractice(entry, now = new Date()) {+ const nowMs = now.getTime();+ return {+ ...entry,+ lastPracticedAt: now.toISOString(),+ // Only push the clock FORWARD — never pull a due/needs-refresh review earlier.+ nextReviewAt: (() => {+ const bumped = addDays(nowMs, intervalForStage(entry.reviewStage || 0));+ const cur = Date.parse(entry.nextReviewAt ?? '');+ return Number.isNaN(cur) || Date.parse(bumped) > cur ? bumped : entry.nextReviewAt;+ })(),+ // Practicing a needs-refresh skill clears the refresh flag (they're on it).+ status: entry.status === 'needs-refresh' ? 'fresh' : entry.status,+ };+}++// =============================================================================+// SESSION SYNC — one load-modify-save+// =============================================================================++/**+ * Reconcile the review schedule against a just-completed session:+ * 1. Upsert every currently-mastered skill (new ones get `masteredAt=now` ++ * a first review 7d out). Existing entries refresh their label/drill+ * metadata but keep their review schedule.+ * 2. Record formal review results for review reps in this session+ * (`reviewResults`) — pass pushes the interval out, fail → needs-refresh.+ * 3. Reset the staleness clock for mastered skills actively practiced this+ * session (`practicedSkillIds`) that were NOT themselves review reps.+ *+ * @param {object} args+ * @param {Array} args.masteredSkills - current mastered-skill descriptors+ * @param {string[]} [args.practicedSkillIds] - skill ids exercised this session+ * @param {Array<{skillId,passed}>} [args.reviewResults] - review-rep outcomes+ * @param {Date} [args.now]+ * @returns {Promise<{added:number, reviewed:number, refreshed:number}>}+ */+export async function applySessionToReviewSchedule({ masteredSkills = [], practicedSkillIds = [], reviewResults = [], now = new Date() } = {}) {+ const schedule = await loadReviewSchedule();+ const skills = schedule.skills;+ let added = 0;+ let reviewed = 0;+ let refreshed = 0;++ // 1. Upsert mastered skills.+ for (const skill of masteredSkills) {+ if (!skill?.skillId) continue;+ const existing = skills[skill.skillId];+ if (!existing) {+ skills[skill.skillId] = defaultReviewEntry(skill, now);+ added += 1;+ } else {+ // Refresh mutable descriptor metadata (label/drill config can evolve) but+ // preserve the earned review schedule.+ existing.label = skill.label ?? existing.label;+ existing.drillType = skill.drillType ?? existing.drillType;+ existing.level = skill.level ?? existing.level;+ existing.factors = skill.factors ?? existing.factors;+ existing.config = skill.config ?? existing.config;+ existing.memoryItemId = skill.memoryItemId ?? existing.memoryItemId;+ existing.chunkId = skill.chunkId ?? existing.chunkId;+ }+ }++ // 2. Record formal review results.+ const reviewedIds = new Set();+ for (const r of reviewResults) {+ if (!r?.skillId || !skills[r.skillId]) continue;+ skills[r.skillId] = applyReviewResult(skills[r.skillId], !!r.passed, now);+ reviewedIds.add(r.skillId);+ reviewed += 1;+ }++ // 3. Reset staleness for actively-practiced (non-review) mastered skills.+ for (const id of practicedSkillIds) {+ if (reviewedIds.has(id)) continue; // a review rep already updated it+ if (!skills[id]) continue;+ skills[id] = applyPractice(skills[id], now);+ refreshed += 1;+ }++ await saveReviewSchedule(schedule);+ if (added || reviewed) {+ console.log(`🔁 POST review schedule: +${added} mastered, ${reviewed} reviewed, ${refreshed} refreshed`);+ }+ return { added, reviewed, refreshed };+}++// =============================================================================+// READ API+// =============================================================================++/** All tracked review entries (array). */+export async function getReviewSchedule() {+ const { skills } = await loadReviewSchedule();+ return Object.values(skills);+}++/**+ * Mastered skills whose maintenance review is currently due (or needs-refresh),+ * most-overdue first, capped at `limit`. These become the labeled "maintenance+ * reps" the launcher mixes into a Quick session.+ */+export async function getDueReviews(now = new Date(), limit = 2) {+ const entries = await getReviewSchedule();+ return entries+ .filter(e => reviewState(e, now) !== 'fresh')+ .sort((a, b) => Date.parse(a.nextReviewAt || 0) - Date.parse(b.nextReviewAt || 0))+ .slice(0, Math.max(0, limit));+}++/**+ * Per-skill retention states + an overall 90-day retention % for the progress+ * dashboard mastery block (issue #2091 + #2096).+ */+export async function getRetentionReport(now = new Date()) {+ const entries = await getReviewSchedule();+ let totalTaken = 0;+ let totalPassed = 0;+ const skills = entries.map(e => {+ const ret = retentionForEntry(e, now);+ totalTaken += ret.reviewsTaken;+ totalPassed += ret.reviewsPassed;+ return {+ skillId: e.skillId,+ kind: e.kind,+ label: e.label,+ state: reviewState(e, now),+ masteredAt: e.masteredAt,+ nextReviewAt: e.nextReviewAt,+ retentionPct: ret.retentionPct,+ };+ });+ const dueCount = skills.filter(s => s.state !== 'fresh').length;+ return {+ skills,+ dueCount,+ trackedCount: skills.length,+ retentionPct: totalTaken ? Math.round((totalPassed / totalTaken) * 100) : null,+ windowDays: RETENTION_WINDOW_DAYS,+ };+}diff --git a/server/services/meatspacePostReview.test.js b/server/services/meatspacePostReview.test.jsnew file mode 100644index 0000000000..835e274fe8--- /dev/null+++ b/server/services/meatspacePostReview.test.js@@ -0,0 +1,210 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock file I/O so the store tests stay pure — one in-memory schedule the mock+// reads/writes, so applySession* → getDueReviews round-trips without touching disk.+let store = { skills: {} };+vi.mock('../lib/fileUtils.js', () => ({+ atomicWrite: vi.fn((path, data) => { store = data; return Promise.resolve(); }),+ PATHS: { meatspace: '/tmp/test-meatspace' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ readJSONFile: vi.fn(() => Promise.resolve(store)),+}));++import {+ REVIEW_INTERVALS_DAYS,+ REFRESH_INTERVAL_DAYS,+ defaultReviewEntry,+ isReviewDue,+ reviewState,+ applyReviewResult,+ applyPractice,+ retentionForEntry,+ applySessionToReviewSchedule,+ getDueReviews,+ getRetentionReport,+} from './meatspacePostReview.js';++const DAY = 86400000;+const skill = (over = {}) => ({ skillId: 'multiplication:L0', kind: 'multiplication', label: 'Multiplication 1×1-digit', drillType: 'multiplication', level: 0, factors: [1, 1], ...over });++beforeEach(() => {+ store = { skills: {} };+ vi.clearAllMocks();+});++describe('defaultReviewEntry', () => {+ it('schedules the first review one (7-day) interval out and starts fresh', () => {+ const now = new Date('2026-07-01T00:00:00.000Z');+ const entry = defaultReviewEntry(skill(), now);+ expect(entry.status).toBe('fresh');+ expect(entry.reviewStage).toBe(0);+ expect(entry.masteredAt).toBe(now.toISOString());+ expect(Date.parse(entry.nextReviewAt) - now.getTime()).toBe(REVIEW_INTERVALS_DAYS[0] * DAY);+ expect(entry.reviewsTaken).toBe(0);+ });+});++describe('isReviewDue / reviewState', () => {+ const now = new Date('2026-07-10T00:00:00.000Z');+ it('fresh before nextReviewAt, due after', () => {+ const fresh = { nextReviewAt: new Date(now.getTime() + DAY).toISOString(), status: 'fresh' };+ const overdue = { nextReviewAt: new Date(now.getTime() - DAY).toISOString(), status: 'fresh' };+ expect(isReviewDue(fresh, now)).toBe(false);+ expect(reviewState(fresh, now)).toBe('fresh');+ expect(isReviewDue(overdue, now)).toBe(true);+ expect(reviewState(overdue, now)).toBe('due');+ });+ it('needs-refresh state wins over fresh/due classification', () => {+ const entry = { nextReviewAt: new Date(now.getTime() + DAY).toISOString(), status: 'needs-refresh' };+ expect(reviewState(entry, now)).toBe('needs-refresh');+ });+ it('treats a missing/invalid nextReviewAt as due', () => {+ expect(isReviewDue({}, now)).toBe(true);+ });+});++describe('applyReviewResult — expanding intervals', () => {+ const now = new Date('2026-07-15T00:00:00.000Z');+ it('a passed review advances the stage and pushes the next review FURTHER out', () => {+ const entry = defaultReviewEntry(skill(), new Date('2026-07-01T00:00:00.000Z'));+ const after = applyReviewResult(entry, true, now);+ expect(after.status).toBe('fresh');+ expect(after.reviewStage).toBe(1);+ expect(Date.parse(after.nextReviewAt) - now.getTime()).toBe(REVIEW_INTERVALS_DAYS[1] * DAY);+ expect(after.reviewsPassed).toBe(1);+ expect(after.reviewsTaken).toBe(1);+ });+ it('successive passes keep expanding, then cap at the last interval', () => {+ let entry = defaultReviewEntry(skill(), now);+ entry = applyReviewResult(entry, true, now); // stage 1+ entry = applyReviewResult(entry, true, now); // stage 2 (last)+ entry = applyReviewResult(entry, true, now); // stays stage 2+ expect(entry.reviewStage).toBe(REVIEW_INTERVALS_DAYS.length - 1);+ expect(Date.parse(entry.nextReviewAt) - now.getTime()).toBe(REVIEW_INTERVALS_DAYS[REVIEW_INTERVALS_DAYS.length - 1] * DAY);+ });+ it('a failed review flips to needs-refresh and schedules a SOONER re-review, resetting the stage', () => {+ let entry = defaultReviewEntry(skill(), now);+ entry = applyReviewResult(entry, true, now); // stage 1+ const failed = applyReviewResult(entry, false, now);+ expect(failed.status).toBe('needs-refresh');+ expect(failed.reviewStage).toBe(0);+ expect(Date.parse(failed.nextReviewAt) - now.getTime()).toBe(REFRESH_INTERVAL_DAYS * DAY);+ expect(REFRESH_INTERVAL_DAYS).toBeLessThan(REVIEW_INTERVALS_DAYS[0]);+ expect(failed.reviewsPassed).toBe(1); // the earlier pass still counted+ expect(failed.reviewsTaken).toBe(2);+ });+ it('never carries a floorLevel field — demotion is out of scope for the scheduler', () => {+ const entry = defaultReviewEntry(skill(), now);+ const failed = applyReviewResult(entry, false, now);+ expect(failed).not.toHaveProperty('floorLevel');+ });+});++describe('applyPractice — active use resets staleness', () => {+ it('pushes nextReviewAt forward and clears needs-refresh, but never pulls it earlier', () => {+ const now = new Date('2026-08-01T00:00:00.000Z');+ const stale = { ...defaultReviewEntry(skill(), new Date('2026-07-01T00:00:00.000Z')), status: 'needs-refresh', reviewStage: 0, nextReviewAt: '2026-07-08T00:00:00.000Z' };+ const after = applyPractice(stale, now);+ expect(after.status).toBe('fresh');+ expect(Date.parse(after.nextReviewAt)).toBeGreaterThan(now.getTime());+ expect(after.lastPracticedAt).toBe(now.toISOString());+ });+ it('does not pull a far-future review earlier', () => {+ const now = new Date('2026-08-01T00:00:00.000Z');+ const future = { ...defaultReviewEntry(skill(), now), reviewStage: 2, nextReviewAt: new Date(now.getTime() + 90 * DAY).toISOString() };+ const after = applyPractice(future, now);+ expect(after.nextReviewAt).toBe(future.nextReviewAt);+ });+});++describe('retentionForEntry — 90-day retention %', () => {+ const now = new Date('2026-07-15T00:00:00.000Z');+ it('is passed/taken over the window, null when no in-window reviews', () => {+ expect(retentionForEntry({ reviewHistory: [] }, now).retentionPct).toBeNull();+ const entry = { reviewHistory: [+ { date: new Date(now.getTime() - 10 * DAY).toISOString(), passed: true },+ { date: new Date(now.getTime() - 20 * DAY).toISOString(), passed: false },+ { date: new Date(now.getTime() - 5 * DAY).toISOString(), passed: true },+ ] };+ expect(retentionForEntry(entry, now)).toMatchObject({ reviewsTaken: 3, reviewsPassed: 2, retentionPct: 67 });+ });+ it('excludes reviews older than the window', () => {+ const entry = { reviewHistory: [+ { date: new Date(now.getTime() - 200 * DAY).toISOString(), passed: false },+ { date: new Date(now.getTime() - 1 * DAY).toISOString(), passed: true },+ ] };+ expect(retentionForEntry(entry, now)).toMatchObject({ reviewsTaken: 1, reviewsPassed: 1, retentionPct: 100 });+ });+});++describe('applySessionToReviewSchedule — session sync', () => {+ it('upserts newly-mastered skills (fresh installs: nothing tracked until first mastery)', async () => {+ expect(await getDueReviews(new Date())).toEqual([]); // fresh install → nothing+ const res = await applySessionToReviewSchedule({ masteredSkills: [skill()], now: new Date('2026-07-01T00:00:00.000Z') });+ expect(res.added).toBe(1);+ expect(Object.keys(store.skills)).toEqual(['multiplication:L0']);+ // Not due yet (7d out) → still nothing surfaces.+ expect(await getDueReviews(new Date('2026-07-02T00:00:00.000Z'))).toEqual([]);+ });++ it('does not reset an existing entry\'s schedule on re-mastery, only refreshes metadata', async () => {+ await applySessionToReviewSchedule({ masteredSkills: [skill()], now: new Date('2026-07-01T00:00:00.000Z') });+ const firstNext = store.skills['multiplication:L0'].nextReviewAt;+ await applySessionToReviewSchedule({ masteredSkills: [skill({ label: 'Renamed' })], now: new Date('2026-07-05T00:00:00.000Z') });+ expect(store.skills['multiplication:L0'].nextReviewAt).toBe(firstNext); // schedule preserved+ expect(store.skills['multiplication:L0'].label).toBe('Renamed'); // metadata refreshed+ });++ it('records a review rep result and surfaces a failed skill as needs-refresh', async () => {+ await applySessionToReviewSchedule({ masteredSkills: [skill()], now: new Date('2026-07-01T00:00:00.000Z') });+ const res = await applySessionToReviewSchedule({ reviewResults: [{ skillId: 'multiplication:L0', passed: false }], now: new Date('2026-07-10T00:00:00.000Z') });+ expect(res.reviewed).toBe(1);+ expect(store.skills['multiplication:L0'].status).toBe('needs-refresh');+ const due = await getDueReviews(new Date('2026-07-10T00:00:00.000Z'));+ expect(due.map(d => d.skillId)).toEqual(['multiplication:L0']);+ });++ it('resets staleness for actively-practiced mastered skills', async () => {+ // Mastered long ago and now overdue.+ await applySessionToReviewSchedule({ masteredSkills: [skill()], now: new Date('2026-01-01T00:00:00.000Z') });+ expect((await getDueReviews(new Date('2026-07-01T00:00:00.000Z'))).length).toBe(1);+ await applySessionToReviewSchedule({ masteredSkills: [skill()], practicedSkillIds: ['multiplication:L0'], now: new Date('2026-07-01T00:00:00.000Z') });+ expect((await getDueReviews(new Date('2026-07-01T00:00:00.000Z'))).length).toBe(0); // no longer stale+ });+});++describe('getDueReviews — caps + ordering', () => {+ it('returns most-overdue first, capped at the limit', async () => {+ const base = new Date('2026-01-01T00:00:00.000Z');+ await applySessionToReviewSchedule({ masteredSkills: [+ skill({ skillId: 'a' }), skill({ skillId: 'b' }), skill({ skillId: 'c' }),+ ], now: base });+ // Force distinct overdue times.+ store.skills.a.nextReviewAt = '2026-03-01T00:00:00.000Z';+ store.skills.b.nextReviewAt = '2026-02-01T00:00:00.000Z';+ store.skills.c.nextReviewAt = '2026-04-01T00:00:00.000Z';+ const due = await getDueReviews(new Date('2026-07-01T00:00:00.000Z'), 2);+ expect(due.map(d => d.skillId)).toEqual(['b', 'a']); // oldest-due first, capped at 2+ });+});++describe('getRetentionReport', () => {+ it('reports per-skill state + an overall 90-day retention %', async () => {+ const now = new Date('2026-07-15T00:00:00.000Z');+ await applySessionToReviewSchedule({ masteredSkills: [skill()], now: new Date('2026-07-01T00:00:00.000Z') });+ store.skills['multiplication:L0'].reviewHistory = [+ { date: new Date(now.getTime() - 2 * DAY).toISOString(), passed: true },+ { date: new Date(now.getTime() - 3 * DAY).toISOString(), passed: false },+ ];+ const report = await getRetentionReport(now);+ expect(report.trackedCount).toBe(1);+ expect(report.retentionPct).toBe(50);+ // Mastered 2026-07-01 with a 7-day first interval → overdue by 2026-07-15.+ expect(report.skills[0]).toMatchObject({ skillId: 'multiplication:L0', state: 'due' });+ });++ it('is empty with null retention on a fresh install', async () => {+ const report = await getRetentionReport(new Date());+ expect(report).toMatchObject({ trackedCount: 0, dueCount: 0, retentionPct: null });+ });+});