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 applied numeracy drills to POST (#4443) (#4509)

[._.]/ Adam Eivyf021a622872d
diff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsx
index 719b15e953..c4e33da16f 100644
--- a/client/src/components/meatspace/post/PostDrillConfig.jsx
+++ b/client/src/components/meatspace/post/PostDrillConfig.jsx
@@ -89,10 +89,28 @@ const DRILL_META = {
{ key: 'tolerancePct', label: 'Tolerance %', type: 'number', min: 1, max: 50 },
{ key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 600 }
]
+ },
+ 'applied-numeracy': {
+ label: 'Applied Numeracy',
+ desc: 'Everyday percentages, ratios, units, rates, and estimation',
+ fields: [
+ { key: 'count', label: 'Questions', type: 'number', min: 1, max: 20 },
+ { key: 'difficulty', label: 'Complexity Level', type: 'number', min: 1, max: 3 },
+ { key: 'family', label: 'Scenario Family', type: 'select', options: [
+ { value: 'mixed', label: 'Mixed' },
+ { value: 'percentage', label: 'Percentages' },
+ { value: 'ratio', label: 'Ratios' },
+ { value: 'unit', label: 'Units' },
+ { value: 'rate', label: 'Rates' },
+ { value: 'estimate', label: 'Estimation' },
+ ] },
+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 600 }
+ ]
}
};
const MATH_TYPES = Object.keys(DRILL_META);
+const MATH_STRING_FIELDS = new Set(['family']);
// LLM drill config meta for all 14 generatable types.
// `defaults.count` mirrors the server (`server/services/meatspacePostLlm.js`,
@@ -716,7 +734,7 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {
function updateField(type, key, value) {
const coerced = value === '' || value === null || value === undefined
? undefined
- : Number(value);
+ : MATH_STRING_FIELDS.has(key) ? value : Number(value);
setDrillTypes(prev => ({
...prev,
[type]: { ...prev[type], [key]: coerced }
diff --git a/client/src/components/meatspace/post/PostDrillConfig.test.jsx b/client/src/components/meatspace/post/PostDrillConfig.test.jsx
index 2d4b1ba708..645b14cbe9 100644
--- a/client/src/components/meatspace/post/PostDrillConfig.test.jsx
+++ b/client/src/components/meatspace/post/PostDrillConfig.test.jsx
@@ -109,6 +109,19 @@ async function saveConfig() {
}
describe('PostDrillConfig', () => {
+ it('persists Applied Numeracy complexity and scenario family settings', async () => {
+ await renderConfig(<PostDrillConfig config={config} onSaved={vi.fn()} onBack={vi.fn()} />);
+ fireEvent.change(screen.getByLabelText('Complexity Level'), { target: { value: '3' } });
+ fireEvent.change(screen.getByLabelText('Scenario Family'), { target: { value: 'unit' } });
+
+ await saveConfig();
+
+ expect(updatePostConfig.mock.calls[0][0].mentalMath.drillTypes['applied-numeracy']).toMatchObject({
+ difficulty: 3,
+ family: 'unit',
+ });
+ });
+
it('renders a card for every one of the 14 LLM drill types', async () => {
await renderConfig(<PostDrillConfig config={config} onSaved={vi.fn()} onBack={vi.fn()} />);
for (const type of ALL_LLM_TYPES) {
diff --git a/client/src/components/meatspace/post/PostDrillRunner.jsx b/client/src/components/meatspace/post/PostDrillRunner.jsx
index cc7fd7ced8..1e1866cc34 100644
--- a/client/src/components/meatspace/post/PostDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostDrillRunner.jsx
@@ -17,6 +17,16 @@ function PowersLesson({ prompt }) {
);
}
+function AppliedNumeracyLesson({ method }) {
+ if (!method) return null;
+ return (
+ <div className="mt-3 w-full max-w-md rounded-lg border border-port-accent/30 bg-port-bg p-3 text-left text-sm text-gray-300">
+ <div className="mb-1 text-xs font-semibold text-port-accent">Shortest method</div>
+ {method}
+ </div>
+ );
+}
+
export default function PostDrillRunner({ session }) {
const {
currentDrill,
@@ -112,6 +122,7 @@ export default function PostDrillRunner({ session }) {
// MEMORY_DRILL_TYPES now includes 'memory-fill-blank' (issue #2099/#2116),
// so the explicit extra check this used to need is gone.
const isTextDrill = MEMORY_DRILL_TYPES.includes(currentDrill.type);
+ const isAppliedNumeracy = currentDrill.type === 'applied-numeracy';
const timePct = timeLimitMs > 0 ? (timeLeft / timeLimitMs) * 100 : 0;
const progressPct = totalQuestions > 0 ? ((currentQuestionIndex + 1) / totalQuestions) * 100 : 0;
@@ -179,6 +190,7 @@ export default function PostDrillRunner({ session }) {
)}
</div>
)}
+ <AppliedNumeracyLesson method={lastAnswer.method} />
</div>
<button
@@ -270,12 +282,12 @@ export default function PostDrillRunner({ session }) {
) : (
<input
ref={inputRef}
- type={isTextDrill ? 'text' : 'number'}
- inputMode={isTextDrill ? 'text' : 'numeric'}
+ type={isTextDrill || isAppliedNumeracy ? 'text' : 'number'}
+ inputMode={isTextDrill ? 'text' : isAppliedNumeracy ? 'decimal' : 'numeric'}
value={inputValue}
onChange={e => setInputValue(e.target.value)}
- placeholder="Answer"
- aria-label="Your answer"
+ placeholder={isAppliedNumeracy ? 'Number and unit when requested' : 'Answer'}
+ aria-label={isAppliedNumeracy ? 'Your numeric answer and unit when requested' : 'Your answer'}
autoFocus
className="w-full bg-port-bg border border-port-border rounded-lg px-4 py-3 text-xl font-mono text-white text-center placeholder-gray-600 focus:border-port-accent focus:outline-none"
/>
diff --git a/client/src/components/meatspace/post/PostDrillRunner.test.jsx b/client/src/components/meatspace/post/PostDrillRunner.test.jsx
index 829197d2ed..442449993a 100644
--- a/client/src/components/meatspace/post/PostDrillRunner.test.jsx
+++ b/client/src/components/meatspace/post/PostDrillRunner.test.jsx
@@ -23,6 +23,48 @@ describe('PostDrillRunner Powers training feedback', () => {
});
});
+describe('PostDrillRunner Applied Numeracy', () => {
+ it('uses a mobile-friendly unit input and explains the method after an answer', () => {
+ render(<PostDrillRunner session={{
+ currentDrill: { type: 'applied-numeracy', questions: [{ prompt: 'Convert 1.5 km to m.' }], timeLimitSec: 90 },
+ currentQuestionIndex: 0,
+ currentDrillIndex: 0,
+ drillCount: 1,
+ state: 'drilling',
+ isTraining: true,
+ lastAnswer: {
+ prompt: 'Convert 1.5 km to m.', expected: '1500 m', answered: '1.5 km', correct: true,
+ method: 'Use 1 km = 1000 m, then multiply 1.5 by 1000.',
+ },
+ submitAnswer: vi.fn(),
+ skipQuestion: vi.fn(),
+ acknowledgeAnswer: vi.fn(),
+ timeExpired: vi.fn(),
+ }} />);
+
+ expect(screen.getByText('Shortest method')).toBeInTheDocument();
+ expect(screen.getByText(/1 km = 1000 m/)).toBeInTheDocument();
+
+ render(<PostDrillRunner session={{
+ currentDrill: { type: 'applied-numeracy', questions: [{ prompt: 'Convert 1.5 km to m.' }], timeLimitSec: 90 },
+ currentQuestionIndex: 0,
+ currentDrillIndex: 0,
+ drillCount: 1,
+ state: 'drilling',
+ isTraining: false,
+ lastAnswer: null,
+ submitAnswer: vi.fn(),
+ skipQuestion: vi.fn(),
+ acknowledgeAnswer: vi.fn(),
+ timeExpired: vi.fn(),
+ }} />);
+
+ const input = screen.getByLabelText('Your numeric answer and unit when requested');
+ expect(input).toHaveAttribute('type', 'text');
+ expect(input).toHaveAttribute('inputmode', 'decimal');
+ });
+});
+
describe('PostDrillRunner multi-blank recall', () => {
it('renders one labeled input per blank and submits indexed values', () => {
const submitAnswer = vi.fn();
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsx
index 5c6314f946..fd991ae5c3 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx
@@ -319,7 +319,9 @@ export default function PostSessionLauncher({
startRange: cfg.startRange,
bases: cfg.bases,
maxExponent: cfg.maxExponent,
- tolerancePct: cfg.tolerancePct
+ tolerancePct: cfg.tolerancePct,
+ difficulty: cfg.difficulty,
+ family: cfg.family,
},
timeLimitSec: cfg.timeLimitSec || 120
}));
@@ -462,6 +464,8 @@ export default function PostSessionLauncher({
bases: cfg.bases,
maxExponent: cfg.maxExponent,
tolerancePct: cfg.tolerancePct,
+ difficulty: cfg.difficulty,
+ family: cfg.family,
};
} else if (source === 'cognitive') {
focusConfig = cognitiveDrillConfig(cfg);
diff --git a/client/src/components/meatspace/post/PracticePlan.test.jsx b/client/src/components/meatspace/post/PracticePlan.test.jsx
index 1c70c6df88..21287d83c9 100644
--- a/client/src/components/meatspace/post/PracticePlan.test.jsx
+++ b/client/src/components/meatspace/post/PracticePlan.test.jsx
@@ -11,9 +11,14 @@ vi.mock('../../ui/Toast', () => ({
}));
import PracticePlan from './PracticePlan';
+import { POST_TOPICS } from './constants';
import { updatePostConfig, getMemoryItems } from '../../../services/api';
import toast from '../../ui/Toast';
+const drillTypesForModule = (module) => [...new Set(
+ POST_TOPICS.filter(topic => topic.module === module).flatMap(topic => topic.drillTypes)
+)].sort();
+
// A config shaped like what the server actually hands the client: DEFAULT_CONFIG
// deep-merged over whatever is saved. Deliberately carries NO `topics` key, so
// every test starts from the legacy "absent = enabled" baseline.
@@ -179,10 +184,10 @@ describe('PracticePlan save', () => {
await waitFor(() => expect(updatePostConfig).toHaveBeenCalled());
const [patch] = updatePostConfig.mock.calls[0];
- expect(Object.keys(patch.llmDrills.drillTypes)).toHaveLength(14);
- expect(Object.keys(patch.mentalMath.drillTypes)).toHaveLength(5);
- expect(Object.keys(patch.cognitive.drillTypes)).toHaveLength(9);
- expect(Object.keys(patch.memory.drillTypes)).toHaveLength(3);
+ expect(Object.keys(patch.llmDrills.drillTypes).sort()).toEqual(drillTypesForModule('llm-drills'));
+ expect(Object.keys(patch.mentalMath.drillTypes).sort()).toEqual(drillTypesForModule('mental-math'));
+ expect(Object.keys(patch.cognitive.drillTypes).sort()).toEqual(drillTypesForModule('cognitive'));
+ expect(Object.keys(patch.memory.drillTypes).sort()).toEqual(drillTypesForModule('memory'));
// A drill type absent from the saved config is persisted as disabled — the
// launcher already ignored it, so seeding must not silently switch it on.
expect(patch.llmDrills.drillTypes['bridge-word']).toEqual({ enabled: false });
diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.js
index 4d4c902d64..3f0cda97bb 100644
--- a/client/src/components/meatspace/post/constants.js
+++ b/client/src/components/meatspace/post/constants.js
@@ -72,7 +72,7 @@ export const POST_TOPICS = [
label: 'Mental Math',
module: 'mental-math',
surface: 'session',
- drillTypes: ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'],
+ drillTypes: ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation', 'applied-numeracy'],
},
{
id: 'memory',
@@ -264,6 +264,7 @@ export const DRILL_LABELS = {
'multiplication': 'Multiplication',
'powers': 'Powers',
'estimation': 'Estimation',
+ 'applied-numeracy': 'Applied Numeracy',
'word-association': 'Word Association',
'story-recall': 'Story Recall',
'verbal-fluency': 'Verbal Fluency',
@@ -296,6 +297,41 @@ export const DRILL_LABELS = {
'flanker': 'Flanker Control',
};
+function parseAppliedNumeracyInput(value, question) {
+ const text = String(value ?? '').trim();
+ const match = text.match(/^(-?(?:\d+|\d+\.\d+|\d+\s*\/\s*-?\d+))\s*([a-zA-Z]+)?$/);
+ if (!match) return null;
+ const fraction = match[1].match(/^(-?\d+)\s*\/\s*(-?\d+)$/);
+ const numeric = fraction
+ ? Number(fraction[1]) / Number(fraction[2])
+ : Number(match[1]);
+ if (!Number.isFinite(numeric) || (fraction && Number(fraction[2]) === 0)) return null;
+ const suppliedUnit = match[2]?.toLowerCase() || null;
+ const unit = suppliedUnit ? (question.unitAliases?.[suppliedUnit] || suppliedUnit) : null;
+ return { numeric, unit };
+}
+
+// The client provides immediate training feedback from public generated metadata;
+// submitPostSession always reconstructs the seeded question server-side.
+export function appliedNumeracyAnswerCorrect(value, question = {}) {
+ const parsed = parseAppliedNumeracyInput(value, question);
+ if (!parsed) return false;
+ let expected = question.expected;
+ let actual = parsed.numeric;
+ if (question.unit) {
+ const suppliedFactor = question.unitOptions?.[parsed.unit];
+ const expectedFactor = question.unitOptions?.[question.unit];
+ if (!suppliedFactor || !expectedFactor) return false;
+ actual *= suppliedFactor;
+ expected *= expectedFactor;
+ } else if (parsed.unit) {
+ return false;
+ }
+ const tolerance = question.tolerance || {};
+ const margin = Math.max(tolerance.absolute || 0, Math.abs(expected) * (tolerance.relative || 0));
+ return Math.abs(actual - expected) <= margin + 1e-9;
+}
+
// Human-readable label for a domain key. `other` collects drills whose type
// isn't mapped to a DOMAINS bucket (e.g. legacy/removed drill types).
export const domainLabel = (key) => (key === 'other' ? 'Other' : DOMAINS[key]?.label || key);
diff --git a/client/src/components/meatspace/post/constants.test.js b/client/src/components/meatspace/post/constants.test.js
index 3f7b9a3e68..fbb559f5c9 100644
--- a/client/src/components/meatspace/post/constants.test.js
+++ b/client/src/components/meatspace/post/constants.test.js
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
computeDomainAverages, domainLabel, computeGoalProgress, hasGoals,
POST_TOPICS, DOMAINS, DRILL_TO_DOMAIN, composedSessionDrillTypes,
- isTopicEnabled, isMemoryItemEnabled, resolveTopicForDrillType,
+ isTopicEnabled, isMemoryItemEnabled, resolveTopicForDrillType, appliedNumeracyAnswerCorrect,
} from './constants';
describe('domainLabel', () => {
@@ -20,6 +20,25 @@ describe('domainLabel', () => {
});
});
+describe('appliedNumeracyAnswerCorrect', () => {
+ const unitQuestion = {
+ expected: 1500,
+ unit: 'm',
+ unitOptions: { m: 1, km: 1000 },
+ unitAliases: { meters: 'm', kilometers: 'km' },
+ };
+
+ it('accepts a compatible equivalent unit and rejects a missing unit', () => {
+ expect(appliedNumeracyAnswerCorrect('1.5 km', unitQuestion)).toBe(true);
+ expect(appliedNumeracyAnswerCorrect('1500', unitQuestion)).toBe(false);
+ });
+
+ it('accepts an equivalent fraction and rejects a zero denominator', () => {
+ expect(appliedNumeracyAnswerCorrect('2/4', { expected: 0.5 })).toBe(true);
+ expect(appliedNumeracyAnswerCorrect('2/0', { expected: 0.5 })).toBe(false);
+ });
+});
+
describe('computeDomainAverages', () => {
it('derives the domain from the drill TYPE, not the coarse module segment', () => {
// pun-wordplay lives under the `wordplay` domain even though its coarse
diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.js
index b6b507ff45..b882d005b9 100644
--- a/client/src/hooks/usePostSession.js
+++ b/client/src/hooks/usePostSession.js
@@ -4,7 +4,7 @@ import toast from '../components/ui/Toast';
import { uuidv4 } from '../lib/uuid.js';
import {
LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, DRILL_TO_DOMAIN, countLlmCorrect,
- WORDPLAY_LLM_DRILL_TYPES, LLM_TRAINING_CORRECT_THRESHOLD,
+ WORDPLAY_LLM_DRILL_TYPES, LLM_TRAINING_CORRECT_THRESHOLD, appliedNumeracyAnswerCorrect,
} from '../components/meatspace/post/constants';
// sessionStorage key for the single in-progress run. Single-user tool → one
@@ -308,7 +308,8 @@ export function usePostSession() {
if (!q) return;
const responseMs = Date.now() - questionStartRef.current;
const hasFillBlankAnswers = Array.isArray(q.answers) && q.answers.length > 0;
- const isTextAnswer = typeof q.expected === 'string' || hasFillBlankAnswers;
+ const isAppliedNumeracy = currentDrill.type === 'applied-numeracy';
+ const isTextAnswer = typeof q.expected === 'string' || hasFillBlankAnswers || isAppliedNumeracy;
// For estimation drills, check within tolerance
let correct;
@@ -319,7 +320,9 @@ export function usePostSession() {
correct = entries.length > 0 && entries.every(entry => entry.correct);
} else if (isTextAnswer) {
answered = value;
- correct = value !== null && String(value).toLowerCase().trim() === String(q.expected).toLowerCase().trim();
+ correct = isAppliedNumeracy
+ ? appliedNumeracyAnswerCorrect(value, q)
+ : value !== null && String(value).toLowerCase().trim() === String(q.expected).toLowerCase().trim();
} else if (currentDrill.type === 'estimation') {
const raw = (value === null || String(value).trim() === '') ? null : Number(value);
answered = (raw !== null && isNaN(raw)) ? null : raw;
@@ -333,10 +336,11 @@ export function usePostSession() {
const answer = {
prompt: q.prompt,
- expected: q.expected,
+ expected: q.answerDisplay || q.expected,
answered,
correct,
responseMs,
+ ...(q.method ? { method: q.method } : {}),
...memoryAttribution(q),
};
@@ -403,10 +407,11 @@ export function usePostSession() {
const answered = hasFillBlankAnswers ? buildFillBlankAnswerEntries(q, null) : null;
return {
prompt: q.prompt,
- expected: q.expected,
+ expected: q.answerDisplay || q.expected,
answered,
correct: false,
responseMs: 0,
+ ...(q.method ? { method: q.method } : {}),
...memoryAttribution(q)
};
});
@@ -522,7 +527,7 @@ export function usePostSession() {
? (r.responses || []).length
: (r.questions || []).filter((question) => question?.answered != null).length;
const inputMode = r.inputMode || (
- isLlmDrill || MEMORY_DRILL_TYPES.includes(r.type)
+ isLlmDrill || MEMORY_DRILL_TYPES.includes(r.type) || r.type === 'applied-numeracy'
? 'text'
: r.module === 'cognitive' ? 'interactive' : 'numeric'
);
diff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.js
index 29feb51d75..d6be1729b3 100644
--- a/client/src/hooks/usePostSession.test.js
+++ b/client/src/hooks/usePostSession.test.js
@@ -12,6 +12,60 @@ vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: v
import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingRun } from '../services/api';
import { usePostSession } from './usePostSession';
+describe('usePostSession — Applied Numeracy', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ sessionStorage.clear();
+ });
+
+ it('restores a seeded unit drill and keeps equivalent-unit feedback correct', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'applied-numeracy',
+ config: { seed: 4443, difficulty: 2, family: 'unit' },
+ questions: [{
+ prompt: 'Convert 1500 m to km.', expected: 1.5, answerDisplay: '1.5 km', unit: 'km',
+ unitOptions: { m: 1, km: 1000 }, unitAliases: { kilometer: 'km', kilometers: 'km' },
+ method: 'Divide meters by 1000 to get kilometers.',
+ }],
+ });
+
+ const first = renderHook(() => usePostSession());
+ await act(async () => {
+ await first.result.current.startSession([{ type: 'applied-numeracy', config: {}, timeLimitSec: 60 }]);
+ });
+ first.unmount();
+
+ const second = renderHook(() => usePostSession());
+ expect(second.result.current.currentDrill?.config.seed).toBe(4443);
+ act(() => { second.result.current.submitAnswer('1500 m'); });
+
+ const task = second.result.current.drillResults[0];
+ expect(task.config).toMatchObject({ seed: 4443, difficulty: 2, family: 'unit' });
+ expect(task.questions[0]).toMatchObject({ correct: true, expected: '1.5 km', method: 'Divide meters by 1000 to get kilometers.' });
+ });
+
+ it('records unanswered applied-numeracy questions when the timer expires', async () => {
+ generatePostDrill.mockResolvedValue({
+ type: 'applied-numeracy', config: { seed: 44, difficulty: 1 },
+ questions: [
+ { prompt: 'Convert 2 km to m.', expected: 2000, answerDisplay: '2000 m' },
+ { prompt: 'Convert 3 l to ml.', expected: 3000, answerDisplay: '3000 ml' },
+ ],
+ });
+
+ const { result } = renderHook(() => usePostSession());
+ await act(async () => {
+ await result.current.startSession([{ type: 'applied-numeracy', config: {}, timeLimitSec: 60 }]);
+ });
+ act(() => { result.current.timeExpired(); });
+
+ expect(result.current.drillResults[0].questions).toEqual(expect.arrayContaining([
+ expect.objectContaining({ answered: null, correct: false, expected: '2000 m' }),
+ expect.objectContaining({ answered: null, correct: false, expected: '3000 ml' }),
+ ]));
+ });
+});
+
// Covers issue #2010: a memory drill completed inside a POST session must
// carry its memoryItemId through to the submitted task (so the server can
// advance that item's spaced-repetition schedule) and use the `memory`
diff --git a/client/src/lib/postQuickSession.js b/client/src/lib/postQuickSession.js
index 6eb8a3f007..d02fca105c 100644
--- a/client/src/lib/postQuickSession.js
+++ b/client/src/lib/postQuickSession.js
@@ -62,6 +62,8 @@ export function buildQuickDrillConfig({ cfg = {}, source, memoryItemId } = {}) {
bases: cfg.bases,
maxExponent: cfg.maxExponent,
tolerancePct: cfg.tolerancePct,
+ difficulty: cfg.difficulty,
+ family: cfg.family,
};
}
if (source === 'cognitive') {
diff --git a/server/lib/README.md b/server/lib/README.md
index 8d1fc424a1..7ee3fbe130 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -304,6 +304,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `textUtils.js` | Pure server-side prose helpers. `countWords(text)` — canonical whitespace-token count (`\S+`), the single home for what `writersRoom/local.js`, `issueLength.js`, and the client's `formatters.js` used to each re-implement. |
| `pipelineIssueOrder.js` | Pure renumber algorithm for pipeline issues. |
| `postAdaptive.js` | Pure POST adaptive-difficulty policy — nudges a math drill's primary knob (`steps`/`maxDigits`/`maxExponent`/`tolerancePct`) up/down within clamped bounds from recent scored performance. Opt-in via the config Adaptive toggle. |
+| `postAppliedNumeracy.js` | Pure seeded Applied Numeracy pack — everyday percentage, ratio, unit, rate, and estimation scenarios plus server-authoritative numeric/fraction/unit scoring with explicit tolerance handling. |
| `postMultiplicationLadder.js` | Pure progressive multiplication ladder — mastery-gated difficulty rungs (`[1,1]` → `[1,2]` → `[1,1,1]` → …). Resolves the user's current level from per-level speed+accuracy stats so the plain multiplication drill ramps up instead of starting at a fixed hard difficulty. On by default. Built on `postProgression.js`. |
| `postPowersLadder.js` | Pure technique-anchored Powers ladder — cumulative named-method pools, full supported-pair registry, and speed+accuracy mastery progression built on `postProgression.js`. |
| `postProgression.js` | Generic mastery-gated progression ladder (extracted from `postMultiplicationLadder.js`) — `createProgression({ levels, describeLevel, speedTargetForLevel? })` resolves a user's current rung from exact-level sample, accuracy, completion, and optional speed evidence with an anti-demotion floor. Also defines meaningful cognitive-drill ladders (including task switching, Go/No-Go, and Flanker) and their level→generator-config mapping. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 53375dc862..d244f39850 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -285,6 +285,7 @@ export * from './providerFamilies.js';
export * from './personaTraitBlend.js';
export * from './pipelineIssueOrder.js';
export * from './postAdaptive.js';
+export * from './postAppliedNumeracy.js';
export * from './postMultiplicationLadder.js';
export * from './postPowersLadder.js';
export * from './postProgression.js';
diff --git a/server/lib/postAppliedNumeracy.js b/server/lib/postAppliedNumeracy.js
new file mode 100644
index 0000000000..3f1a500885
--- /dev/null
+++ b/server/lib/postAppliedNumeracy.js
@@ -0,0 +1,294 @@
+// Deterministic applied-numeracy drill generation and authoritative scoring.
+// Each question is reconstructed from the persisted seed/config on submit, so
+// client-supplied expected values, prompts, and correctness never affect scores.
+
+export const APPLIED_NUMERACY_DRILL_TYPE = 'applied-numeracy';
+export const APPLIED_NUMERACY_FAMILIES = ['percentage', 'ratio', 'unit', 'rate', 'estimate'];
+export const APPLIED_NUMERACY_DIFFICULTIES = [1, 2, 3];
+
+const EPSILON = 1e-9;
+
+const UNIT_DIMENSIONS = {
+ distance: { m: 1, km: 1000, cm: 0.01 },
+ duration: { s: 1, min: 60, h: 3600 },
+ volume: { ml: 1, l: 1000 },
+ mass: { g: 1, kg: 1000 },
+};
+
+const UNIT_ALIASES = {
+ meter: 'm', meters: 'm', metre: 'm', metres: 'm',
+ kilometer: 'km', kilometers: 'km', kilometre: 'km', kilometres: 'km',
+ centimeter: 'cm', centimeters: 'cm', centimetre: 'cm', centimetres: 'cm',
+ second: 's', seconds: 's', sec: 's', secs: 's',
+ minute: 'min', minutes: 'min', mins: 'min',
+ hour: 'h', hours: 'h', hr: 'h', hrs: 'h',
+ milliliter: 'ml', milliliters: 'ml', millilitre: 'ml', millilitres: 'ml',
+ liter: 'l', liters: 'l', litre: 'l', litres: 'l',
+ gram: 'g', grams: 'g', kilogram: 'kg', kilograms: 'kg',
+};
+
+function normalizeSeed(seed = 0) {
+ return Number.isInteger(seed) && seed >= 0 && seed <= 0xFFFFFFFF ? seed : 0;
+}
+
+function seededRandom(seed) {
+ let state = normalizeSeed(seed) || 0x6D2B79F5;
+ return () => {
+ state += 0x6D2B79F5;
+ let value = state;
+ value = Math.imul(value ^ (value >>> 15), value | 1);
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+function pick(random, values) {
+ return values[Math.floor(random() * values.length)];
+}
+
+function integer(random, min, max) {
+ return Math.floor(random() * (max - min + 1)) + min;
+}
+
+function trimNumber(value) {
+ return Number.isInteger(value) ? String(value) : String(Math.round(value * 1000) / 1000);
+}
+
+function unitQuestion({ prompt, expected, unit, dimension, method, tolerance = null }) {
+ const unitOptions = UNIT_DIMENSIONS[dimension];
+ const unitAliases = Object.fromEntries(
+ Object.entries(UNIT_ALIASES).filter(([, canonical]) => unitOptions[canonical])
+ );
+ return {
+ prompt,
+ promptLabel: `Enter a number and unit (for example, ${trimNumber(expected)} ${unit})`,
+ expected,
+ unit,
+ dimension,
+ unitOptions,
+ unitAliases,
+ answerDisplay: `${trimNumber(expected)} ${unit}`,
+ method,
+ ...(tolerance ? { tolerance } : {}),
+ };
+}
+
+function numberQuestion({ prompt, expected, method, tolerance = null }) {
+ return {
+ prompt,
+ promptLabel: 'Enter a number',
+ expected,
+ answerDisplay: trimNumber(expected),
+ method,
+ ...(tolerance ? { tolerance } : {}),
+ };
+}
+
+function percentageQuestion(random, difficulty) {
+ const amount = integer(random, difficulty === 1 ? 40 : 80, difficulty === 3 ? 240 : 160);
+ const percent = pick(random, difficulty === 1 ? [10, 20, 25, 50] : [12, 15, 20, 25, 30]);
+ if (difficulty === 1) {
+ const expected = amount * (1 - percent / 100);
+ return numberQuestion({
+ prompt: `A ${amount}-credit pass is discounted ${percent}%. What is the sale price?`,
+ expected,
+ method: `${percent}% of ${amount} is ${trimNumber(amount * percent / 100)}; subtract that discount from ${amount}.`,
+ });
+ }
+ const expected = amount * (1 + percent / 100);
+ const step = difficulty === 3 ? 'Then round only after the percentage change.' : '';
+ return numberQuestion({
+ prompt: `A ${amount}-credit refill gets a ${percent}% markup. What is the new price?`,
+ expected,
+ method: `A ${percent}% markup means multiply ${amount} by ${trimNumber(1 + percent / 100)}. ${step}`.trim(),
+ });
+}
+
+function ratioQuestion(random, difficulty) {
+ const left = integer(random, 2, 4);
+ const right = integer(random, left + 1, 6);
+ if (difficulty === 3) {
+ const expected = left / (left + right);
+ return numberQuestion({
+ prompt: `A pattern has ${left} blue tiles and ${right} yellow tiles in each repeat. What fraction of one repeat is blue?`,
+ expected,
+ method: `There are ${left + right} tiles in one repeat, so blue is ${left}/${left + right}. An equivalent fraction or decimal is accepted.`,
+ });
+ }
+ const known = right * integer(random, difficulty === 1 ? 3 : 4, difficulty === 3 ? 8 : 6);
+ const expected = known * left / right;
+ const label = difficulty === 3 ? 'tiles' : 'parts';
+ return numberQuestion({
+ prompt: `A pattern uses ${left} blue ${label} for every ${right} yellow ${label}. If it has ${known} yellow ${label}, how many blue ${label} are needed?`,
+ expected,
+ method: `${known} ÷ ${right} = ${trimNumber(known / right)} equal ratio groups; multiply by ${left} blue ${label} per group.`,
+ });
+}
+
+function unitConversionQuestion(random, difficulty) {
+ const choices = difficulty === 1
+ ? [
+ { from: 'km', to: 'm', dimension: 'distance', amount: integer(random, 2, 9) },
+ { from: 'l', to: 'ml', dimension: 'volume', amount: integer(random, 2, 8) },
+ ]
+ : [
+ { from: 'm', to: 'cm', dimension: 'distance', amount: integer(random, 15, 90) },
+ { from: 'h', to: 'min', dimension: 'duration', amount: integer(random, 2, 6) },
+ { from: 'kg', to: 'g', dimension: 'mass', amount: integer(random, 2, 9) },
+ ];
+ const choice = pick(random, choices);
+ const options = UNIT_DIMENSIONS[choice.dimension];
+ const expected = choice.amount * options[choice.from] / options[choice.to];
+ return unitQuestion({
+ prompt: `Convert ${choice.amount} ${choice.from} to ${choice.to}.`,
+ expected,
+ unit: choice.to,
+ dimension: choice.dimension,
+ method: `Use the ${choice.from} → ${choice.to} scale: ${choice.amount} ${choice.from} equals ${trimNumber(expected)} ${choice.to}.`,
+ });
+}
+
+function rateQuestion(random, difficulty) {
+ const per = integer(random, difficulty === 1 ? 6 : 8, difficulty === 3 ? 18 : 12);
+ const baseMinutes = integer(random, 2, 6);
+ const targetMinutes = baseMinutes * integer(random, difficulty === 1 ? 2 : 3, difficulty === 3 ? 5 : 4);
+ const completed = per * baseMinutes;
+ const expected = per * targetMinutes;
+ return numberQuestion({
+ prompt: `A crew sorts ${completed} sample cards in ${baseMinutes} minutes at a steady rate. How many sample cards can it sort in ${targetMinutes} minutes?`,
+ expected,
+ method: `${completed} ÷ ${baseMinutes} = ${per} cards per minute; multiply ${per} by ${targetMinutes} minutes.`,
+ });
+}
+
+function estimateQuestion(random, difficulty) {
+ const a = integer(random, difficulty === 1 ? 35 : 120, difficulty === 3 ? 760 : 420);
+ const b = integer(random, difficulty === 1 ? 16 : 40, difficulty === 3 ? 190 : 120);
+ const nearest = difficulty === 1 ? 100 : difficulty === 2 ? 1000 : 10000;
+ const expected = Math.round((a * b) / nearest) * nearest;
+ const tolerance = difficulty === 1
+ ? { absolute: nearest }
+ : { relative: difficulty === 2 ? 0.15 : 0.2 };
+ return numberQuestion({
+ prompt: `Estimate ${a} × ${b}. Give a sensible order-of-magnitude estimate (nearest ${nearest}).`,
+ expected,
+ tolerance,
+ method: `Round ${a} and ${b} to easy nearby values, multiply, then keep the result near ${nearest}. Answers within the stated estimate band count.`,
+ });
+}
+
+const FAMILY_GENERATORS = {
+ percentage: percentageQuestion,
+ ratio: ratioQuestion,
+ unit: unitConversionQuestion,
+ rate: rateQuestion,
+ estimate: estimateQuestion,
+};
+
+function normalizedConfig(config = {}) {
+ const count = Number.isInteger(config.count) ? Math.max(1, Math.min(50, config.count)) : 5;
+ const difficulty = APPLIED_NUMERACY_DIFFICULTIES.includes(config.difficulty) ? config.difficulty : 1;
+ const family = APPLIED_NUMERACY_FAMILIES.includes(config.family) ? config.family : 'mixed';
+ return { count, difficulty, family, seed: normalizeSeed(config.seed) };
+}
+
+/** Pure seeded generator. Given the same config it always emits the same pack. */
+export function generateAppliedNumeracyDrill(config = {}) {
+ const resolved = normalizedConfig(config);
+ const random = seededRandom(resolved.seed);
+ const offset = Math.floor(random() * APPLIED_NUMERACY_FAMILIES.length);
+ const questions = Array.from({ length: resolved.count }, (_, index) => {
+ const family = resolved.family === 'mixed'
+ ? APPLIED_NUMERACY_FAMILIES[(offset + index) % APPLIED_NUMERACY_FAMILIES.length]
+ : resolved.family;
+ return { index, family, difficulty: resolved.difficulty, ...FAMILY_GENERATORS[family](random, resolved.difficulty) };
+ });
+ return { type: APPLIED_NUMERACY_DRILL_TYPE, config: resolved, questions };
+}
+
+function parseNumber(raw) {
+ const text = String(raw ?? '').trim();
+ if (!text) return null;
+ const fraction = text.match(/^(-?\d+)\s*\/\s*(-?\d+)$/);
+ if (fraction) {
+ const numerator = Number(fraction[1]);
+ const denominator = Number(fraction[2]);
+ if (!Number.isFinite(numerator) || !Number.isFinite(denominator) || denominator === 0) return null;
+ return numerator / denominator;
+ }
+ if (!/^-?(?:\d+|\d+\.\d+)$/.test(text)) return null;
+ const value = Number(text);
+ return Number.isFinite(value) ? value : null;
+}
+
+/** Parse a numeric or fractional response with an optional unit; malformed input returns null. */
+export function parseAppliedNumeracyAnswer(raw) {
+ const text = String(raw ?? '').trim();
+ if (!text) return null;
+ const match = text.match(/^(-?(?:\d+|\d+\.\d+|\d+\s*\/\s*-?\d+))\s*([a-zA-Z]+)?$/);
+ if (!match) return null;
+ const value = parseNumber(match[1]);
+ if (value == null) return null;
+ const supplied = match[2]?.toLowerCase() || null;
+ return { value, unit: supplied ? (UNIT_ALIASES[supplied] || supplied) : null };
+}
+
+function correctAppliedAnswer(question, raw) {
+ const parsed = parseAppliedNumeracyAnswer(raw);
+ if (!parsed) return { parsed: null, correct: false };
+ let expected = question.expected;
+ let actual = parsed.value;
+ if (question.unit) {
+ const unitFactor = question.unitOptions?.[parsed.unit];
+ const expectedFactor = question.unitOptions?.[question.unit];
+ if (!unitFactor || !expectedFactor) return { parsed, correct: false };
+ actual *= unitFactor;
+ expected *= expectedFactor;
+ } else if (parsed.unit) {
+ return { parsed, correct: false };
+ }
+ const difference = Math.abs(actual - expected);
+ const tolerance = question.tolerance || {};
+ const permitted = Math.max(tolerance.absolute || 0, Math.abs(expected) * (tolerance.relative || 0));
+ return { parsed, correct: difference <= permitted + EPSILON };
+}
+
+function scoreBundle(questions, timeLimitMs) {
+ const answered = questions.filter(question => question.answered != null);
+ const answeredCount = answered.length;
+ const totalCount = questions.length;
+ const correctCount = questions.filter(question => question.correct).length;
+ const correctRatio = totalCount ? correctCount / totalCount : 0;
+ const totalResponseMs = answered.reduce((sum, question) => sum + Math.min(Math.max(question.responseMs || 0, 0), timeLimitMs), 0);
+ const avgForBonus = answeredCount ? totalResponseMs / answeredCount : timeLimitMs;
+ const speedBonus = Math.max(0, 1 - avgForBonus / timeLimitMs);
+ return {
+ score: Math.min(100, Math.max(0, Math.round((correctRatio * 0.8 + speedBonus * 0.2) * 100))),
+ questions,
+ accuracy: answeredCount ? correctCount / answeredCount : null,
+ completion: totalCount ? answeredCount / totalCount : null,
+ avgResponseMs: answeredCount ? Math.round(totalResponseMs / answeredCount) : null,
+ answeredCount,
+ totalCount,
+ };
+}
+
+/** Rebuild the pack from its seed and score only its server-derived answer keys. */
+export function scoreAppliedNumeracyDrill(submittedQuestions = [], timeLimitMs = 120000, config = {}) {
+ const generated = generateAppliedNumeracyDrill(config);
+ const source = Array.isArray(submittedQuestions) ? submittedQuestions : [];
+ const questions = generated.questions.map((question, index) => {
+ const submitted = source[index] || {};
+ const raw = submitted.answered;
+ const answered = raw == null || String(raw).trim() === '' ? null : String(raw).trim();
+ const { correct } = correctAppliedAnswer(question, answered);
+ return {
+ ...question,
+ answered,
+ expected: question.answerDisplay,
+ correct,
+ responseMs: Number.isFinite(submitted.responseMs) ? submitted.responseMs : 0,
+ };
+ });
+ return scoreBundle(questions, Math.max(1, timeLimitMs));
+}
diff --git a/server/lib/postAppliedNumeracy.test.js b/server/lib/postAppliedNumeracy.test.js
new file mode 100644
index 0000000000..ef6442edf7
--- /dev/null
+++ b/server/lib/postAppliedNumeracy.test.js
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+import {
+ APPLIED_NUMERACY_FAMILIES,
+ generateAppliedNumeracyDrill,
+ parseAppliedNumeracyAnswer,
+ scoreAppliedNumeracyDrill,
+} from './postAppliedNumeracy.js';
+
+describe('Applied Numeracy', () => {
+ it('generates reproducible packs from a seed', () => {
+ const config = { seed: 4443, count: 5, difficulty: 2 };
+ expect(generateAppliedNumeracyDrill(config)).toEqual(generateAppliedNumeracyDrill(config));
+ });
+
+ it.each(APPLIED_NUMERACY_FAMILIES)('scores a server-rebuilt %s fixture', (family) => {
+ const drill = generateAppliedNumeracyDrill({ seed: 12, family, count: 1, difficulty: 2 });
+ const result = scoreAppliedNumeracyDrill(
+ [{ answered: drill.questions[0].answerDisplay, responseMs: 1000 }],
+ 120000,
+ drill.config,
+ );
+ expect(result.questions[0]).toMatchObject({ correct: true, prompt: drill.questions[0].prompt });
+ expect(result.accuracy).toBe(1);
+ });
+
+ it('accepts equivalent fractions but rejects a zero denominator', () => {
+ const drill = generateAppliedNumeracyDrill({ seed: 8, family: 'ratio', count: 1, difficulty: 3 });
+ const [, blue, yellow] = drill.questions[0].prompt.match(/(\d+) blue tiles and (\d+) yellow/);
+ const fraction = `${blue}/${Number(blue) + Number(yellow)}`;
+ const result = scoreAppliedNumeracyDrill([{ answered: fraction, responseMs: 1000 }], 120000, drill.config);
+
+ expect(result.questions[0].correct).toBe(true);
+ expect(parseAppliedNumeracyAnswer('-2.5')).toEqual({ value: -2.5, unit: null });
+ expect(parseAppliedNumeracyAnswer('3/0')).toBe(null);
+ });
+
+ it('requires a compatible unit while accepting equivalent unit conversions', () => {
+ const drill = generateAppliedNumeracyDrill({ seed: 10, family: 'unit', count: 1, difficulty: 1 });
+ const question = drill.questions[0];
+ const units = Object.entries(question.unitOptions);
+ const [alternateUnit, alternateFactor] = units.find(([unit]) => unit !== question.unit);
+ const equivalent = question.expected * question.unitOptions[question.unit] / alternateFactor;
+
+ const accepted = scoreAppliedNumeracyDrill([{ answered: `${equivalent} ${alternateUnit}`, responseMs: 1000 }], 120000, drill.config);
+ const missingUnit = scoreAppliedNumeracyDrill([{ answered: String(question.expected), responseMs: 1000 }], 120000, drill.config);
+ const wrongUnit = scoreAppliedNumeracyDrill([{ answered: `${question.expected} bananas`, responseMs: 1000 }], 120000, drill.config);
+
+ expect(accepted.questions[0].correct).toBe(true);
+ expect(missingUnit.questions[0].correct).toBe(false);
+ expect(wrongUnit.questions[0].correct).toBe(false);
+ });
+
+ it('honors inclusive absolute and relative tolerance boundaries', () => {
+ const absolute = generateAppliedNumeracyDrill({ seed: 5, family: 'estimate', count: 1, difficulty: 1 });
+ const absoluteQuestion = absolute.questions[0];
+ const absoluteResult = scoreAppliedNumeracyDrill([{
+ answered: String(absoluteQuestion.expected + absoluteQuestion.tolerance.absolute), responseMs: 1000,
+ }], 120000, absolute.config);
+ const relative = generateAppliedNumeracyDrill({ seed: 5, family: 'estimate', count: 1, difficulty: 2 });
+ const relativeQuestion = relative.questions[0];
+ const relativeResult = scoreAppliedNumeracyDrill([{
+ answered: String(relativeQuestion.expected * (1 + relativeQuestion.tolerance.relative)), responseMs: 1000,
+ }], 120000, relative.config);
+
+ expect(absoluteResult.questions[0].correct).toBe(true);
+ expect(relativeResult.questions[0].correct).toBe(true);
+ });
+
+ it('ignores client-supplied prompts and answer keys', () => {
+ const drill = generateAppliedNumeracyDrill({ seed: 22, family: 'rate', count: 1, difficulty: 2 });
+ const result = scoreAppliedNumeracyDrill([{
+ prompt: 'client replacement', expected: 999999, answered: '999999', correct: true, responseMs: 1000,
+ }], 120000, drill.config);
+
+ expect(result.questions[0].prompt).toBe(drill.questions[0].prompt);
+ expect(result.questions[0].correct).toBe(false);
+ });
+});
diff --git a/server/lib/postTopics.js b/server/lib/postTopics.js
index cd6daa8f48..abfd4c71c2 100644
--- a/server/lib/postTopics.js
+++ b/server/lib/postTopics.js
@@ -38,7 +38,7 @@ export const POST_TOPICS = [
label: 'Mental Math',
module: 'mental-math',
surface: 'session',
- drillTypes: ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'],
+ drillTypes: ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation', 'applied-numeracy'],
},
{
id: 'memory',
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index 89700a7388..581fe54e0a 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -80,7 +80,7 @@ const llmResponseSchema = z.object({
});
// Drill type configuration
-const MATH_DRILL_TYPES = ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'];
+const MATH_DRILL_TYPES = ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation', 'applied-numeracy'];
const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay', 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist', 'what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'];
const MEMORY_DRILL_TYPES = ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'];
// Memory drills supported by the POST runner (client-side scoring with string
@@ -149,6 +149,15 @@ const drillTypeConfigSchema = z.object({
bases: z.array(z.number().int().min(2).max(20)).min(1).optional(),
maxExponent: z.number().int().min(2).max(20).optional(),
tolerancePct: z.number().min(1).max(50).optional(),
+ // Applied Numeracy uses an unsigned numeric replay key while the cognitive
+ // generators use bounded string seeds. This shared config must preserve both
+ // shapes on the request and scored-session round-trips.
+ seed: z.union([
+ z.string().max(100),
+ z.number().int().min(0).max(0xFFFFFFFF),
+ ]).optional(),
+ difficulty: z.number().int().min(1).max(3).optional(),
+ family: z.enum(['percentage', 'ratio', 'unit', 'rate', 'estimate', 'mixed']).optional(),
// --- Cognitive drill knobs (n-back / digit-span / stroop) ---
// Bounds match the generator clamps in meatspacePostCognitive.js so the UI /
// API can't accept a value the generator will silently narrow. Exception:
@@ -180,7 +189,6 @@ const drillTypeConfigSchema = z.object({
minDelayMs: z.number().int().min(300).max(5000).optional(),
maxDelayMs: z.number().int().min(300).max(8000).optional(),
choices: z.number().int().min(2).max(4).optional(),
- seed: z.string().max(100).optional(),
ruleCount: z.number().int().min(2).max(3).optional(),
switchRatePct: z.number().int().min(0).max(100).optional(),
cueStimulusIntervalMs: z.number().int().min(100).max(2000).optional(),
diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.js
index 9b4355fc78..5c0fb951ea 100644
--- a/server/lib/postValidation.test.js
+++ b/server/lib/postValidation.test.js
@@ -82,6 +82,30 @@ describe('postConfigUpdateSchema cognitive compatibility', () => {
});
});
+describe('Applied Numeracy validation', () => {
+ it('accepts the persisted replay key and complexity configuration', () => {
+ const parsed = postConfigUpdateSchema.parse({
+ mentalMath: {
+ drillTypes: Object.fromEntries(
+ getTopic('math').drillTypes.map(type => [type, type === 'applied-numeracy'
+ ? { enabled: true, count: 5, difficulty: 3, family: 'unit', seed: 4443, timeLimitSec: 150 }
+ : { enabled: true, count: 5, timeLimitSec: 120 }])
+ ),
+ },
+ });
+ expect(parsed.mentalMath.drillTypes['applied-numeracy']).toMatchObject({ difficulty: 3, family: 'unit', seed: 4443 });
+ });
+
+ it('rejects an out-of-range seed, difficulty, or family', () => {
+ const withApplied = (entry) => ({
+ mentalMath: { drillTypes: Object.fromEntries(getTopic('math').drillTypes.map(type => [type, type === 'applied-numeracy' ? entry : { enabled: true }])) },
+ });
+ expect(() => postConfigUpdateSchema.parse(withApplied({ seed: -1 }))).toThrow();
+ expect(() => postConfigUpdateSchema.parse(withApplied({ difficulty: 4 }))).toThrow();
+ expect(() => postConfigUpdateSchema.parse(withApplied({ family: 'tax' }))).toThrow();
+ });
+});
+
describe('Morse drill types stay scoped to the training log', () => {
// Regression: MORSE_DRILL_TYPES must never be spliced into the shared
// DRILL_TYPES array — that array also backs the *scored* session submit
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index 4a4605a284..556bab89ae 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -14,6 +14,12 @@ import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from
import { normalizeHistoricalPostLlmEvaluation, normalizePostLlmEvaluation } from '../lib/postLlmContracts.js';
import { resolveTopicForDrillType, isTopicEnabled, isMemoryItemEnabled } from '../lib/postTopics.js';
import { adaptDrillConfig, ADAPTIVE_SPECS, ADAPTIVE_DEFAULTS } from '../lib/postAdaptive.js';
+import {
+ APPLIED_NUMERACY_DRILL_TYPE,
+ APPLIED_NUMERACY_DIFFICULTIES,
+ generateAppliedNumeracyDrill,
+ scoreAppliedNumeracyDrill,
+} from '../lib/postAppliedNumeracy.js';
import { resolveMultiplicationLevel, MASTERY_DEFAULTS } from '../lib/postMultiplicationLadder.js';
import {
POWERS_MASTERY_DEFAULTS,
@@ -88,7 +94,11 @@ const DEFAULT_CONFIG = {
// a user turns the progressive ladder off.
'multiplication': { enabled: true, count: 10, maxDigits: 2, progressive: true, timeLimitSec: 120 },
'powers': { enabled: true, bases: [2, 3, 5], maxExponent: 10, count: 8, progressive: true, timeLimitSec: 90 },
- 'estimation': { enabled: true, count: 5, tolerancePct: 10, timeLimitSec: 120 }
+ 'estimation': { enabled: true, count: 5, tolerancePct: 10, timeLimitSec: 120 },
+ // Pure, seeded everyday numeracy scenarios. No provider call or
+ // high-stakes domain is involved; the returned seed is stored with each
+ // session so the server can rebuild answer keys on submit.
+ 'applied-numeracy': { enabled: true, count: 5, difficulty: 1, timeLimitSec: 150 }
}
},
llmDrills: {
@@ -473,6 +483,45 @@ export async function submitPostSession(sessionData) {
// count as a genuine re-verification (mirrors COGNITIVE_MASTERY_DEFAULTS
// minCompletion). Below it, the review is recorded as failed rather than passed.
const MIN_REVIEW_COMPLETION = 0.75;
+const APPLIED_NUMERACY_MASTERY = { minSamples: 3, accuracy: 0.8, completion: 0.75 };
+
+/**
+ * Aggregate complexity-level evidence for Applied Numeracy. Its rungs measure
+ * representation changes, units, and multi-step transforms rather than larger
+ * operands, so retention can schedule a targeted rep at the earned level.
+ */
+export async function getAppliedNumeracyProgress() {
+ const sessions = await getPostSessions();
+ const buckets = Object.fromEntries([1, 2, 3].map(level => [level, { samples: 0, accuracy: 0, completion: 0 }]));
+ for (const session of sessions) {
+ for (const task of session.tasks || []) {
+ if (task.type !== APPLIED_NUMERACY_DRILL_TYPE) continue;
+ const level = APPLIED_NUMERACY_DIFFICULTIES.includes(task.config?.difficulty) ? task.config.difficulty : 1;
+ const accuracy = deriveTaskAccuracy(task);
+ const completion = deriveTaskCompletion(task);
+ if (accuracy == null) continue;
+ buckets[level].samples += 1;
+ buckets[level].accuracy += accuracy;
+ buckets[level].completion += completion ?? 1;
+ }
+ }
+ return {
+ levels: Object.entries(buckets).map(([level, bucket]) => {
+ const samples = bucket.samples;
+ const accuracy = samples ? bucket.accuracy / samples : 0;
+ const completion = samples ? bucket.completion / samples : 0;
+ return {
+ level: Number(level),
+ samples,
+ accuracy,
+ completion,
+ mastered: samples >= APPLIED_NUMERACY_MASTERY.minSamples
+ && accuracy >= APPLIED_NUMERACY_MASTERY.accuracy
+ && completion >= APPLIED_NUMERACY_MASTERY.completion,
+ };
+ }),
+ };
+}
/**
* Current mastered-but-inactive skills eligible for re-verification tracking:
@@ -486,7 +535,12 @@ const MIN_REVIEW_COMPLETION = 0.75;
export async function getMasteredSkills() {
const skills = [];
- const mul = await getMultiplicationProgress();
+ const [mul, powers, cog, numeracy] = await Promise.all([
+ getMultiplicationProgress(),
+ getPowersProgress(),
+ getCognitiveProgress(),
+ getAppliedNumeracyProgress(),
+ ]);
for (const rung of mul.levels || []) {
if (rung.mastered && rung.level < mul.level) {
skills.push({
@@ -501,7 +555,6 @@ export async function getMasteredSkills() {
}
}
- const powers = await getPowersProgress();
for (const rung of powers.levels || []) {
if (rung.mastered && rung.level < powers.level) {
skills.push({
@@ -516,7 +569,6 @@ export async function getMasteredSkills() {
}
}
- const cog = await getCognitiveProgress();
for (const [type, prog] of Object.entries(cog)) {
if (!prog) continue;
for (const rung of prog.levels || []) {
@@ -534,6 +586,18 @@ export async function getMasteredSkills() {
}
}
+ for (const rung of numeracy.levels || []) {
+ if (!rung.mastered) continue;
+ skills.push({
+ skillId: `applied-numeracy:D${rung.level}`,
+ kind: APPLIED_NUMERACY_DRILL_TYPE,
+ label: `Applied Numeracy level ${rung.level}`,
+ drillType: APPLIED_NUMERACY_DRILL_TYPE,
+ module: 'mental-math',
+ difficulty: rung.level,
+ });
+ }
+
return skills;
}
@@ -569,6 +633,9 @@ export function getSessionSkillContext(session) {
practicedSkillIds.add(`powers:L${cfg.level}`);
} else if (cognitiveLadder(task.type) && Number.isInteger(cfg.level)) {
practicedSkillIds.add(`cognitive:${task.type}:L${cfg.level}`);
+ } else if (task.type === APPLIED_NUMERACY_DRILL_TYPE) {
+ const difficulty = APPLIED_NUMERACY_DIFFICULTIES.includes(cfg.difficulty) ? cfg.difficulty : 1;
+ practicedSkillIds.add(`applied-numeracy:D${difficulty}`);
} else if (task.memoryItemId) {
for (const q of task.questions || []) {
if (q?.chunkId) practicedSkillIds.add(`memory:${task.memoryItemId}:${q.chunkId}`);
@@ -636,6 +703,15 @@ export async function getPostReviewReps(now = new Date(), limit = 2) {
type: entry.drillType,
config: { ...(entry.config || cognitiveLevelConfig(entry.drillType, entry.level)), level: entry.level, review: true, reviewSkillId: entry.skillId },
});
+ } else if (entry.kind === APPLIED_NUMERACY_DRILL_TYPE) {
+ reps.push({
+ skillId: entry.skillId,
+ label: entry.label,
+ state: entry.status === 'needs-refresh' ? 'needs-refresh' : 'due',
+ module: 'mental-math',
+ type: APPLIED_NUMERACY_DRILL_TYPE,
+ config: { count: 5, difficulty: entry.difficulty, review: true, reviewSkillId: entry.skillId },
+ });
}
}
return reps;
@@ -1679,6 +1755,13 @@ export function generateDrill(type, config = {}) {
return generatePowers(config.bases, config.maxExponent, config.count, config.level, config.review);
case 'estimation':
return generateEstimation(config.count, config.tolerancePct);
+ case APPLIED_NUMERACY_DRILL_TYPE:
+ return generateAppliedNumeracyDrill({
+ ...config,
+ // The generator itself is pure for a seed. New runs get a seed once;
+ // it is stamped into the returned config and becomes the score key.
+ seed: config.seed ?? Math.floor(Math.random() * 0x100000000),
+ });
case 'n-back':
case 'digit-span':
case 'stroop':
@@ -2122,6 +2205,9 @@ export function computeExpectedFromPrompt(prompt) {
}
export function scoreDrill(type, questions, timeLimitMs, config = {}) {
+ if (type === APPLIED_NUMERACY_DRILL_TYPE) {
+ return scoreAppliedNumeracyDrill(questions, timeLimitMs, config);
+ }
if (!questions?.length) {
return { score: 0, questions, accuracy: null, completion: null, avgResponseMs: null, answeredCount: 0, totalCount: 0 };
}