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 remote-tracking branch 'origin/main' into next/issue-2099

Adam Eivya6860f3a0155
diff --cc .changelog/NEXT.md
index 7d8b43e0cf,13e90f45b4..0a7a90c25b
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@@ -15,9 -18,9 +18,10 @@@
## MeatSpace POST
+- **[issue-2099] POST correctness batch: fill-blank scoring, an honest adaptive preview, weighted session scores, and fair shuffles.** Memory Fill-Blank drills now score and count toward your spaced-repetition schedule/mastery like Memory Sequence and Element Flash — a scoring-shape bug meant a fill-blank answer could never be marked correct no matter what you typed, so any fill-blank work inside a scored session was silently unrecorded (also closes #2116). The Adaptive Difficulty preview for Multiplication now matches what a session will actually generate: it shows your current progressive-ladder rung when the ladder is on (the default) instead of a "Max Digits" adjustment that could never apply. Session scoring config gained real teeth — a per-domain weight you set now actually shifts your blended session score (uniform weights, the default, score exactly as before). Memory drill generators (fill-blank, sequence recall, element flash) now use an unbiased shuffle instead of a skewed one, so which lines/elements you're drilled on is genuinely random.
- **[issue-2101] POST config & UX polish: Morse in the sidebar, config presets, keyboard-accessible history, pausable transitions.** Morse is now a full nav entry under the POST sidebar section (previously reachable only via the launcher or ⌘K). The drill config page gained one-click presets — "Balanced daily", "Math focus", "Cognitive focus", and "Everything (local-only)" — plus per-group "Enable all / Disable all" buttons on the Mental Math, Cognitive, and LLM sections (bulk-enabling LLM drills is blocked until you've picked an AI provider). History session rows now expand/collapse with the keyboard (Enter/Space), not just a mouse click. The inter-drill transition screen gained a Pause/Resume control and pauses its 3-second auto-advance countdown while you're hovering or focused on it, so you're never yanked into the next drill mid-read.
- **[issue-2097] The Wordplay tab now tracks your practice.** Completing a round of Compound Chain, Bridge Word, Double Meaning, or Idiom Twist in the standalone Wordplay tab used to score every response and then throw the result away — closing the tab meant the practice never happened. Each completed round now logs to your training history (same log the in-session drills and streak use), so Wordplay accuracy shows up in training stats and counts toward your practice streak. The standalone tab and the in-session drill runner now also share one scoring path for these four types, and a bug that always logged 0% accuracy for in-session LLM-drill training rounds (regardless of actual performance) is fixed too.
+ - **[issue-2114] Wordplay training-log entries now keep the per-question breakdown, not just the round total.** Follow-up to #2097: each completed Wordplay round — whether from the standalone Wordplay tab or a wordplay drill inside an in-session training session — previously logged only the aggregate question/correct counts. It now also stores each question's prompt/response, score, feedback, and whether it cleared the correct threshold — so a future progress dashboard can trend which individual wordplay prompts you miss. Bridge Word's persisted prompt is now the clue set it actually showed you (it previously had no readable prompt at all). Entries without a breakdown (older rows, and other training modules) remain fully valid.
- **[issue-2094] Scores now separate how *accurate* you were from how *fast* — and stop rewarding not answering.** Every scored drill now records accuracy (of the answers you actually gave), completion (how much of a timed drill you reached), and average speed as distinct numbers alongside the blended headline score, so the session and history views show accuracy and speed side by side instead of one merged figure. Running out of time on a timed drill now lowers *completion*, not accuracy — an unreached question no longer counts as wrong. Adaptive difficulty follows your accuracy (with a guard that skips adjusting when you barely started a drill), so a fast-but-sloppy run and a slow-but-careful run now push difficulty in different, correct directions. The n-back drill is rescored with proper signal-detection: never pressing now lands at ~50% (chance) instead of the old ~70% freebie, and always-pressing is penalized for its false alarms. The reaction-time drill is now scored on your median reaction speed (false starts invalidate their trial) with your best time tracked too. Older saved sessions without the new fields still display and chart correctly.
- **[issue-2093] Session results now teach from mistakes on every drill, not just AI ones.** Expanding a math, memory, or cognitive (n-back, digit-span, Stroop, Schulte table, mental rotation, reaction time) drill row on the results screen used to do nothing — only AI-scored drills showed a review. Every drill row now expands into a per-question/per-trial breakdown: a "missed items" summary up top, then a type-appropriate view — a prompt/answer/expected table for math and memory, letter-sequence hit/miss/false-alarm marks for n-back, shown-vs-recalled digits for digit span, word/ink/your-answer for Stroop, and per-trial timing with slow-response outliers flagged for the pure speed drills. Unanswered questions are shown distinctly from wrong ones. The same review now also appears when you expand a past session in History.
- **Multiplication drills now ramp up instead of starting hard.** The mental-math multiplication drill used to open at a fixed 2-digit × 2-digit difficulty (e.g. `566 × 191`) for everyone. It now climbs a mastery-gated ladder — `1×1` → `1×2` → `1×1×1` → `2×2` → … — starting at single-digit × single-digit and advancing to the next rung only after you answer a level quickly *and* accurately (≥90% correct within a per-rung speed target). The drill header and the config page show your current rung and per-level mastery. On by default; turn off "Progressive difficulty" on the Multiplication card to go back to the manual Max Digits setting.
diff --cc server/lib/postValidation.js
index 2ce9d60d18,d3ffe11a49..f3de416907
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@@ -396,6 -419,7 +431,7 @@@ export const trainingEntrySchema = z.ob
questionCount: z.number().int().min(0),
correctCount: z.number().int().min(0),
totalMs: z.number().min(0),
+ questions: z.array(trainingQuestionSchema).optional(),
});
-export { LLM_DRILL_TYPES, MATH_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES, COGNITIVE_DRILL_TYPES, MORSE_DRILL_TYPES };
+export { LLM_DRILL_TYPES, MATH_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES, POST_MODULES, COGNITIVE_DRILL_TYPES, MORSE_DRILL_TYPES };
diff --cc server/lib/postValidation.test.js
index b6a36f30d7,596f16dc57..e473620cad
--- a/server/lib/postValidation.test.js
+++ b/server/lib/postValidation.test.js
@@@ -1,5 -1,15 +1,17 @@@
import { describe, it, expect } from 'vitest';
- import { postLlmScoreRequestSchema, postConfigUpdateSchema, postSessionSubmitSchema, postDrillRequestSchema, trainingEntrySchema, LLM_DRILL_TYPES, POST_MODULES, POST_SUPPORTED_MEMORY_TYPES } from './postValidation.js';
+ import {
+ postLlmScoreRequestSchema,
+ postConfigUpdateSchema,
+ postSessionSubmitSchema,
+ postDrillRequestSchema,
+ trainingEntrySchema,
+ memoryItemCreateSchema,
+ memoryScheduleSchema,
+ memoryPracticeSchema,
+ LLM_DRILL_TYPES,
++ POST_MODULES,
++ POST_SUPPORTED_MEMORY_TYPES,
+ } from './postValidation.js';
describe('postConfigUpdateSchema llmDrills', () => {
// Regression: the config UI (PostDrillConfig.jsx) exposed only 5 of the 14
diff --cc server/services/meatspacePost.test.js
index b5936e2a26,2e634c6363..582d960657
--- a/server/services/meatspacePost.test.js
+++ b/server/services/meatspacePost.test.js
@@@ -28,8 -28,8 +28,9 @@@ import
postConfigEvents,
resolveDrillConfig,
getMultiplicationProgress,
+ getAdaptivePreview,
getPostStats,
+ getAdaptivePreview,
deriveTaskAccuracy,
deriveTaskCompletion,
} from './meatspacePost.js';
@@@ -1202,3 -1011,343 +1203,346 @@@ 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 },
- mentalMath: { drillTypes: { multiplication: { maxDigits: 2 } } },
++ // 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();
+ });
+ });