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

tell the estimation drill user how precise to be

[._.]/ Adam Eivy3875b638d403
diff --git a/client/src/components/meatspace/post/DrillQuestionReview.jsx b/client/src/components/meatspace/post/DrillQuestionReview.jsx
index c96b7f79a1..6197ef1924 100644
--- a/client/src/components/meatspace/post/DrillQuestionReview.jsx
+++ b/client/src/components/meatspace/post/DrillQuestionReview.jsx
@@ -1,5 +1,6 @@
import { Check, X, MinusCircle, AlertTriangle } from 'lucide-react';
import { powersBreakdownFromPrompt } from '../../../lib/powersBreakdown.js';
+import EstimationPrecision from './EstimationPrecision';
// Sub-second precision — most drill response times are under a few seconds,
// so the shared `formatDurationMs` (client/src/utils/formatters.js), which
@@ -98,9 +99,15 @@ function answeredForDisplay(type, q) {
return formatGenericValue(type, q.answered);
}
-function GenericReview({ questions, missed, type }) {
+function GenericReview({ questions, missed, type, config }) {
return (
<div>
+ {/* Estimation grades within a band, so the Expected column rarely matches
+ the answer beside it exactly. Name the rule, or a ✓ on "600 vs 616"
+ reads as a bug. */}
+ {type === 'estimation' && (
+ <EstimationPrecision tolerancePct={config?.tolerancePct} className="text-xs text-gray-500 mb-2" />
+ )}
<MissedSummary missed={missed} formatPrompt={(q) => q.prompt} />
<TableShell>
<thead>
@@ -425,8 +432,12 @@ function TimingReview({ questions, missed, type }) {
* `drillData` is the generated drill — used by Stroop (color swatch hex
* lookup) and digit-span (true shown-digit sequence + direction). Optional,
* and safely ignored by every other type.
+ *
+ * `config` is the drill's resolved config — used by estimation to state the
+ * tolerance its ✓/✗ column was graded against. Also optional; a history record
+ * stores it under `difficulty`, so callers pass whichever they hold.
*/
-export default function DrillQuestionReview({ type, questions, drillData }) {
+export default function DrillQuestionReview({ type, questions, drillData, config }) {
const list = questions || [];
if (!list.length) return null;
@@ -445,6 +456,6 @@ export default function DrillQuestionReview({ type, questions, drillData }) {
case 'reaction-time':
return <TimingReview questions={list} missed={missed} type={type} />;
default:
- return <GenericReview questions={list} missed={missed} type={type} />;
+ return <GenericReview questions={list} missed={missed} type={type} config={config} />;
}
}
diff --git a/client/src/components/meatspace/post/DrillQuestionReview.test.jsx b/client/src/components/meatspace/post/DrillQuestionReview.test.jsx
index 2f9c3bca44..3884d3b245 100644
--- a/client/src/components/meatspace/post/DrillQuestionReview.test.jsx
+++ b/client/src/components/meatspace/post/DrillQuestionReview.test.jsx
@@ -230,3 +230,26 @@ describe('DrillQuestionReview — schulte-table / reaction-time timing review',
expect(screen.getByText('Correct')).toBeInTheDocument();
});
});
+
+describe('DrillQuestionReview — estimation grading band', () => {
+ // The Expected column shows the exact answer, so a ✓ next to "600 vs 616"
+ // only makes sense once the tolerance it was graded against is on screen.
+ const questions = [
+ { prompt: '925 - 309', expected: 616, answered: 600, correct: true, responseMs: 3100 },
+ ];
+
+ it('names the band a live result was graded against', () => {
+ render(<DrillQuestionReview type="estimation" questions={questions} config={{ tolerancePct: 10 }} />);
+ expect(screen.getByText('Within 10% counts — 2 significant figures is close enough')).toBeInTheDocument();
+ });
+
+ it('falls back to the default band when the record predates a stored tolerance', () => {
+ render(<DrillQuestionReview type="estimation" questions={questions} />);
+ expect(screen.getByText(/Within 10% counts/)).toBeInTheDocument();
+ });
+
+ it('stays out of an exactly-graded drill review', () => {
+ render(<DrillQuestionReview type="multiplication" questions={questions} config={{ count: 5 }} />);
+ expect(screen.queryByText(/significant figure/)).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/meatspace/post/EstimationPrecision.jsx b/client/src/components/meatspace/post/EstimationPrecision.jsx
new file mode 100644
index 0000000000..de6a009764
--- /dev/null
+++ b/client/src/components/meatspace/post/EstimationPrecision.jsx
@@ -0,0 +1,14 @@
+import { estimationToleranceText } from '../../../lib/estimationTolerance.js';
+
+/**
+ * The one statement of an estimation drill's grading band, shown wherever a
+ * question or its answer key is: a bare `309 - 925` leaves the drillee guessing
+ * how precise to be, and an Expected column showing 616 beside an accepted 600
+ * reads as a scoring bug until the band is named.
+ *
+ * Callers gate on the drill type and pass the typography for their surface, so
+ * the copy itself has exactly one owner.
+ */
+export default function EstimationPrecision({ tolerancePct, className = 'text-sm text-gray-400' }) {
+ return <div className={className}>{estimationToleranceText(tolerancePct)}</div>;
+}
diff --git a/client/src/components/meatspace/post/PostDrillRunner.jsx b/client/src/components/meatspace/post/PostDrillRunner.jsx
index 0032bbec3e..8d5efe1360 100644
--- a/client/src/components/meatspace/post/PostDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostDrillRunner.jsx
@@ -4,6 +4,15 @@ import { CheckCircle, XCircle } from 'lucide-react';
import { MEMORY_DRILL_TYPES, DRILL_LABELS } from './constants';
import { powersBreakdownFromPrompt } from '../../../lib/powersBreakdown.js';
import { shouldIgnoreGlobalKey } from '../../../lib/a11yKeyboard.js';
+import EstimationPrecision from './EstimationPrecision';
+
+// Answer-input copy for the drill types that need their own wording. Types not
+// listed here (including every text/memory drill) take the default.
+const INPUT_COPY = {
+ 'applied-numeracy': { placeholder: 'Number (unit optional)', ariaLabel: 'Your numeric answer' },
+ estimation: { placeholder: 'Estimate', ariaLabel: 'Your estimate' },
+};
+const DEFAULT_INPUT_COPY = { placeholder: 'Answer', ariaLabel: 'Your answer' };
function PowersLesson({ prompt }) {
const breakdown = powersBreakdownFromPrompt(prompt);
@@ -142,6 +151,8 @@ export default function PostDrillRunner({ session }) {
// 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 isEstimation = currentDrill.type === 'estimation';
+ const inputCopy = INPUT_COPY[currentDrill.type] || DEFAULT_INPUT_COPY;
const timePct = timeLimitMs > 0 ? (timeLeft / timeLimitMs) * 100 : 0;
const progressPct = totalQuestions > 0 ? ((currentQuestionIndex + 1) / totalQuestions) * 100 : 0;
@@ -198,6 +209,7 @@ export default function PostDrillRunner({ session }) {
<>
<div className="text-sm text-gray-400">Expected</div>
<div className="text-3xl font-mono font-bold text-port-success">{lastAnswer.expected}</div>
+ {isEstimation && <EstimationPrecision tolerancePct={currentDrill.config?.tolerancePct} />}
</>
)}
<PowersLesson prompt={lastAnswer.prompt} />
@@ -271,6 +283,9 @@ export default function PostDrillRunner({ session }) {
<div className="text-4xl font-mono font-bold text-white">
{question?.prompt}
</div>
+ {isEstimation && (
+ <EstimationPrecision tolerancePct={currentDrill.config?.tolerancePct} className="mt-3 text-sm text-gray-400" />
+ )}
</div>
{/* Input */}
@@ -304,8 +319,8 @@ export default function PostDrillRunner({ session }) {
inputMode={isTextDrill ? 'text' : isAppliedNumeracy ? 'decimal' : 'numeric'}
value={inputValue}
onChange={e => setInputValue(e.target.value)}
- placeholder={isAppliedNumeracy ? 'Number (unit optional)' : 'Answer'}
- aria-label={isAppliedNumeracy ? 'Your numeric answer' : 'Your answer'}
+ placeholder={inputCopy.placeholder}
+ aria-label={inputCopy.ariaLabel}
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 92db72d924..2f546d2c56 100644
--- a/client/src/components/meatspace/post/PostDrillRunner.test.jsx
+++ b/client/src/components/meatspace/post/PostDrillRunner.test.jsx
@@ -103,3 +103,70 @@ describe('PostDrillRunner multi-blank recall', () => {
]);
});
});
+
+describe('PostDrillRunner estimation precision', () => {
+ const estimationSession = (overrides = {}) => ({
+ currentDrill: {
+ type: 'estimation',
+ config: { count: 5, tolerancePct: 10 },
+ questions: [{ prompt: '925 - 309', expected: 616 }],
+ timeLimitSec: 120,
+ },
+ currentQuestionIndex: 0,
+ currentDrillIndex: 0,
+ drillCount: 1,
+ state: 'drilling',
+ isTraining: false,
+ lastAnswer: null,
+ submitAnswer: vi.fn(),
+ skipQuestion: vi.fn(),
+ acknowledgeAnswer: vi.fn(),
+ timeExpired: vi.fn(),
+ ...overrides,
+ });
+
+ it('states the tolerance and the precision it implies beside the question', () => {
+ render(<PostDrillRunner session={estimationSession()} />);
+
+ expect(screen.getByText('Within 10% counts — 2 significant figures is close enough')).toBeInTheDocument();
+ expect(screen.getByLabelText('Your estimate')).toBeInTheDocument();
+ expect(screen.getByPlaceholderText('Estimate')).toBeInTheDocument();
+ });
+
+ it('tracks a tightened tolerance rather than hardcoding the default band', () => {
+ render(<PostDrillRunner session={estimationSession({
+ currentDrill: {
+ type: 'estimation',
+ config: { count: 5, tolerancePct: 3 },
+ questions: [{ prompt: '925 - 309', expected: 616 }],
+ timeLimitSec: 120,
+ },
+ })} />);
+
+ expect(screen.getByText('Within 3% counts — 3 significant figures is close enough')).toBeInTheDocument();
+ });
+
+ it('repeats the rule with the answer key so a near miss reads as a near miss', () => {
+ render(<PostDrillRunner session={estimationSession({
+ isTraining: true,
+ lastAnswer: { prompt: '925 - 309', expected: 616, answered: 500, correct: false },
+ })} />);
+
+ expect(screen.getByText('616')).toBeInTheDocument();
+ expect(screen.getByText('Within 10% counts — 2 significant figures is close enough')).toBeInTheDocument();
+ });
+
+ it('leaves an exactly-graded drill alone', () => {
+ render(<PostDrillRunner session={estimationSession({
+ currentDrill: {
+ type: 'multiplication',
+ config: { count: 5 },
+ questions: [{ prompt: '12 x 13', expected: 156 }],
+ timeLimitSec: 120,
+ },
+ })} />);
+
+ expect(screen.queryByText(/significant figure/)).not.toBeInTheDocument();
+ expect(screen.getByLabelText('Your answer')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/meatspace/post/PostSessionResults.test.jsx b/client/src/components/meatspace/post/PostSessionResults.test.jsx
index f0d8f9aed4..8b390fda5d 100644
--- a/client/src/components/meatspace/post/PostSessionResults.test.jsx
+++ b/client/src/components/meatspace/post/PostSessionResults.test.jsx
@@ -154,3 +154,27 @@ describe('PostSessionResults daily routine actions', () => {
expect(onSaved).toHaveBeenCalledWith(saved, { continueDaily: true });
});
});
+
+describe('PostSessionResults estimation grading band', () => {
+ // A live drill result carries its resolved `config`; a stored history task
+ // carries the same map as `difficulty`. Both have to reach the review, or a
+ // ✓ beside "600 / Expected 616" reads as a scoring bug.
+ const estimationResult = (overrides) => ({
+ type: 'estimation',
+ score: 80,
+ questions: [{ prompt: '925 - 309', expected: 616, answered: 600, correct: true, responseMs: 3000 }],
+ ...overrides,
+ });
+
+ it('names the band from a live result config', () => {
+ renderResults({ drillResults: [estimationResult({ config: { count: 5, tolerancePct: 20 } })] });
+ fireEvent.click(screen.getByText('Estimation'));
+ expect(screen.getByText('Within 20% counts — 2 significant figures is close enough')).toBeInTheDocument();
+ });
+
+ it('names it from a history task, whose config is stored as `difficulty`', () => {
+ renderResults({ drillResults: [estimationResult({ difficulty: { count: 5, tolerancePct: 3 } })] });
+ fireEvent.click(screen.getByText('Estimation'));
+ expect(screen.getByText('Within 3% counts — 3 significant figures is close enough')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/meatspace/post/PostSessionSummary.jsx b/client/src/components/meatspace/post/PostSessionSummary.jsx
index 3cf4c2dc41..10e2f8ef44 100644
--- a/client/src/components/meatspace/post/PostSessionSummary.jsx
+++ b/client/src/components/meatspace/post/PostSessionSummary.jsx
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { CheckCircle, ChevronDown, ChevronUp, Dumbbell } from 'lucide-react';
-import { LLM_DRILL_TYPES, DRILL_TO_DOMAIN, DOMAINS, DRILL_LABELS, nBackBalancedAccuracy } from './constants';
+import { LLM_DRILL_TYPES, DRILL_TO_DOMAIN, DOMAINS, DRILL_LABELS, nBackBalancedAccuracy, drillResultConfig } from './constants';
import DrillQuestionReview from './DrillQuestionReview';
function fillBlankAttempts(questions) {
@@ -187,7 +187,12 @@ export default function PostSessionSummary({ drillResults = [], sessionScore = 0
{/* Math / Memory / Cognitive per-question review */}
{!isLlm && isExpanded && (result.questions?.length > 0) && (
<div className="mt-2 ml-2 bg-port-bg border border-port-border rounded p-3">
- <DrillQuestionReview type={result.type} questions={result.questions} drillData={result.drillData} />
+ <DrillQuestionReview
+ type={result.type}
+ questions={result.questions}
+ drillData={result.drillData}
+ config={drillResultConfig(result)}
+ />
</div>
)}
</div>
diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.js
index bf4a0b6166..b3f2db4fa9 100644
--- a/client/src/components/meatspace/post/constants.js
+++ b/client/src/components/meatspace/post/constants.js
@@ -451,3 +451,12 @@ export const getDifficultyColor = (difficulty) => {
// Re-exported from the leaf both server/services/meatspacePost.js and this
// file used to carry separate copies of.
export { nBackBalancedAccuracy } from '../../../../../server/lib/postScoring.js';
+
+/**
+ * The resolved config of a drill result, under whichever name that result
+ * carries it: a live in-session result keeps `config`, while a stored history
+ * task persists the same map as `difficulty` (see `postSessionTaskSchema` in
+ * `server/lib/postValidation.js`). Anything reading a drill's settings back out
+ * of a result has to handle both, so it is named once here.
+ */
+export const drillResultConfig = (result) => result?.config || result?.difficulty || null;
diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.js
index 2b26600541..2080841c5a 100644
--- a/client/src/hooks/usePostSession.js
+++ b/client/src/hooks/usePostSession.js
@@ -3,6 +3,7 @@ import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTraining
import toast from '../components/ui/Toast';
import { safeReadJsonSession, safeRemoveSession, safeWriteJsonSession } from '../lib/safeStorage.js';
import { uuidv4 } from '../lib/uuid.js';
+import { resolveEstimationTolerancePct } from '../../../server/lib/postScoring.js';
import {
LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, DRILL_TO_DOMAIN, countLlmCorrect,
WORDPLAY_LLM_DRILL_TYPES, LLM_TRAINING_CORRECT_THRESHOLD, appliedNumeracyAnswerCorrect,
@@ -350,7 +351,9 @@ export function usePostSession() {
} else if (currentDrill.type === 'estimation') {
const raw = (value === null || String(value).trim() === '') ? null : Number(value);
answered = (raw !== null && isNaN(raw)) ? null : raw;
- const tolerance = (currentDrill.config?.tolerancePct || 10) / 100;
+ // Same resolver the server rescore uses, so this optimistic ✓/✗ and the
+ // band the drill UI states on screen can never disagree with the saved score.
+ const tolerance = resolveEstimationTolerancePct(currentDrill.config?.tolerancePct) / 100;
correct = answered !== null && Math.abs(answered - q.expected) <= Math.abs(q.expected * tolerance);
} else {
const raw = (value === null || String(value).trim() === '') ? null : Number(value);
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e30180c552..ff92b27076 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -218,6 +218,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `songBookDraft.js` | SongBook editor save/dirty boundary: `buildSongBookPatch(draft, savedDraft)` preserves unchanged-link omission; `songBookDraftsEqual(a, b)` compares the same serialized values. Exports `SCROLL_DURATION_MIN/MAX` for the form. Page owns defaults and lifecycle; add save normalization here so the navigation guard follows. |
| `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. |
| `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. |
+| `estimationTolerance.js` | `estimationToleranceText(tolerancePct)` → the one line an estimation drill shows to say how precise to be, e.g. "Within 10% counts — 2 significant figures is close enough". Converts the grading band into significant figures (scale-free: rounding to `n` of them is worst-case `0.5 x 10^(1-n)` off, so the smallest `n` that fits the band IS the precision required), because a percentage of an answer you have not worked out yet is not actionable mid-drill. Reads the band through `resolveEstimationTolerancePct` (`server/lib/postScoring.js`), the same resolver both graders use, so the copy can never claim a band the ✓/✗ did not apply. Rendered by `components/meatspace/post/EstimationPrecision.jsx`. Pure, DOM-free. |
| `powersBreakdown.js` | Pure, DOM-free Powers mental-math lessons — maps supported base/exponent pairs to named techniques and deterministic worked steps for drill misses and historical review. |
| `promptStageGroups.js` | Search + grouping for the Prompt Manager's Stages pane (#3284). `buildStageGroups(stages, { query, systemOnly, systemStageKeys })` → `{ groups, matchCount, totalCount }`, filtering the `{ key: config }` stage map on title + description + key (AND-token, reusing `mediaSearch.js`'s `tokenizeQuery`/`matchHaystack`) and bucketing survivors into ordered `[{ key, label, stages: [[key, config], …] }]` groups (`Other` pinned last). `stageGroupLabel(name)` derives the family from the `Family — Specific` dash convention (em dash, en dash, or a spaced ASCII hyphen — a user typing their own stage name reaches for the last), falling back to the `STAGE_WORD_PREFIXES` word list (`CoS Agent Briefing`) and then `Other`; `stageGroupKey(label)` case-folds it into the group's identity, so `Pipeline — X` and `pipeline — y` are one group rather than twin headers that render alike under `uppercase`; `stageGroupLabelFor(key, config)` / `stageGroupKeyFor(key, config)` are the name-or-key forms both the bucketing and the page's auto-expand call, so a deep-linked stage opens the group it actually renders in. `stageHaystack(key, config)` is the searchable string. The system-stage list is NOT mirrored here — `GET /api/prompts` ships it as `systemStages` from `server/lib/promptSystemStages.js` and the page threads it in as `systemStageKeys` (#3314). Pure — no React, no I/O. |
| `spriteCollectionActions.js` | Gating for the Sprite Manager asset collection's inline actions (#2931). `buildCollectionActions({ detail, walkPending, referencePending, generateWalk, generateAnchor, onRequestTrim })` → `{ regenerateFor(asset), trimFor(asset) }`, each returning `null` for an asset it can't act on. Regenerate mirrors the authoritative workflow surfaces exactly — a walk direction is regenerable only when its anchor is locked, the direction isn't approved, the walk set isn't finalized and no render is in flight; a reference anchor only while it's an unlocked candidate (`south`/main is excluded, since it needs a design prompt or upload). Trim is offered only for a run that actually packed a strip (the trim endpoint 409s otherwise). Each actionable regenerate also names the `correctionKey` (#3134) the card binds its inline correction note to — `walk:<dir>` for a walk output, the bare direction for an anchor — so the card can never write a still-image note into a video re-roll. Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js` and the key vocabulary from `spriteCorrections.js`. |
diff --git a/client/src/lib/estimationTolerance.js b/client/src/lib/estimationTolerance.js
new file mode 100644
index 0000000000..1bdb914167
--- /dev/null
+++ b/client/src/lib/estimationTolerance.js
@@ -0,0 +1,47 @@
+/**
+ * Estimation-drill precision copy.
+ *
+ * Estimation drills grade within a percentage band of the exact answer, but a
+ * bare "309 - 925" tells the drillee nothing about how precise to be — are they
+ * estimating to the nearest 10, or the nearest 100? A percentage is also not
+ * directly actionable mid-drill, because it is a percentage of an answer they
+ * have not worked out yet.
+ *
+ * Significant figures are the scale-free way to say it. Rounding a value to `n`
+ * significant figures costs at most half a unit in the nth place, so the worst
+ * relative error is 0.5 x 10^(1-n) regardless of the answer's magnitude: ~50%
+ * at 1 sig fig, ~5% at 2, ~0.5% at 3. The smallest `n` whose worst case fits
+ * inside the tolerance band is the precision the drillee actually has to hit.
+ *
+ * The band itself comes from `server/lib/postScoring.js` — the same resolver
+ * grading reads, so this copy can never claim a band the ✓/✗ didn't use.
+ */
+
+import { resolveEstimationTolerancePct } from '../../../server/lib/postScoring.js';
+import { pluralize } from './textUtils.js';
+
+// 6 covers a 0.00005% band — far past the 1-50% the config allows, and past
+// anything a person estimates in their head. The cap only exists so a tolerance
+// of 0 (exact match) can't spin the loop.
+const MAX_SIGNIFICANT_FIGURES = 6;
+
+/**
+ * Fewest significant figures whose worst-case rounding error still lands inside
+ * the tolerance band.
+ */
+function significantFiguresFor(tolerancePct) {
+ const tolerance = tolerancePct / 100;
+ for (let n = 1; n < MAX_SIGNIFICANT_FIGURES; n++) {
+ if (0.5 * Math.pow(10, 1 - n) <= tolerance) return n;
+ }
+ return MAX_SIGNIFICANT_FIGURES;
+}
+
+/**
+ * One line of drill copy stating both the grading rule and the precision it
+ * implies, e.g. "Within 10% counts — 2 significant figures is close enough".
+ */
+export function estimationToleranceText(tolerancePct) {
+ const pct = resolveEstimationTolerancePct(tolerancePct);
+ return `Within ${pct}% counts — ${pluralize(significantFiguresFor(pct), 'significant figure')} is close enough`;
+}
diff --git a/client/src/lib/estimationTolerance.test.js b/client/src/lib/estimationTolerance.test.js
new file mode 100644
index 0000000000..7e980c34da
--- /dev/null
+++ b/client/src/lib/estimationTolerance.test.js
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+
+import { estimationToleranceText } from './estimationTolerance.js';
+
+// Rounding a value to `n` significant figures must never push it outside the
+// band the copy claims — and `n - 1` figures must genuinely miss it, or the
+// drill is demanding more precision than it says.
+const roundToSigFigs = (value, figures) => {
+ const magnitude = Math.pow(10, Math.floor(Math.log10(Math.abs(value))) - figures + 1);
+ return Math.round(value / magnitude) * magnitude;
+};
+
+const figuresClaimedBy = (text) => Number(text.match(/(\d+) significant figure/)[1]);
+
+describe('estimationToleranceText', () => {
+ it('states the grading rule and the precision it implies', () => {
+ expect(estimationToleranceText(10)).toBe('Within 10% counts — 2 significant figures is close enough');
+ });
+
+ it('singularizes a one-figure target', () => {
+ expect(estimationToleranceText(50)).toBe('Within 50% counts — 1 significant figure is close enough');
+ });
+
+ it.each([
+ [50, 1], // the 1↔2 boundary: 1 sig fig is worst-case 50% off
+ [20, 2],
+ [5, 2], // the 2↔3 boundary: 2 sig figs is worst-case 5% off
+ [3, 3],
+ ])('%i%% tolerance claims %i significant figure(s)', (tolerancePct, expected) => {
+ expect(figuresClaimedBy(estimationToleranceText(tolerancePct))).toBe(expected);
+ });
+
+ it.each([50, 20, 10, 5, 3, 1])('the figures claimed for a %i%% band are exactly enough', (tolerancePct) => {
+ const figures = figuresClaimedBy(estimationToleranceText(tolerancePct));
+ const band = (value) => Math.abs(value * (tolerancePct / 100));
+
+ // Scale-free: one value near 1, one large, both just past a rounding
+ // midpoint where the relative error of rounding is worst.
+ for (const value of [1 + Math.pow(10, 1 - figures) / 2, 285825]) {
+ expect(Math.abs(roundToSigFigs(value, figures) - value)).toBeLessThanOrEqual(band(value));
+ }
+
+ if (figures > 1) {
+ const tooCoarse = figures - 1;
+ const value = 1 + Math.pow(10, 1 - tooCoarse) / 2;
+ expect(Math.abs(roundToSigFigs(value, tooCoarse) - value)).toBeGreaterThan(band(value));
+ }
+ });
+
+ it('falls back to the shipped 10% band when the drill carried no usable tolerance', () => {
+ // A drill generated without an explicit tolerance omits the key, and both
+ // graders default it to 10 — the copy has to say the same number.
+ for (const value of [undefined, null, '', -5, NaN, 'wide']) {
+ expect(estimationToleranceText(value)).toBe('Within 10% counts — 2 significant figures is close enough');
+ }
+ });
+
+ it('honors a 0% band as exact match rather than reading it as unset', () => {
+ // `resolveEstimationTolerancePct` is deliberately not a `|| DEFAULT`: a 0
+ // tolerance means the server grades exact-match, so the copy must not
+ // promise a 10% band the ✓/✗ will not honor.
+ expect(estimationToleranceText(0)).toBe('Within 0% counts — 6 significant figures is close enough');
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index e6fa4248fb..a693d7d3bc 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -157,6 +157,7 @@ export * from './drumPlayback.js';
export * from './editorialChecks.js';
export * from './editorialHealth.js';
export * from './episodeSceneImport.js';
+export * from './estimationTolerance.js';
export * from './lookaheadTransport.js';
export * from './lossSparkline.js';
export * from './managedAppSources.js';
diff --git a/server/lib/README.md b/server/lib/README.md
index 9ccf9205d6..a65d6d052a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -495,7 +495,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `spacedRepetition.js` | The shared SM-2-inspired review scheduler, extracted from `services/meatspacePostMemory.js` when SongBook practice became its second consumer (#4102). One four-field schedule shape (`{ ease, intervalDays, nextReview, lastReviewed }`, no `repetitions` counter — the 0 → 1 → 6 → `round(prev * ease)` ladder derives from the previous interval, so a schedule round-trips through import/export/federation on those four fields alone). `advanceSchedule(schedule, ratio, now)` is the core (ease clamped to `MIN_EASE`..`MAX_EASE`, interval capped at `MAX_INTERVAL_DAYS` so `new Date(now + interval*DAY)` can't overflow into an Invalid Date; quality < 3 zeroes the interval to resurface the record but still applies the ease penalty). `mergeScheduleAdvance(prev, advanced, now)` gates interval GROWTH to once per review day (a shrink always applies) for UIs that submit per chunk/section; `isSameReviewDay` is that gate's own predicate, reusable by callers gating their own once-a-day progression. `scheduleOrDefault(record, schedule?)` is the read-path fallback — a record with no schedule derives one anchored to its `updatedAt`/`createdAt` (stable and in the past → due now), so "due" can't flap between two reads a millisecond apart. `ratioToQuality` / `qualityToRatio` are exact inverses over the integers, so a self-graded 0..5 review lands on the quality the user picked. `isScheduleDue` treats an absent/unparseable `nextReview` as due — a record we can't schedule is one to surface, never one to hide forever. Pure. |
| `songPractice.js` | SongBook repertoire practice scheduling (#4102) — the pure core behind `POST /api/brain/songbook/:id/practice`. `applySongPractice(song, quality, now)` → `{ stage, practice }`, the exact partial to hand `brainStorage.updateWith`: it advances the shared `spacedRepetition` schedule from a 0..5 self-grade and moves the song's `stage` along `SONG_STAGE_ORDER` (≥ `SONG_PROMOTE_MIN_QUALITY` promotes, ≤ `SONG_REGRESS_MAX_QUALITY` regresses, a 3 holds). Promotion is gated to once per practice day (regression never is), and a practiced song floors at `learning` — `new` means "never picked up", which stops being true after one session. `songPracticeOrDefault(song)` derives the schedule on READ for every song predating the feature (nothing is backfilled to disk: a migration would restamp `updatedAt` on every record and spray federation churn, and would break the `data.reference/` seeds' byte-identity). `nextSongStage` no-ops on a stage this install doesn't recognize, so a practice log can't rewrite a value synced from a newer peer. `isSongDue(song, now)` mirrors the client's `songDueAt` in `client/src/components/songbook/constants.js`. Pure. |
| `postTopics.js` | Pure POST practice-topic registry — `POST_TOPICS` (`{ id, label, module, surface, drillTypes }`) is the single source of truth for "what am I studying?", plus `resolveTopicForDrillType` / `isTopicEnabled` / `isMemoryItemEnabled`. Gates session composition and recommendations, including Memory's composed and dedicated practice routes plus standalone Morse. A pure leaf: the client's post `constants.js` re-exports it and layers the UI-only `TOPIC_UI` on top. |
-| `postScoring.js` | Scoring and accuracy helpers for post-training drill types shared between server (`services/meatspacePost.js`) and client (`components/meatspace/post/constants.js`) — `nBackBalancedAccuracy` (balanced signal-detection accuracy for n-back questions). |
+| `postScoring.js` | Scoring and accuracy helpers for post-training drill types shared between server (`services/meatspacePost.js`) and client (`components/meatspace/post/constants.js`) — `nBackBalancedAccuracy` (balanced signal-detection accuracy for n-back questions), plus `DEFAULT_ESTIMATION_TOLERANCE_PCT` / `resolveEstimationTolerancePct(pct)` — the single estimation band that server grading, the client's optimistic check, and the on-screen "within N%" copy all read, so the number shown and the number graded cannot drift. |
| `postRotation.js` | Pure deterministic day-based rotation for POST practice selection — `shuffleForDay` supplies a stable pseudorandom daily mix; `orderByRecencyRotation` sorts candidates fresh-before-recently-practiced, then by priority, and rotates equivalent ones by local day so a tier never pins to one drill. Mirrored at `client/src/lib/postRotation.js`. |
| `postStreak.js` | Pure DST-safe POST practice-streak math — the single `computePostStreaks` implementation shared by scored sessions and the training log, plus `computeUnifiedStreak` (a day is active with EITHER a session or a practice entry), `normalizeYmd` (day-key prefix for a date that may be a full ISO timestamp), and `recordDayKey` / `withDerivedDayKeys` (re-derive a record's day key from its `startedAt`/`completedAt`/`timestamp` instant, so readers ignore a `date` frozen in a previously-configured timezone). |
| `activeDays.js` | Cross-domain "days active" set math (#4120) — `unionActiveDayKeys(sources, timezone)` unions several domains' stored date values into one sorted array of user-local `YYYY-MM-DD` keys (`.length` is the honest day count; summing per-domain counts would double-count any day logged in two domains), and `toUserDayKey(value, timezone)` is its per-value normalizer. Owns the day-boundary reconciliation between POST (stamps `userLocalToday()`) and the health logs (stamp the server-local `getDateString()`): a value carrying an INSTANT (the pre-#2681 full-ISO shape some legacy training entries still store) is re-keyed into the user's timezone rather than `split('T')[0]`'d to the UTC day, while a value that is already a bare day LABEL is taken as authored — there is no instant left to re-derive from, so retro-normalizing stored health keys is out of scope by construction, not by omission. Non-day values are dropped rather than coerced. Pure. |
diff --git a/server/lib/postScoring.js b/server/lib/postScoring.js
index a4d067f0d4..07923b22a8 100644
--- a/server/lib/postScoring.js
+++ b/server/lib/postScoring.js
@@ -23,3 +23,27 @@ export function nBackBalancedAccuracy(questions) {
const crRate = correctRejections + falseAlarms ? correctRejections / (correctRejections + falseAlarms) : null;
return hitRate == null && crRate == null ? null : ((hitRate ?? 0.5) + (crRate ?? 0.5)) / 2;
}
+
+// The estimation band every surface has to agree on. Four copies of this `10`
+// existed — server grading, the client's optimistic check, the shipped drill
+// config, and the adaptive baseline — and the drill UI now states the band on
+// screen, so the number it claims and the number that decides ✓/✗ must be one
+// object.
+export const DEFAULT_ESTIMATION_TOLERANCE_PCT = 10;
+
+/**
+ * Resolve a drill's stored tolerance to the percentage grading will use.
+ *
+ * `0` is a meaningful band — it means grade exact-match — so this is neither a
+ * `|| DEFAULT` fallback (which would read 0 as unset and silently widen the
+ * band to 10%) nor a bare `Number()` coercion: `Number(null)` and `Number('')`
+ * are both 0, so an absent tolerance would come back out as exact-match. Absent
+ * is rejected first, then the value is validated.
+ */
+export function resolveEstimationTolerancePct(tolerancePct) {
+ if (tolerancePct === null || tolerancePct === undefined || tolerancePct === '') {
+ return DEFAULT_ESTIMATION_TOLERANCE_PCT;
+ }
+ const pct = Number(tolerancePct);
+ return Number.isFinite(pct) && pct >= 0 ? pct : DEFAULT_ESTIMATION_TOLERANCE_PCT;
+}
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index b610485437..9f1c7a566d 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -11,7 +11,7 @@ import { EventEmitter } from 'events';
import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
import { deepMerge } from '../lib/objects.js';
import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';
-import { nBackBalancedAccuracy } from '../lib/postScoring.js';
+import { nBackBalancedAccuracy, resolveEstimationTolerancePct } from '../lib/postScoring.js';
import { normalizeHistoricalPostLlmEvaluation, normalizePostLlmEvaluation } from '../lib/postLlmContracts.js';
import { resolveTopicForDrillType, isTopicEnabled, isMemoryItemEnabled } from '../lib/postTopics.js';
import {
@@ -1719,11 +1719,14 @@ export function generateSerialSubtraction(start, subtrahend = 7, steps = 10, sta
return { type: 'serial-subtraction', config: { startValue: startVal, subtrahend, steps }, questions };
}
+// Random integer in [min, max], inclusive.
+function between(min, max) {
+ return Math.floor(Math.random() * (max - min + 1)) + min;
+}
+
// Random integer with exactly `digits` digits (1 → 1-9, 2 → 10-99, …).
function randInt(digits) {
- const maxVal = Math.pow(10, digits) - 1;
- const minVal = digits > 1 ? Math.pow(10, digits - 1) : 1;
- return Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;
+ return between(digits > 1 ? Math.pow(10, digits - 1) : 1, Math.pow(10, digits) - 1);
}
/**
@@ -1792,26 +1795,29 @@ export function generatePowers(bases, maxExponent = 10, count = 8, level = null,
return { type: 'powers', config: { bases, maxExponent, count }, questions };
}
+const MIN_ESTIMATION_DIFFERENCE = 100;
+
+// Subtraction operands, larger first and at least MIN_ESTIMATION_DIFFERENCE
+// apart. Two independently-drawn 3-digit numbers land closer than that about a
+// fifth of the time, and a PERCENTAGE tolerance of a tiny difference is a
+// sub-unit band — `509 - 499` grades to ±1 at the default 10%, exact arithmetic
+// wearing an estimation label. Keeping the answer itself 3-digit is what rules
+// that out; how precise the drillee must then be is the tolerance's job to say,
+// and the drill UI states it. Ordering the pair also settles whether a
+// `309 - 925` prompt wants 616 or -616.
+function estimationSubtractionPair() {
+ const hi = between(100 + MIN_ESTIMATION_DIFFERENCE, 999);
+ return [hi, between(100, hi - MIN_ESTIMATION_DIFFERENCE)];
+}
+
export function generateEstimation(count = 5, tolerancePct) {
const ops = ['+', '-', 'x'];
const questions = [];
for (let i = 0; i < count; i++) {
- const a = Math.floor(Math.random() * 900) + 100; // 100-999
- const b = Math.floor(Math.random() * 900) + 100;
const op = ops[Math.floor(Math.random() * ops.length)];
- let expected;
- let prompt;
- if (op === '+') {
- expected = a + b;
- prompt = `${a} + ${b}`;
- } else if (op === '-') {
- expected = a - b;
- prompt = `${a} - ${b}`;
- } else {
- expected = a * b;
- prompt = `${a} x ${b}`;
- }
- questions.push({ prompt, expected });
+ const [a, b] = op === '-' ? estimationSubtractionPair() : [randInt(3), randInt(3)];
+ const expected = op === '+' ? a + b : op === '-' ? a - b : a * b;
+ questions.push({ prompt: `${a} ${op} ${b}`, expected });
}
const config = { count };
if (tolerancePct != null) config.tolerancePct = tolerancePct;
@@ -2138,7 +2144,7 @@ export function scoreDrill(type, questions, timeLimitMs, config = {}) {
if (expected == null || answered == null || isNaN(answered)) {
correct = false;
} else if (type === 'estimation') {
- const tolerance = ((config.tolerancePct ?? 10) / 100);
+ const tolerance = resolveEstimationTolerancePct(config.tolerancePct) / 100;
correct = Math.abs(answered - expected) <= Math.abs(expected * tolerance);
} else {
correct = answered === expected;
diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.js
index e5f88f586c..20a5b9e6bf 100644
--- a/server/services/meatspacePost.test.js
+++ b/server/services/meatspacePost.test.js
@@ -551,6 +551,22 @@ describe('generateEstimation', () => {
}
});
+ it('keeps subtraction answerable BY ESTIMATING — larger first, at least 100 apart', () => {
+ // A percentage tolerance of a tiny difference is a sub-unit band: two
+ // independently-drawn 3-digit numbers land within 100 of each other about a
+ // fifth of the time, and `509 - 499` then grades to ±1 at the default 10% —
+ // exact arithmetic wearing an estimation label. Keeping the answer 3-digit
+ // is what rules that out; a tightened adaptive rung is knowingly harder
+ // than that, and the drill UI states the precision it demands. Ordering the
+ // pair also settles whether `309 - 925` wants 616 or -616.
+ const subtractions = generateEstimation(60).questions.filter(q => q.prompt.includes(' - '));
+ expect(subtractions.length).toBeGreaterThan(0);
+ for (const q of subtractions) {
+ const [a, b] = q.prompt.split(' - ').map(Number);
+ expect(a).toBeGreaterThanOrEqual(b + 100);
+ }
+ });
+
it('preserves tolerancePct in config when provided', () => {
const result = generateEstimation(3, 25);
expect(result.config.tolerancePct).toBe(25);
@@ -731,6 +747,20 @@ describe('scoreDrill', () => {
expect(q5[0].correct).toBe(false);
});
+ it('grades an absent tolerance at the default band, and an explicit 0 as exact match', () => {
+ // `resolveEstimationTolerancePct` distinguishes the two: 0 is a real band
+ // (exact), so it cannot be read as "unset" — and null/undefined cannot be
+ // coerced through `Number()` into 0, which would grade exact-match on a
+ // drill the UI told the user was a 10% band.
+ const near = [{ prompt: '500 + 300', answered: 850, responseMs: 1000 }];
+ const exact = [{ prompt: '500 + 300', answered: 800, responseMs: 1000 }];
+ for (const config of [{}, { tolerancePct: null }, { tolerancePct: undefined }]) {
+ expect(scoreDrill('estimation', near, 60000, config).questions[0].correct).toBe(true);
+ }
+ expect(scoreDrill('estimation', near, 60000, { tolerancePct: 0 }).questions[0].correct).toBe(false);
+ expect(scoreDrill('estimation', exact, 60000, { tolerancePct: 0 }).questions[0].correct).toBe(true);
+ });
+
it('coerces string answered values to numbers', () => {
const questions = [
{ prompt: '5 x 3', answered: '15', responseMs: 1000 },