Skip to content

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

feat(post): add drill cache, local scoring, loading UX, and tutorial hints

Adam Eivybf71c83808a3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f7801e91e6..eda5fb7b6c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,6 +1,10 @@
# Unreleased Changes
## Added
+- POST wordplay drill cache: pre-generates challenges on startup so drills load instantly from cache with background replenishment
+- POST local scoring for deterministic drill types (bridge-word, compound-chain, verbal-fluency, story-recall) — instant results without LLM calls
+- POST loading indicator with elapsed timer, progress bar, and cycling status messages replaces static spinner
+- POST drill tutorial hints: compound chain shows example compounds, bridge word explains the goal, double-meaning and idiom-twist show example answers
- Ambient Dashboard Mode: fullscreen live status board at `/ambient` for wall-mounted displays — shows real-time clock, death clock countdown, today's calendar events, goal progress, and agent activity with auto-refresh, auto-hiding controls, and fullscreen toggle
- Agent options (Worktree+PR, /simplify, Review Loop) configurable per-app on both the Automation tab and CoS Schedule per-app overrides
- Review Loop agent option: runs PR review feedback loop after opening a PR until checks pass
diff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
index f56df7f698..914af73bba 100644
--- a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useRef, useCallback } from 'react';
import { CheckCircle, XCircle, Loader } from 'lucide-react';
import { scorePostLlmDrill } from '../../../services/api';
import { DRILL_LABELS } from './constants';
-import { CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI } from './WordplayDrillUI';
+import { AILoadingIndicator, CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI } from './WordplayDrillUI';
export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, drillCount, onComplete, isTraining, providerId, model }) {
const [questionIndex, setQuestionIndex] = useState(0);
@@ -207,10 +207,7 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr
<span className="text-purple-400">{DRILL_LABELS[drillType] || drillType} — Training</span>
<span>Drill {drillIndex + 1} of {drillCount}</span>
</div>
- <div className="flex flex-col items-center gap-3 py-12">
- <Loader size={32} className="text-purple-400 animate-spin" />
- <span className="text-gray-400 text-sm">Evaluating your response...</span>
- </div>
+ <AILoadingIndicator label="Evaluating your response..." />
</div>
);
}
diff --git a/client/src/components/meatspace/post/WordplayDrillUI.jsx b/client/src/components/meatspace/post/WordplayDrillUI.jsx
index 09f1302d99..039d90e0e5 100644
--- a/client/src/components/meatspace/post/WordplayDrillUI.jsx
+++ b/client/src/components/meatspace/post/WordplayDrillUI.jsx
@@ -1,5 +1,47 @@
+import { useState, useEffect } from 'react';
+import { Loader } from 'lucide-react';
import { getDifficultyColor } from './constants';
+const LOADING_MESSAGES = [
+ 'Crafting challenges...',
+ 'Picking interesting words...',
+ 'Building puzzles...',
+ 'Almost ready...',
+];
+
+export function AILoadingIndicator({ label, color = 'text-purple-400' }) {
+ const [elapsed, setElapsed] = useState(0);
+
+ useEffect(() => {
+ const start = Date.now();
+ const timer = setInterval(() => setElapsed(Math.floor((Date.now() - start) / 1000)), 1000);
+ return () => clearInterval(timer);
+ }, []);
+
+ const msgIndex = Math.floor(elapsed / 3) % LOADING_MESSAGES.length;
+
+ const pct = Math.min(90, elapsed * 6);
+
+ return (
+ <div className="flex flex-col items-center gap-4 py-8">
+ <Loader size={28} className={`${color} animate-spin`} />
+ <div className="text-center space-y-1">
+ <span className="text-gray-300 text-sm">{label}</span>
+ <div className="text-gray-500 text-xs">{LOADING_MESSAGES[msgIndex]}</div>
+ </div>
+ <div className="w-48 space-y-1">
+ <div className="w-full h-1 bg-port-border rounded-full overflow-hidden">
+ <div
+ className="h-full bg-port-accent/50 rounded-full transition-all duration-1000"
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ <div className="text-center text-xs text-gray-600">{elapsed}s</div>
+ </div>
+ </div>
+ );
+}
+
export function ProgressBar({ index, total }) {
const pct = total > 0 ? ((index + 1) / total) * 100 : 0;
return (
@@ -22,7 +64,18 @@ export function DifficultyBadge({ difficulty }) {
);
}
+function ExampleHint({ example }) {
+ if (!example) return null;
+ return <div className="text-xs text-gray-600 mt-3 italic">e.g. &quot;{example}&quot;</div>;
+}
+
export function CompoundChainUI({ challenge, items, inputValue, setInputValue, onAddItem, onRemoveItem, onSubmit, inputRef, questionIndex, totalPrompts }) {
+ const directionHint = challenge?.position === 'prefix'
+ ? `e.g. ${challenge?.rootWord}house, ${challenge?.rootWord}work`
+ : challenge?.position === 'suffix'
+ ? `e.g. day${challenge?.rootWord}, flash${challenge?.rootWord}`
+ : `e.g. ${challenge?.rootWord}house, flash${challenge?.rootWord}`;
+
return (
<>
<div className="text-center py-4">
@@ -32,6 +85,9 @@ export function CompoundChainUI({ challenge, items, inputValue, setInputValue, o
{challenge?.position === 'prefix' ? 'Starts with this word' : challenge?.position === 'suffix' ? 'Ends with this word' : 'Either direction'}
{challenge?.minExpected && ` · Target: ${challenge.minExpected}+`}
</div>
+ {items.length === 0 && (
+ <div className="text-xs text-gray-600 mt-2 italic">{directionHint}</div>
+ )}
</div>
<form onSubmit={onAddItem} className="flex gap-2">
@@ -85,7 +141,8 @@ export function BridgeWordUI({ puzzle, inputValue, setInputValue, onSubmit, inpu
<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>}
+ <div className="text-xs text-gray-600 mt-3 italic">One word completes all the blanks above</div>
+ {puzzle?.hint && <div className="text-sm text-gray-500 mt-2">Hint: {puzzle.hint}</div>}
{puzzle?.difficulty && <DifficultyBadge difficulty={puzzle.difficulty} />}
</div>
<form onSubmit={onSubmit} className="space-y-3">
@@ -152,6 +209,7 @@ export function DoubleMeaningUI({ challenge, inputValue, setInputValue, onSubmit
<span key={i} className="px-3 py-1 bg-amber-500/20 text-amber-400 rounded-lg text-sm">{m}</span>
))}
</div>
+ <ExampleHint example={challenge?.example} />
{challenge?.difficulty && <div className="mt-3"><DifficultyBadge difficulty={challenge.difficulty} /></div>}
</div>
{input}
@@ -200,6 +258,7 @@ export function IdiomTwistUI({ challenge, inputValue, setInputValue, onSubmit, i
<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>
+ <ExampleHint example={challenge?.example} />
{challenge?.difficulty && <div className="mt-3"><DifficultyBadge difficulty={challenge.difficulty} /></div>}
</div>
{input}
diff --git a/client/src/components/meatspace/post/WordplayTrainer.jsx b/client/src/components/meatspace/post/WordplayTrainer.jsx
index fc5b127729..fb18c3280e 100644
--- a/client/src/components/meatspace/post/WordplayTrainer.jsx
+++ b/client/src/components/meatspace/post/WordplayTrainer.jsx
@@ -1,7 +1,7 @@
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';
+import { AILoadingIndicator, CompoundChainUI, BridgeWordUI, DoubleMeaningUI, IdiomTwistUI, ProgressBar } from './WordplayDrillUI';
const GAME_MODES = [
{
@@ -195,10 +195,10 @@ export default function WordplayTrainer({ onBack, config }) {
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>
+ <AILoadingIndicator
+ label={`Generating ${modeInfo?.label} challenges...`}
+ color={modeInfo?.color || 'text-purple-400'}
+ />
</div>
);
}
@@ -249,10 +249,10 @@ export default function WordplayTrainer({ onBack, config }) {
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>
+ <AILoadingIndicator
+ label="Evaluating your response..."
+ color={modeInfo?.color || 'text-purple-400'}
+ />
</div>
);
}
diff --git a/server/index.js b/server/index.js
index f7d0abcd69..26d744d7cb 100644
--- a/server/index.js
+++ b/server/index.js
@@ -83,6 +83,7 @@ import { restoreLoops } from './services/loops.js';
import { startBrainScheduler } from './services/brainScheduler.js';
import { recoverStuckClassifications } from './services/brain.js';
import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridge.js';
+import { initDrillCache } from './services/meatspacePostDrillCache.js';
import { createAIToolkit } from 'portos-ai-toolkit/server';
import { createPortOSProviderRoutes } from './routes/providers.js';
import { createPortOSRunsRoutes } from './routes/runs.js';
@@ -268,6 +269,8 @@ recoverStuckClassifications().catch(err => console.error(`❌ Brain recovery fai
startBrainScheduler();
// Initialize brain→memory bridge (mirrors brain data into CoS memory for semantic search)
initBrainMemoryBridge();
+// Pre-fill POST drill cache in background
+initDrillCache().catch(err => console.error(`❌ POST drill cache init failed: ${err.message}`));
// Initialize backup scheduler for daily data backups
startBackupScheduler().catch(err => console.error(`❌ Backup scheduler init failed: ${err.message}`));
// Initialize Telegram (manual bot or MCP bridge based on settings)
diff --git a/server/routes/meatspace.js b/server/routes/meatspace.js
index 7dbd116bbd..72d0855d1a 100644
--- a/server/routes/meatspace.js
+++ b/server/routes/meatspace.js
@@ -45,6 +45,7 @@ import * as healthService from '../services/meatspaceHealth.js';
import * as postService from '../services/meatspacePost.js';
import * as memoryService from '../services/meatspacePostMemory.js';
import { generateLlmDrill, scoreLlmDrill } from '../services/meatspacePostLlm.js';
+import { getCachedDrill, triggerReplenish } from '../services/meatspacePostDrillCache.js';
import * as trainingService from '../services/meatspacePostTraining.js';
import * as calendarService from '../services/meatspaceCalendar.js';
@@ -575,10 +576,20 @@ router.post('/post/drill', asyncHandler(async (req, res) => {
const data = validateRequest(postDrillRequestSchema, req.body);
if (LLM_DRILL_TYPES.includes(data.type)) {
+ // Try pre-generated cache first for instant response
+ const cached = getCachedDrill(data.type);
+ if (cached) {
+ console.log(`⚡ POST drill served from cache: ${data.type}`);
+ triggerReplenish(data.type, data.providerId, data.model);
+ return res.json(cached);
+ }
+
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' });
}
+ // Trigger background fill so next request is instant
+ triggerReplenish(data.type, data.providerId, data.model);
return res.json(drill);
}
diff --git a/server/services/meatspacePostDrillCache.js b/server/services/meatspacePostDrillCache.js
new file mode 100644
index 0000000000..eae7a3924b
--- /dev/null
+++ b/server/services/meatspacePostDrillCache.js
@@ -0,0 +1,120 @@
+/**
+ * POST Drill Cache — Pre-generates wordplay drills so users don't wait.
+ *
+ * On startup, fills cache to MIN_PER_TYPE. When a drill is consumed,
+ * background replenishment kicks in. Cache persists to disk.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { PATHS } from '../lib/paths.js';
+import { generateLlmDrill } from './meatspacePostLlm.js';
+
+const CACHE_FILE = join(PATHS.data, 'meatspace', 'post-drill-cache.json');
+const MIN_PER_TYPE = 3;
+const MAX_PER_TYPE = 10;
+
+// Only cache LLM-generated drill types used in wordplay training
+const CACHEABLE_TYPES = [
+ 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist',
+];
+
+let cache = {}; // { type: [drill, drill, ...] }
+let replenishing = new Set(); // types currently being refilled
+let saveQueued = false;
+
+async function loadCache() {
+ const raw = await readFile(CACHE_FILE, 'utf-8').catch(() => '{}');
+ cache = JSON.parse(raw);
+ for (const type of CACHEABLE_TYPES) {
+ if (!Array.isArray(cache[type])) cache[type] = [];
+ }
+}
+
+async function saveCache() {
+ await writeFile(CACHE_FILE, JSON.stringify(cache, null, 2));
+}
+
+function debouncedSave() {
+ if (saveQueued) return;
+ saveQueued = true;
+ setTimeout(async () => {
+ saveQueued = false;
+ await saveCache().catch(() => {});
+ }, 500);
+}
+
+function replenishType(type, providerId, model) {
+ if (replenishing.has(type)) return;
+ if ((cache[type]?.length || 0) >= MIN_PER_TYPE) return;
+
+ replenishing.add(type);
+ const needed = MAX_PER_TYPE - (cache[type]?.length || 0);
+
+ (async () => {
+ let generated = 0;
+ try {
+ for (let i = 0; i < needed; i++) {
+ const drill = await generateLlmDrill(type, { count: 5 }, providerId, model).catch(err => {
+ console.log(`⚠️ POST cache: failed to generate ${type}: ${err.message}`);
+ return null;
+ });
+ if (drill) {
+ cache[type].push(drill);
+ generated++;
+ }
+ }
+ if (generated > 0) {
+ await saveCache();
+ console.log(`📦 POST cache: added ${generated} ${type} drills (total: ${cache[type].length})`);
+ }
+ } finally {
+ replenishing.delete(type);
+ }
+ })();
+}
+
+/**
+ * Pull a cached drill for the given type. Returns null if cache is empty.
+ */
+export function getCachedDrill(type) {
+ if (!CACHEABLE_TYPES.includes(type)) return null;
+ const drills = cache[type];
+ if (!drills?.length) return null;
+ return drills.shift(); // consume oldest
+}
+
+/**
+ * Trigger background replenishment after consuming a drill.
+ */
+export function triggerReplenish(type, providerId, model) {
+ if (!CACHEABLE_TYPES.includes(type)) return;
+ replenishType(type, providerId, model);
+ debouncedSave();
+}
+
+/**
+ * Get cache stats for debugging/status.
+ */
+export function getCacheStats() {
+ const stats = {};
+ for (const type of CACHEABLE_TYPES) {
+ stats[type] = cache[type]?.length || 0;
+ }
+ return stats;
+}
+
+/**
+ * Initialize cache: load from disk, start background fill for empty types.
+ */
+export async function initDrillCache(providerId, model) {
+ await loadCache();
+ const stats = CACHEABLE_TYPES.map(t => `${t}:${cache[t]?.length || 0}`).join(' ');
+ console.log(`📦 POST drill cache loaded: ${stats}`);
+
+ for (const type of CACHEABLE_TYPES) {
+ if ((cache[type]?.length || 0) < MIN_PER_TYPE) {
+ replenishType(type, providerId, model);
+ }
+ }
+}
diff --git a/server/services/meatspacePostLlm.js b/server/services/meatspacePostLlm.js
index c4e0629b6b..1bfb3e6d19 100644
--- a/server/services/meatspacePostLlm.js
+++ b/server/services/meatspacePostLlm.js
@@ -477,70 +477,21 @@ export async function generateLlmDrill(type, config = {}, providerId, model) {
// 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;
- 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;
- case 'alternative-uses':
- scorePrompt = buildAlternativeUsesScorePrompt(drillData, userResponses);
- break;
- case 'story-prompt':
- scorePrompt = buildStoryPromptScorePrompt(drillData, userResponses);
- break;
- case 'invention-pitch':
- scorePrompt = buildInventionPitchScorePrompt(drillData, userResponses);
- break;
- case 'reframe':
- scorePrompt = buildReframeScorePrompt(drillData, userResponses);
- break;
- default:
- return { score: 0, evaluation: null, questions: userResponses };
- }
+// ─────────────────────────────────────────────────────────────────────────────
+// SCORING HELPERS
+// ─────────────────────────────────────────────────────────────────────────────
- const response = await callAI(scorePrompt, providerId, model);
- const evaluation = parseJsonFromAI(response);
+function averageScore(scores) {
+ return scores.length > 0
+ ? Math.round(scores.reduce((s, x) => s + x.score, 0) / scores.length)
+ : 0;
+}
- // Combine LLM quality score (80%) with speed bonus (20%)
+function buildScoringResult(evaluation, userResponses, speedBonus) {
const qualityScore = Math.min(100, Math.max(0, evaluation.overallScore || 0));
- const finalScore = Math.round(qualityScore * 0.8 + speedBonus * 0.2 * 100);
-
+ const finalScore = Math.min(100, Math.max(0, Math.round(qualityScore * 0.8 + speedBonus * 0.2 * 100)));
return {
- score: Math.min(100, Math.max(0, finalScore)),
+ score: finalScore,
evaluation,
questions: userResponses.map((r, i) => ({
...r,
@@ -550,6 +501,135 @@ export async function scoreLlmDrill(type, drillData, userResponses, timeLimitMs,
};
}
+// ─────────────────────────────────────────────────────────────────────────────
+// LOCAL (INSTANT) SCORING — no LLM call needed
+// ─────────────────────────────────────────────────────────────────────────────
+
+function scoreLocalBridgeWord(drillData, userResponses) {
+ const scores = userResponses.map((r, i) => {
+ const puzzle = drillData.puzzles?.[i];
+ if (!puzzle?.answer) return { score: 0, feedback: 'No answer available' };
+ const userAnswer = (r.response || '').trim().toLowerCase();
+ const correct = puzzle.answer.trim().toLowerCase();
+ const isCorrect = userAnswer === correct;
+ return {
+ score: isCorrect ? 100 : 0,
+ feedback: isCorrect ? 'Correct!' : `The answer was "${puzzle.answer}"`,
+ };
+ });
+ const overallScore = averageScore(scores);
+ return { overallScore, scores, summary: `${scores.filter(s => s.score === 100).length} of ${scores.length} correct` };
+}
+
+function scoreLocalCompoundChain(drillData, userResponses) {
+ const scores = userResponses.map((r, i) => {
+ const challenge = drillData.challenges?.[i];
+ if (!challenge?.rootWord) return { score: 0, feedback: 'No root word', validCount: 0, invalidItems: [] };
+ const root = challenge.rootWord.toLowerCase();
+ const seen = new Set();
+ const valid = [];
+ const invalid = [];
+ for (const item of (r.items || [])) {
+ const lower = item.toLowerCase().replace(/[\s-]/g, '');
+ if (seen.has(lower)) continue;
+ seen.add(lower);
+ if (lower.includes(root) && lower !== root) {
+ valid.push(item);
+ } else {
+ invalid.push(item);
+ }
+ }
+ const target = challenge.minExpected || 8;
+ const score = Math.round(Math.min(1, valid.length / target) * 100);
+ const fb = valid.length >= target
+ ? `${valid.length} valid compounds — great job!`
+ : `${valid.length} valid compound${valid.length !== 1 ? 's' : ''} (target: ${target})`;
+ return { score, feedback: fb, validCount: valid.length, invalidItems: invalid };
+ });
+ const overallScore = averageScore(scores);
+ return { overallScore, scores, summary: `Average ${overallScore}% across ${scores.length} challenges` };
+}
+
+function scoreLocalVerbalFluency(drillData, userResponses) {
+ const scores = userResponses.map((r, i) => {
+ const cat = drillData.categories?.[i];
+ const seen = new Set();
+ for (const item of (r.items || [])) seen.add(item.toLowerCase().trim());
+ const uniqueCount = seen.size;
+ const target = cat?.minExpected || 15;
+ const score = Math.round(Math.min(1, uniqueCount / target) * 100);
+ return {
+ score,
+ feedback: `${uniqueCount} unique item${uniqueCount !== 1 ? 's' : ''} (target: ${target})`,
+ validCount: uniqueCount,
+ invalidItems: [],
+ };
+ });
+ const overallScore = averageScore(scores);
+ return { overallScore, scores, summary: `Average ${overallScore}%` };
+}
+
+function scoreLocalStoryRecall(drillData, userResponses) {
+ const scores = userResponses.map((r, i) => {
+ const questions = drillData.exercises?.[i]?.questions || [];
+ if (questions.length === 0) return { score: 0, feedback: 'No questions' };
+ let correct = 0;
+ for (let qi = 0; qi < questions.length; qi++) {
+ const expected = (questions[qi].answer || '').toLowerCase().trim();
+ const given = (r.answers?.[qi] || '').toLowerCase().trim();
+ if (given && (given === expected || expected.includes(given) || given.includes(expected))) {
+ correct++;
+ }
+ }
+ const score = Math.round((correct / questions.length) * 100);
+ return { score, feedback: `${correct} of ${questions.length} correct` };
+ });
+ const overallScore = averageScore(scores);
+ return { overallScore, scores, summary: `${overallScore}% recall accuracy` };
+}
+
+const LOCAL_SCORERS = {
+ 'bridge-word': scoreLocalBridgeWord,
+ 'compound-chain': scoreLocalCompoundChain,
+ 'verbal-fluency': scoreLocalVerbalFluency,
+ 'story-recall': scoreLocalStoryRecall,
+};
+
+const LLM_SCORE_BUILDERS = {
+ 'word-association': buildWordAssociationScorePrompt,
+ 'wit-comeback': buildWitComebackScorePrompt,
+ 'pun-wordplay': buildPunWordplayScorePrompt,
+ 'double-meaning': buildDoubleMeaningScorePrompt,
+ 'idiom-twist': buildIdiomTwistScorePrompt,
+ 'what-if': buildWhatIfScorePrompt,
+ 'alternative-uses': buildAlternativeUsesScorePrompt,
+ 'story-prompt': buildStoryPromptScorePrompt,
+ 'invention-pitch': buildInventionPitchScorePrompt,
+ 'reframe': buildReframeScorePrompt,
+};
+
+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);
+
+ // Fast path: score locally for drill types with deterministic answers
+ const localScorer = LOCAL_SCORERS[type];
+ if (localScorer) {
+ console.log(`⚡ POST local scoring: ${type}`);
+ return buildScoringResult(localScorer(drillData, userResponses), userResponses, speedBonus);
+ }
+
+ // Slow path: LLM scoring for creative/subjective drills
+ const builder = LLM_SCORE_BUILDERS[type];
+ if (!builder) return { score: 0, evaluation: null, questions: userResponses };
+
+ console.log(`🧪 POST LLM scoring: ${type}`);
+ const response = await callAI(builder(drillData, userResponses), providerId, model);
+ return buildScoringResult(parseJsonFromAI(response), userResponses, speedBonus);
+}
+
function buildWordAssociationScorePrompt(drillData, responses) {
const pairs = responses.map((r, i) => {
const q = drillData.questions?.[i];