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
feat: POST training mode (M55 P4)
Adam Eivy691540a7c511
diff --git a/client/src/components/meatspace/post/PostDrillRunner.jsx b/client/src/components/meatspace/post/PostDrillRunner.jsxindex 94e0bff259..9117614472 100644--- a/client/src/components/meatspace/post/PostDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostDrillRunner.jsx@@ -1,4 +1,5 @@import { useState, useEffect, useRef, useCallback } from 'react';+import { CheckCircle, XCircle } from 'lucide-react';const DRILL_LABELS = {'doubling-chain': 'Doubling Chain',@@ -15,8 +16,11 @@ export default function PostDrillRunner({ session }) {currentDrillIndex,drillCount,state,+ isTraining,+ lastAnswer,submitAnswer,skipQuestion,+ acknowledgeAnswer,timeExpired} = session;@@ -34,10 +38,15 @@ export default function PostDrillRunner({ session }) {timeExpiredRef.current = timeExpired;}, [timeExpired]);- // Timer+ // Timer (disabled in training mode — no time pressure)useEffect(() => {if (state !== 'drilling' || !currentDrill) return;+ if (isTraining) {+ setTimeLeft(0);+ return;+ }+const startTime = Date.now();const limit = (currentDrill.timeLimitSec || 120) * 1000;setTimeLeft(limit);@@ -53,7 +62,7 @@ export default function PostDrillRunner({ session }) {}, 100);return () => clearInterval(timerRef.current);- }, [state, currentDrill, currentDrillIndex]);+ }, [state, currentDrill, currentDrillIndex, isTraining]);// Auto-focus input on question changeuseEffect(() => {@@ -86,26 +95,89 @@ export default function PostDrillRunner({ session }) {if (timePct <= 10) timerColor = 'bg-port-error';else if (timePct <= 25) timerColor = 'bg-port-warning';+ // Training mode: show feedback overlay+ if (isTraining && lastAnswer) {+ return (+ <div className="max-w-lg mx-auto space-y-6">+ <div className="flex items-center justify-between text-sm text-gray-400">+ <span className="text-purple-400">{DRILL_LABELS[currentDrill.type] || currentDrill.type} — Training</span>+ <span>Drill {currentDrillIndex + 1} of {drillCount}</span>+ </div>++ <div className="text-center py-8">+ <div className="text-2xl font-mono text-gray-400 mb-4">{lastAnswer.prompt}</div>+ {lastAnswer.correct ? (+ <div className="flex flex-col items-center gap-2">+ <CheckCircle size={48} className="text-port-success" />+ <div className="text-3xl font-mono font-bold text-port-success">{lastAnswer.answered}</div>+ <div className="text-sm text-gray-400">Correct</div>+ </div>+ ) : (+ <div className="flex flex-col items-center gap-3">+ <XCircle size={48} className="text-port-error" />+ {lastAnswer.answered != null ? (+ <div className="text-2xl font-mono text-port-error line-through">{lastAnswer.answered}</div>+ ) : (+ <div className="text-sm text-gray-500">Skipped</div>+ )}+ <div className="text-sm text-gray-400">Expected</div>+ <div className="text-3xl font-mono font-bold text-port-success">{lastAnswer.expected}</div>+ {/* Hint: break down the calculation */}+ {lastAnswer.prompt && (+ <div className="text-xs text-gray-500 mt-2 bg-port-bg border border-port-border rounded px-3 py-2">+ {formatHint(lastAnswer.prompt, lastAnswer.expected)}+ </div>+ )}+ </div>+ )}+ </div>++ <button+ onClick={acknowledgeAnswer}+ autoFocus+ className="w-full px-6 py-3 bg-purple-600 hover:bg-purple-500 text-white font-medium rounded-lg transition-colors"+ >+ Next+ </button>++ <div className="space-y-1">+ <div className="flex justify-between text-xs text-gray-500">+ <span>Question {currentQuestionIndex + 1} of {totalQuestions}</span>+ <span>{Math.round(progressPct)}%</span>+ </div>+ <div className="w-full h-1.5 bg-port-border rounded-full overflow-hidden">+ <div className="h-full bg-purple-500/60 transition-all" style={{ width: `${progressPct}%` }} />+ </div>+ </div>+ </div>+ );+ }+return (<div className="max-w-lg mx-auto space-y-6">{/* Drill header */}<div className="flex items-center justify-between text-sm text-gray-400">- <span>{DRILL_LABELS[currentDrill.type] || currentDrill.type}</span>+ <span className={isTraining ? 'text-purple-400' : ''}>+ {DRILL_LABELS[currentDrill.type] || currentDrill.type}+ {isTraining && ' — Training'}+ </span><span>Drill {currentDrillIndex + 1} of {drillCount}</span></div>- {/* Timer bar */}- <div className="w-full h-2 bg-port-border rounded-full overflow-hidden">- <div- className={`h-full ${timerColor} transition-all duration-100`}- style={{ width: `${timePct}%` }}- />- </div>-- {/* Time remaining */}- <div className="text-center text-sm text-gray-500">- {Math.ceil(timeLeft / 1000)}s remaining- </div>+ {/* Timer bar (hidden in training mode) */}+ {!isTraining && (+ <>+ <div className="w-full h-2 bg-port-border rounded-full overflow-hidden">+ <div+ className={`h-full ${timerColor} transition-all duration-100`}+ style={{ width: `${timePct}%` }}+ />+ </div>+ <div className="text-center text-sm text-gray-500">+ {Math.ceil(timeLeft / 1000)}s remaining+ </div>+ </>+ )}{/* Question */}<div className="text-center py-8">@@ -129,7 +201,7 @@ export default function PostDrillRunner({ session }) {<buttontype="submit"disabled={inputValue.trim() === ''}- className="px-6 py-3 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white font-medium rounded-lg transition-colors"+ className={`px-6 py-3 ${isTraining ? 'bg-purple-600 hover:bg-purple-500' : 'bg-port-accent hover:bg-port-accent/80'} disabled:opacity-50 text-white font-medium rounded-lg transition-colors`}>Enter</button>@@ -153,7 +225,7 @@ export default function PostDrillRunner({ session }) {</div><div className="w-full h-1.5 bg-port-border rounded-full overflow-hidden"><div- className="h-full bg-port-accent/60 transition-all"+ className={`h-full ${isTraining ? 'bg-purple-500/60' : 'bg-port-accent/60'} transition-all`}style={{ width: `${progressPct}%` }}/></div>@@ -161,3 +233,13 @@ export default function PostDrillRunner({ session }) {</div>);}++function formatHint(prompt, expected) {+ // Break down the calculation for learning+ const match = prompt.match(/^(-?\d+)\s*([+\-x^])\s*(-?\d+)$/);+ if (!match) return `${prompt} = ${expected}`;+ const [, a, op, b] = match;+ if (op === 'x') return `${a} × ${b} = ${expected}`;+ if (op === '^') return `${a}^${b} = ${expected}`;+ return `${prompt} = ${expected}`;+}diff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.jsxindex 6017ea36dd..8275845508 100644--- a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx@@ -1,4 +1,6 @@import { useState, useEffect, useRef, useCallback } from 'react';+import { CheckCircle, XCircle, Loader } from 'lucide-react';+import { scorePostLlmDrill } from '../../../services/api';const DRILL_LABELS = {'word-association': 'Word Association',@@ -13,13 +15,14 @@ const DRILL_LABELS = {'reframe': 'Reframe',};-export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drillCount, onComplete }) {+export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drillCount, onComplete, isTraining, providerId, model }) {const [questionIndex, setQuestionIndex] = useState(0);const [responses, setResponses] = useState([]);const [inputValue, setInputValue] = useState('');const [timeLeft, setTimeLeft] = useState(0);const [phase, setPhase] = useState('active'); // active | reading | recallconst [items, setItems] = useState([]); // for verbal-fluency+ const [trainingFeedback, setTrainingFeedback] = useState(null); // { score, feedback, scoring }const inputRef = useRef(null);const timerRef = useRef(null);const questionStartRef = useRef(Date.now());@@ -39,6 +42,12 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drdrillStartRef.current = Date.now();questionStartRef.current = Date.now();setPhase(drillType === 'story-recall' ? 'reading' : 'active');+ setTrainingFeedback(null);++ if (isTraining) {+ setTimeLeft(0);+ return;+ }const startTime = Date.now();const limit = timeLimitMs;@@ -55,7 +64,7 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr}, 100);return () => clearInterval(timerRef.current);- }, [drill]);+ }, [drill, isTraining]);// Keep refs in sync with state for use in interval callbacksuseEffect(() => { responsesRef.current = responses; }, [responses]);@@ -92,13 +101,12 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr});}- const handleSubmit = useCallback((e) => {+ const handleSubmit = useCallback(async (e) => {e?.preventDefault();const responseMs = Date.now() - questionStartRef.current;let responseObj;if (drillType === 'story-recall') {- // Submit all recall answers at onceresponseObj = {answers: items.length > 0 ? items : [inputValue.trim()],responseMs@@ -119,6 +127,21 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drconst newResponses = [...responses, responseObj];setResponses(newResponses);+ // Training mode: score this response immediately and show feedback+ if (isTraining) {+ setTrainingFeedback({ scoring: true });+ 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',+ });+ return;+ }+if (questionIndex + 1 >= totalPrompts) {finishDrill(newResponses);} else {@@ -129,7 +152,22 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drsetItems([]);}}- }, [inputValue, items, responses, questionIndex, totalPrompts, drillType, currentPrompt]);+ }, [inputValue, items, responses, questionIndex, totalPrompts, drillType, currentPrompt, isTraining, drill, timeLimitMs, providerId, model]);++ // Training mode: advance after acknowledging feedback+ const acknowledgeTrainingFeedback = useCallback(() => {+ setTrainingFeedback(null);+ if (questionIndex + 1 >= totalPrompts) {+ finishDrill(responses);+ } else {+ setQuestionIndex(questionIndex + 1);+ questionStartRef.current = Date.now();+ if (drillType === 'story-recall') {+ setPhase('reading');+ setItems([]);+ }+ }+ }, [questionIndex, totalPrompts, responses, drillType]);// Story recall: transition from reading to answeringfunction handleStartRecall() {@@ -171,19 +209,79 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drif (timePct <= 10) timerColor = 'bg-port-error';else if (timePct <= 25) timerColor = 'bg-port-warning';+ // Training mode: feedback overlay+ if (isTraining && trainingFeedback) {+ if (trainingFeedback.scoring) {+ return (+ <div className="max-w-lg mx-auto space-y-6">+ <div className="flex items-center justify-between text-sm text-gray-400">+ <span className="text-purple-400">{DRILL_LABELS[drillType] || drillType} — Training</span>+ <span>Drill {drillIndex + 1} of {drillCount}</span>+ </div>+ <div className="flex flex-col items-center gap-3 py-12">+ <Loader size={32} className="text-purple-400 animate-spin" />+ <span className="text-gray-400 text-sm">Evaluating your response...</span>+ </div>+ </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;++ return (+ <div className="max-w-lg mx-auto space-y-6">+ <div className="flex items-center justify-between text-sm text-gray-400">+ <span className="text-purple-400">{DRILL_LABELS[drillType] || drillType} — Training</span>+ <span>Drill {drillIndex + 1} of {drillCount}</span>+ </div>+ <div className="text-center py-6">+ <FbIcon size={40} className={fbScoreColor} />+ <div className={`text-3xl font-mono font-bold mt-2 ${fbScoreColor}`}>{trainingFeedback.score}</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <p className="text-sm text-gray-300">{trainingFeedback.feedback}</p>+ </div>+ <button+ onClick={acknowledgeTrainingFeedback}+ autoFocus+ className="w-full px-6 py-3 bg-purple-600 hover:bg-purple-500 text-white font-medium rounded-lg transition-colors"+ >+ Next+ </button>+ <div className="space-y-1">+ <div className="flex justify-between text-xs text-gray-500">+ <span>Prompt {questionIndex + 1} of {totalPrompts}</span>+ </div>+ <div className="w-full h-1.5 bg-port-border rounded-full overflow-hidden">+ <div className="h-full bg-purple-500/60 transition-all" style={{ width: `${((questionIndex + 1) / totalPrompts) * 100}%` }} />+ </div>+ </div>+ </div>+ );+ }+return (<div className="max-w-lg mx-auto space-y-6">{/* Header */}<div className="flex items-center justify-between text-sm text-gray-400">- <span>{DRILL_LABELS[drillType] || drillType}</span>+ <span className={isTraining ? 'text-purple-400' : ''}>+ {DRILL_LABELS[drillType] || drillType}+ {isTraining && ' — Training'}+ </span><span>Drill {drillIndex + 1} of {drillCount}</span></div>- {/* Timer bar */}- <div className="w-full h-2 bg-port-border rounded-full overflow-hidden">- <div className={`h-full ${timerColor} transition-all duration-100`} style={{ width: `${timePct}%` }} />- </div>- <div className="text-center text-sm text-gray-500">{Math.ceil(timeLeft / 1000)}s remaining</div>+ {/* Timer bar (hidden in training mode) */}+ {!isTraining && (+ <>+ <div className="w-full h-2 bg-port-border rounded-full overflow-hidden">+ <div className={`h-full ${timerColor} transition-all duration-100`} style={{ width: `${timePct}%` }} />+ </div>+ <div className="text-center text-sm text-gray-500">{Math.ceil(timeLeft / 1000)}s remaining</div>+ </>+ )}{/* Drill-specific UI */}{drillType === 'word-association' && (diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex ea72b41427..0c31b8b69f 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -1,5 +1,5 @@import { useState, useEffect } from 'react';-import { Zap, History, Settings, Play, Brain, BookOpen } from 'lucide-react';+import { Zap, History, Settings, Play, Brain, BookOpen, Dumbbell } from 'lucide-react';import { getProviders } from '../../../services/api';const DRILL_LABELS = {@@ -25,6 +25,7 @@ const DRILL_LABELS = {export default function PostSessionLauncher({ config, recentSessions, onStart, onViewHistory, onViewConfig, onViewMemory }) {const [tags, setTags] = useState({ sleep: '', caffeine: '', stress: '' });+ const [mode, setMode] = useState('test'); // 'test' | 'train'const [providers, setProviders] = useState([]);useEffect(() => {@@ -78,7 +79,7 @@ export default function PostSessionLauncher({ config, recentSessions, onStart, ofor (const [k, v] of Object.entries(tags)) {if (v.trim()) cleanTags[k] = v.trim();}- onStart(drillConfigs, cleanTags);+ onStart(drillConfigs, cleanTags, mode === 'train');}const hasAnyDrills = enabledMathDrills.length > 0 || enabledLlmDrills.length > 0;@@ -180,8 +181,42 @@ export default function PostSessionLauncher({ config, recentSessions, onStart, o</div>)}- {/* Condition Tags */}+ {/* Mode Toggle */}<div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3">Session Mode</h3>+ <div className="flex gap-2">+ <button+ onClick={() => setMode('test')}+ className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors ${+ mode === 'test'+ ? 'bg-port-accent text-white'+ : 'bg-port-bg border border-port-border text-gray-400 hover:text-white'+ }`}+ >+ <Zap size={14} />+ Test+ </button>+ <button+ onClick={() => setMode('train')}+ className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors ${+ mode === 'train'+ ? 'bg-purple-600 text-white'+ : 'bg-port-bg border border-port-border text-gray-400 hover:text-white'+ }`}+ >+ <Dumbbell size={14} />+ Train+ </button>+ </div>+ <p className="text-xs text-gray-500 mt-2">+ {mode === 'train'+ ? 'Training mode: immediate feedback, hints on wrong answers. Not scored.'+ : 'Test mode: timed drills with scoring. Saved to history.'}+ </p>+ </div>++ {/* Condition Tags */}+ {mode === 'test' && <div className="bg-port-card border border-port-border rounded-lg p-4"><h3 className="text-sm font-medium text-gray-400 mb-3">Conditions (optional)</h3><div className="grid grid-cols-3 gap-3">{Object.entries(tags).map(([key, value]) => (@@ -197,16 +232,20 @@ export default function PostSessionLauncher({ config, recentSessions, onStart, o</div>))}</div>- </div>+ </div>}{/* Start Button */}<buttononClick={handleStart}disabled={!hasAnyDrills}- className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors"+ className={`w-full flex items-center justify-center gap-2 px-6 py-3 ${+ mode === 'train'+ ? 'bg-purple-600 hover:bg-purple-500'+ : 'bg-port-accent hover:bg-port-accent/80'+ } disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors`}>- <Play size={18} />- Start POST+ {mode === 'train' ? <Dumbbell size={18} /> : <Play size={18} />}+ {mode === 'train' ? 'Start Training' : 'Start POST'}</button>{/* Recent Scores */}diff --git a/client/src/components/meatspace/post/PostSessionResults.jsx b/client/src/components/meatspace/post/PostSessionResults.jsxindex 6f118845f8..3e914aae36 100644--- a/client/src/components/meatspace/post/PostSessionResults.jsx+++ b/client/src/components/meatspace/post/PostSessionResults.jsx@@ -1,5 +1,5 @@import { useState } from 'react';-import { CheckCircle, Save, ArrowLeft, ChevronDown, ChevronUp } from 'lucide-react';+import { CheckCircle, Save, ArrowLeft, ChevronDown, ChevronUp, Dumbbell } from 'lucide-react';import { LLM_DRILL_TYPES } from './constants';const DRILL_LABELS = {@@ -16,7 +16,7 @@ const DRILL_LABELS = {};export default function PostSessionResults({ session, tags = {}, onSaved, onBack }) {- const { drillResults, sessionScore, state, saveSession } = session;+ const { drillResults, sessionScore, state, saveSession, isTraining } = session;const [expandedDrill, setExpandedDrill] = useState(null);const scoreColor = sessionScore >= 80 ? 'text-port-success' :@@ -32,12 +32,16 @@ export default function PostSessionResults({ session, tags = {}, onSaved, onBack{/* Overall Score */}<div className="text-center py-8"><div className="flex items-center justify-center gap-3 mb-2">- <CheckCircle size={28} className={scoreColor} />- <span className="text-sm text-gray-400">Session Score</span>- </div>- <div className={`text-6xl font-mono font-bold ${scoreColor}`}>- {sessionScore}+ {isTraining ? <Dumbbell size={28} className="text-purple-400" /> : <CheckCircle size={28} className={scoreColor} />}+ <span className="text-sm text-gray-400">{isTraining ? 'Training Session' : 'Session Score'}</span></div>+ {isTraining ? (+ <div className="text-2xl text-purple-400 font-medium">Practice Complete</div>+ ) : (+ <div className={`text-6xl font-mono font-bold ${scoreColor}`}>+ {sessionScore}+ </div>+ )}</div>{/* Per-drill Breakdown */}@@ -117,10 +121,12 @@ export default function PostSessionResults({ session, tags = {}, onSaved, onBack{state === 'complete' && (<buttononClick={handleSave}- className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-port-success hover:bg-port-success/80 text-white font-medium rounded-lg transition-colors"+ className={`w-full flex items-center justify-center gap-2 px-6 py-3 ${+ isTraining ? 'bg-purple-600 hover:bg-purple-500' : 'bg-port-success hover:bg-port-success/80'+ } text-white font-medium rounded-lg transition-colors`}>- <Save size={18} />- Save Session+ {isTraining ? <Dumbbell size={18} /> : <Save size={18} />}+ {isTraining ? 'Log Training' : 'Save Session'}</button>)}diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsxindex e8d791b44a..88cf96772f 100644--- a/client/src/components/meatspace/tabs/PostTab.jsx+++ b/client/src/components/meatspace/tabs/PostTab.jsx@@ -30,9 +30,9 @@ export default function PostTab() {setRecentSessions(sessions || []);}- async function handleStart(drillConfigs, tags) {+ async function handleStart(drillConfigs, tags, training = false) {setSessionTags(tags || {});- const started = await session.startSession(drillConfigs);+ const started = await session.startSession(drillConfigs, training);if (started) setView('running');}@@ -88,6 +88,7 @@ export default function PostTab() {switch (view) {case 'running':if (isLlmDrill) {+ const drillConfig = session.drills[session.currentDrillIndex];return (<PostLlmDrillRunnerdrill={session.currentDrill}@@ -95,6 +96,9 @@ export default function PostTab() {drillIndex={session.currentDrillIndex}drillCount={session.drillCount}onComplete={session.completeLlmDrill}+ isTraining={session.isTraining}+ providerId={drillConfig?.providerId}+ model={drillConfig?.model}/>);}diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex b305e07e23..5c982fcdda 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -1,5 +1,5 @@import { useState, useCallback, useRef } from 'react';-import { generatePostDrill, submitPostSession, scorePostLlmDrill } from '../services/api';+import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingEntry } from '../services/api';import toast from 'react-hot-toast';import { LLM_DRILL_TYPES } from '../components/meatspace/post/constants';@@ -24,21 +24,25 @@ export function usePostSession() {const [drillResults, setDrillResults] = useState([]); // completed drill resultsconst [sessionScore, setSessionScore] = useState(0);const [savedSession, setSavedSession] = useState(null);+ const [isTraining, setIsTraining] = useState(false);+ const [lastAnswer, setLastAnswer] = useState(null); // { correct, expected, answered } for training feedbackconst questionStartRef = useRef(Date.now());const drillStartRef = useRef(Date.now());const finishDrillRef = useRef(null);- const startSession = useCallback(async (drillConfigs) => {+ const startSession = useCallback(async (drillConfigs, training = false) => {// drillConfigs: [{ type, config, timeLimitSec }]if (!drillConfigs?.length) {toast.error('No drills configured');return;}setState(STATES.LOADING);+ setIsTraining(training);setDrills(drillConfigs);setCurrentDrillIndex(0);setDrillResults([]);setSavedSession(null);+ setLastAnswer(null);const first = drillConfigs[0];const drill = await generatePostDrill(first.type, first.config, first.providerId, first.model).catch(err => {@@ -124,6 +128,12 @@ export function usePostSession() {const newAnswers = [...answers, answer];setAnswers(newAnswers);+ // Training mode: pause to show feedback before advancing+ if (isTraining) {+ setLastAnswer(answer);+ return;+ }+// Check if drill is completeif (currentQuestionIndex + 1 >= (currentDrill.questions?.length ?? 0)) {finishDrillRef.current(newAnswers);@@ -131,12 +141,23 @@ export function usePostSession() {setCurrentQuestionIndex(currentQuestionIndex + 1);questionStartRef.current = Date.now();}- }, [state, currentDrill, currentQuestionIndex, answers]);+ }, [state, currentDrill, currentQuestionIndex, answers, isTraining]);const skipQuestion = useCallback(() => {submitAnswer(null);}, [submitAnswer]);+ // Training mode: advance to next question after user sees feedback+ const acknowledgeAnswer = useCallback(() => {+ setLastAnswer(null);+ if (currentQuestionIndex + 1 >= (currentDrill?.questions?.length ?? 0)) {+ finishDrillRef.current(answers);+ } else {+ setCurrentQuestionIndex(currentQuestionIndex + 1);+ questionStartRef.current = Date.now();+ }+ }, [currentQuestionIndex, currentDrill, answers]);+const nextDrill = useCallback(async () => {const nextIndex = currentDrillIndex + 1;setCurrentDrillIndex(nextIndex);@@ -217,6 +238,25 @@ export function usePostSession() {const saveSession = useCallback(async (tags = {}) => {setState(STATES.SAVING);++ // Training mode: log each drill to the training log, don't save scored session+ if (isTraining) {+ for (const r of drillResults) {+ const questionCount = r.questions?.length || r.responses?.length || 0;+ const correctCount = r.questions?.filter(q => q.correct).length ?? 0;+ await submitTrainingEntry({+ module: r.module,+ drillType: r.type,+ questionCount,+ correctCount,+ totalMs: r.totalMs || 0,+ }).catch(() => {});+ }+ toast.success('Training session logged');+ setState(STATES.SAVED);+ return { training: true };+ }+const modules = [...new Set(drillResults.map(r => r.module))];const session = await submitPostSession({cadence: 'daily',@@ -233,7 +273,7 @@ export function usePostSession() {toast.success(`POST complete — score: ${session.score}`);setState(STATES.SAVED);return session;- }, [drillResults]);+ }, [drillResults, isTraining]);const reset = useCallback(() => {setState(STATES.IDLE);@@ -245,6 +285,8 @@ export function usePostSession() {setDrillResults([]);setSessionScore(0);setSavedSession(null);+ setIsTraining(false);+ setLastAnswer(null);}, []);return {@@ -252,14 +294,18 @@ export function usePostSession() {currentDrill,currentQuestionIndex,currentDrillIndex,+ drills,drillCount: drills.length,answers,drillResults,sessionScore,savedSession,+ isTraining,+ lastAnswer,startSession,submitAnswer,skipQuestion,+ acknowledgeAnswer,nextDrill,timeExpired,completeLlmDrill,diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 842ff9f41e..c07feb83ba 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1537,6 +1537,14 @@ export const generateMemoryDrill = (data) => request('/meatspace/post/memory-dribody: JSON.stringify(data)});+// MeatSpace - POST Training Log+export const submitTrainingEntry = (data) => request('/meatspace/post/training', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const getTrainingStats = (days) => request(`/meatspace/post/training/stats${days != null ? `?days=${days}` : ''}`);+export const getTrainingEntries = (limit) => request(`/meatspace/post/training/entries${limit ? `?limit=${limit}` : ''}`);+// Life Calendarexport const getLifeCalendar = () => request('/meatspace/calendar');export const getActivities = () => request('/meatspace/activities');diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 4ab295ab72..ac06088f39 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -184,4 +184,13 @@ export const memoryDrillRequestSchema = z.object({count: z.number().int().min(1).max(30).optional().default(5),});+// Training log entry submission+export const trainingEntrySchema = z.object({+ module: z.string(),+ drillType: z.enum(DRILL_TYPES),+ questionCount: z.number().int().min(0),+ correctCount: z.number().int().min(0),+ totalMs: z.number().min(0),+});+export { LLM_DRILL_TYPES, MATH_DRILL_TYPES, MEMORY_DRILL_TYPES };diff --git a/server/routes/meatspace.js b/server/routes/meatspace.jsindex c5eab8bcaf..6c1ba3a0c6 100644--- a/server/routes/meatspace.js+++ b/server/routes/meatspace.js@@ -28,6 +28,7 @@ import {memoryDrillRequestSchema,LLM_DRILL_TYPES,MEMORY_DRILL_TYPES,+ trainingEntrySchema,} from '../lib/postValidation.js';import * as meatspaceService from '../services/meatspace.js';import * as alcoholService from '../services/meatspaceAlcohol.js';@@ -35,6 +36,7 @@ import * as healthService from '../services/meatspaceHealth.js';import * as postService from '../services/meatspacePost.js';import * as memoryService from '../services/meatspacePostMemory.js';import { generateLlmDrill, scoreLlmDrill } from '../services/meatspacePostLlm.js';+import * as trainingService from '../services/meatspacePostTraining.js';import * as calendarService from '../services/meatspaceCalendar.js';const router = Router();@@ -477,6 +479,41 @@ router.post('/post/score-llm', asyncHandler(async (req, res) => {res.json(result);}));+// =============================================================================+// POST - Training Log+// =============================================================================++/**+ * POST /api/meatspace/post/training+ * Submit a training practice entry (separate from scored sessions)+ */+router.post('/post/training', asyncHandler(async (req, res) => {+ const data = validateRequest(trainingEntrySchema, req.body);+ const entry = await trainingService.submitTrainingEntry(data);+ res.status(201).json(entry);+}));++/**+ * GET /api/meatspace/post/training/stats+ * Training stats: practice counts, streaks, accuracy by drill type+ */+router.get('/post/training/stats', asyncHandler(async (req, res) => {+ const rawDays = req.query.days != null ? parseInt(req.query.days, 10) : 30;+ const days = Number.isNaN(rawDays) ? 30 : rawDays > 0 ? Math.min(rawDays, 365) : 0;+ const stats = await trainingService.getTrainingStats(days);+ res.json(stats);+}));++/**+ * GET /api/meatspace/post/training/entries+ * Recent training entries+ */+router.get('/post/training/entries', asyncHandler(async (req, res) => {+ const limit = Math.min(parseInt(req.query.limit, 10) || 20, 100);+ const entries = await trainingService.getTrainingEntries(limit);+ res.json(entries);+}));+// =============================================================================// POST - Memory Builder// =============================================================================diff --git a/server/services/meatspacePostTraining.js b/server/services/meatspacePostTraining.jsnew file mode 100644index 0000000000..a88b95d004--- /dev/null+++ b/server/services/meatspacePostTraining.js@@ -0,0 +1,125 @@+/**+ * POST Training Log Service+ *+ * Tracks practice sessions separate from scored POST history.+ * Training mode: progressive difficulty, hints, immediate feedback.+ */++import { writeFile } from 'fs/promises';+import { join } from 'path';+import { randomUUID } from 'crypto';+import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';++const MEATSPACE_DIR = PATHS.meatspace;+const TRAINING_LOG_FILE = join(MEATSPACE_DIR, 'post-training-log.json');++async function loadTrainingLog() {+ const data = await readJSONFile(TRAINING_LOG_FILE, { entries: [] }, { allowArray: false });+ if (!Array.isArray(data.entries)) data.entries = [];+ return data;+}++async function saveTrainingLog(data) {+ await ensureDir(MEATSPACE_DIR);+ await writeFile(TRAINING_LOG_FILE, JSON.stringify(data, null, 2));+}++/**+ * Submit a training practice entry after a training-mode drill completes.+ */+export async function submitTrainingEntry(entry) {+ const data = await loadTrainingLog();+ const now = new Date().toISOString();++ const record = {+ id: randomUUID(),+ date: now.split('T')[0],+ timestamp: now,+ module: entry.module,+ drillType: entry.drillType,+ questionCount: entry.questionCount || 0,+ correctCount: entry.correctCount || 0,+ totalMs: entry.totalMs || 0,+ };++ data.entries.push(record);+ await saveTrainingLog(data);+ console.log(`🏋️ Training logged: ${record.module}/${record.drillType} ${record.correctCount}/${record.questionCount}`);+ return record;+}++/**+ * Get training stats: per-drill practice counts, streaks, recent activity.+ */+export async function getTrainingStats(days = 30) {+ const data = await loadTrainingLog();+ let entries = data.entries;++ if (days > 0) {+ const cutoff = new Date();+ cutoff.setDate(cutoff.getDate() - days);+ const cutoffStr = cutoff.toISOString().split('T')[0];+ entries = entries.filter(e => e.date >= cutoffStr);+ }++ // Group by drill type+ const byDrill = {};+ for (const e of entries) {+ const key = `${e.module}:${e.drillType}`;+ if (!byDrill[key]) byDrill[key] = { practiceCount: 0, totalCorrect: 0, totalQuestions: 0, totalMs: 0, dates: new Set() };+ byDrill[key].practiceCount++;+ byDrill[key].totalCorrect += e.correctCount;+ byDrill[key].totalQuestions += e.questionCount;+ byDrill[key].totalMs += e.totalMs;+ byDrill[key].dates.add(e.date);+ }++ // Compute streaks (consecutive days of practice)+ const allDates = [...new Set(entries.map(e => e.date))].sort();+ let currentStreak = 0;+ if (allDates.length > 0) {+ const today = new Date().toISOString().split('T')[0];+ const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0];+ // Count backwards from today/yesterday+ let checkDate = allDates.includes(today) ? today : allDates.includes(yesterday) ? yesterday : null;+ if (checkDate) {+ currentStreak = 1;+ let d = new Date(checkDate);+ while (true) {+ d.setDate(d.getDate() - 1);+ const prev = d.toISOString().split('T')[0];+ if (allDates.includes(prev)) {+ currentStreak++;+ } else {+ break;+ }+ }+ }+ }++ // Summarize+ const summary = {};+ for (const [key, stats] of Object.entries(byDrill)) {+ summary[key] = {+ practiceCount: stats.practiceCount,+ accuracy: stats.totalQuestions > 0 ? Math.round((stats.totalCorrect / stats.totalQuestions) * 100) : 0,+ totalMs: stats.totalMs,+ daysActive: stats.dates.size,+ };+ }++ return {+ days,+ totalEntries: entries.length,+ currentStreak,+ byDrill: summary,+ };+}++/**+ * Get recent training entries for display.+ */+export async function getTrainingEntries(limit = 20) {+ const data = await loadTrainingLog();+ return data.entries.slice(-limit).reverse();+}diff --git a/server/services/meatspacePostTraining.test.js b/server/services/meatspacePostTraining.test.jsnew file mode 100644index 0000000000..b5beac2ceb--- /dev/null+++ b/server/services/meatspacePostTraining.test.js@@ -0,0 +1,158 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('fs/promises', () => ({+ writeFile: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { meatspace: '/tmp/test-meatspace' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ readJSONFile: vi.fn().mockResolvedValue({ entries: [] }),+}));++import { readJSONFile } from '../lib/fileUtils.js';+import { writeFile } from 'fs/promises';+import {+ submitTrainingEntry,+ getTrainingStats,+ getTrainingEntries,+} from './meatspacePostTraining.js';++beforeEach(() => {+ vi.clearAllMocks();+ readJSONFile.mockResolvedValue({ entries: [] });+});++describe('submitTrainingEntry', () => {+ it('creates a training entry with correct fields', async () => {+ const entry = await submitTrainingEntry({+ module: 'mental-math',+ drillType: 'multiplication',+ questionCount: 10,+ correctCount: 7,+ totalMs: 45000,+ });++ expect(entry).toMatchObject({+ module: 'mental-math',+ drillType: 'multiplication',+ questionCount: 10,+ correctCount: 7,+ totalMs: 45000,+ });+ expect(entry.id).toBeTruthy();+ expect(entry.date).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ expect(entry.timestamp).toBeTruthy();+ expect(writeFile).toHaveBeenCalledOnce();+ });++ it('appends to existing entries', async () => {+ readJSONFile.mockResolvedValue({+ entries: [{ id: 'old', module: 'mental-math', drillType: 'powers' }]+ });++ await submitTrainingEntry({+ module: 'llm-drills',+ drillType: 'wit-comeback',+ questionCount: 5,+ correctCount: 3,+ totalMs: 30000,+ });++ const savedData = JSON.parse(writeFile.mock.calls[0][1]);+ expect(savedData.entries).toHaveLength(2);+ expect(savedData.entries[0].id).toBe('old');+ expect(savedData.entries[1].module).toBe('llm-drills');+ });+});++describe('getTrainingStats', () => {+ it('returns empty stats for no entries', async () => {+ const stats = await getTrainingStats(30);+ expect(stats).toMatchObject({+ days: 30,+ totalEntries: 0,+ currentStreak: 0,+ byDrill: {},+ });+ });++ it('computes accuracy and practice count by drill', async () => {+ const today = new Date().toISOString().split('T')[0];+ readJSONFile.mockResolvedValue({+ entries: [+ { date: today, module: 'mental-math', drillType: 'multiplication', questionCount: 10, correctCount: 8, totalMs: 5000 },+ { date: today, module: 'mental-math', drillType: 'multiplication', questionCount: 10, correctCount: 6, totalMs: 6000 },+ ]+ });++ const stats = await getTrainingStats(30);+ expect(stats.totalEntries).toBe(2);+ expect(stats.byDrill['mental-math:multiplication']).toMatchObject({+ practiceCount: 2,+ accuracy: 70, // (8+6)/(10+10) = 70%+ totalMs: 11000,+ daysActive: 1,+ });+ });++ it('computes streak for consecutive days', async () => {+ const today = new Date();+ const dates = [0, 1, 2].map(d => {+ const dt = new Date(today);+ dt.setDate(dt.getDate() - d);+ return dt.toISOString().split('T')[0];+ });++ readJSONFile.mockResolvedValue({+ entries: dates.map(date => ({+ date,+ module: 'mental-math',+ drillType: 'multiplication',+ questionCount: 5,+ correctCount: 5,+ totalMs: 3000,+ }))+ });++ const stats = await getTrainingStats(30);+ expect(stats.currentStreak).toBe(3);+ });++ it('filters by date range', async () => {+ const old = '2020-01-01';+ const today = new Date().toISOString().split('T')[0];+ readJSONFile.mockResolvedValue({+ entries: [+ { date: old, module: 'mental-math', drillType: 'powers', questionCount: 5, correctCount: 5, totalMs: 3000 },+ { date: today, module: 'mental-math', drillType: 'powers', questionCount: 5, correctCount: 3, totalMs: 4000 },+ ]+ });++ const stats = await getTrainingStats(7);+ expect(stats.totalEntries).toBe(1);+ });+});++describe('getTrainingEntries', () => {+ it('returns entries in reverse order (most recent first)', async () => {+ readJSONFile.mockResolvedValue({+ entries: [+ { id: 'a', date: '2024-01-01' },+ { id: 'b', date: '2024-01-02' },+ { id: 'c', date: '2024-01-03' },+ ]+ });++ const entries = await getTrainingEntries(10);+ expect(entries.map(e => e.id)).toEqual(['c', 'b', 'a']);+ });++ it('respects limit', async () => {+ readJSONFile.mockResolvedValue({+ entries: Array.from({ length: 50 }, (_, i) => ({ id: `e${i}`, date: '2024-01-01' }))+ });++ const entries = await getTrainingEntries(5);+ expect(entries).toHaveLength(5);+ });+});