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: add background POST rhetoric evaluation

[._.]/ Adam Eivyd90a47df8e07
diff --git a/client/src/components/meatspace/post/RhetoricTrainer.jsx b/client/src/components/meatspace/post/RhetoricTrainer.jsx
index 0618ccf061..aba738b75c 100644
--- a/client/src/components/meatspace/post/RhetoricTrainer.jsx
+++ b/client/src/components/meatspace/post/RhetoricTrainer.jsx
@@ -1,6 +1,10 @@
import { useEffect, useMemo, useRef, useState } from 'react';
-import { ArrowLeft, CheckCircle, ChevronRight, Feather, Lightbulb, Repeat2, RotateCcw, Timer } from 'lucide-react';
-import { submitTrainingEntry } from '../../../services/api';
+import { ArrowLeft, CheckCircle, ChevronRight, Feather, Lightbulb, Repeat2, RotateCcw, Save, Sparkles, Timer } from 'lucide-react';
+import { evaluateRhetoricAttempt, submitTrainingEntry, updatePostConfig } from '../../../services/api';
+import useProviderModels from '../../../hooks/useProviderModels';
+import ProviderModelSelector from '../../ProviderModelSelector';
+import toast from '../../ui/Toast';
+import { uuidv4 } from '../../../lib/uuid';
const TRAINING_MODULE = 'rhetoric';
const ROUND_SIZE = 5;
@@ -81,53 +85,318 @@ export const RHETORIC_MODES = [
];
const modeFor = (id) => RHETORIC_MODES.find((mode) => mode.id === id) || null;
+const newRoundId = () => uuidv4();
+const evaluatorProviderFilter = (provider) => provider?.enabled !== false;
-export default function RhetoricTrainer({ mode, onSelectMode, onExitMode, onBack, onContinue }) {
+function EvaluatorReport({ results, enabled }) {
+ if (!enabled) return null;
+ const evaluated = results.filter((result) => result.evaluation);
+ const pending = results.filter((result) => !result.evaluation && !result.evaluationError).length;
+ const average = evaluated.length
+ ? Math.round(evaluated.reduce((sum, result) => sum + result.evaluation.overallScore, 0) / evaluated.length)
+ : null;
+ return (
+ <div className="mt-6 text-left border-t border-port-border pt-5 space-y-3">
+ <div className="flex items-center justify-between gap-3 flex-wrap">
+ <div className="flex items-center gap-2">
+ <Sparkles size={16} className="text-port-accent" />
+ <h4 className="font-medium text-white">Evaluator report</h4>
+ </div>
+ <span className="text-xs text-gray-500">
+ {pending > 0 ? `${pending} still evaluating…` : `${evaluated.length}/${results.length} evaluated`}
+ {average != null ? ` · ${average}% average` : ''}
+ </span>
+ </div>
+ <p className="text-xs text-gray-500">
+ The evaluator ran after each save, while the next prompt was available. Its score is separate from your self-score.
+ </p>
+ <div className="space-y-2">
+ {results.map((result, index) => (
+ <div key={result.id} className="rounded-lg bg-port-bg border border-port-border p-3">
+ <div className="flex items-center gap-2 text-xs">
+ <span className="text-gray-500">Attempt {index + 1}</span>
+ <span className="text-gray-500">self {result.rating}/5</span>
+ {result.evaluation && <span className="ml-auto text-port-accent">AI {result.evaluation.overallScore}%</span>}
+ {!result.evaluation && !result.evaluationError && <span className="ml-auto text-gray-500">working…</span>}
+ </div>
+ {result.evaluation
+ ? <>
+ <p className="mt-2 text-sm text-gray-300">{result.evaluation.summary}</p>
+ <div className="mt-2 grid gap-1 sm:grid-cols-3">
+ {result.evaluation.dimensions.map((dimension) => (
+ <div key={dimension.id} className="text-[11px] text-gray-500">
+ <span className="text-gray-400">{dimension.id}</span> · {dimension.score}%
+ <span className="block text-gray-600">{dimension.feedback}</span>
+ </div>
+ ))}
+ </div>
+ </>
+ : result.evaluationError && <p className="mt-2 text-xs text-amber-400">Evaluation unavailable: {result.evaluationError}</p>}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function RhetoricEvaluatorConfig({
+ config,
+ providers,
+ providerId,
+ model,
+ effort,
+ availableModels,
+ enabled,
+ onProviderChange,
+ onModelChange,
+ onEffortChange,
+ onEnabledChange,
+ saving,
+ error,
+ onSave,
+}) {
+ const saved = config?.rhetoricEvaluator?.enabled === true;
+ return (
+ <section className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">
+ <div className="flex items-start gap-3">
+ <span className="rounded-lg p-2 bg-port-accent/15"><Sparkles size={18} className="text-port-accent" /></span>
+ <div>
+ <h3 className="font-semibold text-white">Optional AI evaluator</h3>
+ <p className="mt-1 text-sm text-gray-400">
+ Score each attempt in the background while you answer the next prompt. The completed round keeps the report and provider/model/effort provenance in POST training history.
+ </p>
+ </div>
+ </div>
+ <label htmlFor="rhetoric-evaluator-enabled" className="flex items-start gap-3 text-sm text-gray-300 cursor-pointer">
+ <input
+ id="rhetoric-evaluator-enabled"
+ type="checkbox"
+ checked={enabled}
+ onChange={(event) => onEnabledChange(event.target.checked)}
+ className="mt-0.5 accent-port-accent"
+ />
+ <span>
+ Evaluate rhetoric attempts after save
+ <span className="block text-xs text-gray-500 mt-0.5">Off by default. Saving this setting is the consent gate for background provider calls.</span>
+ </span>
+ </label>
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={providerId}
+ selectedModel={model}
+ availableModels={availableModels}
+ onProviderChange={onProviderChange}
+ onModelChange={onModelChange}
+ onEffortChange={onEffortChange}
+ effort={effort}
+ emptyProviderOption="Use active provider"
+ emptyModelOption="Provider default"
+ alwaysShowModel
+ layout="stacked"
+ disabled={saving}
+ />
+ {providers.length === 0 && <p className="text-xs text-gray-500">No enabled providers are available yet. You can save the active-provider choice and configure one later.</p>}
+ <div className="flex items-center gap-3 flex-wrap">
+ <button
+ type="button"
+ onClick={onSave}
+ disabled={saving}
+ className="inline-flex items-center gap-2 min-h-[44px] px-4 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
+ >
+ <Save size={15} /> {saving ? 'Saving…' : 'Save evaluator'}
+ </button>
+ {saved && !saving && <span className="text-xs text-emerald-400">Enabled for the next round</span>}
+ {error && <span className="text-xs text-amber-400" role="alert">{error}</span>}
+ </div>
+ </section>
+ );
+}
+
+export default function RhetoricTrainer({ mode, onSelectMode, onExitMode, onBack, onContinue, config, onConfigUpdate }) {
const selectedMode = modeFor(mode);
const [promptIndex, setPromptIndex] = useState(0);
const [response, setResponse] = useState('');
const [rating, setRating] = useState(null);
const [results, setResults] = useState([]);
const [saving, setSaving] = useState(false);
+ const [evaluatorSaving, setEvaluatorSaving] = useState(false);
+ const [evaluatorSaveError, setEvaluatorSaveError] = useState('');
+ const savedEvaluator = config?.rhetoricEvaluator || {};
+ const [evaluatorEnabled, setEvaluatorEnabled] = useState(savedEvaluator.enabled === true);
+ const [evaluatorEffort, setEvaluatorEffort] = useState(savedEvaluator.effort || '');
+ const {
+ providers,
+ selectedProviderId: evaluatorProviderId,
+ selectedModel: evaluatorModel,
+ availableModels: evaluatorModels,
+ setSelectedProviderId: setEvaluatorProviderId,
+ setSelectedModel: setEvaluatorModel,
+ } = useProviderModels({ filter: evaluatorProviderFilter, allowDefault: true, silent: true, withEffort: true });
const roundStart = useRef(Date.now());
+ const promptStart = useRef(Date.now());
+ const roundIdRef = useRef(newRoundId());
+ const resultsByRoundRef = useRef(new Map([[roundIdRef.current, []]]));
+ const evaluatorTailRef = useRef(Promise.resolve());
+ const roundEvaluationPromisesRef = useRef([]);
useEffect(() => {
+ const nextRoundId = newRoundId();
+ roundIdRef.current = nextRoundId;
+ resultsByRoundRef.current.set(nextRoundId, []);
+ roundEvaluationPromisesRef.current = [];
setPromptIndex(0);
setResponse('');
setRating(null);
setResults([]);
+ setSaving(false);
+ setEvaluatorSaveError('');
roundStart.current = Date.now();
+ promptStart.current = Date.now();
}, [selectedMode?.id]);
+ useEffect(() => {
+ setEvaluatorEnabled(savedEvaluator.enabled === true);
+ setEvaluatorProviderId(savedEvaluator.providerId || '');
+ setEvaluatorModel(savedEvaluator.model || '');
+ setEvaluatorEffort(savedEvaluator.effort || '');
+ }, [savedEvaluator.enabled, savedEvaluator.providerId, savedEvaluator.model, savedEvaluator.effort]);
+
const prompt = selectedMode?.prompts[promptIndex];
const completed = results.length;
const average = useMemo(() => completed
? Math.round(results.reduce((sum, result) => sum + result.rating, 0) / completed * 20)
: 0, [completed, results]);
+ function replaceRoundResults(roundId, nextResults) {
+ resultsByRoundRef.current.set(roundId, nextResults);
+ if (roundId === roundIdRef.current) {
+ setResults(nextResults);
+ }
+ }
+
+ function enqueueEvaluation(attempt, roundId) {
+ const evaluator = config?.rhetoricEvaluator;
+ if (evaluator?.enabled !== true) return null;
+ const request = {
+ attemptId: attempt.id,
+ mode: selectedMode.id,
+ prompt: attempt.prompt,
+ response: attempt.response,
+ ...(evaluator.providerId && { providerId: evaluator.providerId }),
+ ...(evaluator.model && { model: evaluator.model }),
+ ...(evaluator.effort && { effort: evaluator.effort }),
+ };
+ const queued = evaluatorTailRef.current.then(() => evaluateRhetoricAttempt(request, { silent: true }));
+ // Keep the serial queue alive after one provider failure. The failed request
+ // is shown on its own attempt, while the next answer still gets evaluated.
+ evaluatorTailRef.current = queued.catch(() => null);
+ roundEvaluationPromisesRef.current.push(queued);
+ queued.then((result) => {
+ const current = resultsByRoundRef.current.get(roundId) || [];
+ replaceRoundResults(roundId, current.map((item) => item.id === attempt.id
+ ? { ...item, evaluation: result.evaluation }
+ : item));
+ }).catch((error) => {
+ const message = String(error?.message || error || 'Unknown evaluator error').slice(0, 500);
+ const current = resultsByRoundRef.current.get(roundId) || [];
+ replaceRoundResults(roundId, current.map((item) => item.id === attempt.id
+ ? { ...item, evaluationError: message }
+ : item));
+ });
+ return queued;
+ }
+
function resetRound() {
- setPromptIndex(0); setResponse(''); setRating(null); setResults([]); roundStart.current = Date.now();
+ const nextRoundId = newRoundId();
+ roundIdRef.current = nextRoundId;
+ resultsByRoundRef.current.set(nextRoundId, []);
+ roundEvaluationPromisesRef.current = [];
+ setPromptIndex(0);
+ setResponse('');
+ setRating(null);
+ setResults([]);
+ setSaving(false);
+ setEvaluatorSaveError('');
+ roundStart.current = Date.now();
+ promptStart.current = Date.now();
}
- function finishRound(nextResults) {
+ function finishRound(roundId, nextResults, roundStartedAt) {
+ const pendingEvaluations = roundEvaluationPromisesRef.current.slice();
+ const roundTotalMs = Math.max(0, Date.now() - roundStartedAt);
setSaving(true);
- submitTrainingEntry({
- module: TRAINING_MODULE,
- drillType: TRAINING_TYPES[selectedMode.id],
- score: Math.round(nextResults.reduce((sum, result) => sum + result.rating, 0) / nextResults.length * 20),
- questionCount: nextResults.length,
- correctCount: nextResults.filter((result) => result.rating >= 4).length,
- totalMs: Date.now() - roundStart.current,
- }, { silent: true }).catch(() => {}).finally(() => setSaving(false));
+ Promise.allSettled(pendingEvaluations)
+ .then(() => {
+ const finalResults = resultsByRoundRef.current.get(roundId) || nextResults;
+ return submitTrainingEntry({
+ module: TRAINING_MODULE,
+ drillType: TRAINING_TYPES[selectedMode.id],
+ score: Math.round(finalResults.reduce((sum, result) => sum + result.rating, 0) / finalResults.length * 20),
+ questionCount: finalResults.length,
+ correctCount: finalResults.filter((result) => result.rating >= 4).length,
+ totalMs: roundTotalMs,
+ scorerProvenance: config?.rhetoricEvaluator?.enabled === true
+ ? 'post-rhetoric-self+ai'
+ : 'post-rhetoric-self',
+ questions: finalResults.map((result) => ({
+ id: result.id,
+ prompt: result.prompt,
+ response: result.response,
+ responseMs: result.responseMs,
+ selfRating: result.rating,
+ score: result.rating * 20,
+ correct: result.rating >= 4,
+ ...(result.evaluation && { evaluation: result.evaluation }),
+ ...(result.evaluationError && { evaluationError: result.evaluationError }),
+ })),
+ }, { silent: true });
+ })
+ .catch((error) => {
+ if (roundId === roundIdRef.current) setEvaluatorSaveError(String(error?.message || error || 'Could not save this round').slice(0, 500));
+ })
+ .finally(() => {
+ if (roundId === roundIdRef.current) setSaving(false);
+ });
}
function submitResponse() {
if (!response.trim() || rating == null) return;
- const nextResults = [...results, { response: response.trim(), rating }];
- setResults(nextResults);
+ const roundId = roundIdRef.current;
+ const attempt = {
+ id: `${roundId}:${results.length + 1}`,
+ prompt,
+ response: response.trim(),
+ rating,
+ responseMs: Math.max(0, Date.now() - promptStart.current),
+ };
+ const nextResults = [...results, attempt];
+ replaceRoundResults(roundId, nextResults);
+ enqueueEvaluation(attempt, roundId);
setResponse(''); setRating(null);
- if (nextResults.length >= ROUND_SIZE) finishRound(nextResults);
- else setPromptIndex((index) => index + 1);
+ if (nextResults.length >= ROUND_SIZE) finishRound(roundId, nextResults, roundStart.current);
+ else {
+ setPromptIndex((index) => index + 1);
+ promptStart.current = Date.now();
+ }
+ }
+
+ function saveEvaluator() {
+ setEvaluatorSaving(true);
+ setEvaluatorSaveError('');
+ updatePostConfig({
+ rhetoricEvaluator: {
+ enabled: evaluatorEnabled,
+ providerId: evaluatorProviderId || null,
+ model: evaluatorModel || null,
+ effort: evaluatorEffort || null,
+ },
+ }, { silent: true })
+ .then((updated) => {
+ onConfigUpdate?.(updated);
+ toast.success('Rhetoric evaluator settings saved');
+ })
+ .catch((error) => setEvaluatorSaveError(String(error?.message || error || 'Could not save evaluator settings').slice(0, 500)))
+ .finally(() => setEvaluatorSaving(false));
}
if (!selectedMode) {
@@ -138,6 +407,22 @@ export default function RhetoricTrainer({ mode, onSelectMode, onExitMode, onBack
<div className="flex items-center gap-3"><Feather className="text-port-accent" size={28} /><h2 className="text-2xl font-bold text-white">Rhetoric practice</h2></div>
<p className="mt-2 text-gray-400 max-w-2xl">Train the small structures that make language memorable. Each round gives you five prompts, a compact craft checklist, and space to make the attempt your own.</p>
</div>
+ <RhetoricEvaluatorConfig
+ config={config}
+ providers={providers}
+ providerId={evaluatorProviderId}
+ model={evaluatorModel}
+ effort={evaluatorEffort}
+ availableModels={evaluatorModels}
+ enabled={evaluatorEnabled}
+ onProviderChange={(value) => { setEvaluatorProviderId(value); setEvaluatorEffort(''); }}
+ onModelChange={setEvaluatorModel}
+ onEffortChange={setEvaluatorEffort}
+ onEnabledChange={setEvaluatorEnabled}
+ saving={evaluatorSaving}
+ error={evaluatorSaveError}
+ onSave={saveEvaluator}
+ />
<div className="grid gap-4 sm:grid-cols-2">
{RHETORIC_MODES.map((entry) => {
const Icon = entry.icon;
@@ -164,11 +449,21 @@ export default function RhetoricTrainer({ mode, onSelectMode, onExitMode, onBack
{!roundComplete ? <>
<div className="mt-6 rounded-lg bg-port-bg border border-port-border p-4"><div className="text-xs uppercase tracking-wide text-port-accent mb-2">Prompt {promptIndex + 1}</div><p className="text-lg text-white">{prompt}</p></div>
<label htmlFor="rhetoric-response" className="block mt-5 text-sm text-gray-300">Your attempt</label>
- <textarea id="rhetoric-response" value={response} onChange={(event) => setResponse(event.target.value)} rows={5} autoFocus placeholder="Write without over-editing. The first live version is useful data." className="mt-2 w-full bg-port-bg border border-port-border rounded-lg px-3 py-3 text-white placeholder-gray-600 focus:outline-none focus:border-port-accent resize-y" />
+ <textarea id="rhetoric-response" value={response} onChange={(event) => setResponse(event.target.value)} maxLength={10000} rows={5} autoFocus placeholder="Write without over-editing. The first live version is useful data." className="mt-2 w-full bg-port-bg border border-port-border rounded-lg px-3 py-3 text-white placeholder-gray-600 focus:outline-none focus:border-port-accent resize-y" />
<div className="mt-4"><p className="text-sm text-gray-400 mb-2">How well did it meet the craft goal?</p><div className="flex flex-wrap gap-2">{[1, 2, 3, 4, 5].map((value) => <button key={value} type="button" onClick={() => setRating(value)} aria-label={`Rate ${value} out of 5`} className={`px-4 py-2 rounded border text-sm ${rating === value ? 'border-port-accent bg-port-accent/20 text-white' : 'border-port-border text-gray-400 hover:text-white'}`}>{value}</button>)}</div></div>
<div className="mt-5 border-t border-port-border pt-4"><p className="text-xs text-gray-500 mb-2">Quick check</p><ul className="grid gap-1 sm:grid-cols-3 text-xs text-gray-400">{selectedMode.checklist.map((item) => <li key={item}>· {item}</li>)}</ul></div>
<button type="button" onClick={submitResponse} disabled={!response.trim() || rating == null} className="mt-5 w-full rounded-lg bg-port-accent hover:bg-port-accent/80 disabled:opacity-40 disabled:cursor-not-allowed text-white py-2.5 font-medium">Save attempt &amp; next</button>
- </> : <div className="mt-6 text-center py-8"><CheckCircle size={42} className="mx-auto text-port-success" /><h3 className="mt-3 text-xl font-semibold text-white">Round complete</h3><p className="mt-2 text-gray-400">You rated this round {average}%. Notice which structure felt easiest to reach for.</p><div className="flex gap-3 justify-center mt-6"><button type="button" onClick={resetRound} className="flex items-center gap-2 px-4 py-2 rounded-lg border border-port-border text-gray-300 hover:text-white"><RotateCcw size={16} /> New round</button><button type="button" onClick={onContinue} disabled={saving} className="px-4 py-2 rounded-lg bg-port-accent text-white disabled:opacity-50">{saving ? 'Logging…' : 'Continue POST'}</button></div></div>}
+ </> : <div className="mt-6 text-center py-8">
+ <CheckCircle size={42} className="mx-auto text-port-success" />
+ <h3 className="mt-3 text-xl font-semibold text-white">Round complete</h3>
+ <p className="mt-2 text-gray-400">You rated this round {average}%. Notice which structure felt easiest to reach for.</p>
+ <EvaluatorReport results={results} enabled={savedEvaluator.enabled === true} />
+ {evaluatorSaveError && <p className="mt-3 text-xs text-amber-400" role="alert">{evaluatorSaveError}</p>}
+ <div className="flex gap-3 justify-center mt-6 flex-wrap">
+ <button type="button" onClick={resetRound} className="flex items-center gap-2 min-h-[44px] px-4 py-2 rounded-lg border border-port-border text-gray-300 hover:text-white"><RotateCcw size={16} /> New round</button>
+ <button type="button" onClick={onContinue} disabled={saving} className="min-h-[44px] px-4 py-2 rounded-lg bg-port-accent text-white disabled:opacity-50">{saving ? 'Saving report…' : 'Continue POST'}</button>
+ </div>
+ </div>}
</div>
</div>;
}
diff --git a/client/src/components/meatspace/post/RhetoricTrainer.test.jsx b/client/src/components/meatspace/post/RhetoricTrainer.test.jsx
index c480665b3b..b994c05954 100644
--- a/client/src/components/meatspace/post/RhetoricTrainer.test.jsx
+++ b/client/src/components/meatspace/post/RhetoricTrainer.test.jsx
@@ -1,25 +1,29 @@
-import { fireEvent, render, screen } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import RhetoricTrainer from './RhetoricTrainer';
+import { evaluateRhetoricAttempt, submitTrainingEntry } from '../../../services/api';
vi.mock('../../../services/api', () => ({
+ evaluateRhetoricAttempt: vi.fn(),
+ getProviders: vi.fn(() => Promise.resolve({ providers: [] })),
submitTrainingEntry: vi.fn(() => Promise.resolve()),
}));
describe('RhetoricTrainer', () => {
const props = { onBack: vi.fn(), onSelectMode: vi.fn(), onExitMode: vi.fn(), onContinue: vi.fn() };
- it('shows the rhetoric exercise choices', () => {
+ it('shows the rhetoric exercise choices', async () => {
render(<RhetoricTrainer {...props} />);
- expect(screen.getByText('Iambic Pentameter')).toBeInTheDocument();
+ await waitFor(() => expect(screen.getByText('Iambic Pentameter')).toBeInTheDocument());
expect(screen.getByText('Diacope')).toBeInTheDocument();
expect(screen.getByText('Chiasmus')).toBeInTheDocument();
expect(screen.getByText('Progressia')).toBeInTheDocument();
expect(screen.getByText('Rhetorical Brainstorm')).toBeInTheDocument();
});
- it('requires an attempt and self-rating before advancing', () => {
+ it('requires an attempt and self-rating before advancing', async () => {
render(<RhetoricTrainer {...props} mode="diacope" />);
+ await waitFor(() => expect(screen.getByText('Prompt 1')).toBeInTheDocument());
const save = screen.getByRole('button', { name: /save attempt/i });
expect(save).toBeDisabled();
fireEvent.change(screen.getByLabelText('Your attempt'), { target: { value: 'Stay, until the storm passes. Stay.' } });
@@ -29,10 +33,52 @@ describe('RhetoricTrainer', () => {
expect(screen.getByText('Prompt 2')).toBeInTheDocument();
});
- it('offers a chiasmus prompt and craft checklist', () => {
+ it('offers a chiasmus prompt and craft checklist', async () => {
render(<RhetoricTrainer {...props} mode="chiasmus" />);
+ await waitFor(() => expect(screen.getByText('Prompt 1')).toBeInTheDocument());
expect(screen.getByText('Chiasmus')).toBeInTheDocument();
expect(screen.getByText(/reverses its key terms/i)).toBeInTheDocument();
expect(screen.getByText(/reverse order/i)).toBeInTheDocument();
});
+
+ it('advances while evaluations are pending and saves the completed report', async () => {
+ const deferred = Array.from({ length: 5 }, () => {
+ let resolve;
+ const promise = new Promise((finish) => { resolve = finish; });
+ return { promise, resolve };
+ });
+ let evaluationIndex = 0;
+ evaluateRhetoricAttempt.mockImplementation(() => deferred[evaluationIndex++].promise);
+ const evaluation = {
+ overallScore: 82,
+ dimensions: ['form', 'image', 'sound'].map((id) => ({ id, score: 82, feedback: 'Specific evidence.' })),
+ summary: 'A clear attempt with a deliberate image.',
+ provenance: { rubricVersion: 'rhetoric-evaluator-v1', providerId: 'example-provider', model: 'example-model', effort: 'high' },
+ };
+ const evaluatorConfig = {
+ rhetoricEvaluator: { enabled: true, providerId: 'example-provider', model: 'example-model', effort: 'high' },
+ };
+ render(<RhetoricTrainer {...props} mode="meter" config={evaluatorConfig} />);
+ await waitFor(() => expect(screen.getByText('Prompt 1')).toBeInTheDocument());
+
+ for (let index = 0; index < 5; index += 1) {
+ fireEvent.change(screen.getByLabelText('Your attempt'), { target: { value: `Attempt ${index + 1}` } });
+ fireEvent.click(screen.getByRole('button', { name: 'Rate 4 out of 5' }));
+ fireEvent.click(screen.getByRole('button', { name: /Save attempt & next/i }));
+ await waitFor(() => expect(evaluateRhetoricAttempt).toHaveBeenCalledTimes(index + 1));
+ if (index < 4) {
+ deferred[index].resolve({ evaluation });
+ await waitFor(() => expect(screen.getByText(`Prompt ${index + 2}`)).toBeInTheDocument());
+ }
+ }
+
+ expect(screen.getByRole('button', { name: 'Saving report…' })).toBeDisabled();
+ deferred[4].resolve({ evaluation });
+ await waitFor(() => expect(submitTrainingEntry).toHaveBeenCalledTimes(1));
+ const saved = submitTrainingEntry.mock.calls[0][0];
+ expect(saved.scorerProvenance).toBe('post-rhetoric-self+ai');
+ expect(saved.questions).toHaveLength(5);
+ expect(saved.questions.every((question) => question.evaluation?.overallScore === 82)).toBe(true);
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Continue POST' })).not.toBeDisabled());
+ });
});
diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsx
index 76785e983a..f81c9cecfb 100644
--- a/client/src/components/meatspace/tabs/PostTab.jsx
+++ b/client/src/components/meatspace/tabs/PostTab.jsx
@@ -297,6 +297,8 @@ export default function PostTab({ tab = 'launcher', subtab, mode }) {
case 'rhetoric':
return (
<RhetoricTrainer
+ config={config}
+ onConfigUpdate={setConfig}
mode={subtab}
onSelectMode={(id) => navigate(`/post/rhetoric/${id}`)}
onExitMode={() => navigate('/post/rhetoric')}
diff --git a/client/src/components/settings/ModelCapabilityTests.jsx b/client/src/components/settings/ModelCapabilityTests.jsx
index 4f88e1708d..98afd2f0a1 100644
--- a/client/src/components/settings/ModelCapabilityTests.jsx
+++ b/client/src/components/settings/ModelCapabilityTests.jsx
@@ -46,6 +46,7 @@ const TEST_META = {
'image-analysis': { Icon: Eye, cls: 'text-amber-400', border: 'border-amber-400/35' },
'story-outline': { Icon: BookOpen, cls: 'text-port-accent-2', border: 'border-port-accent-2/35' },
'fiction-scene': { Icon: BookOpen, cls: 'text-pink-400', border: 'border-pink-400/35' },
+ 'rhetoric-reference': { Icon: BookOpen, cls: 'text-green-400', border: 'border-green-400/35' },
};
const testMeta = (id) => TEST_META[id] || { Icon: FlaskConical, cls: 'text-gray-400', border: 'border-port-border' };
@@ -87,6 +88,7 @@ const TASK_FILTERS = [
// Older servers shipped only the outline proxy. Prefer the prose check when
// present, but keep the filter useful during a rolling upgrade.
{ id: 'writing', label: 'Writing', testIds: ['fiction-scene', 'story-outline'] },
+ { id: 'rhetoric', label: 'Rhetoric', testIds: ['rhetoric-reference'] },
];
const verdictRank = { passed: 2, partial: 1, failed: 0 };
@@ -111,6 +113,9 @@ const taskScore = (taskId, result) => {
: 0;
return detail.total ? beats : anchors * 0.7 + craft * 0.3;
}
+ if (taskId === 'rhetoric' && Number.isFinite(detail.meanAbsoluteError)) {
+ return Math.max(0, 1 - detail.meanAbsoluteError / 100);
+ }
return verdictRank[result.verdict] / 2;
};
@@ -126,6 +131,7 @@ const specializationScore = (taskId, model) => {
const id = String(model?.modelId || '').toLowerCase();
if (taskId === 'coding') return /coder|code/.test(id) ? 2 : 0;
if (taskId === 'writing') return /fable|fiction|writer|story/.test(id) ? 2 : 0;
+ if (taskId === 'rhetoric') return /writer|story|reason|instruct/.test(id) ? 2 : 0;
return 0;
};
@@ -355,10 +361,45 @@ function SandboxChecks({ detail }) {
);
}
+/** Calibration summary for the committed rhetoric reference corpus. */
+function RhetoricReferenceScore({ detail }) {
+ const worst = [...(detail.items || [])]
+ .sort((a, b) => b.absoluteError - a.absoluteError)
+ .slice(0, 5);
+ return (
+ <div className="space-y-3">
+ <p className="text-[11px] text-gray-500 leading-snug">
+ PortOS compares the model&rsquo;s scores with a fixed, fictional gold set. Lower error is better;
+ the verdict also requires broad agreement so a model cannot hide a few extreme misses behind an average.
+ </p>
+ <dl className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs">
+ <div><dt className="text-gray-500">References</dt><dd className="text-gray-200">{detail.evaluatedCount ?? detail.referenceCount ?? '—'}</dd></div>
+ <div><dt className="text-gray-500">Mean error</dt><dd className="text-gray-200">{detail.meanAbsoluteError ?? '—'} pts</dd></div>
+ <div><dt className="text-gray-500">Within 10</dt><dd className="text-gray-200">{detail.within10Count ?? '—'}</dd></div>
+ <div><dt className="text-gray-500">Within 20</dt><dd className="text-gray-200">{detail.within20Count ?? '—'}</dd></div>
+ </dl>
+ {worst.length > 0 && (
+ <div>
+ <h4 className="text-xs font-medium text-gray-400 mb-1">Largest calibration gaps</h4>
+ {worst.map((item) => (
+ <div key={item.id} className="flex items-center gap-2 py-1.5 border-b border-port-border/50 last:border-b-0 text-xs">
+ <span className="font-mono text-gray-500">{item.id}</span>
+ <span className="ml-auto text-gray-400">gold {item.expected}</span>
+ <span className="text-gray-400">model {item.predicted}</span>
+ <span className="text-port-warning">Δ {item.absoluteError}</span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
const SCORE_VIEWS = {
'image-analysis': KeywordScore,
'story-outline': BeatScore,
'fiction-scene': FictionScore,
+ 'rhetoric-reference': RhetoricReferenceScore,
'sandbox-repair': SandboxChecks,
};
diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.js
index 6c29d954e3..a7056955a2 100644
--- a/client/src/services/apiMeatspace.js
+++ b/client/src/services/apiMeatspace.js
@@ -229,6 +229,15 @@ export const scorePostLlmDrill = (type, drillData, responses, timeLimitMs, provi
body: JSON.stringify({ type, drillData, responses, timeLimitMs, ...(providerId && { providerId }), ...(model && { model }) }),
...options
});
+// Standalone rhetoric attempts are evaluated one at a time in the trainer's
+// background queue. Callers own the inline failure state, so they should pass
+// `{ silent: true }` here rather than making a provider hiccup interrupt the
+// next prompt.
+export const evaluateRhetoricAttempt = (data, options = {}) => request('/meatspace/post/rhetoric/evaluate', {
+ method: 'POST',
+ body: JSON.stringify(data),
+ ...options
+});
export const getPostDrillCacheStatus = () => request('/meatspace/post/drill-cache/status');
export const fillPostDrillCache = (types, providerId, model) => request('/meatspace/post/drill-cache/fill', {
method: 'POST',
diff --git a/server/lib/README.md b/server/lib/README.md
index 947fc07f35..ac0e534d5f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -59,6 +59,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `peerSyncValidation.js` | Federated peer-sync wire/request schemas (push payload, subscribe, sync-now, pull-metadata). |
| `pipelineValidation.js` | Creative-production pipeline schemas (Writers Room works/folders/live-mode/drafts, story-bible character/place/object, editorial checks, storyboard shots/scenes, prompt-stage config, issue-list query). |
| `postLlmContracts.js` | Versioned POST LLM generation/scoring schemas, semantic-verdict validation, and secret-free generator/scorer provenance with explicit legacy normalization. |
+| `postRhetoric.js` | Shared rhetoric evaluator rubric, mode/drill ids, structured evaluator prompt/response validation, and the 40-item fictional gold-reference corpus used by POST background reports and local-model performance checks. |
| `postValidation.js` | MeatSpace POST (Power On Self Test) schemas — drill config (incl. adaptive toggle), drill generation/scoring, sessions, memory builder, training log. |
| `privacyValidation.js` | Privacy Center schemas — PII Vault (issue #2140): vault record create/update (partial PUT), list query, UUID params; the vault type/status vocabularies + the sensitive-type (`ssn`/`passport`/`drivers_license`/`financial_account`) `useForScans` hard-false rule and per-type scan defaults. Trusted Organizations registry (issue #2141): org create/update (partial PUT), list query, UUID params, and the replace-set holdings schema. Data-broker database + case ledger (issue #2144): broker list/case-list query filters, the scan-start + refresh action bodies, and the `PRIVACY_BROKER_CASE_STATES` vocabulary. |
| `roundsValidation.js` | Rounds workbench shape bounds + pure record sanitizers (sections, layers, recordings, pitch analysis, references, progress) — `sanitizeRound(raw, builtinIds)` and the length/count limits shared with routes/rounds.js. |
@@ -136,7 +137,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path, and `videoTextEncoderRuntimes()` enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written. |
| `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file. |
| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. |
-| `modelCapabilityTests.js` | Catalog + scoring for the CAPABILITY tests on `/models/performance` (run by `services/modelCapabilityTests.js`): `CAPABILITY_TESTS` (sandbox repair / image analysis / story outline, each gated on the capability badges the install catalog already shows), `applicabilityFor` + `applicableTests` (`applicable` / `not-applicable` / `unknown` — an UNCLAIMED capability is never a failure, and `null` capabilities mean the runtime reported none, which is distinct from `[]`), `scoreKeywords` + `VISION_FIXTURE_KEYWORDS` (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), `scoreStoryBeats` + `HEROS_JOURNEY_BEATS` (coverage AND ordering, judged only over the beats present), `scoreSandboxRepair` (verdict from observed disk facts — editing the test instead of the module fails outright), `formatAgentEvent` (one agent stream frame → a transcript line), `rollUpVerdict`, and the verbatim `CAPABILITY_TEST_PROMPTS` / `SANDBOX_TASK_PROMPT` the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call. |
+| `modelCapabilityTests.js` | Catalog + scoring for the CAPABILITY tests on `/models/performance` (run by `services/modelCapabilityTests.js`): `CAPABILITY_TESTS` (sandbox repair / image analysis / story outline / fiction scene / rhetoric evaluator, each gated on the capability badges the install catalog already shows), `applicabilityFor` + `applicableTests` (`applicable` / `not-applicable` / `unknown` — an UNCLAIMED capability is never a failure, and `null` capabilities mean the runtime reported none, which is distinct from `[]`), `scoreKeywords` + `VISION_FIXTURE_KEYWORDS` (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), `scoreStoryBeats` + `HEROS_JOURNEY_BEATS` (coverage AND ordering, judged only over the beats present), `scoreSandboxRepair` (verdict from observed disk facts — editing the test instead of the module fails outright), `formatAgentEvent` (one agent stream frame → a transcript line), `rollUpVerdict`, and the verbatim `CAPABILITY_TEST_PROMPTS` / `SANDBOX_TASK_PROMPT` the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call. |
| `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. |
| `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). |
| `subscriptionSavings.js` | Subscription-vs-API savings math for the usage page — `resolveSavingsWindow` (clamps an open-ended report range to today / first activity day), `prorateMonthlyCost` (monthly plan price → this window's share, `DAYS_PER_MONTH`, capped by `MAX_MONTHLY_COST`), `savingsPercent` / `costMultiplier` (null, never 0, when the comparison is undefined), `attributeReportCostToFamilies` (groups report rows by their stamped `family`), `roundCents` (the one money rounder), and `buildSubscriptionSavings({ entries, range, unmatchedApiCost })` → per-family rows + totals. Pure. |
diff --git a/server/lib/creativeLatitude.js b/server/lib/creativeLatitude.js
index 91e8686c17..4ba49125c0 100644
--- a/server/lib/creativeLatitude.js
+++ b/server/lib/creativeLatitude.js
@@ -132,6 +132,7 @@ export const OPERATIONAL_RUN_SOURCES = Object.freeze([
'jira-title',
'loop', // user-authored recurring prompts — one tag for every kind, so it can't be split
'memory-embedding-summary',
+ 'meatspace-post-rhetoric-evaluator',
'model-personality-alignment',
'model-personality-profile',
'moltbook-challenge',
diff --git a/server/lib/index.js b/server/lib/index.js
index 80fccc7bdb..ef8d4558af 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -39,6 +39,7 @@ export * as notesValidation from './notesValidation.js';
export * as peerSyncValidation from './peerSyncValidation.js';
export * as pipelineValidation from './pipelineValidation.js';
export * as postLlmContracts from './postLlmContracts.js';
+export * as postRhetoric from './postRhetoric.js';
export * as postValidation from './postValidation.js';
export * as privacyValidation from './privacyValidation.js';
export * as roundsValidation from './roundsValidation.js';
diff --git a/server/lib/modelCapabilityTests.js b/server/lib/modelCapabilityTests.js
index 12dd0086f6..39446c02c6 100644
--- a/server/lib/modelCapabilityTests.js
+++ b/server/lib/modelCapabilityTests.js
@@ -24,6 +24,12 @@
*/
import { escapeRegExp } from './textUtils.js';
+import {
+ buildRhetoricReferencePrompt,
+ parseRhetoricJson,
+ RHETORIC_REFERENCE_SET,
+ scoreRhetoricReference,
+} from './postRhetoric.js';
/** Verdicts every scorer returns. `partial` is real evidence, not a soft fail. */
export const TEST_VERDICTS = Object.freeze(['passed', 'partial', 'failed']);
@@ -48,6 +54,7 @@ export const CAPABILITY_TEST_PROMPTS = Object.freeze({
'Write a 350–500 word opening scene in close third person.',
'Keep the prose concrete and sensory. Include one spoken line of dialogue, the oyster farmer taking a consequential action, and a final turn that makes the sea wall the source of the dying water.',
].join('\n'),
+ 'rhetoric-reference': buildRhetoricReferencePrompt(),
});
/**
@@ -111,6 +118,15 @@ export const CAPABILITY_TESTS = Object.freeze([
blurb: 'Write a short opening scene from a fixed premise. Scored on required story facts plus minimum scene craft signals; read the saved prose for quality.',
driver: 'chat',
}),
+ Object.freeze({
+ id: 'rhetoric-reference',
+ label: 'Rhetoric evaluator',
+ kind: 'text',
+ capabilities: Object.freeze(['chat']),
+ prefers: Object.freeze(['reasoning']),
+ blurb: `Score ${RHETORIC_REFERENCE_SET.length} fictional, human-labelled rhetoric attempts. The result reports calibration error and agreement against the committed gold scores.`,
+ driver: 'chat',
+ }),
]);
export const CAPABILITY_TEST_IDS = Object.freeze(CAPABILITY_TESTS.map((t) => t.id));
diff --git a/server/lib/modelCapabilityTests.test.js b/server/lib/modelCapabilityTests.test.js
index 9e8d3b7647..ffcb212b39 100644
--- a/server/lib/modelCapabilityTests.test.js
+++ b/server/lib/modelCapabilityTests.test.js
@@ -17,6 +17,7 @@ import {
const visionTest = getCapabilityTest('image-analysis');
const sandboxTest = getCapabilityTest('sandbox-repair');
+const rhetoricTest = getCapabilityTest('rhetoric-reference');
describe('applicabilityFor', () => {
it('applies a test only where the model claims the capability', () => {
@@ -48,6 +49,15 @@ describe('applicabilityFor', () => {
expect(applicableTests(['chat', 'tools', 'vision']).map((t) => t.state))
.toEqual(CAPABILITY_TESTS.map(() => 'applicable'));
});
+
+ it('offers the rhetoric reference benchmark to chat-capable models', () => {
+ expect(rhetoricTest).toMatchObject({
+ kind: 'text',
+ capabilities: ['chat'],
+ driver: 'chat',
+ });
+ expect(applicabilityFor(rhetoricTest, ['chat']).state).toBe('applicable');
+ });
});
describe('scoreKeywords', () => {
diff --git a/server/lib/postRhetoric.js b/server/lib/postRhetoric.js
new file mode 100644
index 0000000000..319ed97616
--- /dev/null
+++ b/server/lib/postRhetoric.js
@@ -0,0 +1,220 @@
+import { z } from 'zod';
+import { EFFORT_LEVELS } from './providerModels.js';
+
+export const RHETORIC_MODE_IDS = Object.freeze([
+ 'meter',
+ 'diacope',
+ 'chiasmus',
+ 'progressia',
+ 'brainstorm',
+]);
+
+export const RHETORIC_DRILL_TYPES = Object.freeze(
+ RHETORIC_MODE_IDS.map((mode) => `rhetoric-${mode}`),
+);
+
+export const RHETORIC_EVALUATOR_RUBRIC_VERSION = 'rhetoric-evaluator-v1';
+
+export const RHETORIC_RUBRICS = Object.freeze({
+ meter: Object.freeze([
+ Object.freeze({ id: 'form', label: 'Meter and syllable control', instruction: 'Does the line make a credible attempt at ten syllables and a mostly rising da-DUM pulse?' }),
+ Object.freeze({ id: 'image', label: 'Concrete image or thought', instruction: 'Does the line give the reader a specific image, turn, or thought rather than a generic statement?' }),
+ Object.freeze({ id: 'sound', label: 'Line sound and finish', instruction: 'Does the line read naturally aloud and finish with a deliberate word or cadence?' }),
+ ]),
+ diacope: Object.freeze([
+ Object.freeze({ id: 'pattern', label: 'Separated repetition', instruction: 'Is a word or phrase repeated with meaningful material between its appearances?' }),
+ Object.freeze({ id: 'emphasis', label: 'Rhetorical force', instruction: 'Does the repetition add urgency, emphasis, or a changed implication?' }),
+ Object.freeze({ id: 'voice', label: 'Natural voice', instruction: 'Does the sentence remain clear, intentional, and alive when read aloud?' }),
+ ]),
+ chiasmus: Object.freeze([
+ Object.freeze({ id: 'reversal', label: 'Structural reversal', instruction: 'Are paired terms or structures presented again in reverse order?' }),
+ Object.freeze({ id: 'meaning', label: 'Meaningful turn', instruction: 'Does the reversal sharpen, complicate, or transform the thought?' }),
+ Object.freeze({ id: 'clarity', label: 'Clarity and balance', instruction: 'Can the sentence be understood without forcing the reader to decode the syntax?' }),
+ ]),
+ progressia: Object.freeze([
+ Object.freeze({ id: 'steps', label: 'Discernible steps', instruction: 'Are there at least three identifiable stages, images, or movements?' }),
+ Object.freeze({ id: 'escalation', label: 'Escalation or transformation', instruction: 'Does each stage intensify or transform what came before it?' }),
+ Object.freeze({ id: 'landing', label: 'Earned landing', instruction: 'Does the final phrase feel like a satisfying consequence rather than an arbitrary largest word?' }),
+ ]),
+ brainstorm: Object.freeze([
+ Object.freeze({ id: 'variety', label: 'Distinct angles', instruction: 'Are there at least three genuinely different approaches rather than one idea repeated?' }),
+ Object.freeze({ id: 'specificity', label: 'Specific language', instruction: 'Do the attempts contain concrete, usable images or claims?' }),
+ Object.freeze({ id: 'voltage', label: 'Unexpected turn', instruction: 'Does at least one version take a surprising, risky, or especially memorable angle?' }),
+ ]),
+});
+
+const rhetoricDimensionSchema = z.object({
+ id: z.string().trim().min(1).max(50),
+ score: z.number().int().min(0).max(100),
+ feedback: z.string().trim().min(1).max(1000),
+}).strict();
+
+const rhetoricEvaluationResponseSchema = z.object({
+ overallScore: z.number().int().min(0).max(100),
+ dimensions: z.array(rhetoricDimensionSchema).min(1).max(5),
+ summary: z.string().trim().min(1).max(2000),
+}).strict();
+
+export const rhetoricEvaluationSchema = rhetoricEvaluationResponseSchema.extend({
+ provenance: z.object({
+ rubricVersion: z.string().trim().min(1).max(100),
+ providerId: z.string().trim().min(1).max(300),
+ model: z.string().trim().min(1).max(300),
+ effort: z.enum(EFFORT_LEVELS).nullable(),
+ }).strict(),
+}).strict();
+
+export function validateRhetoricEvaluationPayload(mode, value) {
+ const parsed = rhetoricEvaluationResponseSchema.parse(value);
+ const rubric = RHETORIC_RUBRICS[mode];
+ if (!rubric) throw new Error(`Unknown rhetoric mode: ${mode}`);
+ const expectedIds = rubric.map((criterion) => criterion.id);
+ const actualIds = parsed.dimensions.map((dimension) => dimension.id);
+ if (actualIds.length !== expectedIds.length || new Set(actualIds).size !== actualIds.length
+ || expectedIds.some((id) => !actualIds.includes(id))) {
+ throw new Error(`Rhetoric evaluator returned the wrong dimensions for ${mode}`);
+ }
+ return parsed;
+}
+
+export function buildRhetoricEvaluatorPrompt({ mode, prompt, response }) {
+ const rubric = RHETORIC_RUBRICS[mode];
+ if (!rubric) throw new Error(`Unknown rhetoric mode: ${mode}`);
+ const rubricText = rubric.map((criterion) => `- ${criterion.id}: ${criterion.instruction}`).join('\n');
+ const dimensionShape = JSON.stringify({
+ overallScore: 0,
+ dimensions: rubric.map((criterion) => ({ id: criterion.id, score: 0, feedback: 'brief evidence' })),
+ summary: 'one concise paragraph',
+ });
+ return [
+ 'Evaluate one POST rhetoric-practice attempt as a careful writing coach.',
+ 'Use only the supplied prompt, attempt, and rubric. Do not reward length, confidence, or agreement with the evaluator.',
+ 'Score each dimension from 0 to 100, then give an overall score from 0 to 100. Be specific but concise.',
+ 'Return ONLY valid JSON. Do not use markdown or add keys outside this shape:',
+ dimensionShape,
+ `Mode: ${mode}`,
+ 'Rubric:',
+ rubricText,
+ `Practice prompt: ${prompt}`,
+ `Practice attempt: ${response}`,
+ ].join('\n\n');
+}
+
+// This is deliberately committed, fictional reference material rather than a
+// user's POST history. It is a small expert-labelled corpus: enough varied
+// examples to expose evaluator calibration, while still fitting in one bounded
+// local-model request. The reference responses are the material under test; the
+// expected scores are the gold labels, not part of the model prompt.
+export const RHETORIC_REFERENCE_SET = Object.freeze([
+ { id: 'meter-01', mode: 'meter', prompt: 'Write a line about an empty train station.', response: 'The last train sighs softly through the rain.', expectedScore: 86 },
+ { id: 'meter-02', mode: 'meter', prompt: 'Write a line that turns from doubt to hope.', response: 'I fear the dark, yet dawn is on its way.', expectedScore: 87 },
+ { id: 'meter-03', mode: 'meter', prompt: 'Write a line containing the word “winter”.', response: 'Winter lays its silver hand across the town.', expectedScore: 84 },
+ { id: 'meter-04', mode: 'meter', prompt: 'Write a line spoken by someone keeping a secret.', response: 'I keep the key where no one hears it turn.', expectedScore: 81 },
+ { id: 'meter-05', mode: 'meter', prompt: 'Write a line that ends on a strong one-syllable noun.', response: 'The empty platform waits beneath the moon.', expectedScore: 83 },
+ { id: 'meter-06', mode: 'meter', prompt: 'Write a line about a lighthouse.', response: 'The lighthouse blinks, then swallows up the dark.', expectedScore: 78 },
+ { id: 'meter-07', mode: 'meter', prompt: 'Write a line about an empty train station.', response: 'Train station empty I am sad today.', expectedScore: 28 },
+ { id: 'meter-08', mode: 'meter', prompt: 'Write a line containing the word “winter”.', response: 'Winter is cold and the station has a train.', expectedScore: 35 },
+
+ { id: 'diacope-01', mode: 'diacope', prompt: 'Write a warning using “stay”.', response: 'Stay, until the sirens learn our names. Stay.', expectedScore: 90 },
+ { id: 'diacope-02', mode: 'diacope', prompt: 'Write a plea using “listen”.', response: 'Listen, the room is listening back. Listen.', expectedScore: 87 },
+ { id: 'diacope-03', mode: 'diacope', prompt: 'Write a defiant line using “no”.', response: 'No, I will not bow to borrowed thunder. No.', expectedScore: 91 },
+ { id: 'diacope-04', mode: 'diacope', prompt: 'Write a comic line using “again”.', response: 'Again, the joke wore shoes and left the room. Again.', expectedScore: 79 },
+ { id: 'diacope-05', mode: 'diacope', prompt: 'Write a line about trust.', response: 'The key is trust, and trust is the key.', expectedScore: 31 },
+ { id: 'diacope-06', mode: 'diacope', prompt: 'Write a line using “run”.', response: 'Run run run.', expectedScore: 20 },
+ { id: 'diacope-07', mode: 'diacope', prompt: 'Write a plea using “listen”.', response: 'Please listen to my listen.', expectedScore: 30 },
+ { id: 'diacope-08', mode: 'diacope', prompt: 'Write a line about returning home.', response: 'Home, after all the roads, home.', expectedScore: 85 },
+
+ { id: 'chiasmus-01', mode: 'chiasmus', prompt: 'Write a line about learning that reverses its key terms.', response: 'We teach our questions, and our questions teach us.', expectedScore: 90 },
+ { id: 'chiasmus-02', mode: 'chiasmus', prompt: 'Turn a choice between freedom and safety into a crossed sentence.', response: 'Freedom needs safety, but safety needs freedom.', expectedScore: 83 },
+ { id: 'chiasmus-03', mode: 'chiasmus', prompt: 'Write a compact chiasmus about listening and speaking.', response: 'We speak to be heard, and listen to be understood.', expectedScore: 63 },
+ { id: 'chiasmus-04', mode: 'chiasmus', prompt: 'Use a reversal to show a friendship changing over time.', response: 'She changed the plan, and the plan changed her.', expectedScore: 88 },
+ { id: 'chiasmus-05', mode: 'chiasmus', prompt: 'Write a comic chiasmus about making plans and plans making trouble.', response: 'I make my schedule, then my schedule makes me.', expectedScore: 85 },
+ { id: 'chiasmus-06', mode: 'chiasmus', prompt: 'Write a line about plans and trouble.', response: 'Plans made trouble, and trouble made plans.', expectedScore: 66 },
+ { id: 'chiasmus-07', mode: 'chiasmus', prompt: 'Write a line about practice.', response: 'Learning is the point of practice, and practice is learning.', expectedScore: 70 },
+ { id: 'chiasmus-08', mode: 'chiasmus', prompt: 'Write a line about a cat and a mouse.', response: 'The cat chased the mouse and the mouse chased the cat.', expectedScore: 55 },
+
+ { id: 'progressia-01', mode: 'progressia', prompt: 'Escalate a whisper into a public alarm.', response: 'A whisper became a rumor, a rumor became a warning, a warning became a bell.', expectedScore: 92 },
+ { id: 'progressia-02', mode: 'progressia', prompt: 'Build a three-step progression from want to need to obsession.', response: 'I wanted a cup, then a pot, then the whole river.', expectedScore: 81 },
+ { id: 'progressia-03', mode: 'progressia', prompt: 'Turn a small kindness into a changed life.', response: 'Kindness warmed a hand, a home, a street.', expectedScore: 78 },
+ { id: 'progressia-04', mode: 'progressia', prompt: 'Escalate a disagreement without using the word “anger”.', response: 'The quarrel sharpened to a shout, a shove, a slammed door.', expectedScore: 82 },
+ { id: 'progressia-05', mode: 'progressia', prompt: 'Build from a single drop of water to a flood.', response: 'A drop became a stream, a stream became a river, a river took the road.', expectedScore: 90 },
+ { id: 'progressia-06', mode: 'progressia', prompt: 'Build a progression from noticing to action.', response: 'First I noticed it, then I thought about it.', expectedScore: 35 },
+ { id: 'progressia-07', mode: 'progressia', prompt: 'Escalate a simple idea.', response: 'Big, bigger, biggest.', expectedScore: 45 },
+ { id: 'progressia-08', mode: 'progressia', prompt: 'Build from wanting something to obsession.', response: 'He wanted things and got more things.', expectedScore: 22 },
+
+ { id: 'brainstorm-01', mode: 'brainstorm', prompt: 'Brainstorm three openings for a story about a locked room.', response: 'Locked room: a witness, a coffin, a seed vault.', expectedScore: 88 },
+ { id: 'brainstorm-02', mode: 'brainstorm', prompt: 'Argue for, against, and sideways about convenience.', response: 'Convenience is a gift, a trap, and a habit wearing a smile.', expectedScore: 86 },
+ { id: 'brainstorm-03', mode: 'brainstorm', prompt: 'Find three metaphors for a difficult conversation.', response: 'A bridge under repair, a knot, a weather report.', expectedScore: 84 },
+ { id: 'brainstorm-04', mode: 'brainstorm', prompt: 'Write three headlines for the same surprising event.', response: 'Local Door Refuses to Open; Room Wins Standoff; Key Takes the Day Off.', expectedScore: 91 },
+ { id: 'brainstorm-05', mode: 'brainstorm', prompt: 'Describe one ordinary object as sacred, dangerous, and ridiculous.', response: 'A spoon: a chalice, a weapon, a tiny mirror.', expectedScore: 89 },
+ { id: 'brainstorm-06', mode: 'brainstorm', prompt: 'Brainstorm three openings for a story about a locked room.', response: 'Locked room. Another locked room. A room is locked.', expectedScore: 25 },
+ { id: 'brainstorm-07', mode: 'brainstorm', prompt: 'Argue for and against convenience.', response: 'Convenience is good and bad.', expectedScore: 30 },
+ { id: 'brainstorm-08', mode: 'brainstorm', prompt: 'Describe one ordinary object in three surprising ways.', response: 'Sacred, dangerous, ridiculous: a mug, a mug, a mug.', expectedScore: 38 },
+]);
+
+const rhetoricReferenceResponseSchema = z.object({
+ evaluations: z.array(z.object({
+ id: z.string().trim().min(1).max(100),
+ score: z.number().min(0).max(100),
+ }).strict()).min(1).max(RHETORIC_REFERENCE_SET.length),
+}).strict();
+
+export function buildRhetoricReferencePrompt(referenceSet = RHETORIC_REFERENCE_SET) {
+ const examples = referenceSet.map(({ id, mode, prompt, response }) => ({ id, mode, prompt, response }));
+ return [
+ 'You are being benchmarked as a rhetoric-practice evaluator.',
+ 'Score every reference attempt from 0 to 100 using the mode-specific criteria below.',
+ 'Judge the attempt against its prompt. Do not infer hidden intent, and do not omit any item.',
+ 'Return ONLY valid JSON with exactly one evaluation for every id:',
+ '{"evaluations":[{"id":"meter-01","score":0}]}',
+ 'Criteria:',
+ Object.entries(RHETORIC_RUBRICS).map(([mode, rubric]) => `${mode}: ${rubric.map((criterion) => criterion.instruction).join(' ')}`).join('\n'),
+ 'Reference attempts:',
+ JSON.stringify(examples),
+ ].join('\n\n');
+}
+
+export function parseRhetoricJson(content) {
+ if (!content || typeof content !== 'string') throw new Error('Empty rhetoric evaluator response');
+ let json = content.trim();
+ const fenced = json.match(/```(?:json)?\s*([\s\S]*?)```/);
+ if (fenced) json = fenced[1].trim();
+ const object = json.match(/(\{[\s\S]*\})/);
+ if (object) json = object[1];
+ return JSON.parse(json);
+}
+
+export function scoreRhetoricReference(value, referenceSet = RHETORIC_REFERENCE_SET) {
+ const parsed = rhetoricReferenceResponseSchema.parse(value);
+ const expectedIds = referenceSet.map((item) => item.id);
+ const predictions = new Map(parsed.evaluations.map((item) => [item.id, item.score]));
+ if (predictions.size !== parsed.evaluations.length || predictions.size !== expectedIds.length
+ || expectedIds.some((id) => !predictions.has(id))) {
+ throw new Error(`Rhetoric reference evaluator returned ${predictions.size} of ${expectedIds.length} unique ids`);
+ }
+ const items = referenceSet.map((item) => ({
+ id: item.id,
+ expected: item.expectedScore,
+ predicted: Math.round(predictions.get(item.id)),
+ absoluteError: Math.abs(Math.round(predictions.get(item.id)) - item.expectedScore),
+ }));
+ const meanAbsoluteError = Math.round(items.reduce((sum, item) => sum + item.absoluteError, 0) / items.length * 10) / 10;
+ const within10Count = items.filter((item) => item.absoluteError <= 10).length;
+ const within20Count = items.filter((item) => item.absoluteError <= 20).length;
+ const within20Rate = within20Count / items.length;
+ const verdict = meanAbsoluteError <= 12 && within20Rate >= 0.8
+ ? 'passed'
+ : (meanAbsoluteError <= 25 && within20Rate >= 0.6 ? 'partial' : 'failed');
+ return {
+ verdict,
+ summary: `${items.length} reference attempts; mean absolute error ${meanAbsoluteError} points; ${within20Count}/${items.length} within 20 points`,
+ referenceCount: referenceSet.length,
+ evaluatedCount: items.length,
+ meanAbsoluteError,
+ within10Count,
+ within20Count,
+ within10Rate: Math.round(within10Count / items.length * 1000) / 1000,
+ within20Rate: Math.round(within20Rate * 1000) / 1000,
+ items,
+ };
+}
diff --git a/server/lib/postRhetoric.test.js b/server/lib/postRhetoric.test.js
new file mode 100644
index 0000000000..235fc9c64d
--- /dev/null
+++ b/server/lib/postRhetoric.test.js
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildRhetoricEvaluatorPrompt,
+ buildRhetoricReferencePrompt,
+ parseRhetoricJson,
+ RHETORIC_REFERENCE_SET,
+ RHETORIC_RUBRICS,
+ scoreRhetoricReference,
+ validateRhetoricEvaluationPayload,
+} from './postRhetoric.js';
+
+describe('rhetoric evaluator contract', () => {
+ it('keeps a sizeable, fictional gold corpus across every practice mode', () => {
+ expect(RHETORIC_REFERENCE_SET).toHaveLength(40);
+ expect(new Set(RHETORIC_REFERENCE_SET.map((item) => item.mode))).toEqual(new Set(Object.keys(RHETORIC_RUBRICS)));
+ expect(new Set(RHETORIC_REFERENCE_SET.map((item) => item.id)).size).toBe(40);
+ });
+
+ it('does not leak gold labels into the benchmark prompt', () => {
+ const prompt = buildRhetoricReferencePrompt();
+ expect(prompt).toContain('meter-01');
+ expect(prompt).toContain('Return ONLY valid JSON');
+ expect(prompt).not.toContain('"expectedScore"');
+ });
+
+ it('requires the exact rubric dimensions for an attempt', () => {
+ const payload = validateRhetoricEvaluationPayload('meter', {
+ overallScore: 82,
+ dimensions: RHETORIC_RUBRICS.meter.map((criterion) => ({
+ id: criterion.id,
+ score: 82,
+ feedback: 'Specific evidence.',
+ })),
+ summary: 'A credible line with a deliberate image.',
+ });
+ expect(payload.dimensions).toHaveLength(3);
+ expect(() => validateRhetoricEvaluationPayload('meter', {
+ ...payload,
+ dimensions: payload.dimensions.slice(0, 2),
+ })).toThrow(/wrong dimensions/i);
+ });
+
+ it('parses fenced evaluator JSON and scores perfect reference agreement', () => {
+ const parsed = parseRhetoricJson('```json\n{"evaluations":[{"id":"x","score":50}]}\n```');
+ expect(parsed.evaluations[0]).toEqual({ id: 'x', score: 50 });
+ const scored = scoreRhetoricReference({
+ evaluations: RHETORIC_REFERENCE_SET.map(({ id, expectedScore }) => ({ id, score: expectedScore })),
+ });
+ expect(scored.verdict).toBe('passed');
+ expect(scored.meanAbsoluteError).toBe(0);
+ expect(scored.within20Count).toBe(40);
+ });
+
+ it('marks broad calibration drift partial instead of treating one average as enough', () => {
+ const scored = scoreRhetoricReference({
+ evaluations: RHETORIC_REFERENCE_SET.map(({ id, expectedScore }) => ({ id, score: Math.max(0, expectedScore - 18) })),
+ });
+ expect(scored.verdict).toBe('partial');
+ expect(scored.meanAbsoluteError).toBe(18);
+ expect(scored.within20Count).toBe(40);
+ });
+
+ it('includes the selected attempt in the live evaluation prompt', () => {
+ const prompt = buildRhetoricEvaluatorPrompt({ mode: 'chiasmus', prompt: 'Reverse a pair of terms.', response: 'We shape tools, and tools shape us.' });
+ expect(prompt).toContain('Mode: chiasmus');
+ expect(prompt).toContain('Reverse a pair of terms.');
+ expect(prompt).toContain('We shape tools, and tools shape us.');
+ });
+});
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index ddf7243683..36a8f005c3 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -4,6 +4,8 @@ import { COGNITIVE_DRILL_TYPES } from '../services/meatspacePostCognitive.js';
import { TOPIC_IDS } from './postTopics.js';
import { HHMM_STRICT_RE } from './timezone.js';
import { POST_LLM_MAX_SEMANTIC_CANDIDATES, postLlmEvaluationSchema } from './postLlmContracts.js';
+import { EFFORT_LEVELS } from './providerModels.js';
+import { RHETORIC_DRILL_TYPES, RHETORIC_MODE_IDS, rhetoricEvaluationSchema } from './postRhetoric.js';
// =============================================================================
// POST (Power On Self Test) VALIDATION SCHEMAS
@@ -126,10 +128,9 @@ const DRILL_TYPES = [...MATH_DRILL_TYPES, ...LLM_DRILL_TYPES, ...MEMORY_DRILL_TY
// of being rejected. Morse and rhetoric only ever post through
// trainingEntrySchema below.
const MORSE_DRILL_TYPES = ['morse-copy', 'morse-head-copy', 'morse-send'];
-// Rhetoric is a standalone, self-assessed training surface. It never enters a
-// scored POST session or calls an LLM, but its rounds still use the shared
-// training log endpoint for streaks and progress reporting.
-const RHETORIC_DRILL_TYPES = ['rhetoric-meter', 'rhetoric-diacope', 'rhetoric-chiasmus', 'rhetoric-progressia', 'rhetoric-brainstorm'];
+// Rhetoric is a standalone training surface. It never enters a scored POST
+// session; its self-score and optional evaluator report use the shared training
+// log endpoint for streaks and progress reporting.
const drillTypeConfigSchema = z.object({
enabled: z.boolean().optional(),
@@ -336,6 +337,20 @@ const llmDrillTypeConfigSchema = z.object({
model: z.string().optional()
});
+// The evaluator is deliberately a separate opt-in block. Saving a provider or
+// effort here must never make an existing POST screen start spending tokens:
+// callers still have to set `enabled: true`, and the default config keeps it
+// false.
+export const postRhetoricEvaluatorConfigSchema = z.object({
+ enabled: z.boolean().optional(),
+ providerId: z.string().trim().max(300).nullable().optional(),
+ model: z.string().trim().max(300).nullable().optional(),
+ effort: z.preprocess(
+ value => (value === '' ? undefined : value),
+ z.enum(EFFORT_LEVELS).nullable().optional(),
+ ),
+});
+
// Optional practice goals (issue #2100). Every field is optional so a config
// with no goals — or a legacy config that predates this block entirely — stays
// valid; bounds keep a hand-edited config from persisting a nonsensical target.
@@ -359,6 +374,7 @@ export const postConfigUpdateSchema = z.object({
model: z.string().nullable().optional(),
drillTypes: z.record(z.enum(LLM_DRILL_TYPES), llmDrillTypeConfigSchema).optional()
}).optional(),
+ rhetoricEvaluator: postRhetoricEvaluatorConfigSchema.optional(),
// Deterministic cognitive drills — no provider, so no provider/model fields.
// Partial so an older browser's complete pre-executive-control map remains a
// valid patch after newer drill types are added to the enum (Zod 4 records
@@ -453,6 +469,22 @@ export const postLlmScoreRequestSchema = z.object({
}
});
+// One attempt is sent at a time by the trainer. The browser deliberately does
+// not await this request before advancing to the next prompt, so this is a
+// bounded single-item contract rather than a batch evaluator endpoint.
+export const postRhetoricEvaluationRequestSchema = z.object({
+ attemptId: z.string().trim().min(1).max(200),
+ mode: z.enum(RHETORIC_MODE_IDS),
+ prompt: z.string().trim().min(1).max(1000),
+ response: z.string().trim().min(1).max(10000),
+ providerId: z.string().trim().min(1).max(300).optional(),
+ model: z.string().trim().min(1).max(300).optional(),
+ effort: z.preprocess(
+ value => (value === '' ? undefined : value),
+ z.enum(EFFORT_LEVELS).nullable().optional(),
+ ),
+});
+
// Explicit, user-consented request to warm the wordplay drill cache
export const postDrillCacheFillSchema = z.object({
types: z.array(z.enum(CACHEABLE_TYPES)).min(1).optional(),
@@ -646,13 +678,17 @@ export const postProgressQuerySchema = z.object({
// future progress dashboard can render training-log and scored-session
// breakdowns with the same renderer rather than inventing a training-only shape.
const trainingQuestionSchema = z.object({
+ id: z.string().min(1).max(200).optional(),
prompt: z.string().optional(),
response: z.string().optional(),
items: z.array(z.string()).optional(),
responseMs: z.number().min(0).optional(),
+ selfRating: z.number().int().min(1).max(5).optional(),
score: z.number().min(0).max(100).optional(),
feedback: z.string().optional(),
correct: z.boolean().optional(),
+ evaluation: rhetoricEvaluationSchema.optional(),
+ evaluationError: z.string().max(500).optional(),
});
// Training log entry submission
diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.js
index e0b06e0ff5..5892df01a2 100644
--- a/server/lib/postValidation.test.js
+++ b/server/lib/postValidation.test.js
@@ -16,7 +16,9 @@ import {
postQuickSessionPlanSchema,
postBenchmarkSchema,
postConditionsSchema,
+ postRhetoricEvaluationRequestSchema,
} from './postValidation.js';
+import { RHETORIC_RUBRICS } from './postRhetoric.js';
import { getTopic, POST_TOPICS } from './postTopics.js';
describe('postBenchmarkSchema', () => {
@@ -166,6 +168,36 @@ describe('postConfigUpdateSchema llmDrills', () => {
});
});
+describe('rhetoric evaluator configuration', () => {
+ it('accepts an explicit provider, model, and effort without making the block required', () => {
+ const parsed = postConfigUpdateSchema.parse({
+ rhetoricEvaluator: { enabled: true, providerId: 'example-provider', model: 'example-model', effort: 'high' },
+ });
+ expect(parsed.rhetoricEvaluator).toEqual({
+ enabled: true, providerId: 'example-provider', model: 'example-model', effort: 'high',
+ });
+ expect(postConfigUpdateSchema.parse({}).rhetoricEvaluator).toBeUndefined();
+ });
+
+ it('accepts an empty effort sentinel as absent', () => {
+ expect(postConfigUpdateSchema.parse({ rhetoricEvaluator: { effort: '' } }).rhetoricEvaluator).toEqual({});
+ });
+
+ it('bounds one background evaluation request', () => {
+ const parsed = postRhetoricEvaluationRequestSchema.parse({
+ attemptId: 'round-1:1',
+ mode: 'meter',
+ prompt: 'Write a line about an empty station.',
+ response: 'The last train sighs softly through the rain.',
+ providerId: 'example-provider',
+ model: 'example-model',
+ effort: 'high',
+ });
+ expect(parsed.mode).toBe('meter');
+ expect(() => postRhetoricEvaluationRequestSchema.parse({ ...parsed, mode: 'not-a-mode' })).toThrow();
+ });
+});
+
describe('postConfigUpdateSchema cognitive compatibility', () => {
it('accepts a legacy six-drill map after newer cognitive types are added', () => {
const legacyTypes = ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'];
@@ -297,6 +329,32 @@ describe('trainingEntrySchema per-question breakdown (issue #2114)', () => {
questions: [{ prompt: 'x', score: 150 }],
})).toThrow();
});
+
+ it('accepts a rhetoric question with a validated evaluator report', () => {
+ const parsed = trainingEntrySchema.parse({
+ module: 'rhetoric',
+ drillType: 'rhetoric-meter',
+ questionCount: 1,
+ correctCount: 1,
+ totalMs: 1000,
+ questions: [{
+ id: 'round-1:1',
+ prompt: 'Write a line about an empty station.',
+ response: 'The last train sighs softly through the rain.',
+ responseMs: 900,
+ selfRating: 5,
+ score: 100,
+ correct: true,
+ evaluation: {
+ overallScore: 84,
+ dimensions: RHETORIC_RUBRICS.meter.map(({ id }) => ({ id, score: 84, feedback: 'Specific evidence.' })),
+ summary: 'A strong attempt.',
+ provenance: { rubricVersion: 'rhetoric-evaluator-v1', providerId: 'example-provider', model: 'example-model', effort: 'high' },
+ },
+ }],
+ });
+ expect(parsed.questions[0].evaluation.provenance.model).toBe('example-model');
+ });
});
describe('questionResultSchema chunkId/element (issue #2016)', () => {
diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.js
index a8e57d5336..df129cc064 100644
--- a/server/routes/meatspacePostRoutes.js
+++ b/server/routes/meatspacePostRoutes.js
@@ -13,6 +13,7 @@ import {
postConfigUpdateSchema,
postDrillRequestSchema,
postLlmScoreRequestSchema,
+ postRhetoricEvaluationRequestSchema,
postDrillCacheFillSchema,
memoryItemCreateSchema,
memoryItemUpdateSchema,
@@ -30,6 +31,7 @@ import {
import * as postService from '../services/meatspacePost.js';
import * as memoryService from '../services/meatspacePostMemory.js';
import { generateLlmDrill, scoreLlmDrill } from '../services/meatspacePostLlm.js';
+import { evaluateRhetoricAttempt } from '../services/meatspacePostRhetoric.js';
import { getCachedDrill, triggerReplenish, getCacheStats, requestCacheFill } from '../services/meatspacePostDrillCache.js';
import * as trainingService from '../services/meatspacePostTraining.js';
import * as morseService from '../services/meatspacePostMorse.js';
@@ -277,6 +279,17 @@ router.post('/post/score-llm', asyncHandler(async (req, res) => {
res.json(result);
}));
+/**
+ * POST /api/meatspace/post/rhetoric/evaluate
+ * Evaluate one rhetoric attempt. The client advances before awaiting this
+ * response, and serializes its own requests so a local provider is not flooded.
+ */
+router.post('/post/rhetoric/evaluate', asyncHandler(async (req, res) => {
+ const data = validateRequest(postRhetoricEvaluationRequestSchema, req.body);
+ const result = await evaluateRhetoricAttempt(data);
+ res.json(result);
+}));
+
/**
* GET /api/meatspace/post/drill-cache/status
* Per-type cache counts for the wordplay drill cache, so the client can
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index a7badd58fd..8abb2b0007 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -231,6 +231,15 @@ const DEFAULT_CONFIG = {
'pun-wordplay': { enabled: true, count: 5, timeLimitSec: 120 }
}
},
+ // Optional AI judging for the standalone rhetoric trainer. It is explicitly
+ // off by default so loading POST or opening the practice page never queues a
+ // provider call without a user opting in and saving this block.
+ rhetoricEvaluator: {
+ enabled: false,
+ providerId: null,
+ model: null,
+ effort: null,
+ },
// Deterministic cognitive drills (working-memory / attention / inhibition).
// No provider calls — enabled by default since they're free to run. No
// timeLimitSec — these drills are self-paced/stimulus-driven and never
diff --git a/server/services/meatspacePostLlm.js b/server/services/meatspacePostLlm.js
index 6f624a29b5..9bda7bb490 100644
--- a/server/services/meatspacePostLlm.js
+++ b/server/services/meatspacePostLlm.js
@@ -43,7 +43,7 @@ export const LLM_DRILL_TYPES = [
// AI CALLER (mirrors brain.js pattern)
// ─────────────────────────────────────────────────────────────────────────────
-async function callAI(prompt, providerId, model) {
+export async function callAI(prompt, providerId, model, effort = null, source = 'meatspace-post-llm') {
const provider = providerId
? await getProviderById(providerId)
: await getActiveProvider();
@@ -53,7 +53,7 @@ async function callAI(prompt, providerId, model) {
}
const selectedModel = model || provider.defaultModel;
- console.log(`🧪 POST LLM drill: ${provider.id} / ${selectedModel}`);
+ console.log(`🧪 POST LLM: ${provider.id} / ${selectedModel}`);
// Append headlessArgs so claude-code's POST drills don't pollute the
// user's session list. The clone leaves the saved provider config
@@ -64,7 +64,7 @@ async function callAI(prompt, providerId, model) {
: provider;
const result = await runPromptThroughProvider({
- provider: providerForCall, prompt, source: 'meatspace-post-llm', model: selectedModel,
+ provider: providerForCall, prompt, source, model: selectedModel, effort,
timeout: provider.timeout || 120000,
});
return {
@@ -74,7 +74,7 @@ async function callAI(prompt, providerId, model) {
};
}
-function parseJsonFromAI(content) {
+export function parseJsonFromAI(content) {
if (!content || typeof content !== 'string') throw new Error('Empty AI response');
let jsonStr = content.trim();
// Strip fenced code blocks
diff --git a/server/services/meatspacePostLlm.test.js b/server/services/meatspacePostLlm.test.js
index 214187e737..d3b2342e11 100644
--- a/server/services/meatspacePostLlm.test.js
+++ b/server/services/meatspacePostLlm.test.js
@@ -38,7 +38,8 @@ import {
generateStoryPrompt,
generateInventionPitch,
generateReframe,
- scoreLlmDrill
+ scoreLlmDrill,
+ callAI,
} from './meatspacePostLlm.js';
// Helper: mock an API provider that returns a given JSON string. Sets the
@@ -106,6 +107,17 @@ describe('LLM_DRILL_TYPES', () => {
});
});
+describe('callAI', () => {
+ it('passes an explicit effort and source through the shared runner', async () => {
+ mockApiProvider({ ok: true });
+ await callAI('Evaluate this attempt.', 'test-provider', 'test-model', 'high', 'meatspace-post-rhetoric-evaluator');
+ expect(runPromptThroughProvider).toHaveBeenCalledWith(expect.objectContaining({
+ effort: 'high',
+ source: 'meatspace-post-rhetoric-evaluator',
+ }));
+ });
+});
+
// =============================================================================
// WORD ASSOCIATION
// =============================================================================
diff --git a/server/services/meatspacePostRhetoric.js b/server/services/meatspacePostRhetoric.js
new file mode 100644
index 0000000000..68a94341b3
--- /dev/null
+++ b/server/services/meatspacePostRhetoric.js
@@ -0,0 +1,50 @@
+import { callAI, parseJsonFromAI } from './meatspacePostLlm.js';
+import {
+ buildRhetoricEvaluatorPrompt,
+ rhetoricEvaluationSchema,
+ RHETORIC_EVALUATOR_RUBRIC_VERSION,
+ validateRhetoricEvaluationPayload,
+} from '../lib/postRhetoric.js';
+
+/**
+ * Evaluate one captured rhetoric attempt.
+ *
+ * The route intentionally owns no queue: the trainer serializes these calls in
+ * the background so the next prompt can render immediately, while this bounded
+ * request still records a complete provider/model/effort provenance object for
+ * the round's final training entry.
+ */
+export async function evaluateRhetoricAttempt({
+ attemptId,
+ mode,
+ prompt,
+ response,
+ providerId,
+ model,
+ effort,
+}) {
+ const startedAt = Date.now();
+ const aiResponse = await callAI(
+ buildRhetoricEvaluatorPrompt({ mode, prompt, response }),
+ providerId,
+ model,
+ effort,
+ 'meatspace-post-rhetoric-evaluator',
+ );
+ const payload = validateRhetoricEvaluationPayload(mode, parseJsonFromAI(aiResponse.text));
+ const evaluation = rhetoricEvaluationSchema.parse({
+ ...payload,
+ provenance: {
+ rubricVersion: RHETORIC_EVALUATOR_RUBRIC_VERSION,
+ providerId: aiResponse.providerId,
+ model: aiResponse.model,
+ effort: effort || null,
+ },
+ });
+ return {
+ attemptId,
+ mode,
+ evaluation,
+ elapsedMs: Math.max(0, Date.now() - startedAt),
+ };
+}
diff --git a/server/services/meatspacePostRhetoric.test.js b/server/services/meatspacePostRhetoric.test.js
new file mode 100644
index 0000000000..b344918a4b
--- /dev/null
+++ b/server/services/meatspacePostRhetoric.test.js
@@ -0,0 +1,54 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('./meatspacePostLlm.js', () => ({
+ callAI: vi.fn(),
+ parseJsonFromAI: vi.fn(),
+}));
+
+import { callAI, parseJsonFromAI } from './meatspacePostLlm.js';
+import { RHETORIC_RUBRICS } from '../lib/postRhetoric.js';
+import { evaluateRhetoricAttempt } from './meatspacePostRhetoric.js';
+
+describe('evaluateRhetoricAttempt', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('returns a validated report with provider/model/effort provenance', async () => {
+ callAI.mockResolvedValue({ text: '{}', providerId: 'example-provider', model: 'example-model' });
+ parseJsonFromAI.mockReturnValue({
+ overallScore: 84,
+ dimensions: RHETORIC_RUBRICS.meter.map(({ id }) => ({ id, score: 84, feedback: 'A concrete observation.' })),
+ summary: 'A strong attempt with a clear image.',
+ });
+
+ const result = await evaluateRhetoricAttempt({
+ attemptId: 'round-1:1',
+ mode: 'meter',
+ prompt: 'Write a line about an empty train station.',
+ response: 'The last train sighs softly through the rain.',
+ providerId: 'example-provider',
+ model: 'example-model',
+ effort: 'high',
+ });
+
+ expect(result).toMatchObject({
+ attemptId: 'round-1:1',
+ mode: 'meter',
+ evaluation: {
+ overallScore: 84,
+ provenance: {
+ rubricVersion: 'rhetoric-evaluator-v1',
+ providerId: 'example-provider',
+ model: 'example-model',
+ effort: 'high',
+ },
+ },
+ });
+ expect(callAI).toHaveBeenCalledWith(
+ expect.stringContaining('The last train sighs softly through the rain.'),
+ 'example-provider',
+ 'example-model',
+ 'high',
+ 'meatspace-post-rhetoric-evaluator',
+ );
+ });
+});
diff --git a/server/services/modelCapabilityTests.js b/server/services/modelCapabilityTests.js
index 89cfe3258a..9103780f24 100644
--- a/server/services/modelCapabilityTests.js
+++ b/server/services/modelCapabilityTests.js
@@ -3,7 +3,7 @@
*
* The assessments panel next door answers "how fast is this model here". This
* one answers the question speed cannot: **can it actually do what its badges
- * claim?** Four tests, each bound to the capability badges the install catalog
+ * claim?** Five tests, each bound to the capability badges the install catalog
* already shows, each keeping the model's full output:
*
* - `sandbox-repair` (`tools`) — a broken module and its failing test are
@@ -59,6 +59,7 @@ import {
applicableTests, getCapabilityTest,
scoreKeywords, scoreFictionScene, scoreStoryBeats, scoreSandboxRepair, rollUpVerdict,
} from '../lib/modelCapabilityTests.js';
+import { parseRhetoricJson, scoreRhetoricReference } from '../lib/postRhetoric.js';
import { listRuntimeModels, runtimeEndpoint, runtimeApiKey } from './localModelAssessments.js';
import { runLocalLlmTest, runEndpointLlmTest } from './localLlmPlayground.js';
import { listProviders } from './providers.js';
@@ -242,6 +243,14 @@ const CHAT_TESTS = {
images: async () => undefined,
score: (text) => scoreFictionScene(text, FICTION_SCENE_KEYWORDS),
},
+ 'rhetoric-reference': {
+ // Forty compact reference attempts plus one JSON score per item fit within
+ // this budget while leaving room for short evidence-free score output.
+ maxTokens: 5000,
+ message: (modelId) => `Scoring the rhetoric reference set with ${modelId}…`,
+ images: async () => undefined,
+ score: (text) => scoreRhetoricReference(parseRhetoricJson(text)),
+ },
};
async function runChatTest({ backend, modelId, testId, signal, emit }) {
@@ -396,6 +405,7 @@ const RUNNERS = {
'image-analysis': runChatTest,
'story-outline': runChatTest,
'fiction-scene': runChatTest,
+ 'rhetoric-reference': runChatTest,
'sandbox-repair': runSandboxRepair,
};
diff --git a/server/services/modelCapabilityTests.test.js b/server/services/modelCapabilityTests.test.js
index 855e0e1597..a0a9251c03 100644
--- a/server/services/modelCapabilityTests.test.js
+++ b/server/services/modelCapabilityTests.test.js
@@ -61,6 +61,7 @@ const {
resolveModelCapabilities, SANDBOX_FILES, __resetFixtureCaches,
} = await import('./modelCapabilityTests.js');
const { loadResults } = await import('./modelCapabilityTestStore.js');
+const { RHETORIC_REFERENCE_SET } = await import('../lib/postRhetoric.js');
const OPENCODE_LLAMA = {
id: 'opencode-llama-tui', name: 'OpenCode llama TUI', type: 'tui', command: 'opencode', args: [], llamaBacked: true,
@@ -229,6 +230,23 @@ describe('runCapabilityTest — fiction scene', () => {
});
});
+describe('runCapabilityTest — rhetoric reference set', () => {
+ it('scores the evaluator against every committed gold label', async () => {
+ runLocalLlmTest.mockResolvedValue({
+ text: JSON.stringify({
+ evaluations: RHETORIC_REFERENCE_SET.map(({ id, expectedScore }) => ({ id, score: expectedScore })),
+ }),
+ timings: { totalMs: 900 },
+ });
+ const record = await runCapabilityTest({ backend: 'ollama', modelId: 'writer', testId: 'rhetoric-reference' });
+
+ expect(record.verdict).toBe('passed');
+ expect(record.detail.referenceCount).toBe(RHETORIC_REFERENCE_SET.length);
+ expect(record.detail.meanAbsoluteError).toBe(0);
+ expect(runLocalLlmTest.mock.calls[0][0].prompt).toContain('meter-01');
+ });
+});
+
describe('runCapabilityTest — sandbox repair', () => {
beforeEach(() => {
getAllProviders.mockResolvedValue({ activeProvider: null, providers: [OPENCODE_LLAMA] });