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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-2099]): POST correctness batch — fill-blank scoring, adaptive preview parity, weighted scores, dead code, shuffles
Adam Eivy5947c2fd6186
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e4bdf09513..7d8b43e0cf 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -15,6 +15,7 @@## 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-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.diff --git a/client/src/components/meatspace/post/PostDrillRunner.jsx b/client/src/components/meatspace/post/PostDrillRunner.jsxindex 82feab44de..80258b5403 100644--- a/client/src/components/meatspace/post/PostDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostDrillRunner.jsx@@ -81,7 +81,9 @@ export default function PostDrillRunner({ session }) {if (state !== 'drilling' || !currentDrill) return null;const question = currentDrill.questions?.[currentQuestionIndex];- const isTextDrill = MEMORY_DRILL_TYPES.includes(currentDrill.type) || currentDrill.type === 'memory-fill-blank';+ // MEMORY_DRILL_TYPES now includes 'memory-fill-blank' (issue #2099/#2116),+ // so the explicit extra check this used to need is gone.+ const isTextDrill = MEMORY_DRILL_TYPES.includes(currentDrill.type);const timePct = timeLimitMs > 0 ? (timeLeft / timeLimitMs) * 100 : 0;const progressPct = totalQuestions > 0 ? ((currentQuestionIndex + 1) / totalQuestions) * 100 : 0;diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.jsindex 457c3e8ab7..02f42544a8 100644--- a/client/src/components/meatspace/post/constants.js+++ b/client/src/components/meatspace/post/constants.js@@ -1,11 +1,18 @@export const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay', 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist', 'what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'];-export const MEMORY_DRILL_TYPES = ['memory-sequence', 'memory-element-flash'];+// Mirrors the server's POST_SUPPORTED_MEMORY_TYPES (server/lib/postValidation.js)+// — all three memory drill types are now fully scored in a POST session (issue+// #2099/#2116): usePostSession.finishDrill uses this to tag the result's+// module as `memory` (not `mental-math`) and preserve memoryItemId so the+// server's schedule/mastery advancement fires.+export const MEMORY_DRILL_TYPES = ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'];// Deterministic cognitive drills (no LLM). Mirror the server's// COGNITIVE_DRILL_TYPES in server/services/meatspacePostCognitive.js.export const COGNITIVE_DRILL_TYPES = ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'];-// Drill types valid elsewhere but not yet supported by the POST runner.-// These use answers[] arrays instead of expected and need dedicated runners.+// Drill types valid elsewhere but not yet wired into the interactive POST+// session drill picker (DOMAINS.memory.drillTypes below) — memory-fill-blank's+// scoring path is fully correct now (see MEMORY_DRILL_TYPES above), it just+// isn't one of the types PostSessionLauncher offers to pick from yet.export const POST_UNSUPPORTED_DRILL_TYPES = ['memory-fill-blank'];// The four wordplay drill types with a dedicated standalone trainerdiff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex c38892a5b5..f772543256 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -154,7 +154,13 @@ export function usePostSession() {if (hasFillBlankAnswers) {answered = value;const normalized = value !== null ? String(value).toLowerCase().trim() : '';- correct = q.answers.some(a => String(a).toLowerCase().trim() === normalized);+ // q.answers holds ACCEPTABLE-WORD OBJECTS ({ index, word, element }), not+ // scalars — comparing via String(a) on an object always produced+ // "[object Object]" so this could never match, silently scoring every+ // fill-blank answer wrong (issue #2116). Compare against the object's+ // `.word` (falling back to the raw value for a plain-string entry, for+ // forward/backward compatibility with any other producer).+ correct = q.answers.some(a => String(a?.word ?? a).toLowerCase().trim() === normalized);} else if (isTextAnswer) {answered = value;correct = value !== null && String(value).toLowerCase().trim() === String(q.expected).toLowerCase().trim();diff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.jsindex 2bcd96337e..245a15622a 100644--- a/client/src/hooks/usePostSession.test.js+++ b/client/src/hooks/usePostSession.test.js@@ -256,6 +256,87 @@ describe('usePostSession — memory drill chunk/element attribution (#2016)', ()});});+// Covers issue #2116: generateFillBlank questions carry acceptable answers as+// `answers[]` OBJECTS ({ index, word, element }), not scalar strings.+// submitAnswer's fill-blank branch used to compare via `String(a)` on each+// object, which always stringifies to "[object Object]" — so a fill-blank+// answer could never be marked correct no matter what the user typed. It must+// now compare against each acceptable answer's `.word`.+describe('usePostSession — memory-fill-blank scoring (issue #2099/#2116)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ function fillBlankDrill(answers) {+ return {+ type: 'memory-fill-blank',+ memoryItemId: 'song-1',+ config: {},+ questions: [{+ prompt: 'The ____ fox',+ fullText: 'The quick fox',+ expected: answers[0]?.word ?? null,+ answers,+ chunkId: 'verse-1',+ }],+ };+ }++ it('marks a fill-blank answer correct when it matches an acceptable answer word', async () => {+ generatePostDrill.mockResolvedValue(+ fillBlankDrill([{ index: 1, word: 'quick', element: null }])+ );++ const { result } = renderHook(() => usePostSession());+ await act(async () => {+ await result.current.startSession([{ type: 'memory-fill-blank', config: {}, timeLimitSec: 60 }]);+ });+ act(() => {+ result.current.submitAnswer('quick');+ });++ const task = result.current.drillResults[0];+ expect(task.questions[0].correct).toBe(true);+ expect(task.module).toBe('memory');+ expect(task.memoryItemId).toBe('song-1');+ });++ it('is case/whitespace-insensitive, matching any of several acceptable blanked words', async () => {+ generatePostDrill.mockResolvedValue(+ fillBlankDrill([+ { index: 1, word: 'quick', element: null },+ { index: 2, word: 'fox', element: null },+ ])+ );++ const { result } = renderHook(() => usePostSession());+ await act(async () => {+ await result.current.startSession([{ type: 'memory-fill-blank', config: {}, timeLimitSec: 60 }]);+ });+ act(() => {+ result.current.submitAnswer(' FOX ');+ });++ expect(result.current.drillResults[0].questions[0].correct).toBe(true);+ });++ it('marks a fill-blank answer incorrect when it matches none of the acceptable words', async () => {+ generatePostDrill.mockResolvedValue(+ fillBlankDrill([{ index: 1, word: 'quick', element: null }])+ );++ const { result } = renderHook(() => usePostSession());+ await act(async () => {+ await result.current.startSession([{ type: 'memory-fill-blank', config: {}, timeLimitSec: 60 }]);+ });+ act(() => {+ result.current.submitAnswer('slow');+ });++ expect(result.current.drillResults[0].questions[0].correct).toBe(false);+ });+});+describe('usePostSession — LLM training-log correctCount (issue #2097)', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/docs/features/post.md b/docs/features/post.mdindex 32fa3e5528..9ae8b27dc0 100644--- a/docs/features/post.md+++ b/docs/features/post.md@@ -12,7 +12,7 @@ Six drill domains, each individually enable/disable-able (`client/src/components`doubling-chain` (sequential doubling from a seed), `serial-subtraction` (countdown by a fixed subtrahend), `multiplication` (random N-digit problems), `powers` (base^exponent), `estimation` (approximate large arithmetic within tolerance).### Memory (~90s)-Memory Builder drills drawn from the user's memory items: `memory-sequence`, `memory-element-flash`, and `memory-fill-blank`, practiced in the standalone Memory Builder (see below). The server's scored-session rescoring accepts `memory-sequence`/`memory-element-flash` (`POST_SUPPORTED_MEMORY_TYPES`), but the session launcher currently composes scored sessions from the math, wordplay/verbal/imagination (LLM), and cognitive domains only — memory training runs separately.+Memory Builder drills drawn from the user's memory items: `memory-sequence`, `memory-element-flash`, and `memory-fill-blank`, practiced in the standalone Memory Builder (see below). The server's scored-session rescoring accepts all three types (`POST_SUPPORTED_MEMORY_TYPES`, issue #2099), but the session launcher currently composes scored sessions from the math, wordplay/verbal/imagination (LLM), and cognitive domains only — memory training runs separately (`memory-fill-blank` isn't yet one of the types `DOMAINS.memory.drillTypes` offers to pick from).### Wordplay (~60s)`pun-wordplay` and `word-association`, plus the cacheable wordplay set: `compound-chain`, `bridge-word`, `double-meaning`, `idiom-twist`. All LLM-scored.@@ -57,11 +57,11 @@ Configurable memory training for songs, poems, sequences, speeches, or any order- **Math**: server-rescored — the server strips client-provided correctness and re-derives expected answers (`meatspacePost.js`, "never trust client-provided expected"); estimation compares within tolerance. Accuracy plus speed bonus.- **Cognitive**: deterministic server-side rescoring per drill type.- **Wordplay/Verbal/Imagination**: LLM-scored against per-drill rubrics (e.g. wit-comeback: humor 40% / cleverness 30% / relevance 30%), blended as quality 80% + speed bonus 20% (`server/services/meatspacePostLlm.js`).-- **Session score**: plain arithmetic mean across completed drills (`computeSessionScore`).+- **Session score**: per-module weighted mean across completed drills (`computeSessionScore`, weights from `config.scoring.weights`, issue #2099). Every module defaults to weight `1.0`, so an unconfigured install still gets the plain arithmetic mean; a module absent from a saved `weights` map also defaults to `1.0` rather than dropping out.## Adaptive Difficulty-Opt-in adaptive tuning for math drills (`server/lib/postAdaptive.js`): recent scored performance nudges drill parameters, with a transparent preview of what would change (`GET /api/meatspace/post/adaptive-preview`).+Opt-in adaptive tuning for math drills (`server/lib/postAdaptive.js`): recent scored performance nudges drill parameters, with a transparent preview of what would change (`GET /api/meatspace/post/adaptive-preview`). Multiplication is a special case: whenever the progressive ladder is on (the default), it owns multiplication's difficulty entirely and the preview reflects the ladder rung, not the generic `maxDigits` knob — the two are mutually exclusive per drill type, never blended.## Drill Cachediff --git a/server/lib/README.md b/server/lib/README.mdindex ec50842515..15f62f64ff 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -240,6 +240,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `apiRegistry.js` | Single source of truth for which PortOS services are externally-callable HTTP APIs (`voice`, `sdapi`). `API_REGISTRY` declares each API's `publicPrefixes` (read/compute-safe surface only) + defaults; `isRegistryPublic(settings, path)` tells `authGate` when an `exposed && !requireAuth` API re-opens its prefix; `resolveApiAccess(settings)` merges persisted `apiAccess` flags for the Settings UI + OpenAPI docs. |+| `arrayUtils.js` | `shuffle(arr)` — Fisher-Yates shuffle (new array, never mutates). The canonical uniform shuffle — never `arr.sort(() => Math.random() - 0.5)`, which is biased. Shared by `meatspacePostCognitive.js` (Schulte table / mental rotation) and `meatspacePostMemory.js` (memory drill generators). || `asyncMutex.js` | Promise-based async mutex. || `authGate.js` | Express + Socket.IO middleware that gates `/api/*` and `/data/*` behind the password set in `settings.secrets.auth`. No-op when auth is off; emits 401 `AUTH_REQUIRED` (or plain text for `/data/*`) when on and the request has no valid session token. Consults `apiRegistry.isRegistryPublic` so an exposed+passwordless API (voice/sdapi) bypasses the gate on its public prefix only. || `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). |diff --git a/server/lib/arrayUtils.js b/server/lib/arrayUtils.jsnew file mode 100644index 0000000000..3eef7d31dd--- /dev/null+++ b/server/lib/arrayUtils.js@@ -0,0 +1,19 @@+/**+ * Array utilities — pure, side-effect-free helpers shared across services.+ */++/**+ * Fisher-Yates shuffle. Returns a new array in randomized order; never+ * mutates the input. Use this everywhere an array needs a uniform random+ * order — never the naive/biased `arr.sort(() => Math.random() - 0.5)`+ * (that comparator violates the sort contract and skews toward certain+ * permutations depending on the engine's sort algorithm).+ */+export function shuffle(arr) {+ const out = [...arr];+ for (let i = out.length - 1; i > 0; i--) {+ const j = Math.floor(Math.random() * (i + 1));+ [out[i], out[j]] = [out[j], out[i]];+ }+ return out;+}diff --git a/server/lib/arrayUtils.test.js b/server/lib/arrayUtils.test.jsnew file mode 100644index 0000000000..ea0a8c83da--- /dev/null+++ b/server/lib/arrayUtils.test.js@@ -0,0 +1,47 @@+import { describe, it, expect, vi } from 'vitest';+import { shuffle } from './arrayUtils.js';++describe('shuffle', () => {+ it('returns a new array — never mutates the input', () => {+ const input = [1, 2, 3, 4, 5];+ const out = shuffle(input);+ expect(out).not.toBe(input);+ expect(input).toEqual([1, 2, 3, 4, 5]);+ });++ it('returns a permutation of the input (same elements, same length)', () => {+ const input = [1, 2, 3, 4, 5, 6, 7, 8];+ const out = shuffle(input);+ expect(out).toHaveLength(input.length);+ expect([...out].sort((a, b) => a - b)).toEqual(input);+ });++ it('handles empty and single-element arrays without throwing', () => {+ expect(shuffle([])).toEqual([]);+ expect(shuffle([42])).toEqual([42]);+ });++ it('uses the Fisher-Yates swap pattern — every position is visited exactly once', () => {+ // Fixed "random" sequence that always swaps with itself (index 0 offset),+ // i.e. Math.random() always returns 0 → j = floor(0 * (i+1)) = 0 every+ // iteration. This exercises every loop iteration (i from length-1 down to+ // 1) without asserting a specific output order — just that the swap loop+ // ran the expected number of times and produced a valid permutation.+ const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0);+ try {+ const input = [1, 2, 3, 4, 5];+ const out = shuffle(input);+ expect(out).toHaveLength(5);+ expect([...out].sort((a, b) => a - b)).toEqual(input);+ } finally {+ randomSpy.mockRestore();+ }+ });++ it('is not the naive biased sort(() => Math.random() - 0.5) pattern — output length matches for larger arrays too', () => {+ const input = Array.from({ length: 100 }, (_, i) => i);+ const out = shuffle(input);+ expect(out).toHaveLength(100);+ expect(new Set(out).size).toBe(100);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 76e9ba10af..549403f604 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -210,6 +210,7 @@ export * from './viteAllowedHosts.js';// === General utilities ===export * from './apiRegistry.js';+export * from './arrayUtils.js';export * from './asyncMutex.js';export * from './authGate.js';export * from './domainAutonomy.js';diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex b6ef7ceb44..2ce9d60d18 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -59,8 +59,20 @@ const llmResponseSchema = z.object({const MATH_DRILL_TYPES = ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'];const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay', 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist', 'what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'];const MEMORY_DRILL_TYPES = ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'];-// Memory drills supported by the POST runner (client-side scoring with string comparison)-const POST_SUPPORTED_MEMORY_TYPES = ['memory-sequence', 'memory-element-flash'];+// Memory drills supported by the POST runner (client-side scoring with string+// comparison) — trusted for score + schedule/mastery advancement on session+// submit (issue #2099). Currently identical to MEMORY_DRILL_TYPES; kept as a+// separate list (rather than aliasing MEMORY_DRILL_TYPES directly) so a FUTURE+// memory drill type can ship generation-only, ahead of its scoring support,+// without silently trusting a client-supplied score for it.+const POST_SUPPORTED_MEMORY_TYPES = ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'];+// Canonical set of coarse "module" tags a scored POST task/session can carry+// (mental-math / llm-drills / cognitive drills / memory drills). Shared by the+// session-submit schema (below) and sessionModules config so a typo'd module+// string is rejected at validation instead of silently creating a phantom+// `byModule` stats bucket (issue #2099). Morse is deliberately excluded — it+// only ever posts through the separate, unrestricted `trainingEntrySchema`.+const POST_MODULES = ['mental-math', 'llm-drills', 'cognitive', 'memory'];// Cognitive drills (deterministic, no LLM) — n-back / digit-span / stroop.// Sourced from meatspacePostCognitive.js so the type list has one owner.const DRILL_TYPES = [...MATH_DRILL_TYPES, ...LLM_DRILL_TYPES, ...MEMORY_DRILL_TYPES, ...COGNITIVE_DRILL_TYPES];@@ -125,7 +137,7 @@ const drillTypeConfigSchema = z.object({// Task result within a session// score is optional — the server recomputes it via scoreDrillconst taskResultSchema = z.object({- module: z.string(),+ module: z.enum(POST_MODULES),type: z.enum(DRILL_TYPES),config: drillTypeConfigSchema.optional().default({}),questions: z.array(questionResultSchema).optional().default([]),@@ -170,7 +182,7 @@ const taskResultSchema = z.object({// Full session submissionexport const postSessionSubmitSchema = z.object({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({})});@@ -201,7 +213,7 @@ export const postConfigUpdateSchema = z.object({enabled: z.boolean().optional(),drillTypes: z.record(z.enum(COGNITIVE_DRILL_TYPES), drillTypeConfigSchema).optional()}).optional(),- sessionModules: z.array(z.string()).optional(),+ sessionModules: z.array(z.enum(POST_MODULES)).optional(),scoring: z.object({weights: z.record(z.number().min(0).max(1)).optional()}).optional(),@@ -386,4 +398,4 @@ export const trainingEntrySchema = z.object({totalMs: z.number().min(0),});-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 --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.jsindex 8a147714ae..b6a36f30d7 100644--- a/server/lib/postValidation.test.js+++ b/server/lib/postValidation.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { postLlmScoreRequestSchema, postConfigUpdateSchema, postSessionSubmitSchema, postDrillRequestSchema, trainingEntrySchema, LLM_DRILL_TYPES } from './postValidation.js';+import { postLlmScoreRequestSchema, postConfigUpdateSchema, postSessionSubmitSchema, postDrillRequestSchema, trainingEntrySchema, 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@@ -171,6 +171,51 @@ describe('questionResultSchema chunkId/element (issue #2016)', () => {});});+describe('postSessionSubmitSchema.modules — enum of known modules (issue #2099, fix #6)', () => {+ // Regression: `modules` (session-level) and each task's `module` were both+ // z.array(z.string())/z.string() — any typo'd string passed validation and+ // then silently created a phantom bucket in getPostStats().byModule, keyed+ // off task.module. Now both must be one of POST_MODULES.+ it('accepts every known module', () => {+ for (const module of POST_MODULES) {+ const parsed = postSessionSubmitSchema.parse({+ modules: [module],+ tasks: [{ module, type: 'doubling-chain', totalMs: 100 }]+ });+ expect(parsed.modules).toEqual([module]);+ }+ });++ it('rejects an unknown module string on the session-level modules array', () => {+ expect(() => postSessionSubmitSchema.parse({+ modules: ['mentalmath'], // typo — missing the hyphen+ tasks: [{ module: 'mental-math', type: 'doubling-chain', totalMs: 100 }]+ })).toThrow();+ });++ it('rejects an unknown module string on a task — the actual byModule phantom-bucket vector', () => {+ expect(() => postSessionSubmitSchema.parse({+ modules: ['mental-math'],+ tasks: [{ module: 'mentalmath', type: 'doubling-chain', totalMs: 100 }]+ })).toThrow();+ });++ it('rejects an unknown module on postConfigUpdateSchema.sessionModules', () => {+ expect(() => postConfigUpdateSchema.parse({ sessionModules: ['not-a-module'] })).toThrow();+ expect(postConfigUpdateSchema.parse({ sessionModules: ['memory'] }).sessionModules).toEqual(['memory']);+ });+});++describe('POST_SUPPORTED_MEMORY_TYPES (issue #2099, fix #1)', () => {+ // Regression: memory-fill-blank used to be absent, which forced its score+ // to 0 and skipped schedule/mastery advancement in submitPostSession.+ it('includes memory-fill-blank alongside memory-sequence and memory-element-flash', () => {+ expect(POST_SUPPORTED_MEMORY_TYPES).toEqual(+ expect.arrayContaining(['memory-fill-blank', 'memory-sequence', 'memory-element-flash'])+ );+ });+});+describe('postLlmScoreRequestSchema', () => {// Regression: Zod's default strip mode dropped `questionIndex` from each// response, so the server scorer fell back to the response-array indexdiff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 20ea9806a5..3a850700bd 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -73,7 +73,10 @@ const DEFAULT_CONFIG = {}},sessionModules: ['mental-math'],- scoring: { weights: { 'mental-math': 1.0, 'llm-drills': 1.0, 'cognitive': 1.0 } },+ // Per-module weight applied to a session's blended score (issue #2099).+ // Uniform 1.0 defaults reproduce the old unweighted-mean behavior exactly —+ // a user only sees a change once they actually adjust a weight.+ scoring: { weights: { 'mental-math': 1.0, 'llm-drills': 1.0, 'cognitive': 1.0, 'memory': 1.0 } },// Opt-in adaptive difficulty (default OFF). When enabled, math drills are// nudged harder/easier at generation time from recent scored performance.adaptive: { enabled: false },@@ -218,7 +221,7 @@ export async function submitPostSession(sessionData) {cadence: sessionData.cadence || 'daily',modules: sessionData.modules,tasks: rescoredTasks,- score: computeSessionScore(rescoredTasks),+ score: computeSessionScore(rescoredTasks, config.scoring?.weights),tags: sessionData.tags || {}};@@ -701,15 +704,31 @@ export async function resolveDrillConfig(type, requestedConfig = {}) {* Build a transparent per-type preview of the effective adaptive difficulty for* every supported math drill, so the config UI can show what Adaptive will do* before a session starts. `enabled` reflects the saved Adaptive toggle.+ *+ * Multiplication is a special case: `resolveDrillConfig` (above) hands+ * multiplication's difficulty entirely to the progressive ladder whenever+ * `progressive !== false` (the default) — the `maxDigits` Adaptive knob is+ * short-circuited and never applied in that mode. Previewing it via+ * `adaptDrillConfig` regardless would advertise a maxDigits adjustment that+ * can never actually happen (issue #2099). So this mirrors resolveDrillConfig's+ * own branch: ladder rung when progressive is on, the maxDigits Adaptive+ * preview only when the user has turned progressive off.*/export async function getAdaptivePreview() {const config = await getPostConfig();const enabled = !!config?.adaptive?.enabled;const stats = await getPostStats(ADAPTIVE_DEFAULTS.windowDays);const savedDrills = config?.mentalMath?.drillTypes || {};+ const multiplicationProgressive = savedDrills.multiplication?.progressive !== false;const drills = {};for (const type of Object.keys(ADAPTIVE_SPECS)) {+ if (type === 'multiplication' && multiplicationProgressive) {+ // Same source of truth resolveDrillConfig uses for the ladder rung —+ // not the generic maxDigits Adaptive signal.+ drills[type] = { ladder: true, ...(await getMultiplicationProgress()) };+ continue;+ }const key = `${MATH_MODULE}:${type}`;const accuracy = stats.byDrillAccuracy?.[key];const completion = stats.byDrillCompletion?.[key];@@ -815,10 +834,27 @@ export function scoreDrill(type, questions, timeLimitMs, config = {}) {};}-function computeSessionScore(tasks) {+/**+ * Blend a session's per-task scores into one headline number, weighted by+ * each task's module (`config.scoring.weights`, issue #2099). A module absent+ * from `weights` (or a non-numeric entry) defaults to 1.0, so an all-uniform+ * (or empty/missing) weights map reproduces the exact old unweighted mean —+ * existing configs and sessions score identically until a user actually+ * adjusts a weight.+ */+function computeSessionScore(tasks, weights = {}) {const valid = (tasks || []).filter(t => typeof t.score === 'number' && !Number.isNaN(t.score));if (!valid.length) return 0;- const totalScore = valid.reduce((sum, t) => sum + t.score, 0);- return Math.round(totalScore / valid.length);+ let totalWeighted = 0;+ let totalWeight = 0;+ for (const t of valid) {+ const w = typeof weights?.[t.module] === 'number' ? weights[t.module] : 1.0;+ totalWeighted += t.score * w;+ totalWeight += w;+ }+ // All-zero weights (every touched module explicitly zeroed) would otherwise+ // divide by zero — fall back to 0 rather than NaN.+ if (!totalWeight) return 0;+ return Math.round(totalWeighted / totalWeight);}diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex 7a26b5d11c..b5936e2a26 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -28,6 +28,7 @@ import {postConfigEvents,resolveDrillConfig,getMultiplicationProgress,+ getAdaptivePreview,getPostStats,deriveTaskAccuracy,deriveTaskCompletion,@@ -666,13 +667,15 @@ describe('submitPostSession — memory drill schedule advance', () => {expect(memoryWrite).toBeUndefined();});- it('does not advance a schedule for an unsupported memory drill type with no memoryItemId', async () => {+ it('does not advance a schedule for a supported memory task with no memoryItemId', async () => {await submitPostSession({cadence: 'daily',modules: ['memory'],tasks: [{module: 'memory',type: 'memory-fill-blank',+ // No memoryItemId — the schedule/mastery advance loop gates on it+ // regardless of whether the type is in POST_SUPPORTED_MEMORY_TYPES.questions: [{ prompt: 'a ____ line', expected: 'test', answered: 'test', correct: true, responseMs: 500 }],totalMs: 500,}],@@ -682,6 +685,131 @@ describe('submitPostSession — memory drill schedule advance', () => {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+ 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) });+ });+});++// =============================================================================+// 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();+ });++ 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({ sessions: [] });+ return Promise.resolve(defaultValue); // post-config → baseDefaults (all weights 1.0)+ });++ const session = await submitPostSession({+ cadence: 'daily',+ modules: ['llm-drills', 'memory'],+ tasks: [llmTask(100), memoryTask(0)],+ tags: {},+ });++ expect(session.score).toBe(50); // (100 + 0) / 2+ });++ 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);+ });++ const session = await submitPostSession({+ cadence: 'daily',+ modules: ['llm-drills', 'memory'],+ tasks: [llmTask(100), memoryTask(80)],+ tags: {},+ });++ // (100*1 + 80*0.5) / (1+0.5) = 140/1.5 = 93.33 → 93+ expect(session.score).toBe(93);+ });++ 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-sessions')) return Promise.resolve({ sessions: [] });+ if (p.includes('post-config')) {+ return Promise.resolve({ scoring: { weights: { memory: 0 } } });+ }+ return Promise.resolve(defaultValue);+ });++ const session = await submitPostSession({+ cadence: 'daily',+ modules: ['llm-drills', 'memory'],+ tasks: [llmTask(80), memoryTask(0)],+ tags: {},+ });++ // memory weight 0 drops out entirely → score is just the llm-drills task's own score+ expect(session.score).toBe(80);+ });});// =============================================================================@@ -852,6 +980,70 @@ describe('resolveDrillConfig — progressive multiplication', () => {});});+// =============================================================================+// 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)diff --git a/server/services/meatspacePostCognitive.js b/server/services/meatspacePostCognitive.jsindex 1ad0e5d9fb..82c0635790 100644--- a/server/services/meatspacePostCognitive.js+++ b/server/services/meatspacePostCognitive.js@@ -15,6 +15,8 @@* NO AI-provider calls happen anywhere in this module.*/+import { shuffle } from '../lib/arrayUtils.js';+// Coarse module tag stored on scored cognitive tasks, so stats read as// `byDrill['cognitive:<type>']` (parallel to `mental-math:<type>`).export const COGNITIVE_MODULE = 'cognitive';@@ -104,17 +106,6 @@ export function median(nums) {return list.length % 2 ? list[mid] : Math.round((list[mid - 1] + list[mid]) / 2);}-// Fisher-Yates shuffle. Used by Schulte table cell placement and mental-// rotation option ordering — never a naive `sort(() => Math.random() - 0.5)`.-function shuffle(arr) {- const out = [...arr];- for (let i = out.length - 1; i > 0; i--) {- const j = Math.floor(Math.random() * (i + 1));- [out[i], out[j]] = [out[j], out[i]];- }- return out;-}-// --- Mental rotation: grid-cell shape helpers -------------------------------// Four chiral pentomino footprints, each within a 4x4 box. Verified (see the// "ROTATION_SHAPES chirality invariant" test in meatspacePostCognitive.test.js,diff --git a/server/services/meatspacePostLlm.js b/server/services/meatspacePostLlm.jsindex 718e92366c..13d716fce8 100644--- a/server/services/meatspacePostLlm.js+++ b/server/services/meatspacePostLlm.js@@ -618,42 +618,6 @@ Return ONLY valid JSON:{"overallScore":75,"scores":[{"score":80,"feedback":"Good creative connections"}],"summary":"Overall assessment"}`;}-function buildStoryRecallScorePrompt(drillData, responses) {- const items = responses.map((r, i) => {- const exercise = drillData.exercises?.[r.questionIndex ?? i];- const qas = (exercise?.questions || []).map((q, qi) => {- const userAnswer = r.answers?.[qi] || '(no answer)';- return ` Q: ${q.question} | Correct: ${q.answer} | User: ${userAnswer}`;- }).join('\n');- return `Story ${i + 1}: "${exercise?.paragraph}"\n${qas}`;- }).join('\n\n');-- return `Score these story recall responses. For each question, determine if the user's answer matches the correct answer (allow minor spelling/phrasing differences).-Rate each exercise 0-100 based on accuracy.--${items}--Return ONLY valid JSON:-{"overallScore":75,"scores":[{"score":80,"feedback":"Recalled 3 of 4 details correctly"}],"summary":"Overall memory assessment"}`;-}--function buildVerbalFluencyScorePrompt(drillData, responses) {- const items = responses.map((r, i) => {- const cat = drillData.categories?.[r.questionIndex ?? i];- return `Category: "${cat?.category}" (expected ~${cat?.minExpected})\nUser items: ${(r.items || []).join(', ') || '(none)'}`;- }).join('\n\n');-- return `Score these verbal fluency responses. For each category:-1. Count valid, unique items (remove duplicates and invalid entries)-2. Compare count to minExpected-3. Note any particularly creative or unusual valid answers--${items}--Return ONLY valid JSON:-{"overallScore":75,"scores":[{"score":80,"feedback":"Named 12 valid animals, good variety","validCount":12,"invalidItems":["rock"]}],"summary":"Overall fluency assessment"}`;-}-function buildWitComebackScorePrompt(drillData, responses) {const items = responses.map((r, i) => {const scenario = drillData.scenarios?.[r.questionIndex ?? i];@@ -688,41 +652,6 @@ Return ONLY valid JSON:// WORDPLAY TRAINING SCORE PROMPTS// ─────────────────────────────────────────────────────────────────────────────-function buildCompoundChainScorePrompt(drillData, responses) {- const items = responses.map((r, i) => {- const challenge = drillData.challenges?.[r.questionIndex ?? i];- return `Root word: "${challenge?.rootWord}" (position: ${challenge?.position}, target: ${challenge?.minExpected}+)\nUser's compounds: ${(r.items || []).join(', ') || '(none)'}`;- }).join('\n\n');-- return `Score these compound word/phrase association responses. For each root word:-1. Count valid compound words or common phrases that actually use the root word-2. Remove duplicates, misspellings, and invalid entries (words that don't form real compounds with the root)-3. Compare count to the target (minExpected)-4. Bonus for creative or unusual but valid compounds--${items}--Return ONLY valid JSON:-{"overallScore":75,"scores":[{"score":80,"feedback":"12 valid compounds, good variety","validCount":12,"invalidItems":["not-a-real-compound"]}],"summary":"Overall compound chain assessment"}`;-}--function buildBridgeWordScorePrompt(drillData, responses) {- const items = responses.map((r, i) => {- const puzzle = drillData.puzzles?.[r.questionIndex ?? i];- return `Clues: ${(puzzle?.clues || []).join(', ')}\nCorrect answer: "${puzzle?.answer}"\nUser's answer: "${r.response || '(no response)'}"`;- }).join('\n\n');-- return `Score these bridge word puzzle responses. For each puzzle:-1. Check if the user's answer matches the correct bridge word (allow minor spelling differences)-2. If the user gave a different word that also validly fills all the blanks, give full credit-3. Rate 0 for wrong answers, 100 for correct--${items}--Return ONLY valid JSON:-{"overallScore":75,"scores":[{"score":100,"feedback":"Correct!"}],"summary":"Overall bridge word assessment"}`;-}-function buildDoubleMeaningScorePrompt(drillData, responses) {const items = responses.map((r, i) => {const challenge = drillData.challenges?.[r.questionIndex ?? i];diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.jsindex 5ee39f07c4..50d5fbabf9 100644--- a/server/services/meatspacePostMemory.js+++ b/server/services/meatspacePostMemory.js@@ -8,6 +8,7 @@import { join } from 'path';import { randomUUID } from 'crypto';import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';+import { shuffle } from '../lib/arrayUtils.js';const MEATSPACE_DIR = PATHS.meatspace;const MEMORY_ITEMS_FILE = join(MEATSPACE_DIR, 'post-memory-items.json');@@ -629,7 +630,7 @@ function generateFillBlank(item, count) {if (!lines.length) return null;const questions = [];- const shuffled = [...lines].sort(() => Math.random() - 0.5).slice(0, Math.min(count, lines.length));+ const shuffled = shuffle(lines).slice(0, Math.min(count, lines.length));for (const line of shuffled) {const words = line.text.split(/\s+/);@@ -665,6 +666,13 @@ function generateFillBlank(item, count) {questions.push({prompt: display,fullText: line.text,+ // Scalar primary answer (the first blanked word) — kept alongside the+ // full `answers[]` acceptable-word list so consumers that expect a+ // single `expected` field (DrillQuestionReview, scoring) have a+ // consistent value instead of always reading "—"/undefined (issue+ // #2116). Scoring still checks `answers[]` for a match against ANY+ // blanked word, not just this primary one.+ expected: answers[0]?.word ?? null,answers,chunkId: findChunkForLine(item, lines.indexOf(line)),});@@ -684,7 +692,7 @@ function generateSequenceRecall(item, count) {if (lines.length < 2) return null;const questions = [];- const indices = [...Array(lines.length - 1).keys()].sort(() => Math.random() - 0.5).slice(0, Math.min(count, lines.length - 1));+ const indices = shuffle([...Array(lines.length - 1).keys()]).slice(0, Math.min(count, lines.length - 1));for (const idx of indices) {questions.push({@@ -708,7 +716,7 @@ function generateElementFlash(item, count) {if (item.id !== 'elements-song' || !item.content.elementMap) return null;const elements = Object.entries(item.content.elementMap);- const shuffled = [...elements].sort(() => Math.random() - 0.5).slice(0, Math.min(count, elements.length));+ const shuffled = shuffle(elements).slice(0, Math.min(count, elements.length));const questions = shuffled.map(([symbol, info]) => {// Randomly ask name→symbol or symbol→namediff --git a/server/services/meatspacePostMemory.test.js b/server/services/meatspacePostMemory.test.jsindex 05ae014219..1bbd68bc9f 100644--- a/server/services/meatspacePostMemory.test.js+++ b/server/services/meatspacePostMemory.test.js@@ -178,6 +178,21 @@ describe('generateMemoryDrill', () => {}});+ // Regression (issue #2116): generateFillBlank used to return only an+ // `answers[]` array of { index, word, element } objects with no scalar+ // `expected` — the client's fill-blank scoring path (and any generic+ // consumer expecting `expected`, like DrillQuestionReview) had nothing+ // consistent to read. `expected` must now be the primary (first blanked)+ // word, and it must always be ONE of the acceptable `answers[]` words.+ it('stamps a scalar `expected` on every fill-blank question, matching the primary acceptable answer', async () => {+ const drill = await generateMemoryDrill({ mode: 'fill-blank', count: 5 });+ for (const q of drill.questions) {+ expect(typeof q.expected).toBe('string');+ expect(q.expected).toBe(q.answers[0].word);+ expect(q.answers.map(a => a.word)).toContain(q.expected);+ }+ });+it('generates sequence drill', async () => {const drill = await generateMemoryDrill({ mode: 'sequence', count: 3 });expect(drill).toBeTruthy();