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-2009]): extract & test cognitive drill result-assembly logic

Adam Eivy2691f3b8986f
diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
index 05ab2a9f40..bdc33065c6 100644
--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
@@ -48,12 +48,90 @@ function DrillHeader({ type, isTraining, drillIndex, drillCount }) {
);
}
-function localAccuracyScore(questions) {
+export function localAccuracyScore(questions) {
if (!questions.length) return 0;
const correct = questions.filter(q => q.correct).length;
return Math.round((correct / questions.length) * 100);
}
+// Shared result-assembly shape every sub-runner hands to `onComplete`. The
+// server rescores deterministically from `drillData`/`questions` on save
+// (server/services/meatspacePostCognitive.js) — this is the client-side
+// mirror, and its `index`/`answered`/`responseMs` fields are what that
+// rescoring depends on.
+export function buildCognitiveResult({ type, drill, questions, totalMs }) {
+ return {
+ module: 'cognitive',
+ type,
+ config: drill.config,
+ drillData: drill,
+ questions,
+ score: localAccuracyScore(questions),
+ totalMs,
+ };
+}
+
+// N-BACK — pure result assembly: given the full letter sequence, the lag `n`,
+// and the parallel `answers` array (index-aligned with `seq`, each entry
+// `{ answered: 'match'|null, responseMs }`), build the scored `questions[]`.
+// Only positions `i >= n` have a defined target (there's no "n back" before
+// that), so the first `n` letters are excluded — the off-by-one this guards
+// against is including/excluding the boundary position `i === n` itself.
+export function buildNBackQuestions(seq, n, answers) {
+ return seq
+ .map((letter, i) => ({ letter, i }))
+ .filter(({ i }) => i >= n)
+ .map(({ letter, i }) => {
+ const a = answers[i] || {};
+ const isTarget = seq[i] === seq[i - n];
+ const answeredMatch = a.answered === 'match';
+ return {
+ prompt: letter,
+ index: i,
+ answered: a.answered ?? null,
+ correct: answeredMatch === isTarget,
+ responseMs: a.responseMs || 0,
+ };
+ });
+}
+
+// DIGIT SPAN — pure scoring for one recalled sequence. `direction` decides
+// whether the expected answer is the digits in shown order ('forward') or
+// reversed ('backward') — the bug this guards against is comparing the
+// typed answer against the wrong ordering. Returns both the persisted
+// `question` (what `finish()` assembles into the result) and the raw
+// `expected`/`answeredRaw` strings the training-mode feedback UI displays.
+export function scoreDigitSpanRecall({ digits, direction, index, answeredStr, responseMs }) {
+ const ordered = direction === 'backward' ? [...digits].reverse() : digits;
+ const expected = ordered.join('');
+ const answeredRaw = (answeredStr || '').replace(/\D/g, '');
+ return {
+ question: {
+ prompt: `${digits.length}-digit (${direction})`,
+ index,
+ answered: answeredRaw.length ? answeredRaw : null,
+ correct: answeredRaw.length > 0 && answeredRaw === expected,
+ responseMs,
+ length: digits.length,
+ },
+ expected,
+ answeredRaw,
+ };
+}
+
+// STROOP — pure scoring for one trial: correct iff the picked color name
+// matches the word's INK color (`trial.inkColor`), not the word text itself
+// — the bug this guards against is accidentally grading against the word.
+export function scoreStroopTrial({ trial, index, colorName, responseMs }) {
+ return {
+ prompt: trial.word,
+ index,
+ answered: colorName,
+ correct: colorName === trial.inkColor,
+ responseMs,
+ };
+}
+
// =============================================================================
// N-BACK — a letter stream; signal when the current letter matches N steps back
// =============================================================================
@@ -71,30 +149,8 @@ function NBackRunner({ drill, drillIndex, drillCount, onComplete, isTraining })
const timeoutRef = useRef(null);
const finish = useCallback(() => {
- const questions = seq
- .map((letter, i) => ({ letter, i }))
- .filter(({ i }) => i >= n)
- .map(({ letter, i }) => {
- const a = answersRef.current[i] || {};
- const isTarget = seq[i] === seq[i - n];
- const answeredMatch = a.answered === 'match';
- return {
- prompt: letter,
- index: i,
- answered: a.answered ?? null,
- correct: answeredMatch === isTarget,
- responseMs: a.responseMs || 0,
- };
- });
- onComplete({
- module: 'cognitive',
- type: 'n-back',
- config: drill.config,
- drillData: drill,
- questions,
- score: localAccuracyScore(questions),
- totalMs: Date.now() - startedAtRef.current,
- });
+ const questions = buildNBackQuestions(seq, n, answersRef.current);
+ onComplete(buildCognitiveResult({ type: 'n-back', drill, questions, totalMs: Date.now() - startedAtRef.current }));
}, [drill, seq, n, onComplete]);
const finishRef = useRef(finish);
@@ -208,15 +264,7 @@ function DigitSpanRunner({ drill, drillIndex, drillCount, onComplete, isTraining
const finish = useCallback(() => {
const questions = answersRef.current.filter(Boolean);
- onComplete({
- module: 'cognitive',
- type: 'digit-span',
- config: drill.config,
- drillData: drill,
- questions,
- score: localAccuracyScore(questions),
- totalMs: Date.now() - startedAtRef.current,
- });
+ onComplete(buildCognitiveResult({ type: 'digit-span', drill, questions, totalMs: Date.now() - startedAtRef.current }));
}, [drill, onComplete]);
const finishRef = useRef(finish);
@@ -253,19 +301,16 @@ function DigitSpanRunner({ drill, drillIndex, drillCount, onComplete, isTraining
const advance = useCallback((answeredStr) => {
const digits = sequences[seqIdx].digits || [];
- const ordered = direction === 'backward' ? [...digits].reverse() : digits;
- const expected = ordered.join('');
- const answered = (answeredStr || '').replace(/\D/g, '');
- answersRef.current[seqIdx] = {
- prompt: `${digits.length}-digit (${direction})`,
+ const { question, expected, answeredRaw } = scoreDigitSpanRecall({
+ digits,
+ direction,
index: seqIdx,
- answered: answered.length ? answered : null,
- correct: answered.length > 0 && answered === expected,
+ answeredStr,
responseMs: Date.now() - recallStartRef.current,
- length: digits.length,
- };
+ });
+ answersRef.current[seqIdx] = question;
if (isTraining) {
- setFeedback({ expected, answered, correct: answered.length > 0 && answered === expected });
+ setFeedback({ expected, answered: answeredRaw, correct: question.correct });
} else {
setSeqIdx(i => i + 1);
}
@@ -376,15 +421,7 @@ function StroopRunner({ drill, drillIndex, drillCount, onComplete, isTraining })
const finish = useCallback(() => {
const questions = answersRef.current.filter(Boolean);
- onComplete({
- module: 'cognitive',
- type: 'stroop',
- config: drill.config,
- drillData: drill,
- questions,
- score: localAccuracyScore(questions),
- totalMs: Date.now() - startedAtRef.current,
- });
+ onComplete(buildCognitiveResult({ type: 'stroop', drill, questions, totalMs: Date.now() - startedAtRef.current }));
}, [drill, onComplete]);
const finishRef = useRef(finish);
@@ -396,17 +433,11 @@ function StroopRunner({ drill, drillIndex, drillCount, onComplete, isTraining })
if (advancingRef.current || feedback) return;
const trial = trials[trialIdx];
if (!trial) return;
- const correct = colorName === trial.inkColor;
- answersRef.current[trialIdx] = {
- prompt: trial.word,
- index: trialIdx,
- answered: colorName,
- correct,
- responseMs: Date.now() - trialStartRef.current,
- };
+ const question = scoreStroopTrial({ trial, index: trialIdx, colorName, responseMs: Date.now() - trialStartRef.current });
+ answersRef.current[trialIdx] = question;
const isLast = trialIdx + 1 >= trials.length;
if (isTraining) {
- setFeedback({ correct, expected: trial.inkColor, isLast });
+ setFeedback({ correct: question.correct, expected: trial.inkColor, isLast });
} else {
advancingRef.current = true;
if (isLast) finishRef.current(); else setTrialIdx(i => i + 1);
diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx
new file mode 100644
index 0000000000..adc08e2fac
--- /dev/null
+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx
@@ -0,0 +1,202 @@
+import { describe, it, expect } from 'vitest';
+import {
+ localAccuracyScore,
+ buildCognitiveResult,
+ buildNBackQuestions,
+ scoreDigitSpanRecall,
+ scoreStroopTrial,
+} from './PostCognitiveDrillRunner';
+
+// Result-assembly tests for PostCognitiveDrillRunner's `finish()` builders.
+// The server rescores each drill deterministically from `drillData`/`questions`
+// (server/services/meatspacePostCognitive.js), so the `index`/`answered`/
+// `responseMs` shape these functions produce is load-bearing — a regression
+// here (n-back off-by-one, digit-span reversed-answer comparison, stroop
+// ink-vs-word grading) would pass silently in the interactive UI.
+
+describe('localAccuracyScore', () => {
+ it('returns 0 for an empty question list', () => {
+ expect(localAccuracyScore([])).toBe(0);
+ });
+
+ it('rounds the percentage of correct answers', () => {
+ expect(localAccuracyScore([{ correct: true }, { correct: true }, { correct: false }])).toBe(67);
+ });
+
+ it('returns 100 when every question is correct', () => {
+ expect(localAccuracyScore([{ correct: true }, { correct: true }])).toBe(100);
+ });
+});
+
+describe('buildCognitiveResult', () => {
+ it('assembles the full onComplete payload shape', () => {
+ const drill = { type: 'n-back', config: { n: 2 }, sequence: ['A', 'B'] };
+ const questions = [{ correct: true }, { correct: false }];
+ const result = buildCognitiveResult({ type: 'n-back', drill, questions, totalMs: 4200 });
+ expect(result).toEqual({
+ module: 'cognitive',
+ type: 'n-back',
+ config: { n: 2 },
+ drillData: drill,
+ questions,
+ score: 50,
+ totalMs: 4200,
+ });
+ });
+});
+
+describe('buildNBackQuestions', () => {
+ const seq = ['A', 'B', 'A', 'C', 'B'];
+ const n = 2;
+
+ it('excludes the first n letters — no target is defined before position n', () => {
+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));
+ const questions = buildNBackQuestions(seq, n, answers);
+ expect(questions).toHaveLength(seq.length - n);
+ expect(questions.map(q => q.index)).toEqual([2, 3, 4]);
+ });
+
+ it('includes the boundary position i === n (off-by-one guard)', () => {
+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));
+ const questions = buildNBackQuestions(seq, n, answers);
+ // Position n=2 (seq[2]='A') IS a valid decision point (compares against seq[0]='A').
+ expect(questions[0].index).toBe(2);
+ expect(questions[0].prompt).toBe('A');
+ });
+
+ it('marks a true target correctly answered "match" as correct', () => {
+ // i=2: seq[2]='A' === seq[0]='A' -> isTarget=true. Answered 'match' -> correct.
+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));
+ answers[2] = { answered: 'match', responseMs: 300 };
+ const questions = buildNBackQuestions(seq, n, answers);
+ const q = questions.find(q => q.index === 2);
+ expect(q.correct).toBe(true);
+ expect(q.answered).toBe('match');
+ expect(q.responseMs).toBe(300);
+ });
+
+ it('marks a true target left unanswered as incorrect', () => {
+ // i=2 is a target; no press recorded.
+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));
+ const questions = buildNBackQuestions(seq, n, answers);
+ const q = questions.find(q => q.index === 2);
+ expect(q.correct).toBe(false);
+ expect(q.answered).toBeNull();
+ });
+
+ it('marks a false-alarm press (non-target answered "match") as incorrect', () => {
+ // i=3: seq[3]='C' !== seq[1]='B' -> isTarget=false. Pressed match anyway -> incorrect.
+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));
+ answers[3] = { answered: 'match', responseMs: 250 };
+ const questions = buildNBackQuestions(seq, n, answers);
+ const q = questions.find(q => q.index === 3);
+ expect(q.correct).toBe(false);
+ });
+
+ it('marks a correct rejection (non-target left unanswered) as correct', () => {
+ // i=4: seq[4]='B' === seq[2]='A'? no -> isTarget=false. No press -> correct rejection.
+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));
+ const questions = buildNBackQuestions(seq, n, answers);
+ const q = questions.find(q => q.index === 4);
+ expect(q.correct).toBe(true);
+ });
+});
+
+describe('scoreDigitSpanRecall', () => {
+ it('scores a forward recall correct when digits match in shown order', () => {
+ const { question, expected } = scoreDigitSpanRecall({
+ digits: [1, 2, 3],
+ direction: 'forward',
+ index: 0,
+ answeredStr: '123',
+ responseMs: 1500,
+ });
+ expect(expected).toBe('123');
+ expect(question).toEqual({
+ prompt: '3-digit (forward)',
+ index: 0,
+ answered: '123',
+ correct: true,
+ responseMs: 1500,
+ length: 3,
+ });
+ });
+
+ it('scores a backward recall correct only when digits are reversed', () => {
+ const { question, expected } = scoreDigitSpanRecall({
+ digits: [1, 2, 3],
+ direction: 'backward',
+ index: 0,
+ answeredStr: '321',
+ responseMs: 900,
+ });
+ expect(expected).toBe('321');
+ expect(question.correct).toBe(true);
+ });
+
+ it('scores a backward recall submitted in forward order as incorrect', () => {
+ // Guards the exact bug class named in the issue: comparing against the
+ // wrong ordering for backward digit-span.
+ const { question } = scoreDigitSpanRecall({
+ digits: [1, 2, 3],
+ direction: 'backward',
+ index: 0,
+ answeredStr: '123',
+ responseMs: 900,
+ });
+ expect(question.correct).toBe(false);
+ });
+
+ it('treats an empty answer as unanswered (null), not empty-string-correct', () => {
+ const { question } = scoreDigitSpanRecall({
+ digits: [4, 5],
+ direction: 'forward',
+ index: 1,
+ answeredStr: '',
+ responseMs: 0,
+ });
+ expect(question.answered).toBeNull();
+ expect(question.correct).toBe(false);
+ });
+
+ it('strips non-digit characters before comparing', () => {
+ const { question } = scoreDigitSpanRecall({
+ digits: [7, 8, 9],
+ direction: 'forward',
+ index: 0,
+ answeredStr: '7-8-9',
+ responseMs: 500,
+ });
+ expect(question.answered).toBe('789');
+ expect(question.correct).toBe(true);
+ });
+});
+
+describe('scoreStroopTrial', () => {
+ it('grades correct when the picked color matches the INK color, not the word', () => {
+ // Classic Stroop conflict: word says "RED" but ink is rendered blue.
+ const trial = { word: 'RED', inkColor: 'blue' };
+ const question = scoreStroopTrial({ trial, index: 0, colorName: 'blue', responseMs: 800 });
+ expect(question).toEqual({
+ prompt: 'RED',
+ index: 0,
+ answered: 'blue',
+ correct: true,
+ responseMs: 800,
+ });
+ });
+
+ it('grades incorrect when the picked color matches the word text instead of the ink', () => {
+ // Guards the exact bug class named in the issue: accidentally grading
+ // against the word rather than the ink color.
+ const trial = { word: 'RED', inkColor: 'blue' };
+ const question = scoreStroopTrial({ trial, index: 0, colorName: 'red', responseMs: 800 });
+ expect(question.correct).toBe(false);
+ });
+
+ it('grades correct on a congruent trial where word and ink agree', () => {
+ const trial = { word: 'GREEN', inkColor: 'green' };
+ const question = scoreStroopTrial({ trial, index: 2, colorName: 'green', responseMs: 400 });
+ expect(question.correct).toBe(true);
+ });
+});