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-2094]): separate accuracy from speed in POST scoring; SDT n-back; latency-based reaction-time

Adam Eivyfc16b01dda72
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c5d8c6fe8c..37f0a79322 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,7 @@
## MeatSpace POST
+- **[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.
- **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.
- **Morse trainer audio now works on mobile Safari.** iOS Safari starts the Web Audio context suspended and only unlocks it once `resume()` fully settles. The trainer fired `resume()` without awaiting it, so the first tones were scheduled against a still-suspended clock and never sounded on iPhone/iPad. It now awaits the resume before scheduling any tone (matching the app's other audio modules), so Copy, Head Copy, and Send-mode keying all produce sound on mobile Safari.
- **The Elements Song trainer is now mobile-friendly and speed-readable.** The periodic-table memorization view no longer overflows off the right edge of a phone screen: the mastery summary, search box, and Mastery/Category toggle now stack and stretch to full width on small screens, the periodic table uses smaller cells (with a scroll-hint fade so it's clear the grid pans horizontally), and the header shrinks to fit. It also gained a **Rapid Read** practice mode that RSVP-flashes the lyrics one word at a time (reusing the app's speed reader) — run the whole song from the Practice list, or tap the gauge icon on any verse to speed-read just that section.
diff --git a/client/src/components/meatspace/post/PostHistory.jsx b/client/src/components/meatspace/post/PostHistory.jsx
index b7bd3a2589..7d808600fd 100644
--- a/client/src/components/meatspace/post/PostHistory.jsx
+++ b/client/src/components/meatspace/post/PostHistory.jsx
@@ -260,9 +260,20 @@ export default function PostHistory({ onBack }) {
if (expanded) {
for (const [i, task] of (s.tasks || []).entries()) {
const isLlm = LLM_DRILL_TYPES.includes(task.type);
- const detail = isLlm
- ? `${task.responses?.length || 0} responses`
- : `${task.questions?.filter(q => q.correct).length || 0}/${task.questions?.length || 0} correct`;
+ // Non-LLM rows show correctness AND average speed separately from
+ // the blended score column (issue #2094). Prefer the persisted
+ // avgResponseMs; fall back to deriving it for legacy sessions.
+ let detail;
+ if (isLlm) {
+ detail = `${task.responses?.length || 0} responses`;
+ } else {
+ const answered = (task.questions || []).filter(q => q.answered != null);
+ const avgMs = task.avgResponseMs != null
+ ? task.avgResponseMs
+ : (answered.length ? Math.round(answered.reduce((s, q) => s + (q.responseMs || 0), 0) / answered.length) : null);
+ const correctStr = `${task.questions?.filter(q => q.correct).length || 0}/${task.questions?.length || 0} correct`;
+ detail = avgMs != null ? `${correctStr} · ${(avgMs / 1000).toFixed(1)}s` : correctStr;
+ }
rows.push(
<tr key={`${s.id}-${i}`} className="bg-port-bg/30">
<td></td>
diff --git a/client/src/components/meatspace/post/PostSessionResults.jsx b/client/src/components/meatspace/post/PostSessionResults.jsx
index 98d012e56b..1a1888f331 100644
--- a/client/src/components/meatspace/post/PostSessionResults.jsx
+++ b/client/src/components/meatspace/post/PostSessionResults.jsx
@@ -73,14 +73,26 @@ export default function PostSessionResults({ session, tags = {}, onSaved, onBack
const summary = result.evaluation?.summary;
subtitle = summary || `${result.responses?.length || 0} responses`;
} else {
- const correct = (result.questions || []).filter(q => q.correct).length;
- const total = (result.questions || []).length;
- const accuracyPct = total > 0 ? Math.round((correct / total) * 100) : 0;
- const answered = (result.questions || []).filter(q => q.answered !== null);
- const avgMs = answered.length > 0
- ? Math.round(answered.reduce((s, q) => s + q.responseMs, 0) / answered.length)
- : 0;
- subtitle = `${accuracyPct}% accuracy · ${(avgMs / 1000).toFixed(1)}s avg`;
+ // Accuracy (answered-only) and speed are shown separately from the
+ // blended score (issue #2094). Prefer the server-persisted metrics;
+ // fall back to deriving from questions[] for legacy sessions, and
+ // surface completion only when the drill wasn't fully answered.
+ const questions = result.questions || [];
+ const answered = questions.filter(q => q.answered !== null);
+ const accPct = result.accuracy != null
+ ? Math.round(result.accuracy * 100)
+ : (answered.length > 0 ? Math.round((answered.filter(q => q.correct).length / answered.length) * 100) : null);
+ const compPct = result.completion != null
+ ? Math.round(result.completion * 100)
+ : (questions.length > 0 ? Math.round((answered.length / questions.length) * 100) : null);
+ const avgMs = result.avgResponseMs != null
+ ? result.avgResponseMs
+ : (answered.length > 0 ? Math.round(answered.reduce((s, q) => s + q.responseMs, 0) / answered.length) : null);
+ const parts = [];
+ if (accPct != null) parts.push(`${accPct}% acc`);
+ if (avgMs != null) parts.push(`${(avgMs / 1000).toFixed(1)}s`);
+ if (compPct != null && compPct < 100) parts.push(`${compPct}% done`);
+ subtitle = parts.join(' · ') || `${questions.length} questions`;
}
const drillScoreColor = (result.score || 0) >= 80 ? 'text-port-success' :
diff --git a/server/lib/postAdaptive.js b/server/lib/postAdaptive.js
index 43caeddbea..bd36137b2f 100644
--- a/server/lib/postAdaptive.js
+++ b/server/lib/postAdaptive.js
@@ -23,9 +23,10 @@ export const ADAPTIVE_SPECS = {
};
export const ADAPTIVE_DEFAULTS = {
- highScore: 90, // >= this over enough samples → bump difficulty up one step
+ highScore: 90, // >= this ACCURACY (0-100, answered-only) over enough samples → harder
lowScore: 50, // <= this → ease difficulty down one step
minSamples: 3, // need at least this many scored samples before adapting
+ minCompletion: 0.5, // skip adaptation when avg completion < this — too little signal
windowDays: 30, // stats window the signal is read over
};
@@ -49,9 +50,9 @@ export function scoreToDirection(score, { highScore, lowScore } = ADAPTIVE_DEFAU
*
* @param {string} type - math drill type
* @param {object} baseConfig - the user's configured drill params
- * @param {{score?: number|null, samples?: number}} signal - recent performance
+ * @param {{score?: number|null, samples?: number, completion?: number|null}} signal - recent performance
* @param {object} [opts] - override ADAPTIVE_DEFAULTS thresholds
- * @returns {{config: object, type, field, from, to, direction, applied, score, samples, reason}}
+ * @returns {{config: object, type, field, from, to, direction, applied, score, samples, completion, reason}}
*/
export function adaptDrillConfig(type, baseConfig = {}, signal = {}, opts = {}) {
const spec = ADAPTIVE_SPECS[type];
@@ -59,6 +60,7 @@ export function adaptDrillConfig(type, baseConfig = {}, signal = {}, opts = {})
const base = { ...(baseConfig || {}) };
const samples = Number.isFinite(signal?.samples) ? signal.samples : 0;
const score = signal?.score == null || Number.isNaN(signal.score) ? null : signal.score;
+ const completion = signal?.completion == null || Number.isNaN(signal.completion) ? null : signal.completion;
const out = {
config: base,
@@ -70,6 +72,7 @@ export function adaptDrillConfig(type, baseConfig = {}, signal = {}, opts = {})
applied: false,
score,
samples,
+ completion,
reason: 'unsupported',
};
@@ -87,6 +90,14 @@ export function adaptDrillConfig(type, baseConfig = {}, signal = {}, opts = {})
return out;
}
+ if (completion != null && completion < options.minCompletion) {
+ // The user barely reached this drill (timed out on most of it) — accuracy off
+ // a handful of answers isn't a trustworthy difficulty signal, so hold the
+ // manual config until they complete more of it (issue #2094).
+ out.reason = 'insufficient-completion';
+ return out;
+ }
+
const direction = scoreToDirection(score, options);
out.direction = direction;
diff --git a/server/lib/postAdaptive.test.js b/server/lib/postAdaptive.test.js
index ee9bc1b084..c1c3dd100a 100644
--- a/server/lib/postAdaptive.test.js
+++ b/server/lib/postAdaptive.test.js
@@ -50,6 +50,30 @@ describe('adaptDrillConfig', () => {
expect(res.config.maxDigits).toBe(2);
});
+ it('skips adaptation when completion is below the floor (too little signal)', () => {
+ // Enough samples and a high accuracy signal, but the user only reached ~30%
+ // of the drill — not a trustworthy difficulty signal, so hold (issue #2094).
+ const res = adaptDrillConfig('multiplication', { maxDigits: 2 }, { score: 95, samples: 5, completion: 0.3 });
+ expect(res.applied).toBe(false);
+ expect(res.reason).toBe('insufficient-completion');
+ expect(res.config.maxDigits).toBe(2);
+ });
+
+ it('adapts normally once completion clears the floor', () => {
+ const res = adaptDrillConfig('multiplication', { maxDigits: 2 }, { score: 95, samples: 5, completion: 0.8 });
+ expect(res.applied).toBe(true);
+ expect(res.reason).toBe('harder');
+ expect(res.completion).toBe(0.8);
+ expect(res.config.maxDigits).toBe(3);
+ });
+
+ it('adapts when completion is absent (legacy signal without the field)', () => {
+ const res = adaptDrillConfig('multiplication', { maxDigits: 2 }, { score: 95, samples: 5 });
+ expect(res.applied).toBe(true);
+ expect(res.reason).toBe('harder');
+ expect(res.completion).toBe(null);
+ });
+
it('bumps the primary knob harder on sustained high scores (higher = harder)', () => {
const res = adaptDrillConfig('multiplication', { maxDigits: 2 }, { score: 95, samples: 5 });
expect(res.applied).toBe(true);
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index 0b7e12f679..ffbf0a4cf5 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -137,6 +137,25 @@ const taskResultSchema = z.object({
// every other drill type.
memoryItemId: z.string().optional(),
score: z.number().min(0).max(100).optional(),
+ // Separated performance metrics stored alongside the blended `score` (issue
+ // #2094). The server always recomputes these from the drill answer key on
+ // submit, so an incoming client value is advisory — accepted (optional,
+ // nullable where a metric can be genuinely absent) rather than rejected, to
+ // keep the request/stored shapes in parity. `accuracy`/`completion` are 0-1
+ // fractions; `avgResponseMs`/`medianMs`/`bestMs` are milliseconds. The n-back
+ // signal-detection counts and reaction-time latency extremes ride along too.
+ accuracy: z.number().min(0).max(1).nullable().optional(),
+ completion: z.number().min(0).max(1).nullable().optional(),
+ avgResponseMs: z.number().min(0).nullable().optional(),
+ answeredCount: z.number().int().min(0).optional(),
+ totalCount: z.number().int().min(0).optional(),
+ medianMs: z.number().min(0).nullable().optional(),
+ bestMs: z.number().min(0).nullable().optional(),
+ span: z.number().int().min(0).optional(),
+ hits: z.number().int().min(0).optional(),
+ misses: z.number().int().min(0).optional(),
+ falseAlarms: z.number().int().min(0).optional(),
+ correctRejections: z.number().int().min(0).optional(),
evaluation: z.object({
score: z.number().min(0).max(100).optional(),
breakdown: z.array(z.object({
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index 9800710cb9..e0b463b8c4 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -179,10 +179,13 @@ export async function submitPostSession(sessionData) {
}
// Cognitive drills: deterministic — recompute the answer key from the
- // generated drillData (never trust client `correct`/`score`).
+ // generated drillData (never trust client `correct`/`score`). Spread the
+ // full scored bundle so the separated metrics (accuracy/completion/
+ // avgResponseMs, plus n-back SDT counts and reaction-time median/best) are
+ // persisted alongside the blended score (issue #2094).
if (COGNITIVE_DRILL_TYPES.includes(rest.type)) {
- const { score, questions } = scoreCognitiveDrill(rest.type, rest.drillData, rest.questions || []);
- return { ...rest, questions, score };
+ const scored = scoreCognitiveDrill(rest.type, rest.drillData, rest.questions || []);
+ return { ...rest, ...scored };
}
// Math drills: strip correct from individual questions and rescore
@@ -192,8 +195,8 @@ export async function submitPostSession(sessionData) {
});
const drillConfig = config.mentalMath?.drillTypes?.[rest.type] || {};
const timeLimitMs = (drillConfig.timeLimitSec || 120) * 1000;
- const { score, questions } = scoreDrill(rest.type, sanitizedQuestions, timeLimitMs, rest.config || drillConfig);
- return { ...rest, questions, score };
+ const scored = scoreDrill(rest.type, sanitizedQuestions, timeLimitMs, rest.config || drillConfig);
+ return { ...rest, ...scored };
});
const session = {
@@ -296,6 +299,32 @@ export function computePostStreaks(sessions, todayStr) {
return { completedToday, currentStreak, longestStreak, lastDate, todayScore };
}
+/**
+ * Answered-only accuracy for a scored task, tolerant of legacy sessions that
+ * predate the persisted `accuracy` field (issue #2094). Order: the stored value
+ * first, else derive from `questions[]` (correct over ANSWERED, not total), else
+ * `null` — never NaN. Used by stats aggregation and the adaptive signal so old
+ * and new session shapes both read cleanly.
+ */
+export function deriveTaskAccuracy(task) {
+ if (typeof task?.accuracy === 'number' && !Number.isNaN(task.accuracy)) return task.accuracy;
+ const qs = Array.isArray(task?.questions) ? task.questions : [];
+ const answered = qs.filter(q => q?.answered != null);
+ if (!answered.length) return null;
+ return answered.filter(q => q?.correct).length / answered.length;
+}
+
+/**
+ * Completion (answered / total) for a scored task, with the same legacy fallback
+ * as deriveTaskAccuracy. `null` when there are no questions to derive from.
+ */
+export function deriveTaskCompletion(task) {
+ if (typeof task?.completion === 'number' && !Number.isNaN(task.completion)) return task.completion;
+ const qs = Array.isArray(task?.questions) ? task.questions : [];
+ if (!qs.length) return null;
+ return qs.filter(q => q?.answered != null).length / qs.length;
+}
+
export async function getPostStats(days = 30) {
const sessions = await getPostSessions();
// Streaks are computed over ALL history, independent of the stats window.
@@ -309,7 +338,7 @@ export async function getPostStats(days = 30) {
}
if (recent.length === 0) {
- return { days, sessionCount: 0, overall: null, byModule: {}, byDrill: {}, byDrillCount: {}, ...streaks };
+ return { days, sessionCount: 0, overall: null, byModule: {}, byDrill: {}, byDrillCount: {}, byDrillAccuracy: {}, byDrillCompletion: {}, ...streaks };
}
const scores = recent.map(s => s.score);
@@ -317,6 +346,11 @@ export async function getPostStats(days = 30) {
const byModule = {};
const byDrill = {};
+ // Accuracy (answered-only) and completion tracked per drill alongside the
+ // blended score, so reporting and the adaptive signal can separate "how right"
+ // from "how fast/complete" (issue #2094). Legacy tasks are derived, not skipped.
+ const byDrillAccuracyList = {};
+ const byDrillCompletionList = {};
for (const session of recent) {
for (const task of session.tasks) {
if (!byModule[task.module]) byModule[task.module] = [];
@@ -325,18 +359,30 @@ export async function getPostStats(days = 30) {
const key = `${task.module}:${task.type}`;
if (!byDrill[key]) byDrill[key] = [];
byDrill[key].push(task.score);
+
+ const acc = deriveTaskAccuracy(task);
+ if (acc != null) (byDrillAccuracyList[key] ||= []).push(acc);
+ const comp = deriveTaskCompletion(task);
+ if (comp != null) (byDrillCompletionList[key] ||= []).push(comp);
}
}
const avg = arr => Math.round(arr.reduce((a, b) => a + b, 0) / arr.length);
+ const avgFrac = arr => arr.reduce((a, b) => a + b, 0) / arr.length;
for (const key of Object.keys(byModule)) byModule[key] = avg(byModule[key]);
// byDrillCount is the per-drill sample size, used to gate adaptive difficulty
// (don't adapt off a single lucky/unlucky run). Captured before averaging.
const byDrillCount = {};
for (const key of Object.keys(byDrill)) byDrillCount[key] = byDrill[key].length;
for (const key of Object.keys(byDrill)) byDrill[key] = avg(byDrill[key]);
-
- return { days, sessionCount: recent.length, overall, byModule, byDrill, byDrillCount, ...streaks };
+ // Per-drill accuracy (0-1) and completion (0-1) means. Separate sample lists so
+ // a drill with no derivable accuracy still reports a completion figure.
+ const byDrillAccuracy = {};
+ for (const key of Object.keys(byDrillAccuracyList)) byDrillAccuracy[key] = avgFrac(byDrillAccuracyList[key]);
+ const byDrillCompletion = {};
+ for (const key of Object.keys(byDrillCompletionList)) byDrillCompletion[key] = avgFrac(byDrillCompletionList[key]);
+
+ return { days, sessionCount: recent.length, overall, byModule, byDrill, byDrillCount, byDrillAccuracy, byDrillCompletion, ...streaks };
}
// =============================================================================
@@ -477,15 +523,23 @@ export function generateDrill(type, config = {}) {
/**
* Read the recent performance signal for one math drill type from scored
- * sessions. Returns { score, samples } — score is the avg session score (0-100)
- * over the adaptive window; samples is how many task samples backed it.
+ * sessions. Returns { score, samples, completion } where `score` is now the avg
+ * ACCURACY (0-100, answered-only) — not the blended session score — so a
+ * fast-but-sloppy run and a slow-but-accurate run produce different adaptive
+ * directions (issue #2094). `completion` (0-1) lets adaptDrillConfig skip
+ * adaptation when the user barely reached the drill (too little signal).
*/
async function getAdaptiveSignal(type) {
const stats = await getPostStats(ADAPTIVE_DEFAULTS.windowDays);
const key = `${MATH_MODULE}:${type}`;
- const score = stats.byDrill?.[key];
+ const accuracy = stats.byDrillAccuracy?.[key];
const samples = stats.byDrillCount?.[key] || 0;
- return { score: score == null ? null : score, samples };
+ const completion = stats.byDrillCompletion?.[key];
+ return {
+ score: accuracy == null ? null : Math.round(accuracy * 100),
+ samples,
+ completion: completion == null ? null : completion,
+ };
}
/**
@@ -615,16 +669,21 @@ export async function getAdaptivePreview() {
const drills = {};
for (const type of Object.keys(ADAPTIVE_SPECS)) {
const key = `${MATH_MODULE}:${type}`;
+ const accuracy = stats.byDrillAccuracy?.[key];
+ const completion = stats.byDrillCompletion?.[key];
const signal = {
- score: stats.byDrill?.[key] == null ? null : stats.byDrill[key],
+ // Preview mirrors the live adaptive signal: accuracy (0-100), not the
+ // blended score, plus completion for the low-completion skip (issue #2094).
+ score: accuracy == null ? null : Math.round(accuracy * 100),
samples: stats.byDrillCount?.[key] || 0,
+ completion: completion == null ? null : completion,
};
// Base off the user's saved config so the preview matches what a session
// would actually use; adaptDrillConfig falls back to the spec base per field.
drills[type] = adaptDrillConfig(type, savedDrills[type] || {}, signal);
}
- return { enabled, windowDays: ADAPTIVE_DEFAULTS.windowDays, thresholds: { highScore: ADAPTIVE_DEFAULTS.highScore, lowScore: ADAPTIVE_DEFAULTS.lowScore, minSamples: ADAPTIVE_DEFAULTS.minSamples }, drills };
+ return { enabled, windowDays: ADAPTIVE_DEFAULTS.windowDays, thresholds: { highScore: ADAPTIVE_DEFAULTS.highScore, lowScore: ADAPTIVE_DEFAULTS.lowScore, minSamples: ADAPTIVE_DEFAULTS.minSamples, minCompletion: ADAPTIVE_DEFAULTS.minCompletion }, drills };
}
// =============================================================================
@@ -682,16 +741,34 @@ export function scoreDrill(type, questions, timeLimitMs, config = {}) {
});
const answered = recomputed.filter(q => q.answered != null);
+ const answeredCount = answered.length;
+ const totalCount = recomputed.length;
const correctCount = recomputed.filter(q => q.correct).length;
- const correctRatio = correctCount / recomputed.length;
+ // Blended `score` stays keyed on correct-over-TOTAL (== accuracy × completion),
+ // so the headline gamification number is unchanged for existing sessions and
+ // fully-answered tasks (back-compat). The separated metrics below are what
+ // reporting and the adaptive signal now consume (issue #2094).
+ const correctRatio = correctCount / totalCount;
// Clamp responseMs to [0, timeLimitMs] to prevent inflated speed bonuses
const totalResponseMs = answered.reduce((sum, q) => sum + Math.min(Math.max(q.responseMs || 0, 0), timeLimitMs), 0);
- const avgResponseMs = answered.length > 0 ? totalResponseMs / answered.length : timeLimitMs;
+ // Speed bonus falls back to the full time window when nothing was answered, so
+ // an empty drill scores 0 (no accuracy, no bonus) rather than dividing by zero.
+ const avgForBonus = answeredCount > 0 ? totalResponseMs / answeredCount : timeLimitMs;
- const speedBonus = Math.max(0, 1 - avgResponseMs / timeLimitMs);
+ const speedBonus = Math.max(0, 1 - avgForBonus / timeLimitMs);
const score = Math.round((correctRatio * 0.8 + speedBonus * 0.2) * 100);
- return { score: Math.min(100, Math.max(0, score)), questions: recomputed };
+ return {
+ score: Math.min(100, Math.max(0, score)),
+ questions: recomputed,
+ // Accuracy is answered-only: running out of time reduces `completion`, never
+ // accuracy (issue #2094). `null` (never NaN) when nothing was answered.
+ accuracy: answeredCount ? correctCount / answeredCount : null,
+ completion: totalCount ? answeredCount / totalCount : null,
+ avgResponseMs: answeredCount ? Math.round(totalResponseMs / answeredCount) : null,
+ answeredCount,
+ totalCount,
+ };
}
function computeSessionScore(tasks) {
diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.js
index 508eaf4dbe..33518e0087 100644
--- a/server/services/meatspacePost.test.js
+++ b/server/services/meatspacePost.test.js
@@ -28,6 +28,9 @@ import {
postConfigEvents,
resolveDrillConfig,
getMultiplicationProgress,
+ getPostStats,
+ deriveTaskAccuracy,
+ deriveTaskCompletion,
} from './meatspacePost.js';
// =============================================================================
@@ -311,9 +314,45 @@ describe('scoreDrill', () => {
{ prompt: '7 x 4', expected: 28, answered: 28, responseMs: 1500 },
{ prompt: '6 x 8', expected: 48, answered: 48, responseMs: 2000 }
];
- const { score } = scoreDrill('multiplication', questions, 120000);
+ const { score, accuracy, completion, avgResponseMs, answeredCount, totalCount } = scoreDrill('multiplication', questions, 120000);
expect(score).toBeGreaterThanOrEqual(90);
expect(score).toBeLessThanOrEqual(100);
+ // Fully-answered task: separated metrics all report cleanly.
+ expect(accuracy).toBe(1);
+ expect(completion).toBe(1);
+ expect(answeredCount).toBe(3);
+ expect(totalCount).toBe(3);
+ expect(avgResponseMs).toBe(1500);
+ });
+
+ it('separates answered-only accuracy from completion; unanswered ≠ wrong', () => {
+ const questions = [
+ { prompt: '5 x 3', expected: 15, answered: 15, responseMs: 1000 }, // correct
+ { prompt: '7 x 4', expected: 28, answered: 99, responseMs: 1200 }, // wrong
+ { prompt: '6 x 8', expected: 48, answered: null, responseMs: 0 }, // unreached
+ { prompt: '2 x 9', expected: 18, answered: null, responseMs: 0 } // unreached
+ ];
+ const { accuracy, completion, answeredCount, totalCount, avgResponseMs } = scoreDrill('multiplication', questions, 60000);
+ // 1 correct of 2 ANSWERED → 0.5 accuracy (the 2 unanswered do not count as wrong).
+ expect(accuracy).toBe(0.5);
+ // 2 answered of 4 → 0.5 completion.
+ expect(completion).toBe(0.5);
+ expect(answeredCount).toBe(2);
+ expect(totalCount).toBe(4);
+ expect(avgResponseMs).toBe(1100);
+ });
+
+ it('accuracy and avgResponseMs are null (never NaN) when nothing was answered', () => {
+ const questions = [
+ { prompt: '5 x 3', expected: 15, answered: null, responseMs: 0 },
+ { prompt: '7 x 4', expected: 28, answered: null, responseMs: 0 }
+ ];
+ const { score, accuracy, completion, avgResponseMs, answeredCount } = scoreDrill('multiplication', questions, 60000);
+ expect(accuracy).toBe(null);
+ expect(avgResponseMs).toBe(null);
+ expect(completion).toBe(0);
+ expect(answeredCount).toBe(0);
+ expect(score).toBe(0);
});
it('0% accuracy gives low score', () => {
@@ -326,15 +365,20 @@ describe('scoreDrill', () => {
expect(score).toBeLessThanOrEqual(20);
});
- it('unanswered questions count against accuracy', () => {
+ it('blended score still folds completion in (back-compat): 1 correct of 2 total', () => {
const questions = [
{ prompt: '5 x 3', expected: 15, answered: 15, responseMs: 1000 },
{ prompt: '7 x 4', expected: 28, answered: null, responseMs: 0 }
];
- const { score } = scoreDrill('multiplication', questions, 60000);
- // 50% accuracy = 40 base, plus speed bonus
+ const { score, accuracy, completion } = scoreDrill('multiplication', questions, 60000);
+ // The headline `score` stays correct-over-TOTAL (== accuracy × completion) so
+ // existing history is unchanged: 1/2 → 40 base + speed bonus.
expect(score).toBeGreaterThanOrEqual(40);
expect(score).toBeLessThanOrEqual(60);
+ // …but the separated metrics report the answered-only accuracy (100%) and the
+ // completion (50%) independently.
+ expect(accuracy).toBe(1);
+ expect(completion).toBe(0.5);
});
it('slow responses reduce speed bonus', () => {
@@ -807,3 +851,129 @@ describe('resolveDrillConfig — progressive multiplication', () => {
expect(progress.windowDays).toBeGreaterThan(0);
});
});
+
+// =============================================================================
+// SCORING MODEL: accuracy vs speed separation, adaptive signal, legacy fallback
+// (issue #2094)
+// =============================================================================
+
+describe('deriveTaskAccuracy / deriveTaskCompletion — legacy-session fallback', () => {
+ it('prefers the persisted fields when present', () => {
+ const task = { accuracy: 0.75, completion: 0.5, questions: [{ answered: 1, correct: true }] };
+ expect(deriveTaskAccuracy(task)).toBe(0.75);
+ expect(deriveTaskCompletion(task)).toBe(0.5);
+ });
+
+ it('derives answered-only accuracy from questions[] for legacy tasks', () => {
+ // 1 correct of 2 ANSWERED (a 3rd is unanswered) → 0.5 accuracy, 2/3 completion.
+ const task = {
+ questions: [
+ { answered: 5, correct: true },
+ { answered: 9, correct: false },
+ { answered: null, correct: false },
+ ],
+ };
+ expect(deriveTaskAccuracy(task)).toBe(0.5);
+ expect(deriveTaskCompletion(task)).toBeCloseTo(2 / 3, 5);
+ });
+
+ it('returns null (never NaN) when there is nothing to derive from', () => {
+ expect(deriveTaskAccuracy({ questions: [] })).toBe(null);
+ expect(deriveTaskAccuracy({ questions: [{ answered: null }] })).toBe(null);
+ expect(deriveTaskCompletion({ questions: [] })).toBe(null);
+ expect(deriveTaskCompletion({})).toBe(null);
+ });
+});
+
+describe('getPostStats — accuracy/completion aggregation', () => {
+ const today = new Date().toISOString().split('T')[0];
+ 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('aggregates answered-only accuracy and completion per drill, mixing new + legacy tasks', async () => {
+ mockSessions([
+ {
+ date: today,
+ score: 50,
+ tasks: [
+ // New-shape task: explicit metrics.
+ { module: 'mental-math', type: 'doubling-chain', score: 60, accuracy: 1, completion: 0.5, questions: [] },
+ // Legacy task (no metrics): derived from questions → accuracy 0.5, completion 1.
+ { module: 'mental-math', type: 'doubling-chain', score: 40, questions: [
+ { answered: 1, correct: true }, { answered: 2, correct: false },
+ ] },
+ ],
+ },
+ ]);
+ const stats = await getPostStats(30);
+ const key = 'mental-math:doubling-chain';
+ // accuracy mean of 1.0 and 0.5 = 0.75; completion mean of 0.5 and 1.0 = 0.75.
+ expect(stats.byDrillAccuracy[key]).toBeCloseTo(0.75, 5);
+ expect(stats.byDrillCompletion[key]).toBeCloseTo(0.75, 5);
+ // Blended byDrill is unchanged (mean of the two scores).
+ expect(stats.byDrill[key]).toBe(50);
+ expect(stats.byDrillCount[key]).toBe(2);
+ });
+});
+
+describe('adaptive signal is accuracy-driven — fast-sloppy vs slow-accurate diverge (issue #2094)', () => {
+ const today = new Date().toISOString().split('T')[0];
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ function mockSessions(sessions) {
+ 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: true } });
+ return Promise.resolve(defaultValue);
+ });
+ }
+
+ // Three doubling-chain tasks (meets minSamples=3), fully completed, at a given
+ // answered-only accuracy — the blended score is deliberately identical across
+ // the two scenarios to prove the OLD blended-score signal could not tell them apart.
+ function accSessions(accuracy) {
+ return [{
+ date: today,
+ score: 55,
+ tasks: Array.from({ length: 3 }, () => ({
+ module: 'mental-math', type: 'doubling-chain', score: 55,
+ accuracy, completion: 1, questions: [],
+ })),
+ }];
+ }
+
+ it('slow-but-accurate (accuracy 1.0) adapts HARDER', async () => {
+ mockSessions(accSessions(1));
+ const { adaptive } = await resolveDrillConfig('doubling-chain', { steps: 8 });
+ expect(adaptive.reason).toBe('harder');
+ expect(adaptive.direction).toBe(1);
+ });
+
+ it('fast-but-sloppy (accuracy 0.0) adapts EASIER — same blended score, opposite direction', async () => {
+ mockSessions(accSessions(0));
+ const { adaptive } = await resolveDrillConfig('doubling-chain', { steps: 8 });
+ expect(adaptive.reason).toBe('easier');
+ expect(adaptive.direction).toBe(-1);
+ });
+
+ it('low completion holds difficulty even at high accuracy', async () => {
+ const sessions = [{
+ date: today, score: 55,
+ tasks: Array.from({ length: 3 }, () => ({
+ module: 'mental-math', type: 'doubling-chain', score: 55,
+ accuracy: 1, completion: 0.2, questions: [],
+ })),
+ }];
+ mockSessions(sessions);
+ const { adaptive } = await resolveDrillConfig('doubling-chain', { steps: 8 });
+ expect(adaptive.reason).toBe('insufficient-completion');
+ expect(adaptive.applied).toBe(false);
+ });
+});
diff --git a/server/services/meatspacePostCognitive.js b/server/services/meatspacePostCognitive.js
index 23c79cac59..6ece85b643 100644
--- a/server/services/meatspacePostCognitive.js
+++ b/server/services/meatspacePostCognitive.js
@@ -66,6 +66,44 @@ function accuracySpeedScore(recomputed, refMs) {
return Math.min(100, Math.max(0, Math.round((correctRatio * 0.8 + speedBonus * 0.2) * 100)));
}
+/**
+ * Answered-only metric bundle stored alongside every scored task, so a reader
+ * can report accuracy (of the answers actually given) separately from completion
+ * (how much of the drill was reached) and average speed — instead of only the
+ * blended headline `score` (issue #2094). Unanswered trials (`answered == null`)
+ * lower `completion`, never `accuracy`. Fields are `null` (never NaN) when there
+ * is no data to derive them from, so downstream readers/aggregators stay safe.
+ *
+ * NOTE: this treats `answered == null` as "not reached". It is therefore the
+ * right helper for skip-means-blank drills (stroop, schulte, mental-rotation,
+ * digit-span, reaction-time) but NOT for n-back, where withholding a press is a
+ * deliberate "no-match" answer — n-back computes its own signal-detection metrics.
+ */
+export function answeredMetrics(recomputed) {
+ const list = Array.isArray(recomputed) ? recomputed : [];
+ const totalCount = list.length;
+ const answered = list.filter(q => q?.answered != null);
+ const answeredCount = answered.length;
+ const correct = answered.filter(q => q?.correct).length;
+ return {
+ accuracy: answeredCount ? correct / answeredCount : null,
+ completion: totalCount ? answeredCount / totalCount : null,
+ avgResponseMs: answeredCount
+ ? Math.round(answered.reduce((s, q) => s + (q.responseMs || 0), 0) / answeredCount)
+ : null,
+ answeredCount,
+ totalCount,
+ };
+}
+
+// Median of a numeric list (integer-rounded for the even case). `null` when empty.
+export function median(nums) {
+ const list = (Array.isArray(nums) ? nums : []).filter(n => Number.isFinite(n)).sort((a, b) => a - b);
+ if (!list.length) return null;
+ const mid = Math.floor(list.length / 2);
+ 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) {
@@ -322,7 +360,8 @@ function scoreNBack(drillData, questions) {
const i = Number.isInteger(q.index) ? q.index : -1;
const isTarget = i >= n && sequence[i] != null && sequence[i] === sequence[i - n];
const expected = isTarget ? 'match' : 'no-match';
- // Anything but an explicit "match" counts as "no-match" (including a skip).
+ // Withholding a press IS the "no-match" answer — n-back is a go/no-go task,
+ // so a skip is a deliberate response, not an unreached trial.
const answered = q.answered === 'match' ? 'match' : q.answered == null ? null : 'no-match';
const effective = answered === 'match' ? 'match' : 'no-match';
return {
@@ -334,7 +373,56 @@ function scoreNBack(drillData, questions) {
responseMs: clampMs(q.responseMs, refMs),
};
});
- return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed };
+
+ // Signal-detection tally: hits/misses over targets, correct-rejections/false-
+ // alarms over non-targets. Scoring on RAW position accuracy (the old behaviour)
+ // rewarded never pressing — with ~30% target density a do-nothing run scored
+ // ~70%. Balanced accuracy — the mean of hit rate and correct-rejection rate —
+ // fixes that: a zero-response run scores ~50 (chance) and an always-press run
+ // is equally penalised for its false alarms (issue #2094).
+ let hits = 0, misses = 0, falseAlarms = 0, correctRejections = 0;
+ for (const q of recomputed) {
+ const pressed = q.answered === 'match';
+ if (q.expected === 'match') {
+ if (pressed) hits += 1; else misses += 1;
+ } else if (pressed) {
+ falseAlarms += 1;
+ } else {
+ correctRejections += 1;
+ }
+ }
+ const targets = hits + misses;
+ const nonTargets = correctRejections + falseAlarms;
+ const hitRate = targets ? hits / targets : null;
+ const correctRejectionRate = nonTargets ? correctRejections / nonTargets : null;
+ // Balanced accuracy over whichever signal classes are present. A run with only
+ // targets (or only non-targets) falls back to the one rate it can measure.
+ let accuracy;
+ if (hitRate != null && correctRejectionRate != null) accuracy = (hitRate + correctRejectionRate) / 2;
+ else if (hitRate != null) accuracy = hitRate;
+ else if (correctRejectionRate != null) accuracy = correctRejectionRate;
+ else accuracy = null;
+
+ const presses = recomputed.filter(q => q.answered === 'match' && q.responseMs > 0);
+ const avgResponseMs = presses.length
+ ? Math.round(presses.reduce((s, q) => s + q.responseMs, 0) / presses.length)
+ : null;
+
+ return {
+ score: accuracy == null ? 0 : Math.min(100, Math.max(0, Math.round(accuracy * 100))),
+ questions: recomputed,
+ accuracy,
+ // Every trial in a go/no-go n-back gets a decision, so completion is 1 when
+ // any trial ran (the metric exists for reader uniformity, not signal).
+ completion: recomputed.length ? 1 : null,
+ avgResponseMs,
+ answeredCount: recomputed.length,
+ totalCount: recomputed.length,
+ hits,
+ misses,
+ falseAlarms,
+ correctRejections,
+ };
}
function scoreDigitSpan(drillData, questions) {
@@ -364,7 +452,7 @@ function scoreDigitSpan(drillData, questions) {
const span = recomputed.filter(q => q.correct).reduce((m, q) => Math.max(m, q.length || 0), 0);
const spanBonus = maxLength > 0 ? Math.min(1, span / maxLength) : 0;
const score = Math.min(100, Math.max(0, Math.round((correctRatio * 0.7 + spanBonus * 0.3) * 100)));
- return { score, questions: recomputed, span };
+ return { score, questions: recomputed, span, ...answeredMetrics(recomputed) };
}
function scoreStroop(drillData, questions) {
@@ -383,7 +471,7 @@ function scoreStroop(drillData, questions) {
responseMs: clampMs(q.responseMs, refMs),
};
});
- return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed };
+ return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed, ...answeredMetrics(recomputed) };
}
// Schulte table: each question is one "find the next number" step, keyed by
@@ -406,7 +494,7 @@ function scoreSchulteTable(drillData, questions) {
responseMs: clampMs(q.responseMs, refMs),
};
});
- return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed };
+ return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed, ...answeredMetrics(recomputed) };
}
// Mental rotation: `index` selects the trial; `answered` is the option index
@@ -428,7 +516,7 @@ function scoreMentalRotation(drillData, questions) {
responseMs: clampMs(q.responseMs, refMs),
};
});
- return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed };
+ return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed, ...answeredMetrics(recomputed) };
}
// Reaction time: 'simple' trials just need a clean (non-false-start) press;
@@ -437,7 +525,10 @@ function scoreMentalRotation(drillData, questions) {
function scoreReactionTime(drillData, questions) {
const trials = drillData?.trials || [];
const mode = drillData?.config?.mode === 'choice' ? 'choice' : 'simple';
+ // `refMs` is the "slow" bound (score 0); `fastMs` the "elite" ceiling (score
+ // 100). A choice reaction is inherently slower, so both shift up in choice mode.
const refMs = mode === 'choice' ? 1200 : 600;
+ const fastMs = mode === 'choice' ? 400 : 200;
const recomputed = questions.map(q => {
const trial = trials[q.index] || {};
const falseStart = q.falseStart === true;
@@ -459,10 +550,41 @@ function scoreReactionTime(drillData, questions) {
expected,
answered,
correct,
+ falseStart,
responseMs: clampMs(q.responseMs, refMs * 3),
};
});
- return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed };
+
+ // Latency IS the score: reaction time is a speed measure, so a valid trial's
+ // median RT vs a reference curve drives the score (issue #2094). A false start
+ // (pressing before the stimulus) invalidates its trial; in choice mode a wrong
+ // target also invalidates it. In simple mode "correct" == a clean, timed press.
+ const valid = recomputed.filter(q => q.correct && !q.falseStart && q.responseMs > 0);
+ const latencies = valid.map(q => q.responseMs);
+ const medianMs = median(latencies);
+ const bestMs = latencies.length ? Math.min(...latencies) : null;
+ const score = medianMs == null
+ ? 0
+ : Math.min(100, Math.max(0, Math.round((100 * (refMs - medianMs)) / (refMs - fastMs))));
+
+ // A press attempt is any non-false-start trial with a real latency; accuracy is
+ // the share of those that were valid (in simple mode every clean press is valid,
+ // so accuracy tracks the false-start-free rate; in choice mode it's target hits).
+ const pressed = recomputed.filter(q => !q.falseStart && q.responseMs > 0);
+ const totalCount = recomputed.length;
+ return {
+ score,
+ questions: recomputed,
+ medianMs,
+ bestMs,
+ accuracy: pressed.length ? valid.length / pressed.length : null,
+ completion: totalCount ? pressed.length / totalCount : null,
+ avgResponseMs: latencies.length
+ ? Math.round(latencies.reduce((s, ms) => s + ms, 0) / latencies.length)
+ : null,
+ answeredCount: pressed.length,
+ totalCount,
+ };
}
/**
diff --git a/server/services/meatspacePostCognitive.test.js b/server/services/meatspacePostCognitive.test.js
index bd749c5f58..4416c986c0 100644
--- a/server/services/meatspacePostCognitive.test.js
+++ b/server/services/meatspacePostCognitive.test.js
@@ -155,7 +155,7 @@ describe('cognitive drill generators', () => {
});
describe('cognitive drill scorers (recompute the answer key, never trust client)', () => {
- it('n-back scores a perfect run near the top and rewards no wrong presses', () => {
+ it('n-back scores a perfect run at 100 via signal-detection (all targets hit, no false alarms)', () => {
// Deterministic sequence: A B A B A → with n=2, positions 2,3,4 are all targets.
const drillData = { type: 'n-back', config: { n: 2, stimulusMs: 2000 }, sequence: ['A', 'B', 'A', 'B', 'A'] };
const questions = [
@@ -163,25 +163,61 @@ describe('cognitive drill scorers (recompute the answer key, never trust client)
{ index: 3, answered: 'match', responseMs: 400 },
{ index: 4, answered: 'match', responseMs: 400 },
];
- const { score, questions: scored } = scoreCognitiveDrill('n-back', drillData, questions);
+ const { score, accuracy, hits, misses, falseAlarms, correctRejections, questions: scored } =
+ scoreCognitiveDrill('n-back', drillData, questions);
expect(scored.every(q => q.correct)).toBe(true);
- // Score is the shared 80% accuracy + 20% speed blend: perfect accuracy floors
- // it at 80, and a 400ms avg response against the 2000ms stimulus window adds
- // 0.2 × (1 − 400/2000) × 100 = 16 → 96. (100 is only reached at instantaneous
- // response, so it's an aspirational ceiling, like a golf score.)
- expect(score).toBe(96);
+ // Balanced accuracy — all 3 targets hit (hitRate 1), no non-targets to falsely
+ // alarm on — is 1.0 → 100. Speed no longer folds into the n-back score.
+ expect(score).toBe(100);
+ expect(accuracy).toBe(1);
+ expect({ hits, misses, falseAlarms, correctRejections }).toEqual({ hits: 3, misses: 0, falseAlarms: 0, correctRejections: 0 });
});
it('n-back marks a false-positive press wrong even if client claims correct', () => {
const drillData = { type: 'n-back', config: { n: 2 }, sequence: ['A', 'B', 'C', 'D'] };
// index 2 (C) is NOT a match of index 0 (A); pressing "match" is wrong.
- const { score, questions } = scoreCognitiveDrill('n-back', drillData, [
+ const { score, falseAlarms, correctRejections, questions } = scoreCognitiveDrill('n-back', drillData, [
{ index: 2, answered: 'match', correct: true, responseMs: 300 },
{ index: 3, answered: null, responseMs: 0 },
]);
expect(questions[0].correct).toBe(false); // client's correct:true ignored
expect(questions[1].correct).toBe(true); // correctly withheld
- expect(score).toBeLessThan(100);
+ // Only non-targets present: one false alarm + one correct rejection →
+ // correct-rejection rate 0.5 → score 50.
+ expect(falseAlarms).toBe(1);
+ expect(correctRejections).toBe(1);
+ expect(score).toBe(50);
+ });
+
+ it('n-back: never responding scores ~50 (chance), not ~70 — the do-nothing exploit is closed', () => {
+ // A B A B A with n=2 → indices 2,3,4 are targets; a full-length sequence would
+ // also carry non-targets, so include one. Sequence A B A C A: idx2=A(target),
+ // idx3=C(non-target), idx4=A(target).
+ const drillData = { type: 'n-back', config: { n: 2 }, sequence: ['A', 'B', 'A', 'C', 'A'] };
+ const questions = [
+ { index: 2, answered: null, responseMs: 0 },
+ { index: 3, answered: null, responseMs: 0 },
+ { index: 4, answered: null, responseMs: 0 },
+ ];
+ const { score, hits, misses, falseAlarms, correctRejections } = scoreCognitiveDrill('n-back', drillData, questions);
+ // 2 targets missed (hitRate 0), 1 non-target correctly rejected (CR rate 1) →
+ // balanced 0.5 → 50. (Old raw-accuracy scoring would have paid ~67 here.)
+ expect({ hits, misses, falseAlarms, correctRejections }).toEqual({ hits: 0, misses: 2, falseAlarms: 0, correctRejections: 1 });
+ expect(score).toBe(50);
+ });
+
+ it('n-back: always pressing is equally penalised for false alarms (~50)', () => {
+ const drillData = { type: 'n-back', config: { n: 2 }, sequence: ['A', 'B', 'A', 'C', 'A'] };
+ const questions = [
+ { index: 2, answered: 'match', responseMs: 300 },
+ { index: 3, answered: 'match', responseMs: 300 },
+ { index: 4, answered: 'match', responseMs: 300 },
+ ];
+ const { score, hits, misses, falseAlarms, correctRejections } = scoreCognitiveDrill('n-back', drillData, questions);
+ // 2 targets hit (hitRate 1), 1 non-target false-alarmed (CR rate 0) →
+ // balanced 0.5 → 50.
+ expect({ hits, misses, falseAlarms, correctRejections }).toEqual({ hits: 2, misses: 0, falseAlarms: 1, correctRejections: 0 });
+ expect(score).toBe(50);
});
it('digit-span expects the reversed sequence for the backward variant', () => {
@@ -253,15 +289,48 @@ describe('cognitive drill scorers (recompute the answer key, never trust client)
it('reaction-time simple mode marks a false start wrong even with a fast responseMs', () => {
const drillData = { type: 'reaction-time', config: { mode: 'simple' }, trials: [{ delayMs: 1000 }, { delayMs: 1000 }] };
- const { questions, score } = scoreCognitiveDrill('reaction-time', drillData, [
+ const { questions, score, medianMs, bestMs } = scoreCognitiveDrill('reaction-time', drillData, [
{ index: 0, answered: 'react', responseMs: 220, falseStart: false },
{ index: 1, answered: null, responseMs: 0, falseStart: true, correct: true }, // client lied "true"
]);
expect(questions[0].correct).toBe(true);
expect(questions[1].correct).toBe(false);
+ // The false-start trial is invalidated — only the 220ms press drives the score.
+ expect(medianMs).toBe(220);
+ expect(bestMs).toBe(220);
expect(score).toBeGreaterThan(0);
});
+ it('reaction-time score is latency-driven: faster median beats slower median', () => {
+ const drillData = { type: 'reaction-time', config: { mode: 'simple' }, trials: [{ delayMs: 800 }, { delayMs: 800 }, { delayMs: 800 }] };
+ const fast = scoreCognitiveDrill('reaction-time', drillData, [
+ { index: 0, answered: 'react', responseMs: 200 },
+ { index: 1, answered: 'react', responseMs: 240 },
+ { index: 2, answered: 'react', responseMs: 260 },
+ ]);
+ const slow = scoreCognitiveDrill('reaction-time', drillData, [
+ { index: 0, answered: 'react', responseMs: 500 },
+ { index: 1, answered: 'react', responseMs: 520 },
+ { index: 2, answered: 'react', responseMs: 540 },
+ ]);
+ expect(fast.medianMs).toBe(240);
+ expect(slow.medianMs).toBe(520);
+ expect(fast.score).toBeGreaterThan(slow.score);
+ // simple-mode reference curve: 200ms→100, 600ms→0. Median 240 → round(100*(600-240)/400)=90.
+ expect(fast.score).toBe(90);
+ });
+
+ it('reaction-time scores 0 when every trial is a false start (no valid latency)', () => {
+ const drillData = { type: 'reaction-time', config: { mode: 'simple' }, trials: [{ delayMs: 500 }, { delayMs: 500 }] };
+ const { score, medianMs, bestMs } = scoreCognitiveDrill('reaction-time', drillData, [
+ { index: 0, answered: null, responseMs: 0, falseStart: true },
+ { index: 1, answered: null, responseMs: 0, falseStart: true },
+ ]);
+ expect(medianMs).toBe(null);
+ expect(bestMs).toBe(null);
+ expect(score).toBe(0);
+ });
+
it('reaction-time choice mode requires the answered index to match the trial target', () => {
const drillData = { type: 'reaction-time', config: { mode: 'choice', choices: 3 }, trials: [{ delayMs: 800, target: 1 }] };
const { questions } = scoreCognitiveDrill('reaction-time', drillData, [