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): add wordplay training module with 4 game modes
Adam Eivy1cad9ce27db9
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 5277ce3e25..5a3cce6332 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -62,7 +62,8 @@ import {Inbox,RefreshCw,Dog,- FilePen+ FilePen,+ MessageCircle} from 'lucide-react';/* global __APP_VERSION__ */import Logo from './Logo';@@ -208,6 +209,7 @@ const navItems = [{ to: '/post/history', label: 'History', icon: History },{ to: '/post/launcher', label: 'Launcher', icon: Play },{ to: '/post/memory', label: 'Memory', icon: Brain },+ { to: '/post/wordplay', label: 'Wordplay', icon: MessageCircle },]},{ to: '/review', label: 'Review Hub', icon: ClipboardList, single: true },diff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.jsxindex 8275845508..e317035cae 100644--- a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx@@ -1,19 +1,8 @@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',- 'story-recall': 'Story Recall',- 'verbal-fluency': 'Verbal Fluency',- 'wit-comeback': 'Wit & Comeback',- 'pun-wordplay': 'Pun & Wordplay',- 'what-if': 'What If?',- 'alternative-uses': 'Alternative Uses',- 'story-prompt': 'Story Prompt',- 'invention-pitch': 'Invention Pitch',- 'reframe': 'Reframe',-};+import { DRILL_LABELS } from './constants';+import { CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI } from './WordplayDrillUI';export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drillCount, onComplete, isTraining, providerId, model }) {const [questionIndex, setQuestionIndex] = useState(0);@@ -111,14 +100,14 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dranswers: items.length > 0 ? items : [inputValue.trim()],responseMs};- } else if (drillType === 'verbal-fluency') {+ } else if (drillType === 'verbal-fluency' || drillType === 'compound-chain' || drillType === 'alternative-uses') {responseObj = {items: items,responseMs};} else {responseObj = {- prompt: currentPrompt?.prompt || currentPrompt?.setup || currentPrompt?.category || '',+ prompt: currentPrompt?.prompt || currentPrompt?.setup || currentPrompt?.category || currentPrompt?.rootWord || currentPrompt?.word || currentPrompt?.idiom || '',response: inputValue.trim(),responseMs};@@ -351,6 +340,59 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr/>)}+ {drillType === 'compound-chain' && (+ <CompoundChainUI+ challenge={currentPrompt}+ items={items}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onAddItem={handleAddItem}+ onRemoveItem={handleRemoveItem}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ />+ )}++ {drillType === 'bridge-word' && (+ <BridgeWordUI+ puzzle={currentPrompt}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ />+ )}++ {drillType === 'double-meaning' && (+ <DoubleMeaningUI+ challenge={currentPrompt}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ TextInput={TextInput}+ />+ )}++ {drillType === 'idiom-twist' && (+ <IdiomTwistUI+ challenge={currentPrompt}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ TextInput={TextInput}+ />+ )}+{drillType === 'what-if' && (<ImaginationUIlabel="Imagine this scenario"@@ -440,6 +482,10 @@ function getPrompts(drill) {case 'verbal-fluency': return drill.categories || [];case 'wit-comeback': return drill.scenarios || [];case 'pun-wordplay': return drill.challenges || [];+ case 'compound-chain': return drill.challenges || [];+ case 'bridge-word': return drill.puzzles || [];+ case 'double-meaning': return drill.challenges || [];+ case 'idiom-twist': return drill.challenges || [];case 'what-if': return drill.scenarios || [];case 'alternative-uses': return drill.objects || [];case 'story-prompt': return drill.prompts || [];diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex 326add1c32..827fe0eec5 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -1,28 +1,7 @@import { useState, useEffect } from 'react';import { Zap, History, Settings, Play, Brain, BookOpen, Dumbbell, Timer } from 'lucide-react';import { getProviders } from '../../../services/api';-import { DOMAINS, DRILL_TO_DOMAIN } from './constants';--const DRILL_LABELS = {- 'doubling-chain': 'Doubling Chain',- 'serial-subtraction': 'Serial Subtraction',- 'multiplication': 'Multiplication',- 'powers': 'Powers',- 'estimation': 'Estimation',- 'word-association': 'Word Association',- 'story-recall': 'Story Recall',- 'verbal-fluency': 'Verbal Fluency',- 'wit-comeback': 'Wit & Comeback',- 'pun-wordplay': 'Pun & Wordplay',- 'memory-fill-blank': 'Memory Fill Blank',- 'memory-sequence': 'Memory Sequence',- 'memory-element-flash': 'Element Flash',- 'what-if': 'What If?',- 'alternative-uses': 'Alternative Uses',- 'story-prompt': 'Story Prompt',- 'invention-pitch': 'Invention Pitch',- 'reframe': 'Reframe',-};+import { DOMAINS, DRILL_TO_DOMAIN, DRILL_LABELS } from './constants';export default function PostSessionLauncher({ config, recentSessions, onStart, onViewHistory, onViewConfig, onViewMemory }) {const [tags, setTags] = useState({ sleep: '', caffeine: '', stress: '' });diff --git a/client/src/components/meatspace/post/WordplayDrillUI.jsx b/client/src/components/meatspace/post/WordplayDrillUI.jsxnew file mode 100644index 0000000000..09f1302d99--- /dev/null+++ b/client/src/components/meatspace/post/WordplayDrillUI.jsx@@ -0,0 +1,209 @@+import { getDifficultyColor } from './constants';++export 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>Challenge {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>+ );+}++export function DifficultyBadge({ difficulty }) {+ if (!difficulty) return null;+ return (+ <span className={`inline-block px-2 py-0.5 rounded text-xs ${getDifficultyColor(difficulty)}`}>{difficulty}</span>+ );+}++export function CompoundChainUI({ challenge, 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">List compound words or phrases using:</div>+ <div className="text-4xl font-bold text-white">{challenge?.rootWord}</div>+ <div className="text-sm text-gray-500 mt-2">+ {challenge?.position === 'prefix' ? 'Starts with this word' : challenge?.position === 'suffix' ? 'Ends with this word' : 'Either direction'}+ {challenge?.minExpected && ` · Target: ${challenge.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 a compound word 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="text-sm text-gray-400 mb-2">Compounds ({items.length})</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} compounds+ </button>+ <ProgressBar index={questionIndex} total={totalPrompts} />+ </>+ );+}++export function BridgeWordUI({ puzzle, inputValue, setInputValue, onSubmit, inputRef, questionIndex, totalPrompts }) {+ return (+ <>+ <div className="text-center py-4">+ <div className="text-sm text-gray-500 mb-3">Find the word that fills all blanks:</div>+ <div className="flex flex-col items-center gap-2">+ {(puzzle?.clues || []).map((clue, i) => (+ <span key={i} className="px-4 py-2 bg-purple-500/20 text-purple-300 rounded-lg text-lg font-mono">{clue}</span>+ ))}+ </div>+ {puzzle?.hint && <div className="text-sm text-gray-500 mt-3">Hint: {puzzle.hint}</div>}+ {puzzle?.difficulty && <DifficultyBadge difficulty={puzzle.difficulty} />}+ </div>+ <form onSubmit={onSubmit} className="space-y-3">+ <input+ ref={inputRef}+ type="text"+ value={inputValue}+ onChange={e => setInputValue(e.target.value)}+ placeholder="The bridge word is..."+ autoFocus+ className="w-full bg-port-bg border border-port-border rounded-lg px-4 py-3 text-white text-center text-lg placeholder-gray-600 focus:border-port-accent focus:outline-none"+ />+ <button+ type="submit"+ disabled={!inputValue.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"+ >+ Submit+ </button>+ </form>+ <ProgressBar index={questionIndex} total={totalPrompts} />+ </>+ );+}++export function DoubleMeaningUI({ challenge, inputValue, setInputValue, onSubmit, inputRef, questionIndex, totalPrompts, TextInput }) {+ const input = TextInput ? (+ <TextInput+ inputRef={inputRef}+ value={inputValue}+ onChange={setInputValue}+ onSubmit={onSubmit}+ placeholder="Write a sentence using both meanings..."+ buttonLabel="Next"+ />+ ) : (+ <form onSubmit={onSubmit} className="space-y-3">+ <textarea+ ref={inputRef}+ value={inputValue}+ onChange={e => setInputValue(e.target.value)}+ placeholder="Write a sentence using both meanings..."+ 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={!inputValue.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"+ >+ Submit+ </button>+ </form>+ );++ return (+ <>+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center">+ <div className="text-sm text-gray-500 mb-2">Use both meanings in one sentence:</div>+ <div className="text-3xl font-bold text-white mb-3">{challenge?.word}</div>+ <div className="flex flex-wrap justify-center gap-2">+ {(challenge?.meanings || []).map((m, i) => (+ <span key={i} className="px-3 py-1 bg-amber-500/20 text-amber-400 rounded-lg text-sm">{m}</span>+ ))}+ </div>+ {challenge?.difficulty && <div className="mt-3"><DifficultyBadge difficulty={challenge.difficulty} /></div>}+ </div>+ {input}+ <ProgressBar index={questionIndex} total={totalPrompts} />+ </>+ );+}++export function IdiomTwistUI({ challenge, inputValue, setInputValue, onSubmit, inputRef, questionIndex, totalPrompts, TextInput }) {+ const input = TextInput ? (+ <TextInput+ inputRef={inputRef}+ value={inputValue}+ onChange={setInputValue}+ onSubmit={onSubmit}+ placeholder="Your twisted idiom..."+ buttonLabel="Next"+ />+ ) : (+ <form onSubmit={onSubmit} className="space-y-3">+ <textarea+ ref={inputRef}+ value={inputValue}+ onChange={e => setInputValue(e.target.value)}+ placeholder="Your twisted idiom..."+ 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={!inputValue.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"+ >+ Submit+ </button>+ </form>+ );++ 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">Adapt this idiom to a new domain:</div>+ <p className="text-white text-lg leading-relaxed italic mb-3">"{challenge?.idiom}"</p>+ <div className="flex items-center justify-center gap-2">+ <span className="text-gray-500">New domain:</span>+ <span className="px-3 py-1 bg-cyan-500/20 text-cyan-400 rounded-lg font-medium">{challenge?.domain}</span>+ </div>+ {challenge?.difficulty && <div className="mt-3"><DifficultyBadge difficulty={challenge.difficulty} /></div>}+ </div>+ {input}+ <ProgressBar index={questionIndex} total={totalPrompts} />+ </>+ );+}diff --git a/client/src/components/meatspace/post/WordplayTrainer.jsx b/client/src/components/meatspace/post/WordplayTrainer.jsxnew file mode 100644index 0000000000..b3f28e6737--- /dev/null+++ b/client/src/components/meatspace/post/WordplayTrainer.jsx@@ -0,0 +1,388 @@+import { useState, useRef, useCallback } from 'react';+import { ArrowLeft, Link, Puzzle, BookOpen, Shuffle, Loader, CheckCircle, XCircle, ChevronRight } from 'lucide-react';+import { generatePostDrill, scorePostLlmDrill } from '../../../services/api';+import { CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI, ProgressBar } from './WordplayDrillUI';++const GAME_MODES = [+ {+ id: 'compound-chain',+ label: 'Compound Chain',+ icon: Link,+ color: 'text-purple-400',+ bgColor: 'bg-purple-500/20',+ description: 'List compound words using a root word',+ example: 'fire → firehouse, firewall, campfire...',+ },+ {+ id: 'bridge-word',+ label: 'Bridge Word',+ icon: Puzzle,+ color: 'text-cyan-400',+ bgColor: 'bg-cyan-500/20',+ description: 'Find the word connecting multiple phrases',+ example: 'news___, ___back, ___weight → paper',+ },+ {+ id: 'double-meaning',+ label: 'Double Meaning',+ icon: BookOpen,+ color: 'text-amber-400',+ bgColor: 'bg-amber-500/20',+ description: 'Use both meanings of a word in one sentence',+ example: 'bark: tree covering + dog sound',+ },+ {+ id: 'idiom-twist',+ label: 'Idiom Twist',+ icon: Shuffle,+ color: 'text-green-400',+ bgColor: 'bg-green-500/20',+ description: 'Adapt idioms to new domains with wordplay',+ example: '"Don\'t put all eggs in one basket" → programming',+ },+];++export default function WordplayTrainer({ onBack, config }) {+ const [selectedMode, setSelectedMode] = useState(null);+ const [drill, setDrill] = useState(null);+ const [loading, setLoading] = useState(false);+ const [questionIndex, setQuestionIndex] = useState(0);+ const [inputValue, setInputValue] = useState('');+ const [items, setItems] = useState([]);+ const [feedback, setFeedback] = useState(null);+ const [results, setResults] = useState([]);+ const inputRef = useRef(null);+ const questionStartRef = useRef(Date.now());++ const providerId = config?.llmDrills?.providerId || null;+ const model = config?.llmDrills?.model || null;++ const prompts = getPrompts(drill);+ const totalPrompts = prompts.length;+ const currentPrompt = prompts[questionIndex];++ async function startMode(modeId) {+ setSelectedMode(modeId);+ setLoading(true);+ setDrill(null);+ setQuestionIndex(0);+ setInputValue('');+ setItems([]);+ setFeedback(null);+ setResults([]);++ const generated = await generatePostDrill(modeId, { count: 5 }, providerId, model).catch(() => null);+ setLoading(false);+ if (generated) {+ setDrill(generated);+ questionStartRef.current = Date.now();+ setTimeout(() => inputRef.current?.focus(), 100);+ }+ }++ function handleBackToModes() {+ setSelectedMode(null);+ setDrill(null);+ setFeedback(null);+ setResults([]);+ }++ const handleSubmit = useCallback(async (e) => {+ e?.preventDefault();+ const responseMs = Date.now() - questionStartRef.current;++ let responseObj;+ if (selectedMode === 'compound-chain') {+ responseObj = { items, responseMs };+ } else {+ responseObj = {+ prompt: currentPrompt?.rootWord || currentPrompt?.word || currentPrompt?.idiom || '',+ response: inputValue.trim(),+ responseMs,+ };+ }++ // Score immediately+ setFeedback({ scoring: true });+ const scored = await scorePostLlmDrill(+ selectedMode, drill, [responseObj], 120000, providerId, model+ ).catch(() => null);+ const fb = scored?.evaluation?.scores?.[0] || {};+ setFeedback({+ scoring: false,+ score: fb.score ?? scored?.score ?? 0,+ feedback: fb.feedback || scored?.evaluation?.summary || 'No feedback available',+ validCount: fb.validCount,+ invalidItems: fb.invalidItems,+ });+ setResults(prev => [...prev, {+ ...responseObj,+ score: fb.score ?? scored?.score ?? 0,+ feedback: fb.feedback || '',+ }]);+ }, [inputValue, items, currentPrompt, selectedMode, drill, providerId, model]);++ const handleNext = useCallback(() => {+ setFeedback(null);+ setInputValue('');+ setItems([]);+ if (questionIndex + 1 >= totalPrompts) {+ setFeedback({ complete: true });+ } else {+ setQuestionIndex(questionIndex + 1);+ questionStartRef.current = Date.now();+ setTimeout(() => inputRef.current?.focus(), 50);+ }+ }, [questionIndex, totalPrompts]);++ function handleAddItem(e) {+ e?.preventDefault();+ const val = inputValue.trim();+ if (!val) return;+ if (!items.some(item => item.toLowerCase() === val.toLowerCase())) {+ setItems(prev => [...prev, val]);+ }+ setInputValue('');+ inputRef.current?.focus();+ }++ function handleRemoveItem(index) {+ setItems(prev => prev.filter((_, i) => i !== index));+ }++ // Mode selection screen+ if (!selectedMode) {+ return (+ <div className="max-w-2xl mx-auto space-y-6 px-4">+ <div className="flex items-center gap-3">+ <button onClick={onBack} className="p-1.5 hover:bg-port-card rounded-lg transition-colors">+ <ArrowLeft size={20} className="text-gray-400" />+ </button>+ <h2 className="text-xl font-bold text-white">Wordplay Training</h2>+ </div>+ <p className="text-gray-400 text-sm">Train verbal association, puns, and creative wordplay. Pick a game mode to start.</p>++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {GAME_MODES.map(mode => {+ const Icon = mode.icon;+ return (+ <button+ key={mode.id}+ onClick={() => startMode(mode.id)}+ className="bg-port-card border border-port-border rounded-lg p-4 text-left hover:border-port-accent transition-colors group"+ >+ <div className="flex items-center gap-3 mb-2">+ <div className={`p-2 rounded-lg ${mode.bgColor}`}>+ <Icon size={20} className={mode.color} />+ </div>+ <span className="text-white font-medium group-hover:text-port-accent transition-colors">{mode.label}</span>+ <ChevronRight size={16} className="text-gray-600 ml-auto group-hover:text-port-accent transition-colors" />+ </div>+ <p className="text-sm text-gray-400 mb-1">{mode.description}</p>+ <p className="text-xs text-gray-600 font-mono">{mode.example}</p>+ </button>+ );+ })}+ </div>+ </div>+ );+ }++ const modeInfo = GAME_MODES.find(m => m.id === selectedMode);+ const ModeIcon = modeInfo?.icon || Link;++ // Loading state+ if (loading) {+ return (+ <div className="max-w-lg mx-auto space-y-6">+ <ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />+ <div className="flex flex-col items-center gap-3 py-12">+ <Loader size={32} className={`${modeInfo?.color || 'text-purple-400'} animate-spin`} />+ <span className="text-gray-400 text-sm">Generating {modeInfo?.label} challenges...</span>+ </div>+ </div>+ );+ }++ // Complete summary+ if (feedback?.complete) {+ const avgScore = results.length > 0+ ? Math.round(results.reduce((sum, r) => sum + (r.score || 0), 0) / results.length)+ : 0;+ const scoreColor = avgScore >= 70 ? 'text-port-success' : avgScore >= 40 ? 'text-port-warning' : 'text-port-error';++ return (+ <div className="max-w-lg mx-auto space-y-6">+ <ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />+ <div className="text-center py-6">+ <div className={`text-5xl font-mono font-bold ${scoreColor}`}>{avgScore}</div>+ <div className="text-gray-400 text-sm mt-1">Average Score</div>+ </div>+ <div className="space-y-2">+ {results.map((r, i) => (+ <div key={i} className="bg-port-card border border-port-border rounded-lg p-3 flex items-center justify-between">+ <span className="text-sm text-gray-300 truncate flex-1">{r.response || (r.items || []).join(', ') || 'No response'}</span>+ <span className={`text-sm font-mono ml-3 ${(r.score || 0) >= 70 ? 'text-port-success' : (r.score || 0) >= 40 ? 'text-port-warning' : 'text-port-error'}`}>{r.score}</span>+ </div>+ ))}+ </div>+ <div className="flex gap-3">+ <button+ onClick={() => startMode(selectedMode)}+ className="flex-1 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white font-medium rounded-lg transition-colors"+ >+ Play Again+ </button>+ <button+ onClick={handleBackToModes}+ className="flex-1 px-4 py-2.5 bg-port-card border border-port-border hover:border-port-accent text-white font-medium rounded-lg transition-colors"+ >+ Pick Mode+ </button>+ </div>+ </div>+ );+ }++ // Feedback overlay+ if (feedback && !feedback.complete) {+ if (feedback.scoring) {+ return (+ <div className="max-w-lg mx-auto space-y-6">+ <ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />+ <div className="flex flex-col items-center gap-3 py-12">+ <Loader size={32} className={`${modeInfo?.color || 'text-purple-400'} animate-spin`} />+ <span className="text-gray-400 text-sm">Evaluating your response...</span>+ </div>+ </div>+ );+ }++ const fbScoreColor = (feedback.score || 0) >= 70 ? 'text-port-success' :+ (feedback.score || 0) >= 40 ? 'text-port-warning' : 'text-port-error';+ const FbIcon = (feedback.score || 0) >= 70 ? CheckCircle : XCircle;++ return (+ <div className="max-w-lg mx-auto space-y-6">+ <ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />+ <div className="text-center py-6">+ <FbIcon size={40} className={fbScoreColor} />+ <div className={`text-3xl font-mono font-bold mt-2 ${fbScoreColor}`}>{feedback.score}</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <p className="text-sm text-gray-300">{feedback.feedback}</p>+ {feedback.validCount != null && (+ <p className="text-xs text-gray-500 mt-2">Valid items: {feedback.validCount}</p>+ )}+ {feedback.invalidItems?.length > 0 && (+ <p className="text-xs text-port-error mt-1">Invalid: {feedback.invalidItems.join(', ')}</p>+ )}+ </div>+ <button+ onClick={handleNext}+ autoFocus+ className={`w-full px-6 py-3 ${modeInfo?.bgColor?.replace('/20', '') || 'bg-purple-600'} hover:opacity-80 text-white font-medium rounded-lg transition-colors`}+ >+ {questionIndex + 1 >= totalPrompts ? 'See Results' : 'Next'}+ </button>+ <ProgressBar index={questionIndex} total={totalPrompts} />+ </div>+ );+ }++ // No drill loaded+ if (!drill) {+ return (+ <div className="max-w-lg mx-auto space-y-6">+ <ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />+ <div className="text-center py-8 text-gray-500">Failed to generate challenges. Check your AI provider config.</div>+ <button onClick={handleBackToModes} className="w-full px-4 py-2.5 bg-port-card border border-port-border text-white rounded-lg">Back</button>+ </div>+ );+ }++ // Active drill UI+ return (+ <div className="max-w-lg mx-auto space-y-6">+ <ModeHeader modeInfo={modeInfo} onBack={handleBackToModes} />++ {selectedMode === 'compound-chain' && (+ <CompoundChainUI+ challenge={currentPrompt}+ items={items}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onAddItem={handleAddItem}+ onRemoveItem={handleRemoveItem}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ />+ )}++ {selectedMode === 'bridge-word' && (+ <BridgeWordUI+ puzzle={currentPrompt}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ />+ )}++ {selectedMode === 'double-meaning' && (+ <DoubleMeaningUI+ challenge={currentPrompt}+ inputValue={inputValue}+ setInputValue={setInputValue}+ onSubmit={handleSubmit}+ inputRef={inputRef}+ questionIndex={questionIndex}+ totalPrompts={totalPrompts}+ />+ )}++ {selectedMode === 'idiom-twist' && (+ <IdiomTwistUI+ 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 'compound-chain': return drill.challenges || [];+ case 'bridge-word': return drill.puzzles || [];+ case 'double-meaning': return drill.challenges || [];+ case 'idiom-twist': return drill.challenges || [];+ default: return [];+ }+}++function ModeHeader({ modeInfo, onBack }) {+ const Icon = modeInfo?.icon || Link;+ return (+ <div className="flex items-center gap-3">+ <button onClick={onBack} className="p-1.5 hover:bg-port-card rounded-lg transition-colors">+ <ArrowLeft size={20} className="text-gray-400" />+ </button>+ <div className={`p-1.5 rounded-lg ${modeInfo?.bgColor || 'bg-purple-500/20'}`}>+ <Icon size={18} className={modeInfo?.color || 'text-purple-400'} />+ </div>+ <span className="text-white font-medium">{modeInfo?.label || 'Wordplay'}</span>+ </div>+ );+}+diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.jsindex f67b7a0419..aac1d3e695 100644--- a/client/src/components/meatspace/post/constants.js+++ b/client/src/components/meatspace/post/constants.js@@ -1,4 +1,4 @@-export const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay', 'what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'];+export const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay', 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist', 'what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'];export const MEMORY_DRILL_TYPES = ['memory-sequence', 'memory-element-flash'];// Drill types valid elsewhere but not yet supported by the POST runner.@@ -29,7 +29,7 @@ export const DOMAINS = {color: 'text-purple-400',bgColor: 'bg-purple-500/20',timeBudgetSec: 60,- drillTypes: ['pun-wordplay', 'word-association'],+ drillTypes: ['pun-wordplay', 'word-association', 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist'],},verbal: {label: 'Verbal Agility',@@ -56,3 +56,36 @@ for (const [domainKey, domain] of Object.entries(DOMAINS)) {DRILL_TO_DOMAIN[dt] = domainKey;}}++// Human-readable labels for all drill types+export const DRILL_LABELS = {+ 'doubling-chain': 'Doubling Chain',+ 'serial-subtraction': 'Serial Subtraction',+ 'multiplication': 'Multiplication',+ 'powers': 'Powers',+ 'estimation': 'Estimation',+ 'word-association': 'Word Association',+ 'story-recall': 'Story Recall',+ 'verbal-fluency': 'Verbal Fluency',+ 'wit-comeback': 'Wit & Comeback',+ 'pun-wordplay': 'Pun & Wordplay',+ 'compound-chain': 'Compound Chain',+ 'bridge-word': 'Bridge Word',+ 'double-meaning': 'Double Meaning',+ 'idiom-twist': 'Idiom Twist',+ 'memory-fill-blank': 'Memory Fill Blank',+ 'memory-sequence': 'Memory Sequence',+ 'memory-element-flash': 'Element Flash',+ 'what-if': 'What If?',+ 'alternative-uses': 'Alternative Uses',+ 'story-prompt': 'Story Prompt',+ 'invention-pitch': 'Invention Pitch',+ 'reframe': 'Reframe',+};++// Difficulty badge color helper+export const getDifficultyColor = (difficulty) => {+ if (difficulty === 'hard') return 'bg-port-error/20 text-port-error';+ if (difficulty === 'medium') return 'bg-port-warning/20 text-port-warning';+ return 'bg-port-success/20 text-port-success';+};diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsxindex e5e76ff85c..5f31607266 100644--- a/client/src/components/meatspace/tabs/PostTab.jsx+++ b/client/src/components/meatspace/tabs/PostTab.jsx@@ -12,6 +12,7 @@ import PostDrillConfig from '../post/PostDrillConfig';import MemoryBuilder from '../post/MemoryBuilder';import ElementsSong from '../post/ElementsSong';import DrillTransition from '../post/DrillTransition';+import WordplayTrainer from '../post/WordplayTrainer';import { LLM_DRILL_TYPES } from '../post/constants';export default function PostTab({ tab = 'launcher', subtab }) {@@ -141,6 +142,8 @@ export default function PostTab({ tab = 'launcher', subtab }) {onBack={() => navigate('/post/launcher')}/>);+ case 'wordplay':+ return <WordplayTrainer config={config} onBack={() => navigate('/post/launcher')} />;case 'memory':if (subtab === 'elements') {return (diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 4294aaaf5d..944ce4732f 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -31,7 +31,7 @@ const llmResponseSchema = z.object({// Drill type configurationconst MATH_DRILL_TYPES = ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'];-const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay', 'what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'];+const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay', 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist', 'what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'];const MEMORY_DRILL_TYPES = ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'];// Memory drills supported by the POST runner (client-side scoring with string comparison)const POST_SUPPORTED_MEMORY_TYPES = ['memory-sequence', 'memory-element-flash'];diff --git a/server/services/meatspacePostLlm.js b/server/services/meatspacePostLlm.jsindex b417db394f..c4e0629b6b 100644--- a/server/services/meatspacePostLlm.js+++ b/server/services/meatspacePostLlm.js@@ -18,6 +18,10 @@ export const LLM_DRILL_TYPES = ['verbal-fluency','wit-comeback','pun-wordplay',+ 'compound-chain',+ 'bridge-word',+ 'double-meaning',+ 'idiom-twist','what-if','alternative-uses','story-prompt',@@ -322,6 +326,118 @@ Return ONLY valid JSON:};}+export async function generateCompoundChain(config, providerId, model) {+ const count = config.count || 5;+ const prompt = `Generate ${count} compound word/phrase association challenges for verbal training.+For each challenge, provide a root word that appears in many compound words or common phrases.+Choose words with at least 10+ valid compound combinations (as prefix or suffix).+Mix common roots (fire, back, hand) with less obvious ones (cross, break, light).++Return ONLY valid JSON (no markdown, no explanation):+{"challenges":[{"rootWord":"paper","position":"prefix","examples":["paperback","paper trail","paperweight","paper clip","paper thin"],"minExpected":8}]}++position is "prefix" if the root starts the compound (firehouse), "suffix" if it ends it (campfire), or "both" if common either way (light→lighthouse, flashlight).+The examples field should contain 5 sample answers. minExpected is the target count.`;++ const response = await callAI(prompt, providerId, model);+ const data = parseJsonFromAI(response);+ return {+ type: 'compound-chain',+ config: { count },+ challenges: (data.challenges || []).slice(0, count).map(c => ({+ rootWord: c.rootWord,+ position: c.position || 'both',+ examples: c.examples || [],+ minExpected: c.minExpected || 8,+ }))+ };+}++export async function generateBridgeWord(config, providerId, model) {+ const count = config.count || 5;+ const prompt = `Generate ${count} "bridge word" puzzles for verbal association training.+In each puzzle, a single hidden word connects multiple given phrases or compound words.+For example: "news___", "___back", "___weight" → answer is "paper" (newspaper, paperback, paperweight).++Each puzzle should have 3-4 clue phrases with blanks where the bridge word goes.+Choose bridge words that have many natural compound forms. Vary difficulty.++Return ONLY valid JSON (no markdown, no explanation):+{"puzzles":[{"clues":["news___","___back","___weight","___clip"],"answer":"paper","difficulty":"easy","hint":"Something you write on"}]}`;++ const response = await callAI(prompt, providerId, model);+ const data = parseJsonFromAI(response);+ return {+ type: 'bridge-word',+ config: { count },+ puzzles: (data.puzzles || []).slice(0, count).map(p => ({+ clues: p.clues || [],+ answer: p.answer,+ difficulty: p.difficulty || 'medium',+ hint: p.hint || '',+ }))+ };+}++export async function generateDoubleMeaning(config, providerId, model) {+ const count = config.count || 5;+ const prompt = `Generate ${count} "double meaning" wordplay challenges for verbal association training.+Each challenge presents a word that has multiple unrelated meanings (homonyms/polysemy).+The user must write a single sentence or short phrase that cleverly uses BOTH meanings at once.++For example: "bark" (tree bark + dog bark) → "The dog's bark was louder than the oak's bark."+"scale" (weight scale + fish scale + musical scale) → multiple meanings to play with.++Choose words with clearly distinct meanings that are fun to combine.++Return ONLY valid JSON (no markdown, no explanation):+{"challenges":[{"word":"bark","meanings":["outer covering of a tree","sound a dog makes"],"example":"The dog's bark echoed off the bark of the old oak.","difficulty":"easy"}]}`;++ const response = await callAI(prompt, providerId, model);+ const data = parseJsonFromAI(response);+ return {+ type: 'double-meaning',+ config: { count },+ challenges: (data.challenges || []).slice(0, count).map(c => ({+ word: c.word,+ meanings: c.meanings || [],+ example: c.example || '',+ difficulty: c.difficulty || 'medium',+ }))+ };+}++export async function generateIdiomTwist(config, providerId, model) {+ const count = config.count || 5;+ const prompt = `Generate ${count} "idiom twist" challenges for creative wordplay training.+Each challenge presents a well-known idiom/phrase AND a new domain/context.+The user must adapt the idiom to the new domain using wordplay, puns, or clever substitution.++For example:+- Idiom: "Don't put all your eggs in one basket" + Domain: "Programming"+ → "Don't put all your bugs in one branch"+- Idiom: "The early bird catches the worm" + Domain: "Stock market"+ → "The early trader catches the dip"++Choose well-known idioms and fun, diverse domains. Mix easy and hard combinations.++Return ONLY valid JSON (no markdown, no explanation):+{"challenges":[{"idiom":"Don't put all your eggs in one basket","domain":"programming","example":"Don't push all your commits to one branch","difficulty":"easy"}]}`;++ const response = await callAI(prompt, providerId, model);+ const data = parseJsonFromAI(response);+ return {+ type: 'idiom-twist',+ config: { count },+ challenges: (data.challenges || []).slice(0, count).map(c => ({+ idiom: c.idiom,+ domain: c.domain,+ example: c.example || '',+ difficulty: c.difficulty || 'medium',+ }))+ };+}+export async function generateLlmDrill(type, config = {}, providerId, model) {switch (type) {case 'word-association':@@ -334,6 +450,14 @@ export async function generateLlmDrill(type, config = {}, providerId, model) {return generateWitComeback(config, providerId, model);case 'pun-wordplay':return generatePunWordplay(config, providerId, model);+ case 'compound-chain':+ return generateCompoundChain(config, providerId, model);+ case 'bridge-word':+ return generateBridgeWord(config, providerId, model);+ case 'double-meaning':+ return generateDoubleMeaning(config, providerId, model);+ case 'idiom-twist':+ return generateIdiomTwist(config, providerId, model);case 'what-if':return generateWhatIf(config, providerId, model);case 'alternative-uses':@@ -377,6 +501,18 @@ export async function scoreLlmDrill(type, drillData, userResponses, timeLimitMs,case 'pun-wordplay':scorePrompt = buildPunWordplayScorePrompt(drillData, userResponses);break;+ case 'compound-chain':+ scorePrompt = buildCompoundChainScorePrompt(drillData, userResponses);+ break;+ case 'bridge-word':+ scorePrompt = buildBridgeWordScorePrompt(drillData, userResponses);+ break;+ case 'double-meaning':+ scorePrompt = buildDoubleMeaningScorePrompt(drillData, userResponses);+ break;+ case 'idiom-twist':+ scorePrompt = buildIdiomTwistScorePrompt(drillData, userResponses);+ break;case 'what-if':scorePrompt = buildWhatIfScorePrompt(drillData, userResponses);break;@@ -495,6 +631,78 @@ Return ONLY valid JSON:{"overallScore":75,"scores":[{"score":90,"feedback":"Excellent double meaning"}],"summary":"Overall wordplay assessment"}`;}+// ─────────────────────────────────────────────────────────────────────────────+// WORDPLAY TRAINING SCORE PROMPTS+// ─────────────────────────────────────────────────────────────────────────────++function buildCompoundChainScorePrompt(drillData, responses) {+ const items = responses.map((r, i) => {+ const challenge = drillData.challenges?.[i];+ return `Root word: "${challenge?.rootWord}" (position: ${challenge?.position}, target: ${challenge?.minExpected}+)\nUser's compounds: ${(r.items || []).join(', ') || '(none)'}`;+ }).join('\n\n');++ return `Score these compound word/phrase association responses. For each root word:+1. Count valid compound words or common phrases that actually use the root word+2. Remove duplicates, misspellings, and invalid entries (words that don't form real compounds with the root)+3. Compare count to the target (minExpected)+4. Bonus for creative or unusual but valid compounds++${items}++Return ONLY valid JSON:+{"overallScore":75,"scores":[{"score":80,"feedback":"12 valid compounds, good variety","validCount":12,"invalidItems":["not-a-real-compound"]}],"summary":"Overall compound chain assessment"}`;+}++function buildBridgeWordScorePrompt(drillData, responses) {+ const items = responses.map((r, i) => {+ const puzzle = drillData.puzzles?.[i];+ return `Clues: ${(puzzle?.clues || []).join(', ')}\nCorrect answer: "${puzzle?.answer}"\nUser's answer: "${r.response || '(no response)'}"`;+ }).join('\n\n');++ return `Score these bridge word puzzle responses. For each puzzle:+1. Check if the user's answer matches the correct bridge word (allow minor spelling differences)+2. If the user gave a different word that also validly fills all the blanks, give full credit+3. Rate 0 for wrong answers, 100 for correct++${items}++Return ONLY valid JSON:+{"overallScore":75,"scores":[{"score":100,"feedback":"Correct!"}],"summary":"Overall bridge word assessment"}`;+}++function buildDoubleMeaningScorePrompt(drillData, responses) {+ const items = responses.map((r, i) => {+ const challenge = drillData.challenges?.[i];+ return `Word: "${challenge?.word}" (meanings: ${(challenge?.meanings || []).join(' / ')})\nUser's sentence: "${r.response || '(no response)'}"`;+ }).join('\n\n');++ return `Score these double meaning wordplay responses. For each challenge:+1. Does the sentence use BOTH meanings of the word? (40%)+2. Is it clever/witty? (30%)+3. Is it grammatically correct and natural-sounding? (30%)+Rate each 0-100. Penalize if only one meaning is used.++${items}++Return ONLY valid JSON:+{"overallScore":75,"scores":[{"score":85,"feedback":"Both meanings used cleverly"}],"summary":"Overall double meaning assessment"}`;+}++function buildIdiomTwistScorePrompt(drillData, responses) {+ const items = responses.map((r, i) => {+ const challenge = drillData.challenges?.[i];+ return `Idiom: "${challenge?.idiom}" → Domain: "${challenge?.domain}"\nUser's twist: "${r.response || '(no response)'}"`;+ }).join('\n\n');++ return `Score these idiom twist responses on: recognizable connection to original idiom (30%), relevance to new domain (30%), cleverness of wordplay (40%).+Rate each 0-100. The best twists maintain the rhythm/structure of the original while making domain-specific substitutions.++${items}++Return ONLY valid JSON:+{"overallScore":75,"scores":[{"score":85,"feedback":"Great structural parallel with clever domain substitution"}],"summary":"Overall idiom twist assessment"}`;+}+// ─────────────────────────────────────────────────────────────────────────────// IMAGINATION DRILL SCORE PROMPTS// ─────────────────────────────────────────────────────────────────────────────diff --git a/server/services/meatspacePostLlm.test.js b/server/services/meatspacePostLlm.test.jsindex d14939150f..0eac2475e4 100644--- a/server/services/meatspacePostLlm.test.js+++ b/server/services/meatspacePostLlm.test.js@@ -50,13 +50,17 @@ beforeEach(() => {// =============================================================================describe('LLM_DRILL_TYPES', () => {- it('exports all 10 drill types', () => {+ it('exports all 14 drill types', () => {expect(LLM_DRILL_TYPES).toEqual(['word-association','story-recall','verbal-fluency','wit-comeback','pun-wordplay',+ 'compound-chain',+ 'bridge-word',+ 'double-meaning',+ 'idiom-twist','what-if','alternative-uses','story-prompt',