Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (claude): prevent ladder demotion when window evidence ages out
Adam Eivyc15a551c751a
diff --git a/server/lib/postMultiplicationLadder.js b/server/lib/postMultiplicationLadder.jsindex c0b4276c03..c241378871 100644--- a/server/lib/postMultiplicationLadder.js+++ b/server/lib/postMultiplicationLadder.js@@ -47,8 +47,15 @@ export const MASTERY_DEFAULTS = {// A [1,1] rung (2 total digits) targets ~4.4s but is floored at minTargetMs.baseMsPerFactorDigit: 2200,minTargetMs: 4000,- // Stats window (days) the mastery signal is read over.+ // Stats window (days) the mastery signal is read over. Mastery is judged over+ // this rolling window so "fast enough to advance" reflects recent performance,+ // NOT stale reps — but earned rungs never age out (see `floorLevel` below).windowDays: 30,+ // Answered questions slower than this are clamped before averaging, so one+ // walked-away-from-the-tab answer can't inflate a rung's avgResponseMs and+ // make it feel un-masterable. Mirrors scoreDrill's per-question clamp; set at+ // the default multiplication time limit (120s).+ responseMsCap: 120000,};export function clampMultiplicationLevel(level) {@@ -101,16 +108,28 @@ export function isLevelMastered(stat, level, opts = MASTERY_DEFAULTS) {/*** Resolve the user's current ladder level from per-level performance stats.*- * Walks the ladder from the bottom and stops at the first rung the user has NOT- * yet mastered — so they stay there accumulating fast-and-accurate reps until- * the speed bar is cleared, then advance. Returns a transparent explainer with- * every rung's status so the UI can show the ladder.+ * Walks the ladder up from the earned `floorLevel` and stops at the first rung+ * the user has NOT yet mastered (over the recent window) — so they stay there+ * accumulating fast-and-accurate reps until the speed bar is cleared, then+ * advance. Returns a transparent explainer with every rung's status so the UI+ * can show the ladder.+ *+ * `floorLevel` is the highest rung the user has EVER generated (all-time, not+ * windowed). It is the anti-demotion floor: because mastery is judged over a+ * rolling window, a rung's samples fall to 0 once its evidence ages out — but+ * you only ever reach a higher rung by having cleared the ones below it, so+ * earned progress must not be lost when it ages out. Without this floor a user+ * grinding level 3 would snap back to level 0 (`7 × 8`) the day their earliest+ * level-0 sessions crossed the window cutoff.** @param {Record<number|string, {samples:number, accuracy:number, avgResponseMs:number}>} levelStats- * @returns {{level, factors, label, atHardest, currentMastered, levels}}+ * @param {object} [opts] - override MASTERY_DEFAULTS thresholds+ * @param {number} [floorLevel=0] - highest all-time-active rung (earned floor)+ * @returns {{level, factors, label, atHardest, currentMastered, floorLevel, levels}}*/-export function resolveMultiplicationLevel(levelStats = {}, opts = {}) {+export function resolveMultiplicationLevel(levelStats = {}, opts = {}, floorLevel = 0) {const options = { ...MASTERY_DEFAULTS, ...opts };+ const floor = clampMultiplicationLevel(floorLevel);const levels = MULTIPLICATION_LADDER.map((factors, level) => {const stat = levelStats?.[level] || levelStats?.[String(level)] || {};const samples = Number.isFinite(stat.samples) ? stat.samples : 0;@@ -129,9 +148,20 @@ export function resolveMultiplicationLevel(levelStats = {}, opts = {}) {};});- let level = 0;+ // Advance from the earned floor while the current rung's recent performance+ // clears the mastery bar. Starting at `floor` (not 0) prevents involuntary+ // demotion of rungs whose window evidence has aged out.+ let level = floor;while (level < MAX_MULTIPLICATION_LEVEL && levels[level].mastered) level += 1;+ // For the UI: every rung strictly below the resolved level has been cleared+ // (you can't be on rung N without having passed the ones beneath it), so mark+ // it mastered even if its recent window is empty — otherwise the ladder dots+ // would falsely show a cleared rung as un-mastered after it ages out.+ for (const rung of levels) {+ if (rung.level < level) rung.mastered = true;+ }+const current = levels[level];return {level,@@ -139,6 +169,7 @@ export function resolveMultiplicationLevel(levelStats = {}, opts = {}) {label: current.label,atHardest: level >= MAX_MULTIPLICATION_LEVEL,currentMastered: current.mastered,+ floorLevel: floor,levels,};}diff --git a/server/lib/postMultiplicationLadder.test.js b/server/lib/postMultiplicationLadder.test.jsindex 2cff446e62..c01cbfe2ed 100644--- a/server/lib/postMultiplicationLadder.test.js+++ b/server/lib/postMultiplicationLadder.test.js@@ -120,4 +120,28 @@ describe('resolveMultiplicationLevel', () => {const r = resolveMultiplicationLevel({ '0': mastered });expect(r.level).toBe(1);});++ it('never demotes below the earned floor when window evidence has aged out', () => {+ // Empty windowed stats (all reps aged past the window) but the user has+ // earned up to rung 3 all-time — must stay at 3, not snap back to 0.+ const r = resolveMultiplicationLevel({}, {}, 3);+ expect(r.level).toBe(3);+ expect(r.floorLevel).toBe(3);+ // Rungs below the floor render as cleared (mastered) even with no samples.+ expect(r.levels[0].mastered).toBe(true);+ expect(r.levels[2].mastered).toBe(true);+ expect(r.levels[3].mastered).toBe(false);+ });++ it('advances above the floor when the floor rung is freshly mastered', () => {+ const mastered = { samples: 20, accuracy: 1, avgResponseMs: 3000 };+ const r = resolveMultiplicationLevel({ 3: mastered }, {}, 3);+ expect(r.level).toBe(4);+ });++ it('clamps an out-of-range floor into the ladder', () => {+ const r = resolveMultiplicationLevel({}, {}, 999);+ expect(r.level).toBe(MAX_MULTIPLICATION_LEVEL);+ expect(r.floorLevel).toBe(MAX_MULTIPLICATION_LEVEL);+ });});diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 7997b9e716..9800710cb9 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -494,7 +494,14 @@ async function getAdaptiveSignal(type) {* mastered. Only answered questions count as samples; each contributes its* correctness and clamped response time.*- * @returns {Promise<Record<number, {samples:number, accuracy:number, avgResponseMs:number}>>}+ * Returns both the windowed per-level stats (for the mastery decision) and the+ * `floorLevel` — the highest rung the user has EVER generated (all-time, NOT+ * windowed). The floor is the anti-demotion signal: mastery is judged over a+ * rolling window, so a rung's samples fall to 0 once its evidence ages out, but+ * a user only reaches a higher rung by clearing the ones below it, so that+ * earned progress must survive the window (see resolveMultiplicationLevel).+ *+ * @returns {Promise<{stats: Record<number, {samples,accuracy,avgResponseMs}>, floorLevel: number}>}*/async function getMultiplicationLevelStats(windowDays = MASTERY_DEFAULTS.windowDays) {const sessions = await getPostSessions();@@ -506,18 +513,26 @@ async function getMultiplicationLevelStats(windowDays = MASTERY_DEFAULTS.windowD}const byLevel = {};+ let floorLevel = 0;for (const session of sessions) {- if (cutoffStr && session.date < cutoffStr) continue;for (const task of session.tasks || []) {if (task.type !== 'multiplication') continue;const level = Number.isInteger(task.config?.level) ? task.config.level : null;if (level == null) continue; // legacy maxDigits-only tasks carry no level+ // All-time floor: any answered question at this level (regardless of the+ // window) proves the user reached — and thus earned — this rung.+ const anyAnswered = (task.questions || []).some(q => q?.answered != null);+ if (anyAnswered && level > floorLevel) floorLevel = level;+ // Mastery stats are windowed — skip out-of-window sessions for the buckets.+ if (cutoffStr && session.date < cutoffStr) continue;const bucket = byLevel[level] || (byLevel[level] = { samples: 0, correct: 0, totalResponseMs: 0 });for (const q of task.questions || []) {if (q?.answered == null) continue;bucket.samples += 1;if (q.correct) bucket.correct += 1;- bucket.totalResponseMs += Math.max(0, q.responseMs || 0);+ // Clamp so one walked-away answer can't inflate avgResponseMs and block+ // mastery (mirrors scoreDrill's per-question clamp).+ bucket.totalResponseMs += Math.min(Math.max(0, q.responseMs || 0), MASTERY_DEFAULTS.responseMsCap);}}}@@ -530,7 +545,7 @@ async function getMultiplicationLevelStats(windowDays = MASTERY_DEFAULTS.windowDavgResponseMs: b.samples ? b.totalResponseMs / b.samples : 0,};}- return stats;+ return { stats, floorLevel };}/**@@ -538,8 +553,8 @@ async function getMultiplicationLevelStats(windowDays = MASTERY_DEFAULTS.windowD* Exposed for the config UI / route so it can show the ladder + mastery status.*/export async function getMultiplicationProgress() {- const levelStats = await getMultiplicationLevelStats(MASTERY_DEFAULTS.windowDays);- const progression = resolveMultiplicationLevel(levelStats);+ const { stats, floorLevel } = await getMultiplicationLevelStats(MASTERY_DEFAULTS.windowDays);+ const progression = resolveMultiplicationLevel(stats, {}, floorLevel);return { ...progression, windowDays: MASTERY_DEFAULTS.windowDays, thresholds: { minSamples: MASTERY_DEFAULTS.minSamples, targetAccuracy: MASTERY_DEFAULTS.targetAccuracy } };}@@ -565,8 +580,8 @@ export async function resolveDrillConfig(type, requestedConfig = {}) {if (type === 'multiplication') {const mulCfg = config?.mentalMath?.drillTypes?.multiplication || {};if (mulCfg.progressive !== false) {- const levelStats = await getMultiplicationLevelStats(MASTERY_DEFAULTS.windowDays);- const progression = resolveMultiplicationLevel(levelStats);+ const { stats, floorLevel } = await getMultiplicationLevelStats(MASTERY_DEFAULTS.windowDays);+ const progression = resolveMultiplicationLevel(stats, {}, floorLevel);const { maxDigits: _drop, ...rest } = requestedConfig || {};const effective = {...rest,diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex d121a5e12b..508eaf4dbe 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -726,9 +726,9 @@ describe('resolveDrillConfig — progressive multiplication', () => {// Build a session with `n` answered multiplication questions at `level`, all// correct and fast (so the level clears the mastery bar).- function masteredSession(level, n = 14, responseMs = 2500) {+ function masteredSession(level, n = 14, responseMs = 2500, date = today) {return {- date: today,+ date,tasks: [{module: 'mental-math',type: 'multiplication',@@ -738,6 +738,9 @@ describe('resolveDrillConfig — progressive multiplication', () => {};}+ // A date well outside the mastery window (60 days ago).+ const oldDate = new Date(Date.now() - 60 * 86400000).toISOString().split('T')[0];+function mockSessions(sessions, configOverride) {readJSONFile.mockImplementation((path, defaultValue) => {const p = String(path);@@ -783,6 +786,17 @@ describe('resolveDrillConfig — progressive multiplication', () => {expect(config.factors).toBeUndefined();});+ it('does not demote to level 0 when the earned rung aged out of the window', async () => {+ // The user mastered level 2 sixty days ago and hasn't practiced since, so the+ // windowed mastery buckets are empty — but the all-time floor keeps them at 2+ // instead of snapping back to single-digit × single-digit.+ mockSessions([masteredSession(2, 14, 2500, oldDate)]);+ const { progression, config } = await resolveDrillConfig('multiplication', { count: 10 });+ expect(progression.level).toBe(2);+ expect(progression.floorLevel).toBe(2);+ expect(config.factors).toEqual([1, 1, 1]);+ });+it('getMultiplicationProgress exposes the full ladder + thresholds', async () => {mockSessions([masteredSession(0)]);const progress = await getMultiplicationProgress();