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

Merge origin/main into next/issue-2098: consolidate memory-write expectations, repair meatspacePost.test.js structure, route #2114 wordplay test through URL-mode harness

Adam Eivy7ae5e844fb09
diff --cc .changelog/NEXT.md
index 9ce8b2c66e,be0eba29a9..5ef618aeb4
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@@ -26,7 -31,8 +31,9 @@@
## POST Training
+- **[issue-2098] POST sessions survive a refresh, are shareable by link, and can't double-record.** A POST session no longer lives only in the current page: refreshing mid-drill now resumes the same run (same drill queue, same completed results, right where you left off), and refreshing on the results screen keeps your results. Every saved session gets its own shareable, bookmarkable address (`/post/session/<id>`) — History rows open it, and it shows the same per-drill mistake review as the just-finished screen; a stale or deleted link shows a clear "session not found" message. Wordplay game modes now live in the URL too (`/post/wordplay/<mode>`), so a mode is deep-linkable and refresh-safe. Saving a session is now idempotent: if the network drops and the app retries, you get one record, not two — and a hiccup in the after-save bookkeeping (spaced-repetition scheduling for memory drills) can never fail an already-saved session.
+ - **[issue-2095] Cognitive drills now level up as you master them, instead of training at one fixed difficulty forever.** N-back, digit span, Schulte table, mental rotation, and Stroop each climb their own mastery-gated ladder: n-back ramps 1-back → 2-back → 3-back and then squeezes the flash speed (2500 → 2000 → 1600ms); digit span grows its span and adds backward recall; Schulte grows the grid 4×4 → 6×6; mental rotation and Stroop add trials. You advance a rung only after sustained high accuracy at the current one (n-back uses the fair signal-detection accuracy, so never-pressing can't bank a level), and you're never demoted below a rung you've earned. Each drill now stamps its difficulty into your saved results, so progress is tracked per level (a 2-back run no longer pools with a 3-back run). The config page shows each drill's current rung and progress toward the next, with a per-drill "Progressive" toggle (on by default) — turn it off to set the knobs by hand, including the previously-hidden n-back stimulus speed and digit-span show time. Reaction time stays a fixed measurement. On by default for existing installs with no migration.
+ - **[issue-2091] A unified Progress dashboard shows whether you're actually improving.** POST has a new **Progress** page (in the POST sidebar section, ⌘K, and voice nav) that pulls scored sessions, Morse/memory practice, and mastery into one view. It charts your score, accuracy, and response-time trends over time — so "am I getting faster?" finally has an answer — with same-day sessions rolled into one point (no more overlapping dots), a per-domain focus selector, and time-in-training cards. Your practice streak is now a single number counting *any* active day — a scored session **or** a Morse/memory practice — so the launcher, the Morse trainer, the Progress page, and the dashboard widgets all show the same streak instead of three different ones. A mastery panel shows your multiplication ladder rung and each memory item's mastery and due status. The full session-history table lives on as a sub-view.
- **[issue-2092] Morse progress now lives on the server, with WPM/accuracy trends and a per-character confusion matrix.** Your Koch level and every completed drill round are now saved server-side instead of only in the browser — so clearing browser data or switching devices (over Tailscale) no longer wipes your Morse mastery, and your level is identical everywhere. The first time you open the trainer it adopts your existing browser level once, then keeps both in sync. A new **Morse Progress** panel on `/post/morse` charts accuracy and effective-WPM trends per mode (Copy / Head Copy / Send), highlights your most-confused character pairs (E↔I and friends), and lists your weakest characters worst-first so you know exactly which to drill next. Send-mode rounds record per-character keying accuracy and timing too.
## Rounds
diff --cc client/src/components/meatspace/post/WordplayTrainer.test.jsx
index b684c12207,d95abb79c3..0cb412fef4
--- a/client/src/components/meatspace/post/WordplayTrainer.test.jsx
+++ b/client/src/components/meatspace/post/WordplayTrainer.test.jsx
@@@ -85,58 -67,19 +85,69 @@@ describe('WordplayTrainer — training-
}));
const entry = submitTrainingEntry.mock.calls[0][0];
expect(entry.totalMs).toBeGreaterThanOrEqual(0);
+
+ // Per-question breakdown (issue #2114) — one entry per scored response,
+ // carrying the score/feedback already computed for the results screen.
+ expect(entry.questions).toHaveLength(1);
+ expect(entry.questions[0]).toMatchObject({
+ prompt: 'fire',
+ items: ['firehouse'],
+ score: 85,
+ feedback: 'Nice compounds!',
+ correct: true,
+ });
});
+ it('does not wedge on a permanent spinner after leaving a mode mid-generation then picking another (issue #2098)', async () => {
+ generatePostDrill
+ .mockImplementationOnce(() => new Promise(() => {})) // mode A generation hangs
+ .mockResolvedValueOnce({
+ type: 'bridge-word',
+ puzzles: [{ clues: ['news___', '___back'], answer: 'paper' }],
+ });
+
+ render(<TrainerHarness onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);
+
+ fireEvent.click(await screen.findByText('Compound Chain')); // enter mode A → loading (hangs)
+ await waitFor(() => expect(screen.getByText(/Generating/i)).toBeInTheDocument());
+
+ // Leave mid-generation via the header Back (mirrors browser-back off the URL).
+ // The stale `loading` from the aborted generation must be cleared, or the
+ // next mode would be stuck on a permanent spinner.
+ fireEvent.click(screen.getAllByRole('button')[0]);
+ await screen.findByText('Bridge Word'); // back on the mode grid
+
+ fireEvent.click(screen.getByText('Bridge Word')); // enter mode B
+ await waitFor(() => expect(screen.getByText('news___')).toBeInTheDocument()); // B generated, not wedged
+ });
+
+ it('ignores a superseded generation when the same mode is re-entered mid-generation (issue #2098)', async () => {
+ let resolveFirst;
+ generatePostDrill
+ .mockImplementationOnce(() => new Promise(r => { resolveFirst = r; })) // run #1 (deferred)
+ .mockResolvedValueOnce({
+ type: 'compound-chain',
+ challenges: [{ rootWord: 'water', position: 'prefix', minExpected: 1 }],
+ }); // run #2
+
+ render(<TrainerHarness onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);
+
+ fireEvent.click(await screen.findByText('Compound Chain')); // enter A → run #1 (deferred)
+ await waitFor(() => expect(screen.getByText(/Generating/i)).toBeInTheDocument());
+ fireEvent.click(screen.getAllByRole('button')[0]); // back to grid (invalidates run #1)
+ await screen.findByText('Compound Chain');
+ fireEvent.click(screen.getByText('Compound Chain')); // re-enter A → run #2 resolves
+ await waitFor(() => expect(screen.getByText('water')).toBeInTheDocument());
+
+ // The stale run #1 finally resolves — its token is superseded, so it must NOT
+ // swap the drill out from under the live run #2.
+ await act(async () => {
+ resolveFirst({ type: 'compound-chain', challenges: [{ rootWord: 'fire', position: 'prefix', minExpected: 1 }] });
+ });
+ expect(screen.getByText('water')).toBeInTheDocument();
+ expect(screen.queryByText('fire')).toBeNull();
+ });
+
it('does not submit a training entry before the round completes', async () => {
generatePostDrill.mockResolvedValue({
type: 'bridge-word',
@@@ -164,4 -107,39 +175,39 @@@
await screen.findByText('Next');
expect(submitTrainingEntry).not.toHaveBeenCalled();
});
+
+ it('persists a Bridge Word breakdown with a readable prompt built from the clue set (issue #2114)', async () => {
+ // Regression: Bridge Word puzzles have no rootWord/word/idiom field, only
+ // `clues`. Before this fix, the persisted question's `prompt` silently
+ // fell through to '' for this mode — the training log couldn't identify
+ // which puzzle a missed answer belonged to.
+ generatePostDrill.mockResolvedValue({
+ type: 'bridge-word',
+ puzzles: [{ clues: ['news___', '___back'], answer: 'paper' }],
+ });
+ scorePostLlmDrill.mockResolvedValue({
+ evaluation: { scores: [{ score: 40, feedback: 'Not quite' }] },
+ });
+
- render(<WordplayTrainer onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);
++ render(<TrainerHarness onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);
+
+ fireEvent.click(await screen.findByText('Bridge Word'));
+ await waitFor(() => expect(screen.getByText('news___')).toBeInTheDocument());
+
+ const input = screen.getByPlaceholderText(/bridge word is/i);
+ fireEvent.change(input, { target: { value: 'wrongword' } });
+ fireEvent.click(screen.getByText('Submit'));
+
+ const seeResults = await screen.findByText('See Results');
+ fireEvent.click(seeResults);
+
+ await waitFor(() => expect(submitTrainingEntry).toHaveBeenCalledTimes(1));
+ const entry = submitTrainingEntry.mock.calls[0][0];
+ expect(entry.questions[0]).toMatchObject({
+ prompt: 'news___ / ___back',
+ response: 'wrongword',
+ score: 40,
+ correct: false,
+ });
+ });
});
diff --cc client/src/components/meatspace/tabs/PostTab.jsx
index 9bc3cacc0f,010f0924fc..790587524a
--- a/client/src/components/meatspace/tabs/PostTab.jsx
+++ b/client/src/components/meatspace/tabs/PostTab.jsx
@@@ -8,8 -8,8 +8,9 @@@ import PostDrillRunner from '../post/Po
import PostLlmDrillRunner from '../post/PostLlmDrillRunner';
import PostCognitiveDrillRunner from '../post/PostCognitiveDrillRunner';
import PostSessionResults from '../post/PostSessionResults';
+import PostSessionDetail from '../post/PostSessionDetail';
import PostHistory from '../post/PostHistory';
+ import PostProgress from '../post/PostProgress';
import PostDrillConfig from '../post/PostDrillConfig';
import MemoryBuilder from '../post/MemoryBuilder';
import ElementsSong from '../post/ElementsSong';
diff --cc client/src/hooks/usePostSession.js
index 4f2dd3e80a,e496df723a..f76a92d551
--- a/client/src/hooks/usePostSession.js
+++ b/client/src/hooks/usePostSession.js
@@@ -1,60 -1,11 +1,63 @@@
-import { useState, useCallback, useRef } from 'react';
+import { useState, useCallback, useRef, useEffect } from 'react';
import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingEntry } from '../services/api';
import toast from '../components/ui/Toast';
- import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, DRILL_TO_DOMAIN, countLlmCorrect } from '../components/meatspace/post/constants';
+ import {
+ LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, DRILL_TO_DOMAIN, countLlmCorrect,
+ WORDPLAY_LLM_DRILL_TYPES, LLM_TRAINING_CORRECT_THRESHOLD,
+ } from '../components/meatspace/post/constants';
+// sessionStorage key for the single in-progress run. Single-user tool → one
+// active run at a time, so a single key is enough. Restored on refresh so a
+// mid-drill reload resumes the same drill queue + completed results, and a
+// reload on the completed-but-unsaved results screen keeps the results.
+const RUN_STORAGE_KEY = 'post.activeRun';
+// Only an active or completed-unsaved run is worth resuming. A run that was
+// still generating a drill (`loading`) lost its in-flight request to the
+// reload, and an `idle`/`saved` run has nothing live to restore.
+const RESTORABLE_STATES = new Set(['drilling', 'between-drills', 'complete']);
+
+// uuid v4 usable in non-secure contexts. `crypto.randomUUID` only exists in a
+// secure context (HTTPS / localhost) — PortOS is commonly reached over plain
+// HTTP via Tailscale, where it's undefined — but `crypto.getRandomValues` is
+// available there too, so derive a spec-valid v4 from it (the server validates
+// the id with Zod `.uuid()`). Math.random is the last-ditch fallback.
+function newRunId() {
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
+ return crypto.randomUUID();
+ }
+ const b = new Uint8Array(16);
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) crypto.getRandomValues(b);
+ else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256);
+ b[6] = (b[6] & 0x0f) | 0x40; // version 4
+ b[8] = (b[8] & 0x3f) | 0x80; // variant 10
+ const h = [...b].map(x => x.toString(16).padStart(2, '0'));
+ return `${h[0]}${h[1]}${h[2]}${h[3]}-${h[4]}${h[5]}-${h[6]}${h[7]}-${h[8]}${h[9]}-${h[10]}${h[11]}${h[12]}${h[13]}${h[14]}${h[15]}`;
+}
+
+function loadRunSnapshot() {
+ if (typeof sessionStorage === 'undefined') return null;
+ const raw = sessionStorage.getItem(RUN_STORAGE_KEY);
+ if (!raw) return null;
+ let snap = null;
+ try { snap = JSON.parse(raw); } catch { return null; } // corrupt storage → start fresh
+ if (!snap || typeof snap !== 'object') return null;
+ if (snap.state === 'saving') {
+ // A scored session re-saves idempotently (client-supplied id → upsert), so
+ // restoring a mid-save run to `complete` is safe. A TRAINING save instead
+ // loops non-idempotent training-log writes; restoring it would let a re-save
+ // double-log every drill — and the entries were most likely already posted —
+ // so drop it rather than resume.
+ if (snap.isTraining) return null;
+ snap.state = 'complete';
+ }
+ if (!RESTORABLE_STATES.has(snap.state)) return null;
+ return snap;
+}
+
+function clearRunSnapshot() {
+ if (typeof sessionStorage !== 'undefined') sessionStorage.removeItem(RUN_STORAGE_KEY);
+}
+
function computeSessionScoreFromResults(results) {
if (!results.length) return 0;
// Group by domain — if any drills have domain info, use weighted avg per domain
diff --cc client/src/hooks/usePostSession.test.js
index c7bed76f86,31aa0f676a..e052ae7c9c
--- a/client/src/hooks/usePostSession.test.js
+++ b/client/src/hooks/usePostSession.test.js
@@@ -452,3 -530,94 +530,201 @@@ describe('usePostSession — LLM traini
}));
});
});
+
+ describe('usePostSession — LLM training-log per-question breakdown (issue #2114)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ // Follow-up to #2097: the standalone Wordplay tab already threads a
+ // per-question breakdown through submitTrainingEntry (WordplayTrainer.jsx).
+ // The in-session runner completes the same four drill types through
+ // completeLlmDrill/saveSession here, and must populate the same field so a
+ // completed in-session wordplay round isn't missing the breakdown.
+ it('threads a per-question breakdown for a completed in-session wordplay drill', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'compound-chain', config: {}, challenges: [{ rootWord: 'fire' }],
+ });
+ scorePostLlmDrill.mockResolvedValue({
+ score: 90,
+ questions: [{ questionIndex: 0, prompt: 'fire', items: ['firehouse'], responseMs: 500, llmScore: 90, llmFeedback: 'Nice!' }],
+ evaluation: { overallScore: 90, scores: [{ score: 90, feedback: 'Nice!' }] },
+ });
+ submitTrainingEntry.mockResolvedValue({});
+
+ const { result } = renderHook(() => usePostSession());
+
+ await act(async () => {
+ await result.current.startSession([{ type: 'compound-chain', config: {}, timeLimitSec: 120 }], true);
+ });
+
+ await act(async () => {
+ await result.current.completeLlmDrill({
+ module: 'llm-drills',
+ type: 'compound-chain',
+ config: {},
+ drillData: {},
+ responses: [{ questionIndex: 0, prompt: 'fire', items: ['firehouse'], responseMs: 500 }],
+ totalMs: 5000,
+ });
+ });
+
+ await act(async () => {
+ await result.current.saveSession({});
+ });
+
+ expect(submitTrainingEntry).toHaveBeenCalledWith(expect.objectContaining({
+ drillType: 'compound-chain',
+ questions: [expect.objectContaining({
+ prompt: 'fire', items: ['firehouse'], score: 90, feedback: 'Nice!', correct: true,
+ })],
+ }));
+ });
+
+ // Non-wordplay LLM drill types (word-association, story-recall, etc.) have
+ // no dashboard use case yet and their `r.responses` shape isn't guaranteed
+ // to carry a renderable prompt — scope the breakdown to WORDPLAY_LLM_DRILL_TYPES
+ // only, same as the standalone tab.
+ it('omits the questions field for a non-wordplay LLM drill type', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'word-association', config: {}, prompts: ['x'],
+ });
+ scorePostLlmDrill.mockResolvedValue({
+ score: 80,
+ questions: [{ questionIndex: 0, response: 'y', llmScore: 80 }],
+ evaluation: { overallScore: 80, scores: [{ score: 80 }] },
+ });
+ submitTrainingEntry.mockResolvedValue({});
+
+ const { result } = renderHook(() => usePostSession());
+
+ await act(async () => {
+ await result.current.startSession([{ type: 'word-association', config: {}, timeLimitSec: 120 }], true);
+ });
+
+ await act(async () => {
+ await result.current.completeLlmDrill({
+ module: 'llm-drills',
+ type: 'word-association',
+ config: {},
+ drillData: {},
+ responses: [{ questionIndex: 0, response: 'y', responseMs: 500 }],
+ totalMs: 3000,
+ });
+ });
+
+ await act(async () => {
+ await result.current.saveSession({});
+ });
+
+ const entry = submitTrainingEntry.mock.calls[0][0];
+ expect(entry).not.toHaveProperty('questions');
+ });
+ });
++
++describe('usePostSession — refresh-safe run + idempotent submit (issue #2098)', () => {
++ beforeEach(() => {
++ vi.clearAllMocks();
++ sessionStorage.clear();
++ });
++
++ it('generates a client run id and submits it as the session id (idempotent upsert key)', async () => {
++ generatePostDrill.mockResolvedValue({
++ type: 'doubling-chain', config: { startValue: 2, steps: 1 }, questions: [{ prompt: '2 x 2', expected: 4 }],
++ });
++ submitPostSession.mockResolvedValue({ id: 'srv', score: 100 });
++
++ const { result } = renderHook(() => usePostSession());
++ await act(async () => {
++ await result.current.startSession([{ type: 'doubling-chain', config: {}, timeLimitSec: 60 }]);
++ });
++ const runId = result.current.runId;
++ expect(runId).toMatch(/^[0-9a-f-]{36}$/i);
++
++ act(() => { result.current.submitAnswer('4'); });
++ await act(async () => { await result.current.saveSession({}); });
++
++ const payload = submitPostSession.mock.calls[0][0];
++ expect(payload.id).toBe(runId); // same id the run started with → retry-safe
++ });
++
++ it('persists the in-progress run to sessionStorage and restores it on a fresh mount (refresh)', async () => {
++ generatePostDrill.mockResolvedValue({
++ type: 'doubling-chain', config: { startValue: 2, steps: 3 },
++ questions: [
++ { prompt: '2 x 2', expected: 4 },
++ { prompt: '4 x 2', expected: 8 },
++ { prompt: '8 x 2', expected: 16 },
++ ],
++ });
++
++ const first = renderHook(() => usePostSession());
++ await act(async () => {
++ await first.result.current.startSession([{ type: 'doubling-chain', config: {}, timeLimitSec: 60 }]);
++ });
++ act(() => { first.result.current.submitAnswer('4'); }); // answer q1, mid-drill
++ const runId = first.result.current.runId;
++ expect(first.result.current.state).toBe('drilling');
++
++ // Simulate a page refresh: a brand-new hook instance reads sessionStorage.
++ first.unmount();
++ const second = renderHook(() => usePostSession());
++ expect(second.result.current.runId).toBe(runId);
++ expect(second.result.current.state).toBe('drilling');
++ expect(second.result.current.currentDrill?.questions).toHaveLength(3);
++ expect(second.result.current.answers).toHaveLength(1); // the mid-drill answer survived
++ });
++
++ it('keeps completed results in the snapshot during next-drill generation (does not drop the run on refresh)', async () => {
++ generatePostDrill
++ .mockResolvedValueOnce({ type: 'doubling-chain', config: {}, questions: [{ prompt: '2 x 2', expected: 4 }] })
++ .mockImplementationOnce(() => new Promise(() => {})); // drill 2 generation hangs (mid-refresh)
++
++ const { result } = renderHook(() => usePostSession());
++ await act(async () => {
++ await result.current.startSession([
++ { type: 'doubling-chain', config: {}, timeLimitSec: 60 },
++ { type: 'doubling-chain', config: {}, timeLimitSec: 60 },
++ ]);
++ });
++ act(() => { result.current.submitAnswer('4'); }); // finish drill 1 → between-drills
++ expect(result.current.state).toBe('between-drills');
++
++ act(() => { result.current.nextDrill(); }); // drill 2 generation starts and hangs → loading
++ expect(result.current.state).toBe('loading');
++
++ // The 'loading' state must NOT have overwritten the stable between-drills
++ // snapshot — drill 1's completed result must survive a refresh here.
++ const snap = JSON.parse(sessionStorage.getItem('post.activeRun'));
++ expect(snap.state).toBe('between-drills');
++ expect(snap.drillResults).toHaveLength(1);
++ });
++
++ it('does not restore a training run persisted mid-save (avoids double training-log)', () => {
++ sessionStorage.setItem('post.activeRun', JSON.stringify({
++ runId: 'r1', state: 'saving', isTraining: true,
++ drills: [{ type: 'compound-chain' }], currentDrillIndex: 0, currentDrill: null,
++ currentQuestionIndex: 0, answers: [],
++ drillResults: [{ module: 'llm-drills', type: 'compound-chain', score: 90 }],
++ sessionScore: 90, tags: {},
++ }));
++ const { result } = renderHook(() => usePostSession());
++ expect(result.current.state).toBe('idle'); // training run is dropped, not resumed
++ });
++
++ it('clears the persisted run on reset (no stale run resumes next mount)', async () => {
++ generatePostDrill.mockResolvedValue({
++ type: 'doubling-chain', config: { startValue: 2, steps: 1 }, questions: [{ prompt: '2 x 2', expected: 4 }],
++ });
++ const { result, unmount } = renderHook(() => usePostSession());
++ await act(async () => {
++ await result.current.startSession([{ type: 'doubling-chain', config: {}, timeLimitSec: 60 }]);
++ });
++ act(() => { result.current.reset(); });
++ unmount();
++
++ const next = renderHook(() => usePostSession());
++ expect(next.result.current.state).toBe('idle');
++ expect(next.result.current.runId).toBeNull();
++ });
++});
diff --cc server/lib/postValidation.js
index 8b5c76fcb8,490df9662b..cc04ee44ed
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@@ -169,13 -185,8 +185,13 @@@ const taskResultSchema = z.object(
// Full session submission
export const postSessionSubmitSchema = z.object({
+ // Client-generated session id (uuid) — keys the idempotent upsert in
+ // submitPostSession so a retry after a dropped response can't double-record.
+ // Optional for back-compat: legacy clients and direct service callers that
+ // omit it get a server-assigned uuid.
+ id: z.string().uuid().optional(),
cadence: z.enum(['daily', 'weekly', 'monthly']).optional().default('daily'),
- modules: z.array(z.string()).min(1),
+ modules: z.array(z.enum(POST_MODULES)).min(1),
tasks: z.array(taskResultSchema).min(1),
tags: postTagsSchema.optional().default({})
});
diff --cc server/lib/postValidation.test.js
index 01b30cd1fb,e473620cad..5b5b07c415
--- a/server/lib/postValidation.test.js
+++ b/server/lib/postValidation.test.js
@@@ -233,3 -299,133 +299,160 @@@ describe('postLlmScoreRequestSchema', (
})).toThrow();
});
});
+
+ // =============================================================================
+ // drillTypeConfigSchema numeric bounds (via postDrillRequestSchema.config)
+ // (issue #2102 notes)
+ // =============================================================================
+
+ describe('drillTypeConfigSchema numeric bounds', () => {
+ it('accepts math-drill knobs within their documented bounds', () => {
+ const parsed = postDrillRequestSchema.parse({
+ type: 'serial-subtraction',
+ config: { steps: 50, subtrahend: 100, maxDigits: 4, tolerancePct: 50 },
+ });
+ expect(parsed.config).toMatchObject({ steps: 50, subtrahend: 100, maxDigits: 4, tolerancePct: 50 });
+ });
+
+ it('rejects steps above the max (50) and below the min (1)', () => {
+ expect(() => postDrillRequestSchema.parse({ type: 'serial-subtraction', config: { steps: 51 } })).toThrow();
+ expect(() => postDrillRequestSchema.parse({ type: 'serial-subtraction', config: { steps: 0 } })).toThrow();
+ });
+
+ it('rejects maxDigits outside 1-4', () => {
+ expect(() => postDrillRequestSchema.parse({ type: 'multiplication', config: { maxDigits: 5 } })).toThrow();
+ expect(() => postDrillRequestSchema.parse({ type: 'multiplication', config: { maxDigits: 0 } })).toThrow();
+ });
+
+ it('rejects tolerancePct outside 1-50', () => {
+ expect(() => postDrillRequestSchema.parse({ type: 'estimation', config: { tolerancePct: 0 } })).toThrow();
+ expect(() => postDrillRequestSchema.parse({ type: 'estimation', config: { tolerancePct: 51 } })).toThrow();
+ });
+
+ it('accepts cognitive-drill knobs within bounds (n, length, size, choices)', () => {
+ const parsed = postDrillRequestSchema.parse({
+ type: 'n-back',
+ config: { n: 3, length: 60, size: 7, choices: 4 },
+ });
+ expect(parsed.config).toMatchObject({ n: 3, length: 60, size: 7, choices: 4 });
+ });
+
+ it('rejects an out-of-range n-back n (must be 1-3)', () => {
+ expect(() => postDrillRequestSchema.parse({ type: 'n-back', config: { n: 4 } })).toThrow();
+ expect(() => postDrillRequestSchema.parse({ type: 'n-back', config: { n: 0 } })).toThrow();
+ });
+
+ it('rejects an out-of-range schulte-table size (must be 3-7)', () => {
+ expect(() => postDrillRequestSchema.parse({ type: 'schulte-table', config: { size: 8 } })).toThrow();
+ expect(() => postDrillRequestSchema.parse({ type: 'schulte-table', config: { size: 2 } })).toThrow();
+ });
+ });
+
+ // =============================================================================
+ // memoryScheduleSchema / memoryItemCreateSchema ease bounds (issue #2102 notes)
+ // =============================================================================
+
+ describe('memoryScheduleSchema ease bounds', () => {
+ it('accepts ease within the SM-2 bounds [1.3, 5]', () => {
+ expect(memoryScheduleSchema.parse({ ease: 1.3, intervalDays: 0, nextReview: '2026-07-01T00:00:00.000Z' }).ease).toBe(1.3);
+ expect(memoryScheduleSchema.parse({ ease: 5, intervalDays: 10, nextReview: '2026-07-01T00:00:00.000Z' }).ease).toBe(5);
+ });
+
+ it('rejects ease below 1.3 or above 5', () => {
+ expect(() => memoryScheduleSchema.parse({ ease: 1.2, intervalDays: 0, nextReview: '2026-07-01T00:00:00.000Z' })).toThrow();
+ expect(() => memoryScheduleSchema.parse({ ease: 5.1, intervalDays: 0, nextReview: '2026-07-01T00:00:00.000Z' })).toThrow();
+ });
+
+ it('rejects a negative intervalDays', () => {
+ expect(() => memoryScheduleSchema.parse({ ease: 2.5, intervalDays: -1, nextReview: '2026-07-01T00:00:00.000Z' })).toThrow();
+ });
+ });
+
+ describe('memoryItemCreateSchema', () => {
+ it('accepts a well-formed create request with an embedded schedule', () => {
+ const parsed = memoryItemCreateSchema.parse({
+ title: 'My Poem',
+ type: 'poem',
+ lines: ['line one', 'line two'],
+ schedule: { ease: 2.5, intervalDays: 1, nextReview: '2026-07-01T00:00:00.000Z' },
+ });
+ expect(parsed.schedule.ease).toBe(2.5);
+ expect(parsed.type).toBe('poem');
+ });
+
+ it('rejects an out-of-bounds embedded schedule ease (schema parity with memoryScheduleSchema)', () => {
+ expect(() => memoryItemCreateSchema.parse({
+ title: 'My Poem',
+ lines: ['line one'],
+ schedule: { ease: 10, intervalDays: 1, nextReview: '2026-07-01T00:00:00.000Z' },
+ })).toThrow();
+ });
+
+ it('rejects an empty lines array', () => {
+ expect(() => memoryItemCreateSchema.parse({ title: 'Empty', lines: [] })).toThrow();
+ });
+
+ it('rejects an unknown item type', () => {
+ expect(() => memoryItemCreateSchema.parse({ title: 'X', type: 'novel', lines: ['a'] })).toThrow();
+ });
+
+ it('defaults type to "text" when omitted', () => {
+ expect(memoryItemCreateSchema.parse({ title: 'X', lines: ['a'] }).type).toBe('text');
+ });
+ });
+
+ // =============================================================================
+ // memoryPracticeSchema mode enums (issue #2102 notes)
+ // =============================================================================
+
+ describe('memoryPracticeSchema mode enums', () => {
+ it('accepts every documented practice mode', () => {
+ for (const mode of ['fill-blank', 'sequence', 'element-flash', 'learn', 'speed-run']) {
+ const parsed = memoryPracticeSchema.parse({ mode, results: [{ correct: true }] });
+ expect(parsed.mode).toBe(mode);
+ }
+ });
+
+ it('rejects an unknown practice mode', () => {
+ expect(() => memoryPracticeSchema.parse({ mode: 'not-a-mode', results: [{ correct: true }] })).toThrow();
+ });
+
+ it('rejects an empty results array', () => {
+ expect(() => memoryPracticeSchema.parse({ mode: 'fill-blank', results: [] })).toThrow();
+ });
+
+ it('accepts a nullable chunkId and optional totalMs', () => {
+ const parsed = memoryPracticeSchema.parse({
+ mode: 'sequence', chunkId: null, results: [{ correct: false, expected: 'x', answered: 'y' }], totalMs: 4000,
+ });
+ expect(parsed.chunkId).toBeNull();
+ expect(parsed.totalMs).toBe(4000);
+ });
+ });
++
++describe('postSessionSubmitSchema client-generated id (issue #2098)', () => {
++ const baseBody = () => ({
++ modules: ['mental-math'],
++ tasks: [{
++ module: 'mental-math',
++ type: 'doubling-chain',
++ questions: [{ prompt: '2 x 2', expected: 4, answered: 4, responseMs: 200 }],
++ totalMs: 200
++ }]
++ });
++
++ it('accepts and preserves a valid uuid id (keys the idempotent upsert)', () => {
++ const id = '123e4567-e89b-42d3-a456-426614174000';
++ const parsed = postSessionSubmitSchema.parse({ ...baseBody(), id });
++ expect(parsed.id).toBe(id);
++ });
++
++ it('accepts a body with no id (server assigns one — back-compat)', () => {
++ const parsed = postSessionSubmitSchema.parse(baseBody());
++ expect(parsed.id).toBeUndefined();
++ });
++
++ it('rejects a non-uuid id', () => {
++ expect(() => postSessionSubmitSchema.parse({ ...baseBody(), id: 'not-a-uuid' })).toThrow();
++ });
++});
diff --cc server/services/meatspacePost.js
index fb63dc1198,ab8d56792f..4cf1ff37ff
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@@ -13,8 -13,22 +13,22 @@@ import { deepMerge, isPlainObject } fro
import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';
import { adaptDrillConfig, ADAPTIVE_SPECS, ADAPTIVE_DEFAULTS } from '../lib/postAdaptive.js';
import { resolveMultiplicationLevel, MASTERY_DEFAULTS } from '../lib/postMultiplicationLadder.js';
+ import {
+ cognitiveLadder,
+ cognitiveLevelConfig,
+ resolveCognitiveProgression,
+ COGNITIVE_LADDER_TYPES,
+ COGNITIVE_MASTERY_DEFAULTS,
+ } from '../lib/postProgression.js';
import { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } from './meatspacePostCognitive.js';
- import { applySessionToMemoryItems } from './meatspacePostMemory.js';
-import { advanceScheduleFromSession, mergeMasteryFromSession, getMemoryItems, getDueMemoryItems } from './meatspacePostMemory.js';
++import { applySessionToMemoryItems, getMemoryItems, getDueMemoryItems } from './meatspacePostMemory.js';
+ import { getAllTrainingEntries } from './meatspacePostTraining.js';
+ import { computePostStreaks, computeUnifiedStreak, ymdToUTC } from '../lib/postStreak.js';
+
+ // Re-export the shared streak helper so existing importers of
+ // `computePostStreaks` from this module keep working after it moved to
+ // server/lib/postStreak.js (single implementation — see that file).
+ export { computePostStreaks };
const MEATSPACE_DIR = PATHS.meatspace;
const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');
diff --cc server/services/meatspacePost.test.js
index 629a88acb0,af6be548be..e1cdfef52a
--- a/server/services/meatspacePost.test.js
+++ b/server/services/meatspacePost.test.js
@@@ -28,9 -28,13 +28,12 @@@ import
postConfigEvents,
resolveDrillConfig,
getMultiplicationProgress,
- getCognitiveProgress,
- generateDrill,
+ getAdaptivePreview,
getPostStats,
- getAdaptivePreview,
deriveTaskAccuracy,
deriveTaskCompletion,
++ getCognitiveProgress,
++ generateDrill,
} from './meatspacePost.js';
// =============================================================================
@@@ -618,13 -622,10 +621,11 @@@ describe('submitPostSession — memory
});
const memoryWrites = atomicWrite.mock.calls.filter(([path]) => String(path).includes('post-memory-items'));
- // Consolidated apply: schedule advance + mastery merge share a single
- // read-modify-write per submit (issue #2098), not one write each.
- // One write for the schedule advance, one for the mastery merge.
- expect(memoryWrites.length).toBe(2);
++ // Consolidated single read-modify-write (issue #2098): the one write
++ // carries BOTH the schedule advance and the mastery merge.
+ expect(memoryWrites.length).toBe(1);
const masteryWrite = memoryWrites[memoryWrites.length - 1];
const updatedItem = masteryWrite[1].items.find(i => i.id === 'song-1');
- // Both effects land on the one written item: schedule advanced AND mastery merged.
- expect(updatedItem.schedule.lastReviewed).toBeTruthy();
expect(updatedItem.mastery.chunks['verse-1']).toEqual({ correct: 1, attempts: 2, lastPracticed: expect.any(String) });
});
@@@ -685,99 -688,130 +688,130 @@@
const memoryWrite = atomicWrite.mock.calls.find(([path]) => String(path).includes('post-memory-items'));
expect(memoryWrite).toBeUndefined();
});
+
+ // Regression (issue #2099, fix #1): memory-fill-blank used to be ABSENT from
+ // POST_SUPPORTED_MEMORY_TYPES, so submitPostSession forced its score to 0
+ // (treating it as an "unsupported memory drill") and the schedule/mastery
+ // advance loop below skipped it entirely — any fill-blank work done inside a
+ // scored session was silently unrecorded. It must now behave exactly like
+ // memory-sequence/memory-element-flash: trust the client-computed score and
+ // advance the drilled item's schedule + mastery.
+ it('trusts the client score and advances schedule/mastery for a memory-fill-blank task (issue #2099/#2116)', async () => {
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['memory'],
+ tasks: [{
+ module: 'memory',
+ type: 'memory-fill-blank',
+ memoryItemId: 'song-1',
+ questions: [
+ { prompt: 'a ____ line', expected: 'test', answered: 'test', correct: true, responseMs: 500, chunkId: 'verse-1' },
+ ],
+ score: 85,
+ totalMs: 500,
+ }],
+ tags: {},
+ });
+
+ // Client-computed score is trusted for this now-supported type, not forced to 0.
+ expect(session.tasks[0].score).toBe(85);
+
+ const memoryWrites = atomicWrite.mock.calls.filter(([path]) => String(path).includes('post-memory-items'));
- expect(memoryWrites.length).toBe(2); // schedule advance + mastery merge
++ expect(memoryWrites.length).toBe(1); // consolidated write: schedule advance + mastery merge (issue #2098)
+ const scheduleWrite = memoryWrites[0];
+ const updatedItem = scheduleWrite[1].items.find(i => i.id === 'song-1');
+ expect(updatedItem.schedule.intervalDays).toBeGreaterThan(0);
+ const masteryWrite = memoryWrites[memoryWrites.length - 1];
+ const updatedMastery = masteryWrite[1].items.find(i => i.id === 'song-1');
+ expect(updatedMastery.mastery.chunks['verse-1']).toEqual({ correct: 1, attempts: 1, lastPracticed: expect.any(String) });
+ });
});
- describe('submitPostSession — idempotent upsert by client id (issue #2098)', () => {
+ // =============================================================================
+ // WEIGHTED SESSION SCORE — scoring.weights (issue #2099, fix #3)
+ //
+ // DEFAULT_CONFIG.scoring.weights + the postConfigUpdateSchema.scoring.weights
+ // slice existed but were never read anywhere — computeSessionScore was a
+ // plain unweighted mean. Wired here: uniform (default) weights must reproduce
+ // the exact old unweighted-mean score; skewed weights must shift the blend
+ // toward the higher-weighted module's score. LLM/memory tasks trust the
+ // client-supplied `score` verbatim (no server-side rescoring), which makes
+ // them the simplest fixture for asserting exact blended-score math.
+ // =============================================================================
+
+ describe('submitPostSession — weighted scoring (issue #2099)', () => {
beforeEach(() => {
vi.clearAllMocks();
- // A shared in-memory sessions store so a re-submit sees the first write.
- let sessionsStore = { sessions: [] };
+ });
+
+ const llmTask = (score) => ({
+ module: 'llm-drills', type: 'word-association', responses: [], score, totalMs: 1000,
+ });
+ const memoryTask = (score) => ({
+ module: 'memory', type: 'memory-sequence', questions: [], score, totalMs: 500,
+ });
+
+ it('uniform default weights reproduce the plain unweighted mean', async () => {
readJSONFile.mockImplementation((path, defaultValue) => {
const p = String(path);
- if (p.includes('post-sessions')) return Promise.resolve(sessionsStore);
- return Promise.resolve(defaultValue);
+ if (p.includes('post-sessions')) return Promise.resolve({ sessions: [] });
+ return Promise.resolve(defaultValue); // post-config → baseDefaults (all weights 1.0)
});
- atomicWrite.mockImplementation((path, data) => {
- if (String(path).includes('post-sessions')) sessionsStore = data;
- return Promise.resolve(undefined);
+
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['llm-drills', 'memory'],
+ tasks: [llmTask(100), memoryTask(0)],
+ tags: {},
});
- });
- const ID = '11111111-1111-4111-8111-111111111111';
- const buildBody = () => ({
- id: ID,
- cadence: 'daily',
- modules: ['mental-math'],
- tasks: [{
- module: 'mental-math',
- type: 'doubling-chain',
- config: { startValue: 2, steps: 1 },
- questions: [{ prompt: '2 x 2', expected: 4, answered: 4, responseMs: 500 }],
- totalMs: 500,
- }],
- tags: {},
+ expect(session.score).toBe(50); // (100 + 0) / 2
});
- it('re-submitting the same id upserts (no duplicate record)', async () => {
- const first = await submitPostSession(buildBody());
- const second = await submitPostSession(buildBody());
- expect(first.id).toBe(ID);
- expect(second.id).toBe(ID);
- const lastWrite = atomicWrite.mock.calls.filter(([p]) => String(p).includes('post-sessions')).pop();
- const stored = lastWrite[1].sessions.filter(s => s.id === ID);
- expect(stored.length).toBe(1);
- });
+ it('a configured module weight skews the blended score toward the higher-weighted module', async () => {
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) return Promise.resolve({ sessions: [] });
+ if (p.includes('post-config')) {
+ // De-emphasize memory (0.5) — mirrors the real 0-1 range
+ // postConfigUpdateSchema.scoring.weights accepts. llm-drills is
+ // absent from this patch and must fall back to the default weight
+ // (1.0), not drop out.
+ return Promise.resolve({ scoring: { weights: { memory: 0.5 } } });
+ }
+ return Promise.resolve(defaultValue);
+ });
- it('preserves the original date/startedAt on an idempotent re-submit (no midnight drift)', async () => {
- const first = await submitPostSession(buildBody());
- const second = await submitPostSession(buildBody());
- // A retry keeps the original day + start timestamp so history ordering and
- // streaks can't be corrupted by a re-submit that arrives later (or next day).
- expect(second.date).toBe(first.date);
- expect(second.startedAt).toBe(first.startedAt);
- });
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['llm-drills', 'memory'],
+ tasks: [llmTask(100), memoryTask(80)],
+ tags: {},
+ });
- it('assigns a server uuid when the client omits an id', async () => {
- const { id, ...noId } = buildBody();
- const session = await submitPostSession(noId);
- expect(session.id).toMatch(/^[0-9a-f-]{36}$/i);
+ // (100*1 + 80*0.5) / (1+0.5) = 140/1.5 = 93.33 → 93
+ expect(session.score).toBe(93);
});
- });
- describe('submitPostSession — memory post-processing never 500s a saved session (issue #2098)', () => {
- beforeEach(() => {
- vi.clearAllMocks();
+ it('a zero weight excludes that module\'s task from the blend entirely', async () => {
readJSONFile.mockImplementation((path, defaultValue) => {
const p = String(path);
- if (p.includes('post-memory-items')) {
- // Malformed item (no mastery / schedule) so the mastery merge throws
- // when it dereferences item.mastery.chunks — exercising the isolation.
- return Promise.resolve({ items: [{ id: 'song-1', title: 'Broken' }] });
- }
if (p.includes('post-sessions')) return Promise.resolve({ sessions: [] });
+ if (p.includes('post-config')) {
+ return Promise.resolve({ scoring: { weights: { memory: 0 } } });
+ }
return Promise.resolve(defaultValue);
});
- });
- it('returns the saved session (does not throw) when memory post-processing fails', async () => {
const session = await submitPostSession({
cadence: 'daily',
- modules: ['memory'],
- tasks: [{
- module: 'memory',
- type: 'memory-sequence',
- memoryItemId: 'song-1',
- questions: [{ prompt: 'x', expected: 'y', answered: 'y', correct: true, responseMs: 500, chunkId: 'verse-1' }],
- score: 100,
- totalMs: 500,
- }],
+ modules: ['llm-drills', 'memory'],
+ tasks: [llmTask(80), memoryTask(0)],
tags: {},
});
- // The session itself persisted (200-equivalent) despite the memory throw.
- expect(session).toBeTruthy();
- const sessionWrite = atomicWrite.mock.calls.find(([p]) => String(p).includes('post-sessions'));
- expect(sessionWrite).toBeTruthy();
- expect(sessionWrite[1].sessions.length).toBe(1);
+
+ // memory weight 0 drops out entirely → score is just the llm-drills task's own score
+ expect(session.score).toBe(80);
});
});
@@@ -949,6 -983,211 +983,70 @@@ describe('resolveDrillConfig — progre
});
});
+ // =============================================================================
-// PROGRESSIVE COGNITIVE LADDERS — resolveDrillConfig / getCognitiveProgress /
-// difficulty stamping through submitPostSession (issue #2095)
-// =============================================================================
-
-describe('progressive cognitive drills', () => {
- const today = new Date().toISOString().split('T')[0];
- const oldDate = new Date(Date.now() - 60 * 86400000).toISOString().split('T')[0];
-
- // A completed cognitive drill at `level` with a given task-level accuracy —
- // the shape getCognitiveLevelStats buckets by (accuracy-only mastery).
- function cognitiveSession(type, level, accuracy, date = today, count = 20) {
- return {
- date,
- tasks: [{
- module: 'cognitive',
- type,
- config: { level },
- accuracy,
- totalCount: count,
- questions: Array.from({ length: count }, () => ({ answered: 'x' })),
- }],
- };
- }
-
- function mockSessions(sessions, configOverride) {
- readJSONFile.mockImplementation((path, defaultValue) => {
- const p = String(path);
- if (p.includes('post-sessions')) return Promise.resolve({ sessions });
- if (p.includes('post-config')) return Promise.resolve(configOverride ?? defaultValue);
- return Promise.resolve(defaultValue);
- });
- }
-
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('starts a fresh user at n-back level 0 (1-back) and stamps the rung knobs', async () => {
- mockSessions([]);
- const { config, progression } = await resolveDrillConfig('n-back', { length: 20 });
- expect(progression.level).toBe(0);
- expect(config.level).toBe(0);
- expect(config.n).toBe(1);
- expect(config.stimulusMs).toBe(2500);
- });
-
- it('advances a cognitive rung on sustained balanced accuracy', async () => {
- // 3 clean 1-back runs at 90% balanced accuracy → clears level 0.
- mockSessions([
- cognitiveSession('n-back', 0, 0.9),
- cognitiveSession('n-back', 0, 0.92),
- cognitiveSession('n-back', 0, 0.95),
- ]);
- const { config, progression } = await resolveDrillConfig('n-back', {});
- expect(progression.level).toBe(1);
- expect(config.n).toBe(2);
- });
-
- it('does not advance on high-accuracy but low-completion runs (skipped hard trials)', async () => {
- // Answered only the easy sequence (100% accuracy) but left the rest blank —
- // low completion must not bank a mastery sample (issue #2095 review).
- const lowCompletion = (level, date = today) => ({
- date,
- tasks: [{ module: 'cognitive', type: 'digit-span', config: { level }, accuracy: 1, completion: 0.25, totalCount: 4, questions: [{ answered: '1' }] }],
- });
- mockSessions([lowCompletion(0), lowCompletion(0), lowCompletion(0)]);
- const { progression } = await resolveDrillConfig('digit-span', {});
- expect(progression.level).toBe(0);
- });
-
- it('does not advance when accuracy is below the mastery bar', async () => {
- mockSessions([
- cognitiveSession('n-back', 0, 0.6),
- cognitiveSession('n-back', 0, 0.7),
- cognitiveSession('n-back', 0, 0.5),
- ]);
- const { progression } = await resolveDrillConfig('n-back', {});
- expect(progression.level).toBe(0);
- });
-
- it('never demotes below the earned floor when the window aged out', async () => {
- mockSessions([
- cognitiveSession('digit-span', 3, 0.9, oldDate),
- cognitiveSession('digit-span', 3, 0.95, oldDate),
- cognitiveSession('digit-span', 3, 0.9, oldDate),
- ]);
- const { progression, config } = await resolveDrillConfig('digit-span', {});
- expect(progression.level).toBe(3);
- expect(progression.floorLevel).toBe(3);
- expect(config.direction).toBe('backward');
- });
-
- it('passes config through unchanged when the drill Progressive toggle is off', async () => {
- mockSessions([], { cognitive: { drillTypes: { 'n-back': { progressive: false } } } });
- const { config, progression } = await resolveDrillConfig('n-back', { n: 3, stimulusMs: 1200 });
- expect(progression == null).toBe(true);
- expect(config).toEqual({ n: 3, stimulusMs: 1200 });
- });
-
- it('reaction-time has no ladder — always passes config through', async () => {
- mockSessions([]);
- const { config, progression } = await resolveDrillConfig('reaction-time', { mode: 'choice' });
- expect(progression == null).toBe(true);
- expect(config).toEqual({ mode: 'choice' });
- });
-
- it('generateDrill stamps the resolved level into the generated cognitive config', async () => {
- mockSessions([]);
- const { config } = await resolveDrillConfig('n-back', { length: 12 });
- const drill = generateDrill('n-back', config);
- expect(drill.config.level).toBe(0);
- expect(drill.config.n).toBe(1);
- });
-
- it('getCognitiveProgress separates per-level history (n=2 vs n=3 recoverable)', async () => {
- mockSessions([
- cognitiveSession('n-back', 1, 0.9),
- cognitiveSession('n-back', 1, 0.95),
- cognitiveSession('n-back', 1, 0.92),
- ]);
- const progress = await getCognitiveProgress();
- expect(progress['n-back'].level).toBe(2); // level-1 mastered → sits on level 2
- expect(progress['n-back'].levels[1].mastered).toBe(true);
- expect(progress['n-back'].levels[2].mastered).toBe(false);
- // Every laddered type reports; reaction-time is absent.
- expect(Object.keys(progress).sort()).toEqual(['digit-span', 'mental-rotation', 'n-back', 'schulte-table', 'stroop']);
- });
-
- it('difficulty stamp survives submitPostSession (stored task carries config.level)', async () => {
- mockSessions([]);
- const { config } = await resolveDrillConfig('schulte-table', {});
- const drill = generateDrill('schulte-table', config);
- // Client submits the served drill's config (with level) + drillData.
- const questions = drill.cells.map((_, i) => ({ index: i, answered: i + 1, responseMs: 500 }));
- const session = await submitPostSession({
- modules: ['cognitive'],
- tasks: [{ module: 'cognitive', type: 'schulte-table', config: drill.config, drillData: drill, questions, totalMs: 5000 }],
- });
- const stored = session.tasks[0];
- expect(stored.config.level).toBe(0);
- expect(Number.isFinite(stored.accuracy)).toBe(true);
+ // ADAPTIVE PREVIEW / resolveDrillConfig PARITY — multiplication (issue #2099, fix #2)
+ //
+ // getAdaptivePreview used to always build multiplication's preview off the
+ // generic maxDigits Adaptive knob, even though resolveDrillConfig hands
+ // multiplication's difficulty entirely to the progressive ladder whenever
+ // `progressive !== false` (the default) — so the previewed maxDigits
+ // adjustment could never actually apply. This locks the two functions'
+ // multiplication branch in parity for both progressive modes.
+ // =============================================================================
+
+ describe('getAdaptivePreview — multiplication parity with resolveDrillConfig', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) return Promise.resolve({ sessions: [] });
+ return Promise.resolve(defaultValue);
+ });
+ });
+
+ it('previews the progressive ladder rung (not a maxDigits knob) when progressive is on (the default)', async () => {
+ const preview = await getAdaptivePreview();
+ const resolved = await resolveDrillConfig('multiplication', { count: 10, maxDigits: 2 });
+
+ expect(preview.drills.multiplication.ladder).toBe(true);
+ // Same rung resolveDrillConfig would actually generate a drill at.
+ expect(preview.drills.multiplication.level).toBe(resolved.progression.level);
+ expect(preview.drills.multiplication.factors).toEqual(resolved.progression.factors);
+ // The generic Adaptive maxDigits field must NOT be present — showing it
+ // would advertise an adjustment resolveDrillConfig will never apply.
+ expect(preview.drills.multiplication.field).toBeUndefined();
+ expect(preview.drills.multiplication.to).toBeUndefined();
+ });
+
+ it('previews the maxDigits Adaptive knob when progressive is turned off', async () => {
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) return Promise.resolve({ sessions: [] });
+ if (p.includes('post-config')) {
+ return Promise.resolve({ mentalMath: { drillTypes: { multiplication: { progressive: false } } } });
+ }
+ return Promise.resolve(defaultValue);
+ });
+
+ const preview = await getAdaptivePreview();
+ const resolved = await resolveDrillConfig('multiplication', { count: 10, maxDigits: 2 });
+
+ // No live adaptation without scored history, but the field/shape must
+ // match the maxDigits knob resolveDrillConfig's Adaptive branch would use
+ // — not the ladder shape.
+ expect(preview.drills.multiplication.ladder).toBeUndefined();
+ expect(preview.drills.multiplication.field).toBe('maxDigits');
+ expect(resolved.progression == null).toBe(true);
+ expect(resolved.config.maxDigits).toBe(2);
+ });
+
+ it('other math drill types are unaffected (still the generic Adaptive preview)', async () => {
+ const preview = await getAdaptivePreview();
+ expect(preview.drills['doubling-chain'].field).toBe('steps');
+ expect(preview.drills['doubling-chain'].ladder).toBeUndefined();
+ });
+ });
+
// =============================================================================
// SCORING MODEL: accuracy vs speed separation, adaptive signal, legacy fallback
// (issue #2094)
@@@ -1107,3 -1346,346 +1205,580 @@@ describe('adaptive signal is accuracy-d
expect(adaptive.applied).toBe(false);
});
});
+
+ // =============================================================================
+ // getPostStats — byModule averaging, days-window cutoff, empty-window shape,
+ // streak passthrough (issue #2102 gap 1)
+ // =============================================================================
+
+ describe('getPostStats — byModule averaging, days window cutoff, empty-window shape', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ function mockSessions(sessions) {
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ if (String(path).includes('post-sessions')) return Promise.resolve({ sessions });
+ return Promise.resolve(defaultValue);
+ });
+ }
+
+ it('averages and rounds byModule scores across multiple tasks in a session', async () => {
+ const today = new Date().toISOString().split('T')[0];
+ // The session-level `score` is deliberately a different number from the
+ // task-mean so this can't pass by mistakenly reading the session score
+ // instead of averaging byModule's own per-task scores.
+ mockSessions([
+ {
+ date: today, score: 40,
+ tasks: [
+ { module: 'mental-math', type: 'doubling-chain', score: 60 },
+ { module: 'mental-math', type: 'multiplication', score: 75 },
+ ],
+ },
+ ]);
+ const stats = await getPostStats(30);
+ // (60 + 75) / 2 = 67.5 — JS Math.round rounds .5 up to 68.
+ expect(stats.byModule['mental-math']).toBe(68);
+ });
+
+ it('includes a session dated exactly at the cutoff boundary (s.date >= cutoff), excludes the day before', async () => {
+ const days = 5;
+ const cutoff = new Date();
+ cutoff.setDate(cutoff.getDate() - days);
+ const cutoffStr = cutoff.toISOString().split('T')[0];
+ const [y, m, d] = cutoffStr.split('-').map(Number);
+ const dayBeforeStr = new Date(Date.UTC(y, m - 1, d) - 86400000).toISOString().split('T')[0];
+
+ mockSessions([
+ { date: cutoffStr, score: 100, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 100 }] },
+ { date: dayBeforeStr, score: 0, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 0 }] },
+ ]);
+ const stats = await getPostStats(days);
+ expect(stats.sessionCount).toBe(1);
+ expect(stats.overall).toBe(100);
+ });
+
+ it('returns the zeroed empty-window shape when nothing falls inside the window, but streaks still pass through from all-time history', async () => {
+ const oldDate = new Date(Date.now() - 90 * 86400000).toISOString().split('T')[0];
+ mockSessions([
+ { date: oldDate, score: 50, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 50 }] },
+ ]);
+ const stats = await getPostStats(5);
+ expect(stats.sessionCount).toBe(0);
+ expect(stats.overall).toBeNull();
+ expect(stats.byModule).toEqual({});
+ expect(stats.byDrill).toEqual({});
+ expect(stats.byDrillCount).toEqual({});
+ expect(stats.byDrillAccuracy).toEqual({});
+ expect(stats.byDrillCompletion).toEqual({});
+ // Streaks are computed over ALL history, independent of the stats window —
+ // the empty-window branch must still spread them onto the result.
+ expect(stats.lastDate).toBe(oldDate);
+ expect(stats.completedToday).toBe(false);
+ });
+
+ it('passes streak fields through unchanged alongside a non-empty window', async () => {
+ const today = new Date().toISOString().split('T')[0];
+ mockSessions([
+ { date: today, score: 80, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 80 }] },
+ ]);
+ const stats = await getPostStats(30);
+ expect(stats.completedToday).toBe(true);
+ expect(stats.currentStreak).toBe(1);
+ expect(stats.todayScore).toBe(80);
+ });
+ });
+
+ // =============================================================================
+ // resolveDrillConfig / getAdaptivePreview — adaptive integration across ALL
+ // math drill types (issue #2102 gap 3). The pure `adaptDrillConfig` policy is
+ // already exhaustively covered in postAdaptive.test.js; these tests exercise
+ // the INTEGRATION — real scored session history flowing through getPostStats
+ // -> getAdaptiveSignal -> resolveDrillConfig/getAdaptivePreview — for the
+ // three types that previously only had multiplication/doubling-chain covered.
+ // =============================================================================
+
+ describe('resolveDrillConfig — adaptive integration for serial-subtraction/powers/estimation', () => {
+ const today = new Date().toISOString().split('T')[0];
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ function mockAdaptiveSessions(type, accuracy, count = 3) {
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) {
+ return Promise.resolve({
+ sessions: [{
+ date: today,
+ score: 55,
+ tasks: Array.from({ length: count }, () => ({
+ module: 'mental-math', type, score: 55, accuracy, completion: 1, questions: [],
+ })),
+ }],
+ });
+ }
+ if (p.includes('post-config')) return Promise.resolve({ adaptive: { enabled: true } });
+ return Promise.resolve(defaultValue);
+ });
+ }
+
+ it('serial-subtraction: sustained high accuracy nudges MORE steps (harder)', async () => {
+ mockAdaptiveSessions('serial-subtraction', 1);
+ const { adaptive, config } = await resolveDrillConfig('serial-subtraction', { steps: 10 });
+ expect(adaptive.reason).toBe('harder');
+ expect(config.steps).toBeGreaterThan(10);
+ });
+
+ it('serial-subtraction: sustained low accuracy nudges FEWER steps (easier)', async () => {
+ mockAdaptiveSessions('serial-subtraction', 0);
+ const { adaptive, config } = await resolveDrillConfig('serial-subtraction', { steps: 10 });
+ expect(adaptive.reason).toBe('easier');
+ expect(config.steps).toBeLessThan(10);
+ });
+
+ it('powers: sustained high accuracy nudges a HIGHER max exponent (harder)', async () => {
+ mockAdaptiveSessions('powers', 1);
+ const { adaptive, config } = await resolveDrillConfig('powers', { maxExponent: 10 });
+ expect(adaptive.reason).toBe('harder');
+ expect(config.maxExponent).toBeGreaterThan(10);
+ });
+
+ it('powers: sustained low accuracy nudges a LOWER max exponent (easier)', async () => {
+ mockAdaptiveSessions('powers', 0);
+ const { adaptive, config } = await resolveDrillConfig('powers', { maxExponent: 10 });
+ expect(adaptive.reason).toBe('easier');
+ expect(config.maxExponent).toBeLessThan(10);
+ });
+
+ it('estimation: sustained high accuracy TIGHTENS tolerance (lower % = harder)', async () => {
+ mockAdaptiveSessions('estimation', 1);
+ const { adaptive, config } = await resolveDrillConfig('estimation', { tolerancePct: 10 });
+ expect(adaptive.reason).toBe('harder');
+ expect(config.tolerancePct).toBeLessThan(10);
+ });
+
+ it('estimation: sustained low accuracy WIDENS tolerance (higher % = easier)', async () => {
+ mockAdaptiveSessions('estimation', 0);
+ const { adaptive, config } = await resolveDrillConfig('estimation', { tolerancePct: 10 });
+ expect(adaptive.reason).toBe('easier');
+ expect(config.tolerancePct).toBeGreaterThan(10);
+ });
+
+ it('holds under the sample gate even with a perfect accuracy signal', async () => {
+ mockAdaptiveSessions('serial-subtraction', 1, 2); // 2 samples, gate is minSamples=3
+ const { adaptive, config } = await resolveDrillConfig('serial-subtraction', { steps: 10 });
+ expect(adaptive.reason).toBe('insufficient-samples');
+ expect(adaptive.applied).toBe(false);
+ expect(config.steps).toBe(10);
+ });
+ });
+
+ describe('getAdaptivePreview', () => {
+ const today = new Date().toISOString().split('T')[0];
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ it('reports enabled:false and leaves every drill unapplied when the Adaptive toggle is off', async () => {
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) return Promise.resolve({ sessions: [] });
+ if (p.includes('post-config')) return Promise.resolve({ adaptive: { enabled: false } });
+ return Promise.resolve(defaultValue);
+ });
+ const preview = await getAdaptivePreview();
+ expect(preview.enabled).toBe(false);
+ expect(preview.windowDays).toBeGreaterThan(0);
+ expect(preview.thresholds.minSamples).toBeGreaterThan(0);
+ expect(Object.keys(preview.drills)).toEqual(
+ expect.arrayContaining(['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'])
+ );
+ });
+
+ it('previews the effective per-type nudge from recent scored performance when enabled', async () => {
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) {
+ return Promise.resolve({
+ sessions: [{
+ date: today,
+ score: 55,
+ tasks: Array.from({ length: 3 }, () => ({
+ module: 'mental-math', type: 'multiplication', score: 55, accuracy: 1, completion: 1, questions: [],
+ })),
+ }],
+ });
+ }
+ if (p.includes('post-config')) {
+ return Promise.resolve({
+ adaptive: { enabled: true },
+ // progressive:false exercises the generic Adaptive nudge path — with the
+ // ladder on (default), the preview shows the ladder rung instead (see the
+ // parity describe below, issue #2099).
+ mentalMath: { drillTypes: { multiplication: { maxDigits: 2, progressive: false } } },
+ });
+ }
+ return Promise.resolve(defaultValue);
+ });
+ const preview = await getAdaptivePreview();
+ expect(preview.enabled).toBe(true);
+ expect(preview.drills.multiplication.reason).toBe('harder');
+ expect(preview.drills.multiplication.config.maxDigits).toBe(3);
+ // A type with no recent samples falls back to "not enough signal yet".
+ expect(preview.drills['doubling-chain'].reason).toBe('insufficient-samples');
+ });
+ });
+
+ // =============================================================================
+ // submitPostSession — non-memory task types recomputed server-side, session
+ // score rollup, and persistence (issue #2102 gap 7). The memory-drill branch
+ // is already covered above; this covers math/cognitive/LLM.
+ // =============================================================================
+
+ describe('submitPostSession — non-memory task types', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) return Promise.resolve({ sessions: [] });
+ if (p.includes('post-memory-items')) return Promise.resolve({ items: [] });
+ return Promise.resolve(defaultValue); // post-config.json -> baseDefaults clone
+ });
+ });
+
+ it('rescores a math task server-side, ignoring client-tampered expected/correct', async () => {
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['mental-math'],
+ tasks: [{
+ module: 'mental-math',
+ type: 'doubling-chain',
+ config: { startValue: 4, steps: 2 },
+ questions: [
+ { prompt: '4 x 2', expected: 999, answered: 8, correct: false, responseMs: 500 },
+ { prompt: '8 x 2', expected: 999, answered: 16, correct: false, responseMs: 500 },
+ ],
+ totalMs: 1000,
+ }],
+ tags: {},
+ });
+
+ const task = session.tasks[0];
+ expect(task.questions[0].expected).toBe(8);
+ expect(task.questions[0].correct).toBe(true);
+ expect(task.accuracy).toBe(1);
+ expect(task.score).toBeGreaterThan(0);
+ });
+
+ it('rescores a cognitive task server-side via scoreCognitiveDrill, ignoring client score', async () => {
+ const drillData = {
+ type: 'digit-span',
+ config: { direction: 'forward', maxLength: 5 },
+ sequences: [{ digits: [1, 2, 3], length: 3 }],
+ };
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['cognitive'],
+ tasks: [{
+ module: 'cognitive',
+ type: 'digit-span',
+ drillData,
+ questions: [{ index: 0, answered: '123', responseMs: 1000 }],
+ score: 0, // client-sent score must be ignored — server recomputes via the answer key
+ totalMs: 1000,
+ }],
+ tags: {},
+ });
+
+ const task = session.tasks[0];
+ expect(task.questions[0].correct).toBe(true);
+ expect(task.score).toBeGreaterThan(0);
+ });
+
+ it('trusts the client-computed score for LLM drill tasks (never re-scored server-side)', async () => {
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['llm-drills'],
+ tasks: [{
+ module: 'llm-drills',
+ type: 'word-association',
+ responses: [{ questionIndex: 0, response: 'church', responseMs: 3000, llmScore: 90 }],
+ score: 87,
+ totalMs: 3000,
+ }],
+ tags: {},
+ });
+ expect(session.tasks[0].score).toBe(87);
+ });
+
+ it('rolls up the session score as the mean of all task scores', async () => {
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['mental-math', 'llm-drills'],
+ tasks: [
+ {
+ module: 'mental-math', type: 'doubling-chain',
+ config: { startValue: 4, steps: 1 },
+ questions: [{ prompt: '4 x 2', answered: 8, responseMs: 500 }],
+ totalMs: 500,
+ },
+ { module: 'llm-drills', type: 'word-association', responses: [], score: 50, totalMs: 1000 },
+ ],
+ tags: {},
+ });
+ const expectedMean = Math.round((session.tasks[0].score + 50) / 2);
+ expect(session.score).toBe(expectedMean);
+ });
+
+ it('persists the computed session via atomicWrite with the durationMs/tags rollup', async () => {
+ await submitPostSession({
+ cadence: 'daily',
+ modules: ['mental-math'],
+ tasks: [{
+ module: 'mental-math', type: 'doubling-chain',
+ config: { startValue: 4, steps: 1 },
+ questions: [{ prompt: '4 x 2', answered: 8, responseMs: 500 }],
+ totalMs: 1234,
+ }],
+ tags: { mood: 'focused' },
+ });
+
+ const sessionWrite = atomicWrite.mock.calls.find(([path]) => String(path).includes('post-sessions'));
+ expect(sessionWrite).toBeTruthy();
+ const persisted = sessionWrite[1].sessions[0];
+ expect(persisted.durationMs).toBe(1234);
+ expect(persisted.tags).toEqual({ mood: 'focused' });
+ expect(persisted.id).toBeTruthy();
+ expect(persisted.date).toBeTruthy();
+ });
+ });
++
++describe('progressive cognitive drills', () => {
++ const today = new Date().toISOString().split('T')[0];
++ const oldDate = new Date(Date.now() - 60 * 86400000).toISOString().split('T')[0];
++
++ // A completed cognitive drill at `level` with a given task-level accuracy —
++ // the shape getCognitiveLevelStats buckets by (accuracy-only mastery).
++ function cognitiveSession(type, level, accuracy, date = today, count = 20) {
++ return {
++ date,
++ tasks: [{
++ module: 'cognitive',
++ type,
++ config: { level },
++ accuracy,
++ totalCount: count,
++ questions: Array.from({ length: count }, () => ({ answered: 'x' })),
++ }],
++ };
++ }
++
++ function mockSessions(sessions, configOverride) {
++ readJSONFile.mockImplementation((path, defaultValue) => {
++ const p = String(path);
++ if (p.includes('post-sessions')) return Promise.resolve({ sessions });
++ if (p.includes('post-config')) return Promise.resolve(configOverride ?? defaultValue);
++ return Promise.resolve(defaultValue);
++ });
++ }
++
++ beforeEach(() => {
++ vi.clearAllMocks();
++ });
++
++ it('starts a fresh user at n-back level 0 (1-back) and stamps the rung knobs', async () => {
++ mockSessions([]);
++ const { config, progression } = await resolveDrillConfig('n-back', { length: 20 });
++ expect(progression.level).toBe(0);
++ expect(config.level).toBe(0);
++ expect(config.n).toBe(1);
++ expect(config.stimulusMs).toBe(2500);
++ });
++
++ it('advances a cognitive rung on sustained balanced accuracy', async () => {
++ // 3 clean 1-back runs at 90% balanced accuracy → clears level 0.
++ mockSessions([
++ cognitiveSession('n-back', 0, 0.9),
++ cognitiveSession('n-back', 0, 0.92),
++ cognitiveSession('n-back', 0, 0.95),
++ ]);
++ const { config, progression } = await resolveDrillConfig('n-back', {});
++ expect(progression.level).toBe(1);
++ expect(config.n).toBe(2);
++ });
++
++ it('does not advance on high-accuracy but low-completion runs (skipped hard trials)', async () => {
++ // Answered only the easy sequence (100% accuracy) but left the rest blank —
++ // low completion must not bank a mastery sample (issue #2095 review).
++ const lowCompletion = (level, date = today) => ({
++ date,
++ tasks: [{ module: 'cognitive', type: 'digit-span', config: { level }, accuracy: 1, completion: 0.25, totalCount: 4, questions: [{ answered: '1' }] }],
++ });
++ mockSessions([lowCompletion(0), lowCompletion(0), lowCompletion(0)]);
++ const { progression } = await resolveDrillConfig('digit-span', {});
++ expect(progression.level).toBe(0);
++ });
++
++ it('does not advance when accuracy is below the mastery bar', async () => {
++ mockSessions([
++ cognitiveSession('n-back', 0, 0.6),
++ cognitiveSession('n-back', 0, 0.7),
++ cognitiveSession('n-back', 0, 0.5),
++ ]);
++ const { progression } = await resolveDrillConfig('n-back', {});
++ expect(progression.level).toBe(0);
++ });
++
++ it('never demotes below the earned floor when the window aged out', async () => {
++ mockSessions([
++ cognitiveSession('digit-span', 3, 0.9, oldDate),
++ cognitiveSession('digit-span', 3, 0.95, oldDate),
++ cognitiveSession('digit-span', 3, 0.9, oldDate),
++ ]);
++ const { progression, config } = await resolveDrillConfig('digit-span', {});
++ expect(progression.level).toBe(3);
++ expect(progression.floorLevel).toBe(3);
++ expect(config.direction).toBe('backward');
++ });
++
++ it('passes config through unchanged when the drill Progressive toggle is off', async () => {
++ mockSessions([], { cognitive: { drillTypes: { 'n-back': { progressive: false } } } });
++ const { config, progression } = await resolveDrillConfig('n-back', { n: 3, stimulusMs: 1200 });
++ expect(progression == null).toBe(true);
++ expect(config).toEqual({ n: 3, stimulusMs: 1200 });
++ });
++
++ it('reaction-time has no ladder — always passes config through', async () => {
++ mockSessions([]);
++ const { config, progression } = await resolveDrillConfig('reaction-time', { mode: 'choice' });
++ expect(progression == null).toBe(true);
++ expect(config).toEqual({ mode: 'choice' });
++ });
++
++ it('generateDrill stamps the resolved level into the generated cognitive config', async () => {
++ mockSessions([]);
++ const { config } = await resolveDrillConfig('n-back', { length: 12 });
++ const drill = generateDrill('n-back', config);
++ expect(drill.config.level).toBe(0);
++ expect(drill.config.n).toBe(1);
++ });
++
++ it('getCognitiveProgress separates per-level history (n=2 vs n=3 recoverable)', async () => {
++ mockSessions([
++ cognitiveSession('n-back', 1, 0.9),
++ cognitiveSession('n-back', 1, 0.95),
++ cognitiveSession('n-back', 1, 0.92),
++ ]);
++ const progress = await getCognitiveProgress();
++ expect(progress['n-back'].level).toBe(2); // level-1 mastered → sits on level 2
++ expect(progress['n-back'].levels[1].mastered).toBe(true);
++ expect(progress['n-back'].levels[2].mastered).toBe(false);
++ // Every laddered type reports; reaction-time is absent.
++ expect(Object.keys(progress).sort()).toEqual(['digit-span', 'mental-rotation', 'n-back', 'schulte-table', 'stroop']);
++ });
++
++ it('difficulty stamp survives submitPostSession (stored task carries config.level)', async () => {
++ mockSessions([]);
++ const { config } = await resolveDrillConfig('schulte-table', {});
++ const drill = generateDrill('schulte-table', config);
++ // Client submits the served drill's config (with level) + drillData.
++ const questions = drill.cells.map((_, i) => ({ index: i, answered: i + 1, responseMs: 500 }));
++ const session = await submitPostSession({
++ modules: ['cognitive'],
++ tasks: [{ module: 'cognitive', type: 'schulte-table', config: drill.config, drillData: drill, questions, totalMs: 5000 }],
++ });
++ const stored = session.tasks[0];
++ expect(stored.config.level).toBe(0);
++ expect(Number.isFinite(stored.accuracy)).toBe(true);
++ });
++});
++
++describe('submitPostSession — idempotent upsert by client id (issue #2098)', () => {
++ beforeEach(() => {
++ vi.clearAllMocks();
++ // A shared in-memory sessions store so a re-submit sees the first write.
++ let sessionsStore = { sessions: [] };
++ readJSONFile.mockImplementation((path, defaultValue) => {
++ const p = String(path);
++ if (p.includes('post-sessions')) return Promise.resolve(sessionsStore);
++ return Promise.resolve(defaultValue);
++ });
++ atomicWrite.mockImplementation((path, data) => {
++ if (String(path).includes('post-sessions')) sessionsStore = data;
++ return Promise.resolve(undefined);
++ });
++ });
++
++ const ID = '11111111-1111-4111-8111-111111111111';
++ const buildBody = () => ({
++ id: ID,
++ cadence: 'daily',
++ modules: ['mental-math'],
++ tasks: [{
++ module: 'mental-math',
++ type: 'doubling-chain',
++ config: { startValue: 2, steps: 1 },
++ questions: [{ prompt: '2 x 2', expected: 4, answered: 4, responseMs: 500 }],
++ totalMs: 500,
++ }],
++ tags: {},
++ });
++
++ it('re-submitting the same id upserts (no duplicate record)', async () => {
++ const first = await submitPostSession(buildBody());
++ const second = await submitPostSession(buildBody());
++ expect(first.id).toBe(ID);
++ expect(second.id).toBe(ID);
++ const lastWrite = atomicWrite.mock.calls.filter(([p]) => String(p).includes('post-sessions')).pop();
++ const stored = lastWrite[1].sessions.filter(s => s.id === ID);
++ expect(stored.length).toBe(1);
++ });
++
++ it('preserves the original date/startedAt on an idempotent re-submit (no midnight drift)', async () => {
++ const first = await submitPostSession(buildBody());
++ const second = await submitPostSession(buildBody());
++ // A retry keeps the original day + start timestamp so history ordering and
++ // streaks can't be corrupted by a re-submit that arrives later (or next day).
++ expect(second.date).toBe(first.date);
++ expect(second.startedAt).toBe(first.startedAt);
++ });
++
++ it('assigns a server uuid when the client omits an id', async () => {
++ const { id, ...noId } = buildBody();
++ const session = await submitPostSession(noId);
++ expect(session.id).toMatch(/^[0-9a-f-]{36}$/i);
++ });
++});
++
++describe('submitPostSession — memory post-processing never 500s a saved session (issue #2098)', () => {
++ beforeEach(() => {
++ vi.clearAllMocks();
++ readJSONFile.mockImplementation((path, defaultValue) => {
++ const p = String(path);
++ if (p.includes('post-memory-items')) {
++ // Malformed item (no mastery / schedule) so the mastery merge throws
++ // when it dereferences item.mastery.chunks — exercising the isolation.
++ return Promise.resolve({ items: [{ id: 'song-1', title: 'Broken' }] });
++ }
++ if (p.includes('post-sessions')) return Promise.resolve({ sessions: [] });
++ return Promise.resolve(defaultValue);
++ });
++ });
++
++ it('returns the saved session (does not throw) when memory post-processing fails', async () => {
++ const session = await submitPostSession({
++ cadence: 'daily',
++ modules: ['memory'],
++ tasks: [{
++ module: 'memory',
++ type: 'memory-sequence',
++ memoryItemId: 'song-1',
++ questions: [{ prompt: 'x', expected: 'y', answered: 'y', correct: true, responseMs: 500, chunkId: 'verse-1' }],
++ score: 100,
++ totalMs: 500,
++ }],
++ tags: {},
++ });
++ // The session itself persisted (200-equivalent) despite the memory throw.
++ expect(session).toBeTruthy();
++ const sessionWrite = atomicWrite.mock.calls.find(([p]) => String(p).includes('post-sessions'));
++ expect(sessionWrite).toBeTruthy();
++ expect(sessionWrite[1].sessions.length).toBe(1);
++ });
++});
diff --cc server/services/meatspacePostMemory.test.js
index 630f048e9d,e69603764a..37974e7cc9
--- a/server/services/meatspacePostMemory.test.js
+++ b/server/services/meatspacePostMemory.test.js
@@@ -19,8 -19,8 +19,9 @@@ import
submitPractice,
advanceScheduleFromSession,
mergeMasteryFromSession,
+ applySessionToMemoryItems,
getMastery,
+ getChunkMasteryOrder,
generateMemoryDrill,
getDueMemoryItems,
advanceSchedule,