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-2010]): advance memory schedule for POST-session drills

Adam Eivy34d1e2eb4a68
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 340322a3dd..17685c275c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -30,6 +30,7 @@
- **[issue-1993] New deterministic cognitive drills — N-Back, Digit Span, and Stroop.** POST spanned math, LLM, and memory drills but was missing classic non-LLM cognitive-training exercises. A new **Cognitive** domain adds three provider-free drills: **N-Back** (1/2/3-back working-memory matching), **Digit Span** (forward/backward sequence recall), and **Stroop** (name the ink color, not the word — attention/inhibition). Each is configurable in the Drill Configuration screen, playable in both Test and Train modes via a dedicated interactive runner, scored, and saved to your training history alongside every other drill — with **zero AI provider calls**. Scoring is recomputed server-side from the generated drill (never trusting the client) using a shared 80% accuracy + 20% speed blend, and the drills are picked up by Full POST and Quick 5 Min automatically. (Closes #1993)
- **[issue-1994] Optional daily reminder for your POST session.** POST is meant to be a daily habit, but nothing ever nudged you to actually do it. A new **Daily Reminder** toggle in the Drill Configuration screen — off by default — lets you pick a time of day; if you haven't completed a session by then, you'll get a single in-app notification reminding you, and it stays silent once you've already practiced that day. Turning it off stops all nudges immediately. No AI calls are involved, and changing the time takes effect right away without a restart. (Closes #1994)
- **[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-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)
## Media Generation
diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.js
index 4ebb57ea79..83603be3f6 100644
--- a/client/src/hooks/usePostSession.js
+++ b/client/src/hooks/usePostSession.js
@@ -1,7 +1,7 @@
import { useState, useCallback, useRef } from 'react';
import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingEntry } from '../services/api';
import toast from '../components/ui/Toast';
-import { LLM_DRILL_TYPES, DRILL_TO_DOMAIN } from '../components/meatspace/post/constants';
+import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, DRILL_TO_DOMAIN } from '../components/meatspace/post/constants';
function computeSessionScoreFromResults(results) {
if (!results.length) return 0;
@@ -98,11 +98,16 @@ export function usePostSession() {
const speedBonus = Math.max(0, 1 - avgResponseMs / timeLimitMs);
const score = Math.min(100, Math.max(0, Math.round((correctRatio * 0.8 + speedBonus * 0.2) * 100)));
+ const isMemoryDrill = MEMORY_DRILL_TYPES.includes(currentDrill.type);
const result = {
- module: 'mental-math',
+ module: isMemoryDrill ? 'memory' : 'mental-math',
type: currentDrill.type,
config: currentDrill.config,
questions: finalAnswers,
+ // Memory drills: carry the drilled item's id through to session submit so
+ // the server can map this review back to it and advance its
+ // spaced-repetition schedule (mirrors the MemoryBuilder practice flow).
+ ...(isMemoryDrill && currentDrill.memoryItemId ? { memoryItemId: currentDrill.memoryItemId } : {}),
score,
totalMs
};
diff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.js
new file mode 100644
index 0000000000..5b2b5fb680
--- /dev/null
+++ b/client/src/hooks/usePostSession.test.js
@@ -0,0 +1,128 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+
+vi.mock('../services/api', () => ({
+ generatePostDrill: vi.fn(),
+ submitPostSession: vi.fn(),
+ scorePostLlmDrill: vi.fn(),
+ submitTrainingEntry: vi.fn(),
+}));
+vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+
+import { generatePostDrill, submitPostSession } from '../services/api';
+import { usePostSession } from './usePostSession';
+
+// Covers issue #2010: a memory drill completed inside a POST session must
+// carry its memoryItemId through to the submitted task (so the server can
+// advance that item's spaced-repetition schedule) and use the `memory`
+// module — not the `mental-math` module every drill result used to be
+// tagged with regardless of type.
+
+describe('usePostSession — memory drill task shape', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('carries memoryItemId and module="memory" through to the drill result for a memory-sequence drill', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'memory-sequence',
+ memoryItemId: 'song-1',
+ memoryItemTitle: 'Test Song',
+ config: {},
+ questions: [
+ { prompt: 'line one', promptLabel: 'What comes next?', 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');
+ });
+
+ expect(result.current.drillResults).toHaveLength(1);
+ const task = result.current.drillResults[0];
+ expect(task.type).toBe('memory-sequence');
+ expect(task.module).toBe('memory');
+ expect(task.memoryItemId).toBe('song-1');
+ });
+
+ it('does not attach memoryItemId to a math drill result, and keeps module="mental-math"', 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');
+ });
+
+ expect(result.current.drillResults).toHaveLength(1);
+ const task = result.current.drillResults[0];
+ expect(task.type).toBe('doubling-chain');
+ expect(task.module).toBe('mental-math');
+ expect(task.memoryItemId).toBeUndefined();
+ });
+
+ it('omits memoryItemId on a memory drill result when the generated drill carried none', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'memory-element-flash',
+ // No memoryItemId — shouldn't happen for a real generateMemoryDrill()
+ // response, but the hook must not synthesize one.
+ 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.module).toBe('memory');
+ expect(task.memoryItemId).toBeUndefined();
+ });
+
+ it('passes memoryItemId through saveSession into the submitted payload', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'memory-sequence',
+ memoryItemId: 'song-1',
+ config: {},
+ questions: [{ prompt: 'line one', expected: 'line two', chunkId: null }],
+ });
+ submitPostSession.mockResolvedValue({ id: 'session-1', score: 100 });
+
+ const { result } = renderHook(() => usePostSession());
+
+ await act(async () => {
+ await result.current.startSession([{ type: 'memory-sequence', config: {}, timeLimitSec: 60 }]);
+ });
+ act(() => {
+ result.current.submitAnswer('line two');
+ });
+ await act(async () => {
+ await result.current.saveSession({});
+ });
+
+ expect(submitPostSession).toHaveBeenCalledTimes(1);
+ const payload = submitPostSession.mock.calls[0][0];
+ expect(payload.tasks).toHaveLength(1);
+ expect(payload.tasks[0].memoryItemId).toBe('song-1');
+ });
+});
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index 54dfb4b214..1143982ec3 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -94,6 +94,11 @@ const taskResultSchema = z.object({
questions: z.array(questionResultSchema).optional().default([]),
responses: z.array(llmResponseSchema).optional().default([]),
drillData: z.any().optional(),
+ // Memory drills: which memory item this task drilled, so the session-submit
+ // path can map the result back and advance that item's spaced-repetition
+ // schedule (mirrors the dedicated MemoryBuilder practice flow). Absent for
+ // every other drill type.
+ memoryItemId: z.string().optional(),
score: z.number().min(0).max(100).optional(),
evaluation: z.object({
score: z.number().min(0).max(100).optional(),
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index 4d958b01aa..d393d4fca0 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -12,6 +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';
const MEATSPACE_DIR = PATHS.meatspace;
const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');
@@ -178,6 +179,21 @@ export async function submitPostSession(sessionData) {
await ensureMeatspaceDir();
await atomicWrite(SESSIONS_FILE, data);
console.log(`🧪 POST session saved: score=${session.score} modules=${session.modules.join(',')}`);
+
+ // A memory drill completed inside this session IS a review — mirror the
+ // dedicated MemoryBuilder practice flow (submitPractice) and advance each
+ // 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.
+ 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));
+ }
+
return session;
}
diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.js
index 2b232dd294..c0477d19eb 100644
--- a/server/services/meatspacePost.test.js
+++ b/server/services/meatspacePost.test.js
@@ -1,4 +1,19 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock file I/O so submitPostSession tests stay pure. Shared by meatspacePost.js
+// AND meatspacePostMemory.js (imported transitively for advanceScheduleFromSession) —
+// route responses by path substring so both modules' reads/writes are covered
+// without depending on call order.
+vi.mock('../lib/fileUtils.js', () => ({
+ atomicWrite: vi.fn().mockResolvedValue(undefined),
+ // `data` is needed too — postValidation.js transitively imports
+ // meatspacePostDrillCache.js, which builds a path off PATHS.data at module load.
+ PATHS: { data: '/tmp/test-data', meatspace: '/tmp/test-meatspace' },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ readJSONFile: vi.fn((path, defaultValue) => Promise.resolve(defaultValue)),
+}));
+
+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
import {
generateDoublingChain,
generateSerialSubtraction,
@@ -8,6 +23,7 @@ import {
scoreDrill,
computeExpectedFromPrompt,
computePostStreaks,
+ submitPostSession,
} from './meatspacePost.js';
// =============================================================================
@@ -430,3 +446,98 @@ describe('computePostStreaks', () => {
expect(r.currentStreak).toBe(2);
});
});
+
+// =============================================================================
+// SUBMIT SESSION — MEMORY DRILL SCHEDULE ADVANCE (issue #2010)
+// =============================================================================
+
+describe('submitPostSession — memory drill schedule advance', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Route each readJSONFile call by path so both meatspacePost.js's own
+ // reads (config/sessions) and meatspacePostMemory.js's read (memory items,
+ // called internally by advanceScheduleFromSession) resolve sensibly
+ // regardless of call order.
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-memory-items')) {
+ return Promise.resolve({
+ items: [{
+ id: 'song-1',
+ title: 'Test Song',
+ builtin: false,
+ schedule: { ease: 2.5, intervalDays: 0, nextReview: '2026-06-01T00:00:00.000Z', lastReviewed: null },
+ mastery: { overallPct: 0, chunks: {}, elements: {} },
+ content: { lines: [{ text: 'a line' }], chunks: [] },
+ }],
+ });
+ }
+ if (p.includes('post-sessions')) {
+ return Promise.resolve({ sessions: [] });
+ }
+ // post-config.json — fall through to the default (baseDefaults clone)
+ return Promise.resolve(defaultValue);
+ });
+ });
+
+ it('advances the schedule of the memory item a POST-supported memory task references', async () => {
+ const session = 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 },
+ { prompt: 'line two', expected: 'line three', answered: 'line three', correct: true, responseMs: 500 },
+ ],
+ score: 90,
+ totalMs: 2000,
+ }],
+ tags: {},
+ });
+
+ expect(session).toBeTruthy();
+ const memoryWrite = atomicWrite.mock.calls.find(([path]) => String(path).includes('post-memory-items'));
+ expect(memoryWrite).toBeTruthy();
+ const updatedItem = memoryWrite[1].items.find(i => i.id === 'song-1');
+ expect(updatedItem.schedule.intervalDays).toBeGreaterThan(0);
+ expect(updatedItem.schedule.lastReviewed).toBeTruthy();
+ });
+
+ it('does not touch memory items for a session with no memory tasks', async () => {
+ await submitPostSession({
+ 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: {},
+ });
+
+ const memoryWrite = atomicWrite.mock.calls.find(([path]) => String(path).includes('post-memory-items'));
+ expect(memoryWrite).toBeUndefined();
+ });
+
+ it('does not advance a schedule for an unsupported memory drill type with no memoryItemId', async () => {
+ await submitPostSession({
+ cadence: 'daily',
+ modules: ['memory'],
+ tasks: [{
+ module: 'memory',
+ type: 'memory-fill-blank',
+ questions: [{ prompt: 'a ____ line', expected: 'test', answered: 'test', correct: true, responseMs: 500 }],
+ totalMs: 500,
+ }],
+ tags: {},
+ });
+
+ const memoryWrite = atomicWrite.mock.calls.find(([path]) => String(path).includes('post-memory-items'));
+ expect(memoryWrite).toBeUndefined();
+ });
+});
diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.js
index 7b0523d5cc..f7f17e4a5d 100644
--- a/server/services/meatspacePostMemory.js
+++ b/server/services/meatspacePostMemory.js
@@ -460,6 +460,34 @@ export async function submitPractice(id, practiceData) {
return { mastery: item.mastery, schedule: item.schedule, practiceId: log.entries[log.entries.length - 1].id };
}
+/**
+ * Advance a memory item's spaced-repetition schedule from a POST-session
+ * memory drill's accuracy ratio (0..1). Mirrors the schedule half of
+ * `submitPractice` — a POST-session memory drill IS a review, so it should
+ * reschedule the item and clear it from "Due Today" just like MemoryBuilder's
+ * dedicated practice flow. Unlike `submitPractice`, this does NOT touch
+ * chunk/element mastery — POST sessions don't carry the chunk/element-level
+ * result data `submitPractice` uses for that.
+ *
+ * Returns the updated schedule, or `null` when `memoryItemId` is absent or
+ * doesn't match a known item (unsupported memory drills like
+ * `memory-fill-blank` carry no memoryItemId — see POST_SUPPORTED_MEMORY_TYPES).
+ */
+export async function advanceScheduleFromSession(memoryItemId, ratio, now = new Date()) {
+ if (!memoryItemId) return null;
+ const items = await loadMemoryItems();
+ const item = items.find(i => i.id === memoryItemId);
+ if (!item) return null;
+
+ const advanced = advanceSchedule(item.schedule, ratio, now);
+ item.schedule = mergeScheduleAdvance(item.schedule, advanced, now);
+ item.updatedAt = now.toISOString();
+ await saveMemoryItems(items);
+
+ console.log(`🧠 POST session reviewed "${item.title}" → next review in ${item.schedule.intervalDays}d`);
+ return item.schedule;
+}
+
/**
* 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 2ffa70ee87..c020ed339c 100644
--- a/server/services/meatspacePostMemory.test.js
+++ b/server/services/meatspacePostMemory.test.js
@@ -9,7 +9,7 @@ tryReadFile: vi.fn().mockResolvedValue(null),
readJSONFile: vi.fn().mockResolvedValue({ items: [] }),
}));
-import { readJSONFile } from '../lib/fileUtils.js';
+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
import {
getMemoryItems,
getMemoryItem,
@@ -17,6 +17,7 @@ import {
updateMemoryItem,
deleteMemoryItem,
submitPractice,
+ advanceScheduleFromSession,
getMastery,
generateMemoryDrill,
getDueMemoryItems,
@@ -273,6 +274,62 @@ describe('submitPractice', () => {
});
});
+describe('advanceScheduleFromSession', () => {
+ const now = new Date('2026-07-01T00:00:00.000Z');
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('advances the schedule of the referenced item (a POST-session review counts like submitPractice)', async () => {
+ readJSONFile.mockResolvedValueOnce({
+ items: [{
+ ...ELEMENTS_SONG,
+ schedule: { ease: 2.5, intervalDays: 0, nextReview: now.toISOString(), lastReviewed: null },
+ }],
+ });
+
+ const schedule = await advanceScheduleFromSession('elements-song', 1, now);
+
+ expect(schedule).toBeTruthy();
+ expect(schedule.intervalDays).toBeGreaterThan(0);
+ expect(schedule.lastReviewed).toBe(now.toISOString());
+ expect(atomicWrite).toHaveBeenCalledTimes(1);
+ const [, written] = atomicWrite.mock.calls[0];
+ expect(written.items.find(i => i.id === 'elements-song').schedule).toEqual(schedule);
+ });
+
+ it('returns null and writes nothing when memoryItemId is absent', async () => {
+ const schedule = await advanceScheduleFromSession(undefined, 1, now);
+ expect(schedule).toBeNull();
+ expect(readJSONFile).not.toHaveBeenCalled();
+ 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 schedule = await advanceScheduleFromSession('does-not-exist', 1, now);
+
+ expect(schedule).toBeNull();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('resets the item to due-now on a miss-heavy review (ratio < 0.6)', async () => {
+ readJSONFile.mockResolvedValueOnce({
+ items: [{
+ ...ELEMENTS_SONG,
+ schedule: { ease: 2.5, intervalDays: 6, nextReview: now.toISOString(), lastReviewed: '2026-06-20T00:00:00.000Z' },
+ }],
+ });
+
+ const schedule = await advanceScheduleFromSession('elements-song', 0, now);
+
+ expect(schedule.intervalDays).toBe(0);
+ expect(schedule.nextReview).toBe(now.toISOString());
+ });
+});
+
// =============================================================================
// SPACED-REPETITION SCHEDULER
// =============================================================================