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-2094]): legacy n-back fallbacks derive balanced SDT accuracy, not raw correct-flag averages (codex round 5)
Adam Eivy003def6ded6e
diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsxindex aeda361490..ed6adc93a0 100644--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useRef, useCallback } from 'react';import { Brain, Check, X } from 'lucide-react';-import { DRILL_LABELS } from './constants';+import { DRILL_LABELS, nBackBalancedAccuracy } from './constants';/*** Interactive runner for deterministic cognitive drills (n-back, digit-span,@@ -63,25 +63,11 @@ export function localAccuracyScore(questions) {// Pre-save mirror of the server's signal-detection n-back score (issue #2094):// balanced accuracy over targets (hit rate) and non-targets (correct-rejection// rate), so the results screen matches what the save persists instead of raw-// position accuracy (which pays ~70% for never pressing).-export function localNBackScore(drill, questions) {- const seq = drill?.sequence || [];- const n = drill?.config?.n ?? 2;- let hits = 0, misses = 0, falseAlarms = 0, correctRejections = 0;- for (const q of questions) {- const isTarget = q.index >= n && seq[q.index] != null && seq[q.index] === seq[q.index - n];- const pressed = q.answered === 'match';- if (isTarget) { 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 crRate = nonTargets ? correctRejections / nonTargets : null;- // A missing signal class counts as chance (0.5), mirroring the server — a- // never-press run through an all-non-target sequence must not show 100.- const accuracy = hitRate == null && crRate == null ? null : ((hitRate ?? 0.5) + (crRate ?? 0.5)) / 2;+// position accuracy (which pays ~70% for never pressing). Delegates to the+// shared answered+correct derivation in constants.js (buildNBackQuestions marks+// `correct` with exactly the identity that derivation relies on).+export function localNBackScore(_drill, questions) {+ const accuracy = nBackBalancedAccuracy(questions);return accuracy == null ? 0 : Math.min(100, Math.max(0, Math.round(accuracy * 100)));}diff --git a/client/src/components/meatspace/post/PostHistory.jsx b/client/src/components/meatspace/post/PostHistory.jsxindex 993ece1896..724f9f40ee 100644--- a/client/src/components/meatspace/post/PostHistory.jsx+++ b/client/src/components/meatspace/post/PostHistory.jsx@@ -5,7 +5,7 @@ import {} from 'recharts';import { getPostSessions, getPostStats } from '../../../services/api';import useChartColors from '../../../hooks/useChartColors.js';-import { LLM_DRILL_TYPES, DRILL_LABELS, DRILL_TO_DOMAIN, domainLabel } from './constants';+import { LLM_DRILL_TYPES, DRILL_LABELS, DRILL_TO_DOMAIN, domainLabel, nBackBalancedAccuracy } from './constants';const RANGES = [{ label: '7d', days: 7 },@@ -264,8 +264,10 @@ export default function PostHistory({ onBack }) {// completion separately from the blended score column (issue// #2094) — never "correct/total", which counts timed-out// questions as wrong. Prefer the server-persisted metrics; fall- // back to deriving from questions[] for legacy sessions, treating- // n-back's withheld presses as reached decisions (not skips).+ // back to deriving from questions[] for legacy sessions. Legacy+ // n-back needs balanced SDT accuracy (its stored `correct`+ // flags encode the old raw-position model that pays ~70% for+ // never pressing) and is always fully reached (go/no-go).let detail;if (isLlm) {detail = `${task.responses?.length || 0} responses`;@@ -273,9 +275,12 @@ export default function PostHistory({ onBack }) {const questions = task.questions || [];const noGo = task.type === 'n-back';const reached = noGo ? questions : questions.filter(q => q.answered != null);+ const derivedAcc = noGo+ ? nBackBalancedAccuracy(questions)+ : (reached.length ? reached.filter(q => q.correct).length / reached.length : null);const accPct = task.accuracy != null? Math.round(task.accuracy * 100)- : (reached.length ? Math.round((reached.filter(q => q.correct).length / reached.length) * 100) : null);+ : (derivedAcc != null ? Math.round(derivedAcc * 100) : null);const compPct = task.completion != null? Math.round(task.completion * 100): (questions.length ? Math.round((reached.length / questions.length) * 100) : null);diff --git a/client/src/components/meatspace/post/PostSessionResults.jsx b/client/src/components/meatspace/post/PostSessionResults.jsxindex ab822c17eb..5680763f0e 100644--- a/client/src/components/meatspace/post/PostSessionResults.jsx+++ b/client/src/components/meatspace/post/PostSessionResults.jsx@@ -1,6 +1,6 @@import { useState } from 'react';import { CheckCircle, Save, ArrowLeft, ChevronDown, ChevronUp, Dumbbell } from 'lucide-react';-import { LLM_DRILL_TYPES, DRILL_TO_DOMAIN, DOMAINS, DRILL_LABELS } from './constants';+import { LLM_DRILL_TYPES, DRILL_TO_DOMAIN, DOMAINS, DRILL_LABELS, nBackBalancedAccuracy } from './constants';export default function PostSessionResults({ session, tags = {}, onSaved, onBack }) {const { drillResults, sessionScore, state, saveSession, isTraining } = session;@@ -78,18 +78,19 @@ export default function PostSessionResults({ session, tags = {}, onSaved, onBack// this pre-save view falls back to deriving from questions[] since// the session hasn't been scored server-side yet. n-back is a go/no-go// task: a withheld press ("answered: null") is a deliberate no-match- // decision, not an unreached trial — so every trial counts as reached- // (completion 100%, matching the server's completion=1). Note: the- // pre-save fallback accuracy here is raw position accuracy over all- // trials — a close stand-in for (not identical to) the balanced- // signal-detection accuracy the server persists on save (#2093 owns- // the deeper results UI).+ // decision, not an unreached trial — every trial counts as reached+ // (completion 100%, matching the server's completion=1), and its+ // accuracy fallback is the balanced signal-detection derivation+ // (raw `correct` averaging would pay ~70% for never pressing).const questions = result.questions || [];const noGo = result.type === 'n-back';const reached = noGo ? questions : questions.filter(q => q.answered !== null);+ const derivedAcc = noGo+ ? nBackBalancedAccuracy(questions)+ : (reached.length > 0 ? reached.filter(q => q.correct).length / reached.length : null);const accPct = result.accuracy != null? Math.round(result.accuracy * 100)- : (reached.length > 0 ? Math.round((reached.filter(q => q.correct).length / reached.length) * 100) : null);+ : (derivedAcc != null ? Math.round(derivedAcc * 100) : null);const compPct = result.completion != null? Math.round(result.completion * 100): (questions.length > 0 ? Math.round((reached.length / questions.length) * 100) : null);diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.jsindex 50f2c123d2..e02ec0466f 100644--- a/client/src/components/meatspace/post/constants.js+++ b/client/src/components/meatspace/post/constants.js@@ -133,3 +133,25 @@ export const getDifficultyColor = (difficulty) => {if (difficulty === 'medium') return 'bg-port-warning/20 text-port-warning';return 'bg-port-success/20 text-port-success';};++// Balanced (signal-detection) accuracy for n-back questions, derived from only+// `answered` + `correct` — the fields BOTH legacy stored sessions and pre-save+// client results carry. `correct` has always been computed as+// "(pressed ? match : no-match) === expected", so `isTarget = pressed === correct`+// is an identity across old and new scorers; legacy raw `correct` flags must+// NOT be averaged directly (a never-press run would still read ~70%). A missing+// signal class counts as chance (0.5). Mirrors `nBackBalancedAccuracy` in+// server/services/meatspacePost.js — keep the two in sync (issue #2094).+export function nBackBalancedAccuracy(questions) {+ let hits = 0, misses = 0, falseAlarms = 0, correctRejections = 0;+ for (const q of Array.isArray(questions) ? questions : []) {+ const pressed = q?.answered === 'match';+ const isTarget = pressed === !!q?.correct;+ if (isTarget) { if (pressed) hits += 1; else misses += 1; }+ else if (pressed) falseAlarms += 1;+ else correctRejections += 1;+ }+ const hitRate = hits + misses ? hits / (hits + misses) : null;+ const crRate = correctRejections + falseAlarms ? correctRejections / (correctRejections + falseAlarms) : null;+ return hitRate == null && crRate == null ? null : ((hitRate ?? 0.5) + (crRate ?? 0.5)) / 2;+}diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 567658f1e2..20ea9806a5 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -316,15 +316,42 @@ export function computePostStreaks(sessions, todayStr) {* `null` — never NaN. Used by stats aggregation and the adaptive signal so old* and new session shapes both read cleanly.*/+/**+ * Balanced (signal-detection) accuracy for n-back questions, derived from only+ * `answered` + `correct` — fields both legacy stored sessions and pre-save+ * client results carry. Works because `correct` was always computed as+ * "(pressed ? match : no-match) === expected", so `isTarget = pressed === correct`+ * is an identity across old and new scorers. A missing signal class counts as+ * chance (0.5), matching scoreNBack. Exported for the client-fallback mirror+ * tests; the client copy lives in components/meatspace/post/constants.js.+ */+export function nBackBalancedAccuracy(questions) {+ let hits = 0, misses = 0, falseAlarms = 0, correctRejections = 0;+ for (const q of Array.isArray(questions) ? questions : []) {+ const pressed = q?.answered === 'match';+ const isTarget = pressed === !!q?.correct;+ if (isTarget) { if (pressed) hits += 1; else misses += 1; }+ else if (pressed) falseAlarms += 1;+ else correctRejections += 1;+ }+ const hitRate = hits + misses ? hits / (hits + misses) : null;+ const crRate = correctRejections + falseAlarms ? correctRejections / (correctRejections + falseAlarms) : null;+ return hitRate == null && crRate == null ? null : ((hitRate ?? 0.5) + (crRate ?? 0.5)) / 2;+}+export function deriveTaskAccuracy(task) {if (typeof task?.accuracy === 'number' && !Number.isNaN(task.accuracy)) return task.accuracy;const qs = Array.isArray(task?.questions) ? task.questions : [];- // n-back is go/no-go: a withheld press (answered == null) is a deliberate- // "no-match" decision, not an unreached trial — so accuracy spans ALL trials,- // mirroring the client fallbacks in PostHistory/PostSessionResults.- const reached = task?.type === 'n-back' ? qs : qs.filter(q => q?.answered != null);- if (!reached.length) return null;- return reached.filter(q => q?.correct).length / reached.length;+ if (!qs.length) return null;+ // n-back is go/no-go: a withheld press is a deliberate "no-match" decision,+ // and its legacy `correct` flags encode the OLD raw-position model — so the+ // fallback recomputes balanced SDT accuracy rather than averaging them+ // (otherwise a legacy never-press run still reads ~70%). Mirrors the client+ // fallbacks in PostHistory/PostSessionResults.+ if (task?.type === 'n-back') return nBackBalancedAccuracy(qs);+ const answered = qs.filter(q => q?.answered != null);+ if (!answered.length) return null;+ return answered.filter(q => q?.correct).length / answered.length;}/**diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex 47998ae288..7a26b5d11c 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -884,22 +884,38 @@ describe('deriveTaskAccuracy / deriveTaskCompletion — legacy-session fallback'expect(deriveTaskCompletion({})).toBe(null);});- it('legacy n-back: withheld presses are decisions, not skips — accuracy spans all trials, completion is 1', () => {- // 10-trial legacy n-back run: 2 presses (1 correct hit, 1 false alarm) and 8- // withheld (all correct rejections). Answered-only filtering would report- // accuracy 0.5 / completion 0.2; go/no-go semantics say 9/10 and fully reached.+ it('legacy n-back: balanced SDT derivation, not raw correct-flag averaging', () => {+ // 10-trial legacy n-back run: 2 presses (1 hit, 1 false alarm) and 8 withheld+ // trials whose stored correct:true flags mark them correct rejections. Raw+ // correct-flag averaging would report 0.9; balanced SDT tallies hit 1+ // (pressed+correct), false alarm 1 (pressed+incorrect), correct rejections 8+ // (withheld+correct) → hitRate 1, crRate 8/9 → (1 + 8/9)/2 ≈ 0.944.const task = {type: 'n-back',questions: [- { answered: 'match', correct: true },- { answered: 'match', correct: false },- ...Array.from({ length: 8 }, () => ({ answered: null, correct: true })),+ { answered: 'match', correct: true }, // hit (target)+ { answered: 'match', correct: false }, // false alarm (non-target)+ ...Array.from({ length: 8 }, () => ({ answered: null, correct: true })), // correct rejections],};- expect(deriveTaskAccuracy(task)).toBeCloseTo(0.9, 5);+ expect(deriveTaskAccuracy(task)).toBeCloseTo((1 + 8 / 9) / 2, 5);expect(deriveTaskCompletion(task)).toBe(1);expect(deriveTaskCompletion({ type: 'n-back', questions: [] })).toBe(null);});++ it('legacy n-back never-press run derives ~50 (not the stored raw ~70)', () => {+ // Old scorer marked withheld non-targets correct:true and missed targets+ // correct:false. 7 non-targets + 3 missed targets, no presses → raw average+ // would read 70%; balanced SDT reads (hitRate 0 + crRate 1)/2 = 0.5.+ const task = {+ type: 'n-back',+ questions: [+ ...Array.from({ length: 7 }, () => ({ answered: null, correct: true })), // correct rejections+ ...Array.from({ length: 3 }, () => ({ answered: null, correct: false })), // misses+ ],+ };+ expect(deriveTaskAccuracy(task)).toBe(0.5);+ });});describe('getPostStats — accuracy/completion aggregation', () => {