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: add LLM-powered wit & memory drills to POST (M53 P2)
Adam Eivyb01e9c1c4a46
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex da4bdc1883..132dfd4c31 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,9 @@# Unreleased Changes## Added+- POST: LLM-powered Wit & Memory drills — 5 new AI drill types (word association, story recall, verbal fluency, wit/comeback, pun/wordplay) with configurable provider/model per drill+- POST: server-side LLM scoring with per-response feedback and evaluation summaries+- POST: provider/model selector in drill config UI for LLM drills## Changed- Update tab: render release notes as markdown instead of plain text, remove max-width constraint for more screen spacediff --git a/PLAN.md b/PLAN.mdindex 4f2afe7d3e..db8160624c 100644--- a/PLAN.md+++ b/PLAN.md@@ -80,7 +80,8 @@ pm2 logs### In Progress- [ ] **M44 P6**: MeatSpace - Genome/Epigenetic Migration cleanup (genome routes moved, but route comments still reference `/api/digital-twin/genome/` and IdentityTab still renders a Genome card with broken link to `/digital-twin/genome`)-- [ ] **M53 P1**: POST (Power On Self Test) - Foundation + Mental Math (daily cognitive self-test with 5 drill types, scoring, history, config). Phase 1 complete: server service/routes/tests, client UI with drill runner, results, history charts, config editor+- [x] **M53 P1**: POST (Power On Self Test) - Foundation + Mental Math (daily cognitive self-test with 5 drill types, scoring, history, config). Phase 1 complete: server service/routes/tests, client UI with drill runner, results, history charts, config editor+- [ ] **M53 P2**: POST - LLM-Powered Wit & Memory Drills (5 AI drill types: word association, story recall, verbal fluency, wit/comeback, pun/wordplay). Per-drill provider/model config, LLM-scored responses with feedback. Server: meatspacePostLlm.js service, score-llm route. Client: PostLlmDrillRunner component, provider selector in config### Planneddiff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsxindex c242ac4e20..0d2398df69 100644--- a/client/src/components/meatspace/post/PostDrillConfig.jsx+++ b/client/src/components/meatspace/post/PostDrillConfig.jsx@@ -1,6 +1,6 @@-import { useState } from 'react';-import { ArrowLeft, Save } from 'lucide-react';-import { updatePostConfig } from '../../../services/api';+import { useState, useEffect } from 'react';+import { ArrowLeft, Save, Brain } from 'lucide-react';+import { updatePostConfig, getProviders } from '../../../services/api';import toast from 'react-hot-toast';const DRILL_META = {@@ -50,12 +50,72 @@ const DRILL_META = {}};+const LLM_DRILL_META = {+ 'word-association': {+ label: 'Word Association',+ desc: 'Associate freely with given words — trains lateral thinking',+ fields: [+ { key: 'count', label: 'Prompts', type: 'number', min: 1, max: 10 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 30, max: 300 }+ ]+ },+ 'story-recall': {+ label: 'Story Recall',+ desc: 'Read a paragraph, then answer questions from memory',+ fields: [+ { key: 'count', label: 'Stories', type: 'number', min: 1, max: 5 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 60, max: 600 }+ ]+ },+ 'verbal-fluency': {+ label: 'Verbal Fluency',+ desc: 'Name as many items in a category as possible',+ fields: [+ { key: 'count', label: 'Categories', type: 'number', min: 1, max: 5 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 30, max: 180 }+ ]+ },+ 'wit-comeback': {+ label: 'Wit & Comeback',+ desc: 'Craft witty responses to scenarios — trains verbal agility',+ fields: [+ { key: 'count', label: 'Scenarios', type: 'number', min: 1, max: 10 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 30, max: 300 }+ ]+ },+ 'pun-wordplay': {+ label: 'Pun & Wordplay',+ desc: 'Create puns and wordplay on given topics',+ fields: [+ { key: 'count', label: 'Challenges', type: 'number', min: 1, max: 10 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 30, max: 300 }+ ]+ }+};+export default function PostDrillConfig({ config, onSaved, onBack }) {const [drillTypes, setDrillTypes] = useState(() => config?.mentalMath?.drillTypes || {});+ const [llmDrillTypes, setLlmDrillTypes] = useState(+ () => config?.llmDrills?.drillTypes || {}+ );+ const [llmEnabled, setLlmEnabled] = useState(+ () => config?.llmDrills?.enabled !== false+ );+ const [llmProviderId, setLlmProviderId] = useState(+ () => config?.llmDrills?.providerId || ''+ );+ const [llmModel, setLlmModel] = useState(+ () => config?.llmDrills?.model || ''+ );+ const [providers, setProviders] = useState([]);const [saving, setSaving] = useState(false);+ useEffect(() => {+ getProviders().then(p => setProviders((p || []).filter(pr => pr.enabled && pr.type === 'api'))).catch(() => {});+ }, []);+function toggleDrill(type) {setDrillTypes(prev => ({...prev,@@ -73,10 +133,36 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {}));}+ function toggleLlmDrill(type) {+ setLlmDrillTypes(prev => ({+ ...prev,+ [type]: { ...prev[type], enabled: !(prev[type]?.enabled !== false) }+ }));+ }++ function updateLlmField(type, key, value) {+ const coerced = value === '' || value === null || value === undefined+ ? undefined+ : Number(value);+ setLlmDrillTypes(prev => ({+ ...prev,+ [type]: { ...prev[type], [key]: coerced }+ }));+ }++ const selectedProvider = providers.find(p => p.id === llmProviderId);+ const availableModels = selectedProvider?.models || [];+async function handleSave() {setSaving(true);const updated = await updatePostConfig({- mentalMath: { drillTypes }+ mentalMath: { drillTypes },+ llmDrills: {+ enabled: llmEnabled,+ providerId: llmProviderId || null,+ model: llmModel || null,+ drillTypes: llmDrillTypes+ }}).catch(() => {setSaving(false);return null;@@ -108,6 +194,8 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {</div>{/* Drill Cards */}+ {/* Mental Math Section */}+ <h3 className="text-sm font-medium text-gray-500 uppercase tracking-wider">Mental Math</h3>{Object.entries(DRILL_META).map(([type, meta]) => {const drillConfig = drillTypes[type] || {};const enabled = drillConfig.enabled !== false;@@ -153,6 +241,108 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {</div>);})}++ {/* LLM Drills Section */}+ <div className="flex items-center justify-between mt-6">+ <div className="flex items-center gap-2">+ <Brain size={16} className="text-purple-400" />+ <h3 className="text-sm font-medium text-gray-500 uppercase tracking-wider">Wit & Memory (LLM)</h3>+ </div>+ <button+ onClick={() => setLlmEnabled(!llmEnabled)}+ className={`w-10 h-5 rounded-full transition-colors relative ${+ llmEnabled ? 'bg-purple-500' : 'bg-port-border'+ }`}+ >+ <div className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${+ llmEnabled ? 'translate-x-5' : 'translate-x-0.5'+ }`} />+ </button>+ </div>++ {llmEnabled && (+ <>+ {/* Provider & Model Selection */}+ <div className="bg-port-card border border-purple-500/30 rounded-lg p-4">+ <h4 className="text-sm font-medium text-gray-400 mb-3">AI Provider</h4>+ <div className="grid grid-cols-2 gap-3">+ <div>+ <label className="text-xs text-gray-500 mb-1 block">Provider</label>+ <select+ value={llmProviderId}+ onChange={e => { setLlmProviderId(e.target.value); setLlmModel(''); }}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"+ >+ <option value="">System Default</option>+ {providers.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ </div>+ <div>+ <label className="text-xs text-gray-500 mb-1 block">Model</label>+ <select+ value={llmModel}+ onChange={e => setLlmModel(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"+ >+ <option value="">Provider Default</option>+ {availableModels.map(m => (+ <option key={m} value={m}>{m}</option>+ ))}+ </select>+ </div>+ </div>+ </div>++ {/* LLM Drill Cards */}+ {Object.entries(LLM_DRILL_META).map(([type, meta]) => {+ const drillConfig = llmDrillTypes[type] || {};+ const enabled = drillConfig.enabled !== false;++ return (+ <div key={type} className={`bg-port-card border rounded-lg p-4 transition-colors ${+ enabled ? 'border-purple-500/30' : 'border-port-border/50 opacity-60'+ }`}>+ <div className="flex items-center justify-between mb-3">+ <div>+ <h3 className="text-white font-medium">{meta.label}</h3>+ <p className="text-gray-500 text-xs">{meta.desc}</p>+ </div>+ <button+ onClick={() => toggleLlmDrill(type)}+ className={`w-10 h-5 rounded-full transition-colors relative ${+ enabled ? 'bg-purple-500' : 'bg-port-border'+ }`}+ >+ <div className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${+ enabled ? 'translate-x-5' : 'translate-x-0.5'+ }`} />+ </button>+ </div>++ {enabled && (+ <div className="grid grid-cols-2 gap-3">+ {meta.fields.map(field => (+ <div key={field.key}>+ <label className="text-xs text-gray-500 mb-1 block">{field.label}</label>+ <input+ type="number"+ min={field.min}+ max={field.max}+ value={drillConfig[field.key] ?? ''}+ onChange={e => updateLlmField(type, field.key, e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"+ />+ </div>+ ))}+ </div>+ )}+ </div>+ );+ })}+ </>+ )}</div>);}diff --git a/client/src/components/meatspace/post/PostHistory.jsx b/client/src/components/meatspace/post/PostHistory.jsxindex 0aca626dbc..f532c1a834 100644--- a/client/src/components/meatspace/post/PostHistory.jsx+++ b/client/src/components/meatspace/post/PostHistory.jsx@@ -8,9 +8,16 @@ const DRILL_LABELS = {'serial-subtraction': 'Serial Subtraction','multiplication': 'Multiplication','powers': 'Powers',- 'estimation': 'Estimation'+ 'estimation': 'Estimation',+ 'word-association': 'Word Association',+ 'story-recall': 'Story Recall',+ 'verbal-fluency': 'Verbal Fluency',+ 'wit-comeback': 'Wit & Comeback',+ 'pun-wordplay': 'Pun & Wordplay'};+const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay'];+const RANGES = [{ label: '7d', days: 7 },{ label: '30d', days: 30 },@@ -151,8 +158,10 @@ export default function PostHistory({ onBack }) {if (expanded) {for (const [i, task] of (s.tasks || []).entries()) {- const correct = task.questions?.filter(q => q.correct).length || 0;- const total = task.questions?.length || 0;+ const isLlm = LLM_DRILL_TYPES.includes(task.type);+ const detail = isLlm+ ? `${task.responses?.length || 0} responses`+ : `${task.questions?.filter(q => q.correct).length || 0}/${task.questions?.length || 0} correct`;rows.push(<tr key={`${s.id}-${i}`} className="bg-port-bg/30"><td></td>@@ -160,7 +169,7 @@ export default function PostHistory({ onBack }) {{DRILL_LABELS[task.type] || task.type}</td><td className="px-4 py-1.5 text-gray-500 text-xs">- {correct}/{total} correct+ {detail}</td><td className="px-4 py-1.5 text-right text-gray-400 text-xs font-mono">{task.score}diff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.jsxnew file mode 100644index 0000000000..b91337de0b--- /dev/null+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx@@ -0,0 +1,486 @@+import { useState, useEffect, useRef, useCallback } from 'react';++const DRILL_LABELS = {+ 'word-association': 'Word Association',+ 'story-recall': 'Story Recall',+ 'verbal-fluency': 'Verbal Fluency',+ 'wit-comeback': 'Wit & Comeback',+ 'pun-wordplay': 'Pun & Wordplay'+};++export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drillCount, onComplete }) {+ 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 | recall+ const [items, setItems] = useState([]); // for verbal-fluency+ const inputRef = useRef(null);+ const timerRef = useRef(null);+ const questionStartRef = useRef(Date.now());+ const drillStartRef = useRef(Date.now());++ const timeLimitMs = (timeLimitSec || 120) * 1000;+ const drillType = drill?.type;++ // Get the list of prompts depending on drill type+ const prompts = getPrompts(drill);+ const totalPrompts = prompts.length;+ const currentPrompt = prompts[questionIndex];++ useEffect(() => {+ drillStartRef.current = Date.now();+ questionStartRef.current = Date.now();+ setPhase(drillType === 'story-recall' ? 'reading' : 'active');++ const startTime = Date.now();+ const limit = timeLimitMs;+ setTimeLeft(limit);++ timerRef.current = setInterval(() => {+ const elapsed = Date.now() - startTime;+ const remaining = Math.max(0, limit - elapsed);+ setTimeLeft(remaining);+ if (remaining <= 0) {+ clearInterval(timerRef.current);+ handleTimeExpired();+ }+ }, 100);++ return () => clearInterval(timerRef.current);+ }, [drill]);++ useEffect(() => {+ setInputValue('');+ setItems([]);+ inputRef.current?.focus();+ }, [questionIndex, phase]);++ function handleTimeExpired() {+ // Submit whatever we have so far+ const remaining = prompts.slice(questionIndex).map(() => ({+ response: '',+ responseMs: 0+ }));+ const finalResponses = [...responses, ...remaining];+ finishDrill(finalResponses);+ }++ function finishDrill(finalResponses) {+ clearInterval(timerRef.current);+ const totalMs = Date.now() - drillStartRef.current;+ onComplete({+ module: 'llm-drills',+ type: drillType,+ config: drill.config,+ drillData: drill,+ responses: finalResponses,+ totalMs+ });+ }++ const handleSubmit = useCallback((e) => {+ e?.preventDefault();+ const responseMs = Date.now() - questionStartRef.current;++ let responseObj;+ if (drillType === 'story-recall') {+ // Submit all recall answers at once+ responseObj = {+ answers: items.length > 0 ? items : [inputValue.trim()],+ responseMs+ };+ } else if (drillType === 'verbal-fluency') {+ responseObj = {+ items: items,+ responseMs+ };+ } else {+ responseObj = {+ prompt: currentPrompt?.prompt || currentPrompt?.setup || currentPrompt?.category || '',+ response: inputValue.trim(),+ responseMs+ };+ }++ const newResponses = [...responses, responseObj];+ setResponses(newResponses);++ if (questionIndex + 1 >= totalPrompts) {+ finishDrill(newResponses);+ } else {+ setQuestionIndex(questionIndex + 1);+ questionStartRef.current = Date.now();+ if (drillType === 'story-recall') {+ setPhase('reading');+ setItems([]);+ }+ }+ }, [inputValue, items, responses, questionIndex, totalPrompts, drillType, currentPrompt]);++ // Story recall: transition from reading to answering+ function handleStartRecall() {+ setPhase('recall');+ setItems([]);+ questionStartRef.current = Date.now();+ setTimeout(() => inputRef.current?.focus(), 50);+ }++ // Verbal fluency: add item to list+ function handleAddItem(e) {+ e?.preventDefault();+ const val = inputValue.trim();+ if (!val) return;+ if (!items.includes(val.toLowerCase())) {+ setItems(prev => [...prev, val]);+ }+ setInputValue('');+ inputRef.current?.focus();+ }++ // Verbal fluency: remove item+ function handleRemoveItem(index) {+ setItems(prev => prev.filter((_, i) => i !== index));+ }++ // Story recall: add recall answer+ function handleAddRecallAnswer(e) {+ e?.preventDefault();+ const val = inputValue.trim();+ if (!val) return;+ setItems(prev => [...prev, val]);+ setInputValue('');+ inputRef.current?.focus();+ }++ const timePct = timeLimitMs > 0 ? (timeLeft / timeLimitMs) * 100 : 0;+ let timerColor = 'bg-port-accent';+ if (timePct <= 10) timerColor = 'bg-port-error';+ else if (timePct <= 25) timerColor = 'bg-port-warning';++ 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>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>++ {/* Drill-specific UI */}+ {drillType === 'word-association' && (+ <WordAssociationUI+ prompt={currentPrompt}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ />+ )}++ {drillType === 'story-recall' && (+ <StoryRecallUI+ exercise={currentPrompt}+ phase={phase}+ onStartRecall={handleStartRecall}+ items={items}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onAddAnswer={handleAddRecallAnswer}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ />+ )}++ {drillType === 'verbal-fluency' && (+ <VerbalFluencyUI+ category={currentPrompt}+ items={items}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onAddItem={handleAddItem}+ onRemoveItem={handleRemoveItem}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ />+ )}++ {drillType === 'wit-comeback' && (+ <WitComebackUI+ scenario={currentPrompt}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ />+ )}++ {drillType === 'pun-wordplay' && (+ <PunWordplayUI+ challenge={currentPrompt}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ />+ )}+ </div>+ );+}++function getPrompts(drill) {+ if (!drill) return [];+ switch (drill.type) {+ case 'word-association': return drill.questions || [];+ case 'story-recall': return drill.exercises || [];+ case 'verbal-fluency': return drill.categories || [];+ case 'wit-comeback': return drill.scenarios || [];+ case 'pun-wordplay': return drill.challenges || [];+ default: return [];+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// DRILL-SPECIFIC UI COMPONENTS+// ─────────────────────────────────────────────────────────────────────────────++function ProgressBar({ index, total }) {+ const pct = total > 0 ? ((index + 1) / total) * 100 : 0;+ return (+ <div className="space-y-1">+ <div className="flex justify-between text-xs text-gray-500">+ <span>Prompt {index + 1} of {total}</span>+ <span>{Math.round(pct)}%</span>+ </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" style={{ width: `${pct}%` }} />+ </div>+ </div>+ );+}++function TextInput({ inputRef, value, onChange, onSubmit, placeholder, buttonLabel = 'Submit' }) {+ return (+ <form onSubmit={onSubmit} className="space-y-3">+ <textarea+ ref={inputRef}+ value={value}+ onChange={e => onChange(e.target.value)}+ placeholder={placeholder}+ rows={3}+ autoFocus+ className="w-full bg-port-bg border border-port-border rounded-lg px-4 py-3 text-white placeholder-gray-600 focus:border-port-accent focus:outline-none resize-none"+ />+ <button+ type="submit"+ disabled={!value.trim()}+ className="w-full px-6 py-2.5 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white font-medium rounded-lg transition-colors"+ >+ {buttonLabel}+ </button>+ </form>+ );+}++function WordAssociationUI({ prompt, inputValue, setInputValue, onSubmit, inputRef, questionIndex, totalPrompts }) {+ return (+ <>+ <div className="text-center py-6">+ <div className="text-sm text-gray-500 mb-2">What comes to mind?</div>+ <div className="text-4xl font-bold text-white">{prompt?.prompt}</div>+ {prompt?.hints && <div className="text-sm text-gray-500 mt-2">{prompt.hints}</div>}+ </div>+ <TextInput+ inputRef={inputRef}+ value={inputValue}+ onChange={setInputValue}+ onSubmit={onSubmit}+ placeholder="Type your associations..."+ buttonLabel="Next"+ />+ <ProgressBar index={questionIndex} total={totalPrompts} />+ </>+ );+}++function StoryRecallUI({ exercise, phase, onStartRecall, items, inputValue, setInputValue, onAddAnswer, onSubmit, inputRef, questionIndex, totalPrompts }) {+ if (phase === 'reading') {+ return (+ <>+ <div className="bg-port-card border border-port-border rounded-lg p-6">+ <div className="text-sm text-gray-500 mb-3">Read carefully — you'll be asked questions about this:</div>+ <p className="text-white text-lg leading-relaxed">{exercise?.paragraph}</p>+ </div>+ <button+ onClick={onStartRecall}+ className="w-full px-6 py-3 bg-port-accent hover:bg-port-accent/80 text-white font-medium rounded-lg transition-colors"+ >+ I'm Ready — Show Questions+ </button>+ <ProgressBar index={questionIndex} total={totalPrompts} />+ </>+ );+ }++ const recallQuestions = exercise?.questions || [];+ return (+ <>+ <div className="space-y-4">+ <div className="text-sm text-gray-400">Answer from memory:</div>+ {recallQuestions.map((q, i) => (+ <div key={i} className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="text-white text-sm mb-2">{q.question}</div>+ {items[i] !== undefined ? (+ <div className="text-port-accent text-sm font-mono">{items[i]}</div>+ ) : (+ <form onSubmit={onAddAnswer} className="flex gap-2">+ <input+ ref={i === items.length ? inputRef : undefined}+ type="text"+ value={i === items.length ? inputValue : ''}+ onChange={e => i === items.length && setInputValue(e.target.value)}+ disabled={i !== items.length}+ placeholder="Your answer..."+ autoFocus={i === items.length}+ className="flex-1 bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white placeholder-gray-600 focus:border-port-accent focus:outline-none disabled:opacity-50"+ />+ {i === items.length && (+ <button type="submit" disabled={!inputValue.trim()} className="px-3 py-1.5 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white text-sm rounded transition-colors">+ Answer+ </button>+ )}+ </form>+ )}+ </div>+ ))}+ </div>+ {items.length >= recallQuestions.length && (+ <button onClick={onSubmit} className="w-full px-6 py-2.5 bg-port-success hover:bg-port-success/80 text-white font-medium rounded-lg transition-colors">+ Submit All Answers+ </button>+ )}+ <ProgressBar index={questionIndex} total={totalPrompts} />+ </>+ );+}++function VerbalFluencyUI({ category, items, inputValue, setInputValue, onAddItem, onRemoveItem, onSubmit, inputRef, questionIndex, totalPrompts }) {+ return (+ <>+ <div className="text-center py-4">+ <div className="text-sm text-gray-500 mb-2">Name as many as you can:</div>+ <div className="text-3xl font-bold text-white">{category?.category}</div>+ {category?.minExpected && (+ <div className="text-sm text-gray-500 mt-2">Target: {category.minExpected}+</div>+ )}+ </div>++ <form onSubmit={onAddItem} className="flex gap-2">+ <input+ ref={inputRef}+ type="text"+ value={inputValue}+ onChange={e => setInputValue(e.target.value)}+ placeholder="Type an item and press Enter..."+ autoFocus+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-4 py-2.5 text-white placeholder-gray-600 focus:border-port-accent focus:outline-none"+ />+ <button type="submit" disabled={!inputValue.trim()} className="px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white font-medium rounded-lg transition-colors">+ Add+ </button>+ </form>++ {items.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between text-sm text-gray-400 mb-2">+ <span>Items ({items.length})</span>+ </div>+ <div className="flex flex-wrap gap-2">+ {items.map((item, i) => (+ <span key={i} className="inline-flex items-center gap-1 px-2 py-1 bg-port-bg border border-port-border rounded text-sm text-white">+ {item}+ <button onClick={() => onRemoveItem(i)} className="text-gray-500 hover:text-port-error ml-1">×</button>+ </span>+ ))}+ </div>+ </div>+ )}++ <button+ onClick={onSubmit}+ disabled={items.length === 0}+ className="w-full px-6 py-2.5 bg-port-success hover:bg-port-success/80 disabled:opacity-50 text-white font-medium rounded-lg transition-colors"+ >+ Done — Submit {items.length} items+ </button>+ <ProgressBar index={questionIndex} total={totalPrompts} />+ </>+ );+}++function WitComebackUI({ scenario, inputValue, setInputValue, onSubmit, inputRef, questionIndex, totalPrompts }) {+ return (+ <>+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center">+ <div className="text-sm text-gray-500 mb-3">+ {scenario?.difficulty && <span className={`inline-block px-2 py-0.5 rounded text-xs mr-2 ${+ scenario.difficulty === 'hard' ? 'bg-port-error/20 text-port-error' :+ scenario.difficulty === 'medium' ? 'bg-port-warning/20 text-port-warning' :+ 'bg-port-success/20 text-port-success'+ }`}>{scenario.difficulty}</span>}+ Respond with wit+ </div>+ <p className="text-white text-lg leading-relaxed">"{scenario?.setup}"</p>+ {scenario?.context && <p className="text-gray-500 text-sm mt-2">{scenario.context}</p>}+ </div>+ <TextInput+ inputRef={inputRef}+ value={inputValue}+ onChange={setInputValue}+ onSubmit={onSubmit}+ placeholder="Your witty response..."+ buttonLabel="Next"+ />+ <ProgressBar index={questionIndex} total={totalPrompts} />+ </>+ );+}++function PunWordplayUI({ challenge, inputValue, setInputValue, onSubmit, inputRef, questionIndex, totalPrompts }) {+ return (+ <>+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center">+ <div className="text-sm text-gray-500 mb-3">+ {challenge?.type && <span className="inline-block px-2 py-0.5 rounded text-xs mr-2 bg-purple-500/20 text-purple-400">{challenge.type}</span>}+ Create wordplay+ </div>+ <p className="text-white text-lg leading-relaxed">{challenge?.prompt}</p>+ {challenge?.topic && <p className="text-gray-500 text-sm mt-2">Topic: {challenge.topic}</p>}+ </div>+ <TextInput+ inputRef={inputRef}+ value={inputValue}+ onChange={setInputValue}+ onSubmit={onSubmit}+ placeholder="Your pun or wordplay..."+ buttonLabel="Next"+ />+ <ProgressBar index={questionIndex} total={totalPrompts} />+ </>+ );+}diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex 2d2b20330e..6a37b0667c 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -1,16 +1,29 @@-import { useState } from 'react';-import { Zap, History, Settings, Play } from 'lucide-react';+import { useState, useEffect } from 'react';+import { Zap, History, Settings, Play, Brain } from 'lucide-react';+import { getProviders } from '../../../services/api';const DRILL_LABELS = {'doubling-chain': 'Doubling Chain','serial-subtraction': 'Serial Subtraction','multiplication': 'Multiplication','powers': 'Powers',- 'estimation': 'Estimation'+ 'estimation': 'Estimation',+ 'word-association': 'Word Association',+ 'story-recall': 'Story Recall',+ 'verbal-fluency': 'Verbal Fluency',+ 'wit-comeback': 'Wit & Comeback',+ 'pun-wordplay': 'Pun & Wordplay'};+const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay'];+export default function PostSessionLauncher({ config, recentSessions, onStart, onViewHistory, onViewConfig }) {const [tags, setTags] = useState({ sleep: '', caffeine: '', stress: '' });+ const [providers, setProviders] = useState([]);++ useEffect(() => {+ getProviders().then(p => setProviders((p || []).filter(pr => pr.enabled && pr.type === 'api'))).catch(() => {});+ }, []);if (!config) {return <div className="text-gray-500">Loading configuration...</div>;@@ -20,11 +33,18 @@ export default function PostSessionLauncher({ config, recentSessions, onStart, oconst todaySession = recentSessions?.find(s => s.date === today);const lastThree = (recentSessions || []).slice(-3).reverse();- const enabledDrills = Object.entries(config.mentalMath?.drillTypes || {})+ const enabledMathDrills = Object.entries(config.mentalMath?.drillTypes || {}).filter(([, cfg]) => cfg.enabled);+ const enabledLlmDrills = config.llmDrills?.enabled !== false+ ? Object.entries(config.llmDrills?.drillTypes || {}).filter(([, cfg]) => cfg.enabled !== false)+ : [];++ const llmProviderId = config.llmDrills?.providerId || null;+ const llmModel = config.llmDrills?.model || null;+function handleStart() {- const drillConfigs = enabledDrills.map(([type, cfg]) => ({+ const mathConfigs = enabledMathDrills.map(([type, cfg]) => ({type,config: {steps: cfg.steps,@@ -38,7 +58,16 @@ export default function PostSessionLauncher({ config, recentSessions, onStart, o},timeLimitSec: cfg.timeLimitSec || 120}));- // Filter out empty tag values++ const llmConfigs = enabledLlmDrills.map(([type, cfg]) => ({+ type,+ config: { count: cfg.count || 5 },+ timeLimitSec: cfg.timeLimitSec || 120,+ providerId: cfg.providerId || llmProviderId,+ model: cfg.model || llmModel+ }));++ const drillConfigs = [...mathConfigs, ...llmConfigs];const cleanTags = {};for (const [k, v] of Object.entries(tags)) {if (v.trim()) cleanTags[k] = v.trim();@@ -46,6 +75,8 @@ export default function PostSessionLauncher({ config, recentSessions, onStart, oonStart(drillConfigs, cleanTags);}+ const hasAnyDrills = enabledMathDrills.length > 0 || enabledLlmDrills.length > 0;+return (<div className="space-y-6 max-w-2xl">{/* Header */}@@ -86,24 +117,55 @@ export default function PostSessionLauncher({ config, recentSessions, onStart, o</div></div>- {/* Enabled Drills */}- <div className="bg-port-card border border-port-border rounded-lg p-4">- <h3 className="text-sm font-medium text-gray-400 mb-3">Enabled Drills</h3>- <div className="space-y-2">- {enabledDrills.map(([type, cfg]) => (- <div key={type} className="flex items-center justify-between text-sm">- <span className="text-white">{DRILL_LABELS[type] || type}</span>- <span className="text-gray-500">- {cfg.steps ? `${cfg.steps} steps` : cfg.count ? `${cfg.count} questions` : ''}- {cfg.timeLimitSec ? ` · ${cfg.timeLimitSec}s` : ''}+ {/* Mental Math Drills */}+ {enabledMathDrills.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3">Mental Math</h3>+ <div className="space-y-2">+ {enabledMathDrills.map(([type, cfg]) => (+ <div key={type} className="flex items-center justify-between text-sm">+ <span className="text-white">{DRILL_LABELS[type] || type}</span>+ <span className="text-gray-500">+ {cfg.steps ? `${cfg.steps} steps` : cfg.count ? `${cfg.count} questions` : ''}+ {cfg.timeLimitSec ? ` · ${cfg.timeLimitSec}s` : ''}+ </span>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* LLM Drills */}+ {enabledLlmDrills.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-3">+ <Brain size={14} className="text-purple-400" />+ <h3 className="text-sm font-medium text-gray-400">Wit & Memory</h3>+ {(llmProviderId || providers.length > 0) && (+ <span className="text-xs text-gray-600 ml-auto">+ {llmProviderId || 'system default'}</span>- </div>- ))}- {enabledDrills.length === 0 && (- <p className="text-gray-500 text-sm">No drills enabled. Configure drills to get started.</p>- )}+ )}+ </div>+ <div className="space-y-2">+ {enabledLlmDrills.map(([type, cfg]) => (+ <div key={type} className="flex items-center justify-between text-sm">+ <span className="text-white">{DRILL_LABELS[type] || type}</span>+ <span className="text-gray-500">+ {cfg.count ? `${cfg.count} prompts` : ''}+ {cfg.timeLimitSec ? ` · ${cfg.timeLimitSec}s` : ''}+ </span>+ </div>+ ))}+ </div></div>- </div>+ )}++ {!hasAnyDrills && (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <p className="text-gray-500 text-sm">No drills enabled. Configure drills to get started.</p>+ </div>+ )}{/* Condition Tags */}<div className="bg-port-card border border-port-border rounded-lg p-4">@@ -127,7 +189,7 @@ export default function PostSessionLauncher({ config, recentSessions, onStart, o{/* Start Button */}<buttononClick={handleStart}- disabled={enabledDrills.length === 0}+ 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"><Play size={18} />diff --git a/client/src/components/meatspace/post/PostSessionResults.jsx b/client/src/components/meatspace/post/PostSessionResults.jsxindex 4add1c9097..2fb3d2ef61 100644--- a/client/src/components/meatspace/post/PostSessionResults.jsx+++ b/client/src/components/meatspace/post/PostSessionResults.jsx@@ -1,15 +1,24 @@-import { CheckCircle, Save, ArrowLeft } from 'lucide-react';+import { useState } from 'react';+import { CheckCircle, Save, ArrowLeft, ChevronDown, ChevronUp } from 'lucide-react';const DRILL_LABELS = {'doubling-chain': 'Doubling Chain','serial-subtraction': 'Serial Subtraction','multiplication': 'Multiplication','powers': 'Powers',- 'estimation': 'Estimation'+ 'estimation': 'Estimation',+ 'word-association': 'Word Association',+ 'story-recall': 'Story Recall',+ 'verbal-fluency': 'Verbal Fluency',+ 'wit-comeback': 'Wit & Comeback',+ 'pun-wordplay': 'Pun & Wordplay'};+const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay'];+export default function PostSessionResults({ session, tags = {}, onSaved, onBack }) {const { drillResults, sessionScore, state, saveSession } = session;+ const [expandedDrill, setExpandedDrill] = useState(null);const scoreColor = sessionScore >= 80 ? 'text-port-success' :sessionScore >= 50 ? 'text-port-warning' : 'text-port-error';@@ -37,28 +46,68 @@ export default function PostSessionResults({ session, tags = {}, onSaved, onBack<h3 className="text-sm font-medium text-gray-400 mb-3">Drill Breakdown</h3><div className="space-y-3">{drillResults.map((result, i) => {- const correct = result.questions.filter(q => q.correct).length;- const total = result.questions.length;- const accuracyPct = total > 0 ? Math.round((correct / total) * 100) : 0;- const answered = result.questions.filter(q => q.answered !== null);- const avgMs = answered.length > 0- ? Math.round(answered.reduce((s, q) => s + q.responseMs, 0) / answered.length)- : 0;+ const isLlm = LLM_DRILL_TYPES.includes(result.type);+ const isExpanded = expandedDrill === i;++ let subtitle;+ if (isLlm) {+ const summary = result.evaluation?.summary;+ subtitle = summary || `${result.responses?.length || 0} responses`;+ } else {+ const correct = (result.questions || []).filter(q => q.correct).length;+ const total = (result.questions || []).length;+ const accuracyPct = total > 0 ? Math.round((correct / total) * 100) : 0;+ const answered = (result.questions || []).filter(q => q.answered !== null);+ const avgMs = answered.length > 0+ ? Math.round(answered.reduce((s, q) => s + q.responseMs, 0) / answered.length)+ : 0;+ subtitle = `${accuracyPct}% accuracy · ${(avgMs / 1000).toFixed(1)}s avg`;+ }- const drillScoreColor = result.score >= 80 ? 'text-port-success' :- result.score >= 50 ? 'text-port-warning' : 'text-port-error';+ const drillScoreColor = (result.score || 0) >= 80 ? 'text-port-success' :+ (result.score || 0) >= 50 ? 'text-port-warning' : 'text-port-error';return (- <div key={i} className="flex items-center justify-between">- <div>- <span className="text-white text-sm">{DRILL_LABELS[result.type] || result.type}</span>- <span className="text-gray-500 text-xs ml-2">- {accuracyPct}% accuracy · {(avgMs / 1000).toFixed(1)}s avg- </span>- </div>- <span className={`font-mono font-medium ${drillScoreColor}`}>- {result.score}- </span>+ <div key={i}>+ <button+ onClick={() => setExpandedDrill(isExpanded ? null : i)}+ className="w-full flex items-center justify-between hover:bg-port-bg/50 rounded px-1 py-1 transition-colors"+ >+ <div className="text-left">+ <span className="text-white text-sm">{DRILL_LABELS[result.type] || result.type}</span>+ <span className="text-gray-500 text-xs ml-2">{subtitle}</span>+ </div>+ <div className="flex items-center gap-2">+ <span className={`font-mono font-medium ${drillScoreColor}`}>+ {result.score || 0}+ </span>+ {isLlm && (isExpanded ? <ChevronUp size={14} className="text-gray-500" /> : <ChevronDown size={14} className="text-gray-500" />)}+ </div>+ </button>++ {/* LLM Feedback Expansion */}+ {isLlm && isExpanded && result.evaluation && (+ <div className="mt-2 ml-2 space-y-2">+ {(result.responses || []).map((r, ri) => {+ const score = r.llmScore ?? result.evaluation?.scores?.[ri]?.score;+ const feedback = r.llmFeedback || result.evaluation?.scores?.[ri]?.feedback;+ const sc = (score || 0) >= 80 ? 'text-port-success' : (score || 0) >= 50 ? 'text-port-warning' : 'text-port-error';+ return (+ <div key={ri} className="bg-port-bg border border-port-border rounded p-3 text-sm">+ <div className="flex justify-between mb-1">+ <span className="text-gray-400 text-xs">Response {ri + 1}</span>+ {score != null && <span className={`font-mono text-xs ${sc}`}>{score}</span>}+ </div>+ <p className="text-white text-xs mb-1">{r.response || r.items?.join(', ') || r.answers?.join(', ') || '—'}</p>+ {feedback && <p className="text-gray-500 text-xs italic">{feedback}</p>}+ </div>+ );+ })}+ {result.evaluation?.summary && (+ <p className="text-gray-400 text-xs italic px-1">{result.evaluation.summary}</p>+ )}+ </div>+ )}</div>);})}diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsxindex d204b18fb5..fb77b3a9c2 100644--- a/client/src/components/meatspace/tabs/PostTab.jsx+++ b/client/src/components/meatspace/tabs/PostTab.jsx@@ -3,10 +3,13 @@ import { getPostConfig, getPostSessions } from '../../../services/api';import { usePostSession } from '../../../hooks/usePostSession';import PostSessionLauncher from '../post/PostSessionLauncher';import PostDrillRunner from '../post/PostDrillRunner';+import PostLlmDrillRunner from '../post/PostLlmDrillRunner';import PostSessionResults from '../post/PostSessionResults';import PostHistory from '../post/PostHistory';import PostDrillConfig from '../post/PostDrillConfig';+const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay'];+export default function PostTab() {const [view, setView] = useState('launcher');const [config, setConfig] = useState(null);@@ -76,8 +79,21 @@ export default function PostTab() {}}, [session.state, session.nextDrill]);+ const isLlmDrill = session.currentDrill && LLM_DRILL_TYPES.includes(session.currentDrill.type);+switch (view) {case 'running':+ if (isLlmDrill) {+ return (+ <PostLlmDrillRunner+ drill={session.currentDrill}+ timeLimitSec={session.currentDrill.timeLimitSec}+ drillIndex={session.currentDrillIndex}+ drillCount={session.drillCount}+ onComplete={session.completeLlmDrill}+ />+ );+ }return (<PostDrillRunnersession={session}diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex ffc40c6cdd..f681e61c14 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -1,7 +1,9 @@import { useState, useCallback, useRef } from 'react';-import { generatePostDrill, submitPostSession } from '../services/api';+import { generatePostDrill, submitPostSession, scorePostLlmDrill } from '../services/api';import toast from 'react-hot-toast';+const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay'];+// States: idle → loading → drilling → between-drills → complete → saving → savedconst STATES = {IDLE: 'idle',@@ -40,7 +42,7 @@ export function usePostSession() {setSavedSession(null);const first = drillConfigs[0];- const drill = await generatePostDrill(first.type, first.config).catch(err => {+ const drill = await generatePostDrill(first.type, first.config, first.providerId, first.model).catch(err => {toast.error(`Failed to generate drill: ${err.message}`);setState(STATES.IDLE);return null;@@ -141,7 +143,7 @@ export function usePostSession() {setState(STATES.LOADING);const next = drills[nextIndex];- const drill = await generatePostDrill(next.type, next.config).catch(err => {+ const drill = await generatePostDrill(next.type, next.config, next.providerId, next.model).catch(err => {toast.error(`Failed to generate drill: ${err.message}`);setState(STATES.IDLE);return null;@@ -173,11 +175,52 @@ export function usePostSession() {finishDrillRef.current(finalAnswers);}, [state, currentDrill, currentQuestionIndex, answers]);+ const completeLlmDrill = useCallback(async (drillResult) => {+ const isLlm = LLM_DRILL_TYPES.includes(drillResult.type);+ let scoredResult = drillResult;++ if (isLlm && drillResult.responses?.length > 0) {+ setState(STATES.LOADING);+ const drillConfig = drills[currentDrillIndex];+ const timeLimitMs = (drillConfig?.timeLimitSec || 120) * 1000;+ const scoreResult = await scorePostLlmDrill(+ drillResult.type, drillResult.drillData, drillResult.responses,+ timeLimitMs, drillConfig?.providerId, drillConfig?.model+ ).catch(err => {+ toast.error(`LLM scoring failed: ${err.message}`);+ return null;+ });++ if (scoreResult) {+ scoredResult = {+ ...drillResult,+ score: scoreResult.score,+ responses: scoreResult.questions || drillResult.responses,+ evaluation: scoreResult.evaluation+ };+ } else {+ scoredResult = { ...drillResult, score: 0 };+ }+ }++ const newResults = [...drillResults, scoredResult];+ setDrillResults(newResults);++ if (currentDrillIndex + 1 < drills.length) {+ setState(STATES.BETWEEN_DRILLS);+ } else {+ const avgScore = Math.round(newResults.reduce((s, r) => s + (r.score || 0), 0) / newResults.length);+ setSessionScore(avgScore);+ setState(STATES.COMPLETE);+ }+ }, [drillResults, currentDrillIndex, drills]);+const saveSession = useCallback(async (tags = {}) => {setState(STATES.SAVING);+ const modules = [...new Set(drillResults.map(r => r.module))];const session = await submitPostSession({cadence: 'daily',- modules: ['mental-math'],+ modules,tasks: drillResults,tags}).catch(err => {@@ -219,6 +262,7 @@ export function usePostSession() {skipQuestion,nextDrill,timeExpired,+ completeLlmDrill,saveSession,reset};diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 9a954eb59d..ff6f782e66 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1487,10 +1487,15 @@ export const submitPostSession = (data) => request('/meatspace/post/sessions', {body: JSON.stringify(data)});export const getPostStats = (days) => request(`/meatspace/post/stats${days != null ? `?days=${days}` : ''}`);-export const generatePostDrill = (type, config = {}) => request('/meatspace/post/drill', {+export const generatePostDrill = (type, config = {}, providerId, model) => request('/meatspace/post/drill', {method: 'POST',- body: JSON.stringify({ type, config })+ body: JSON.stringify({ type, config, ...(providerId && { providerId }), ...(model && { model }) })});+export const scorePostLlmDrill = (type, drillData, responses, timeLimitMs, providerId, model) =>+ request('/meatspace/post/score-llm', {+ method: 'POST',+ body: JSON.stringify({ type, drillData, responses, timeLimitMs, ...(providerId && { providerId }), ...(model && { model }) })+ });// JIRAexport const getJiraInstances = () => request('/jira/instances');diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 1cebbd35d9..50c2bd2faa 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -7,7 +7,7 @@ import { z } from 'zod';// Tags for session conditions (sleep, caffeine, stress, etc.)export const postTagsSchema = z.record(z.string().max(200));-// Individual question result+// Individual question result (math drills)// expected and correct are optional — the server recomputes both via scoreDrillconst questionResultSchema = z.object({prompt: z.string(),@@ -17,8 +17,21 @@ const questionResultSchema = z.object({responseMs: z.number().min(0)});+// LLM drill response (text-based)+const llmResponseSchema = z.object({+ prompt: z.string().optional(),+ response: z.string().optional(),+ answers: z.array(z.string()).optional(),+ items: z.array(z.string()).optional(),+ responseMs: z.number().min(0).optional().default(0),+ llmScore: z.number().min(0).max(100).optional(),+ llmFeedback: z.string().optional()+});+// Drill type configuration-const DRILL_TYPES = ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'];+const MATH_DRILL_TYPES = ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'];+const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay'];+const DRILL_TYPES = [...MATH_DRILL_TYPES, ...LLM_DRILL_TYPES];const drillTypeConfigSchema = z.object({enabled: z.boolean().optional(),@@ -40,7 +53,9 @@ const taskResultSchema = z.object({module: z.string(),type: z.enum(DRILL_TYPES),config: drillTypeConfigSchema.optional().default({}),- questions: z.array(questionResultSchema),+ questions: z.array(questionResultSchema).optional().default([]),+ responses: z.array(llmResponseSchema).optional().default([]),+ drillData: z.any().optional(),score: z.number().min(0).max(100).optional(),totalMs: z.number().min(0)});@@ -53,11 +68,26 @@ export const postSessionSubmitSchema = z.object({tags: postTagsSchema.optional().default({})});+// LLM drill type configuration+const llmDrillTypeConfigSchema = z.object({+ enabled: z.boolean().optional(),+ count: z.number().int().min(1).max(20).optional(),+ timeLimitSec: z.number().int().min(10).max(600).optional(),+ providerId: z.string().optional(),+ model: z.string().optional()+});+// Config update (partial)export const postConfigUpdateSchema = z.object({mentalMath: z.object({enabled: z.boolean().optional(),- drillTypes: z.record(z.enum(DRILL_TYPES), drillTypeConfigSchema).optional()+ drillTypes: z.record(z.enum(MATH_DRILL_TYPES), drillTypeConfigSchema).optional()+ }).optional(),+ llmDrills: z.object({+ enabled: z.boolean().optional(),+ providerId: z.string().optional(),+ model: z.string().optional(),+ drillTypes: z.record(z.enum(LLM_DRILL_TYPES), llmDrillTypeConfigSchema).optional()}).optional(),sessionModules: z.array(z.string()).optional(),scoring: z.object({@@ -67,6 +97,20 @@ export const postConfigUpdateSchema = z.object({// Drill generation requestexport const postDrillRequestSchema = z.object({- type: z.enum(['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation']),- config: drillTypeConfigSchema.optional().default({})+ type: z.enum(DRILL_TYPES),+ config: drillTypeConfigSchema.optional().default({}),+ providerId: z.string().optional(),+ model: z.string().optional()});++// LLM drill scoring request+export const postLlmScoreRequestSchema = z.object({+ type: z.enum(LLM_DRILL_TYPES),+ drillData: z.any(),+ responses: z.array(llmResponseSchema),+ timeLimitMs: z.number().min(1000),+ providerId: z.string().optional(),+ model: z.string().optional()+});++export { LLM_DRILL_TYPES, MATH_DRILL_TYPES };diff --git a/server/routes/meatspace.js b/server/routes/meatspace.jsindex 483c2368f8..db17d351d0 100644--- a/server/routes/meatspace.js+++ b/server/routes/meatspace.js@@ -18,11 +18,14 @@ import {postSessionSubmitSchema,postConfigUpdateSchema,postDrillRequestSchema,+ postLlmScoreRequestSchema,+ LLM_DRILL_TYPES,} from '../lib/postValidation.js';import * as meatspaceService from '../services/meatspace.js';import * as alcoholService from '../services/meatspaceAlcohol.js';import * as healthService from '../services/meatspaceHealth.js';import * as postService from '../services/meatspacePost.js';+import { generateLlmDrill, scoreLlmDrill } from '../services/meatspacePostLlm.js';const router = Router();@@ -384,11 +387,20 @@ router.get('/post/stats', asyncHandler(async (req, res) => {/*** POST /api/meatspace/post/drill- * Generate a drill with questions and expected answers for client-side feedback.- * Server-side scoring recomputes expected answers from the prompt when possible.+ * Generate a drill with questions and expected answers.+ * Supports both math drills (sync) and LLM drills (async, requires AI provider).*/router.post('/post/drill', asyncHandler(async (req, res) => {const data = validateRequest(postDrillRequestSchema, req.body);++ if (LLM_DRILL_TYPES.includes(data.type)) {+ const drill = await generateLlmDrill(data.type, data.config, data.providerId, data.model);+ if (!drill) {+ throw new ServerError('Failed to generate LLM drill', { status: 500, code: 'LLM_DRILL_FAILED' });+ }+ return res.json(drill);+ }+const drill = postService.generateDrill(data.type, data.config);if (!drill) {throw new ServerError('Unknown drill type', { status: 400, code: 'INVALID_DRILL_TYPE' });@@ -396,4 +408,17 @@ router.post('/post/drill', asyncHandler(async (req, res) => {res.json(drill);}));+/**+ * POST /api/meatspace/post/score-llm+ * Score an LLM drill's responses using AI evaluation.+ */+router.post('/post/score-llm', asyncHandler(async (req, res) => {+ const data = validateRequest(postLlmScoreRequestSchema, req.body);+ const result = await scoreLlmDrill(+ data.type, data.drillData, data.responses,+ data.timeLimitMs, data.providerId, data.model+ );+ res.json(result);+}));+export default router;diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 3df4a6f312..6c0496ba0d 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -9,6 +9,7 @@ import { writeFile } from 'fs/promises';import { join } from 'path';import { randomUUID } from 'crypto';import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';+import { LLM_DRILL_TYPES } from '../lib/postValidation.js';const MEATSPACE_DIR = PATHS.meatspace;const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');@@ -25,8 +26,20 @@ const DEFAULT_CONFIG = {'estimation': { enabled: true, count: 5, tolerancePct: 10, timeLimitSec: 120 }}},+ llmDrills: {+ enabled: true,+ providerId: null,+ model: null,+ drillTypes: {+ 'word-association': { enabled: true, count: 5, timeLimitSec: 120 },+ 'story-recall': { enabled: true, count: 3, timeLimitSec: 180 },+ 'verbal-fluency': { enabled: true, count: 3, timeLimitSec: 60 },+ 'wit-comeback': { enabled: true, count: 5, timeLimitSec: 120 },+ 'pun-wordplay': { enabled: true, count: 5, timeLimitSec: 120 }+ }+ },sessionModules: ['mental-math'],- scoring: { weights: { 'mental-math': 1.0 } }+ scoring: { weights: { 'mental-math': 1.0, 'llm-drills': 1.0 } }};async function ensureMeatspaceDir() {@@ -81,11 +94,17 @@ export async function submitPostSession(sessionData) {const data = await loadSessions();const now = new Date().toISOString();- // Strip client-provided score/correct and recompute server-side+ // Strip client-provided score/correct and recompute server-side (math drills only)const rawTasks = Array.isArray(sessionData.tasks) ? sessionData.tasks : [];const rescoredTasks = rawTasks.map(t => {const { score: _score, correct: _correct, ...rest } = t || {};- // Strip correct from individual questions too++ // LLM drills: score was already computed server-side via /post/score-llm+ if (LLM_DRILL_TYPES.includes(rest.type)) {+ return { ...rest, score: t.score || 0 };+ }++ // Math drills: strip correct from individual questions and rescoreconst sanitizedQuestions = (rest.questions || []).map(q => {const { correct: _qCorrect, ...qRest } = q;return qRest;diff --git a/server/services/meatspacePostLlm.js b/server/services/meatspacePostLlm.jsnew file mode 100644index 0000000000..bc01df12e5--- /dev/null+++ b/server/services/meatspacePostLlm.js@@ -0,0 +1,355 @@+/**+ * MeatSpace POST - LLM-Powered Drills+ *+ * Generates and scores cognitive drills that use an AI provider:+ * - word-association: lateral thinking via word associations+ * - story-recall: working memory via paragraph recall+ * - verbal-fluency: category fluency (name items in a category)+ * - wit-comeback: verbal agility via witty responses+ * - pun-wordplay: creative wordplay and pun generation+ */++import { spawn } from 'child_process';+import { getActiveProvider, getProviderById } from './providers.js';++export const LLM_DRILL_TYPES = [+ 'word-association',+ 'story-recall',+ 'verbal-fluency',+ 'wit-comeback',+ 'pun-wordplay'+];++// ─────────────────────────────────────────────────────────────────────────────+// AI CALLER (mirrors brain.js pattern)+// ─────────────────────────────────────────────────────────────────────────────++async function callAI(prompt, providerId, model) {+ const provider = providerId+ ? await getProviderById(providerId)+ : await getActiveProvider();++ if (!provider?.enabled) {+ throw new Error('No AI provider available for POST drills');+ }++ const selectedModel = model || provider.defaultModel;+ console.log(`🧪 POST LLM drill: ${provider.id} / ${selectedModel}`);++ if (provider.type === 'cli') {+ return new Promise((resolve, reject) => {+ const args = [...(provider.args || [])];+ if (provider.headlessArgs?.length) args.push(...provider.headlessArgs);+ if (selectedModel) args.push('--model', selectedModel);+ args.push(prompt);+ let output = '';++ const child = spawn(provider.command, args, {+ env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),+ shell: false,+ windowsHide: true+ });++ child.stdout.on('data', d => { output += d.toString(); });+ child.stderr.on('data', d => { output += d.toString(); });+ child.on('close', code => code === 0 ? resolve(output) : reject(new Error(`CLI exited with code ${code}`)));+ child.on('error', reject);++ setTimeout(() => {+ child.kill();+ reject(new Error('POST AI request timed out'));+ }, provider.timeout || 120000);+ });+ }++ if (provider.type === 'api') {+ const headers = { 'Content-Type': 'application/json' };+ if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;++ const response = await fetch(`${provider.endpoint}/chat/completions`, {+ method: 'POST',+ headers,+ body: JSON.stringify({+ model: selectedModel,+ messages: [{ role: 'user', content: prompt }],+ temperature: 0.7+ })+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`AI API error: ${response.status} - ${errorText}`);+ }++ const data = await response.json();+ return data.choices?.[0]?.message?.content || '';+ }++ throw new Error(`Unsupported provider type: ${provider.type}`);+}++function parseJsonFromAI(content) {+ if (!content || typeof content !== 'string') throw new Error('Empty AI response');+ let jsonStr = content.trim();+ const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);+ if (jsonMatch) jsonStr = jsonMatch[1].trim();+ return JSON.parse(jsonStr);+}++// ─────────────────────────────────────────────────────────────────────────────+// DRILL GENERATORS+// ─────────────────────────────────────────────────────────────────────────────++export async function generateWordAssociation(config, providerId, model) {+ const count = config.count || 5;+ const prompt = `Generate ${count} word association prompts for a cognitive training exercise.+For each prompt, provide a single word or short concept that the user will free-associate with.+Choose diverse, interesting words that encourage creative lateral thinking.+Mix concrete nouns, abstract concepts, and evocative words.++Return ONLY valid JSON (no markdown, no explanation):+{"questions":[{"prompt":"the word","hints":"optional category hint"}]}++Example: {"questions":[{"prompt":"cathedral","hints":"architecture/spirituality"}]}`;++ const response = await callAI(prompt, providerId, model);+ const data = parseJsonFromAI(response);+ return {+ type: 'word-association',+ config: { count },+ questions: (data.questions || []).slice(0, count).map(q => ({+ prompt: q.prompt,+ hints: q.hints || ''+ }))+ };+}++export async function generateStoryRecall(config, providerId, model) {+ const count = config.count || 3;+ const prompt = `Generate ${count} short story recall exercises for cognitive training.+Each exercise has a short paragraph (2-4 sentences) containing specific details: names, numbers, places, colors, dates.+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"}]}]}++Make paragraphs vivid and varied. Include specific numbers, proper nouns, and concrete details.`;++ const response = await callAI(prompt, providerId, model);+ const data = parseJsonFromAI(response);+ return {+ type: 'story-recall',+ config: { count },+ exercises: (data.exercises || []).slice(0, count)+ };+}++export async function generateVerbalFluency(config, providerId, model) {+ const count = config.count || 3;+ const prompt = `Generate ${count} verbal fluency category prompts for cognitive training.+Each prompt is a category where the user must name as many items as possible within a time limit.+Choose categories with many valid answers (at least 20+).+Mix common categories with more creative/specific ones.++Return ONLY valid JSON:+{"categories":[{"category":"Animals","minExpected":15,"examples":["dog","cat","elephant"]}]}++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);+ return {+ type: 'verbal-fluency',+ config: { count },+ categories: (data.categories || []).slice(0, count)+ };+}++export async function generateWitComeback(config, providerId, model) {+ const count = config.count || 5;+ const prompt = `Generate ${count} witty comeback/response scenarios for verbal agility training.+Each scenario presents a situation, statement, or setup that the user must respond to with wit and humor.+Mix scenarios: awkward social situations, playful roasts, clever observations, absurd hypotheticals.++Return ONLY valid JSON:+{"scenarios":[{"setup":"The scenario or statement","context":"brief context about the situation","difficulty":"easy|medium|hard"}]}++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);+ return {+ type: 'wit-comeback',+ config: { count },+ scenarios: (data.scenarios || []).slice(0, count)+ };+}++export async function generatePunWordplay(config, providerId, model) {+ const count = config.count || 5;+ const prompt = `Generate ${count} pun and wordplay challenges for creative language training.+Each challenge gives the user a topic, theme, or constraint and asks them to create a pun, wordplay, or clever phrase.+Mix challenge types: create a pun about a topic, complete a punny sentence, name a punny business, write a wordplay headline.++Return ONLY valid JSON:+{"challenges":[{"type":"pun-topic|complete-sentence|punny-name|wordplay-headline","prompt":"The challenge description","topic":"the subject area","example":"an example of a good answer"}]}++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);+ return {+ type: 'pun-wordplay',+ config: { count },+ challenges: (data.challenges || []).slice(0, count)+ };+}++export async function generateLlmDrill(type, config = {}, providerId, model) {+ switch (type) {+ case 'word-association':+ return generateWordAssociation(config, providerId, model);+ case 'story-recall':+ return generateStoryRecall(config, providerId, model);+ case 'verbal-fluency':+ return generateVerbalFluency(config, providerId, model);+ case 'wit-comeback':+ return generateWitComeback(config, providerId, model);+ case 'pun-wordplay':+ return generatePunWordplay(config, providerId, model);+ default:+ return null;+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// LLM SCORING+// ─────────────────────────────────────────────────────────────────────────────++export async function scoreLlmDrill(type, drillData, userResponses, timeLimitMs, providerId, model) {+ const avgResponseMs = userResponses.length > 0+ ? userResponses.reduce((sum, r) => sum + (r.responseMs || 0), 0) / userResponses.length+ : timeLimitMs;+ const speedBonus = Math.max(0, 1 - avgResponseMs / timeLimitMs);++ let scorePrompt;++ switch (type) {+ case 'word-association':+ scorePrompt = buildWordAssociationScorePrompt(drillData, userResponses);+ break;+ case 'story-recall':+ scorePrompt = buildStoryRecallScorePrompt(drillData, userResponses);+ break;+ case 'verbal-fluency':+ scorePrompt = buildVerbalFluencyScorePrompt(drillData, userResponses);+ break;+ case 'wit-comeback':+ scorePrompt = buildWitComebackScorePrompt(drillData, userResponses);+ break;+ case 'pun-wordplay':+ scorePrompt = buildPunWordplayScorePrompt(drillData, userResponses);+ break;+ default:+ return { score: 0, evaluation: null, questions: userResponses };+ }++ const response = await callAI(scorePrompt, providerId, model);+ const evaluation = parseJsonFromAI(response);++ // Combine LLM quality score (80%) with speed bonus (20%)+ const qualityScore = Math.min(100, Math.max(0, evaluation.overallScore || 0));+ const finalScore = Math.round(qualityScore * 0.8 + speedBonus * 0.2 * 100);++ return {+ score: Math.min(100, Math.max(0, finalScore)),+ evaluation,+ questions: userResponses.map((r, i) => ({+ ...r,+ llmScore: evaluation.scores?.[i]?.score ?? null,+ llmFeedback: evaluation.scores?.[i]?.feedback ?? ''+ }))+ };+}++function buildWordAssociationScorePrompt(drillData, responses) {+ const pairs = responses.map((r, i) => {+ const q = drillData.questions?.[i];+ return `Word: "${q?.prompt}" -> User associations: "${r.response || '(no response)'}"`;+ }).join('\n');++ return `Score these word association responses for creativity, breadth, and relevance.+Rate each response 0-100 and give brief feedback.++${pairs}++Return ONLY valid JSON:+{"overallScore":75,"scores":[{"score":80,"feedback":"Good creative connections"}],"summary":"Overall assessment"}`;+}++function buildStoryRecallScorePrompt(drillData, responses) {+ const items = responses.map((r, i) => {+ const exercise = drillData.exercises?.[i];+ const qas = (exercise?.questions || []).map((q, qi) => {+ const userAnswer = r.answers?.[qi] || '(no answer)';+ return ` Q: ${q.question} | Correct: ${q.answer} | User: ${userAnswer}`;+ }).join('\n');+ return `Story ${i + 1}: "${exercise?.paragraph}"\n${qas}`;+ }).join('\n\n');++ return `Score these story recall responses. For each question, determine if the user's answer matches the correct answer (allow minor spelling/phrasing differences).+Rate each exercise 0-100 based on accuracy.++${items}++Return ONLY valid JSON:+{"overallScore":75,"scores":[{"score":80,"feedback":"Recalled 3 of 4 details correctly"}],"summary":"Overall memory assessment"}`;+}++function buildVerbalFluencyScorePrompt(drillData, responses) {+ const items = responses.map((r, i) => {+ const cat = drillData.categories?.[i];+ return `Category: "${cat?.category}" (expected ~${cat?.minExpected})\nUser items: ${(r.items || []).join(', ') || '(none)'}`;+ }).join('\n\n');++ return `Score these verbal fluency responses. For each category:+1. Count valid, unique items (remove duplicates and invalid entries)+2. Compare count to minExpected+3. Note any particularly creative or unusual valid answers++${items}++Return ONLY valid JSON:+{"overallScore":75,"scores":[{"score":80,"feedback":"Named 12 valid animals, good variety","validCount":12,"invalidItems":["rock"]}],"summary":"Overall fluency assessment"}`;+}++function buildWitComebackScorePrompt(drillData, responses) {+ const items = responses.map((r, i) => {+ const scenario = drillData.scenarios?.[i];+ return `Setup: "${scenario?.setup}"\nContext: ${scenario?.context || 'none'}\nUser's response: "${r.response || '(no response)'}"`;+ }).join('\n\n');++ return `Score these witty comeback responses on: humor (40%), cleverness (30%), relevance to setup (30%).+Rate each 0-100 and give brief feedback.++${items}++Return ONLY valid JSON:+{"overallScore":75,"scores":[{"score":85,"feedback":"Sharp and well-timed"}],"summary":"Overall wit assessment"}`;+}++function buildPunWordplayScorePrompt(drillData, responses) {+ const items = responses.map((r, i) => {+ const challenge = drillData.challenges?.[i];+ return `Challenge: "${challenge?.prompt}" (topic: ${challenge?.topic})\nUser's answer: "${r.response || '(no response)'}"`;+ }).join('\n\n');++ return `Score these pun/wordplay responses on: cleverness of wordplay (40%), humor (30%), relevance to topic (30%).+Rate each 0-100 and give brief feedback on the quality of the pun or wordplay.++${items}++Return ONLY valid JSON:+{"overallScore":75,"scores":[{"score":90,"feedback":"Excellent double meaning"}],"summary":"Overall wordplay assessment"}`;+}