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(post): make mastery durable

[._.]/ Adam Eivy5a0c6cc3e521
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3af0c61dbc..281ce51b54 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -70,7 +70,8 @@
## POST
-- **Elements mastery now tells accuracy and mastery apart.** A single correct flash card can show 100% accuracy while remaining in Learning until it meets the existing mastery gate of three recent checks at 80% or better. The summary count, periodic-table colors, hover tooltip, and selected-element details now all use the same decay-aware rule.
+- **Mastery can now become permanent instead of decaying forever.** Facts stay mastered after three successful checks, broader skill reviews leave the schedule after three consecutive passes, and a user who already knows a memory item can attest that mastery now and verify it with one randomized future spot check; only a failed spot check returns the material to daily training.
+- **Elements mastery now tells accuracy and mastery apart.** A single correct flash card can show 100% accuracy while remaining in Learning until it meets the mastery gate of three checks at 80% or better. The summary count, periodic-table colors, hover tooltip, and selected-element details all use that same rule, while facts that clear it now stay mastered.
- **Finishing a lesson now keeps the daily brain-training routine moving.** Memory lessons, scored POST assessments, standalone Wordplay rounds, and Morse practice now end with an explicit choice to save/finish for now or save and continue. Continue asks the existing recommendation engine for the next scheduled activity and opens it directly even when the routine crosses from memory into math, cognitive training, wordplay, or Morse. The Memory Builder's own "Review Next" button also starts the due practice mode instead of reopening the item's mode menu.
- **The session launcher can show which AI provider a run will use again.** The launcher read the provider list as if the server returned a bare array, but it returns an object wrapping one. The mismatch threw on every mount, was swallowed into a console warning, and left the list permanently empty — so the Wit & Memory panel never showed the provider a drill was about to use unless one had been pinned explicitly.
- **[issue-3253] Powers practice now teaches a fast mental path before raising the difficulty.** New sessions begin with recall-friendly powers of two, unlock named techniques through speed-and-accuracy mastery, never generate a pair without a documented method, and show the worked steps after a miss and in session review. Manual base and exponent controls remain available when Progressive is switched off.
diff --git a/client/src/components/meatspace/post/ElementsSong.jsx b/client/src/components/meatspace/post/ElementsSong.jsx
index 3039a6fe7e..129b1f677f 100644
--- a/client/src/components/meatspace/post/ElementsSong.jsx
+++ b/client/src/components/meatspace/post/ElementsSong.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
-import { ChevronLeft, ChevronRight, BookOpen, Zap, Target, Check, X, SkipForward, Loader, Search, Eye, BarChart3, Gauge, Layers, RotateCw } from 'lucide-react';
-import { submitMemoryPractice, getMemoryMastery, getMemoryItem } from '../../../services/api';
+import { ChevronLeft, ChevronRight, BookOpen, Zap, Target, Check, X, SkipForward, Loader, Search, Eye, BarChart3, Gauge, Layers, RotateCw, ShieldCheck } from 'lucide-react';
+import { submitMemoryPractice, getMemoryMastery, getMemoryItem, attestMemoryMastery } from '../../../services/api';
import { RapidReaderModal } from '../../RapidReader';
import { clickableProps } from '../../../lib/a11yKeyboard';
import PostCompletionActions from './PostCompletionActions';
@@ -83,6 +83,12 @@ export default function ElementsSong({ item: itemProp, onBack, loadItemOnMount,
else onExitMode();
}
+ async function handleAttestMastery() {
+ const result = await attestMemoryMastery(item.id, { silent: true });
+ if (result?.mastery) setMastery(result.mastery);
+ return result;
+ }
+
if (!item) {
return (
<div className="flex flex-col items-center justify-center h-64 gap-3">
@@ -97,7 +103,7 @@ export default function ElementsSong({ item: itemProp, onBack, loadItemOnMount,
if (mode === 'element-flash') return <ElementFlashMode item={item} mastery={mastery} onBack={onExitMode} onComplete={handlePracticeComplete} />;
if (mode === 'fill-blank') return <FillBlankMode item={item} onBack={onExitMode} onComplete={handlePracticeComplete} />;
- return <ElementsSongMain item={item} mastery={mastery} onSelectMode={onSelectMode} onBack={onBack} />;
+ return <ElementsSongMain item={item} mastery={mastery} onSelectMode={onSelectMode} onBack={onBack} onAttestMastery={handleAttestMastery} />;
}
// Sum `{ attempts, correct }` mastery buckets into a single accuracy in [0,1].
@@ -106,7 +112,12 @@ export default function ElementsSong({ item: itemProp, onBack, loadItemOnMount,
// CLAUDE.md) — the caller routes those two to different modes.
function bucketAccuracy(buckets) {
const attempted = Object.values(buckets || {})
- .map(elementMasteryProgress)
+ .map(stat => {
+ const progress = elementMasteryProgress(stat);
+ return progress.mastered && progress.attempts === 0
+ ? { ...progress, attempts: 1, correct: 1, accuracy: 1 }
+ : progress;
+ })
.filter(progress => progress.attempts > 0);
if (attempted.length === 0) return null;
const attempts = attempted.reduce((sum, progress) => sum + progress.attempts, 0);
@@ -134,8 +145,8 @@ export function elementMasteryProgress(stat) {
attempts,
correct,
hasRecent,
- mastered: attempts >= ELEMENT_MASTERY_MIN_ATTEMPTS
- && accuracy >= ELEMENT_MASTERY_TARGET_ACCURACY,
+ mastered: typeof stat?.masteredAt === 'string' || (attempts >= ELEMENT_MASTERY_MIN_ATTEMPTS
+ && accuracy >= ELEMENT_MASTERY_TARGET_ACCURACY),
};
}
@@ -149,6 +160,7 @@ export function elementMasteryProgress(stat) {
* - everything solid → Element Flash as maintenance
*/
export function recommendedElementsMode(mastery) {
+ if (mastery?.retention?.status === 'attested' || mastery?.retention?.status === 'mastered') return null;
const elementAccuracy = bucketAccuracy(mastery?.elements);
if (elementAccuracy === null) return 'element-study';
if (elementAccuracy < 0.8) return 'element-flash';
@@ -157,7 +169,7 @@ export function recommendedElementsMode(mastery) {
return 'element-flash';
}
-function ElementsSongMain({ item, mastery, onSelectMode, onBack }) {
+function ElementsSongMain({ item, mastery, onSelectMode, onBack, onAttestMastery }) {
const recommendedMode = recommendedElementsMode(mastery);
const elementMap = useMemo(() => item.content?.elementMap ?? {}, [item]);
const masteredElementCount = Object.keys(elementMap)
@@ -180,6 +192,19 @@ function ElementsSongMain({ item, mastery, onSelectMode, onBack }) {
// Per-verse expand overrides ({ [chunkId]: bool }). Absent → falls back to
// isHighlighted so selecting an element still auto-opens its verses.
const [openVerses, setOpenVerses] = useState({});
+ const [attestConfirming, setAttestConfirming] = useState(false);
+ const [attesting, setAttesting] = useState(false);
+ const [attestError, setAttestError] = useState('');
+ const retention = mastery.retention || { status: 'learning' };
+
+ async function confirmAttestation() {
+ setAttesting(true);
+ setAttestError('');
+ const result = await onAttestMastery().catch(() => null);
+ setAttesting(false);
+ if (result) setAttestConfirming(false);
+ else setAttestError('Could not save mastery. Please try again.');
+ }
const songText = useMemo(
() => (item.content?.lines || []).map(l => l.text).join(' '),
@@ -231,10 +256,45 @@ function ElementsSongMain({ item, mastery, onSelectMode, onBack }) {
<div className="text-left sm:text-right text-sm text-gray-500">
<div>{masteredElementCount} / {Object.keys(elementMap).length} elements mastered</div>
<div>{Object.keys(elementMap).length} elements in song</div>
- <div className="text-xs text-gray-600">Mastery requires 3 recent checks at 80%+ accuracy</div>
+ <div className="text-xs text-gray-600">Mastery becomes durable after 3 checks at 80%+ accuracy</div>
</div>
</div>
+ <div className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
+ <div className="flex items-start gap-3">
+ <ShieldCheck size={20} className={retention.status === 'lapsed' ? 'text-amber-400' : 'text-emerald-400'} />
+ <div>
+ <div className="text-white text-sm font-medium">
+ {retention.status === 'attested' && 'Mastery attested'}
+ {retention.status === 'mastered' && (retention.spotCheckCompletedAt ? 'Mastery verified permanently' : 'Mastery verified')}
+ {retention.status === 'lapsed' && 'Review resumed'}
+ {retention.status === 'learning' && 'Still learning'}
+ </div>
+ <div className="text-xs text-gray-500 mt-0.5">
+ {retention.status === 'attested' && 'Removed from routine practice; one surprise spot check will verify it.'}
+ {retention.status === 'mastered' && (retention.spotCheckCompletedAt ? 'No more time decay or scheduled reviews.' : 'One future spot check remains; ordinary misses will not erase mastery.')}
+ {retention.status === 'lapsed' && 'A spot check showed a weak area, so this item is back in the routine.'}
+ {retention.status === 'learning' && 'Already know every element? You can attest now and verify it once later.'}
+ </div>
+ </div>
+ </div>
+ {retention.status === 'learning' && (
+ attestConfirming ? (
+ <div className="flex items-center gap-2">
+ <button onClick={() => setAttestConfirming(false)} disabled={attesting} className="min-h-11 px-3 text-sm text-gray-400 hover:text-white">Cancel</button>
+ <button onClick={confirmAttestation} disabled={attesting} className="min-h-11 px-3 text-sm bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white rounded-lg">
+ {attesting ? 'Saving...' : 'Yes, I know these'}
+ </button>
+ </div>
+ ) : (
+ <button onClick={() => setAttestConfirming(true)} className="shrink-0 min-h-11 px-3 text-sm border border-emerald-500/40 text-emerald-400 hover:bg-emerald-500/10 rounded-lg">
+ I already know this
+ </button>
+ )
+ )}
+ {attestError && <div role="alert" className="text-xs text-port-error">{attestError}</div>}
+ </div>
+
{/* Practice Modes — above the periodic table so the page leads with what
to DO, not what to look at (issue #3249). The recommended mode carries a
"Start here" hint so the five options aren't an undirected menu. */}
diff --git a/client/src/components/meatspace/post/ElementsSong.test.jsx b/client/src/components/meatspace/post/ElementsSong.test.jsx
index 2873fbc95d..264a151f33 100644
--- a/client/src/components/meatspace/post/ElementsSong.test.jsx
+++ b/client/src/components/meatspace/post/ElementsSong.test.jsx
@@ -10,11 +10,15 @@ import ElementsSong, { elementMasteryProgress, recommendedElementsMode } from '.
// deck submits `mode: 'element-study'` with element-tagged results.
const submitMemoryPractice = vi.fn(() => Promise.resolve({ mastery: { overallPct: 10, chunks: {}, elements: {} } }));
+const attestMemoryMastery = vi.fn(() => Promise.resolve({
+ mastery: { overallPct: 100, chunks: {}, elements: {}, retention: { status: 'attested', spotCheckAt: '2026-09-01T00:00:00.000Z' } },
+}));
vi.mock('../../../services/api', () => ({
submitMemoryPractice: (...args) => submitMemoryPractice(...args),
getMemoryMastery: () => Promise.resolve(null),
getMemoryItem: () => Promise.resolve(null),
+ attestMemoryMastery: (...args) => attestMemoryMastery(...args),
}));
// The RapidReader modal pulls in browser-only APIs; the study flow never opens
@@ -52,7 +56,10 @@ function RoutedElementsSong(props) {
);
}
-beforeEach(() => submitMemoryPractice.mockClear());
+beforeEach(() => {
+ submitMemoryPractice.mockClear();
+ attestMemoryMastery.mockClear();
+});
describe('ElementsSong — Flash Cards study mode', () => {
it('offers a Flash Cards study mode alongside the recall test', async () => {
@@ -168,7 +175,7 @@ describe('ElementsSong mastery display', () => {
await settle();
expect(screen.getByText('0 / 2 elements mastered')).toBeInTheDocument();
- expect(screen.getByText('Mastery requires 3 recent checks at 80%+ accuracy')).toBeInTheDocument();
+ expect(screen.getByText('Mastery becomes durable after 3 checks at 80%+ accuracy')).toBeInTheDocument();
fireEvent.mouseEnter(screen.getByText('H'));
expect(screen.getAllByText('Learning')).toHaveLength(2); // legend + tooltip status
@@ -176,6 +183,18 @@ describe('ElementsSong mastery display', () => {
expect(screen.getByText('(1/1 recent)')).toBeInTheDocument();
});
+ it('offers an explicit attestation and explains its one future spot check', async () => {
+ render(<ElementsSong item={item} mode={null} onSelectMode={() => {}} onExitMode={() => {}} onBack={() => {}} />);
+ await settle();
+ fireEvent.click(screen.getByRole('button', { name: 'I already know this' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Yes, I know these' }));
+ await settle();
+ expect(attestMemoryMastery).toHaveBeenCalledWith('elements-song', { silent: true });
+ expect(screen.getByText('Mastery attested')).toBeInTheDocument();
+ expect(screen.getByText('Removed from routine practice; one surprise spot check will verify it.')).toBeInTheDocument();
+ expect(screen.queryByText('Start here')).not.toBeInTheDocument();
+ });
+
it('uses recent answers for the same decay-aware mastery gate as the server', () => {
expect(elementMasteryProgress({ attempts: 10, correct: 10, recent: [0, 0, 0] })).toEqual({
accuracy: 0,
@@ -223,6 +242,11 @@ describe('recommendedElementsMode', () => {
chunks: { v1: { attempts: 10, correct: 9 } },
})).toBe('element-flash');
});
+
+ it('does not recommend routine practice while mastery awaits or has passed its spot check', () => {
+ expect(recommendedElementsMode({ retention: { status: 'attested' }, elements: {}, chunks: {} })).toBeNull();
+ expect(recommendedElementsMode({ retention: { status: 'mastered' }, elements: {}, chunks: {} })).toBeNull();
+ });
});
describe('ElementsSong — Element Flash recall test', () => {
diff --git a/client/src/components/meatspace/post/MemoryBuilder.jsx b/client/src/components/meatspace/post/MemoryBuilder.jsx
index e10474e670..017bea6a81 100644
--- a/client/src/components/meatspace/post/MemoryBuilder.jsx
+++ b/client/src/components/meatspace/post/MemoryBuilder.jsx
@@ -17,6 +17,12 @@ const ITEM_TYPES = [
// 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 retention = item?.mastery?.retention;
+ if (retention?.status === 'attested' || retention?.status === 'mastered') {
+ if (retention.spotCheckCompletedAt) return false;
+ const spotCheckAt = Date.parse(retention.spotCheckAt ?? '');
+ return Number.isFinite(spotCheckAt) && spotCheckAt <= Date.now();
+ }
const nr = item?.schedule?.nextReview;
if (typeof nr !== 'string') return true;
const t = Date.parse(nr);
@@ -256,7 +262,7 @@ export default function MemoryBuilder({ onBack, onSelectItem, onReviewItem = onS
</div>
</div>
<div className="flex flex-col items-end gap-1 shrink-0">
- <MasteryBadge pct={item.mastery?.overallPct || 0} />
+ <MasteryBadge pct={item.mastery?.overallPct || 0} retention={item.mastery?.retention} />
{isItemDue(item) && (
<span className="flex items-center gap-1 text-[10px] uppercase tracking-wide text-emerald-400">
<CalendarClock size={10} />
@@ -342,7 +348,16 @@ function ItemIcon({ type, builtin }) {
}
}
-function MasteryBadge({ pct }) {
+function MasteryBadge({ pct, retention }) {
+ if (retention?.status === 'attested') {
+ return <div className="text-xs font-medium text-emerald-400">Attested</div>;
+ }
+ if (retention?.status === 'mastered') {
+ return <div className="text-xs font-medium text-port-success">Mastered</div>;
+ }
+ if (retention?.status === 'lapsed') {
+ return <div className="text-xs font-medium text-amber-400">Review resumed</div>;
+ }
const color = pct >= 80 ? 'text-port-success' : pct >= 40 ? 'text-port-warning' : 'text-gray-500';
return (
<div className={`text-sm font-mono font-medium ${color}`}>
diff --git a/client/src/components/meatspace/post/MemoryPractice.jsx b/client/src/components/meatspace/post/MemoryPractice.jsx
index 8b09bbcf54..92422a9408 100644
--- a/client/src/components/meatspace/post/MemoryPractice.jsx
+++ b/client/src/components/meatspace/post/MemoryPractice.jsx
@@ -1,6 +1,6 @@
import { useState, useRef, useEffect, useMemo } from 'react';
-import { ChevronLeft, Check, X, SkipForward, RotateCcw, Target, ChevronDown, Loader } from 'lucide-react';
-import { submitMemoryPractice, getChunkMastery, getMemoryItem } from '../../../services/api';
+import { ChevronLeft, Check, X, SkipForward, RotateCcw, Target, ChevronDown, Loader, ShieldCheck } from 'lucide-react';
+import { submitMemoryPractice, getChunkMastery, getMemoryItem, attestMemoryMastery } from '../../../services/api';
import PostCompletionActions from './PostCompletionActions';
import { startRetryableSave } from './completionSave';
@@ -27,22 +27,30 @@ export const MEMORY_PRACTICE_MODE_IDS = MODES.map(m => m.id);
export default function MemoryPractice({ itemId, item: seedItem, mode, onSelectMode, onExitMode, onBack, onContinue }) {
const [loadedItem, setLoadedItem] = useState(null);
const [notFound, setNotFound] = useState(false);
- const item = seedItem || loadedItem;
+ const item = loadedItem || seedItem;
useEffect(() => {
- if (seedItem || !itemId) return;
+ if (!itemId) return;
let cancelled = false;
setLoadedItem(null);
setNotFound(false);
getMemoryItem(itemId)
- .then(data => { if (!cancelled) { if (data) setLoadedItem(data); else setNotFound(true); } })
+ .then(data => { if (!cancelled) { if (data) setLoadedItem(data); else if (!seedItem) setNotFound(true); } })
.catch(err => {
console.warn(`⚠️ Failed to load memory item ${itemId}: ${err.message}`);
- if (!cancelled) setNotFound(true);
+ if (!cancelled && !seedItem) setNotFound(true);
});
return () => { cancelled = true; };
}, [itemId, seedItem]);
+ function handleMasteryChange(nextMastery, nextSchedule) {
+ setLoadedItem(current => ({
+ ...(current || seedItem),
+ mastery: nextMastery,
+ ...(nextSchedule ? { schedule: nextSchedule } : {}),
+ }));
+ }
+
if (notFound) {
return (
<div className="space-y-4 max-w-2xl">
@@ -82,6 +90,7 @@ export default function MemoryPractice({ itemId, item: seedItem, mode, onSelectM
onExitMode={onExitMode}
onBack={onBack}
onContinue={onContinue}
+ onMasteryChange={handleMasteryChange}
/>
);
}
@@ -89,7 +98,7 @@ export default function MemoryPractice({ itemId, item: seedItem, mode, onSelectM
// The practice runner itself. `mode` is URL-driven; PostTab keys this component
// on it, so every mode entry (and every return to the picker) mounts fresh —
// no manual per-run state reset is needed.
-function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, onContinue }) {
+function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, onContinue, onMasteryChange }) {
const [results, setResults] = useState([]);
const [currentIdx, setCurrentIdx] = useState(0);
const [answer, setAnswer] = useState('');
@@ -98,6 +107,18 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on
const [startTime] = useState(Date.now());
const inputRef = useRef(null);
const spacedSavesRef = useRef([]);
+ const [mastery, setMastery] = useState(item.mastery || { overallPct: 0, chunks: {}, elements: {}, retention: { status: 'learning' } });
+ const [attestConfirming, setAttestConfirming] = useState(false);
+ const [attesting, setAttesting] = useState(false);
+ const [attestError, setAttestError] = useState('');
+
+ // The route renders its seed immediately, then replaces it with the
+ // authoritative item from the server. Keep the runner's local display in
+ // step so a stale navigation seed cannot resurrect an attestation or other
+ // mastery change that was already persisted.
+ useEffect(() => {
+ setMastery(item.mastery || { overallPct: 0, chunks: {}, elements: {}, retention: { status: 'learning' } });
+ }, [item.id, item.mastery]);
// Spaced repetition state
const [chunkMastery, setChunkMastery] = useState(null);
@@ -106,6 +127,24 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on
const lines = item.content?.lines || [];
const chunks = item.content?.chunks || [];
+ const retention = mastery.retention || { status: 'learning' };
+ const spotCheckTime = Date.parse(retention.spotCheckAt ?? '');
+ const spotCheckDue = (retention.status === 'attested' || retention.status === 'mastered')
+ && !retention.spotCheckCompletedAt
+ && Number.isFinite(spotCheckTime)
+ && spotCheckTime <= Date.now();
+
+ async function confirmAttestation() {
+ setAttesting(true);
+ setAttestError('');
+ const result = await attestMemoryMastery(item.id, { silent: true }).catch(() => null);
+ setAttesting(false);
+ if (result?.mastery) {
+ setMastery(result.mastery);
+ onMasteryChange(result.mastery, result.schedule);
+ setAttestConfirming(false);
+ } else setAttestError('Could not save mastery. Please try again.');
+ }
const fillBlankLine = lines[currentIdx] || null;
const fillBlankText = fillBlankLine?.text || '';
const fillBlankWords = fillBlankText.split(/\s+/).filter(Boolean);
@@ -176,6 +215,41 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on
<p className="text-gray-400 text-sm">Choose a practice mode:</p>
+ <div className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
+ <div className="flex items-start gap-3">
+ <ShieldCheck size={20} className={retention.status === 'lapsed' ? 'text-amber-400' : 'text-emerald-400'} />
+ <div>
+ <div className="text-sm font-medium text-white">
+ {retention.status === 'attested' && 'Mastery attested'}
+ {retention.status === 'mastered' && (retention.spotCheckCompletedAt ? 'Mastery verified permanently' : 'Mastery verified')}
+ {retention.status === 'lapsed' && 'Review resumed'}
+ {retention.status === 'learning' && 'Still learning'}
+ </div>
+ <div className="text-xs text-gray-500 mt-0.5">
+ {retention.status === 'attested' && 'One future spot check will verify this permanently.'}
+ {retention.status === 'mastered' && (retention.spotCheckCompletedAt ? 'No more time decay or scheduled reviews.' : 'One future spot check remains.')}
+ {retention.status === 'lapsed' && 'A missed spot check returned this item to the routine.'}
+ {retention.status === 'learning' && 'Already know it? Attest now and verify it once later.'}
+ </div>
+ </div>
+ </div>
+ {retention.status === 'learning' && (
+ attestConfirming ? (
+ <div className="flex items-center gap-2">
+ <button onClick={() => setAttestConfirming(false)} disabled={attesting} className="min-h-11 px-3 text-sm text-gray-400 hover:text-white">Cancel</button>
+ <button onClick={confirmAttestation} disabled={attesting} className="min-h-11 px-3 text-sm bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white rounded-lg">
+ {attesting ? 'Saving...' : 'Yes, I know this'}
+ </button>
+ </div>
+ ) : (
+ <button onClick={() => setAttestConfirming(true)} className="shrink-0 min-h-11 px-3 text-sm border border-emerald-500/40 text-emerald-400 hover:bg-emerald-500/10 rounded-lg">
+ I already know this
+ </button>
+ )
+ )}
+ {attestError && <div role="alert" className="text-xs text-port-error">{attestError}</div>}
+ </div>
+
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{MODES.map(m => (
<button
@@ -194,7 +268,7 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on
{/* Chunk mastery overview */}
{chunks.length > 0 && (
- <ChunkMasteryOverview item={item} />
+ <ChunkMasteryOverview item={{ ...item, mastery }} />
)}
</div>
);
@@ -706,7 +780,9 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on
} else {
// Save practice for this chunk, move to next
const chunkResults = results.filter(r => r.chunkId === currentChunk.id);
- if (chunkResults.length > 0) {
+ // A due retention audit is scored over the WHOLE spaced run. Saving each
+ // chunk here would let the first chunk permanently pass/fail the item.
+ if (!spotCheckDue && chunkResults.length > 0) {
const payload = {
mode: 'sequence',
chunkId: currentChunk.id,
@@ -749,8 +825,22 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on
async function saveAndExit(continueDaily) {
// Spaced repetition persists each completed chunk as the user advances;
- // the completion action waits for those writes and retries failures.
- if (mode === 'spaced') await Promise.all(spacedSavesRef.current.map(save => save()));
+ // the completion action waits for those writes and retries failures. A due
+ // spot check instead submits one aggregate result at this explicit finish
+ // boundary so no individual chunk can decide the whole audit.
+ if (mode === 'spaced' && spotCheckDue) {
+ await submitMemoryPractice(item.id, {
+ mode: 'sequence',
+ chunkId: null,
+ results: results.map(result => ({
+ correct: result.correct,
+ expected: result.expected,
+ answered: result.answered,
+ chunkId: result.chunkId,
+ })),
+ totalMs: Date.now() - startTime,
+ });
+ } else if (mode === 'spaced') await Promise.all(spacedSavesRef.current.map(save => save()));
else await savePractice(mode, results);
if (continueDaily) onContinue();
else onBack();
@@ -811,7 +901,9 @@ function ChunkMasteryOverview({ item }) {
<div className="px-3 pb-3 space-y-1.5">
{chunks.map(chunk => {
const stats = item.mastery?.chunks?.[chunk.id];
- const accuracy = stats?.attempts > 0 ? Math.round((stats.correct / stats.attempts) * 100) : 0;
+ const accuracy = typeof stats?.masteredAt === 'string'
+ ? 100
+ : stats?.attempts > 0 ? Math.round((stats.correct / stats.attempts) * 100) : 0;
const barColor = accuracy >= 80 ? 'bg-port-success' : accuracy >= 40 ? 'bg-port-warning' : 'bg-gray-600';
return (
diff --git a/client/src/components/meatspace/post/MemoryPractice.test.jsx b/client/src/components/meatspace/post/MemoryPractice.test.jsx
index 167ecd3e8b..8607ca1171 100644
--- a/client/src/components/meatspace/post/MemoryPractice.test.jsx
+++ b/client/src/components/meatspace/post/MemoryPractice.test.jsx
@@ -9,21 +9,33 @@ import MemoryPractice, {
checkSpacedAnswer,
} from './MemoryPractice';
-const { submitMemoryPractice, getChunkMastery } = vi.hoisted(() => ({
+const { submitMemoryPractice, getChunkMastery, getMemoryItem, attestMemoryMastery } = vi.hoisted(() => ({
submitMemoryPractice: vi.fn(),
getChunkMastery: vi.fn(),
+ getMemoryItem: vi.fn(),
+ attestMemoryMastery: vi.fn(),
}));
vi.mock('../../../services/api', () => ({
submitMemoryPractice,
getChunkMastery,
- getMemoryItem: vi.fn(),
+ getMemoryItem,
+ attestMemoryMastery,
}));
beforeEach(() => {
vi.clearAllMocks();
submitMemoryPractice.mockResolvedValue({ mastery: {} });
getChunkMastery.mockResolvedValue([]);
+ getMemoryItem.mockResolvedValue(null);
+ attestMemoryMastery.mockResolvedValue({
+ mastery: {
+ overallPct: 100,
+ chunks: { 'example-chunk': { correct: 0, attempts: 0, masteredAt: '2026-08-01T00:00:00.000Z', masterySource: 'attested' } },
+ elements: {},
+ retention: { status: 'attested' },
+ },
+ });
});
// Pure-function tests for MemoryPractice's correctness scorers (issue #2102
@@ -195,6 +207,34 @@ describe('findChunkForLine', () => {
});
describe('MemoryPractice daily routine actions', () => {
+ it('allows a user to attest mastery and shows the future verification state', async () => {
+ const item = {
+ id: 'example-memory',
+ title: 'Example Memory',
+ content: {
+ lines: [{ text: 'An example line.' }],
+ chunks: [{ id: 'example-chunk', label: 'Example Chunk', lineRange: [0, 0] }],
+ },
+ mastery: { overallPct: 0, chunks: {}, elements: {}, retention: { status: 'learning' } },
+ };
+ const view = render(<MemoryPractice itemId={item.id} item={item} mode={null} onSelectMode={() => {}} onExitMode={() => {}} onBack={() => {}} />);
+ fireEvent.click(screen.getByRole('button', { name: 'I already know this' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Yes, I know this' }));
+ await waitFor(() => expect(attestMemoryMastery).toHaveBeenCalledWith('example-memory', { silent: true }));
+ expect(screen.getByText('Mastery attested')).toBeInTheDocument();
+ expect(screen.getByText('One future spot check will verify this permanently.')).toBeInTheDocument();
+ fireEvent.click(screen.getByText('Chunk Mastery'));
+ expect(screen.getByText('100%')).toBeInTheDocument();
+
+ const attestedMastery = (await attestMemoryMastery.mock.results[0].value).mastery;
+ const attestedItem = { ...item, mastery: attestedMastery };
+ getMemoryItem.mockResolvedValue(attestedItem);
+ view.unmount();
+ render(<MemoryPractice itemId={item.id} item={item} mode={null} onSelectMode={() => {}} onExitMode={() => {}} onBack={() => {}} />);
+ await waitFor(() => expect(screen.getByText('Mastery attested')).toBeInTheDocument());
+ expect(screen.queryByRole('button', { name: 'I already know this' })).not.toBeInTheDocument();
+ });
+
it('waits for progress to save before continuing from a completed lesson', async () => {
let resolveSave;
submitMemoryPractice.mockImplementation(() => new Promise(resolve => { resolveSave = resolve; }));
@@ -310,4 +350,49 @@ describe('MemoryPractice daily routine actions', () => {
await act(async () => resolveSave({ mastery: {} }));
await waitFor(() => expect(onContinue).toHaveBeenCalledTimes(1));
});
+
+ it('scores a due multi-chunk spot check only after the whole spaced run is finished', async () => {
+ getChunkMastery.mockResolvedValue([
+ { id: 'chunk-a', label: 'Chunk A', lineRange: [0, 0], accuracy: 100, hintLevel: 3 },
+ { id: 'chunk-b', label: 'Chunk B', lineRange: [1, 1], accuracy: 100, hintLevel: 3 },
+ ]);
+ const item = {
+ id: 'example-memory',
+ title: 'Example Memory',
+ content: {
+ lines: [{ text: 'First line.' }, { text: 'Second line.' }],
+ chunks: [
+ { id: 'chunk-a', label: 'Chunk A', lineRange: [0, 0] },
+ { id: 'chunk-b', label: 'Chunk B', lineRange: [1, 1] },
+ ],
+ },
+ mastery: {
+ overallPct: 100,
+ chunks: {},
+ elements: {},
+ retention: { status: 'mastered', spotCheckAt: '2000-01-01T00:00:00.000Z', spotCheckCompletedAt: null },
+ },
+ };
+
+ render(<MemoryPractice itemId={item.id} item={item} mode="spaced" onSelectMode={() => {}} onExitMode={() => {}} onBack={() => {}} onContinue={() => {}} />);
+
+ let input = await screen.findByPlaceholderText('Type the line...');
+ fireEvent.change(input, { target: { value: 'First line.' } });
+ fireEvent.click(screen.getByText('Check'));
+ fireEvent.click(screen.getByText('Next'));
+ await waitFor(() => expect(screen.getByText(/Chunk 2\/2/)).toBeInTheDocument());
+ expect(submitMemoryPractice).not.toHaveBeenCalled();
+
+ input = screen.getByPlaceholderText('Type the line...');
+ fireEvent.change(input, { target: { value: 'wrong' } });
+ fireEvent.click(screen.getByText('Check'));
+ fireEvent.click(screen.getByText('Next'));
+ expect(submitMemoryPractice).not.toHaveBeenCalled();
+
+ fireEvent.click(await screen.findByText('Save Progress'));
+ await waitFor(() => expect(submitMemoryPractice).toHaveBeenCalledTimes(1));
+ const payload = submitMemoryPractice.mock.calls[0][1];
+ expect(payload.results).toHaveLength(2);
+ expect(payload.results.map(result => result.chunkId)).toEqual(['chunk-a', 'chunk-b']);
+ });
});
diff --git a/client/src/components/meatspace/post/PostProgress.jsx b/client/src/components/meatspace/post/PostProgress.jsx
index 8db4b84f3f..d8ca22d1e2 100644
--- a/client/src/components/meatspace/post/PostProgress.jsx
+++ b/client/src/components/meatspace/post/PostProgress.jsx
@@ -352,11 +352,13 @@ const RETENTION_STATE_CLASS = {
fresh: 'bg-port-success/10 border-port-success/30 text-port-success',
due: 'bg-port-warning/10 border-port-warning/30 text-port-warning',
'needs-refresh': 'bg-port-error/10 border-port-error/30 text-port-error',
+ permanent: 'bg-emerald-500/10 border-emerald-500/30 text-emerald-300',
};
const RETENTION_STATE_LABEL = {
fresh: 'fresh',
due: 'due for review',
'needs-refresh': 'needs refresh',
+ permanent: 'mastered permanently',
};
function ProgressTabs({ subtab, navigate }) {
diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.js
index f15850a2d5..fccbb60c00 100644
--- a/client/src/services/apiMeatspace.js
+++ b/client/src/services/apiMeatspace.js
@@ -250,6 +250,11 @@ export const submitMemoryPractice = (id, data) => request(`/meatspace/post/memor
method: 'POST',
body: JSON.stringify(data)
});
+export const attestMemoryMastery = (id, options = {}) => request(`/meatspace/post/memory-items/${id}/attest-mastery`, {
+ method: 'POST',
+ body: JSON.stringify({ acknowledged: true }),
+ ...options
+});
export const getMemoryMastery = (id) => request(`/meatspace/post/memory-items/${id}/mastery`);
export const getChunkMastery = (id) => request(`/meatspace/post/memory-items/${id}/chunk-mastery`);
export const generateMemoryDrill = (data) => request('/meatspace/post/memory-drill', {
diff --git a/scripts/migrations/215-post-durable-memory-mastery.js b/scripts/migrations/215-post-durable-memory-mastery.js
new file mode 100644
index 0000000000..53269ef028
--- /dev/null
+++ b/scripts/migrations/215-post-durable-memory-mastery.js
@@ -0,0 +1,102 @@
+/**
+ * Persist durable POST memory mastery metadata.
+ *
+ * Existing stats that already clear the shipped 3-check / 80% gate are
+ * grandfathered as verified so an upgrade cannot erase mastery the user had
+ * already demonstrated. Every item also receives the additive retention state
+ * used by attestation and its one-time future spot check.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+const REL_PATH = 'data/meatspace/post-memory-items.json';
+const MIN_ATTEMPTS = 3;
+const TARGET_ACCURACY = 0.8;
+const SPOT_CHECK_DAYS = 60;
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+function clearsMasteryGate(stat) {
+ if (typeof stat?.masteredAt === 'string') return true;
+ const recent = Array.isArray(stat?.recent) && stat.recent.length ? stat.recent : null;
+ const attempts = recent ? recent.length : (Number.isFinite(stat?.attempts) ? stat.attempts : 0);
+ const correct = recent
+ ? recent.reduce((sum, result) => sum + (result ? 1 : 0), 0)
+ : (Number.isFinite(stat?.correct) ? stat.correct : 0);
+ return attempts >= MIN_ATTEMPTS && correct / attempts >= TARGET_ACCURACY;
+}
+
+function targetStats(item) {
+ if (item.id === 'elements-song' && item.content?.elementMap) {
+ return Object.keys(item.content.elementMap).map(symbol => item.mastery?.elements?.[symbol]);
+ }
+ return (item.content?.chunks || []).map(chunk => item.mastery?.chunks?.[chunk.id]);
+}
+
+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) return { updated: 0, reason: 'no-file' };
+
+ let data;
+ try {
+ data = JSON.parse(raw);
+ } catch {
+ return { updated: 0, reason: 'invalid-json' };
+ }
+ if (!Array.isArray(data?.items)) return { updated: 0, reason: 'no-items' };
+
+ const fallbackNow = new Date().toISOString();
+ let updated = 0;
+ for (const item of data.items) {
+ if (!item.mastery || typeof item.mastery !== 'object') continue;
+ let changed = false;
+ if (!item.mastery.retention || typeof item.mastery.retention !== 'object') {
+ item.mastery.retention = { status: 'learning' };
+ changed = true;
+ }
+ const masteredAt = item.updatedAt || item.createdAt || fallbackNow;
+ for (const bucketName of ['chunks', 'elements']) {
+ const bucket = item.mastery[bucketName];
+ if (!bucket || typeof bucket !== 'object') continue;
+ for (const stat of Object.values(bucket)) {
+ if (!stat?.masteredAt && clearsMasteryGate(stat)) {
+ stat.masteredAt = masteredAt;
+ stat.masterySource = 'verified';
+ changed = true;
+ }
+ }
+ }
+ const targets = targetStats(item);
+ if (item.mastery.retention.status === 'learning'
+ && targets.length > 0
+ && targets.every(clearsMasteryGate)) {
+ const spotCheckAt = new Date(Date.parse(fallbackNow) + SPOT_CHECK_DAYS * DAY_MS).toISOString();
+ item.mastery.retention = {
+ status: 'mastered',
+ masteredAt,
+ spotCheckAt,
+ spotCheckCompletedAt: null,
+ lapsedAt: null,
+ };
+ item.mastery.overallPct = 100;
+ item.schedule = {
+ ease: Number.isFinite(item.schedule?.ease) ? item.schedule.ease : 2.5,
+ intervalDays: SPOT_CHECK_DAYS,
+ nextReview: spotCheckAt,
+ lastReviewed: item.schedule?.lastReviewed ?? null,
+ };
+ changed = true;
+ }
+ if (changed) updated += 1;
+ }
+
+ if (!updated) return { updated: 0, reason: 'already-durable' };
+ await writeFile(itemsPath, `${JSON.stringify(data, null, 2)}\n`);
+ return { updated };
+ },
+};
diff --git a/scripts/migrations/215-post-durable-memory-mastery.test.js b/scripts/migrations/215-post-durable-memory-mastery.test.js
new file mode 100644
index 0000000000..51efc962a9
--- /dev/null
+++ b/scripts/migrations/215-post-durable-memory-mastery.test.js
@@ -0,0 +1,92 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './215-post-durable-memory-mastery.js';
+
+const readJson = path => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 215 — durable POST memory mastery', () => {
+ let rootDir;
+ let itemsPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-215-'));
+ mkdirSync(join(rootDir, 'data', 'meatspace'), { recursive: true });
+ itemsPath = join(rootDir, 'data', 'meatspace', 'post-memory-items.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('no-ops when the store does not exist', async () => {
+ expect(await migration.up({ rootDir })).toEqual({ updated: 0, reason: 'no-file' });
+ expect(existsSync(itemsPath)).toBe(false);
+ });
+
+ it('grandfathers stats that already clear the mastery gate', async () => {
+ writeFileSync(itemsPath, JSON.stringify({ items: [{
+ id: 'example',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ mastery: {
+ chunks: {
+ strong: { attempts: 3, correct: 3, recent: [1, 1, 1] },
+ weak: { attempts: 3, correct: 1, recent: [1, 0, 0] },
+ },
+ elements: {},
+ },
+ }] }));
+
+ expect(await migration.up({ rootDir })).toEqual({ updated: 1 });
+ const item = readJson(itemsPath).items[0];
+ expect(item.mastery.retention).toEqual({ status: 'learning' });
+ expect(item.mastery.chunks.strong).toMatchObject({
+ masteredAt: '2026-01-01T00:00:00.000Z',
+ masterySource: 'verified',
+ });
+ expect(item.mastery.chunks.weak.masteredAt).toBeUndefined();
+ });
+
+ it('is idempotent and preserves existing durable timestamps', async () => {
+ writeFileSync(itemsPath, JSON.stringify({ items: [{
+ id: 'example',
+ mastery: {
+ retention: { status: 'learning' },
+ chunks: { a: { attempts: 3, correct: 3, masteredAt: '2025-01-01T00:00:00.000Z', masterySource: 'verified' } },
+ elements: {},
+ },
+ }] }));
+ expect(await migration.up({ rootDir })).toEqual({ updated: 0, reason: 'already-durable' });
+ expect(readJson(itemsPath).items[0].mastery.chunks.a.masteredAt).toBe('2025-01-01T00:00:00.000Z');
+ });
+
+ it('moves a fully mastered legacy item out of routine review and schedules one audit', async () => {
+ writeFileSync(itemsPath, JSON.stringify({ items: [{
+ id: 'example',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ content: { chunks: [{ id: 'a' }, { id: 'b' }] },
+ mastery: {
+ overallPct: 100,
+ chunks: {
+ a: { attempts: 3, correct: 3, recent: [1, 1, 1] },
+ b: { attempts: 5, correct: 4, recent: [1, 1, 1, 1, 0] },
+ },
+ elements: {},
+ },
+ schedule: { ease: 2.7, intervalDays: 0, nextReview: '2026-01-01T00:00:00.000Z', lastReviewed: null },
+ }] }));
+
+ const before = Date.now();
+ expect(await migration.up({ rootDir })).toEqual({ updated: 1 });
+ const after = Date.now();
+ const item = readJson(itemsPath).items[0];
+ expect(item.mastery.retention).toMatchObject({
+ status: 'mastered',
+ masteredAt: '2026-01-01T00:00:00.000Z',
+ spotCheckCompletedAt: null,
+ });
+ const spotCheckMs = Date.parse(item.mastery.retention.spotCheckAt);
+ expect(spotCheckMs).toBeGreaterThanOrEqual(before + 60 * 86400000);
+ expect(spotCheckMs).toBeLessThanOrEqual(after + 60 * 86400000);
+ expect(item.schedule).toMatchObject({ ease: 2.7, intervalDays: 60, nextReview: item.mastery.retention.spotCheckAt });
+ });
+});
diff --git a/scripts/migrations/216-post-review-verification-passes.js b/scripts/migrations/216-post-review-verification-passes.js
new file mode 100644
index 0000000000..52148a71ea
--- /dev/null
+++ b/scripts/migrations/216-post-review-verification-passes.js
@@ -0,0 +1,36 @@
+/** Backfill the consecutive-pass counter used to end skill review schedules. */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+const REL_PATH = 'data/meatspace/post-review-schedule.json';
+
+export default {
+ async up({ rootDir }) {
+ const schedulePath = join(rootDir, REL_PATH);
+ const raw = await readFile(schedulePath, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return { updated: 0, reason: 'no-file' };
+
+ let data;
+ try {
+ data = JSON.parse(raw);
+ } catch {
+ return { updated: 0, reason: 'invalid-json' };
+ }
+ if (!data?.skills || typeof data.skills !== 'object') return { updated: 0, reason: 'no-skills' };
+
+ let updated = 0;
+ for (const entry of Object.values(data.skills)) {
+ if (Number.isInteger(entry?.verificationPasses) && entry.verificationPasses >= 0) continue;
+ entry.verificationPasses = 0;
+ updated += 1;
+ }
+ if (!updated) return { updated: 0, reason: 'already-counted' };
+
+ await writeFile(schedulePath, `${JSON.stringify(data, null, 2)}\n`);
+ return { updated };
+ },
+};
diff --git a/scripts/migrations/216-post-review-verification-passes.test.js b/scripts/migrations/216-post-review-verification-passes.test.js
new file mode 100644
index 0000000000..18848b6344
--- /dev/null
+++ b/scripts/migrations/216-post-review-verification-passes.test.js
@@ -0,0 +1,34 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './216-post-review-verification-passes.js';
+
+describe('migration 216 — review verification passes', () => {
+ let rootDir;
+ let schedulePath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-216-'));
+ mkdirSync(join(rootDir, 'data', 'meatspace'), { recursive: true });
+ schedulePath = join(rootDir, 'data', 'meatspace', 'post-review-schedule.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('starts legacy review entries at zero consecutive verification passes', async () => {
+ writeFileSync(schedulePath, JSON.stringify({ skills: {
+ a: { skillId: 'a', reviewsPassed: 2 },
+ b: { skillId: 'b', verificationPasses: 1 },
+ } }));
+ expect(await migration.up({ rootDir })).toEqual({ updated: 1 });
+ const skills = JSON.parse(readFileSync(schedulePath, 'utf-8')).skills;
+ expect(skills.a.verificationPasses).toBe(0);
+ expect(skills.b.verificationPasses).toBe(1);
+ expect(await migration.up({ rootDir })).toEqual({ updated: 0, reason: 'already-counted' });
+ });
+
+ it('no-ops when the review store is absent', async () => {
+ expect(await migration.up({ rootDir })).toEqual({ updated: 0, reason: 'no-file' });
+ });
+});
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index 3f4094bce6..9a968e03ca 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -369,11 +369,25 @@ export const memoryItemUpdateSchema = z.object({
correct: z.number().int().min(0),
attempts: z.number().int().min(0),
lastPracticed: z.string().nullable().optional(),
+ recent: z.array(z.union([z.literal(0), z.literal(1)])).max(10).optional(),
+ masteredAt: z.string().optional(),
+ masterySource: z.enum(['verified', 'attested']).optional(),
})).optional(),
elements: z.record(z.object({
correct: z.number().int().min(0),
attempts: z.number().int().min(0),
+ recent: z.array(z.union([z.literal(0), z.literal(1)])).max(10).optional(),
+ masteredAt: z.string().optional(),
+ masterySource: z.enum(['verified', 'attested']).optional(),
})).optional(),
+ retention: z.object({
+ status: z.enum(['learning', 'attested', 'mastered', 'lapsed']),
+ attestedAt: z.string().nullable().optional(),
+ masteredAt: z.string().nullable().optional(),
+ spotCheckAt: z.string().nullable().optional(),
+ spotCheckCompletedAt: z.string().nullable().optional(),
+ lapsedAt: z.string().nullable().optional(),
+ }).optional(),
}).optional(),
});
@@ -383,6 +397,7 @@ const practiceResultSchema = z.object({
element: z.string().nullable().optional(),
expected: z.string().optional(),
answered: z.string().optional(),
+ chunkId: z.string().optional(),
});
export const memoryPracticeSchema = z.object({
@@ -395,6 +410,10 @@ export const memoryPracticeSchema = z.object({
totalMs: z.number().min(0).optional(),
});
+export const memoryMasteryAttestationSchema = z.object({
+ acknowledged: z.literal(true),
+});
+
export const memoryDrillRequestSchema = z.object({
mode: z.enum(['fill-blank', 'sequence', 'element-flash']).optional().default('fill-blank'),
memoryItemId: z.string().optional(),
diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.js
index eb29130f46..d80588972b 100644
--- a/server/routes/meatspacePostRoutes.js
+++ b/server/routes/meatspacePostRoutes.js
@@ -17,6 +17,7 @@ import {
memoryItemCreateSchema,
memoryItemUpdateSchema,
memoryPracticeSchema,
+ memoryMasteryAttestationSchema,
memoryDrillRequestSchema,
morseRoundSchema,
morseLevelUpdateSchema,
@@ -434,6 +435,17 @@ router.post('/post/memory-items/:id/practice', asyncHandler(async (req, res) =>
res.json(result);
}));
+/**
+ * POST /api/meatspace/post/memory-items/:id/attest-mastery
+ * Provisionally accept user-attested mastery and schedule one future audit.
+ */
+router.post('/post/memory-items/:id/attest-mastery', asyncHandler(async (req, res) => {
+ validateRequest(memoryMasteryAttestationSchema, req.body);
+ const result = await memoryService.attestMemoryItemMastery(req.params.id);
+ if (!result) throw new ServerError('Memory item not found or has no practice targets', { status: 404, code: 'NOT_FOUND' });
+ res.json(result);
+}));
+
/**
* GET /api/meatspace/post/memory-items/:id/mastery
* Get mastery breakdown for a memory item
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index 1bf809f77a..32b0b9851c 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -28,7 +28,7 @@ import {
COGNITIVE_MASTERY_DEFAULTS,
} from '../lib/postProgression.js';
import { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } from './meatspacePostCognitive.js';
-import { applySessionToMemoryItems, getMemoryItems, getDueMemoryItems, isStatMastered, MASTERY_TARGET_ACCURACY } from './meatspacePostMemory.js';
+import { applySessionToMemoryItems, getMemoryItems, getDueMemoryItems, MASTERY_TARGET_ACCURACY } from './meatspacePostMemory.js';
import { applySessionToReviewSchedule, getDueReviews, getRetentionReport } from './meatspacePostReview.js';
import { getAllTrainingEntries } from './meatspacePostTraining.js';
import { getMorseProgress, MAX_KOCH_LEVEL } from './meatspacePostMorse.js';
@@ -399,8 +399,9 @@ const MIN_REVIEW_COMPLETION = 0.75;
* Current mastered-but-inactive skills eligible for re-verification tracking:
* - multiplication / Powers rungs strictly BELOW the resolved current level
* (you've moved past them, so they're no longer actively drilled),
- * - cognitive rungs strictly below the current level, per laddered type,
- * - memory chunks whose windowed mastery clears the gate.
+ * - cognitive rungs strictly below the current level, per laddered type.
+ * Memory items own their durable-mastery + one-time spot-check lifecycle in
+ * meatspacePostMemory.js, so they are intentionally not duplicated here.
* Returns opaque skill descriptors the review scheduler upserts + schedules.
*/
export async function getMasteredSkills() {
@@ -454,25 +455,6 @@ export async function getMasteredSkills() {
}
}
- const memoryItems = await getMemoryItems();
- for (const item of memoryItems) {
- const chunkStats = item.mastery?.chunks || {};
- for (const chunk of item.content?.chunks || []) {
- const stat = chunkStats[chunk.id];
- if (stat && isStatMastered(stat)) {
- skills.push({
- skillId: `memory:${item.id}:${chunk.id}`,
- kind: 'memory',
- label: `${item.title} — ${chunk.label || chunk.id}`,
- drillType: 'memory-sequence',
- module: 'memory',
- memoryItemId: item.id,
- chunkId: chunk.id,
- });
- }
- }
- }
-
return skills;
}
diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.js
index cd21a37401..e63f710724 100644
--- a/server/services/meatspacePostMemory.js
+++ b/server/services/meatspacePostMemory.js
@@ -45,6 +45,8 @@ export const MASTERY_WINDOW = 10;
// Mastery gate: at least this many attempts (in the window) at ≥ this accuracy.
export const MASTERY_MIN_ATTEMPTS = 3;
export const MASTERY_TARGET_ACCURACY = 0.8;
+export const SPOT_CHECK_MIN_DAYS = 30;
+export const SPOT_CHECK_MAX_DAYS = 90;
/** Push a per-attempt correctness flag onto a mastery stat's rolling window. */
function pushRecent(stat, correct) {
@@ -75,10 +77,29 @@ export function windowedAccuracy(stat) {
/** True when a mastery stat clears the windowed gate (≥3 recent attempts, ≥0.8). */
export function isStatMastered(stat) {
+ if (typeof stat?.masteredAt === 'string') return true;
const { attempts, accuracy } = windowedAccuracy(stat);
return attempts >= MASTERY_MIN_ATTEMPTS && accuracy >= MASTERY_TARGET_ACCURACY;
}
+/** Freeze a fact once it has cleared the mastery gate. */
+function preserveStatMastery(stat, nowIso, source = 'verified') {
+ if (!stat.masteredAt && isStatMastered(stat)) {
+ stat.masteredAt = nowIso;
+ stat.masterySource = source;
+ }
+ return stat;
+}
+
+/** Randomized one-time retention audit, 30–90 days after mastery. */
+export function scheduleSpotCheckAt(now = new Date(), random = Math.random) {
+ const sample = random();
+ const clamped = Math.max(0, Math.min(0.999999, Number.isFinite(sample) ? sample : 0));
+ const days = SPOT_CHECK_MIN_DAYS
+ + Math.floor(clamped * (SPOT_CHECK_MAX_DAYS - SPOT_CHECK_MIN_DAYS + 1));
+ 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
@@ -169,8 +190,105 @@ export function mergeScheduleAdvance(prev, advanced, now = new Date()) {
return advanced;
}
-/** True when an item is due for review (no schedule / invalid date = due). */
+function ensureMastery(item) {
+ if (!item.mastery || typeof item.mastery !== 'object') {
+ item.mastery = { overallPct: 0, chunks: {}, elements: {}, retention: { status: 'learning' } };
+ }
+ if (!item.mastery.chunks || typeof item.mastery.chunks !== 'object') item.mastery.chunks = {};
+ if (!item.mastery.elements || typeof item.mastery.elements !== 'object') item.mastery.elements = {};
+ if (!item.mastery.retention || typeof item.mastery.retention !== 'object') {
+ item.mastery.retention = { status: 'learning' };
+ }
+ return item.mastery;
+}
+
+function targetMasteryEntries(item) {
+ ensureMastery(item);
+ if (item.id === 'elements-song' && item.content?.elementMap) {
+ return Object.keys(item.content.elementMap).map(key => [key, item.mastery.elements, item.mastery.elements[key]]);
+ }
+ return (item.content?.chunks || []).map(chunk => [chunk.id, item.mastery.chunks, item.mastery.chunks[chunk.id]]);
+}
+
+function isItemFullyMastered(item) {
+ const targets = targetMasteryEntries(item);
+ return targets.length > 0 && targets.every(([, , stat]) => isStatMastered(stat));
+}
+
+function setAuditSchedule(item, spotCheckAt, now = new Date()) {
+ ensureSchedule(item);
+ item.schedule = {
+ ...item.schedule,
+ intervalDays: Math.max(0, Math.round((Date.parse(spotCheckAt) - now.getTime()) / DAY_MS)),
+ nextReview: spotCheckAt,
+ };
+}
+
+function promoteCompletedMastery(item, now, random = Math.random) {
+ const mastery = ensureMastery(item);
+ const retention = mastery.retention;
+ if (!isItemFullyMastered(item) || ['attested', 'mastered'].includes(retention.status)) return false;
+ const nowIso = now.toISOString();
+ const spotCheckAt = scheduleSpotCheckAt(now, random);
+ mastery.retention = {
+ status: 'mastered',
+ masteredAt: nowIso,
+ spotCheckAt,
+ spotCheckCompletedAt: null,
+ lapsedAt: null,
+ };
+ setAuditSchedule(item, spotCheckAt, now);
+ return true;
+}
+
+export function isMemorySpotCheckDue(item, now = new Date()) {
+ const retention = item?.mastery?.retention;
+ if (!['attested', 'mastered'].includes(retention?.status) || retention.spotCheckCompletedAt) return false;
+ const dueAt = Date.parse(retention.spotCheckAt ?? '');
+ return Number.isFinite(dueAt) && dueAt <= now.getTime();
+}
+
+function completeSpotCheck(item, now) {
+ const retention = ensureMastery(item).retention;
+ const nowIso = now.toISOString();
+ item.mastery.retention = {
+ ...retention,
+ status: 'mastered',
+ masteredAt: retention.masteredAt || nowIso,
+ spotCheckCompletedAt: nowIso,
+ lapsedAt: null,
+ };
+ for (const [, , stat] of targetMasteryEntries(item)) {
+ if (!stat) continue;
+ stat.masteredAt ||= nowIso;
+ stat.masterySource = 'verified';
+ }
+}
+
+function resumeTrainingAfterFailedSpotCheck(item, now) {
+ const nowIso = now.toISOString();
+ for (const [, , stat] of targetMasteryEntries(item)) {
+ if (!stat) continue;
+ delete stat.masteredAt;
+ delete stat.masterySource;
+ stat.recent = [];
+ }
+ item.mastery.retention = {
+ status: 'lapsed',
+ masteredAt: null,
+ spotCheckAt: null,
+ spotCheckCompletedAt: null,
+ lapsedAt: nowIso,
+ };
+ item.schedule = defaultSchedule(nowIso);
+}
+
+/** True when an item is due for routine learning or its one-time spot check. */
export function isMemoryItemDue(item, now = new Date()) {
+ const retention = item?.mastery?.retention;
+ 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);
@@ -294,7 +412,7 @@ const ELEMENTS_SONG = {
Og: { name: "Oganesson", atomicNumber: 118 },
}
},
- mastery: { overallPct: 0, chunks: {}, elements: {} },
+ mastery: { overallPct: 0, chunks: {}, elements: {}, retention: { status: 'learning' } },
createdAt: '2026-03-08T00:00:00.000Z',
updatedAt: '2026-03-08T00:00:00.000Z',
};
@@ -323,7 +441,10 @@ async function loadMemoryItems() {
// 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);
+ for (const item of items) {
+ ensureSchedule(item);
+ ensureMastery(item);
+ }
return items;
}
@@ -382,7 +503,7 @@ export async function createMemoryItem(data) {
lines: contentLines,
chunks: remappedChunks,
},
- mastery: { overallPct: 0, chunks: {}, elements: {} },
+ mastery: { overallPct: 0, chunks: {}, elements: {}, retention: { status: 'learning' } },
// Honor a client-provided schedule (e.g. importing an item with progress),
// else stamp a fresh "due now" default.
schedule: data.schedule || defaultSchedule(now),
@@ -416,6 +537,7 @@ export async function updateMemoryItem(id, updates) {
if (updates.title) item.title = updates.title;
if (updates.type) item.type = updates.type;
if (updates.schedule) item.schedule = updates.schedule;
+ if (updates.mastery) item.mastery = updates.mastery;
if (updates.lines) {
item.content.lines = updates.lines.map(l => ({
text: l.text || l,
@@ -431,6 +553,43 @@ export async function updateMemoryItem(id, updates) {
return item;
}
+/**
+ * User attestation is trusted provisionally: remove the item from routine
+ * training now, then schedule one randomized future audit. Passing that audit
+ * makes the attestation verified; failing it resumes ordinary learning.
+ */
+export async function attestMemoryItemMastery(id, now = new Date(), random = Math.random) {
+ const items = await loadMemoryItems();
+ const item = items.find(i => i.id === id);
+ if (!item) return null;
+
+ const targets = targetMasteryEntries(item);
+ if (!targets.length) return null;
+ const nowIso = now.toISOString();
+ for (const [key, bucket, existing] of targets) {
+ const stat = existing || { correct: 0, attempts: 0 };
+ stat.masteredAt = nowIso;
+ stat.masterySource = 'attested';
+ bucket[key] = stat;
+ }
+
+ const spotCheckAt = scheduleSpotCheckAt(now, random);
+ item.mastery.retention = {
+ status: 'attested',
+ attestedAt: nowIso,
+ masteredAt: null,
+ spotCheckAt,
+ spotCheckCompletedAt: null,
+ lapsedAt: null,
+ };
+ item.mastery.overallPct = computeOverallMastery(item);
+ setAuditSchedule(item, spotCheckAt, now);
+ item.updatedAt = nowIso;
+ await saveMemoryItems(items);
+ console.log(`🧠 Memory mastery attested: "${item.title}" → one future spot check scheduled`);
+ return { mastery: item.mastery, schedule: item.schedule };
+}
+
export async function deleteMemoryItem(id) {
const items = await loadMemoryItems();
const idx = items.findIndex(i => i.id === id);
@@ -446,6 +605,18 @@ export async function deleteMemoryItem(id) {
// PRACTICE & MASTERY
// =============================================================================
+function recordChunkResults(item, chunkId, results, nowIso) {
+ if (!item.mastery.chunks[chunkId]) {
+ item.mastery.chunks[chunkId] = { correct: 0, attempts: 0, lastPracticed: null };
+ }
+ const chunk = item.mastery.chunks[chunkId];
+ chunk.attempts += results.length;
+ chunk.correct += results.filter(r => r.correct).length;
+ chunk.lastPracticed = nowIso;
+ for (const result of results) pushRecent(chunk, result.correct);
+ preserveStatMastery(chunk, nowIso);
+}
+
export async function submitPractice(id, practiceData) {
const items = await loadMemoryItems();
const item = items.find(i => i.id === id);
@@ -462,18 +633,27 @@ export async function submitPractice(id, practiceData) {
// keeps the exact instant, matching submitTrainingEntry's shape. Derive the day
// from the SAME `nowDate` so a midnight boundary can't split date and timestamp.
const todayLocal = await userLocalToday(nowDate);
+ const correctCount = results.filter(r => r.correct).length;
+ const ratio = results.length ? correctCount / results.length : 0;
+ const spotCheckDue = isMemorySpotCheckDue(item, nowDate);
+ if (spotCheckDue && ratio < MASTERY_TARGET_ACCURACY) {
+ resumeTrainingAfterFailedSpotCheck(item, nowDate);
+ }
// Update chunk mastery
if (chunkId) {
- if (!item.mastery.chunks[chunkId]) {
- item.mastery.chunks[chunkId] = { correct: 0, attempts: 0, lastPracticed: null };
+ recordChunkResults(item, chunkId, results, now);
+ } else {
+ const resultsByChunk = new Map();
+ for (const result of results) {
+ if (!result.chunkId) continue;
+ const bucket = resultsByChunk.get(result.chunkId) || [];
+ bucket.push(result);
+ resultsByChunk.set(result.chunkId, bucket);
+ }
+ for (const [resultChunkId, chunkResults] of resultsByChunk) {
+ recordChunkResults(item, resultChunkId, chunkResults, now);
}
- const chunk = item.mastery.chunks[chunkId];
- chunk.attempts += results.length;
- chunk.correct += results.filter(r => r.correct).length;
- chunk.lastPracticed = now;
- // Rolling window for decay-aware mastery (issue #2096) — one flag per result.
- for (const r of results) pushRecent(chunk, r.correct);
}
// Update element-level mastery (for elements song)
@@ -487,6 +667,7 @@ export async function submitPractice(id, practiceData) {
el.attempts++;
if (r.correct) el.correct++;
pushRecent(el, r.correct);
+ preserveStatMastery(el, now);
}
}
}
@@ -500,10 +681,14 @@ export async function submitPractice(id, practiceData) {
// staying due today. `mergeScheduleAdvance` gates interval growth to once per
// day so the per-chunk submits of a spaced session don't compound the interval,
// while a miss anywhere still resets the item to due-now.
- const correctCount = results.filter(r => r.correct).length;
- const ratio = results.length ? correctCount / results.length : 0;
- const advanced = advanceSchedule(item.schedule, ratio, new Date(now));
- item.schedule = mergeScheduleAdvance(item.schedule, advanced, new Date(now));
+ if (spotCheckDue && ratio >= MASTERY_TARGET_ACCURACY) {
+ completeSpotCheck(item, nowDate);
+ } else if (!spotCheckDue && promoteCompletedMastery(item, nowDate)) {
+ item.mastery.overallPct = computeOverallMastery(item);
+ } else if (!['attested', 'mastered'].includes(item.mastery.retention?.status)) {
+ const advanced = advanceSchedule(item.schedule, ratio, nowDate);
+ item.schedule = mergeScheduleAdvance(item.schedule, advanced, nowDate);
+ }
item.updatedAt = now;
await saveMemoryItems(items);
@@ -558,6 +743,16 @@ export async function advanceScheduleFromSession(memoryItemId, ratio, now = new
// single core guarantees the consolidated one-pass path produces byte-identical
// schedule results to the legacy per-task path.
function applyScheduleAdvanceToItem(item, ratio, now) {
+ if (isMemorySpotCheckDue(item, now)) {
+ if (ratio >= MASTERY_TARGET_ACCURACY) completeSpotCheck(item, now);
+ else resumeTrainingAfterFailedSpotCheck(item, now);
+ item.updatedAt = now.toISOString();
+ return item.schedule;
+ }
+ if (['attested', 'mastered'].includes(item.mastery?.retention?.status)) {
+ item.updatedAt = now.toISOString();
+ return item.schedule;
+ }
const advanced = advanceSchedule(item.schedule, ratio, now);
item.schedule = mergeScheduleAdvance(item.schedule, advanced, now);
item.updatedAt = now.toISOString();
@@ -569,6 +764,12 @@ function applyScheduleAdvanceToItem(item, ratio, now) {
// applyScheduleAdvanceToItem above.
function applyMasteryMergeToItem(item, questions, now) {
const nowIso = now.toISOString();
+ const correct = questions.filter(q => q.correct).length;
+ const ratio = questions.length ? correct / questions.length : 0;
+ const spotCheckDue = isMemorySpotCheckDue(item, now);
+ if (spotCheckDue && ratio < MASTERY_TARGET_ACCURACY) {
+ resumeTrainingAfterFailedSpotCheck(item, now);
+ }
for (const q of questions) {
if (q.chunkId) {
if (!item.mastery.chunks[q.chunkId]) {
@@ -579,6 +780,7 @@ function applyMasteryMergeToItem(item, questions, now) {
if (q.correct) chunk.correct += 1;
chunk.lastPracticed = nowIso;
pushRecent(chunk, q.correct);
+ preserveStatMastery(chunk, nowIso);
}
if (q.element) {
if (!item.mastery.elements[q.element]) {
@@ -588,10 +790,16 @@ function applyMasteryMergeToItem(item, questions, now) {
el.attempts += 1;
if (q.correct) el.correct += 1;
pushRecent(el, q.correct);
+ preserveStatMastery(el, nowIso);
}
}
item.mastery.overallPct = computeOverallMastery(item);
+ if (spotCheckDue && ratio >= MASTERY_TARGET_ACCURACY) {
+ completeSpotCheck(item, now);
+ } else if (!spotCheckDue && promoteCompletedMastery(item, now)) {
+ item.mastery.overallPct = computeOverallMastery(item);
+ }
item.updatedAt = nowIso;
return item.mastery;
}
@@ -888,10 +1096,14 @@ export function computeOverallMastery(item) {
return Math.round((masteredCount / totalElements) * 100);
}
- // For generic items: mastery is based on windowed chunk accuracy.
+ // For generic items: durable chunks remain at 100%; learning chunks continue
+ // to show their rolling-window accuracy.
const chunks = Object.values(item.mastery.chunks);
if (!chunks.length) return 0;
- const avgAccuracy = chunks.reduce((sum, c) => sum + windowedAccuracy(c).accuracy, 0) / chunks.length;
+ const avgAccuracy = chunks.reduce(
+ (sum, c) => sum + (typeof c?.masteredAt === 'string' ? 1 : windowedAccuracy(c).accuracy),
+ 0,
+ ) / chunks.length;
return Math.round(avgAccuracy * 100);
}
diff --git a/server/services/meatspacePostMemory.test.js b/server/services/meatspacePostMemory.test.js
index 4a9ea01597..3ecd39aa5a 100644
--- a/server/services/meatspacePostMemory.test.js
+++ b/server/services/meatspacePostMemory.test.js
@@ -25,6 +25,7 @@ import {
updateMemoryItem,
deleteMemoryItem,
submitPractice,
+ attestMemoryItemMastery,
advanceScheduleFromSession,
mergeMasteryFromSession,
applySessionToMemoryItems,
@@ -35,6 +36,8 @@ import {
advanceSchedule,
mergeScheduleAdvance,
isMemoryItemDue,
+ isMemorySpotCheckDue,
+ scheduleSpotCheckAt,
defaultSchedule,
DEFAULT_EASE,
ELEMENTS_SONG,
@@ -991,3 +994,98 @@ describe('mastery window is bounded', () => {
expect(result.elements.H.attempts).toBe(MASTERY_WINDOW + 5); // cumulative unbounded
});
});
+
+describe('durable memory mastery', () => {
+ const masteredCustomItem = (retention = { status: 'learning' }) => ({
+ id: 'custom-durable',
+ title: 'Example Poem',
+ type: 'poem',
+ builtin: false,
+ content: {
+ lines: [{ text: 'Example line' }],
+ chunks: [{ id: 'verse-1', label: 'Verse 1', lineRange: [0, 0] }],
+ },
+ mastery: { overallPct: 0, chunks: {}, elements: {}, retention },
+ schedule: defaultSchedule('2026-07-01T00:00:00.000Z'),
+ createdAt: '2026-07-01T00:00:00.000Z',
+ updatedAt: '2026-07-01T00:00:00.000Z',
+ });
+
+ beforeEach(() => vi.clearAllMocks());
+
+ it('keeps a fact mastered after it clears three checks, even after a later ordinary miss', () => {
+ const stat = { attempts: 4, correct: 3, recent: [1, 1, 1, 0], masteredAt: '2026-07-01T00:00:00.000Z' };
+ expect(isStatMastered(stat)).toBe(true);
+ expect(windowedAccuracy(stat).accuracy).toBe(0.75);
+ });
+
+ it('schedules the one-time spot check 30 to 90 days in the future', () => {
+ const now = new Date('2026-07-01T00:00:00.000Z');
+ expect(scheduleSpotCheckAt(now, () => 0)).toBe('2026-07-31T00:00:00.000Z');
+ expect(scheduleSpotCheckAt(now, () => 0.999999)).toBe('2026-09-29T00:00:00.000Z');
+ });
+
+ it('attests every target and removes the item from routine practice until its audit', async () => {
+ const now = new Date('2026-07-01T00:00:00.000Z');
+ readJSONFile.mockResolvedValueOnce({ items: [masteredCustomItem()] });
+ const result = await attestMemoryItemMastery('custom-durable', now, () => 0);
+ expect(result.mastery.retention).toMatchObject({
+ status: 'attested',
+ attestedAt: now.toISOString(),
+ spotCheckAt: '2026-07-31T00:00:00.000Z',
+ });
+ expect(result.mastery.chunks['verse-1']).toMatchObject({ masterySource: 'attested', masteredAt: now.toISOString() });
+ expect(result.mastery.overallPct).toBe(100);
+ expect(isMemoryItemDue({ mastery: result.mastery, schedule: result.schedule }, now)).toBe(false);
+ });
+
+ it('makes a passed spot check permanent and never due again', async () => {
+ const now = new Date('2026-08-01T00:00:00.000Z');
+ vi.useFakeTimers();
+ vi.setSystemTime(now);
+ try {
+ const item = masteredCustomItem({
+ status: 'attested',
+ attestedAt: '2026-07-01T00:00:00.000Z',
+ spotCheckAt: now.toISOString(),
+ spotCheckCompletedAt: null,
+ });
+ item.mastery.chunks['verse-1'] = { correct: 0, attempts: 0, masteredAt: '2026-07-01T00:00:00.000Z', masterySource: 'attested' };
+ readJSONFile.mockResolvedValueOnce({ items: [item] }).mockResolvedValueOnce({ entries: [] });
+
+ const result = await submitPractice('custom-durable', {
+ mode: 'sequence', chunkId: 'verse-1', results: [{ correct: true }], totalMs: 100,
+ });
+ expect(result.mastery.retention.status).toBe('mastered');
+ expect(result.mastery.retention.spotCheckCompletedAt).toBe(now.toISOString());
+ expect(isMemoryItemDue({ mastery: result.mastery, schedule: result.schedule }, new Date('2099-01-01T00:00:00.000Z'))).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('resumes training only after a failed due spot check', async () => {
+ const now = new Date('2026-08-01T00:00:00.000Z');
+ vi.useFakeTimers();
+ vi.setSystemTime(now);
+ try {
+ const item = masteredCustomItem({
+ status: 'mastered', masteredAt: '2026-07-01T00:00:00.000Z',
+ spotCheckAt: now.toISOString(), spotCheckCompletedAt: null,
+ });
+ item.mastery.chunks['verse-1'] = { correct: 3, attempts: 3, recent: [1, 1, 1], masteredAt: '2026-07-01T00:00:00.000Z', masterySource: 'verified' };
+ readJSONFile.mockResolvedValueOnce({ items: [item] }).mockResolvedValueOnce({ entries: [] });
+
+ expect(isMemorySpotCheckDue(item, now)).toBe(true);
+ const result = await submitPractice('custom-durable', {
+ mode: 'sequence', chunkId: 'verse-1', results: [{ correct: false }], totalMs: 100,
+ });
+ expect(result.mastery.retention.status).toBe('lapsed');
+ expect(result.mastery.chunks['verse-1'].masteredAt).toBeUndefined();
+ expect(result.mastery.overallPct).toBe(0);
+ expect(isMemoryItemDue({ mastery: result.mastery, schedule: result.schedule }, now)).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/server/services/meatspacePostReview.js b/server/services/meatspacePostReview.js
index 7c45ba4dcd..d77ed86d37 100644
--- a/server/services/meatspacePostReview.js
+++ b/server/services/meatspacePostReview.js
@@ -9,10 +9,10 @@
* - When a skill first becomes mastered it's tracked with `masteredAt` and a
* first review due 7 days out.
* - Left un-practiced, it goes "due for review" on an expanding interval
- * (7 → 30 → 90 days). Passing a maintenance review pushes the next review
- * further out; failing one flips it to "needs refresh" and schedules a
- * sooner re-review — but NEVER demotes the underlying `floorLevel` (the
- * anti-frustration guard lives in the progression ladder, untouched here).
+ * (7 → 30 → 90 days). Three consecutive passes make mastery permanent and
+ * end the schedule. A failure resets that verification count, flips to
+ * "needs refresh", and schedules a sooner re-review — but NEVER demotes the
+ * underlying `floorLevel` (the anti-frustration guard lives elsewhere).
* - Actively practicing a mastered skill (any non-review session at it) resets
* its staleness clock, so only genuinely inactive skills ever surface.
*
@@ -36,6 +36,7 @@ const REVIEW_SCHEDULE_FILE = join(MEATSPACE_DIR, 'post-review-schedule.json');
// Expanding review intervals (days) after mastery — SM-2-flavored per skill.
export const REVIEW_INTERVALS_DAYS = [7, 30, 90];
+export const PERMANENT_MASTERY_PASSES = 3;
// A failed review schedules a much sooner re-review (and flips to needs-refresh).
export const REFRESH_INTERVAL_DAYS = 3;
// Retention % window (reviews passed / taken) reported in the progress dashboard.
@@ -91,15 +92,17 @@ export function defaultReviewEntry(skill, now = new Date()) {
lastReviewedAt: null,
reviewStage: 0,
nextReviewAt: addDays(nowMs, REVIEW_INTERVALS_DAYS[0]),
- status: 'fresh', // 'fresh' | 'needs-refresh'
+ status: 'fresh', // 'fresh' | 'needs-refresh' | 'permanent'
reviewsPassed: 0,
reviewsTaken: 0,
+ verificationPasses: 0,
reviewHistory: [], // [{ date, passed }]
};
}
/** True when a tracked skill's review is due (`nextReviewAt <= now`). */
export function isReviewDue(entry, now = new Date()) {
+ if (entry?.status === 'permanent') return false;
const t = Date.parse(entry?.nextReviewAt ?? '');
if (Number.isNaN(t)) return true;
return t <= now.getTime();
@@ -107,9 +110,10 @@ export function isReviewDue(entry, now = new Date()) {
/**
* Retention state for reporting: `fresh` (mastered, not yet due), `due` (review
- * overdue), or `needs-refresh` (last review failed, awaiting a sooner re-review).
+ * overdue), `needs-refresh` (last review failed), or `permanent` (three passes).
*/
export function reviewState(entry, now = new Date()) {
+ if (entry?.status === 'permanent') return 'permanent';
if (entry?.status === 'needs-refresh') return 'needs-refresh';
return isReviewDue(entry, now) ? 'due' : 'fresh';
}
@@ -134,6 +138,7 @@ export function retentionForEntry(entry, now = new Date(), windowDays = RETENTIO
/** Apply a passed/failed review to an entry (pure — returns a new entry). */
export function applyReviewResult(entry, passed, now = new Date()) {
+ if (entry?.status === 'permanent') return entry;
const nowMs = now.getTime();
const nowIso = now.toISOString();
const history = [...(Array.isArray(entry.reviewHistory) ? entry.reviewHistory : []), { date: nowIso, passed: !!passed }]
@@ -144,11 +149,20 @@ export function applyReviewResult(entry, passed, now = new Date()) {
lastPracticedAt: nowIso,
reviewsTaken: (entry.reviewsTaken || 0) + 1,
reviewsPassed: (entry.reviewsPassed || 0) + (passed ? 1 : 0),
+ verificationPasses: passed ? (entry.verificationPasses || 0) + 1 : 0,
reviewHistory: history,
};
if (passed) {
- // Passed a maintenance rep — push the next review further out (expanding
- // interval) and clear any needs-refresh flag.
+ // Three passed maintenance reps are enough evidence: mastery becomes
+ // permanent and the skill leaves the review queue entirely.
+ if (next.verificationPasses >= PERMANENT_MASTERY_PASSES) {
+ next.reviewStage = REVIEW_INTERVALS_DAYS.length - 1;
+ next.status = 'permanent';
+ next.nextReviewAt = null;
+ next.permanentAt = nowIso;
+ return next;
+ }
+ // Until then, push the next verification further out.
next.reviewStage = Math.min(REVIEW_INTERVALS_DAYS.length - 1, (entry.reviewStage || 0) + 1);
next.status = 'fresh';
next.nextReviewAt = addDays(nowMs, intervalForStage(next.reviewStage));
@@ -169,6 +183,7 @@ export function applyReviewResult(entry, passed, now = new Date()) {
* the current stage's interval; does not count as a formal review.
*/
export function applyPractice(entry, now = new Date()) {
+ if (entry?.status === 'permanent') return entry;
const nowMs = now.getTime();
return {
...entry,
@@ -279,7 +294,7 @@ export async function getDueReviews(now = new Date(), limit = 2) {
// isReviewDue covers both a fresh skill past its interval and a needs-refresh
// skill past its (shorter) refresh interval.
return entries
- .filter(e => isReviewDue(e, now))
+ .filter(e => e.kind !== 'memory' && isReviewDue(e, now))
.sort((a, b) => Date.parse(a.nextReviewAt || 0) - Date.parse(b.nextReviewAt || 0))
.slice(0, Math.max(0, limit));
}
@@ -289,7 +304,9 @@ export async function getDueReviews(now = new Date(), limit = 2) {
* dashboard mastery block (issue #2091 + #2096).
*/
export async function getRetentionReport(now = new Date()) {
- const entries = await getReviewSchedule();
+ // Memory retention moved to each memory item's mastery record; ignore legacy
+ // per-chunk entries so one fact never receives two competing schedules.
+ const entries = (await getReviewSchedule()).filter(e => e.kind !== 'memory');
let totalTaken = 0;
let totalPassed = 0;
const skills = entries.map(e => {
diff --git a/server/services/meatspacePostReview.test.js b/server/services/meatspacePostReview.test.js
index d7bdd317f1..9e44dba02d 100644
--- a/server/services/meatspacePostReview.test.js
+++ b/server/services/meatspacePostReview.test.js
@@ -12,6 +12,7 @@ vi.mock('../lib/fileUtils.js', () => ({
import {
REVIEW_INTERVALS_DAYS,
+ PERMANENT_MASTERY_PASSES,
REFRESH_INTERVAL_DAYS,
defaultReviewEntry,
isReviewDue,
@@ -41,6 +42,7 @@ describe('defaultReviewEntry', () => {
expect(entry.masteredAt).toBe(now.toISOString());
expect(Date.parse(entry.nextReviewAt) - now.getTime()).toBe(REVIEW_INTERVALS_DAYS[0] * DAY);
expect(entry.reviewsTaken).toBe(0);
+ expect(entry.verificationPasses).toBe(0);
});
});
@@ -61,6 +63,11 @@ describe('isReviewDue / reviewState', () => {
it('treats a missing/invalid nextReviewAt as due', () => {
expect(isReviewDue({}, now)).toBe(true);
});
+ it('never resurfaces permanent mastery', () => {
+ const entry = { nextReviewAt: null, status: 'permanent' };
+ expect(isReviewDue(entry, now)).toBe(false);
+ expect(reviewState(entry, now)).toBe('permanent');
+ });
});
describe('applyReviewResult — expanding intervals', () => {
@@ -74,13 +81,17 @@ describe('applyReviewResult — expanding intervals', () => {
expect(after.reviewsPassed).toBe(1);
expect(after.reviewsTaken).toBe(1);
});
- it('successive passes keep expanding, then cap at the last interval', () => {
+ it('three successful reviews make mastery permanent', () => {
let entry = defaultReviewEntry(skill(), now);
entry = applyReviewResult(entry, true, now); // stage 1
- entry = applyReviewResult(entry, true, now); // stage 2 (last)
- entry = applyReviewResult(entry, true, now); // stays stage 2
+ entry = applyReviewResult(entry, true, now); // stage 2
+ entry = applyReviewResult(entry, true, now); // permanent
+ expect(entry.reviewsPassed).toBe(PERMANENT_MASTERY_PASSES);
+ expect(entry.verificationPasses).toBe(PERMANENT_MASTERY_PASSES);
expect(entry.reviewStage).toBe(REVIEW_INTERVALS_DAYS.length - 1);
- expect(Date.parse(entry.nextReviewAt) - now.getTime()).toBe(REVIEW_INTERVALS_DAYS[REVIEW_INTERVALS_DAYS.length - 1] * DAY);
+ expect(entry.status).toBe('permanent');
+ expect(entry.nextReviewAt).toBeNull();
+ expect(entry.permanentAt).toBe(now.toISOString());
});
it('a failed review flips to needs-refresh and schedules a SOONER re-review, resetting the stage', () => {
let entry = defaultReviewEntry(skill(), now);
@@ -92,12 +103,18 @@ describe('applyReviewResult — expanding intervals', () => {
expect(REFRESH_INTERVAL_DAYS).toBeLessThan(REVIEW_INTERVALS_DAYS[0]);
expect(failed.reviewsPassed).toBe(1); // the earlier pass still counted
expect(failed.reviewsTaken).toBe(2);
+ expect(failed.verificationPasses).toBe(0);
});
it('never carries a floorLevel field — demotion is out of scope for the scheduler', () => {
const entry = defaultReviewEntry(skill(), now);
const failed = applyReviewResult(entry, false, now);
expect(failed).not.toHaveProperty('floorLevel');
});
+ it('treats permanent mastery as terminal even when a stale review result arrives', () => {
+ const permanent = { ...defaultReviewEntry(skill(), now), status: 'permanent', nextReviewAt: null };
+ expect(applyReviewResult(permanent, true, now)).toBe(permanent);
+ expect(applyReviewResult(permanent, false, now)).toBe(permanent);
+ });
});
describe('applyPractice — active use resets staleness', () => {
@@ -115,6 +132,10 @@ describe('applyPractice — active use resets staleness', () => {
const after = applyPractice(future, now);
expect(after.nextReviewAt).toBe(future.nextReviewAt);
});
+ it('does not restart the clock for permanent mastery', () => {
+ const permanent = { ...defaultReviewEntry(skill()), status: 'permanent', nextReviewAt: null };
+ expect(applyPractice(permanent, new Date('2026-08-01T00:00:00.000Z'))).toBe(permanent);
+ });
});
describe('retentionForEntry — 90-day retention %', () => {
@@ -190,6 +211,14 @@ describe('getDueReviews — caps + ordering', () => {
const due = await getDueReviews(new Date('2026-07-01T00:00:00.000Z'), 2);
expect(due.map(d => d.skillId)).toEqual(['b', 'a']); // oldest-due first, capped at 2
});
+
+ it('ignores legacy memory-chunk schedules now owned by the memory item', async () => {
+ await applySessionToReviewSchedule({
+ masteredSkills: [skill({ skillId: 'memory:item:chunk', kind: 'memory' })],
+ now: new Date('2026-01-01T00:00:00.000Z'),
+ });
+ expect(await getDueReviews(new Date('2026-07-01T00:00:00.000Z'))).toEqual([]);
+ });
});
describe('getRetentionReport', () => {