Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(issue-2016): POST-session memory drills also update chunk/element mastery

Adam Eivy1f7f45eb1689
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b340c38e53..776fe8e2c6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -33,6 +33,7 @@
- **[issue-2008] Cognitive drills (N-Back, Digit Span, Stroop) no longer show a "Time Limit" field that did nothing.** These three drills are self-paced/stimulus-driven and never counted down against it, unlike Mental Math and Wit & Memory drills, which genuinely do enforce their time limit. The dead field is removed from the Drill Configuration screen and drill summaries, along with the unreachable `stimulusMs`/`showMs` config pass-through (no UI ever set them — the drills always used their built-in pacing anyway). No behavior change to how the drills actually play. (Closes #2008)
- **[issue-2009] Hardened the N-Back / Digit Span / Stroop cognitive drills against silent scoring regressions.** The result-assembly logic that turns your answers into the `questions[]` payload the server rescores from (N-Back's off-by-one-prone target lookup, Digit Span's forward-vs-backward comparison, Stroop's ink-vs-word grading) is now covered by focused unit tests, matching the test coverage the other POST drill runners already had. No behavior change. (`client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx`, Closes #2009)
- **[issue-2010] Memory drills inside a POST session now count as a review.** Practicing a memory item (Sequence or Element Flash) as part of a scored POST session previously updated your score but never touched that item's spaced-repetition schedule — so it stayed on "Due Today" even right after you'd just reviewed it, which only the dedicated Memory Builder practice screen would clear. A POST-session memory drill now advances the item's schedule the same way MemoryBuilder practice does (a strong session pushes the next review out; a miss-heavy one resets it to due-now), so "Due Today" and the review streak stay accurate no matter which screen you practiced from. (`server/services/meatspacePost.js`, `server/services/meatspacePostMemory.js`, `client/src/hooks/usePostSession.js`, Closes #2010)
+- **[issue-2016] POST-session memory drills now also update per-chunk and per-element mastery, not just the review schedule.** Follow-up to #2010, which only advanced the spaced-repetition schedule because POST-session answers didn't carry enough detail to attribute a right/wrong answer to a specific chunk or element. A Sequence or Element Flash drill now reports which verse/chunk or which element symbol each answer was about, so finishing a POST session updates the same "Mastery" percentages and per-chunk/per-element accuracy shown in Memory Builder — just like practicing directly there. (`client/src/hooks/usePostSession.js`, `server/services/meatspacePost.js`, `server/services/meatspacePostMemory.js`, `server/lib/postValidation.js`, Closes #2016)
- **[issue-2006] Three more Cognitive drills — Schulte Table, Mental Rotation, and Reaction Time.** Rounds out the Cognitive domain from #1993 with the three follow-up exercises: **Schulte Table** (scan a shuffled numbered grid and tap 1, 2, 3... in order — visual attention and scan speed), **Mental Rotation** (pick which of four shapes is the reference shape rotated, not mirrored — spatial reasoning), and **Reaction Time** (simple or choice reaction-time baseline, with a false-start penalty for jumping the gun). All three are configurable, playable in Test and Train modes, scored, and saved to your training history alongside the rest of POST — with zero AI provider calls, same as the rest of the Cognitive domain.
## Media Generation
diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.js
index 83603be3f6..20d6f3000f 100644
--- a/client/src/hooks/usePostSession.js
+++ b/client/src/hooks/usePostSession.js
@@ -27,6 +27,18 @@ function computeSessionScoreFromResults(results) {
return Math.round(results.reduce((s, r) => s + (r.score || 0), 0) / results.length);
}
+// Memory drill questions carry chunk/element attribution the server needs to
+// bucket mastery bookkeeping (item.mastery.chunks / item.mastery.elements) —
+// chunkId on memory-sequence questions (via findChunkForLine), element on
+// memory-element-flash questions. Non-memory questions never have these, so
+// this only adds fields when present rather than sending explicit nulls.
+function memoryAttribution(q) {
+ const attrs = {};
+ if (q?.chunkId != null) attrs.chunkId = q.chunkId;
+ if (q?.element != null) attrs.element = q.element;
+ return attrs;
+}
+
// States: idle → loading → drilling → between-drills → complete → saving → saved
const STATES = {
IDLE: 'idle',
@@ -162,7 +174,8 @@ export function usePostSession() {
expected: q.expected,
answered,
correct,
- responseMs
+ responseMs,
+ ...memoryAttribution(q)
};
const newAnswers = [...answers, answer];
@@ -228,7 +241,8 @@ export function usePostSession() {
expected: q.expected,
answered: null,
correct: false,
- responseMs: 0
+ responseMs: 0,
+ ...memoryAttribution(q)
}));
const finalAnswers = [...answers, ...remaining];
diff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.js
index 5b2b5fb680..64ce0d4471 100644
--- a/client/src/hooks/usePostSession.test.js
+++ b/client/src/hooks/usePostSession.test.js
@@ -126,3 +126,132 @@ describe('usePostSession — memory drill task shape', () => {
expect(payload.tasks[0].memoryItemId).toBe('song-1');
});
});
+
+// Covers issue #2016: a memory-sequence/memory-element-flash question's
+// chunkId/element must survive into the submitted answer so the server can
+// merge chunk/element mastery (mergeMasteryFromSession), not just advance the
+// SR schedule. Deferred out of #2010 because the answer-building in
+// submitAnswer used to strip the question down to a fixed field set.
+
+describe('usePostSession — memory drill chunk/element attribution (#2016)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('preserves chunkId onto the answer for a memory-sequence question', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'memory-sequence',
+ memoryItemId: 'song-1',
+ config: {},
+ questions: [
+ { prompt: 'line one', promptLabel: 'What comes next?', expected: 'line two', chunkId: 'verse-1' },
+ ],
+ });
+
+ const { result } = renderHook(() => usePostSession());
+
+ await act(async () => {
+ await result.current.startSession([{ type: 'memory-sequence', config: {}, timeLimitSec: 60 }]);
+ });
+ act(() => {
+ result.current.submitAnswer('line two');
+ });
+
+ const task = result.current.drillResults[0];
+ expect(task.questions[0].chunkId).toBe('verse-1');
+ expect(task.questions[0].element).toBeUndefined();
+ });
+
+ it('preserves element onto the answer for a memory-element-flash question', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'memory-element-flash',
+ memoryItemId: 'elements-song',
+ config: {},
+ questions: [{ prompt: 'H', promptLabel: 'Element name?', expected: 'Hydrogen', element: 'H' }],
+ });
+
+ const { result } = renderHook(() => usePostSession());
+
+ await act(async () => {
+ await result.current.startSession([{ type: 'memory-element-flash', config: {}, timeLimitSec: 60 }]);
+ });
+ act(() => {
+ result.current.submitAnswer('Hydrogen');
+ });
+
+ const task = result.current.drillResults[0];
+ expect(task.questions[0].element).toBe('H');
+ expect(task.questions[0].chunkId).toBeUndefined();
+ });
+
+ it('does not attach chunkId/element to a math drill answer', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'doubling-chain',
+ config: { startValue: 2, steps: 1 },
+ questions: [{ prompt: '2 x 2', expected: 4 }],
+ });
+
+ const { result } = renderHook(() => usePostSession());
+
+ await act(async () => {
+ await result.current.startSession([{ type: 'doubling-chain', config: {}, timeLimitSec: 60 }]);
+ });
+ act(() => {
+ result.current.submitAnswer('4');
+ });
+
+ const task = result.current.drillResults[0];
+ expect(task.questions[0].chunkId).toBeUndefined();
+ expect(task.questions[0].element).toBeUndefined();
+ });
+
+ it('omits chunkId when a question carries a null chunkId (no matching chunk found)', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'memory-sequence',
+ memoryItemId: 'song-1',
+ config: {},
+ questions: [{ prompt: 'line one', expected: 'line two', chunkId: null }],
+ });
+
+ const { result } = renderHook(() => usePostSession());
+
+ await act(async () => {
+ await result.current.startSession([{ type: 'memory-sequence', config: {}, timeLimitSec: 60 }]);
+ });
+ act(() => {
+ result.current.submitAnswer('line two');
+ });
+
+ const task = result.current.drillResults[0];
+ expect(task.questions[0]).not.toHaveProperty('chunkId');
+ });
+
+ it('preserves chunkId on a timed-out (skipped) question via timeExpired', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'memory-sequence',
+ memoryItemId: 'song-1',
+ config: {},
+ questions: [
+ { prompt: 'line one', expected: 'line two', chunkId: 'verse-1' },
+ { prompt: 'line two', expected: 'line three', chunkId: 'verse-1' },
+ ],
+ });
+
+ const { result } = renderHook(() => usePostSession());
+
+ await act(async () => {
+ await result.current.startSession([{ type: 'memory-sequence', config: {}, timeLimitSec: 60 }]);
+ });
+ // Time expires before any answer is submitted — both questions become
+ // unanswered/incorrect but should still carry chunkId for mastery merge.
+ act(() => {
+ result.current.timeExpired();
+ });
+
+ const task = result.current.drillResults[0];
+ expect(task.questions).toHaveLength(2);
+ expect(task.questions[0].chunkId).toBe('verse-1');
+ expect(task.questions[1].chunkId).toBe('verse-1');
+ expect(task.questions[0].correct).toBe(false);
+ });
+});
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index e620f031b1..ee3464c9a9 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -29,7 +29,14 @@ const questionResultSchema = z.object({
responseMs: z.number().min(0),
// Reaction-time drill only: player pressed before the stimulus appeared.
// Always scored wrong server-side regardless of any client-supplied correct.
- falseStart: z.boolean().optional()
+ falseStart: z.boolean().optional(),
+ // Memory drill questions only: which chunk (memory-sequence) / element
+ // (memory-element-flash) this answer attributes to, so submitPostSession can
+ // merge per-chunk/per-element mastery (mergeMasteryFromSession in
+ // meatspacePostMemory.js) the same way MemoryBuilder's submitPractice does.
+ // Absent for math/LLM/cognitive drills.
+ chunkId: z.string().nullable().optional(),
+ element: z.string().nullable().optional()
});
// LLM drill response (text-based)
diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.js
index 21934952b4..41543ee339 100644
--- a/server/lib/postValidation.test.js
+++ b/server/lib/postValidation.test.js
@@ -87,6 +87,68 @@ describe('Morse drill types stay scoped to the training log', () => {
});
});
+describe('questionResultSchema chunkId/element (issue #2016)', () => {
+ // Regression: memory-sequence/memory-element-flash answers must carry
+ // chunkId/element through postSessionSubmitSchema so submitPostSession can
+ // merge chunk/element mastery (mergeMasteryFromSession) — Zod's default
+ // strip mode would otherwise silently drop these fields.
+ it('accepts and preserves chunkId on a memory-sequence question', () => {
+ const parsed = postSessionSubmitSchema.parse({
+ modules: ['memory'],
+ tasks: [{
+ module: 'memory',
+ type: 'memory-sequence',
+ memoryItemId: 'song-1',
+ questions: [{ prompt: 'line one', expected: 'line two', answered: 'line two', correct: true, responseMs: 500, chunkId: 'verse-1' }],
+ totalMs: 500
+ }]
+ });
+ expect(parsed.tasks[0].questions[0].chunkId).toBe('verse-1');
+ });
+
+ it('accepts and preserves element on a memory-element-flash question', () => {
+ const parsed = postSessionSubmitSchema.parse({
+ modules: ['memory'],
+ tasks: [{
+ module: 'memory',
+ type: 'memory-element-flash',
+ memoryItemId: 'elements-song',
+ questions: [{ prompt: 'H', expected: 'Hydrogen', answered: 'Hydrogen', correct: true, responseMs: 300, element: 'H' }],
+ totalMs: 300
+ }]
+ });
+ expect(parsed.tasks[0].questions[0].element).toBe('H');
+ });
+
+ it('accepts a question with neither chunkId nor element (math/LLM/cognitive drills)', () => {
+ const parsed = postSessionSubmitSchema.parse({
+ modules: ['mental-math'],
+ tasks: [{
+ module: 'mental-math',
+ type: 'doubling-chain',
+ questions: [{ prompt: '2 x 2', expected: 4, answered: 4, responseMs: 200 }],
+ totalMs: 200
+ }]
+ });
+ expect(parsed.tasks[0].questions[0].chunkId).toBeUndefined();
+ expect(parsed.tasks[0].questions[0].element).toBeUndefined();
+ });
+
+ it('accepts a null chunkId (question with no matching chunk)', () => {
+ const parsed = postSessionSubmitSchema.parse({
+ modules: ['memory'],
+ tasks: [{
+ module: 'memory',
+ type: 'memory-sequence',
+ memoryItemId: 'song-1',
+ questions: [{ prompt: 'line one', expected: 'line two', answered: null, correct: false, responseMs: 500, chunkId: null }],
+ totalMs: 500
+ }]
+ });
+ expect(parsed.tasks[0].questions[0].chunkId).toBeNull();
+ });
+});
+
describe('postLlmScoreRequestSchema', () => {
// Regression: Zod's default strip mode dropped `questionIndex` from each
// response, so the server scorer fell back to the response-array index
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index 30d9ae8ee8..e4838129a6 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -12,7 +12,7 @@ import { deepMerge, isPlainObject } from '../lib/objects.js';
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 { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } from './meatspacePostCognitive.js';
-import { advanceScheduleFromSession } from './meatspacePostMemory.js';
+import { advanceScheduleFromSession, mergeMasteryFromSession } from './meatspacePostMemory.js';
const MEATSPACE_DIR = PATHS.meatspace;
const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');
@@ -188,20 +188,24 @@ export async function submitPostSession(sessionData) {
// drilled item's spaced-repetition schedule, so it reschedules and clears
// from "Due Today" just like a direct MemoryBuilder practice session would.
// Ratio comes from raw correctness (not `score`, which also folds in a speed
- // bonus) to match the accuracy signal `advanceSchedule` expects. (Chunk/element
- // MASTERY is not updated here — POST-session answers don't carry that
- // granularity yet; tracked as a follow-up in #2016.)
- // Sequential, not Promise.all: advanceScheduleFromSession does a full
- // read-modify-write of the shared memory-items file with no write queue, so
- // two tasks referencing items resolved concurrently could race and drop an
- // update (last write wins). A session rarely has more than 1-2 memory tasks,
- // so the latency cost of awaiting each is negligible.
+ // bonus) to match the accuracy signal `advanceSchedule` expects. Chunk/element
+ // MASTERY is also merged (mergeMasteryFromSession) using the chunkId/element
+ // attribution usePostSession.js's submitAnswer now preserves per-question —
+ // the other half of submitPractice's bookkeeping, deferred out of #2010 into
+ // #2016 until the client carried that attribution.
+ // Sequential, not Promise.all: advanceScheduleFromSession/mergeMasteryFromSession
+ // each do a full read-modify-write of the shared memory-items file with no
+ // write queue, so two tasks (or two calls for the same task) resolved
+ // concurrently could race and drop an update (last write wins). A session
+ // rarely has more than 1-2 memory tasks, so the latency cost of awaiting
+ // each is negligible.
for (const task of rescoredTasks) {
if (!POST_SUPPORTED_MEMORY_TYPES.includes(task.type) || !task.memoryItemId) continue;
const total = task.questions?.length || 0;
const correct = task.questions?.filter(q => q.correct).length || 0;
const ratio = total ? correct / total : 0;
await advanceScheduleFromSession(task.memoryItemId, ratio, new Date(now));
+ await mergeMasteryFromSession(task.memoryItemId, task.questions, new Date(now));
}
return session;
diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.js
index c0477d19eb..d53bf52f51 100644
--- a/server/services/meatspacePost.test.js
+++ b/server/services/meatspacePost.test.js
@@ -448,7 +448,7 @@ describe('computePostStreaks', () => {
});
// =============================================================================
-// SUBMIT SESSION — MEMORY DRILL SCHEDULE ADVANCE (issue #2010)
+// SUBMIT SESSION — MEMORY DRILL SCHEDULE ADVANCE + MASTERY MERGE (#2010, #2016)
// =============================================================================
describe('submitPostSession — memory drill schedule advance', () => {
@@ -506,6 +506,55 @@ describe('submitPostSession — memory drill schedule advance', () => {
expect(updatedItem.schedule.lastReviewed).toBeTruthy();
});
+ it('merges chunk/element mastery from per-question attribution alongside the schedule advance (issue #2016)', async () => {
+ await submitPostSession({
+ cadence: 'daily',
+ modules: ['memory'],
+ tasks: [{
+ module: 'memory',
+ type: 'memory-sequence',
+ memoryItemId: 'song-1',
+ questions: [
+ { prompt: 'line one', expected: 'line two', answered: 'line two', correct: true, responseMs: 500, chunkId: 'verse-1' },
+ { prompt: 'line two', expected: 'line three', answered: null, correct: false, responseMs: 500, chunkId: 'verse-1' },
+ ],
+ score: 50,
+ totalMs: 2000,
+ }],
+ tags: {},
+ });
+
+ const memoryWrites = atomicWrite.mock.calls.filter(([path]) => String(path).includes('post-memory-items'));
+ // One write for the schedule advance, one for the mastery merge.
+ expect(memoryWrites.length).toBe(2);
+ const masteryWrite = memoryWrites[memoryWrites.length - 1];
+ const updatedItem = masteryWrite[1].items.find(i => i.id === 'song-1');
+ expect(updatedItem.mastery.chunks['verse-1']).toEqual({ correct: 1, attempts: 2, lastPracticed: expect.any(String) });
+ });
+
+ it('buckets memory-element-flash answers into element mastery via the element attribution', async () => {
+ await submitPostSession({
+ cadence: 'daily',
+ modules: ['memory'],
+ tasks: [{
+ module: 'memory',
+ type: 'memory-element-flash',
+ memoryItemId: 'song-1',
+ questions: [
+ { prompt: 'Hydrogen', expected: 'H', answered: 'H', correct: true, responseMs: 400, element: 'H' },
+ ],
+ score: 100,
+ totalMs: 400,
+ }],
+ tags: {},
+ });
+
+ const memoryWrites = atomicWrite.mock.calls.filter(([path]) => String(path).includes('post-memory-items'));
+ const masteryWrite = memoryWrites[memoryWrites.length - 1];
+ const updatedItem = masteryWrite[1].items.find(i => i.id === 'song-1');
+ expect(updatedItem.mastery.elements.H).toEqual({ correct: 1, attempts: 1 });
+ });
+
it('does not touch memory items for a session with no memory tasks', async () => {
await submitPostSession({
cadence: 'daily',
diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.js
index f7f17e4a5d..5ee39f07c4 100644
--- a/server/services/meatspacePostMemory.js
+++ b/server/services/meatspacePostMemory.js
@@ -488,6 +488,59 @@ export async function advanceScheduleFromSession(memoryItemId, ratio, now = new
return item.schedule;
}
+/**
+ * Merge a POST session's per-question memory drill results into an item's
+ * chunk/element mastery (`item.mastery.chunks`/`item.mastery.elements`) —
+ * the mastery half of what `submitPractice` does, deferred out of #2010
+ * (schedule-only) into #2016 because POST-session answers didn't carry
+ * chunk/element attribution until `usePostSession.js`'s `submitAnswer` started
+ * preserving `q.chunkId` / `q.element` onto each answer.
+ *
+ * Unlike `submitPractice` (one `chunkId` for the whole batch — a dedicated
+ * chunk-practice session), a POST-session memory-sequence drill can span
+ * several chunks and a memory-element-flash drill spans several elements, so
+ * this buckets PER-QUESTION by whichever attribution that question carries.
+ * Questions with neither `chunkId` nor `element` (e.g. an unsupported/legacy
+ * shape) are counted toward correctness of nothing — they simply don't shift
+ * `item.mastery`.
+ *
+ * Returns the updated mastery, or `null` when `memoryItemId`/`questions` are
+ * absent or the id doesn't match a known item.
+ */
+export async function mergeMasteryFromSession(memoryItemId, questions, now = new Date()) {
+ if (!memoryItemId || !Array.isArray(questions) || !questions.length) return null;
+ const items = await loadMemoryItems();
+ const item = items.find(i => i.id === memoryItemId);
+ if (!item) return null;
+
+ const nowIso = now.toISOString();
+ for (const q of questions) {
+ if (q.chunkId) {
+ if (!item.mastery.chunks[q.chunkId]) {
+ item.mastery.chunks[q.chunkId] = { correct: 0, attempts: 0, lastPracticed: null };
+ }
+ const chunk = item.mastery.chunks[q.chunkId];
+ chunk.attempts += 1;
+ if (q.correct) chunk.correct += 1;
+ chunk.lastPracticed = nowIso;
+ }
+ if (q.element) {
+ if (!item.mastery.elements[q.element]) {
+ item.mastery.elements[q.element] = { correct: 0, attempts: 0 };
+ }
+ item.mastery.elements[q.element].attempts += 1;
+ if (q.correct) item.mastery.elements[q.element].correct += 1;
+ }
+ }
+
+ item.mastery.overallPct = computeOverallMastery(item);
+ item.updatedAt = nowIso;
+ await saveMemoryItems(items);
+
+ console.log(`🧠 POST session mastery merged: "${item.title}" ${questions.length} answers → ${item.mastery.overallPct}% overall`);
+ return item.mastery;
+}
+
/**
* List memory items currently due for review (`nextReview <= now`), sorted by
* how overdue they are (most overdue first).
diff --git a/server/services/meatspacePostMemory.test.js b/server/services/meatspacePostMemory.test.js
index c020ed339c..05ae014219 100644
--- a/server/services/meatspacePostMemory.test.js
+++ b/server/services/meatspacePostMemory.test.js
@@ -18,6 +18,7 @@ import {
deleteMemoryItem,
submitPractice,
advanceScheduleFromSession,
+ mergeMasteryFromSession,
getMastery,
generateMemoryDrill,
getDueMemoryItems,
@@ -330,6 +331,125 @@ describe('advanceScheduleFromSession', () => {
});
});
+describe('mergeMasteryFromSession', () => {
+ const now = new Date('2026-07-01T00:00:00.000Z');
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns null and writes nothing when memoryItemId is absent', async () => {
+ const result = await mergeMasteryFromSession(undefined, [{ chunkId: 'verse-1', correct: true }], now);
+ expect(result).toBeNull();
+ expect(readJSONFile).not.toHaveBeenCalled();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('returns null and writes nothing when questions is empty or absent', async () => {
+ expect(await mergeMasteryFromSession('elements-song', [], now)).toBeNull();
+ expect(await mergeMasteryFromSession('elements-song', undefined, now)).toBeNull();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('returns null and writes nothing when the item id does not match any item', async () => {
+ readJSONFile.mockResolvedValueOnce({ items: [{ ...ELEMENTS_SONG }] });
+ const result = await mergeMasteryFromSession('does-not-exist', [{ chunkId: 'verse-1', correct: true }], now);
+ expect(result).toBeNull();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('buckets per-question chunk attribution (memory-sequence) into chunk mastery', async () => {
+ readJSONFile.mockResolvedValueOnce({
+ items: [{
+ ...ELEMENTS_SONG,
+ mastery: { overallPct: 0, chunks: {}, elements: {} },
+ }],
+ });
+
+ const result = await mergeMasteryFromSession('elements-song', [
+ { chunkId: 'verse-1', correct: true },
+ { chunkId: 'verse-1', correct: false },
+ { chunkId: 'verse-2', correct: true },
+ ], now);
+
+ expect(result.chunks['verse-1']).toEqual({ correct: 1, attempts: 2, lastPracticed: now.toISOString() });
+ expect(result.chunks['verse-2']).toEqual({ correct: 1, attempts: 1, lastPracticed: now.toISOString() });
+ expect(atomicWrite).toHaveBeenCalledTimes(1);
+ });
+
+ it('buckets per-question element attribution (memory-element-flash) into element mastery', async () => {
+ readJSONFile.mockResolvedValueOnce({
+ items: [{
+ ...ELEMENTS_SONG,
+ mastery: { overallPct: 0, chunks: {}, elements: {} },
+ }],
+ });
+
+ const result = await mergeMasteryFromSession('elements-song', [
+ { element: 'H', correct: true },
+ { element: 'H', correct: true },
+ { element: 'He', correct: false },
+ ], now);
+
+ expect(result.elements.H).toEqual({ correct: 2, attempts: 2 });
+ expect(result.elements.He).toEqual({ correct: 0, attempts: 1 });
+ });
+
+ it('accumulates onto existing mastery counts rather than overwriting them', async () => {
+ readJSONFile.mockResolvedValueOnce({
+ items: [{
+ ...ELEMENTS_SONG,
+ mastery: {
+ overallPct: 0,
+ chunks: { 'verse-1': { correct: 2, attempts: 3, lastPracticed: '2026-06-01T00:00:00.000Z' } },
+ elements: {},
+ },
+ }],
+ });
+
+ const result = await mergeMasteryFromSession('elements-song', [
+ { chunkId: 'verse-1', correct: true },
+ ], now);
+
+ expect(result.chunks['verse-1']).toEqual({ correct: 3, attempts: 4, lastPracticed: now.toISOString() });
+ });
+
+ it('ignores questions with neither chunkId nor element', async () => {
+ readJSONFile.mockResolvedValueOnce({
+ items: [{
+ ...ELEMENTS_SONG,
+ mastery: { overallPct: 0, chunks: {}, elements: {} },
+ }],
+ });
+
+ const result = await mergeMasteryFromSession('elements-song', [
+ { correct: true },
+ ], now);
+
+ expect(result.chunks).toEqual({});
+ expect(result.elements).toEqual({});
+ });
+
+ it('recomputes overallPct after merging', async () => {
+ readJSONFile.mockResolvedValueOnce({
+ items: [{
+ ...ELEMENTS_SONG,
+ mastery: { overallPct: 0, chunks: {}, elements: {} },
+ }],
+ });
+
+ // 3 correct/3 attempts >= 0.8 accuracy threshold with >=3 attempts marks
+ // element mastered per computeOverallMastery's elements-song branch.
+ const result = await mergeMasteryFromSession('elements-song', [
+ { element: 'H', correct: true },
+ { element: 'H', correct: true },
+ { element: 'H', correct: true },
+ ], now);
+
+ expect(result.overallPct).toBeGreaterThan(0);
+ });
+});
+
// =============================================================================
// SPACED-REPETITION SCHEDULER
// =============================================================================