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: schedule SongBook repertoire practice with SM-2 spaced repetition (#4102)
[._.]/ Adam Eivyfb06e089a7b6
diff --git a/.changelog/next/added-issue-4102.md b/.changelog/next/added-issue-4102.mdnew file mode 100644index 0000000000..fa1c7e67a7--- /dev/null+++ b/.changelog/next/added-issue-4102.md@@ -0,0 +1 @@+- SongBook repertoire practice is now scheduled: log a run graded 0-5 and PortOS advances the song's learning stage and books the next review with SM-2 spaced repetition. The index gains a Due filter (?due=1) so you can open exactly what needs practice today.diff --git a/client/src/components/songbook/PracticeLogger.jsx b/client/src/components/songbook/PracticeLogger.jsxnew file mode 100644index 0000000000..a0e2cd5837--- /dev/null+++ b/client/src/components/songbook/PracticeLogger.jsx@@ -0,0 +1,78 @@+/**+ * Log a practice run for a repertoire song (#4102).+ *+ * The user grades the run 0..5 and the SERVER decides what that means — it owns+ * the SM-2 advance and the resulting `stage`/`practice`, because the advance is+ * computed from the stored schedule. So this component sends one number and+ * hands the whole updated record back to its parent, which merges it into local+ * state (no refetch).+ *+ * Each grade button spells out what it will do, so "Solid" advancing the stage+ * is never a surprise — the stage select stays available for a manual override.+ */++import { CheckCircle2, GraduationCap } from 'lucide-react';+import { useAsyncAction } from '../../hooks/useAsyncAction';+import { timeAgo, timeUntil } from '../../utils/formatters';+import { practiceSong } from '../../services/api';+import toast from '../ui/Toast';+import {+ SONG_PRACTICE_RATINGS, isSongDue, songNextReviewAt, songPracticeSessions,+} from './constants';++export default function PracticeLogger({ song, onLogged, className = '' }) {+ // `useAsyncAction` owns the error toast, so the request itself stays silent —+ // one error layer only (client/src/CLAUDE.md).+ const [logPractice, logging] = useAsyncAction(async (quality) => {+ const updated = await practiceSong(song.id, quality, { silent: true });+ onLogged?.(updated);+ const when = timeUntil(updated?.practice?.nextReview, 'today');+ toast.success(`Practice logged — ${updated?.stage}, next review ${when}`);+ return updated;+ }, { errorMessage: 'Failed to log practice' });++ const due = isSongDue(song);+ const sessions = songPracticeSessions(song);+ const lastPracticed = song?.practice?.lastReviewed;++ return (+ <div className={`bg-port-card border border-port-border rounded-lg p-3 ${className}`}>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mb-2">+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white">+ <GraduationCap size={15} className="text-gray-500" aria-hidden="true" />+ Practice+ </h2>+ {due ? (+ <span className="px-2 py-0.5 rounded-full text-[11px] bg-port-warning/20 text-port-warning border border-port-warning/30">+ Due now+ </span>+ ) : (+ <span className="flex items-center gap-1 text-xs text-gray-500">+ <CheckCircle2 size={12} aria-hidden="true" />+ Next review {timeUntil(songNextReviewAt(song), 'today')}+ </span>+ )}+ <span className="text-xs text-gray-500">+ {sessions === 0+ ? 'Never practiced'+ : `${sessions} session${sessions === 1 ? '' : 's'} · last ${timeAgo(lastPracticed)}`}+ </span>+ </div>++ <div className="flex flex-wrap gap-2" role="group" aria-label="Log a practice run">+ {SONG_PRACTICE_RATINGS.map((rating) => (+ <button+ key={rating.quality}+ type="button"+ onClick={() => logPractice(rating.quality)}+ disabled={logging}+ title={rating.hint}+ className="flex-1 min-w-[84px] min-h-[44px] px-3 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white hover:border-port-accent/50 hover:bg-port-border/50 disabled:opacity-50"+ >+ {rating.label}+ </button>+ ))}+ </div>+ </div>+ );+}diff --git a/client/src/components/songbook/PracticeLogger.test.jsx b/client/src/components/songbook/PracticeLogger.test.jsxnew file mode 100644index 0000000000..02fe38b0fe--- /dev/null+++ b/client/src/components/songbook/PracticeLogger.test.jsx@@ -0,0 +1,84 @@+import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';+import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';++vi.mock('../../services/api', () => ({ practiceSong: vi.fn() }));+vi.mock('../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn() },+}));++import PracticeLogger from './PracticeLogger.jsx';+import { practiceSong } from '../../services/api';+import toast from '../ui/Toast';++const song = (overrides = {}) => ({+ id: 'song-1',+ title: 'Example Song',+ stage: 'learning',+ updatedAt: '2026-02-01T00:00:00.000Z',+ createdAt: '2026-01-01T00:00:00.000Z',+ ...overrides,+});++const future = () => new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toISOString();++afterEach(cleanup);+beforeEach(() => vi.clearAllMocks());++describe('PracticeLogger', () => {+ it('marks a song with no schedule as due and never practiced', () => {+ render(<PracticeLogger song={song()} />);+ expect(screen.getByText('Due now')).toBeTruthy();+ expect(screen.getByText('Never practiced')).toBeTruthy();+ });++ it('shows the next review and the session count once practiced', () => {+ render(<PracticeLogger song={song({+ practice: { nextReview: future(), lastReviewed: '2026-02-20T00:00:00.000Z', sessions: 3 },+ })} />);+ expect(screen.queryByText('Due now')).toBeNull();+ expect(screen.getByText(/Next review in/)).toBeTruthy();+ expect(screen.getByText(/3 sessions/)).toBeTruthy();+ });++ it('singularizes a single session', () => {+ render(<PracticeLogger song={song({+ practice: { nextReview: future(), lastReviewed: '2026-02-20T00:00:00.000Z', sessions: 1 },+ })} />);+ expect(screen.getByText(/1 session ·/)).toBeTruthy();+ });++ it('posts the grade and hands the updated record back — no client-side scheduling', async () => {+ const updated = { ...song(), stage: 'learned', practice: { nextReview: future(), sessions: 1 } };+ practiceSong.mockResolvedValue(updated);+ const onLogged = vi.fn();+ render(<PracticeLogger song={song()} onLogged={onLogged} />);++ fireEvent.click(screen.getByRole('button', { name: 'Solid' }));++ await waitFor(() => expect(onLogged).toHaveBeenCalledWith(updated));+ // The grade is the ONLY thing sent; the server owns stage + schedule.+ expect(practiceSong).toHaveBeenCalledWith('song-1', 4, { silent: true });+ expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('learned'));+ });++ it('sends the low grade for a failed run', async () => {+ practiceSong.mockResolvedValue({ ...song(), stage: 'learning', practice: { nextReview: new Date().toISOString() } });+ render(<PracticeLogger song={song()} />);+ fireEvent.click(screen.getByRole('button', { name: 'Struggled' }));+ await waitFor(() => expect(practiceSong).toHaveBeenCalledWith('song-1', 0, { silent: true }));+ });++ it('surfaces a failure once and leaves local state alone', async () => {+ practiceSong.mockRejectedValue(new Error('nope'));+ const onLogged = vi.fn();+ render(<PracticeLogger song={song()} onLogged={onLogged} />);++ fireEvent.click(screen.getByRole('button', { name: 'Clean' }));++ await waitFor(() => expect(toast.error).toHaveBeenCalled());+ expect(onLogged).not.toHaveBeenCalled();+ // The request is silent so useAsyncAction's toast is the ONLY error layer.+ expect(practiceSong).toHaveBeenCalledWith('song-1', 5, { silent: true });+ expect(toast.success).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/songbook/constants.js b/client/src/components/songbook/constants.jsindex 18c399cabc..0769d8a974 100644--- a/client/src/components/songbook/constants.js+++ b/client/src/components/songbook/constants.js@@ -1,5 +1,6 @@// Shared SongBook constants — learning-stage progression, stage chip colors,-// and the instrument list (mirrors server/lib/brainValidation.js enums).+// the practice-grade vocabulary, and the instrument list (mirrors the enums in+// server/lib/brainValidation.js and the ladder in server/lib/songPractice.js).export const SONG_STAGES = [{ id: 'new', label: 'New' },@@ -16,6 +17,49 @@ export const SONG_STAGE_COLORS = {memorized: 'bg-port-success/20 text-port-success border-port-success/30',};+// =============================================================================+// PRACTICE (spaced repetition, #4102)+// =============================================================================++// The grades offered for a practice run, in the order the buttons render.+// `quality` is the SM-2 self-grade the server schedules on (0..5); the four+// rungs are the Anki-style shorthand for the ones that mean something here —+// the intermediate grades (1, 2) all regress, and 5 vs 4 differ only in how far+// the interval steps. Mirrors SONG_PROMOTE_MIN_QUALITY (4) and+// SONG_REGRESS_MAX_QUALITY (2) in server/lib/songPractice.js; parity is+// asserted in constants.test.js.+export const SONG_PRACTICE_RATINGS = [+ { quality: 0, label: 'Struggled', hint: 'Fell apart — regress a stage and practice again today' },+ { quality: 3, label: 'Rough', hint: 'Got through it — hold the stage, review sooner' },+ { quality: 4, label: 'Solid', hint: 'Played it with hesitation — advance a stage' },+ { quality: 5, label: 'Clean', hint: 'Played it clean — advance a stage, review later' },+];++// Read the song's practice schedule the same way the server does: absent (a+// song predating the feature, or one never practiced) derives an anchor from+// the record itself rather than collapsing into "due at this instant", so the+// answer doesn't flap between renders. Mirrors `songPracticeOrDefault` in+// server/lib/songPractice.js.+export const songNextReviewAt = (song) => {+ const nextReview = song?.practice?.nextReview;+ if (typeof nextReview === 'string') return nextReview;+ return song?.updatedAt || song?.createdAt || null;+};++// Is this song due for practice? A never-practiced song IS due — and so is one+// whose stored date we can't read, because a song we can't schedule is one to+// surface, never one to hide forever.+export const isSongDue = (song, now = Date.now()) => {+ const at = Date.parse(songNextReviewAt(song) ?? '');+ return !Number.isFinite(at) || at <= now;+};++// Has this song ever been practiced? `null` (absent schedule) must not read the+// same as a real session count of 0 — the empty-vs-absent rule.+export const songPracticeSessions = (song) => (+ Number.isInteger(song?.practice?.sessions) ? song.practice.sessions : 0+);+export const INSTRUMENTS = [{ id: 'guitar', label: 'Guitar' },{ id: 'piano', label: 'Piano' },diff --git a/client/src/components/songbook/constants.test.js b/client/src/components/songbook/constants.test.jsindex c245fdbb23..bcebb33a48 100644--- a/client/src/components/songbook/constants.test.js+++ b/client/src/components/songbook/constants.test.js@@ -1,7 +1,8 @@import { describe, it, expect } from 'vitest';import {- INSTRUMENTS, SONG_FORMATS, DRUM_FORMAT, DRUM_INSTRUMENT,- instrumentLabel, withStoredOption,+ INSTRUMENTS, SONG_FORMATS, DRUM_FORMAT, DRUM_INSTRUMENT, SONG_STAGES,+ SONG_PRACTICE_RATINGS, instrumentLabel, withStoredOption,+ isSongDue, songNextReviewAt, songPracticeSessions,} from './constants.js';describe('SongBook constants', () => {@@ -28,6 +29,62 @@ describe('SongBook constants', () => {});});+describe('practice grades (#4102)', () => {+ it('mirrors the server songStageEnum ladder order (server/lib/songPractice.js)', () => {+ expect(SONG_STAGES.map((s) => s.id)).toEqual(['new', 'learning', 'learned', 'memorized']);+ });++ it('offers grades inside the server-accepted 0..5 range, ascending', () => {+ const grades = SONG_PRACTICE_RATINGS.map((r) => r.quality);+ expect(grades).toEqual([...grades].sort((a, b) => a - b));+ for (const quality of grades) {+ expect(Number.isInteger(quality)).toBe(true);+ expect(quality).toBeGreaterThanOrEqual(0);+ expect(quality).toBeLessThanOrEqual(5);+ }+ });++ it('covers every outcome the server ladder can produce', () => {+ const grades = SONG_PRACTICE_RATINGS.map((r) => r.quality);+ // SONG_REGRESS_MAX_QUALITY = 2, SONG_PROMOTE_MIN_QUALITY = 4 — a grade set+ // that can't reach one of the three outcomes leaves it unreachable in the UI.+ expect(grades.some((q) => q <= 2)).toBe(true);+ expect(grades.some((q) => q === 3)).toBe(true);+ expect(grades.some((q) => q >= 4)).toBe(true);+ expect(SONG_PRACTICE_RATINGS.every((r) => r.label && r.hint)).toBe(true);+ });+});++describe('songNextReviewAt / isSongDue / songPracticeSessions', () => {+ const NOW = Date.parse('2026-03-10T12:00:00.000Z');++ it('reads the stored schedule when there is one', () => {+ const song = { practice: { nextReview: '2026-03-20T00:00:00.000Z' }, updatedAt: '2026-01-01T00:00:00.000Z' };+ expect(songNextReviewAt(song)).toBe('2026-03-20T00:00:00.000Z');+ expect(isSongDue(song, NOW)).toBe(false);+ });++ it('anchors a song predating the feature to its own timestamps → due now', () => {+ // Mirrors songPracticeOrDefault server-side: NOT "due at this instant", so+ // two renders a millisecond apart agree.+ expect(songNextReviewAt({ updatedAt: '2026-02-01T00:00:00.000Z' })).toBe('2026-02-01T00:00:00.000Z');+ expect(songNextReviewAt({ createdAt: '2026-01-01T00:00:00.000Z' })).toBe('2026-01-01T00:00:00.000Z');+ expect(isSongDue({ updatedAt: '2026-02-01T00:00:00.000Z' }, NOW)).toBe(true);+ });++ it('surfaces a song it cannot schedule rather than hiding it forever', () => {+ expect(songNextReviewAt({})).toBe(null);+ expect(isSongDue({}, NOW)).toBe(true);+ expect(isSongDue({ practice: { nextReview: 'whenever' } }, NOW)).toBe(true);+ });++ it('distinguishes "never practiced" from a real zero without producing NaN', () => {+ expect(songPracticeSessions({})).toBe(0);+ expect(songPracticeSessions({ practice: { sessions: 4 } })).toBe(4);+ expect(songPracticeSessions({ practice: { sessions: 'many' } })).toBe(0);+ });+});+describe('withStoredOption', () => {it('returns the known list unchanged for a known value', () => {expect(withStoredOption(INSTRUMENTS, 'drums')).toEqual(INSTRUMENTS);diff --git a/client/src/pages/SongBook.jsx b/client/src/pages/SongBook.jsxindex ea39c9c274..90db6540a9 100644--- a/client/src/pages/SongBook.jsx+++ b/client/src/pages/SongBook.jsx@@ -6,9 +6,11 @@* memorized). A plain padded+scrolling page (NOT full-width, like /rounds);* the play/edit viewer lives at /songbook/:id and import at /songbook/import.*- * Filters live in URL search params (?stage=&instrument=&tag=&q=) so a- * filtered view is linkable (Catalog.jsx pattern). Stage flips PATCH just the- * stage field and update local state reactively — no refetch.+ * Filters live in URL search params (?stage=&instrument=&tag=&q=&due=) so a+ * filtered view is linkable (Catalog.jsx pattern) — `?due=1` is the "what+ * should I practice today?" view, reading the spaced-repetition schedule the+ * practice endpoint maintains (#4102). Stage flips PATCH just the stage field+ * and update local state reactively — no refetch.*/import { useEffect, useMemo, useState, useCallback } from 'react';@@ -19,12 +21,13 @@ import PageHeader from '../components/PageHeader';import EmptyState from '../components/EmptyState';import Banner from '../components/ui/Banner';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';-import { timeAgo } from '../utils/formatters';+import { timeAgo, timeUntil } from '../utils/formatters';import { useAsyncAction } from '../hooks/useAsyncAction';import { useConfirmDelete } from '../hooks/useConfirmDelete';import { listSongs, createSong, deleteSong, updateSong } from '../services/api';import {SONG_STAGES, SONG_STAGE_COLORS, INSTRUMENTS, instrumentLabel, inputClass, labelClass,+ isSongDue, songNextReviewAt,} from '../components/songbook/constants';export default function SongBook() {@@ -34,6 +37,9 @@ export default function SongBook() {const instrumentFilter = searchParams.get('instrument') || '';const tagFilter = searchParams.get('tag') || '';const q = searchParams.get('q') || '';+ // "What should I practice today?" — URL-backed like every other filter, so a+ // practice session is a bookmarkable view (?due=1).+ const dueOnly = searchParams.get('due') === '1';const setParam = useCallback((key, value) => {setSearchParams((prev) => {@@ -101,14 +107,21 @@ export default function SongBook() {const filtered = useMemo(() => {const needle = q.trim().toLowerCase();+ const now = Date.now();return (songs || []).filter((s) => {if (stageFilter && s.stage !== stageFilter) return false;if (instrumentFilter && s.instrument !== instrumentFilter) return false;if (tagFilter && !(Array.isArray(s.tags) && s.tags.includes(tagFilter))) return false;if (needle && !(`${s.title} ${s.artist}`.toLowerCase().includes(needle))) return false;+ if (dueOnly && !isSongDue(s, now)) return false;return true;});- }, [songs, stageFilter, instrumentFilter, tagFilter, q]);+ }, [songs, stageFilter, instrumentFilter, tagFilter, q, dueOnly]);++ const dueCount = useMemo(() => {+ const now = Date.now();+ return (songs || []).filter((s) => isSongDue(s, now)).length;+ }, [songs]);const selectClass = 'bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:border-port-accent focus:outline-none';@@ -187,6 +200,16 @@ export default function SongBook() {<option value="">All instruments</option>{INSTRUMENTS.map((i) => <option key={i.id} value={i.id}>{i.label}</option>)}</select>+ <button+ type="button"+ onClick={() => setParam('due', dueOnly ? '' : '1')}+ aria-pressed={dueOnly}+ className={`px-3 py-2 rounded-lg text-sm border ${dueOnly+ ? 'bg-port-warning/20 text-port-warning border-port-warning/30'+ : 'bg-port-bg text-gray-400 border-port-border hover:text-white'}`}+ >+ Due{dueCount > 0 ? ` (${dueCount})` : ''}+ </button>{tagFilter && (<buttontype="button"@@ -251,6 +274,11 @@ export default function SongBook() {{song.artist && <span className="text-gray-400">{song.artist}</span>}{song.instrument && <span>{instrumentLabel(song.instrument)}</span>}{song.updatedAt && <span>Edited {timeAgo(song.updatedAt)}</span>}+ {isSongDue(song) ? (+ <span className="text-port-warning">Due for practice</span>+ ) : (+ <span>Review {timeUntil(songNextReviewAt(song), 'today')}</span>+ )}</div></Link>{Array.isArray(song.tags) && song.tags.length > 0 && (diff --git a/client/src/pages/SongBook.test.jsx b/client/src/pages/SongBook.test.jsxindex ff52bb2395..0b1688de8a 100644--- a/client/src/pages/SongBook.test.jsx+++ b/client/src/pages/SongBook.test.jsx@@ -88,6 +88,40 @@ describe('SongBook index', () => {expect(screen.queryByText('Example Song')).toBeNull();});+ // Practice scheduling (#4102) — the "what should I practice today?" view.+ it('filters to due songs from ?due=1 and counts them on the toggle', async () => {+ const soon = new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toISOString();+ api.listSongs.mockResolvedValue({+ songs: [+ song('s1', 'Example Song'), // no practice schedule → due+ song('s2', 'Other Tune', { practice: { nextReview: soon, sessions: 2 } }),+ ],+ });+ renderPage('/songbook?due=1');+ expect(await screen.findByText('Example Song')).toBeTruthy();+ expect(screen.queryByText('Other Tune')).toBeNull();+ // Count is over ALL songs, not the filtered view.+ expect(screen.getByRole('button', { name: 'Due (1)' }).getAttribute('aria-pressed')).toBe('true');+ });++ it('labels each card as due or scheduled', async () => {+ const soon = new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toISOString();+ api.listSongs.mockResolvedValue({+ songs: [song('s1', 'Example Song'), song('s2', 'Other Tune', { practice: { nextReview: soon } })],+ });+ renderPage();+ expect(await screen.findByText('Due for practice')).toBeTruthy();+ expect(screen.getByText(/^Review in \d/)).toBeTruthy();+ });++ it('toggles the due filter into the URL rather than local state', async () => {+ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: /^Due/ }));+ await waitFor(() => expect(+ screen.getByRole('button', { name: /^Due/ }).getAttribute('aria-pressed'),+ ).toBe('true'));+ });+it('shows the teaching empty state when there are no songs', async () => {api.listSongs.mockResolvedValue({ songs: [] });renderPage();diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex 3f49c3cd29..98c87e2dd1 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -55,6 +55,7 @@ import TabSheetView from '../components/songbook/TabSheetView';import DrumSheetView from '../components/songbook/DrumSheetView';import DrumPreview from '../components/songbook/DrumPreview';import DrumTransportBar from '../components/songbook/DrumTransportBar';+import PracticeLogger from '../components/songbook/PracticeLogger';import {SONG_STAGES, SONG_STAGE_COLORS, INSTRUMENTS, SONG_FORMATS, DRUM_FORMAT,DRUM_INSTRUMENT, withStoredOption,@@ -366,6 +367,15 @@ export default function SongBookViewer() {.catch(() => {});}, [id]);+ // A logged practice run advances `stage` server-side alongside `practice`, so+ // the whole updated record replaces local state — and the edit draft's stage+ // follows, or reopening Edit would save the pre-practice stage back over it.+ const onPracticeLogged = useCallback((updated) => {+ if (!updated) return;+ setSong(updated);+ setDraft((prev) => (prev ? { ...prev, stage: updated.stage } : prev));+ }, []);+const [save, saving] = useAsyncAction(async () => {const title = draft.title.trim();if (!title) { toast.error('Title is required'); return null; }@@ -934,6 +944,10 @@ export default function SongBookViewer() {</div>)}+ {/* Practice sits at the END of the sheet, which is where a run of+ the song actually finishes (the autoscroll leaves you here). */}+ <PracticeLogger song={song} onLogged={onPracticeLogged} className="mt-6 max-w-4xl" />+{/* Attachments */}<div className="mt-8 max-w-4xl border-t border-port-border pt-4 pb-16"><div className="flex items-center justify-between mb-2">diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxindex 9e2d6634e6..0b4616a365 100644--- a/client/src/pages/SongBookViewer.test.jsx+++ b/client/src/pages/SongBookViewer.test.jsx@@ -10,6 +10,7 @@ const api = vi.hoisted(() => ({listSongAttachments: vi.fn(),uploadSongAttachment: vi.fn(),deleteSongAttachment: vi.fn(),+ practiceSong: vi.fn(),songAttachmentUrl: (id, filename) => `/api/brain/songbook/${id}/attachments/${filename}`,}));vi.mock('../services/api', () => api);@@ -64,6 +65,7 @@ describe('SongBookViewer', () => {api.listSongAttachments.mockReset().mockResolvedValue([]);api.updateSong.mockReset();api.deleteSong.mockReset();+ api.practiceSong.mockReset();globalThis.localStorage?.clear?.();});@@ -111,6 +113,21 @@ describe('SongBookViewer', () => {await waitFor(() => expect(screen.getByLabelText('Learning stage').value).toBe('learned'));});+ // A logged practice run moves the stage server-side (#4102), so the chip and+ // the edit draft must both follow the returned record — not just `practice`.+ it('merges a logged practice run, advancing the stage chip', async () => {+ api.practiceSong.mockResolvedValue(song({+ stage: 'learning',+ practice: { ease: 2.5, intervalDays: 1, nextReview: '2099-01-01T00:00:00.000Z', lastReviewed: '2026-03-01T00:00:00.000Z', sessions: 1 },+ }));+ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: 'Solid' }));+ expect(api.practiceSong).toHaveBeenCalledWith('abc', 4, { silent: true });+ await waitFor(() => expect(screen.getByLabelText('Learning stage').value).toBe('learning'));+ // The stage select stays available as a manual override.+ expect(screen.getByLabelText('Learning stage').disabled).toBe(false);+ });+it('marks synced-but-absent attachments as not on this machine', async () => {api.listSongAttachments.mockResolvedValue([{ filename: 'aaaa1111-sheet.pdf', label: 'Sheet music', mime: 'application/pdf', size: 1024, sha256: 'x', present: false },diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 5ffa124311..be7b9b7c01 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -115,7 +115,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiWritersRoom.js` | Writers Room (folders + works + drafts, live continuation + render-preview reservation, scene-image attach). || `apiSharing.js` | Share buckets + federation sync. || `apiRounds.js` | Rounds workbench CRUD (a cappella round writing + arranging voice layers + learning tracking). |-| `apiSongbook.js` | SongBook repertoire tracker (`/songbook` — Brain `songs` entity): song CRUD + stage PATCH, URL import draft, and attachments (base64 upload, present-flag list, raw serve URL via `songAttachmentUrl`). |+| `apiSongbook.js` | SongBook repertoire tracker (`/songbook` — Brain `songs` entity): song CRUD + stage PATCH, `practiceSong(id, quality)` (logs a 0..5-graded practice run; the server owns the SM-2 advance and the resulting `stage`/`practice`), URL import draft, and attachments (base64 upload, present-flag list, raw serve URL via `songAttachmentUrl`). || `apiPeerSync.js` | Per-record peer sync subscriptions (universe + series → other PortOS instances over Tailnet). || `apiSyncReview.js` | Sync hygiene: duplicate-record detection + smart merge (universe/series) and the non-blocking edit-conflict journal (list/resolve). Surfaced in Sharing → Duplicates / Conflicts. |diff --git a/client/src/services/apiSongbook.js b/client/src/services/apiSongbook.jsindex 7ca09ce333..f7c13459c2 100644--- a/client/src/services/apiSongbook.js+++ b/client/src/services/apiSongbook.js@@ -35,6 +35,13 @@ export const updateSong = (id, patch, options) =>export const deleteSong = (id, options) =>request(`/brain/songbook/${enc(id)}`, { method: 'DELETE', ...options });+// Log one practice run, graded 0..5 (`SONG_PRACTICE_RATINGS` in+// components/songbook/constants.js) → the updated song record. The server owns+// the SM-2 advance and the resulting `stage`/`practice` — the grade is the only+// input, and a client-supplied `practice` object is stripped (#4102).+export const practiceSong = (id, quality, options) =>+ request(`/brain/songbook/${enc(id)}/practice`, { method: 'POST', body: JSON.stringify({ quality }), ...options });+// Fetch + extract a draft from a tab/chord-sheet URL → { draft: { title,// artist, content: { format, text }, sourceUrl } }. Nothing is stored — the// user reviews and saves explicitly. Error codes: 400 UNSAFE_URL,diff --git a/docs/plans/2026-07-15-songbook.md b/docs/plans/2026-07-15-songbook.mdindex 1e838f3ea3..ecd45fd429 100644--- a/docs/plans/2026-07-15-songbook.md+++ b/docs/plans/2026-07-15-songbook.md@@ -205,8 +205,15 @@ invent fixture tabs (e.g. "Example Song" by "The Placeholders").## Explicitly deferred (PLAN.md items if not done)-- Practice/spaced-rep integration (`songProgress.js` / SM-2 in meatspacePostMemory) —- stage field is manual v1.+- ~~Practice/spaced-rep integration (`songProgress.js` / SM-2 in meatspacePostMemory) —+ stage field is manual v1.~~ **Shipped in #4102** — the SM-2 core moved out of+ `meatspacePostMemory.js` into `server/lib/spacedRepetition.js` (shared, with+ the service re-exporting it), `server/lib/songPractice.js` holds the song+ semantics, and `POST /:id/practice` logs a run graded 0..5 that advances the+ `practice` schedule and the `stage`. `practice` is server-managed (no write-+ schema key, like `attachments`) and derived on READ for songs predating the+ feature — no backfill migration, so the `data.reference/` seeds stay+ byte-identical across installs.- Linking a song to existing Rounds/Tracks/MIDI records (cross-links field).- Chord diagrams / fretboard rendering; MIDI/score preview embedding in the viewer.- Voice/palette actions (nav entry alone gives ⌘K + voice nav).diff --git a/server/lib/README.md b/server/lib/README.mdindex 44702edb33..9cf6615772 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -292,6 +292,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `postMultiplicationLadder.js` | Pure progressive multiplication ladder — mastery-gated difficulty rungs (`[1,1]` → `[1,2]` → `[1,1,1]` → …). Resolves the user's current level from per-level speed+accuracy stats so the plain multiplication drill ramps up instead of starting at a fixed hard difficulty. On by default. Built on `postProgression.js`. || `postPowersLadder.js` | Pure technique-anchored Powers ladder — cumulative named-method pools, full supported-pair registry, and speed+accuracy mastery progression built on `postProgression.js`. || `postProgression.js` | Generic mastery-gated progression ladder (extracted from `postMultiplicationLadder.js`) — `createProgression({ levels, describeLevel, speedTargetForLevel? })` resolves a user's current rung from per-level stats with an anti-demotion floor. Also defines the cognitive-drill ladders (n-back / digit-span / schulte / mental-rotation / stroop) and their level→generator-config mapping. |+| `spacedRepetition.js` | The shared SM-2-inspired review scheduler, extracted from `services/meatspacePostMemory.js` when SongBook practice became its second consumer (#4102). One four-field schedule shape (`{ ease, intervalDays, nextReview, lastReviewed }`, no `repetitions` counter — the 0 → 1 → 6 → `round(prev * ease)` ladder derives from the previous interval, so a schedule round-trips through import/export/federation on those four fields alone). `advanceSchedule(schedule, ratio, now)` is the core (ease clamped to `MIN_EASE`..`MAX_EASE`, interval capped at `MAX_INTERVAL_DAYS` so `new Date(now + interval*DAY)` can't overflow into an Invalid Date; quality < 3 zeroes the interval to resurface the record but still applies the ease penalty). `mergeScheduleAdvance(prev, advanced, now)` gates interval GROWTH to once per review day (a shrink always applies) for UIs that submit per chunk/section; `isSameReviewDay` is that gate's own predicate, reusable by callers gating their own once-a-day progression. `scheduleOrDefault(record, schedule?)` is the read-path fallback — a record with no schedule derives one anchored to its `updatedAt`/`createdAt` (stable and in the past → due now), so "due" can't flap between two reads a millisecond apart. `ratioToQuality` / `qualityToRatio` are exact inverses over the integers, so a self-graded 0..5 review lands on the quality the user picked. `isScheduleDue` treats an absent/unparseable `nextReview` as due — a record we can't schedule is one to surface, never one to hide forever. Pure. |+| `songPractice.js` | SongBook repertoire practice scheduling (#4102) — the pure core behind `POST /api/brain/songbook/:id/practice`. `applySongPractice(song, quality, now)` → `{ stage, practice }`, the exact partial to hand `brainStorage.updateWith`: it advances the shared `spacedRepetition` schedule from a 0..5 self-grade and moves the song's `stage` along `SONG_STAGE_ORDER` (≥ `SONG_PROMOTE_MIN_QUALITY` promotes, ≤ `SONG_REGRESS_MAX_QUALITY` regresses, a 3 holds). Promotion is gated to once per practice day (regression never is), and a practiced song floors at `learning` — `new` means "never picked up", which stops being true after one session. `songPracticeOrDefault(song)` derives the schedule on READ for every song predating the feature (nothing is backfilled to disk: a migration would restamp `updatedAt` on every record and spray federation churn, and would break the `data.reference/` seeds' byte-identity). `nextSongStage` no-ops on a stage this install doesn't recognize, so a practice log can't rewrite a value synced from a newer peer. `isSongDue(song, now)` mirrors the client's `songDueAt` in `client/src/components/songbook/constants.js`. Pure. || `postTopics.js` | Pure POST practice-topic registry — `POST_TOPICS` (`{ id, label, module, surface, drillTypes }`) is the single source of truth for "what am I studying?", plus `resolveTopicForDrillType` / `isTopicEnabled` / `isMemoryItemEnabled`. Gates session composition and recommendations, including Memory's composed and dedicated practice routes plus standalone Morse. Mirrored to the client's post `constants.js` (parity test). || `postStreak.js` | Pure DST-safe POST practice-streak math — the single `computePostStreaks` implementation shared by scored sessions and the training log, plus `computeUnifiedStreak` (a day is active with EITHER a session or a practice entry) and `normalizeYmd` (day-key prefix for a date that may be a full ISO timestamp). || `planIds.js` | Utilities for PLAN.md `[slug]` IDs. |diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex b62a464fed..43415dc0f7 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -1,6 +1,7 @@import { z } from 'zod';import { partialWithoutDefaults, optionalBooleanMap } from './zodCompat.js';import { REPO_INTAKE_KEYS } from './repoIntakeActions.js';+import { MAX_QUALITY } from './spacedRepetition.js';// Destination enum. `links` is reachable only from the bare-URL capture// short-circuit (a pasted URL is filed straight to the links collection) — the@@ -674,6 +675,24 @@ export const songUpdateSchema = partialWithoutDefaults(songInputSchema).extend({content: partialWithoutDefaults(songContentSchema).optional()});+// POST /api/brain/songbook/:id/practice — log one practice run (#4102).+//+// `quality` is the SM-2 self-grade for the run: 0 = couldn't play it, 5 = clean.+// It is the ONLY input; the resulting schedule and stage are computed+// server-side from the stored record (see lib/songPractice.js), because an+// SM-2 advance needs the previous schedule and a client-computed one would both+// race and put the scheduler in the browser.+//+// The `practice` object itself is deliberately absent from songInputSchema /+// songUpdateSchema: like `attachments`, it is server-managed, so Zod's+// unknown-key stripping drops a client-supplied value and only this endpoint+// can move it.+// The ceiling reads from lib/spacedRepetition.js rather than restating `5`, so+// the accepted grade range can never drift from the scale the scheduler grades on.+export const songPracticeInputSchema = z.object({+ quality: z.number().int().min(0).max(MAX_QUALITY)+});+// POST /api/brain/songbook/import/urlexport const songImportUrlSchema = z.object({url: z.string().url().max(2000)diff --git a/server/lib/index.js b/server/lib/index.jsindex ebe3b5feac..49e3b9c087 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -275,6 +275,8 @@ export * from './postPowersLadder.js';export * from './postProgression.js';export * from './postStreak.js';export * from './postTopics.js';+export * from './spacedRepetition.js';+export * from './songPractice.js';export * from './planIds.js';export * from './renderSlot.js';export * from './renderTargets.js';diff --git a/server/lib/songPractice.js b/server/lib/songPractice.jsnew file mode 100644index 0000000000..ff025a2dcb--- /dev/null+++ b/server/lib/songPractice.js@@ -0,0 +1,134 @@+/**+ * SongBook practice scheduling — the pure core behind `POST+ * /api/brain/songbook/:id/practice` (#4102).+ *+ * A repertoire song's `stage` (`new → learning → learned → memorized`) was+ * manual in SongBook v1: nothing moved it, and nothing told the user WHICH song+ * to pick up today. Logging a practice session now does both — it grades the+ * run 0..5 and, from that grade, advances the SM-2 schedule (shared with+ * MeatSpace POST via `lib/spacedRepetition.js`) and advances or regresses the+ * stage.+ *+ * ## Where the schedule lives+ *+ * On the song record as `practice`, carrying the shared four-field schedule+ * plus two song-local counters:+ *+ * { ease, intervalDays, nextReview, lastReviewed, sessions, lastQuality }+ *+ * `practice` is SERVER-MANAGED, exactly like `attachments`: the write schemas+ * have no key for it, so Zod's unknown-key stripping drops a client-supplied+ * value and only the practice endpoint can move it. Computing an SM-2 advance+ * needs the stored schedule, so it could not be a plain PATCH anyway — that+ * would race, and would push the scheduler into the browser.+ *+ * ## Backward + forward compatibility (this matters — songs federate)+ *+ * Brain songs sync raw between installs (LWW, no Zod on receive), and every+ * install upgrades on its own schedule. So:+ *+ * - `practice` is purely ADDITIVE and absent on every song that predates this+ * feature. `songPracticeOrDefault` derives one on READ, anchored to the+ * song's own `updatedAt`/`createdAt` — nothing is backfilled to disk. A+ * backfill migration would rewrite every song record on every peer, restamp+ * `updatedAt`, and spray that churn across the federation for a value the+ * read path already computes. It would also break the `data.reference/`+ * seeds' byte-identity (a seeded `nextReview` differs per install).+ * - An unrecognized `stage` from a newer peer is left ALONE rather than+ * snapped into this version's ladder (`nextSongStage` no-ops on it), so a+ * practice log can't rewrite a value this install doesn't understand.+ */++import {+ advanceSchedule,+ isSameReviewDay,+ isScheduleDue,+ mergeScheduleAdvance,+ qualityToRatio,+ scheduleOrDefault,+} from './spacedRepetition.js';++/**+ * The stage ladder, in order. Mirrors `songStageEnum` in brainValidation.js and+ * `SONG_STAGES` in client/src/components/songbook/constants.js — parity is+ * asserted by the tests on both sides.+ */+export const SONG_STAGE_ORDER = Object.freeze(['new', 'learning', 'learned', 'memorized']);++/**+ * Grade at or above which a session promotes the song one stage. 4 = "solid,+ * with hesitation" on the SM-2 scale — the point where you'd say you can play+ * it, not merely that you got through it.+ */+export const SONG_PROMOTE_MIN_QUALITY = 4;+/**+ * Grade at or below which a session regresses one stage. 2 = "wrong, but it+ * came back once you saw it". A 3 holds the stage: a shaky-but-complete run is+ * evidence you're where you thought you were, not evidence of movement.+ */+export const SONG_REGRESS_MAX_QUALITY = 2;++/**+ * The lowest stage a PRACTICED song can regress to. `new` means "never picked+ * up", which stops being true the moment you log a session — so a bad run drops+ * you to `learning`, never back to `new`. (This is also why a bad first session+ * on a `new` song moves it FORWARD to `learning`: you have now started it.)+ */+const MIN_PRACTICED_STAGE_INDEX = 1;++/**+ * The song's practice schedule as it should be READ, without persisting+ * anything. Absent/malformed → a default anchored to the song itself, so an+ * unpracticed song reads as due now and two reads a millisecond apart agree.+ */+export function songPracticeOrDefault(song) {+ return scheduleOrDefault(song, song?.practice);+}++/** Is this song due for practice at `now`? Never-practiced songs are due. */+export function isSongDue(song, now = new Date()) {+ return isScheduleDue(songPracticeOrDefault(song), now);+}++/**+ * The stage a session graded `quality` moves `stage` to.+ *+ * `allowPromotion: false` holds the stage where it is on a good run — used for+ * a second session on a day that already had one, for the same reason interval+ * growth is gated: two run-throughs in one afternoon are one day of progress,+ * not two. A regression is never gated; a run that fell apart should show today+ * regardless of how the earlier one went.+ *+ * An unknown stage (a value synced from a newer peer) is returned unchanged.+ */+export function nextSongStage(stage, quality, { allowPromotion = true } = {}) {+ const index = SONG_STAGE_ORDER.indexOf(stage);+ if (index === -1) return stage;+ if (quality <= SONG_REGRESS_MAX_QUALITY) {+ return SONG_STAGE_ORDER[Math.max(MIN_PRACTICED_STAGE_INDEX, index - 1)];+ }+ if (allowPromotion && quality >= SONG_PROMOTE_MIN_QUALITY) {+ return SONG_STAGE_ORDER[Math.min(SONG_STAGE_ORDER.length - 1, index + 1)];+ }+ return stage;+}++/**+ * Log one practice session against `song`, graded `quality` (0..5).+ *+ * Pure — returns ONLY the fields to persist (`{ stage, practice }`), so the+ * caller can hand it straight to `brainStorage.updateWith` and let the locked+ * read-modify-write merge it over the freshest record.+ */+export function applySongPractice(song, quality, now = new Date()) {+ const previous = songPracticeOrDefault(song);+ const sameDay = isSameReviewDay(previous.lastReviewed, now);+ const advanced = advanceSchedule(previous, qualityToRatio(quality), now);+ const schedule = mergeScheduleAdvance(previous, advanced, now);+ const sessions = Number.isInteger(previous.sessions) ? previous.sessions : 0;++ return {+ stage: nextSongStage(song?.stage || 'new', quality, { allowPromotion: !sameDay }),+ practice: { ...schedule, sessions: sessions + 1, lastQuality: quality },+ };+}diff --git a/server/lib/songPractice.test.js b/server/lib/songPractice.test.jsnew file mode 100644index 0000000000..f688ec5005--- /dev/null+++ b/server/lib/songPractice.test.js@@ -0,0 +1,167 @@+import { describe, it, expect } from 'vitest';+import {+ SONG_PROMOTE_MIN_QUALITY,+ SONG_REGRESS_MAX_QUALITY,+ SONG_STAGE_ORDER,+ applySongPractice,+ isSongDue,+ nextSongStage,+ songPracticeOrDefault,+} from './songPractice.js';+import { songStageEnum } from './brainValidation.js';+import { DEFAULT_EASE } from './spacedRepetition.js';++const NOW = new Date('2026-03-10T12:00:00.000Z');+const LATER = new Date('2026-03-14T12:00:00.000Z');++const song = (overrides = {}) => ({+ id: 'song-1',+ title: 'Example Song',+ stage: 'learning',+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-02-01T00:00:00.000Z',+ ...overrides,+});++describe('SONG_STAGE_ORDER', () => {+ it('mirrors songStageEnum, in ladder order', () => {+ expect(SONG_STAGE_ORDER).toEqual(songStageEnum.options);+ });+});++describe('songPracticeOrDefault', () => {+ it('derives a schedule for a song that predates the feature', () => {+ const derived = songPracticeOrDefault(song());+ expect(derived).toEqual({+ ease: DEFAULT_EASE,+ intervalDays: 0,+ // Anchored to the song's own updatedAt — stable across reads, in the past.+ nextReview: '2026-02-01T00:00:00.000Z',+ lastReviewed: null,+ });+ expect(songPracticeOrDefault(song())).toEqual(derived);+ });++ it('returns a stored practice schedule untouched', () => {+ const practice = { ease: 2.6, intervalDays: 6, nextReview: '2026-04-01T00:00:00.000Z', sessions: 3 };+ expect(songPracticeOrDefault(song({ practice }))).toBe(practice);+ });+});++describe('isSongDue', () => {+ it('treats a never-practiced song as due', () => {+ expect(isSongDue(song(), NOW)).toBe(true);+ });++ it('respects a scheduled future review', () => {+ const scheduled = song({ practice: { ease: 2.5, intervalDays: 6, nextReview: '2026-03-20T00:00:00.000Z' } });+ expect(isSongDue(scheduled, NOW)).toBe(false);+ expect(isSongDue(scheduled, new Date('2026-03-21T00:00:00.000Z'))).toBe(true);+ });+});++describe('nextSongStage', () => {+ it('promotes one rung at or above the promote grade', () => {+ expect(nextSongStage('new', SONG_PROMOTE_MIN_QUALITY)).toBe('learning');+ expect(nextSongStage('learning', 5)).toBe('learned');+ expect(nextSongStage('learned', 4)).toBe('memorized');+ });++ it('holds at the top of the ladder', () => {+ expect(nextSongStage('memorized', 5)).toBe('memorized');+ });++ it('holds on a middling grade', () => {+ expect(nextSongStage('learning', 3)).toBe('learning');+ expect(nextSongStage('memorized', 3)).toBe('memorized');+ });++ it('regresses one rung at or below the regress grade', () => {+ expect(nextSongStage('memorized', SONG_REGRESS_MAX_QUALITY)).toBe('learned');+ expect(nextSongStage('learned', 0)).toBe('learning');+ });++ it('floors a practiced song at learning — never back to new', () => {+ expect(nextSongStage('learning', 0)).toBe('learning');+ // A bad first run on an untouched song still means you have STARTED it.+ expect(nextSongStage('new', 0)).toBe('learning');+ });++ it('leaves a stage this install does not recognize alone', () => {+ expect(nextSongStage('gigging', 5)).toBe('gigging');+ expect(nextSongStage('gigging', 0)).toBe('gigging');+ expect(nextSongStage(undefined, 5)).toBe(undefined);+ });++ it('holds a promotion when promotion is gated', () => {+ expect(nextSongStage('learning', 5, { allowPromotion: false })).toBe('learning');+ // A regression is never gated.+ expect(nextSongStage('learned', 0, { allowPromotion: false })).toBe('learning');+ });+});++describe('applySongPractice', () => {+ it('returns only the fields to persist', () => {+ expect(Object.keys(applySongPractice(song(), 5, NOW)).sort()).toEqual(['practice', 'stage']);+ });++ it('advances the schedule and the stage on a good first run', () => {+ const { stage, practice } = applySongPractice(song(), 5, NOW);+ expect(stage).toBe('learned');+ expect(practice.intervalDays).toBe(1);+ expect(practice.lastReviewed).toBe(NOW.toISOString());+ expect(practice.sessions).toBe(1);+ expect(practice.lastQuality).toBe(5);+ expect(isSongDue({ practice }, NOW)).toBe(false);+ });++ it('resurfaces the song immediately and regresses the stage on a bad run', () => {+ const practiced = song({+ stage: 'memorized',+ practice: { ease: 2.5, intervalDays: 30, nextReview: NOW.toISOString(), lastReviewed: '2026-02-08T12:00:00.000Z', sessions: 4 },+ });+ const { stage, practice } = applySongPractice(practiced, 0, NOW);+ expect(stage).toBe('learned');+ expect(practice.intervalDays).toBe(0);+ expect(practice.sessions).toBe(5);+ expect(isSongDue({ practice }, NOW)).toBe(true);+ });++ it('counts two sessions in one day as one day of progress', () => {+ const first = applySongPractice(song({ stage: 'new' }), 5, NOW);+ const second = applySongPractice(song({ stage: first.stage, practice: first.practice }), 5, NOW);+ // Stage held and the interval did not compound…+ expect(second.stage).toBe(first.stage);+ expect(second.practice.intervalDays).toBe(first.practice.intervalDays);+ expect(second.practice.nextReview).toBe(first.practice.nextReview);+ // …but the session still counted.+ expect(second.practice.sessions).toBe(2);+ });++ it('advances again on a later day', () => {+ const first = applySongPractice(song({ stage: 'new' }), 5, NOW);+ const second = applySongPractice(song({ stage: first.stage, practice: first.practice }), 5, LATER);+ expect(second.stage).toBe('learned');+ expect(second.practice.intervalDays).toBeGreaterThan(first.practice.intervalDays);+ });++ it('applies a same-day miss even after a same-day success', () => {+ const good = applySongPractice(song({ stage: 'learning' }), 5, NOW);+ const bad = applySongPractice(song({ stage: good.stage, practice: good.practice }), 0, NOW);+ expect(bad.practice.intervalDays).toBe(0);+ expect(bad.stage).toBe('learning');+ });++ it('starts session counting from 1 for a song with no practice history', () => {+ expect(applySongPractice(song(), 3, NOW).practice.sessions).toBe(1);+ // A corrupt/absent counter must not produce NaN.+ expect(applySongPractice(song({ practice: { nextReview: NOW.toISOString(), sessions: 'many' } }), 3, NOW).practice.sessions).toBe(1);+ });++ it('is pure — the song record is never mutated', () => {+ const record = song({ practice: { ease: 2.5, intervalDays: 6, nextReview: NOW.toISOString(), lastReviewed: null, sessions: 1 } });+ const snapshot = JSON.parse(JSON.stringify(record));+ applySongPractice(record, 5, LATER);+ expect(JSON.parse(JSON.stringify(record))).toEqual(snapshot);+ });+});diff --git a/server/lib/spacedRepetition.js b/server/lib/spacedRepetition.jsnew file mode 100644index 0000000000..cae99c2599--- /dev/null+++ b/server/lib/spacedRepetition.js@@ -0,0 +1,178 @@+/**+ * Spaced repetition (SM-2 inspired) — the shared scheduling core.+ *+ * Every record that wants to resurface on a review cadence carries the same+ * four-field schedule:+ *+ * { ease, intervalDays, nextReview, lastReviewed }+ *+ * A record is "due" when `nextReview <= now`. Reviewing it advances the+ * schedule: a correct-heavy pass pushes the next review further out, a miss+ * resets the interval to 0 so the record resurfaces immediately.+ *+ * The shape is deliberately additive and migration-safe — a record predating+ * spaced repetition simply has no schedule, and `scheduleOrDefault` derives one+ * anchored to the record's own `updatedAt`/`createdAt` (stable, in the past →+ * due now) so "due" state can't flap between reads.+ *+ * There is NO `repetitions` counter: the 0 → 1 → 6 → round(prev * ease) ladder+ * is derived from the previous interval, so a schedule round-tripping through+ * import/export/federation needs only these four fields.+ *+ * Extracted from `services/meatspacePostMemory.js` (which re-exports these for+ * its existing callers) when SongBook repertoire practice became the second+ * consumer — see #4102.+ */++/** Starting ease for a never-reviewed record — the classic SM-2 default. */+export const DEFAULT_EASE = 2.5;+/** SM-2's ease floor: below this the interval ladder stops growing usefully. */+export const MIN_EASE = 1.3;+/**+ * Ease ceiling. The per-review +0.1 bumps are unbounded otherwise, so ~26+ * perfect reps would push ease past 5, and any Zod schema mirroring this shape+ * (`memoryScheduleSchema.ease.max(5)` in postValidation.js) would then 400 on+ * the server's own value during an import / out-of-band reschedule round-trip.+ * Keep any such schema in sync with this constant.+ */+export const MAX_EASE = 5;+/**+ * Cap the interval at a year so a long run of perfect reviews can't grow it+ * without bound — an astronomically large `intervalDays` would overflow+ * `new Date(now + intervalDays * DAY_MS)` into an Invalid Date and throw. A+ * yearly review floor is a conventional SRS ceiling and keeps records+ * resurfacing.+ */+export const MAX_INTERVAL_DAYS = 365;+/** Top of the SM-2 quality scale — a review grades 0..MAX_QUALITY. */+export const MAX_QUALITY = 5;++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 };+}++/** True when `schedule` is a usable schedule object rather than absent/garbage. */+export function isValidSchedule(schedule) {+ return Boolean(schedule) && typeof schedule === 'object' && typeof schedule.nextReview === 'string';+}++/**+ * The schedule to READ for a record, without persisting anything. Absent or+ * malformed schedules derive a default anchored to the record's own+ * `updatedAt`/`createdAt` — stable and in the past, so the record reads as due+ * now instead of the "due" answer flapping with the clock on every call.+ *+ * `null`/absent is deliberately NOT collapsed into "due at this instant": the+ * anchor is what makes two reads a millisecond apart agree.+ */+export function scheduleOrDefault(record, schedule = record?.schedule) {+ if (isValidSchedule(schedule)) return schedule;+ return defaultSchedule(record?.updatedAt || record?.createdAt || new Date().toISOString());+}++/**+ * SM-2 quality (0..5) for a correctness ratio (0..1). Non-finite input scores+ * 0 — an unmeasurable pass must never read as a perfect one.+ *+ * Note the pass threshold this implies: quality >= 3 needs ratio >= 0.5+ * (0.5 * 5 = 2.5 → rounds to 3).+ */+export function ratioToQuality(ratio) {+ const clamped = Math.max(0, Math.min(1, Number.isFinite(ratio) ? ratio : 0));+ return Math.round(clamped * MAX_QUALITY);+}++/**+ * The correctness ratio a caller passes to `advanceSchedule` for a review the+ * user graded directly on the 0..MAX_QUALITY scale (rather than one measured as+ * correct/total). Exact inverse of `ratioToQuality` over the integers, so a+ * self-graded review lands on the quality the user actually picked.+ */+export function qualityToRatio(quality) {+ const clamped = Math.max(0, Math.min(MAX_QUALITY, Number.isFinite(quality) ? quality : 0));+ return clamped / MAX_QUALITY;+}++/**+ * Did the previous review land on the same UTC day as `now`? The signal behind+ * once-per-day gating (interval growth in `mergeScheduleAdvance`, and any+ * caller-side progression that should count a day of work once).+ *+ * An absent/unparseable `lastReviewed` is NOT the same day — a record with no+ * review history must never read as "already reviewed today".+ */+export function isSameReviewDay(lastReviewed, now = new Date()) {+ const lastReviewedMs = Date.parse(lastReviewed ?? '');+ if (!Number.isFinite(lastReviewedMs)) return false;+ return new Date(lastReviewedMs).toISOString().slice(0, 10) === now.toISOString().slice(0, 10);+}++/**+ * Advance a schedule from a review'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 pass) → intervalDays 0 → due now again, but the+ * ease penalty still applies.+ * - 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 quality = ratioToQuality(ratio);+ 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.min(MAX_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));+ intervalDays = Math.min(MAX_INTERVAL_DAYS, intervalDays);+ }++ const nextReview = new Date(now.getTime() + intervalDays * DAY_MS).toISOString();+ return { ease, intervalDays, nextReview, lastReviewed: nowIso };+}++/**+ * Merge a freshly-advanced schedule against the record's prior schedule, gating+ * interval GROWTH to once per review day.+ *+ * Why: a "review" is one pass through the record, but a UI that submits per+ * chunk/section fires several advances in one sitting. Advancing on every+ * submission would compound the interval (0→1→6→16d) and drop the record off+ * the due list far longer than one completed review warrants. So a same-day+ * continuation only refreshes ease and `lastReviewed` — it keeps the+ * interval/nextReview already set earlier today. A miss (interval shrinks to 0)+ * always applies, so a fumbled pass still resurfaces the record immediately+ * regardless of earlier same-day success.+ */+export function mergeScheduleAdvance(prev, advanced, now = new Date()) {+ const prevInterval = typeof prev?.intervalDays === 'number' ? prev.intervalDays : 0;+ // Suppress compounding only when this is a same-day continuation AND the+ // interval would grow. Any shrink (a miss reset) always applies.+ if (isSameReviewDay(prev?.lastReviewed, now) && advanced.intervalDays > prevInterval) {+ return { ...prev, ease: advanced.ease, lastReviewed: advanced.lastReviewed };+ }+ return advanced;+}++/**+ * Is this schedule due at `now`? An absent or unparseable `nextReview` reads as+ * due — a record we can't schedule is one we should surface, never one we+ * silently hide forever.+ */+export function isScheduleDue(schedule, now = new Date()) {+ const nextReview = schedule?.nextReview;+ if (typeof nextReview !== 'string') return true;+ const at = Date.parse(nextReview);+ return Number.isNaN(at) || at <= now.getTime();+}diff --git a/server/lib/spacedRepetition.test.js b/server/lib/spacedRepetition.test.jsnew file mode 100644index 0000000000..db1940a67e--- /dev/null+++ b/server/lib/spacedRepetition.test.js@@ -0,0 +1,184 @@+import { describe, it, expect } from 'vitest';+import {+ DEFAULT_EASE,+ MAX_EASE,+ MAX_INTERVAL_DAYS,+ MAX_QUALITY,+ MIN_EASE,+ advanceSchedule,+ defaultSchedule,+ isSameReviewDay,+ isScheduleDue,+ isValidSchedule,+ mergeScheduleAdvance,+ qualityToRatio,+ ratioToQuality,+ scheduleOrDefault,+} from './spacedRepetition.js';++const NOW = new Date('2026-03-10T12:00:00.000Z');++describe('defaultSchedule', () => {+ it('is due at the anchor instant', () => {+ const schedule = defaultSchedule(NOW.toISOString());+ expect(schedule).toEqual({+ ease: DEFAULT_EASE, intervalDays: 0, nextReview: NOW.toISOString(), lastReviewed: null,+ });+ expect(isScheduleDue(schedule, NOW)).toBe(true);+ });+});++describe('scheduleOrDefault', () => {+ it('returns the stored schedule untouched when it is usable', () => {+ const stored = { ease: 2.1, intervalDays: 9, nextReview: '2026-04-01T00:00:00.000Z' };+ expect(scheduleOrDefault({ schedule: stored })).toBe(stored);+ });++ it('anchors a derived default to the record so two reads agree', () => {+ const record = { updatedAt: '2026-01-05T00:00:00.000Z', createdAt: '2025-12-01T00:00:00.000Z' };+ const first = scheduleOrDefault(record);+ const second = scheduleOrDefault(record);+ // Anchored to updatedAt (not "right now"), so repeated reads are identical+ // and the record reads as due rather than flapping with the clock.+ expect(first.nextReview).toBe('2026-01-05T00:00:00.000Z');+ expect(second).toEqual(first);+ expect(isScheduleDue(first, NOW)).toBe(true);+ });++ it('falls back to createdAt, then to now, and rejects malformed schedules', () => {+ expect(scheduleOrDefault({ createdAt: '2025-12-01T00:00:00.000Z' }).nextReview)+ .toBe('2025-12-01T00:00:00.000Z');+ // A schedule missing nextReview is not "empty", it is unusable — it must not+ // be handed back as if it scheduled anything.+ expect(isValidSchedule({ ease: 2.5, intervalDays: 3 })).toBe(false);+ expect(scheduleOrDefault({ createdAt: '2025-12-01T00:00:00.000Z' }, { ease: 2.5 }).ease)+ .toBe(DEFAULT_EASE);+ expect(typeof scheduleOrDefault({}).nextReview).toBe('string');+ });++ it('reads an explicit schedule argument instead of record.schedule', () => {+ const practice = { ease: 1.9, intervalDays: 4, nextReview: '2026-05-05T00:00:00.000Z' };+ expect(scheduleOrDefault({ schedule: undefined, practice }, practice)).toBe(practice);+ });+});++describe('ratioToQuality / qualityToRatio', () => {+ it('round-trips every integer grade exactly', () => {+ for (let quality = 0; quality <= MAX_QUALITY; quality += 1) {+ expect(ratioToQuality(qualityToRatio(quality))).toBe(quality);+ }+ });++ it('clamps out-of-range and non-finite input to the low end', () => {+ expect(ratioToQuality(2)).toBe(MAX_QUALITY);+ expect(ratioToQuality(-1)).toBe(0);+ // An unmeasurable pass must never read as a perfect one.+ expect(ratioToQuality(undefined)).toBe(0);+ expect(ratioToQuality(NaN)).toBe(0);+ expect(qualityToRatio(99)).toBe(1);+ expect(qualityToRatio(undefined)).toBe(0);+ });+});++describe('advanceSchedule', () => {+ it('steps the interval ladder 0 → 1 → 6 → round(prev * ease)', () => {+ const first = advanceSchedule(defaultSchedule(NOW.toISOString()), 1, NOW);+ expect(first.intervalDays).toBe(1);+ const second = advanceSchedule({ ...first, intervalDays: 1 }, 1, NOW);+ expect(second.intervalDays).toBe(6);+ const third = advanceSchedule({ ease: 2.5, intervalDays: 6, nextReview: NOW.toISOString() }, 1, NOW);+ expect(third.intervalDays).toBe(Math.round(6 * third.ease));+ });++ it('sets nextReview intervalDays into the future and stamps lastReviewed', () => {+ const next = advanceSchedule({ ease: 2.5, intervalDays: 6, nextReview: NOW.toISOString() }, 1, NOW);+ const expected = NOW.getTime() + next.intervalDays * 24 * 60 * 60 * 1000;+ expect(Date.parse(next.nextReview)).toBe(expected);+ expect(next.lastReviewed).toBe(NOW.toISOString());+ });++ it('resets a miss to due-now but still applies the ease penalty', () => {+ const prev = { ease: 2.5, intervalDays: 20, nextReview: NOW.toISOString() };+ const next = advanceSchedule(prev, 0, NOW);+ expect(next.intervalDays).toBe(0);+ expect(next.nextReview).toBe(NOW.toISOString());+ expect(next.ease).toBeLessThan(prev.ease);+ });++ it('clamps ease to the floor and ceiling', () => {+ let schedule = defaultSchedule(NOW.toISOString());+ for (let i = 0; i < 10; i += 1) schedule = advanceSchedule(schedule, 0, NOW);+ expect(schedule.ease).toBe(MIN_EASE);++ schedule = defaultSchedule(NOW.toISOString());+ for (let i = 0; i < 40; i += 1) schedule = advanceSchedule(schedule, 1, NOW);+ expect(schedule.ease).toBe(MAX_EASE);+ });++ it('caps the interval at a year so nextReview can never overflow', () => {+ const huge = advanceSchedule({ ease: 5, intervalDays: 10_000, nextReview: NOW.toISOString() }, 1, NOW);+ expect(huge.intervalDays).toBe(MAX_INTERVAL_DAYS);+ expect(Number.isNaN(Date.parse(huge.nextReview))).toBe(false);+ });++ it('treats an absent schedule as a fresh one rather than throwing', () => {+ expect(advanceSchedule(undefined, 1, NOW).intervalDays).toBe(1);+ });++ it('is pure — the input schedule is never mutated', () => {+ const prev = { ease: 2.5, intervalDays: 6, nextReview: NOW.toISOString(), lastReviewed: null };+ const snapshot = { ...prev };+ advanceSchedule(prev, 1, NOW);+ expect(prev).toEqual(snapshot);+ });+});++describe('isSameReviewDay', () => {+ it('is true only within the same UTC day', () => {+ expect(isSameReviewDay('2026-03-10T01:00:00.000Z', NOW)).toBe(true);+ expect(isSameReviewDay('2026-03-09T23:59:59.000Z', NOW)).toBe(false);+ });++ it('treats no review history as NOT reviewed today', () => {+ expect(isSameReviewDay(null, NOW)).toBe(false);+ expect(isSameReviewDay(undefined, NOW)).toBe(false);+ expect(isSameReviewDay('not-a-date', NOW)).toBe(false);+ });+});++describe('mergeScheduleAdvance', () => {+ it('lets the first review of the day through', () => {+ const prev = { ease: 2.5, intervalDays: 1, nextReview: NOW.toISOString(), lastReviewed: '2026-03-01T12:00:00.000Z' };+ const advanced = advanceSchedule(prev, 1, NOW);+ expect(mergeScheduleAdvance(prev, advanced, NOW)).toEqual(advanced);+ });++ it('suppresses same-day interval GROWTH but keeps the refreshed ease', () => {+ const prev = { ease: 2.5, intervalDays: 1, nextReview: NOW.toISOString(), lastReviewed: NOW.toISOString() };+ const advanced = advanceSchedule(prev, 1, NOW); // would step 1 → 6+ const merged = mergeScheduleAdvance(prev, advanced, NOW);+ expect(merged.intervalDays).toBe(1);+ expect(merged.nextReview).toBe(prev.nextReview);+ expect(merged.ease).toBe(advanced.ease);+ expect(merged.lastReviewed).toBe(advanced.lastReviewed);+ });++ it('always applies a same-day miss', () => {+ const prev = { ease: 2.5, intervalDays: 6, nextReview: NOW.toISOString(), lastReviewed: NOW.toISOString() };+ const advanced = advanceSchedule(prev, 0, NOW);+ expect(mergeScheduleAdvance(prev, advanced, NOW)).toEqual(advanced);+ });+});++describe('isScheduleDue', () => {+ it('compares nextReview against now', () => {+ expect(isScheduleDue({ nextReview: '2026-03-10T11:59:59.000Z' }, NOW)).toBe(true);+ expect(isScheduleDue({ nextReview: '2026-03-11T00:00:00.000Z' }, NOW)).toBe(false);+ });++ it('surfaces a record it cannot schedule rather than hiding it', () => {+ expect(isScheduleDue(undefined, NOW)).toBe(true);+ expect(isScheduleDue({}, NOW)).toBe(true);+ expect(isScheduleDue({ nextReview: 'whenever' }, NOW)).toBe(true);+ });+});diff --git a/server/routes/brainSongbook.js b/server/routes/brainSongbook.jsindex c1ff5ebb0b..ef46696ccb 100644--- a/server/routes/brainSongbook.js+++ b/server/routes/brainSongbook.js@@ -7,6 +7,11 @@** Mounted from the brain barrel at /songbook → /api/brain/songbook/...*+ * Practice: `POST /:id/practice` logs a graded run and moves the song's SM-2+ * schedule (`practice`) plus its learning `stage`. Both `practice` and+ * `attachments` are server-managed — the write schemas have no key for them, so+ * Zod's unknown-key stripping drops a client-supplied value.+ ** Attachments: METADATA lives in the synced record (identical on all peers);* BYTES are machine-local under data/brain/songbook/ (<uuid8>-<sanitized-name>).* The list endpoint reports `present: boolean` per attachment so peers lacking@@ -23,8 +28,10 @@ import {songInputSchema,songUpdateSchema,songImportUrlSchema,+ songPracticeInputSchema,songAttachmentUploadSchema,} from '../lib/brainValidation.js';+import { applySongPractice } from '../lib/songPractice.js';import * as brainStorage from '../services/brainStorage.js';import { importSongFromUrl } from '../services/brainSongbookImport.js';import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';@@ -134,6 +141,26 @@ router.delete('/:id', asyncHandler(async (req, res) => {res.json({ id: req.params.id });}));+// =============================================================================+// PRACTICE (spaced repetition)+// =============================================================================++// POST /:id/practice — log one practice run, graded 0..5. Advances the song's+// SM-2 schedule and its learning stage (see lib/songPractice.js).+//+// This earns its own endpoint rather than riding the generic PATCH because an+// SM-2 advance is computed FROM the stored schedule: the work happens inside+// `updateWith`'s locked read-modify-write, against the freshest record, so a+// concurrent edit or a peer-sync apply can't be clobbered — and the scheduler+// stays on the server instead of in the browser.+router.post('/:id/practice', asyncHandler(async (req, res) => {+ const { quality } = validateRequest(songPracticeInputSchema, req.body);+ const song = requireSong(await brainStorage.updateWith('songs', req.params.id,+ (fresh) => applySongPractice(fresh, quality)));+ console.log(`🎸 Practice logged: "${song.title}" quality=${quality} → ${song.stage}, next review in ${song.practice.intervalDays}d`);+ res.json(song);+}));+// =============================================================================// ATTACHMENTS// =============================================================================diff --git a/server/routes/brainSongbook.test.js b/server/routes/brainSongbook.test.jsindex ae8a6c3c29..9c9aeb07bb 100644--- a/server/routes/brainSongbook.test.js+++ b/server/routes/brainSongbook.test.js@@ -251,6 +251,89 @@ describe('Brain SongBook routes', () => {});});+ // ===========================================================================+ // PRACTICE (#4102)+ // ===========================================================================++ describe('POST /api/brain/songbook/:id/practice', () => {+ it('persists a schedule + stage advance computed from the FRESH record', async () => {+ const seen = mockUpdateWith(baseSong({ stage: 'learning' }));+ const res = await request(app)+ .post(`/api/brain/songbook/${SONG_ID}/practice`)+ .send({ quality: 5 });++ expect(res.status).toBe(200);+ expect(brainStorage.updateWith).toHaveBeenCalledWith('songs', SONG_ID, expect.any(Function));+ // Only stage + practice are written — a practice log must not touch the sheet.+ expect(Object.keys(seen.updates).sort()).toEqual(['practice', 'stage']);+ expect(seen.updates.stage).toBe('learned');+ expect(seen.updates.practice).toMatchObject({ intervalDays: 1, sessions: 1, lastQuality: 5 });+ expect(res.body.stage).toBe('learned');+ expect(res.body.practice.nextReview).toEqual(expect.any(String));+ // The rest of the record survives the merge.+ expect(res.body.content).toEqual({ format: 'tab', text: 'e|--0--|' });+ });++ it('resurfaces the song and regresses the stage on a failed run', async () => {+ const seen = mockUpdateWith(baseSong({+ stage: 'memorized',+ practice: {+ ease: 2.5, intervalDays: 30, nextReview: '2026-08-01T00:00:00.000Z',+ lastReviewed: '2026-07-02T00:00:00.000Z', sessions: 3,+ },+ }));+ const res = await request(app)+ .post(`/api/brain/songbook/${SONG_ID}/practice`)+ .send({ quality: 0 });++ expect(res.status).toBe(200);+ expect(seen.updates.stage).toBe('learned');+ expect(seen.updates.practice.intervalDays).toBe(0);+ expect(seen.updates.practice.sessions).toBe(4);+ });++ it('schedules a song that predates the feature without a backfill', async () => {+ const seen = mockUpdateWith(baseSong()); // no `practice` key at all+ const res = await request(app)+ .post(`/api/brain/songbook/${SONG_ID}/practice`)+ .send({ quality: 4 });++ expect(res.status).toBe(200);+ expect(seen.updates.practice).toMatchObject({ intervalDays: 1, sessions: 1 });+ expect(seen.updates.stage).toBe('learning');+ });++ it('400s on a grade outside 0..5 or a non-integer', async () => {+ mockUpdateWith(baseSong());+ for (const quality of [6, -1, 2.5, 'good']) {+ const res = await request(app)+ .post(`/api/brain/songbook/${SONG_ID}/practice`)+ .send({ quality });+ expect(res.status).toBe(400);+ }+ expect(brainStorage.updateWith).not.toHaveBeenCalled();+ });++ it('ignores a client-supplied practice object — the schedule is server-managed', async () => {+ const seen = mockUpdateWith(baseSong({ stage: 'learning' }));+ const res = await request(app)+ .post(`/api/brain/songbook/${SONG_ID}/practice`)+ .send({ quality: 5, practice: { ease: 99, intervalDays: 9999, nextReview: '2099-01-01T00:00:00.000Z' } });++ expect(res.status).toBe(200);+ expect(seen.updates.practice.intervalDays).toBe(1);+ expect(seen.updates.practice.ease).toBeLessThanOrEqual(5);+ });++ it('404s when the song vanished mid-request', async () => {+ mockUpdateWith(null);+ const res = await request(app)+ .post(`/api/brain/songbook/${SONG_ID}/practice`)+ .send({ quality: 3 });+ expect(res.status).toBe(404);+ });+ });+// ===========================================================================// IMPORT// ===========================================================================diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.jsindex e63f710724..fdcc659130 100644--- a/server/services/meatspacePostMemory.js+++ b/server/services/meatspacePostMemory.js@@ -11,6 +11,14 @@ import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.jsimport { shuffle } from '../lib/arrayUtils.js';import { isMemoryItemEnabled } from '../lib/postTopics.js';import { userLocalToday } from '../lib/timezone.js';+import {+ DEFAULT_EASE,+ advanceSchedule,+ defaultSchedule,+ isScheduleDue,+ mergeScheduleAdvance,+ scheduleOrDefault,+} from '../lib/spacedRepetition.js';const MEATSPACE_DIR = PATHS.meatspace;const MEMORY_ITEMS_FILE = join(MEATSPACE_DIR, 'post-memory-items.json');@@ -27,8 +35,13 @@ const TRAINING_LOG_FILE = join(MEATSPACE_DIR, 'post-training-log.json');// 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.+//+// The scheduling MATH itself now lives in `lib/spacedRepetition.js`, shared with+// SongBook repertoire practice (#4102). It is re-exported here so the existing+// callers and tests of this service keep their import site.++export { DEFAULT_EASE, advanceSchedule, defaultSchedule, mergeScheduleAdvance };-export const DEFAULT_EASE = 2.5;// =============================================================================// WINDOWED (DECAY-AWARE) MASTERY// =============================================================================@@ -48,6 +61,8 @@ export const MASTERY_TARGET_ACCURACY = 0.8;export const SPOT_CHECK_MIN_DAYS = 30;export const SPOT_CHECK_MAX_DAYS = 90;+const DAY_MS = 24 * 60 * 60 * 1000;+/** Push a per-attempt correctness flag onto a mastery stat's rolling window. */function pushRecent(stat, correct) {if (!Array.isArray(stat.recent)) stat.recent = [];@@ -100,96 +115,16 @@ export function scheduleSpotCheckAt(now = new Date(), random = Math.random) {return new Date(now.getTime() + days * DAY_MS).toISOString();}-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-// ease past 5 and a later round-trip through POST/PUT (import / out-of-band-// reschedule) would 400 on the server's own value. Keep the two in sync.-const MAX_EASE = 5;-// Cap the interval at a year so a long run of perfect reviews can't grow it-// without bound — an astronomically large `intervalDays` would overflow-// `new Date(now + intervalDays*DAY_MS)` into an Invalid Date and throw. A yearly-// review floor is a conventional SRS ceiling and keeps items resurfacing.-const MAX_INTERVAL_DAYS = 365;-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());- }+ item.schedule = scheduleOrDefault(item);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.min(MAX_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));- intervalDays = Math.min(MAX_INTERVAL_DAYS, intervalDays);- }-- const nextReview = new Date(now.getTime() + intervalDays * DAY_MS).toISOString();- return { ease, intervalDays, nextReview, lastReviewed: nowIso };-}--/**- * Merge a freshly-advanced schedule against the item's prior schedule, gating- * interval GROWTH to once per review day.- *- * Why: a "review" of a memory item is one pass through it, but the existing- * spaced-practice flow (`MemoryPractice.advanceSpaced`) submits once PER CHUNK.- * Advancing on every submission would compound a multi-chunk item's interval in- * a single sitting (0→1→6→16d) and drop it off the due list far longer than one- * completed review warrants. So a same-day continuation only refreshes ease and- * `lastReviewed` — it keeps the interval/nextReview already set earlier today.- * A miss (interval shrinks to 0) always applies, so a fumbled chunk still- * resurfaces the item immediately regardless of earlier same-day success.- */-export function mergeScheduleAdvance(prev, advanced, now = new Date()) {- const prevInterval = typeof prev?.intervalDays === 'number' ? prev.intervalDays : 0;- const lastReviewedMs = Date.parse(prev?.lastReviewed ?? '');- const sameReviewDay = Number.isFinite(lastReviewedMs)- && new Date(lastReviewedMs).toISOString().slice(0, 10) === now.toISOString().slice(0, 10);- // Suppress compounding only when this is a same-day continuation AND the- // interval would grow. Any shrink (a miss reset) always applies.- if (sameReviewDay && advanced.intervalDays > prevInterval) {- return { ...prev, ease: advanced.ease, lastReviewed: advanced.lastReviewed };- }- return advanced;-}-function ensureMastery(item) {if (!item.mastery || typeof item.mastery !== 'object') {item.mastery = { overallPct: 0, chunks: {}, elements: {}, retention: { status: 'learning' } };@@ -289,10 +224,7 @@ export function isMemoryItemDue(item, now = new Date()) {if (['attested', 'mastered'].includes(retention?.status)) {return isMemorySpotCheckDue(item, now);}- const nr = item?.schedule?.nextReview;- if (typeof nr !== 'string') return true;- const t = Date.parse(nr);- return Number.isNaN(t) || t <= now.getTime();+ return isScheduleDue(item?.schedule, now);}// =============================================================================