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-1991]): add spaced-repetition scheduling to POST memory items

[._.]/ Adam Eivyd0951c326bcd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 76cad2b521..2e33badfc7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -23,6 +23,7 @@
- **[issue-1990] The POST launcher now shows your progress at a glance — streak, trend, and weakest-domain focus.** The Power On Self Test launcher (`PostSessionLauncher.jsx`) previously surfaced only "Today's Status" plus the last three raw scores, even though the server already computes rich analytics that never reached it. It now loads `GET /post/stats` (30-day and 7-day windows) alongside the config/session fetch and renders a compact analytics strip above the fold: a **current streak** card with the same 🔥/⚡/✨ glyphs as the dashboard Daily POST widget (plus your best streak), a **7-day average** card with a trend arrow showing how the last week compares to your 30-day baseline, and a **weakest-domain callout** ("Lowest domain this month: Verbal Agility — 62 avg") derived from per-drill averages mapped to their training domain. A one-click **Practice \<domain\>** button starts a focused session running every enabled drill in your weakest domain — and it always targets a domain you actually have drills enabled for, so it can't dead-end. Everything degrades gracefully with no history (the strip simply doesn't render), and all existing launcher behavior — Full POST, Quick 5 Min, the Test/Train toggle, and condition tags — is unchanged. Extracted the shared `domainLabel` / `computeDomainAverages` helpers into `constants.js` (now reused by History). (`client/src/components/meatspace/post/PostSessionLauncher.jsx`, `constants.js`, `PostTab.jsx`, Closes #1990)
- **[issue-1988] POST History is now a responsive analytics dashboard.** The History view (`client/src/components/meatspace/post/PostHistory.jsx`) was a single `max-w-3xl` column that stacked a lone overall-score line chart, a 3-up stat block, and the session table — surfacing only a fraction of what `getPostStats` already computes. It now fills desktop width and surfaces the full stats payload: a 4-up summary of **Sessions / Avg Score / Current Streak / Longest Streak**, a wide **Score Trend** line beside a horizontal **Avg by Domain** bar chart (each domain colored to match its `text-*-400` domain class), and a **Drill Breakdown** card that groups every drill's average into per-domain progress bars — so per-domain and per-drill averages plus streaks are visible without opening a single session. The five training domains (Mental Math / Memory / Wordplay / Verbal Agility / Imagination) are derived from each drill's *type* via `DRILL_TO_DOMAIN`, because the runners persist coarse module keys (`mental-math`, `llm-drills`) rather than domain keys — so all LLM drills split correctly across Wordplay/Verbal/Imagination instead of collapsing into one bucket. Mobile stays single-column; the 7/30/90/All range selector still drives every panel from one fetch. (Closes #1988)
- **[issue-1989] POST Memory surfaces are now responsive.** The Memory Builder, Practice, and Session Results screens were all pinned to a single narrow `max-w-2xl` column that wasted desktop width. **Memory Builder** (`MemoryBuilder.jsx`) now renders its saved items as a responsive card grid (`grid-cols-1 md:grid-cols-2 xl:grid-cols-3`) — each card lays out the item icon, title, line/chunk meta, and mastery badge above a full-width Practice button (with an aria-labeled delete for non-built-ins), while the create form and description stay in a readable `max-w-2xl` column above the grid. **Memory Practice** (`MemoryPractice.jsx`) widens the reading-oriented screens to `max-w-4xl` — the practice-mode picker (now a two-column card grid), Learn progressive-reveal, and Speed Run — while the active-recall focus steps (Sequence, Fill-in-the-Blank, Spaced Repetition) stay at a comfortable `max-w-2xl` for readability. **Session Results** (`PostSessionResults.jsx`) widens to `max-w-4xl` and lays the per-drill breakdown out in two columns on desktop. Layout-only: create/edit/delete, practice submission, mastery display, and score/breakdown rendering are unchanged; every surface collapses to a single column on mobile. (Closes #1989)
+- **[issue-1991] POST memory items now resurface on a spaced-repetition schedule.** Memory items (songs, poems, speeches, sequences) tracked mastery but had no review cadence — practice was entirely user-initiated, with nothing telling you *what to review today*. Each item now carries a lightweight SM-2-inspired schedule (ease, interval, next-review date): finishing a practice session reschedules the item automatically — a strong, mostly-correct session pushes the next review further out, while a miss-heavy session resets it to "due now" so it comes back around immediately. The Memory Builder gains a **Due Today (N)** banner listing what's ready for review with a one-click **Review Next**, plus a small "Due" badge on each item that's ready; the count updates the moment you finish practicing. Existing items keep working unchanged — a migration stamps every pre-existing item with a "due now" default so nothing gets stranded — and a new `GET /post/memory-items/due` endpoint lists due items most-overdue first.
- **[issue-1992] Opt-in adaptive difficulty for mental-math POST drills.** Math drill params (`steps` / `maxDigits` / `maxExponent` / estimation `tolerancePct`) were fixed values from config that never responded to how you were doing. A new **Adaptive difficulty** toggle in the Drill Configuration screen (default OFF, so existing installs are unchanged) makes each math drill nudge its primary difficulty knob from your recent scored performance: sustained high accuracy (≥90% over enough sessions) bumps it one step harder, repeated misses (≤50%) ease it back, all clamped to safe min/max bounds — and it won't move until it has enough scored samples to trust. The adjustment is a pure, unit-tested policy (`server/lib/postAdaptive.js`) applied server-side at drill-generation time, so manual config still wins whenever Adaptive is off. It's fully transparent: each math drill card shows the effective difficulty (e.g. "Adaptive: max digits 2 → 3 (harder · 94% recent)") via a new `GET /post/adaptive-preview` endpoint, so it's never a black box. (`server/lib/postAdaptive.js`, `server/services/meatspacePost.js`, `client/src/components/meatspace/post/PostDrillConfig.jsx`, Closes #1992)
## Media Generation
diff --git a/client/src/components/meatspace/post/MemoryBuilder.jsx b/client/src/components/meatspace/post/MemoryBuilder.jsx
index 4e8af95f63..4b46c5e44f 100644
--- a/client/src/components/meatspace/post/MemoryBuilder.jsx
+++ b/client/src/components/meatspace/post/MemoryBuilder.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
-import { Brain, ChevronLeft, Plus, Trash2, BookOpen, Zap, FlaskConical, Eye, X, Save } from 'lucide-react';
+import { Brain, ChevronLeft, Plus, Trash2, BookOpen, Zap, FlaskConical, Eye, X, Save, CalendarClock } from 'lucide-react';
import { getMemoryItems, createMemoryItem, deleteMemoryItem } from '../../../services/api';
import ConfirmButtonPair from '../../ui/ConfirmButtonPair';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
@@ -14,6 +14,16 @@ const ITEM_TYPES = [
{ id: 'text', label: 'Text' },
];
+// An item is due when its spaced-repetition schedule says so. No/invalid
+// schedule = due (matches the server's `isMemoryItemDue`), so legacy items and
+// anything the migration hasn't stamped still surface for review.
+function isItemDue(item) {
+ const nr = item?.schedule?.nextReview;
+ if (typeof nr !== 'string') return true;
+ const t = Date.parse(nr);
+ return Number.isNaN(t) || t <= Date.now();
+}
+
export default function MemoryBuilder({ onBack, onNavigateElements }) {
const [items, setItems] = useState([]);
const [selectedItem, setSelectedItem] = useState(null);
@@ -138,6 +148,39 @@ export default function MemoryBuilder({ onBack, onNavigateElements }) {
Train your memory with songs, poems, speeches, and sequences. Track mastery and practice weak spots.
</p>
+ {/* Due Today — spaced repetition. Recomputes reactively as `items` update. */}
+ {(() => {
+ const dueItems = items.filter(isItemDue);
+ if (dueItems.length === 0) {
+ return (
+ <div className="flex items-center gap-2 text-sm text-gray-500 max-w-2xl">
+ <CalendarClock size={16} className="text-gray-600" />
+ Nothing due for review right now — all caught up.
+ </div>
+ );
+ }
+ return (
+ <div className="bg-port-card border border-emerald-500/30 rounded-lg p-4 max-w-2xl flex items-center justify-between gap-3">
+ <div className="flex items-center gap-3 min-w-0">
+ <CalendarClock size={20} className="text-emerald-400 shrink-0" />
+ <div className="min-w-0">
+ <div className="text-white font-medium">Due Today ({dueItems.length})</div>
+ <div className="text-xs text-gray-500 truncate">
+ {dueItems.map(i => i.title).join(', ')}
+ </div>
+ </div>
+ </div>
+ <button
+ onClick={() => handleSelect(dueItems[0])}
+ className="shrink-0 flex items-center gap-1.5 px-3 py-1.5 text-sm bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg transition-colors"
+ >
+ <BookOpen size={14} />
+ Review Next
+ </button>
+ </div>
+ );
+ })()}
+
{/* Create Form */}
{creating && (
<div className="bg-port-card border border-port-accent/30 rounded-lg p-5 space-y-4 max-w-2xl">
@@ -234,7 +277,15 @@ export default function MemoryBuilder({ onBack, onNavigateElements }) {
</div>
</div>
</div>
- <MasteryBadge pct={item.mastery?.overallPct || 0} />
+ <div className="flex flex-col items-end gap-1 shrink-0">
+ <MasteryBadge pct={item.mastery?.overallPct || 0} />
+ {isItemDue(item) && (
+ <span className="flex items-center gap-1 text-[10px] uppercase tracking-wide text-emerald-400">
+ <CalendarClock size={10} />
+ Due
+ </span>
+ )}
+ </div>
</div>
<div className="flex items-center gap-2 mt-4">
diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.js
index 2373ba9813..44f38a6a4a 100644
--- a/client/src/services/apiMeatspace.js
+++ b/client/src/services/apiMeatspace.js
@@ -202,6 +202,7 @@ export const fillPostDrillCache = (types, providerId, model) => request('/meatsp
// MeatSpace - POST Memory Builder
export const getMemoryItems = () => request('/meatspace/post/memory-items');
+export const getDueMemoryItems = () => request('/meatspace/post/memory-items/due');
export const getMemoryItem = (id) => request(`/meatspace/post/memory-items/${id}`);
export const createMemoryItem = (data) => request('/meatspace/post/memory-items', {
method: 'POST',
diff --git a/scripts/migrations/154-post-memory-spaced-repetition.js b/scripts/migrations/154-post-memory-spaced-repetition.js
new file mode 100644
index 0000000000..46a0af0018
--- /dev/null
+++ b/scripts/migrations/154-post-memory-spaced-repetition.js
@@ -0,0 +1,79 @@
+/**
+ * Backfill a spaced-repetition schedule on POST memory items that predate the
+ * feature (issue #1991).
+ *
+ * Background:
+ * Memory items in `data/meatspace/post-memory-items.json` gained a review
+ * schedule — `{ ease, intervalDays, nextReview, lastReviewed }` — so items
+ * resurface on a due-today cadence (see `meatspacePostMemory.js`). New items
+ * get one at creation and the service backfills a default on read, but a
+ * persisted default keeps the on-disk record honest (and lets cross-machine
+ * sync carry the schedule). This migration stamps a default schedule — due
+ * NOW (intervalDays 0) — on every item that lacks one.
+ *
+ * The built-in Elements Song is re-seeded on read, so a missing file is a
+ * clean no-op (the service adds a schedule when the file is first written).
+ * Re-runs detect the schedule is present and skip. A user (or the service)
+ * who already advanced an item's schedule is never clobbered.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+// Mirror `meatspacePostMemory.DEFAULT_EASE` — the migration test asserts parity
+// so a drift fails CI rather than shipping two different defaults.
+export const MIGRATION_DEFAULT_EASE = 2.5;
+
+const REL_PATH = 'data/meatspace/post-memory-items.json';
+
+const hasSchedule = (item) =>
+ item && typeof item.schedule === 'object' && item.schedule !== null
+ && typeof item.schedule.nextReview === 'string';
+
+export default {
+ async up({ rootDir }) {
+ const itemsPath = join(rootDir, REL_PATH);
+ const raw = await readFile(itemsPath, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) {
+ console.log(`📄 ${REL_PATH} not present — skipping (fresh installs seed the schedule on first write)`);
+ return { updated: 0, reason: 'no-file' };
+ }
+
+ let data;
+ try {
+ data = JSON.parse(raw);
+ } catch (err) {
+ console.log(`⚠️ ${REL_PATH}: invalid JSON, skipping (${err.message})`);
+ return { updated: 0, reason: 'invalid-json' };
+ }
+
+ const items = Array.isArray(data?.items) ? data.items : null;
+ if (!items) {
+ console.log(`⚠️ ${REL_PATH}: no items array — skipping`);
+ return { updated: 0, reason: 'no-items' };
+ }
+
+ const now = new Date().toISOString();
+ let updated = 0;
+ for (const item of items) {
+ if (hasSchedule(item)) continue;
+ // Anchor "due now" to the item's own timestamp when available (stable and
+ // in the past → due), else the migration run time.
+ const anchor = item?.updatedAt || item?.createdAt || now;
+ item.schedule = { ease: MIGRATION_DEFAULT_EASE, intervalDays: 0, nextReview: anchor, lastReviewed: null };
+ updated++;
+ }
+
+ if (updated === 0) {
+ console.log(`✅ ${REL_PATH}: all ${items.length} memory item(s) already scheduled — no changes`);
+ return { updated: 0, reason: 'already-scheduled' };
+ }
+
+ await writeFile(itemsPath, `${JSON.stringify(data, null, 2)}\n`);
+ console.log(`📝 ${REL_PATH}: backfilled review schedule on ${updated}/${items.length} memory item(s)`);
+ return { updated };
+ },
+};
diff --git a/scripts/migrations/154-post-memory-spaced-repetition.test.js b/scripts/migrations/154-post-memory-spaced-repetition.test.js
new file mode 100644
index 0000000000..3fb1332841
--- /dev/null
+++ b/scripts/migrations/154-post-memory-spaced-repetition.test.js
@@ -0,0 +1,80 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration, { MIGRATION_DEFAULT_EASE } from './154-post-memory-spaced-repetition.js';
+import { DEFAULT_EASE } from '../../server/services/meatspacePostMemory.js';
+
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 154 — backfill POST memory spaced-repetition schedule', () => {
+ let rootDir;
+ let itemsPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-154-'));
+ mkdirSync(join(rootDir, 'data', 'meatspace'), { recursive: true });
+ itemsPath = join(rootDir, 'data', 'meatspace', 'post-memory-items.json');
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('does not drift from the service default ease', () => {
+ expect(MIGRATION_DEFAULT_EASE).toBe(DEFAULT_EASE);
+ });
+
+ it('no-ops when the memory items file is missing', async () => {
+ const result = await migration.up({ rootDir });
+ expect(result).toEqual({ updated: 0, reason: 'no-file' });
+ expect(existsSync(itemsPath)).toBe(false);
+ });
+
+ it('stamps a default schedule on items that lack one', async () => {
+ writeJson(itemsPath, {
+ items: [
+ { id: 'a', title: 'A', updatedAt: '2026-01-01T00:00:00.000Z' },
+ { id: 'b', title: 'B' },
+ ],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.updated).toBe(2);
+
+ const { items } = readJson(itemsPath);
+ expect(items[0].schedule).toEqual({
+ ease: MIGRATION_DEFAULT_EASE,
+ intervalDays: 0,
+ nextReview: '2026-01-01T00:00:00.000Z', // anchored to updatedAt
+ lastReviewed: null,
+ });
+ // Second item has no timestamps → anchored to run time (a valid ISO string).
+ expect(items[1].schedule.intervalDays).toBe(0);
+ expect(Number.isNaN(Date.parse(items[1].schedule.nextReview))).toBe(false);
+ });
+
+ it('leaves an already-scheduled item untouched', async () => {
+ const existing = { ease: 2.6, intervalDays: 6, nextReview: '2030-01-01T00:00:00.000Z', lastReviewed: '2026-05-01T00:00:00.000Z' };
+ writeJson(itemsPath, { items: [{ id: 'a', title: 'A', schedule: existing }] });
+ const result = await migration.up({ rootDir });
+ expect(result).toEqual({ updated: 0, reason: 'already-scheduled' });
+ expect(readJson(itemsPath).items[0].schedule).toEqual(existing);
+ });
+
+ it('is idempotent across re-runs', async () => {
+ writeJson(itemsPath, { items: [{ id: 'a', title: 'A' }] });
+ await migration.up({ rootDir });
+ const afterFirst = readJson(itemsPath);
+ const second = await migration.up({ rootDir });
+ expect(second).toEqual({ updated: 0, reason: 'already-scheduled' });
+ expect(readJson(itemsPath)).toEqual(afterFirst);
+ });
+
+ it('skips a malformed items file without throwing', async () => {
+ writeFileSync(itemsPath, '{ not json');
+ const result = await migration.up({ rootDir });
+ expect(result).toEqual({ updated: 0, reason: 'invalid-json' });
+ });
+});
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index c76d73c5fb..edabcebe10 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -159,11 +159,22 @@ const memoryChunkSchema = z.object({
label: z.string(),
});
+// Spaced-repetition schedule (SM-2 inspired). Server-managed via practice, but
+// accepted on both POST (seed an imported item's progress) and PUT (persist an
+// out-of-band reschedule). When absent the service stamps a fresh default.
+export const memoryScheduleSchema = z.object({
+ ease: z.number().min(1.3).max(5),
+ intervalDays: z.number().min(0),
+ nextReview: z.string(),
+ lastReviewed: z.string().nullable().optional(),
+});
+
export const memoryItemCreateSchema = z.object({
title: z.string().min(1).max(200),
type: z.enum(['song', 'poem', 'speech', 'sequence', 'text']).optional().default('text'),
lines: z.array(z.union([z.string(), memoryLineSchema])).min(1),
chunks: z.array(memoryChunkSchema).optional(),
+ schedule: memoryScheduleSchema.optional(),
});
export const memoryItemUpdateSchema = z.object({
@@ -171,6 +182,7 @@ export const memoryItemUpdateSchema = z.object({
type: z.enum(['song', 'poem', 'speech', 'sequence', 'text']).optional(),
lines: z.array(z.union([z.string(), memoryLineSchema])).optional(),
chunks: z.array(memoryChunkSchema).optional(),
+ schedule: memoryScheduleSchema.optional(),
mastery: z.object({
overallPct: z.number().min(0).max(100).optional(),
chunks: z.record(z.object({
diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.js
index 23ebe5645a..9326343ed1 100644
--- a/server/routes/meatspacePostRoutes.js
+++ b/server/routes/meatspacePostRoutes.js
@@ -237,6 +237,16 @@ router.get('/post/memory-items', asyncHandler(async (req, res) => {
res.json(items);
}));
+/**
+ * GET /api/meatspace/post/memory-items/due
+ * List memory items currently due for spaced-repetition review (nextReview <= now),
+ * most-overdue first. Declared before /:id so "due" isn't captured as an id.
+ */
+router.get('/post/memory-items/due', asyncHandler(async (req, res) => {
+ const items = await memoryService.getDueMemoryItems();
+ res.json(items);
+}));
+
/**
* GET /api/meatspace/post/memory-items/:id
* Get a single memory item
diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.js
index d8e79bac9f..46ca1e4f0c 100644
--- a/server/services/meatspacePostMemory.js
+++ b/server/services/meatspacePostMemory.js
@@ -13,6 +13,80 @@ const MEATSPACE_DIR = PATHS.meatspace;
const MEMORY_ITEMS_FILE = join(MEATSPACE_DIR, 'post-memory-items.json');
const TRAINING_LOG_FILE = join(MEATSPACE_DIR, 'post-training-log.json');
+// =============================================================================
+// SPACED-REPETITION SCHEDULER (SM-2 inspired)
+// =============================================================================
+//
+// Every memory item carries a lightweight review schedule:
+// { ease, intervalDays, nextReview, lastReviewed }
+// An item is "due" when `nextReview <= now`. Practicing it advances the schedule
+// (a correct-heavy session pushes the next review further out; a miss resets it
+// to "due now" so the item resurfaces immediately). The 4-field shape is
+// additive and migration-safe — legacy items with no schedule are treated as
+// due now (see `ensureSchedule`) and get a persisted default by migration 154.
+
+export const DEFAULT_EASE = 2.5;
+const MIN_EASE = 1.3;
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/** Fresh schedule — due at `nowIso` (i.e. immediately). */
+export function defaultSchedule(nowIso = new Date().toISOString()) {
+ return { ease: DEFAULT_EASE, intervalDays: 0, nextReview: nowIso, lastReviewed: null };
+}
+
+/**
+ * Guarantee an item has a valid schedule. Legacy/built-in items with none get a
+ * default anchored to their own `updatedAt`/`createdAt` (stable + in the past →
+ * due now), so "due" state doesn't flap between reads. Mutates in place.
+ */
+function ensureSchedule(item) {
+ const s = item?.schedule;
+ const valid = s && typeof s === 'object' && typeof s.nextReview === 'string';
+ if (!valid) {
+ item.schedule = defaultSchedule(item?.updatedAt || item?.createdAt || new Date().toISOString());
+ }
+ return item;
+}
+
+/**
+ * Advance a schedule from a practice session's correctness ratio (0..1).
+ * Pure — returns a new schedule object, never mutates the input.
+ * - ratio maps to an SM-2 quality (0..5); ease adjusts per the SM-2 formula.
+ * - quality < 3 (a miss-heavy session) → intervalDays 0 → due now again.
+ * - otherwise the interval steps 0→1→6→round(interval*ease).
+ */
+export function advanceSchedule(schedule, ratio, now = new Date()) {
+ const prev = schedule && typeof schedule === 'object' ? schedule : {};
+ const clamped = Math.max(0, Math.min(1, Number.isFinite(ratio) ? ratio : 0));
+ const quality = Math.round(clamped * 5); // 0..5
+ const nowIso = now.toISOString();
+
+ const prevEase = typeof prev.ease === 'number' ? prev.ease : DEFAULT_EASE;
+ let ease = prevEase + (0.1 - (5 - quality) * (0.08 + (5 - quality) * 0.02));
+ ease = Math.max(MIN_EASE, Math.round(ease * 100) / 100);
+
+ let intervalDays;
+ if (quality < 3) {
+ intervalDays = 0; // relearn — resurface immediately
+ } else {
+ const prevInterval = typeof prev.intervalDays === 'number' ? prev.intervalDays : 0;
+ if (prevInterval <= 0) intervalDays = 1;
+ else if (prevInterval < 6) intervalDays = 6;
+ else intervalDays = Math.max(1, Math.round(prevInterval * ease));
+ }
+
+ const nextReview = new Date(now.getTime() + intervalDays * DAY_MS).toISOString();
+ return { ease, intervalDays, nextReview, lastReviewed: nowIso };
+}
+
+/** True when an item is due for review (no schedule / invalid date = due). */
+export function isMemoryItemDue(item, now = new Date()) {
+ const nr = item?.schedule?.nextReview;
+ if (typeof nr !== 'string') return true;
+ const t = Date.parse(nr);
+ return Number.isNaN(t) || t <= now.getTime();
+}
+
// =============================================================================
// TOM LEHRER'S ELEMENTS SONG — BUILT-IN CONTENT
// =============================================================================
@@ -151,10 +225,16 @@ async function loadMemoryItems() {
const existing = items[existingIdx];
const fresh = structuredClone(ELEMENTS_SONG);
fresh.mastery = existing.mastery || fresh.mastery;
+ // Preserve the learned review schedule across content re-seeds (like mastery).
+ if (existing.schedule) fresh.schedule = existing.schedule;
fresh.updatedAt = existing.updatedAt;
items[existingIdx] = fresh;
}
+ // Backfill a schedule on any item that predates spaced-repetition (built-in
+ // or legacy custom items) so every item is schedulable + surfaces as due.
+ for (const item of items) ensureSchedule(item);
+
return items;
}
@@ -213,6 +293,9 @@ export async function createMemoryItem(data) {
chunks: remappedChunks,
},
mastery: { overallPct: 0, chunks: {}, elements: {} },
+ // Honor a client-provided schedule (e.g. importing an item with progress),
+ // else stamp a fresh "due now" default.
+ schedule: data.schedule || defaultSchedule(now),
createdAt: now,
updatedAt: now,
};
@@ -228,9 +311,10 @@ export async function updateMemoryItem(id, updates) {
const idx = items.findIndex(i => i.id === id);
if (idx === -1) return null;
if (items[idx].builtin) {
- // Only allow mastery updates on built-in items
- if (updates.mastery) {
- items[idx].mastery = updates.mastery;
+ // Only allow mastery / schedule updates on built-in items
+ if (updates.mastery || updates.schedule) {
+ if (updates.mastery) items[idx].mastery = updates.mastery;
+ if (updates.schedule) items[idx].schedule = updates.schedule;
items[idx].updatedAt = new Date().toISOString();
await saveMemoryItems(items);
return items[idx];
@@ -241,6 +325,7 @@ export async function updateMemoryItem(id, updates) {
const item = items[idx];
if (updates.title) item.title = updates.title;
if (updates.type) item.type = updates.type;
+ if (updates.schedule) item.schedule = updates.schedule;
if (updates.lines) {
item.content.lines = updates.lines.map(l => ({
text: l.text || l,
@@ -305,6 +390,12 @@ export async function submitPractice(id, practiceData) {
// Recompute overall mastery percentage
item.mastery.overallPct = computeOverallMastery(item);
+
+ // Advance the spaced-repetition schedule from this session's accuracy.
+ const correctCount = results.filter(r => r.correct).length;
+ const ratio = results.length ? correctCount / results.length : 0;
+ item.schedule = advanceSchedule(item.schedule, ratio, new Date(now));
+
item.updatedAt = now;
await saveMemoryItems(items);
@@ -322,8 +413,19 @@ export async function submitPractice(id, practiceData) {
});
await saveTrainingLog(log);
- console.log(`🧠 Practice logged: "${item.title}" mode=${mode} ${results.filter(r => r.correct).length}/${results.length}`);
- return { mastery: item.mastery, practiceId: log.entries[log.entries.length - 1].id };
+ console.log(`🧠 Practice logged: "${item.title}" mode=${mode} ${correctCount}/${results.length} → next review in ${item.schedule.intervalDays}d`);
+ return { mastery: item.mastery, schedule: item.schedule, practiceId: log.entries[log.entries.length - 1].id };
+}
+
+/**
+ * List memory items currently due for review (`nextReview <= now`), sorted by
+ * how overdue they are (most overdue first).
+ */
+export async function getDueMemoryItems(now = new Date()) {
+ const items = await loadMemoryItems();
+ return items
+ .filter(i => isMemoryItemDue(i, now))
+ .sort((a, b) => Date.parse(a.schedule?.nextReview || 0) - Date.parse(b.schedule?.nextReview || 0));
}
export async function getMastery(id) {
diff --git a/server/services/meatspacePostMemory.test.js b/server/services/meatspacePostMemory.test.js
index a5c8ca651a..37bb468fc9 100644
--- a/server/services/meatspacePostMemory.test.js
+++ b/server/services/meatspacePostMemory.test.js
@@ -19,6 +19,11 @@ import {
submitPractice,
getMastery,
generateMemoryDrill,
+ getDueMemoryItems,
+ advanceSchedule,
+ isMemoryItemDue,
+ defaultSchedule,
+ DEFAULT_EASE,
ELEMENTS_SONG,
} from './meatspacePostMemory.js';
@@ -266,3 +271,118 @@ describe('submitPractice', () => {
expect(result.mastery.chunks['verse-1'].lastPracticed).toBeTruthy();
});
});
+
+// =============================================================================
+// SPACED-REPETITION SCHEDULER
+// =============================================================================
+
+describe('advanceSchedule', () => {
+ const now = new Date('2026-07-01T00:00:00.000Z');
+
+ it('a fully-correct session steps a fresh item to a 1-day interval', () => {
+ const next = advanceSchedule(defaultSchedule(now.toISOString()), 1, now);
+ expect(next.intervalDays).toBe(1);
+ expect(next.ease).toBeGreaterThanOrEqual(DEFAULT_EASE);
+ expect(next.lastReviewed).toBe(now.toISOString());
+ expect(Date.parse(next.nextReview)).toBe(now.getTime() + 24 * 60 * 60 * 1000);
+ });
+
+ it('steps 1-day → 6-day → interval*ease on repeated success', () => {
+ const one = advanceSchedule({ ease: DEFAULT_EASE, intervalDays: 1, nextReview: now.toISOString() }, 1, now);
+ expect(one.intervalDays).toBe(6);
+ const two = advanceSchedule({ ease: 2.5, intervalDays: 6, nextReview: now.toISOString() }, 1, now);
+ expect(two.intervalDays).toBe(Math.round(6 * two.ease));
+ expect(two.intervalDays).toBeGreaterThan(6);
+ });
+
+ it('a miss-heavy session resets the interval to 0 (due now) and lowers ease', () => {
+ const next = advanceSchedule({ ease: 2.5, intervalDays: 20, nextReview: now.toISOString() }, 0, now);
+ expect(next.intervalDays).toBe(0);
+ expect(next.ease).toBeLessThan(2.5);
+ expect(Date.parse(next.nextReview)).toBe(now.getTime()); // due now
+ });
+
+ it('never drops ease below the SM-2 floor of 1.3', () => {
+ let schedule = { ease: 1.3, intervalDays: 0, nextReview: now.toISOString() };
+ for (let i = 0; i < 10; i++) schedule = advanceSchedule(schedule, 0, now);
+ expect(schedule.ease).toBe(1.3);
+ });
+
+ it('tolerates a missing/garbage prior schedule', () => {
+ const next = advanceSchedule(undefined, 1, now);
+ expect(next.intervalDays).toBe(1);
+ expect(next.ease).toBeGreaterThan(0);
+ });
+});
+
+describe('isMemoryItemDue', () => {
+ const now = new Date('2026-07-01T00:00:00.000Z');
+
+ it('treats a missing schedule as due', () => {
+ expect(isMemoryItemDue({}, now)).toBe(true);
+ expect(isMemoryItemDue({ schedule: {} }, now)).toBe(true);
+ });
+
+ it('is due when nextReview is in the past', () => {
+ expect(isMemoryItemDue({ schedule: { nextReview: '2026-06-01T00:00:00.000Z' } }, now)).toBe(true);
+ });
+
+ it('is not due when nextReview is in the future', () => {
+ expect(isMemoryItemDue({ schedule: { nextReview: '2026-08-01T00:00:00.000Z' } }, now)).toBe(false);
+ });
+});
+
+describe('getDueMemoryItems', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns only items whose schedule is due, most-overdue first', async () => {
+ readJSONFile.mockResolvedValue({
+ items: [
+ { id: 'future', title: 'F', schedule: { nextReview: '2999-01-01T00:00:00.000Z' } },
+ { id: 'due-recent', title: 'R', schedule: { nextReview: '2026-06-30T00:00:00.000Z' } },
+ { id: 'due-old', title: 'O', schedule: { nextReview: '2020-01-01T00:00:00.000Z' } },
+ ],
+ });
+ const now = new Date('2026-07-01T00:00:00.000Z');
+ const due = await getDueMemoryItems(now);
+ const ids = due.map(i => i.id);
+ // elements-song is re-seeded on load and has no persisted schedule → due now.
+ expect(ids).toContain('due-old');
+ expect(ids).toContain('due-recent');
+ expect(ids).not.toContain('future');
+ // Most overdue (oldest nextReview) sorts before the recent one.
+ expect(ids.indexOf('due-old')).toBeLessThan(ids.indexOf('due-recent'));
+ });
+});
+
+describe('submitPractice — schedule advancement', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ readJSONFile
+ .mockResolvedValueOnce({ items: [{ ...structuredClone(ELEMENTS_SONG) }] })
+ .mockResolvedValueOnce({ entries: [] }); // training log
+ });
+
+ it('advances and returns the schedule after a correct session', async () => {
+ const result = await submitPractice('elements-song', {
+ mode: 'fill-blank',
+ results: [{ correct: true }, { correct: true }, { correct: true }],
+ totalMs: 5000,
+ });
+ expect(result.schedule).toBeTruthy();
+ expect(result.schedule.intervalDays).toBeGreaterThanOrEqual(1);
+ expect(result.schedule.lastReviewed).toBeTruthy();
+ expect(Date.parse(result.schedule.nextReview)).toBeGreaterThan(Date.now());
+ });
+
+ it('keeps a miss-heavy session due now (interval 0)', async () => {
+ const result = await submitPractice('elements-song', {
+ mode: 'fill-blank',
+ results: [{ correct: false }, { correct: false }, { correct: true }],
+ totalMs: 5000,
+ });
+ expect(result.schedule.intervalDays).toBe(0);
+ });
+});