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: validate POST LLM scoring contracts (#4449)
Adam Eivy34974481e769
diff --git a/.changelog/next/fixed-issue-4449.md b/.changelog/next/fixed-issue-4449.mdnew file mode 100644index 0000000000..85bbac2544--- /dev/null+++ b/.changelog/next/fixed-issue-4449.md@@ -0,0 +1 @@+- Validate POST LLM drill contracts and score responses exactly once.diff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.jsxindex f084dc6f9e..f4b5133e55 100644--- a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx@@ -5,6 +5,26 @@ import { scorePostLlmDrill } from '../../../services/api';import { DRILL_LABELS, WORDPLAY_LLM_DRILL_TYPES } from './constants';import { AILoadingIndicator, MissedExamplesDisplay, CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI, scoreWordplayResponse } from './WordplayDrillUI';+export function combineTrainingScoreResults(scoreResults) {+ if (!scoreResults.length) return null;+ const scores = scoreResults.flatMap((result) => result.evaluation.scores);+ const representativeProvenance = scoreResults.find(+ (result) => result.evaluation.provenance.scorer.kind !== 'local',+ )?.evaluation.provenance || scoreResults[0].evaluation.provenance;+ const overallScore = Math.round(+ scoreResults.reduce((sum, result) => sum + result.evaluation.overallScore, 0) / scoreResults.length,+ );+ return {+ score: Math.round(scoreResults.reduce((sum, result) => sum + result.score, 0) / scoreResults.length),+ evaluation: {+ overallScore,+ scores,+ summary: `Average ${overallScore}% across ${scores.length} training responses`,+ provenance: representativeProvenance,+ },+ };+}+export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drillCount, onComplete, isTraining, providerId, model }) {const [questionIndex, setQuestionIndex] = useState(0);const [responses, setResponses] = useState([]);@@ -13,12 +33,15 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drconst [phase, setPhase] = useState('active'); // active | reading | recallconst [items, setItems] = useState([]); // for verbal-fluencyconst [trainingFeedback, setTrainingFeedback] = useState(null); // { score, feedback, scoring }+ const [completionFeedback, setCompletionFeedback] = useState(null); // { scoring, error, responses, totalMs }const inputRef = useRef(null);const timerRef = useRef(null);const questionStartRef = useRef(Date.now());const drillStartRef = useRef(Date.now());const responsesRef = useRef([]);const questionIndexRef = useRef(0);+ const trainingScoreResultsRef = useRef([]);+ const completionInFlightRef = useRef(false);const timeLimitMs = (timeLimitSec || 120) * 1000;const drillType = drill?.type;@@ -28,18 +51,28 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drconst totalPrompts = prompts.length;const currentPrompt = prompts[questionIndex];- const finishDrill = useCallback((finalResponses) => {+ const finishDrill = useCallback((finalResponses, preservedTotalMs) => {+ if (completionInFlightRef.current) return;+ completionInFlightRef.current = true;clearInterval(timerRef.current);- const totalMs = Date.now() - drillStartRef.current;- onComplete({- module: 'llm-drills',- type: drillType,- config: drill.config,- drillData: drill,- responses: finalResponses,- totalMs- });- }, [drill, drillType, onComplete]);+ const totalMs = preservedTotalMs ?? Date.now() - drillStartRef.current;+ const preScored = isTraining ? combineTrainingScoreResults(trainingScoreResultsRef.current) : null;+ setCompletionFeedback({ scoring: true, error: null, responses: finalResponses, totalMs });+ Promise.resolve()+ .then(() => onComplete({+ module: 'llm-drills',+ type: drillType,+ config: drill.config,+ drillData: drill,+ responses: finalResponses,+ totalMs,+ ...(preScored || {}),+ }))+ .catch((err) => {+ setCompletionFeedback({ scoring: false, error: err.message, responses: finalResponses, totalMs });+ })+ .finally(() => { completionInFlightRef.current = false; });+ }, [drill, drillType, isTraining, onComplete]);const handleTimeExpired = useCallback(() => {// Submit whatever we have so far (use refs to avoid stale closures in interval callback)@@ -58,6 +91,9 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drquestionStartRef.current = Date.now();setPhase(drillType === 'story-recall' ? 'reading' : 'active');setTrainingFeedback(null);+ setCompletionFeedback(null);+ trainingScoreResultsRef.current = [];+ completionInFlightRef.current = false;if (isTraining) {setTimeLeft(0);@@ -97,9 +133,6 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drconst responseObj = buildLlmResponseObj({ drillType, questionIndex, items, inputValue, currentPrompt, responseMs });- const newResponses = [...responses, responseObj];- setResponses(newResponses);-// Training mode: score this response immediately and show feedback.// The four wordplay types (compound-chain/bridge-word/double-meaning/// idiom-twist) delegate to scoreWordplayResponse — the same scoring core@@ -108,24 +141,35 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr// existing inline path unchanged.if (isTraining) {setTrainingFeedback({ scoring: true });- if (WORDPLAY_LLM_DRILL_TYPES.includes(drillType)) {- const result = await scoreWordplayResponse(drillType, drill, responseObj, timeLimitMs, providerId, model);- setTrainingFeedback({ scoring: false, ...result });- } else {- const scored = await scorePostLlmDrill(- drillType, drill, [responseObj], timeLimitMs, providerId, model- ).catch(() => null);- const fb = scored?.evaluation?.scores?.[0] || {};- setTrainingFeedback({- scoring: false,- score: fb.score ?? scored?.score ?? 0,- feedback: fb.feedback || scored?.evaluation?.summary || 'No feedback available',- missedExamples: fb.missedExamples,- });- }+ const scoreResult = await (+ WORDPLAY_LLM_DRILL_TYPES.includes(drillType)+ ? scoreWordplayResponse(drillType, drill, responseObj, timeLimitMs, providerId, model, { silent: true })+ .then((result) => result.scoreResult)+ : scorePostLlmDrill(drillType, drill, [responseObj], timeLimitMs, providerId, model, { silent: true })+ ).catch((err) => {+ setTrainingFeedback({ scoring: false, error: err.message });+ return null;+ });+ if (!scoreResult) return;+ const scoredResponse = scoreResult.questions[0];+ const feedback = scoreResult.evaluation.scores[0];+ const newResponses = [...responses, scoredResponse];+ trainingScoreResultsRef.current = [...trainingScoreResultsRef.current, scoreResult];+ setResponses(newResponses);+ setTrainingFeedback({+ scoring: false,+ score: feedback.score,+ feedback: feedback.feedback || scoreResult.evaluation.summary,+ invalidItems: feedback.invalidItems,+ duplicateItems: feedback.duplicateItems,+ missedExamples: feedback.missedExamples,+ });return;}+ const newResponses = [...responses, responseObj];+ setResponses(newResponses);+if (questionIndex + 1 >= totalPrompts) {finishDrill(newResponses);} else {@@ -193,6 +237,31 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drif (timePct <= 10) timerTone = 'error';else if (timePct <= 25) timerTone = 'warning';+ if (completionFeedback) {+ if (completionFeedback.scoring) {+ return (+ <div className="max-w-lg mx-auto space-y-6">+ <AILoadingIndicator label="Scoring your completed drill..." />+ </div>+ );+ }+ return (+ <div className="max-w-lg mx-auto space-y-6">+ <div className="bg-port-card border border-port-error/50 rounded-lg p-5 space-y-3 text-center">+ <XCircle size={40} className="mx-auto text-port-error" />+ <p className="text-sm text-gray-200">Scoring failed: {completionFeedback.error}</p>+ <p className="text-xs text-gray-500">Your completed responses are preserved and have not been assigned a fallback score.</p>+ </div>+ <button+ onClick={() => finishDrill(completionFeedback.responses, completionFeedback.totalMs)}+ className="w-full px-6 py-3 bg-port-accent hover:bg-port-accent/80 text-white font-medium rounded-lg transition-colors"+ >+ Retry scoring+ </button>+ </div>+ );+ }+// Training mode: feedback overlayif (isTraining && trainingFeedback) {if (trainingFeedback.scoring) {@@ -207,6 +276,24 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr);}+ if (trainingFeedback.error) {+ return (+ <div className="max-w-lg mx-auto space-y-6">+ <div className="bg-port-card border border-port-error/50 rounded-lg p-5 space-y-3 text-center">+ <XCircle size={40} className="mx-auto text-port-error" />+ <p className="text-sm text-gray-200">Scoring failed: {trainingFeedback.error}</p>+ <p className="text-xs text-gray-500">Your response is still available. Retry when the provider is ready.</p>+ </div>+ <button+ onClick={handleSubmit}+ className="w-full px-6 py-3 bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2 font-medium rounded-lg transition-colors"+ >+ Retry scoring+ </button>+ </div>+ );+ }+const fbScoreColor = (trainingFeedback.score || 0) >= 70 ? 'text-port-success' :(trainingFeedback.score || 0) >= 40 ? 'text-port-warning' : 'text-port-error';const FbIcon = (trainingFeedback.score || 0) >= 70 ? CheckCircle : XCircle;@@ -223,6 +310,12 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr</div><div className="bg-port-card border border-port-border rounded-lg p-4 space-y-2"><p className="text-sm text-gray-300">{trainingFeedback.feedback}</p>+ {trainingFeedback.invalidItems?.length > 0 && (+ <p className="text-xs text-port-error">Invalid: {trainingFeedback.invalidItems.join(', ')}</p>+ )}+ {trainingFeedback.duplicateItems?.length > 0 && (+ <p className="text-xs text-gray-500">Duplicates: {trainingFeedback.duplicateItems.join(', ')}</p>+ )}<MissedExamplesDisplay examples={trainingFeedback.missedExamples} /></div><buttondiff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.test.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.test.jsxindex a09cd5312f..4c06af36fe 100644--- a/client/src/components/meatspace/post/PostLlmDrillRunner.test.jsx+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.test.jsx@@ -5,12 +5,28 @@ vi.mock('../../../services/api', () => ({scorePostLlmDrill: vi.fn(),}));-import PostLlmDrillRunner, { getPrompts, buildLlmResponseObj } from './PostLlmDrillRunner';+import PostLlmDrillRunner, { getPrompts, buildLlmResponseObj, combineTrainingScoreResults } from './PostLlmDrillRunner';import { scorePostLlmDrill } from '../../../services/api';import { LLM_DRILL_TYPES } from './constants';const noop = () => {};+function scoredResult(score, feedback, response = {}) {+ return {+ score,+ evaluation: {+ overallScore: score,+ scores: [{ score, feedback }],+ summary: feedback,+ provenance: {+ generator: { schemaVersion: '1', promptVersion: '1', providerId: 'provider-a', model: 'model-a' },+ scorer: { kind: 'llm', rubricVersion: '1', providerId: 'provider-a', model: 'model-a' },+ },+ },+ questions: [{ questionIndex: 0, responseMs: 1000, llmScore: score, llmFeedback: feedback, ...response }],+ };+}+beforeEach(() => {vi.clearAllMocks();});@@ -109,9 +125,7 @@ describe('PostLlmDrillRunner — per-question prompt for training-log persistencdescribe('PostLlmDrillRunner — training-mode scoring path', () => {it('scores a wordplay type through the shared scoreWordplayResponse core', async () => {- scorePostLlmDrill.mockResolvedValue({- evaluation: { scores: [{ score: 88, feedback: 'Great chain!' }] },- });+ scorePostLlmDrill.mockResolvedValue(scoredResult(88, 'Great chain!', { items: ['firehouse'] }));render(<PostLlmDrillRunner@@ -133,14 +147,12 @@ describe('PostLlmDrillRunner — training-mode scoring path', () => {await waitFor(() => expect(screen.getByText('88')).toBeInTheDocument());expect(scorePostLlmDrill).toHaveBeenCalledWith(- 'compound-chain', expect.any(Object), expect.any(Array), 60000, null, null+ 'compound-chain', expect.any(Object), expect.any(Array), 60000, null, null, { silent: true });});it('still scores a non-wordplay LLM type (word-association) through its original inline path (unaffected by the wordplay extraction)', async () => {- scorePostLlmDrill.mockResolvedValue({- evaluation: { scores: [{ score: 65, feedback: 'Solid associations' }] },- });+ scorePostLlmDrill.mockResolvedValue(scoredResult(65, 'Solid associations', { response: 'wave, blue, salt' }));render(<PostLlmDrillRunner@@ -161,6 +173,88 @@ describe('PostLlmDrillRunner — training-mode scoring path', () => {await waitFor(() => expect(screen.getByText('65')).toBeInTheDocument());});++ it('carries the immediate training score into completion without a second request', async () => {+ const onComplete = vi.fn().mockResolvedValue({});+ scorePostLlmDrill.mockResolvedValue(scoredResult(88, 'Great chain!', { items: ['firehouse'] }));++ render(+ <PostLlmDrillRunner+ drill={{ type: 'compound-chain', challenges: [{ rootWord: 'fire', position: 'prefix', minExpected: 1 }] }}+ timeLimitSec={60}+ drillIndex={0}+ drillCount={1}+ onComplete={onComplete}+ isTraining+ />+ );++ fireEvent.change(screen.getByPlaceholderText(/other half/i), { target: { value: 'firehouse' } });+ fireEvent.click(screen.getByText('Add'));+ fireEvent.click(screen.getByText(/Done — Submit 1 compounds/));+ await screen.findByText('88');+ fireEvent.click(screen.getByText('Next'));++ await waitFor(() => expect(onComplete).toHaveBeenCalledTimes(1));+ expect(scorePostLlmDrill).toHaveBeenCalledTimes(1);+ expect(onComplete.mock.calls[0][0]).toMatchObject({+ score: 88,+ responses: [{ items: ['firehouse'], llmScore: 88 }],+ evaluation: { overallScore: 88, scores: [{ score: 88, feedback: 'Great chain!' }] },+ });+ });++ it('keeps a failed training score retryable without adding a fallback response', async () => {+ scorePostLlmDrill+ .mockRejectedValueOnce(new Error('provider unavailable'))+ .mockResolvedValueOnce(scoredResult(75, 'Validated', { response: 'wave' }));++ render(+ <PostLlmDrillRunner+ drill={{ type: 'word-association', questions: [{ prompt: 'ocean' }] }}+ timeLimitSec={60}+ drillIndex={0}+ drillCount={1}+ onComplete={noop}+ isTraining+ />+ );++ fireEvent.change(screen.getByPlaceholderText(/type your associations/i), { target: { value: 'wave' } });+ fireEvent.click(screen.getByText('Next'));+ expect(await screen.findByText(/Scoring failed: provider unavailable/)).toBeInTheDocument();+ fireEvent.click(screen.getByText('Retry scoring'));++ expect(await screen.findByText('75')).toBeInTheDocument();+ expect(scorePostLlmDrill).toHaveBeenCalledTimes(2);+ });+});++describe('combineTrainingScoreResults', () => {+ it('combines already-scored responses without changing their provenance', () => {+ const combined = combineTrainingScoreResults([+ scoredResult(80, 'First'), scoredResult(60, 'Second'),+ ]);++ expect(combined).toMatchObject({+ score: 70,+ evaluation: { overallScore: 70, scores: [{ score: 80 }, { score: 60 }] },+ });+ expect(combined.evaluation.provenance).toEqual(scoredResult(80, 'First').evaluation.provenance);+ });++ it('retains provider provenance when a hybrid response follows a local response', () => {+ const local = scoredResult(100, 'Known answer');+ local.evaluation.provenance.scorer = {+ kind: 'local', rubricVersion: '1', providerId: 'local', model: 'local',+ };+ const hybrid = scoredResult(60, 'Semantically validated');+ hybrid.evaluation.provenance.scorer.kind = 'hybrid';++ const combined = combineTrainingScoreResults([local, hybrid]);++ expect(combined.evaluation.provenance).toEqual(hybrid.evaluation.provenance);+ });});// getPrompts pure-function coverage (issue #2102 gap #9): each of the 14diff --git a/client/src/components/meatspace/post/WordplayDrillUI.jsx b/client/src/components/meatspace/post/WordplayDrillUI.jsxindex ef0465bc4d..53e677a59a 100644--- a/client/src/components/meatspace/post/WordplayDrillUI.jsx+++ b/client/src/components/meatspace/post/WordplayDrillUI.jsx@@ -9,15 +9,18 @@ import { getDifficultyColor } from './constants';// entry points score/feed back identically instead of maintaining two// slightly-drifted copies of the same score?.evaluation?.scores?.[0]// unwrapping logic (see issue #2097).-export async function scoreWordplayResponse(type, drill, responseObj, timeLimitMs, providerId, model) {- const scored = await scorePostLlmDrill(type, drill, [responseObj], timeLimitMs, providerId, model).catch(() => null);- const fb = scored?.evaluation?.scores?.[0] || {};+export async function scoreWordplayResponse(type, drill, responseObj, timeLimitMs, providerId, model, options = {}) {+ const scored = await scorePostLlmDrill(type, drill, [responseObj], timeLimitMs, providerId, model, options);+ const fb = scored.evaluation.scores[0];return {- score: fb.score ?? scored?.score ?? 0,- feedback: fb.feedback || scored?.evaluation?.summary || 'No feedback available',+ score: fb.score,+ feedback: fb.feedback || scored.evaluation.summary,validCount: fb.validCount,invalidItems: fb.invalidItems,+ duplicateItems: fb.duplicateItems,missedExamples: fb.missedExamples,+ scoreResult: scored,+ scoredResponse: scored.questions[0],};}diff --git a/client/src/components/meatspace/post/WordplayTrainer.jsx b/client/src/components/meatspace/post/WordplayTrainer.jsxindex d566984c41..bd8596c760 100644--- a/client/src/components/meatspace/post/WordplayTrainer.jsx+++ b/client/src/components/meatspace/post/WordplayTrainer.jsx@@ -345,8 +345,12 @@ export default function WordplayTrainer({ onBack, onContinue, config, onConfigUp// for these same four drill types (issue #2097) — one scoring path.setFeedback({ scoring: true });const result = await scoreWordplayResponse(- selectedMode, drill, responseObj, SCORE_TIMEOUT_MS, activeProviderId, activeModel- );+ selectedMode, drill, responseObj, SCORE_TIMEOUT_MS, activeProviderId, activeModel, { silent: true }+ ).catch((err) => {+ setFeedback({ scoring: false, error: err.message });+ return null;+ });+ if (!result) return;setFeedback({ scoring: false, ...result });setResults(prev => [...prev, {...responseObj,@@ -532,6 +536,25 @@ export default function WordplayTrainer({ onBack, onContinue, config, onConfigUp);}+ if (feedback.error) {+ return (+ <div className="max-w-lg mx-auto space-y-6">+ <ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />+ <div className="bg-port-card border border-port-error/50 rounded-lg p-5 space-y-3 text-center">+ <XCircle size={40} className="mx-auto text-port-error" />+ <p className="text-sm text-gray-200">Scoring failed: {feedback.error}</p>+ <p className="text-xs text-gray-500">Your response is still here. Retry when the provider is available.</p>+ </div>+ <button+ onClick={handleSubmit}+ className="w-full px-6 py-3 bg-port-accent hover:bg-port-accent/80 text-white font-medium rounded-lg transition-colors"+ >+ Retry scoring+ </button>+ </div>+ );+ }+const fbScoreColor = (feedback.score || 0) >= 70 ? 'text-port-success' :(feedback.score || 0) >= 40 ? 'text-port-warning' : 'text-port-error';const FbIcon = (feedback.score || 0) >= 70 ? CheckCircle : XCircle;diff --git a/client/src/components/meatspace/post/WordplayTrainer.test.jsx b/client/src/components/meatspace/post/WordplayTrainer.test.jsxindex b1a4fcb916..2d81ba7b0e 100644--- a/client/src/components/meatspace/post/WordplayTrainer.test.jsx+++ b/client/src/components/meatspace/post/WordplayTrainer.test.jsx@@ -25,6 +25,22 @@ import {// suite is competing for CI's event loop.const GENERATED_DRILL_TIMEOUT = 5_000;+function wordplayScore(score, feedback, response = {}) {+ return {+ score,+ evaluation: {+ overallScore: score,+ scores: [{ score, feedback }],+ summary: feedback,+ provenance: {+ generator: { schemaVersion: '1', promptVersion: '1', providerId: 'provider-a', model: 'model-a' },+ scorer: { kind: 'local', rubricVersion: '1', providerId: 'local', model: 'local' },+ },+ },+ questions: [{ questionIndex: 0, responseMs: 1000, llmScore: score, llmFeedback: feedback, ...response }],+ };+}+// Vitest's default per-test timeout is also 5s, so a `waitFor` bounded at// GENERATED_DRILL_TIMEOUT was allowed to consume the entire test budget: the// inner bound could never actually report its own failure, and a test with work@@ -105,9 +121,7 @@ describe('WordplayTrainer — training-log persistence (issue #2097)', () => {type: 'compound-chain',challenges: [{ rootWord: 'fire', position: 'prefix', minExpected: 1 }],});- scorePostLlmDrill.mockResolvedValue({- evaluation: { scores: [{ score: 85, feedback: 'Nice compounds!' }] },- });+ scorePostLlmDrill.mockResolvedValue(wordplayScore(85, 'Nice compounds!', { items: ['firehouse'] }));render(<TrainerHarness onBack={() => {}} onContinue={onContinue} config={{}} onConfigUpdate={() => {}} />);@@ -161,9 +175,7 @@ describe('WordplayTrainer — training-log persistence (issue #2097)', () => {type: 'compound-chain',challenges: [{ rootWord: 'fire', position: 'prefix', minExpected: 1 }],});- scorePostLlmDrill.mockResolvedValue({- evaluation: { scores: [{ score: 85, feedback: 'Nice compounds!' }] },- });+ scorePostLlmDrill.mockResolvedValue(wordplayScore(85, 'Nice compounds!', { items: ['firehouse'] }));render(<TrainerHarness onBack={() => {}} onContinue={onContinue} config={{}} onConfigUpdate={() => {}} />);await selectMode('Compound Chain');@@ -238,9 +250,7 @@ describe('WordplayTrainer — training-log persistence (issue #2097)', () => {{ clues: ['sun___', '___light'], answer: 'flower' },],});- scorePostLlmDrill.mockResolvedValue({- evaluation: { scores: [{ score: 40, feedback: 'Not quite' }] },- });+ scorePostLlmDrill.mockResolvedValue(wordplayScore(40, 'Not quite', { response: 'wrongword' }));render(<TrainerHarness onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);@@ -283,9 +293,7 @@ describe('WordplayTrainer — training-log persistence (issue #2097)', () => {type: 'bridge-word',puzzles: [{ clues: ['news___', '___back'], answer: 'paper' }],});- scorePostLlmDrill.mockResolvedValue({- evaluation: { scores: [{ score: 40, feedback: 'Not quite' }] },- });+ scorePostLlmDrill.mockResolvedValue(wordplayScore(40, 'Not quite', { response: 'wrongword' }));render(<TrainerHarness onBack={() => {}} config={{}} onConfigUpdate={() => {}} />);diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex 142e4c31a8..db8fb51390 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -418,10 +418,14 @@ export function usePostSession() {const completeLlmDrill = useCallback(async (drillResult) => {const isLlm = LLM_DRILL_TYPES.includes(drillResult.type);+ const hasReusableTrainingScore = isTraining+ && Number.isFinite(drillResult.score)+ && drillResult.evaluation?.scores?.length === drillResult.responses?.length+ && drillResult.evaluation?.provenance != null+ && drillResult.responses?.every((response) => Number.isFinite(response.llmScore));let scoredResult = drillResult;- if (isLlm && drillResult.responses?.length > 0) {- setState(STATES.LOADING);+ if (isLlm && drillResult.responses?.length > 0 && !hasReusableTrainingScore) {const drillConfig = drills[currentDrillIndex];const timeLimitMs = (drillConfig?.timeLimitSec || 120) * 1000;const scoreResult = await scorePostLlmDrill(@@ -429,19 +433,15 @@ export function usePostSession() {timeLimitMs, drillConfig?.providerId, drillConfig?.model, { silent: true }).catch(err => {toast.error(`LLM scoring failed: ${err.message}`);- return null;+ throw err;});- if (scoreResult) {- scoredResult = {- ...drillResult,- score: scoreResult.score,- responses: scoreResult.questions || drillResult.responses,- evaluation: scoreResult.evaluation- };- } else {- scoredResult = { ...drillResult, score: 0 };- }+ scoredResult = {+ ...drillResult,+ score: scoreResult.score,+ responses: scoreResult.questions,+ evaluation: scoreResult.evaluation+ };}scoredResult = { ...scoredResult, id: scoredResult.id || newRunId() };@@ -455,7 +455,8 @@ export function usePostSession() {setSessionScore(computeSessionScoreFromResults(newResults));setState(STATES.COMPLETE);}- }, [drillResults, currentDrillIndex, drills]);+ return scoredResult;+ }, [drillResults, currentDrillIndex, drills, isTraining]);// Interactive cognitive drills (n-back / digit-span / stroop) build their own// fully-formed result (questions + local score) and hand it back here. Unlikediff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.jsindex f37c2da500..c6fa186369 100644--- a/client/src/hooks/usePostSession.test.js+++ b/client/src/hooks/usePostSession.test.js@@ -503,6 +503,73 @@ describe('usePostSession — LLM training-log correctCount (issue #2097)', () =>}));});+ it('reuses immediate training scores instead of calling the scorer again at completion', async () => {+ generatePostDrill.mockResolvedValue({+ type: 'compound-chain', config: {}, challenges: [{ rootWord: 'fire' }],+ });+ const evaluation = {+ overallScore: 90,+ scores: [{ score: 90, feedback: 'Validated' }],+ summary: 'Validated',+ provenance: {+ generator: { schemaVersion: '1', promptVersion: '1', providerId: 'provider-a', model: 'model-a' },+ scorer: { kind: 'hybrid', rubricVersion: '1', providerId: 'provider-a', model: 'model-a' },+ },+ };++ const { result } = renderHook(() => usePostSession());+ await act(async () => {+ await result.current.startSession([{ type: 'compound-chain', config: {}, timeLimitSec: 120 }], true);+ });+ await act(async () => {+ await result.current.completeLlmDrill({+ module: 'llm-drills',+ type: 'compound-chain',+ config: {},+ drillData: {},+ score: 90,+ evaluation,+ responses: [{ questionIndex: 0, items: ['firehouse'], responseMs: 500, llmScore: 90, llmFeedback: 'Validated' }],+ totalMs: 5000,+ });+ });++ expect(scorePostLlmDrill).not.toHaveBeenCalled();+ expect(result.current.drillResults[0]).toMatchObject({ score: 90, evaluation });+ });++ it('scores a non-training response set in one completion batch', async () => {+ generatePostDrill.mockResolvedValue({+ type: 'word-association', config: {}, questions: [{ prompt: 'ocean' }, { prompt: 'forest' }],+ });+ scorePostLlmDrill.mockResolvedValue({+ score: 75,+ questions: [+ { questionIndex: 0, response: 'wave', llmScore: 80 },+ { questionIndex: 1, response: 'trees', llmScore: 70 },+ ],+ evaluation: { overallScore: 75, scores: [{ score: 80 }, { score: 70 }] },+ });++ const { result } = renderHook(() => usePostSession());+ await act(async () => {+ await result.current.startSession([{ type: 'word-association', config: {}, timeLimitSec: 120 }], false);+ });+ await act(async () => {+ await result.current.completeLlmDrill({+ module: 'llm-drills', type: 'word-association', drillData: result.current.currentDrill,+ responses: [+ { questionIndex: 0, response: 'wave', responseMs: 500 },+ { questionIndex: 1, response: 'trees', responseMs: 500 },+ ],+ totalMs: 1000,+ });+ });++ expect(scorePostLlmDrill).toHaveBeenCalledTimes(1);+ expect(scorePostLlmDrill.mock.calls[0][2]).toHaveLength(2);+ });+it('logs correctCount=0 when the llmScore is below the correct threshold', async () => {generatePostDrill.mockResolvedValue({type: 'bridge-word', config: {}, puzzles: [{ clues: ['a', 'b'] }],diff --git a/server/lib/README.md b/server/lib/README.mdindex 2ee41463c4..c27bc553fe 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -53,6 +53,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `notesValidation.js` | Notes route schemas + safe-relative-path guard. || `peerSyncValidation.js` | Federated peer-sync wire/request schemas (push payload, subscribe, sync-now, pull-metadata). || `pipelineValidation.js` | Creative-production pipeline schemas (Writers Room works/folders/live-mode/drafts, story-bible character/place/object, editorial checks, storyboard shots/scenes, prompt-stage config, issue-list query). |+| `postLlmContracts.js` | Versioned POST LLM generation/scoring schemas, semantic-verdict validation, and secret-free generator/scorer provenance with explicit legacy normalization. || `postValidation.js` | MeatSpace POST (Power On Self Test) schemas — drill config (incl. adaptive toggle), drill generation/scoring, sessions, memory builder, training log. || `privacyValidation.js` | Privacy Center schemas — PII Vault (issue #2140): vault record create/update (partial PUT), list query, UUID params; the vault type/status vocabularies + the sensitive-type (`ssn`/`passport`/`drivers_license`/`financial_account`) `useForScans` hard-false rule and per-type scan defaults. Trusted Organizations registry (issue #2141): org create/update (partial PUT), list query, UUID params, and the replace-set holdings schema. Data-broker database + case ledger (issue #2144): broker list/case-list query filters, the scan-start + refresh action bodies, and the `PRIVACY_BROKER_CASE_STATES` vocabulary. || `roundsValidation.js` | Rounds workbench shape bounds + pure record sanitizers (sections, layers, recordings, pitch analysis, references, progress) — `sanitizeRound(raw, builtinIds)` and the length/count limits shared with routes/rounds.js. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 930f4d5a92..53375dc862 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -36,6 +36,7 @@ export * as musicVideoValidation from './musicVideoValidation.js';export * as notesValidation from './notesValidation.js';export * as peerSyncValidation from './peerSyncValidation.js';export * as pipelineValidation from './pipelineValidation.js';+export * as postLlmContracts from './postLlmContracts.js';export * as postValidation from './postValidation.js';export * as privacyValidation from './privacyValidation.js';export * as roundsValidation from './roundsValidation.js';diff --git a/server/lib/postLlmContracts.js b/server/lib/postLlmContracts.jsnew file mode 100644index 0000000000..b56daa4062--- /dev/null+++ b/server/lib/postLlmContracts.js@@ -0,0 +1,292 @@+import { z } from 'zod';++export const POST_LLM_GENERATOR_SCHEMA_VERSION = '1';+export const POST_LLM_PROMPT_VERSIONS = Object.freeze({+ 'word-association': '1',+ 'story-recall': '1',+ 'verbal-fluency': '1',+ 'wit-comeback': '1',+ 'pun-wordplay': '1',+ 'compound-chain': '1',+ 'bridge-word': '1',+ 'double-meaning': '1',+ 'idiom-twist': '1',+ 'what-if': '1',+ 'alternative-uses': '1',+ 'story-prompt': '1',+ 'invention-pitch': '1',+ reframe: '1',+});++export const POST_LLM_RUBRIC_VERSIONS = Object.freeze(+ Object.fromEntries(Object.keys(POST_LLM_PROMPT_VERSIONS).map((type) => [type, '1'])),+);++const shortText = z.string().trim().min(1).max(500);+const longText = z.string().trim().min(1).max(5000);+const responseItem = z.string().trim().min(1).max(500);+const rejectedResponseItem = z.string().max(500);+const difficulty = z.enum(['easy', 'medium', 'hard']);++function normalizedKey(value) {+ return value.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '');+}++const compoundChainItemSchema = z.object({+ rootWord: shortText,+ position: z.enum(['prefix', 'suffix', 'both']),+ examples: z.array(shortText).min(10).max(15),+ minExpected: z.number().int().min(1).max(50),+}).superRefine((challenge, ctx) => {+ const root = normalizedKey(challenge.rootWord);+ const seen = new Set();+ challenge.examples.forEach((example, index) => {+ const normalized = normalizedKey(example);+ const inAllowedPosition = challenge.position === 'prefix'+ ? normalized.startsWith(root)+ : challenge.position === 'suffix'+ ? normalized.endsWith(root)+ : normalized.startsWith(root) || normalized.endsWith(root);+ if (!inAllowedPosition || normalized === root) {+ ctx.addIssue({+ code: 'custom', path: ['examples', index], message: 'example must contain the root in the declared position',+ });+ }+ if (seen.has(normalized)) {+ ctx.addIssue({ code: 'custom', path: ['examples', index], message: 'duplicate compound example' });+ }+ seen.add(normalized);+ });+});++const generationItemSchemas = {+ 'word-association': z.object({+ prompt: shortText,+ hints: z.string().trim().max(500).optional().default(''),+ }),+ 'story-recall': z.object({+ paragraph: longText,+ questions: z.array(z.object({+ question: shortText,+ answer: shortText,+ aliases: z.array(shortText).max(10).optional().default([]),+ })).min(3).max(4),+ }),+ 'verbal-fluency': z.object({+ category: shortText,+ minExpected: z.number().int().min(1).max(100),+ examples: z.array(shortText).min(3).max(5),+ }),+ 'wit-comeback': z.object({+ setup: longText,+ context: z.string().trim().max(1000).optional().default(''),+ difficulty,+ }),+ 'pun-wordplay': z.object({+ type: z.enum(['pun-topic', 'complete-sentence', 'punny-name', 'wordplay-headline']),+ prompt: longText,+ topic: shortText,+ example: longText,+ }),+ 'compound-chain': compoundChainItemSchema,+ 'bridge-word': z.object({+ clues: z.array(shortText).min(3).max(4),+ answer: shortText,+ difficulty: difficulty.optional().default('medium'),+ hint: z.string().trim().max(500).optional().default(''),+ }),+ 'double-meaning': z.object({+ word: shortText,+ meanings: z.array(shortText).min(2).max(5),+ example: z.string().trim().max(2000).optional().default(''),+ difficulty: difficulty.optional().default('medium'),+ }),+ 'idiom-twist': z.object({+ idiom: shortText,+ domain: shortText,+ example: z.string().trim().max(2000).optional().default(''),+ difficulty: difficulty.optional().default('medium'),+ }),+ 'what-if': z.object({ prompt: longText, category: shortText }),+ 'alternative-uses': z.object({+ object: shortText,+ commonUse: shortText,+ minExpected: z.number().int().min(1).max(100),+ }),+ 'story-prompt': z.object({ words: z.array(shortText).length(3) }),+ 'invention-pitch': z.object({ problem: longText, category: shortText, difficulty }),+ reframe: z.object({ situation: longText, severity: z.enum(['low', 'medium', 'high']) }),+};++const generationFields = {+ 'word-association': 'questions',+ 'story-recall': 'exercises',+ 'verbal-fluency': 'categories',+ 'wit-comeback': 'scenarios',+ 'pun-wordplay': 'challenges',+ 'compound-chain': 'challenges',+ 'bridge-word': 'puzzles',+ 'double-meaning': 'challenges',+ 'idiom-twist': 'challenges',+ 'what-if': 'scenarios',+ 'alternative-uses': 'objects',+ 'story-prompt': 'prompts',+ 'invention-pitch': 'problems',+ reframe: 'situations',+};++const identity = z.string().trim().min(1).max(300);++export const postLlmGeneratorProvenanceSchema = z.object({+ schemaVersion: identity,+ promptVersion: identity,+ providerId: identity,+ model: identity,+});++export const postLlmScorerProvenanceSchema = z.object({+ kind: z.enum(['local', 'llm', 'hybrid', 'legacy']),+ rubricVersion: identity,+ providerId: identity,+ model: identity,+});++export const postLlmEvaluationProvenanceSchema = z.object({+ generator: postLlmGeneratorProvenanceSchema,+ scorer: postLlmScorerProvenanceSchema,+});++export const LEGACY_POST_LLM_PROVENANCE = Object.freeze({+ generator: Object.freeze({+ schemaVersion: 'legacy', promptVersion: 'legacy', providerId: 'legacy', model: 'legacy',+ }),+ scorer: Object.freeze({+ kind: 'legacy', rubricVersion: 'legacy', providerId: 'legacy', model: 'legacy',+ }),+});++export const postLlmEvaluationScoreSchema = z.object({+ score: z.number().min(0).max(100),+ feedback: z.string().max(2000),+ validCount: z.number().int().min(0).optional(),+ validItems: z.array(responseItem).max(200).optional(),+ invalidItems: z.array(rejectedResponseItem).max(200).optional(),+ duplicateItems: z.array(rejectedResponseItem).max(200).optional(),+ missedExamples: z.array(responseItem).max(200).optional(),+});++const currentEvaluationSchema = z.object({+ overallScore: z.number().min(0).max(100),+ scores: z.array(postLlmEvaluationScoreSchema).max(100),+ summary: z.string().max(4000),+ provenance: postLlmEvaluationProvenanceSchema,+});++function legacyEvaluation(value) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return value;+ if ('overallScore' in value) {+ return {+ ...value,+ scores: Array.isArray(value.scores) ? value.scores : [],+ summary: typeof value.summary === 'string' ? value.summary : 'Legacy evaluation',+ provenance: value.provenance || LEGACY_POST_LLM_PROVENANCE,+ };+ }+ if ('score' in value || Array.isArray(value.breakdown)) {+ const scores = (value.breakdown || []).map((item) => ({+ score: item?.score,+ feedback: item?.feedback || '',+ }));+ const derivedScore = scores.length+ ? Math.round(scores.reduce((sum, item) => sum + item.score, 0) / scores.length)+ : undefined;+ return {+ overallScore: value.score ?? derivedScore,+ scores,+ summary: 'Legacy evaluation',+ provenance: LEGACY_POST_LLM_PROVENANCE,+ };+ }+ return value;+}++export const postLlmEvaluationSchema = z.preprocess(legacyEvaluation, currentEvaluationSchema);++function contractError(label, issues) {+ const details = issues+ .map((issue) => `${issue.path.length ? issue.path.join('.') : 'response'}: ${issue.message}`)+ .join('; ');+ return new Error(`Invalid ${label}: ${details}`);+}++function parseContract(schema, value, label) {+ const parsed = schema.safeParse(value);+ if (!parsed.success) throw contractError(label, parsed.error.issues);+ return parsed.data;+}++export function validatePostLlmGenerationPayload(type, value, count) {+ const field = generationFields[type];+ const itemSchema = generationItemSchemas[type];+ if (!field || !itemSchema) throw new Error(`Unsupported POST LLM generator type: ${type}`);+ const schema = z.object({ [field]: z.array(itemSchema).length(count) });+ return parseContract(schema, value, `${type} generation response`);+}++export function validatePostLlmScorePayload(value, responseCount) {+ const schema = z.object({+ overallScore: z.number().min(0).max(100),+ scores: z.array(postLlmEvaluationScoreSchema).length(responseCount),+ summary: z.string().max(4000),+ });+ return parseContract(schema, value, 'POST LLM scoring response');+}++export function validatePostLlmSemanticVerdicts(value, candidates, label) {+ const keys = new Set(candidates.map(({ responseIndex, itemIndex }) => `${responseIndex}:${itemIndex}`));+ const schema = z.object({+ verdicts: z.array(z.object({+ responseIndex: z.number().int().min(0),+ itemIndex: z.number().int().min(0),+ valid: z.boolean(),+ reason: z.string().max(500).optional(),+ })).length(candidates.length),+ }).superRefine((data, ctx) => {+ const seen = new Set();+ data.verdicts.forEach((verdict, index) => {+ const key = `${verdict.responseIndex}:${verdict.itemIndex}`;+ if (!keys.has(key)) {+ ctx.addIssue({ code: 'custom', path: ['verdicts', index], message: 'verdict does not match a submitted item' });+ } else if (seen.has(key)) {+ ctx.addIssue({ code: 'custom', path: ['verdicts', index], message: 'duplicate verdict for submitted item' });+ }+ seen.add(key);+ });+ for (const key of keys) {+ if (!seen.has(key)) ctx.addIssue({ code: 'custom', path: ['verdicts'], message: `missing verdict for ${key}` });+ }+ });+ return parseContract(schema, value, label);+}++export function buildPostLlmGeneratorProvenance(type, providerId, model) {+ return postLlmGeneratorProvenanceSchema.parse({+ schemaVersion: POST_LLM_GENERATOR_SCHEMA_VERSION,+ promptVersion: POST_LLM_PROMPT_VERSIONS[type],+ providerId,+ model,+ });+}++export function buildPostLlmScorerProvenance(type, kind, providerId, model) {+ return postLlmScorerProvenanceSchema.parse({+ kind,+ rubricVersion: POST_LLM_RUBRIC_VERSIONS[type],+ providerId,+ model,+ });+}++export function normalizePostLlmEvaluation(value) {+ return postLlmEvaluationSchema.parse(value);+}diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 67c5254a59..ca66eea101 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -3,6 +3,7 @@ import { CACHEABLE_TYPES } from '../services/meatspacePostDrillCache.js';import { COGNITIVE_DRILL_TYPES } from '../services/meatspacePostCognitive.js';import { TOPIC_IDS } from './postTopics.js';import { HHMM_STRICT_RE } from './timezone.js';+import { postLlmEvaluationSchema } from './postLlmContracts.js';// =============================================================================// POST (Power On Self Test) VALIDATION SCHEMAS@@ -61,13 +62,13 @@ const llmResponseSchema = z.object({// back to the array index (always 0 for single-response submits), and every// answer would be evaluated against the first prompt.questionIndex: z.number().int().min(0).optional(),- prompt: z.string().optional(),- response: z.string().optional(),- answers: z.array(z.string()).optional(),- items: z.array(z.string()).optional(),+ prompt: z.string().max(5000).optional(),+ response: z.string().max(10000).optional(),+ answers: z.array(z.string().max(1000)).max(100).optional(),+ items: z.array(z.string().trim().min(1).max(500)).max(100).optional(),responseMs: z.number().min(0).optional().default(0),llmScore: z.number().min(0).max(100).optional(),- llmFeedback: z.string().optional()+ llmFeedback: z.string().max(2000).optional()});// Drill type configuration@@ -174,7 +175,7 @@ const taskResultSchema = z.object({type: z.enum(DRILL_TYPES),config: drillTypeConfigSchema.optional().default({}),questions: z.array(questionResultSchema).optional().default([]),- responses: z.array(llmResponseSchema).optional().default([]),+ responses: z.array(llmResponseSchema).max(50).optional().default([]),drillData: z.any().optional(),// Memory drills: which memory item this task drilled, so the session-submit// path can map the result back and advance that item's spaced-repetition@@ -207,15 +208,24 @@ const taskResultSchema = z.object({confidence: z.number().min(0).max(1).nullable().optional(),inputMode: z.string().min(1).max(50).optional(),scorerProvenance: z.string().min(1).max(100).optional(),- evaluation: z.object({- score: z.number().min(0).max(100).optional(),- breakdown: z.array(z.object({- question: z.string().optional(),- score: z.number().min(0).max(100).optional(),- feedback: z.string().optional()- })).optional()- }).optional(),+ evaluation: postLlmEvaluationSchema.optional(),totalMs: z.number().min(0)+}).superRefine((task, ctx) => {+ if (!LLM_DRILL_TYPES.includes(task.type)) return;+ if (!task.evaluation) {+ ctx.addIssue({ code: 'custom', path: ['evaluation'], message: 'scored LLM drills require an evaluation' });+ }+ if (task.score === undefined) {+ ctx.addIssue({ code: 'custom', path: ['score'], message: 'scored LLM drills require a score' });+ }+ if (task.evaluation && task.evaluation.scores.length !== task.responses.length) {+ ctx.addIssue({ code: 'custom', path: ['evaluation', 'scores'], message: 'evaluation score count must match response count' });+ }+ task.responses.forEach((response, index) => {+ if (response.llmScore === undefined) {+ ctx.addIssue({ code: 'custom', path: ['responses', index, 'llmScore'], message: 'scored LLM responses require llmScore' });+ }+ });});// Full session submission@@ -351,11 +361,11 @@ export const postDrillRequestSchema = z.object({// LLM drill scoring requestexport const postLlmScoreRequestSchema = z.object({type: z.enum(LLM_DRILL_TYPES),- drillData: z.any(),- responses: z.array(llmResponseSchema),+ drillData: z.unknown(),+ responses: z.array(llmResponseSchema).min(1).max(50),timeLimitMs: z.number().min(1000),- providerId: z.string().optional(),- model: z.string().optional()+ providerId: z.string().min(1).max(300).optional(),+ model: z.string().min(1).max(300).optional()});// Explicit, user-consented request to warm the wordplay drill cachediff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.jsindex e50c87d72f..5a5708eb80 100644--- a/server/lib/postValidation.test.js+++ b/server/lib/postValidation.test.js@@ -398,6 +398,81 @@ describe('postLlmScoreRequestSchema', () => {});});+describe('postSessionSubmitSchema LLM evaluation contract', () => {+ const provenance = {+ generator: {+ schemaVersion: '1', promptVersion: '1', providerId: 'provider-a', model: 'model-a', apiKey: 'strip-me',+ },+ scorer: {+ kind: 'llm', rubricVersion: '1', providerId: 'provider-a', model: 'model-a', authHeader: 'strip-me',+ },+ };++ const task = (evaluation) => ({+ module: 'llm-drills',+ type: 'word-association',+ score: 80,+ responses: [{ response: 'ocean blue', responseMs: 1000, llmScore: 80, llmFeedback: 'Relevant' }],+ evaluation,+ totalMs: 1000,+ });++ it('preserves the producer shape and strips undeclared provenance secrets', () => {+ const parsed = postSessionSubmitSchema.parse({+ modules: ['llm-drills'],+ tasks: [task({+ overallScore: 80,+ scores: [{ score: 80, feedback: 'Relevant' }],+ summary: 'Good response',+ provenance,+ })],+ });++ expect(parsed.tasks[0].evaluation).toEqual({+ overallScore: 80,+ scores: [{ score: 80, feedback: 'Relevant' }],+ summary: 'Good response',+ provenance: {+ generator: { schemaVersion: '1', promptVersion: '1', providerId: 'provider-a', model: 'model-a' },+ scorer: { kind: 'llm', rubricVersion: '1', providerId: 'provider-a', model: 'model-a' },+ },+ });+ expect(JSON.stringify(parsed.tasks[0].evaluation)).not.toContain('strip-me');+ });++ it('normalizes historical evaluation fields with an explicit legacy sentinel', () => {+ const parsed = postSessionSubmitSchema.parse({+ modules: ['llm-drills'],+ tasks: [task({ score: 70, breakdown: [{ score: 70, feedback: 'Historical feedback' }] })],+ });++ expect(parsed.tasks[0].evaluation).toMatchObject({+ overallScore: 70,+ scores: [{ score: 70, feedback: 'Historical feedback' }],+ provenance: {+ generator: { schemaVersion: 'legacy', promptVersion: 'legacy', providerId: 'legacy', model: 'legacy' },+ scorer: { kind: 'legacy', rubricVersion: 'legacy', providerId: 'legacy', model: 'legacy' },+ },+ });+ });++ it('rejects missing, malformed, and wrong-count evaluations', () => {+ expect(() => postSessionSubmitSchema.parse({+ modules: ['llm-drills'], tasks: [task(undefined)],+ })).toThrow(/evaluation/i);++ expect(() => postSessionSubmitSchema.parse({+ modules: ['llm-drills'],+ tasks: [task({ overallScore: '80', scores: [], summary: 'Wrong type', provenance })],+ })).toThrow();++ expect(() => postSessionSubmitSchema.parse({+ modules: ['llm-drills'],+ tasks: [task({ overallScore: 80, scores: [], summary: 'Truncated', provenance })],+ })).toThrow(/score count/i);+ });+});+// =============================================================================// drillTypeConfigSchema numeric bounds (via postDrillRequestSchema.config)// (issue #2102 notes)diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 84752d5c86..3abdeeccc2 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -11,6 +11,7 @@ import { EventEmitter } from 'events';import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';import { deepMerge } from '../lib/objects.js';import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';+import { normalizePostLlmEvaluation } from '../lib/postLlmContracts.js';import { resolveTopicForDrillType, isTopicEnabled, isMemoryItemEnabled } from '../lib/postTopics.js';import { adaptDrillConfig, ADAPTIVE_SPECS, ADAPTIVE_DEFAULTS } from '../lib/postAdaptive.js';import { resolveMultiplicationLevel, MASTERY_DEFAULTS } from '../lib/postMultiplicationLadder.js';@@ -241,6 +242,17 @@ async function loadSessions({ strict = false } = {}) {return { sessions: await listPostSessions({ strict }) };}+function normalizeHistoricalLlmEvaluations(session) {+ return {+ ...session,+ tasks: (session?.tasks || []).map((task) => (+ LLM_DRILL_TYPES.includes(task?.type) && task.evaluation+ ? { ...task, evaluation: normalizePostLlmEvaluation(task.evaluation) }+ : task+ )),+ };+}+/*** All scored sessions, with each record's `date` RE-DERIVED from its `startedAt`* instant in the user's CURRENT timezone (issue #4168). This is the single read@@ -253,7 +265,7 @@ async function loadSessions({ strict = false } = {}) {export async function getPostSessions(from, to, options) {const data = await loadSessions(options);const timezone = await getUserTimezone();- let sessions = withDerivedDayKeys(data.sessions, timezone);+ let sessions = withDerivedDayKeys(data.sessions, timezone).map(normalizeHistoricalLlmEvaluations);// Re-derivation can move a record across a day boundary, so re-sort rather// than trusting the stored-date order `submitPostSession` wrote.sessions.sort((a, b) => (a?.date || '').localeCompare(b?.date || ''));@@ -274,7 +286,7 @@ export async function getPostSessions(from, to, options) {export async function getPostSession(id) {const session = await getStoredPostSession(id);if (!session) return null;- return { ...session, date: recordDayKey(session, await getUserTimezone()) };+ return normalizeHistoricalLlmEvaluations({ ...session, date: recordDayKey(session, await getUserTimezone()) });}export async function submitPostSession(sessionData) {@@ -310,7 +322,14 @@ export async function submitPostSession(sessionData) {// This is a single-user internal tool so client score trust is acceptable.// The evaluation field and per-response llmScore/llmFeedback contain the server-generated breakdown.if (LLM_DRILL_TYPES.includes(rest.type)) {- return { ...rest, score: t.score || 0 };+ if (!Number.isFinite(t.score)) {+ throw new Error(`Cannot store ${rest.type} result without a validated score`);+ }+ return {+ ...rest,+ evaluation: normalizePostLlmEvaluation(rest.evaluation),+ score: t.score,+ };}// Memory drills: trust client-side scoring only for supported typesdiff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex 43a2c7e69a..74b96ea51f 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -65,6 +65,27 @@ describe('Quick POST config', () => {});});+function llmTaskResult(score, overrides = {}) {+ const responses = overrides.responses || [{ response: 'example', responseMs: 1000, llmScore: score }];+ return {+ module: 'llm-drills',+ type: 'word-association',+ responses,+ score,+ evaluation: {+ overallScore: score,+ scores: responses.map(() => ({ score, feedback: 'Validated response' })),+ summary: 'Validated response',+ provenance: {+ generator: { schemaVersion: '1', promptVersion: '1', providerId: 'provider-a', model: 'model-a' },+ scorer: { kind: 'llm', rubricVersion: '1', providerId: 'provider-a', model: 'model-a' },+ },+ },+ totalMs: 1000,+ ...overrides,+ };+}+// =============================================================================// DOUBLING CHAIN TESTS// =============================================================================@@ -823,9 +844,7 @@ describe('submitPostSession — weighted scoring (issue #2099)', () => {vi.clearAllMocks();});- const llmTask = (score) => ({- module: 'llm-drills', type: 'word-association', responses: [], score, totalMs: 1000,- });+ const llmTask = (score) => llmTaskResult(score);const memoryTask = (score) => ({module: 'memory', type: 'memory-sequence', questions: [], score, totalMs: 500,});@@ -1623,6 +1642,30 @@ describe('POST readers re-derive day keys after a timezone change (issue #4168)'expect(laHistory.map(s => s.date)).toEqual(['2026-07-16', '2026-07-17']);});+ it('normalizes historical LLM evaluations with explicit legacy provenance on read', async () => {+ freezeAt('2026-07-18T12:00:00Z', 'UTC');+ mockHistory([{+ date: '2026-07-17',+ startedAt: '2026-07-17T12:00:00.000Z',+ score: 70,+ tasks: [{+ module: 'llm-drills', type: 'word-association', score: 70,+ evaluation: { score: 70, breakdown: [{ score: 70, feedback: 'Historical feedback' }] },+ }],+ }]);++ const [session] = await getPostSessions();++ expect(session.tasks[0].evaluation).toMatchObject({+ overallScore: 70,+ scores: [{ score: 70, feedback: 'Historical feedback' }],+ provenance: {+ generator: { schemaVersion: 'legacy', promptVersion: 'legacy', providerId: 'legacy', model: 'legacy' },+ scorer: { kind: 'legacy', rubricVersion: 'legacy', providerId: 'legacy', model: 'legacy' },+ },+ });+ });+it('getPostStats counts the streak and today against the new zone', async () => {// Under UTC the second session lands on 2026-07-18, which IS today there.freezeAt('2026-07-18T12:00:00Z', 'UTC');@@ -1884,13 +1927,10 @@ describe('submitPostSession — non-memory task types', () => {const session = await submitPostSession({cadence: 'daily',modules: ['llm-drills'],- tasks: [{- module: 'llm-drills',- type: 'word-association',+ tasks: [llmTaskResult(87, {responses: [{ questionIndex: 0, response: 'church', responseMs: 3000, llmScore: 90 }],- score: 87,totalMs: 3000,- }],+ })],tags: {},});expect(session.tasks[0].score).toBe(87);@@ -1907,7 +1947,7 @@ describe('submitPostSession — non-memory task types', () => {questions: [{ prompt: '4 x 2', answered: 8, responseMs: 500 }],totalMs: 500,},- { module: 'llm-drills', type: 'word-association', responses: [], score: 50, totalMs: 1000 },+ llmTaskResult(50),],tags: {},});diff --git a/server/services/meatspacePostLlm.js b/server/services/meatspacePostLlm.jsindex 13d716fce8..94fba937f1 100644--- a/server/services/meatspacePostLlm.js+++ b/server/services/meatspacePostLlm.js@@ -11,6 +11,15 @@import { getActiveProvider, getProviderById } from './providers.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';+import {+ LEGACY_POST_LLM_PROVENANCE,+ buildPostLlmGeneratorProvenance,+ buildPostLlmScorerProvenance,+ postLlmEvaluationSchema,+ validatePostLlmGenerationPayload,+ validatePostLlmScorePayload,+ validatePostLlmSemanticVerdicts,+} from '../lib/postLlmContracts.js';export const LLM_DRILL_TYPES = ['word-association',@@ -29,6 +38,8 @@ export const LLM_DRILL_TYPES = ['reframe',];+const MAX_SEMANTIC_CANDIDATES = 200;+// ─────────────────────────────────────────────────────────────────────────────// AI CALLER (mirrors brain.js pattern)// ─────────────────────────────────────────────────────────────────────────────@@ -53,11 +64,15 @@ async function callAI(prompt, providerId, model) {? { ...provider, args: [...(provider.args || []), ...provider.headlessArgs] }: provider;- const { text } = await runPromptThroughProvider({+ const result = await runPromptThroughProvider({provider: providerForCall, prompt, source: 'meatspace-post-llm', model: selectedModel,timeout: provider.timeout || 120000,});- return text;+ return {+ text: result.text,+ providerId: provider.id || 'unknown',+ model: result.model || selectedModel || 'unknown',+ };}function parseJsonFromAI(content) {@@ -76,6 +91,14 @@ function parseJsonFromAI(content) {return JSON.parse(jsonStr);}+async function generateValidatedPayload(type, count, prompt, providerId, model) {+ const response = await callAI(prompt, providerId, model);+ return {+ data: validatePostLlmGenerationPayload(type, parseJsonFromAI(response.text), count),+ generation: buildPostLlmGeneratorProvenance(type, response.providerId, response.model),+ };+}+// ─────────────────────────────────────────────────────────────────────────────// DRILL GENERATORS// ─────────────────────────────────────────────────────────────────────────────@@ -92,14 +115,14 @@ Return ONLY valid JSON (no markdown, no explanation):Example: {"questions":[{"prompt":"cathedral","hints":"architecture/spirituality"}]}`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('word-association', count, prompt, providerId, model);return {type: 'word-association',config: { count },- questions: (data.questions || []).slice(0, count).map(q => ({+ generation,+ questions: data.questions.map(q => ({prompt: q.prompt,- hints: q.hints || ''+ hints: q.hints,}))};}@@ -111,16 +134,17 @@ Each exercise has a short paragraph (2-4 sentences) containing specific details:Then provide 3-4 recall questions about those details, each with a correct answer.Return ONLY valid JSON:-{"exercises":[{"paragraph":"The story text...","questions":[{"question":"What was the name...?","answer":"correct answer"}]}]}+{"exercises":[{"paragraph":"The story text...","questions":[{"question":"Who visited?","answer":"Jane","aliases":[]},{"question":"Where did she go?","answer":"New York City","aliases":["NYC"]},{"question":"When did she go?","answer":"Monday","aliases":[]}]}]}-Make paragraphs vivid and varied. Include specific numbers, proper nouns, and concrete details.`;+Make paragraphs vivid and varied. Include specific numbers, proper nouns, and concrete details.+Only declare aliases that are complete interchangeable answers (for example "NYC" for "New York City"); do not list fragments or substrings.`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('story-recall', count, prompt, providerId, model);return {type: 'story-recall',config: { count },- exercises: (data.exercises || []).slice(0, count)+ generation,+ exercises: data.exercises,};}@@ -137,12 +161,12 @@ Return ONLY valid JSON:The examples field should contain 3-5 sample answers for validation reference.minExpected is the minimum number a healthy adult should name in 60 seconds.`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('verbal-fluency', count, prompt, providerId, model);return {type: 'verbal-fluency',config: { count },- categories: (data.categories || []).slice(0, count)+ generation,+ categories: data.categories,};}@@ -157,12 +181,12 @@ Return ONLY valid JSON:Make setups varied and fun. Range from easy (obvious joke setup) to hard (requires clever lateral thinking).`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('wit-comeback', count, prompt, providerId, model);return {type: 'wit-comeback',config: { count },- scenarios: (data.scenarios || []).slice(0, count)+ generation,+ scenarios: data.scenarios,};}@@ -177,12 +201,12 @@ Return ONLY valid JSON:Make challenges diverse and fun. The example should be witty but not the only valid answer.`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('pun-wordplay', count, prompt, providerId, model);return {type: 'pun-wordplay',config: { count },- challenges: (data.challenges || []).slice(0, count)+ generation,+ challenges: data.challenges,};}@@ -195,12 +219,12 @@ Mix science, society, nature, and everyday life. Be creative and specific.Return ONLY valid JSON:{"scenarios":[{"prompt":"What if gravity reversed for 10 minutes every Tuesday?","category":"physics"}]}`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('what-if', count, prompt, providerId, model);return {type: 'what-if',config: { count },- scenarios: (data.scenarios || []).slice(0, count)+ generation,+ scenarios: data.scenarios,};}@@ -213,12 +237,12 @@ Pick objects that have many possible creative uses.Return ONLY valid JSON:{"objects":[{"object":"brick","commonUse":"building material","minExpected":8}]}`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('alternative-uses', count, prompt, providerId, model);return {type: 'alternative-uses',config: { count },- objects: (data.objects || []).slice(0, count)+ generation,+ objects: data.objects,};}@@ -231,12 +255,12 @@ Choose words that are surprising when combined.Return ONLY valid JSON:{"prompts":[{"words":["lighthouse","saxophone","marmalade"]}]}`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('story-prompt', count, prompt, providerId, model);return {type: 'story-prompt',config: { count },- prompts: (data.prompts || []).slice(0, count)+ generation,+ prompts: data.prompts,};}@@ -249,12 +273,12 @@ Mix everyday annoyances, workplace challenges, and social problems.Return ONLY valid JSON:{"problems":[{"problem":"You always forget where you put your keys","category":"everyday","difficulty":"easy"}]}`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('invention-pitch', count, prompt, providerId, model);return {type: 'invention-pitch',config: { count },- problems: (data.problems || []).slice(0, count)+ generation,+ problems: data.problems,};}@@ -267,12 +291,12 @@ Mix minor annoyances with bigger setbacks. Keep them relatable.Return ONLY valid JSON:{"situations":[{"situation":"Your flight was delayed by 4 hours","severity":"medium"}]}`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('reframe', count, prompt, providerId, model);return {type: 'reframe',config: { count },- situations: (data.situations || []).slice(0, count)+ generation,+ situations: data.situations,};}@@ -284,21 +308,21 @@ Choose words with at least 10+ valid compound combinations (as prefix or suffix)Mix common roots (fire, back, hand) with less obvious ones (cross, break, light).Return ONLY valid JSON (no markdown, no explanation):-{"challenges":[{"rootWord":"paper","position":"prefix","examples":["paperback","paper trail","paperweight","paper clip","paper thin"],"minExpected":8}]}+{"challenges":[{"rootWord":"paper","position":"prefix","examples":["paperback","paper trail","paperweight","paper clip","paper thin","paper plane","paper cut","paper mill","paper bag","paper tiger"],"minExpected":8}]}position is "prefix" if the root starts the compound (firehouse), "suffix" if it ends it (campfire), or "both" if common either way (light→lighthouse, flashlight).The examples field should contain 10-15 sample answers for reference. minExpected is the target count.`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('compound-chain', count, prompt, providerId, model);return {type: 'compound-chain',config: { count },- challenges: (data.challenges || []).slice(0, count).map(c => ({+ generation,+ challenges: data.challenges.map(c => ({rootWord: c.rootWord,- position: c.position || 'both',- examples: c.examples || [],- minExpected: c.minExpected || 8,+ position: c.position,+ examples: c.examples,+ minExpected: c.minExpected,}))};}@@ -315,16 +339,16 @@ Choose bridge words that have many natural compound forms. Vary difficulty.Return ONLY valid JSON (no markdown, no explanation):{"puzzles":[{"clues":["news___","___back","___weight","___clip"],"answer":"paper","difficulty":"easy","hint":"Something you write on"}]}`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('bridge-word', count, prompt, providerId, model);return {type: 'bridge-word',config: { count },- puzzles: (data.puzzles || []).slice(0, count).map(p => ({- clues: p.clues || [],+ generation,+ puzzles: data.puzzles.map(p => ({+ clues: p.clues,answer: p.answer,- difficulty: p.difficulty || 'medium',- hint: p.hint || '',+ difficulty: p.difficulty,+ hint: p.hint,}))};}@@ -343,16 +367,16 @@ Choose words with clearly distinct meanings that are fun to combine.Return ONLY valid JSON (no markdown, no explanation):{"challenges":[{"word":"bark","meanings":["outer covering of a tree","sound a dog makes"],"example":"The dog's bark echoed off the bark of the old oak.","difficulty":"easy"}]}`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('double-meaning', count, prompt, providerId, model);return {type: 'double-meaning',config: { count },- challenges: (data.challenges || []).slice(0, count).map(c => ({+ generation,+ challenges: data.challenges.map(c => ({word: c.word,- meanings: c.meanings || [],- example: c.example || '',- difficulty: c.difficulty || 'medium',+ meanings: c.meanings,+ example: c.example,+ difficulty: c.difficulty,}))};}@@ -374,16 +398,16 @@ Choose well-known idioms and fun, diverse domains. Mix easy and hard combinationReturn ONLY valid JSON (no markdown, no explanation):{"challenges":[{"idiom":"Don't put all your eggs in one basket","domain":"programming","example":"Don't push all your commits to one branch","difficulty":"easy"}]}`;- const response = await callAI(prompt, providerId, model);- const data = parseJsonFromAI(response);+ const { data, generation } = await generateValidatedPayload('idiom-twist', count, prompt, providerId, model);return {type: 'idiom-twist',config: { count },- challenges: (data.challenges || []).slice(0, count).map(c => ({+ generation,+ challenges: data.challenges.map(c => ({idiom: c.idiom,domain: c.domain,- example: c.example || '',- difficulty: c.difficulty || 'medium',+ example: c.example,+ difficulty: c.difficulty,}))};}@@ -438,19 +462,56 @@ function averageScore(scores) {}function buildScoringResult(evaluation, userResponses, speedBonus) {- const qualityScore = Math.min(100, Math.max(0, evaluation.overallScore || 0));+ const qualityScore = evaluation.overallScore;const finalScore = Math.min(100, Math.max(0, Math.round(qualityScore * 0.8 + speedBonus * 0.2 * 100)));return {score: finalScore,evaluation,questions: userResponses.map((r, i) => ({...r,- llmScore: evaluation.scores?.[i]?.score ?? null,- llmFeedback: evaluation.scores?.[i]?.feedback ?? ''+ llmScore: evaluation.scores[i].score,+ llmFeedback: evaluation.scores[i].feedback,}))};}+function normalizeAnswer(value) {+ return String(value || '')+ .normalize('NFKC')+ .toLowerCase()+ .replace(/[^\p{L}\p{N}]+/gu, ' ')+ .trim()+ .replace(/\s+/g, ' ');+}++function normalizeCompound(value) {+ return normalizeAnswer(value).replace(/\s/g, '');+}++function evaluationWithProvenance(type, drillData, evaluation, kind, providerId = 'local', model = 'local') {+ return postLlmEvaluationSchema.parse({+ ...evaluation,+ provenance: {+ generator: drillData?.generation || LEGACY_POST_LLM_PROVENANCE.generator,+ scorer: buildPostLlmScorerProvenance(type, kind, providerId, model),+ },+ });+}++async function semanticVerdicts(candidates, prompt, providerId, model, label) {+ if (candidates.length === 0) return { verdicts: new Map(), providerId: 'local', model: 'local' };+ if (candidates.length > MAX_SEMANTIC_CANDIDATES) {+ throw new Error(`Cannot score ${candidates.length} open-ended items in one bounded batch (max ${MAX_SEMANTIC_CANDIDATES})`);+ }+ const response = await callAI(prompt, providerId, model);+ const parsed = validatePostLlmSemanticVerdicts(parseJsonFromAI(response.text), candidates, label);+ return {+ verdicts: new Map(parsed.verdicts.map((verdict) => [`${verdict.responseIndex}:${verdict.itemIndex}`, verdict.valid])),+ providerId: response.providerId,+ model: response.model,+ };+}+// ─────────────────────────────────────────────────────────────────────────────// LOCAL (INSTANT) SCORING — no LLM call needed// ─────────────────────────────────────────────────────────────────────────────@@ -458,9 +519,9 @@ function buildScoringResult(evaluation, userResponses, speedBonus) {function scoreLocalBridgeWord(drillData, userResponses) {const scores = userResponses.map((r, i) => {const puzzle = drillData.puzzles?.[r.questionIndex ?? i];- if (!puzzle?.answer) return { score: 0, feedback: 'No answer available' };- const userAnswer = (r.response || '').trim().toLowerCase();- const correct = puzzle.answer.trim().toLowerCase();+ if (!puzzle?.answer) throw new Error(`Cannot score bridge-word response ${i}: missing answer key`);+ const userAnswer = normalizeAnswer(r.response);+ const correct = normalizeAnswer(puzzle.answer);const isCorrect = userAnswer === correct;return {score: isCorrect ? 100 : 0,@@ -471,88 +532,178 @@ function scoreLocalBridgeWord(drillData, userResponses) {return { overallScore, scores, summary: `${scores.filter(s => s.score === 100).length} of ${scores.length} correct` };}-function scoreLocalCompoundChain(drillData, userResponses) {- const scores = userResponses.map((r, i) => {- const challenge = drillData.challenges?.[r.questionIndex ?? i];- if (!challenge?.rootWord) return { score: 0, feedback: 'No root word', validCount: 0, invalidItems: [], missedExamples: [] };- const root = challenge.rootWord.toLowerCase();- const norm = s => s.toLowerCase().replace(/[\s-]/g, '');+function matchedCompoundExample(challenge, item) {+ const root = normalizeCompound(challenge.rootWord);+ const normalized = normalizeCompound(item);+ return (challenge.examples || []).find((example) => {+ const full = normalizeCompound(example);+ if (normalized === full) return true;+ if ((challenge.position === 'prefix' || challenge.position === 'both') && full.startsWith(root)) {+ if (normalized === full.slice(root.length)) return true;+ }+ if ((challenge.position === 'suffix' || challenge.position === 'both') && full.endsWith(root)) {+ if (normalized === full.slice(0, -root.length)) return true;+ }+ return false;+ });+}++function coverCompound(covered, challenge, item) {+ const root = normalizeCompound(challenge.rootWord);+ const normalized = normalizeCompound(item);+ covered.add(normalized);+ if (challenge.position === 'prefix' || challenge.position === 'both') covered.add(root + normalized);+ if (challenge.position === 'suffix' || challenge.position === 'both') covered.add(normalized + root);+}++async function scoreCompoundChain(drillData, userResponses, providerId, model) {+ const candidates = [];+ const states = userResponses.map((r, responseIndex) => {+ const challenge = drillData.challenges?.[r.questionIndex ?? responseIndex];+ if (!challenge?.rootWord) throw new Error(`Cannot score compound-chain response ${responseIndex}: missing challenge`);const seen = new Set();- const valid = [];- const invalid = [];- // The "covered" set is the canonical full-compound form for each accepted- // item: typing "firehouse" or just "house" both contribute "firehouse" so- // missedExamples can suppress duplicates regardless of how the user typed it.- const coveredFull = new Set();- for (const item of (r.items || [])) {- const lower = norm(item);- if (!lower || seen.has(lower)) continue;- seen.add(lower);- if (lower === root) {- // Bare root word is not itself a compound — reject.- invalid.push(item);- continue;- }- if (lower.includes(root)) {- // Full compound already containing the root (e.g., "firehouse", "campfire").- valid.push(item);- coveredFull.add(lower);+ const state = { challenge, validItems: [], invalidItems: [], duplicateItems: [], covered: new Set() };+ (r.items || []).forEach((item, itemIndex) => {+ const normalized = normalizeCompound(item);+ if (!normalized || normalized === normalizeCompound(challenge.rootWord)) {+ state.invalidItems.push(item);+ } else if (seen.has(normalized)) {+ state.duplicateItems.push(item);} else {- // Half-compound shorthand: assume the user means root+item or item+root- // (e.g., "hose" → firehose). We can't validate against a dictionary- // without an LLM call, so accept it and let the user keep momentum.- valid.push(item);- coveredFull.add(root + lower);- coveredFull.add(lower + root);+ seen.add(normalized);+ const example = matchedCompoundExample(challenge, item);+ if (example) {+ state.validItems.push(item);+ state.covered.add(normalizeCompound(example));+ } else {+ candidates.push({ responseIndex, itemIndex, item, rootWord: challenge.rootWord, position: challenge.position });+ }}+ });+ return state;+ });++ const semantic = await semanticVerdicts(+ candidates,+ `Validate these proposed compound words or common fixed phrases. A proposal is valid only if it forms a recognized compound or common phrase with the root in the stated position. Reject invented fragments and the bare root.\n\nCandidates:\n${JSON.stringify(candidates)}\n\nReturn ONLY valid JSON with exactly one verdict per candidate:\n{"verdicts":[{"responseIndex":0,"itemIndex":0,"valid":true,"reason":"common compound"}]}`,+ providerId,+ model,+ 'compound-chain semantic validation response',+ );++ candidates.forEach((candidate) => {+ const state = states[candidate.responseIndex];+ if (semantic.verdicts.get(`${candidate.responseIndex}:${candidate.itemIndex}`)) {+ state.validItems.push(candidate.item);+ coverCompound(state.covered, state.challenge, candidate.item);+ } else {+ state.invalidItems.push(candidate.item);}- const target = challenge.minExpected || 8;- const score = Math.round(Math.min(1, valid.length / target) * 100);- const fb = valid.length >= target- ? `${valid.length} valid compounds — great job!`- : `${valid.length} valid compound${valid.length !== 1 ? 's' : ''} (target: ${target})`;- // Show examples the user didn't find. `coveredFull` already contains the- // user's valid compounds plus `root+half`/`half+root` pairings, so a single- // membership check covers both full-compound and half-word inputs.- const missedExamples = (challenge.examples || []).filter(ex => !coveredFull.has(norm(ex)));- return { score, feedback: fb, validCount: valid.length, invalidItems: invalid, missedExamples };+ });++ const scores = states.map((state) => {+ const target = state.challenge.minExpected;+ const validCount = state.validItems.length;+ const score = Math.round(Math.min(1, validCount / target) * 100);+ const feedback = validCount >= target+ ? `${validCount} valid compounds — great job!`+ : `${validCount} valid compound${validCount !== 1 ? 's' : ''} (target: ${target})`;+ const missedExamples = (state.challenge.examples || [])+ .filter((example) => !state.covered.has(normalizeCompound(example)));+ return {+ score, feedback, validCount, validItems: state.validItems,+ invalidItems: state.invalidItems, duplicateItems: state.duplicateItems, missedExamples,+ };});const overallScore = averageScore(scores);- return { overallScore, scores, summary: `Average ${overallScore}% across ${scores.length} challenges` };+ return {+ evaluation: { overallScore, scores, summary: `Average ${overallScore}% across ${scores.length} challenges` },+ kind: candidates.length ? 'hybrid' : 'local',+ providerId: semantic.providerId,+ model: semantic.model,+ };}-function scoreLocalVerbalFluency(drillData, userResponses) {- const scores = userResponses.map((r, i) => {- const cat = drillData.categories?.[r.questionIndex ?? i];+function isLexicalCandidate(value) {+ const item = String(value || '').trim();+ return item.length > 0+ && item.length <= 80+ && /\p{L}/u.test(item)+ && !/[\u0000-\u001f\u007f]/u.test(item);+}++async function scoreVerbalFluency(drillData, userResponses, providerId, model) {+ const candidates = [];+ const states = userResponses.map((r, responseIndex) => {+ const category = drillData.categories?.[r.questionIndex ?? responseIndex];+ if (!category?.category) throw new Error(`Cannot score verbal-fluency response ${responseIndex}: missing category`);+ const examples = new Set((category.examples || []).map(normalizeAnswer));const seen = new Set();- for (const item of (r.items || [])) seen.add(item.toLowerCase().trim());- const uniqueCount = seen.size;- const target = cat?.minExpected || 15;- const score = Math.round(Math.min(1, uniqueCount / target) * 100);- const missedExamples = (cat?.examples || []).filter(ex => !seen.has(ex.toLowerCase().trim()));+ const state = { category, validItems: [], invalidItems: [], duplicateItems: [] };+ (r.items || []).forEach((item, itemIndex) => {+ const normalized = normalizeAnswer(item);+ if (!isLexicalCandidate(item)) {+ state.invalidItems.push(item);+ } else if (seen.has(normalized)) {+ state.duplicateItems.push(item);+ } else if (examples.has(normalized)) {+ seen.add(normalized);+ state.validItems.push(item);+ } else {+ seen.add(normalized);+ candidates.push({ responseIndex, itemIndex, item, category: category.category });+ }+ });+ return state;+ });++ const semantic = await semanticVerdicts(+ candidates,+ `Validate each unique verbal-fluency item against its category. Accept real lexical items that genuinely belong to the category; reject invented strings, category labels, commentary, and unrelated words.\n\nCandidates:\n${JSON.stringify(candidates)}\n\nReturn ONLY valid JSON with exactly one verdict per candidate:\n{"verdicts":[{"responseIndex":0,"itemIndex":0,"valid":true,"reason":"belongs to category"}]}`,+ providerId,+ model,+ 'verbal-fluency semantic validation response',+ );++ candidates.forEach((candidate) => {+ const state = states[candidate.responseIndex];+ if (semantic.verdicts.get(`${candidate.responseIndex}:${candidate.itemIndex}`)) state.validItems.push(candidate.item);+ else state.invalidItems.push(candidate.item);+ });++ const scores = states.map((state) => {+ const validCount = state.validItems.length;+ const target = state.category.minExpected;+ const score = Math.round(Math.min(1, validCount / target) * 100);+ const found = new Set(state.validItems.map(normalizeAnswer));return {score,- feedback: `${uniqueCount} unique item${uniqueCount !== 1 ? 's' : ''} (target: ${target})`,- validCount: uniqueCount,- invalidItems: [],- missedExamples,+ feedback: `${validCount} valid unique item${validCount !== 1 ? 's' : ''} (target: ${target})`,+ validCount,+ validItems: state.validItems,+ invalidItems: state.invalidItems,+ duplicateItems: state.duplicateItems,+ missedExamples: (state.category.examples || []).filter((example) => !found.has(normalizeAnswer(example))),};});const overallScore = averageScore(scores);- return { overallScore, scores, summary: `Average ${overallScore}%` };+ return {+ evaluation: { overallScore, scores, summary: `Average ${overallScore}%` },+ kind: candidates.length ? 'hybrid' : 'local',+ providerId: semantic.providerId,+ model: semantic.model,+ };}function scoreLocalStoryRecall(drillData, userResponses) {const scores = userResponses.map((r, i) => {const questions = drillData.exercises?.[r.questionIndex ?? i]?.questions || [];- if (questions.length === 0) return { score: 0, feedback: 'No questions' };+ if (questions.length === 0) throw new Error(`Cannot score story-recall response ${i}: missing questions`);let correct = 0;for (let qi = 0; qi < questions.length; qi++) {- const expected = (questions[qi].answer || '').toLowerCase().trim();- const given = (r.answers?.[qi] || '').toLowerCase().trim();- if (given && (given === expected || expected.includes(given) || given.includes(expected))) {- correct++;- }+ const accepted = [questions[qi].answer, ...(questions[qi].aliases || [])].map(normalizeAnswer);+ const given = normalizeAnswer(r.answers?.[qi]);+ if (given && accepted.includes(given)) correct++;}const score = Math.round((correct / questions.length) * 100);return { score, feedback: `${correct} of ${questions.length} correct` };@@ -563,11 +714,20 @@ function scoreLocalStoryRecall(drillData, userResponses) {const LOCAL_SCORERS = {'bridge-word': scoreLocalBridgeWord,- 'compound-chain': scoreLocalCompoundChain,- 'verbal-fluency': scoreLocalVerbalFluency,'story-recall': scoreLocalStoryRecall,};+const HYBRID_SCORERS = {+ 'compound-chain': scoreCompoundChain,+ 'verbal-fluency': scoreVerbalFluency,+};++/*+ * The two open-ended validators above deliberately make one semantic request+ * for the complete response set. Known answer-key entries stay deterministic;+ * every unknown item is classified in that one bounded payload.+ */+const LLM_SCORE_BUILDERS = {'word-association': buildWordAssociationScorePrompt,'wit-comeback': buildWitComebackScorePrompt,@@ -591,16 +751,31 @@ export async function scoreLlmDrill(type, drillData, userResponses, timeLimitMs,const localScorer = LOCAL_SCORERS[type];if (localScorer) {console.log(`⚡ POST local scoring: ${type}`);- return buildScoringResult(localScorer(drillData, userResponses), userResponses, speedBonus);+ const evaluation = evaluationWithProvenance(type, drillData, localScorer(drillData, userResponses), 'local');+ return buildScoringResult(evaluation, userResponses, speedBonus);+ }++ const hybridScorer = HYBRID_SCORERS[type];+ if (hybridScorer) {+ console.log(`🧪 POST evidence-based scoring: ${type}`);+ const scored = await hybridScorer(drillData, userResponses, providerId, model);+ const evaluation = evaluationWithProvenance(+ type, drillData, scored.evaluation, scored.kind, scored.providerId, scored.model,+ );+ return buildScoringResult(evaluation, userResponses, speedBonus);}// Slow path: LLM scoring for creative/subjective drillsconst builder = LLM_SCORE_BUILDERS[type];- if (!builder) return { score: 0, evaluation: null, questions: userResponses };+ if (!builder) throw new Error(`Unsupported POST LLM scorer type: ${type}`);console.log(`🧪 POST LLM scoring: ${type}`);const response = await callAI(builder(drillData, userResponses), providerId, model);- return buildScoringResult(parseJsonFromAI(response), userResponses, speedBonus);+ const payload = validatePostLlmScorePayload(parseJsonFromAI(response.text), userResponses.length);+ const evaluation = evaluationWithProvenance(+ type, drillData, payload, 'llm', response.providerId, response.model,+ );+ return buildScoringResult(evaluation, userResponses, speedBonus);}function buildWordAssociationScorePrompt(drillData, responses) {diff --git a/server/services/meatspacePostLlm.test.js b/server/services/meatspacePostLlm.test.jsindex 9fb62f5559..214187e737 100644--- a/server/services/meatspacePostLlm.test.js+++ b/server/services/meatspacePostLlm.test.js@@ -65,8 +65,20 @@ function mockApiProvider(responseJson) {return provider;}+const storyQuestions = () => [+ { question: 'Who visited?', answer: 'Jane', aliases: ['J. Doe'] },+ { question: 'Where did she go?', answer: 'Paris' },+ { question: 'When did she go?', answer: 'Monday' },+];++const compoundExamples = (root = 'fire') => [+ `${root}house`, `${root}work`, `${root}place`, `${root}wood`, `${root}fly`,+ `${root}proof`, `${root}storm`, `${root}wall`, `${root}light`, `${root}break`,+];+beforeEach(() => {vi.restoreAllMocks();+ vi.clearAllMocks();});// =============================================================================@@ -120,10 +132,9 @@ describe('generateWordAssociation', () => {expect(result.config.count).toBe(5);});- it('slices to count limit', async () => {+ it('rejects a wrong item count instead of truncating the response', async () => {mockApiProvider({ questions: Array.from({ length: 10 }, (_, i) => ({ prompt: `word${i}` })) });- const result = await generateWordAssociation({ count: 3 });- expect(result.questions).toHaveLength(3);+ await expect(generateWordAssociation({ count: 3 })).rejects.toThrow(/questions.*3 item/i);});it('defaults hints to empty string', async () => {@@ -131,6 +142,30 @@ describe('generateWordAssociation', () => {const result = await generateWordAssociation({ count: 1 });expect(result.questions[0].hints).toBe('');});++ it('rejects missing, truncated, and wrong-type output with actionable paths', async () => {+ mockApiProvider({ questions: [{ prompt: 42 }] });+ await expect(generateWordAssociation({ count: 1 })).rejects.toThrow(/questions\.0\.prompt/);++ mockApiProvider({ questions: [] });+ await expect(generateWordAssociation({ count: 1 })).rejects.toThrow(/questions/);++ mockApiProvider({ prompts: [{ prompt: 'wrong key' }] });+ await expect(generateWordAssociation({ count: 1 })).rejects.toThrow(/questions/);+ });++ it('records only secret-free generation provenance', async () => {+ const provider = mockApiProvider({ questions: [{ prompt: 'test' }] });+ provider.apiKey = 'do-not-persist';+ provider.authHeader = 'do-not-persist';++ const result = await generateWordAssociation({ count: 1 });++ expect(result.generation).toEqual({+ schemaVersion: '1', promptVersion: '1', providerId: 'test-provider', model: 'test-model',+ });+ expect(JSON.stringify(result.generation)).not.toContain('do-not-persist');+ });});// =============================================================================@@ -140,7 +175,7 @@ describe('generateWordAssociation', () => {describe('generateStoryRecall', () => {it('returns story-recall drill with exercises', async () => {mockApiProvider({ exercises: [- { paragraph: 'A story about Jane...', questions: [{ question: 'Who?', answer: 'Jane' }] }+ { paragraph: 'A story about Jane...', questions: storyQuestions() }]});const result = await generateStoryRecall({ count: 1 });@@ -152,7 +187,7 @@ describe('generateStoryRecall', () => {});it('defaults count to 3', async () => {- mockApiProvider({ exercises: Array.from({ length: 3 }, () => ({ paragraph: 'p', questions: [] })) });+ mockApiProvider({ exercises: Array.from({ length: 3 }, () => ({ paragraph: 'p', questions: storyQuestions() })) });const result = await generateStoryRecall({});expect(result.config.count).toBe(3);});@@ -165,7 +200,7 @@ describe('generateStoryRecall', () => {describe('generateVerbalFluency', () => {it('returns verbal-fluency drill with categories', async () => {mockApiProvider({ categories: [- { category: 'Animals', minExpected: 15, examples: ['dog', 'cat'] }+ { category: 'Animals', minExpected: 15, examples: ['dog', 'cat', 'otter'] }]});const result = await generateVerbalFluency({ count: 1 });@@ -176,7 +211,7 @@ describe('generateVerbalFluency', () => {});it('defaults count to 3', async () => {- mockApiProvider({ categories: Array.from({ length: 3 }, () => ({ category: 'X', minExpected: 10, examples: [] })) });+ mockApiProvider({ categories: Array.from({ length: 3 }, () => ({ category: 'X', minExpected: 10, examples: ['a', 'b', 'c'] })) });const result = await generateVerbalFluency({});expect(result.config.count).toBe(3);});@@ -238,7 +273,7 @@ describe('generatePunWordplay', () => {describe('generateCompoundChain', () => {it('returns compound-chain drill with challenges', async () => {mockApiProvider({ challenges: [- { rootWord: 'paper', position: 'prefix', examples: ['paperback', 'paperweight'], minExpected: 8 }+ { rootWord: 'paper', position: 'prefix', examples: compoundExamples('paper'), minExpected: 8 }]});const result = await generateCompoundChain({ count: 1 });@@ -247,22 +282,26 @@ describe('generateCompoundChain', () => {expect(result.challenges).toHaveLength(1);expect(result.challenges[0].rootWord).toBe('paper');expect(result.challenges[0].position).toBe('prefix');- expect(result.challenges[0].examples).toEqual(['paperback', 'paperweight']);+ expect(result.challenges[0].examples).toEqual(compoundExamples('paper'));expect(result.challenges[0].minExpected).toBe(8);});it('defaults count to 5', async () => {- mockApiProvider({ challenges: Array.from({ length: 5 }, () => ({ rootWord: 'fire', position: 'both', examples: [], minExpected: 8 })) });+ mockApiProvider({ challenges: Array.from({ length: 5 }, () => ({ rootWord: 'fire', position: 'both', examples: compoundExamples(), minExpected: 8 })) });const result = await generateCompoundChain({});expect(result.config.count).toBe(5);});- it('defaults position, examples, and minExpected when absent', async () => {+ it('rejects a partial challenge instead of inventing scoring fields', async () => {mockApiProvider({ challenges: [{ rootWord: 'light' }] });- const result = await generateCompoundChain({ count: 1 });- expect(result.challenges[0].position).toBe('both');- expect(result.challenges[0].examples).toEqual([]);- expect(result.challenges[0].minExpected).toBe(8);+ await expect(generateCompoundChain({ count: 1 })).rejects.toThrow(/position|examples|minExpected/);+ });++ it('rejects answer-key examples that contradict the declared root position', async () => {+ mockApiProvider({ challenges: [{+ rootWord: 'paper', position: 'prefix', examples: ['newspaper', ...compoundExamples('paper').slice(1)], minExpected: 8,+ }] });+ await expect(generateCompoundChain({ count: 1 })).rejects.toThrow(/declared position/);});});@@ -273,29 +312,29 @@ describe('generateCompoundChain', () => {describe('generateBridgeWord', () => {it('returns bridge-word drill with puzzles', async () => {mockApiProvider({ puzzles: [- { clues: ['news___', '___back'], answer: 'paper', difficulty: 'easy', hint: 'You write on it' }+ { clues: ['news___', '___back', '___weight'], answer: 'paper', difficulty: 'easy', hint: 'You write on it' }]});const result = await generateBridgeWord({ count: 1 });expect(result.type).toBe('bridge-word');expect(result.config.count).toBe(1);expect(result.puzzles).toHaveLength(1);- expect(result.puzzles[0].clues).toEqual(['news___', '___back']);+ expect(result.puzzles[0].clues).toEqual(['news___', '___back', '___weight']);expect(result.puzzles[0].answer).toBe('paper');expect(result.puzzles[0].difficulty).toBe('easy');expect(result.puzzles[0].hint).toBe('You write on it');});it('defaults count to 5', async () => {- mockApiProvider({ puzzles: Array.from({ length: 5 }, () => ({ clues: [], answer: 'x' })) });+ mockApiProvider({ puzzles: Array.from({ length: 5 }, () => ({ clues: ['a___', '___b', 'c___'], answer: 'x' })) });const result = await generateBridgeWord({});expect(result.config.count).toBe(5);});- it('defaults clues, difficulty, and hint when absent', async () => {- mockApiProvider({ puzzles: [{ answer: 'paper' }] });+ it('defaults optional difficulty and hint while retaining required clues', async () => {+ mockApiProvider({ puzzles: [{ clues: ['news___', '___back', '___weight'], answer: 'paper' }] });const result = await generateBridgeWord({ count: 1 });- expect(result.puzzles[0].clues).toEqual([]);+ expect(result.puzzles[0].clues).toHaveLength(3);expect(result.puzzles[0].difficulty).toBe('medium');expect(result.puzzles[0].hint).toBe('');});@@ -321,15 +360,15 @@ describe('generateDoubleMeaning', () => {});it('defaults count to 5', async () => {- mockApiProvider({ challenges: Array.from({ length: 5 }, () => ({ word: 'x', meanings: [] })) });+ mockApiProvider({ challenges: Array.from({ length: 5 }, () => ({ word: 'x', meanings: ['one', 'two'] })) });const result = await generateDoubleMeaning({});expect(result.config.count).toBe(5);});- it('defaults example, difficulty, and meanings when absent', async () => {- mockApiProvider({ challenges: [{ word: 'scale' }] });+ it('defaults optional example and difficulty while requiring meanings', async () => {+ mockApiProvider({ challenges: [{ word: 'scale', meanings: ['measurement', 'fish covering'] }] });const result = await generateDoubleMeaning({ count: 1 });- expect(result.challenges[0].meanings).toEqual([]);+ expect(result.challenges[0].meanings).toEqual(['measurement', 'fish covering']);expect(result.challenges[0].example).toBe('');expect(result.challenges[0].difficulty).toBe('medium');});@@ -500,11 +539,11 @@ describe('generateLlmDrill', () => {const wa = await generateLlmDrill('word-association', { count: 1 });expect(wa.type).toBe('word-association');- mockApiProvider({ exercises: [{ paragraph: 'p', questions: [] }] });+ mockApiProvider({ exercises: [{ paragraph: 'p', questions: storyQuestions() }] });const sr = await generateLlmDrill('story-recall', { count: 1 });expect(sr.type).toBe('story-recall');- mockApiProvider({ categories: [{ category: 'X', minExpected: 10, examples: [] }] });+ mockApiProvider({ categories: [{ category: 'X', minExpected: 10, examples: ['a', 'b', 'c'] }] });const vf = await generateLlmDrill('verbal-fluency', { count: 1 });expect(vf.type).toBe('verbal-fluency');@@ -516,15 +555,15 @@ describe('generateLlmDrill', () => {const pw = await generateLlmDrill('pun-wordplay', { count: 1 });expect(pw.type).toBe('pun-wordplay');- mockApiProvider({ challenges: [{ rootWord: 'fire', position: 'both', examples: [], minExpected: 8 }] });+ mockApiProvider({ challenges: [{ rootWord: 'fire', position: 'both', examples: compoundExamples(), minExpected: 8 }] });const cc = await generateLlmDrill('compound-chain', { count: 1 });expect(cc.type).toBe('compound-chain');- mockApiProvider({ puzzles: [{ answer: 'paper' }] });+ mockApiProvider({ puzzles: [{ clues: ['news___', '___back', '___weight'], answer: 'paper' }] });const bw = await generateLlmDrill('bridge-word', { count: 1 });expect(bw.type).toBe('bridge-word');- mockApiProvider({ challenges: [{ word: 'bark', meanings: [] }] });+ mockApiProvider({ challenges: [{ word: 'bark', meanings: ['tree covering', 'dog sound'] }] });const dm = await generateLlmDrill('double-meaning', { count: 1 });expect(dm.type).toBe('double-meaning');@@ -583,6 +622,10 @@ describe('scoreLlmDrill', () => {expect(result.evaluation.overallScore).toBe(75);expect(result.questions[0].llmScore).toBe(80);expect(result.questions[0].llmFeedback).toBe('Good associations');+ expect(result.evaluation.provenance).toEqual({+ generator: { schemaVersion: 'legacy', promptVersion: 'legacy', providerId: 'legacy', model: 'legacy' },+ scorer: { kind: 'llm', rubricVersion: '1', providerId: 'test-provider', model: 'test-model' },+ });});it('combines quality (80%) and speed bonus (20%)', async () => {@@ -617,27 +660,24 @@ describe('scoreLlmDrill', () => {expect(fast.score).toBeGreaterThan(slow.score);});- it('clamps score between 0 and 100', async () => {+ it('rejects out-of-range scorer output instead of clamping it', async () => {mockApiProvider({overallScore: 150,scores: [{ score: 200, feedback: 'Over max' }],summary: 'Overcapped'});- const result = await scoreLlmDrill(+ await expect(scoreLlmDrill('word-association',{ questions: [{ prompt: 'test' }] },[{ response: 'answer', responseMs: 1000 }],120000- );-- expect(result.score).toBeLessThanOrEqual(100);+ )).rejects.toThrow(/overallScore|score/);});- it('returns score 0 for unknown drill type', async () => {- const result = await scoreLlmDrill('unknown', {}, [], 60000);- expect(result.score).toBe(0);- expect(result.evaluation).toBeNull();+ it('rejects an unknown drill type instead of fabricating zero', async () => {+ await expect(scoreLlmDrill('unknown', {}, [{ response: 'x' }], 60000))+ .rejects.toThrow('Unsupported POST LLM scorer type');});it('attaches per-response llmScore and llmFeedback', async () => {@@ -666,21 +706,32 @@ describe('scoreLlmDrill', () => {expect(result.questions[1].llmFeedback).toBe('Needs work');});- it('handles missing scores array gracefully', async () => {+ it('rejects a missing scores array instead of storing partial feedback', async () => {mockApiProvider({overallScore: 50,summary: 'No per-item scores'});- const result = await scoreLlmDrill(+ await expect(scoreLlmDrill('pun-wordplay',{ challenges: [{ prompt: 'x' }] },[{ response: 'y', responseMs: 1000 }],120000- );+ )).rejects.toThrow(/scores/);+ });- expect(result.questions[0].llmScore).toBeNull();- expect(result.questions[0].llmFeedback).toBe('');+ it('rejects truncated and wrong-type score entries', async () => {+ mockApiProvider({+ overallScore: 50,+ scores: [{ score: '50', feedback: 'wrong type' }],+ summary: 'Malformed',+ });+ await expect(scoreLlmDrill(+ 'word-association',+ { questions: [{ prompt: 'a' }, { prompt: 'b' }] },+ [{ response: 'x' }, { response: 'y' }],+ 120000,+ )).rejects.toThrow(/scores/);});it('scores story-recall with answers', async () => {@@ -696,17 +747,59 @@ describe('scoreLlmDrill', () => {expect(result.evaluation.overallScore).toBe(100);});- it('scores verbal-fluency with items', async () => {- // verbal-fluency uses local scoring: 10 unique items / 15 target = 67+ it('accepts declared story aliases but rejects substring fragments', async () => {+ const drillData = {+ exercises: [{+ questions: [+ { question: 'Where?', answer: 'New York City', aliases: ['NYC'] },+ { question: 'Who?', answer: 'Alexandra', aliases: [] },+ ],+ }],+ };++ const result = await scoreLlmDrill(+ 'story-recall', drillData, [{ answers: ['nyc', 'Alex'], responseMs: 5000 }], 180000,+ );++ expect(result.evaluation.scores[0]).toMatchObject({ score: 50, feedback: '1 of 2 correct' });+ });++ it('scores verbal-fluency from finite known examples without a provider call', async () => {+ const animals = ['dog', 'cat', 'fish', 'bird', 'snake', 'lion', 'tiger', 'bear', 'wolf', 'fox'];const result = await scoreLlmDrill('verbal-fluency',- { categories: [{ category: 'Animals', minExpected: 15, examples: ['dog'] }] },- [{ items: ['dog', 'cat', 'fish', 'bird', 'snake', 'lion', 'tiger', 'bear', 'wolf', 'fox'], responseMs: 45000 }],+ { categories: [{ category: 'Animals', minExpected: 15, examples: animals }] },+ [{ items: animals, responseMs: 45000 }],60000);expect(result.score).toBeGreaterThan(0);expect(result.evaluation.overallScore).toBe(67);+ expect(runPromptThroughProvider).not.toHaveBeenCalled();+ });++ it('batch-validates verbal items once and separates valid, invalid, and duplicate items', async () => {+ mockApiProvider({+ verdicts: [+ { responseIndex: 0, itemIndex: 1, valid: true },+ { responseIndex: 0, itemIndex: 4, valid: false },+ ],+ });++ const result = await scoreLlmDrill(+ 'verbal-fluency',+ { categories: [{ category: 'Animals', minExpected: 3, examples: ['dog'] }] },+ [{ items: ['dog', 'otter', 'OTTER', '', 'not an animal category'], responseMs: 10000 }],+ 60000,+ );++ expect(runPromptThroughProvider).toHaveBeenCalledTimes(1);+ expect(result.evaluation.scores[0]).toMatchObject({+ validCount: 2,+ validItems: ['dog', 'otter'],+ invalidItems: ['', 'not an animal category'],+ duplicateItems: ['OTTER'],+ });});it('compound-chain accepts both full compounds and the other half', async () => {@@ -714,7 +807,7 @@ describe('scoreLlmDrill', () => {// Both should count as valid compound contributions.const result = await scoreLlmDrill('compound-chain',- { challenges: [{ rootWord: 'fire', position: 'either', minExpected: 4, examples: ['firehose', 'firepit', 'firework', 'campfire'] }] },+ { challenges: [{ rootWord: 'fire', position: 'both', minExpected: 4, examples: ['firehose', 'firepit', 'firework', 'campfire'] }] },[{ items: ['hose', 'pit', 'work', 'campfire'], responseMs: 30000 }],60000);@@ -731,7 +824,7 @@ describe('scoreLlmDrill', () => {it('compound-chain rejects bare root word', () => {return scoreLlmDrill('compound-chain',- { challenges: [{ rootWord: 'fire', position: 'either', minExpected: 2, examples: [] }] },+ { challenges: [{ rootWord: 'fire', position: 'both', minExpected: 2, examples: ['firework'] }] },[{ items: ['fire', 'firework'], responseMs: 10000 }],60000).then(result => {@@ -739,6 +832,41 @@ describe('scoreLlmDrill', () => {expect(result.evaluation.scores[0].invalidItems).toContain('fire');});});++ it('batch-validates unknown compound fragments exactly once', async () => {+ mockApiProvider({+ verdicts: [+ { responseIndex: 0, itemIndex: 1, valid: true },+ { responseIndex: 0, itemIndex: 3, valid: false },+ { responseIndex: 0, itemIndex: 4, valid: true },+ ],+ });++ const result = await scoreLlmDrill(+ 'compound-chain',+ { challenges: [{ rootWord: 'fire', position: 'both', minExpected: 3, examples: [] }] },+ [{ items: ['fire', 'firehouse', 'FIRE HOUSE', 'firebanana', 'wildfire'], responseMs: 10000 }],+ 60000,+ );++ expect(runPromptThroughProvider).toHaveBeenCalledTimes(1);+ expect(result.evaluation.scores[0]).toMatchObject({+ validCount: 2,+ validItems: ['firehouse', 'wildfire'],+ invalidItems: ['fire', 'firebanana'],+ duplicateItems: ['FIRE HOUSE'],+ });+ });++ it('rejects incomplete semantic verdict batches', async () => {+ mockApiProvider({ verdicts: [] });+ await expect(scoreLlmDrill(+ 'compound-chain',+ { challenges: [{ rootWord: 'fire', position: 'both', minExpected: 1, examples: [] }] },+ [{ items: ['firehouse'], responseMs: 1000 }],+ 60000,+ )).rejects.toThrow(/verdicts/);+ });});// =============================================================================@@ -771,16 +899,13 @@ describe('scoreLlmDrill bridge-word (local scoring)', () => {expect(result.evaluation.scores[0].feedback).toBe('The answer was "paper"');});- it('falls back to "no answer available" when the puzzle does not resolve', async () => {- const result = await scoreLlmDrill(+ it('rejects a missing answer key instead of fabricating a zero score', async () => {+ await expect(scoreLlmDrill('bridge-word',{ puzzles: [] },[{ response: 'paper', responseMs: 5000 }],60000- );-- expect(result.evaluation.scores[0].score).toBe(0);- expect(result.evaluation.scores[0].feedback).toBe('No answer available');+ )).rejects.toThrow(/missing answer key/);});});@@ -904,4 +1029,3 @@ describe('AI response parsing', () => {await expect(generateWordAssociation({ count: 1 })).rejects.toThrow();});});-