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
refactor: break the two meatspacePost re-export import cycles (#5690)
[._.]/ Adam Eivy4e1bcc5ac8b0
diff --git a/server/lib/postProgression.js b/server/lib/postProgression.jsindex fff83d3d35..6e4d45dccb 100644--- a/server/lib/postProgression.js+++ b/server/lib/postProgression.js@@ -172,7 +172,7 @@ export function createProgression(def) {//// Each ladder is an ordered list of generator-config knob objects: rung N's// object is spread into the drill's requested config at generation time (via-// meatspacePost.js resolveDrillConfig), so climbing the ladder literally makes+// meatspacePostAdaptive.js resolveDrillConfig), so climbing the ladder makes// the generated drill harder. `describe` turns a rung into a short label for// the config/preview badge. reaction-time is deliberately absent — it's a// measurement baseline, not a skill ladder.diff --git a/server/routes/meatspacePostRoutes.analytics.test.js b/server/routes/meatspacePostRoutes.analytics.test.jsnew file mode 100644index 0000000000..c7fb177087--- /dev/null+++ b/server/routes/meatspacePostRoutes.analytics.test.js@@ -0,0 +1,105 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++// The three POST analytics/policy endpoints now call the module that DECLARES+// each entry point instead of a convenience re-export off meatspacePost.js+// (#5690). Mocking the declaring modules proves the route is wired to them —+// with the meatspacePost.js mock stubbing only what the router itself still+// touches, so a re-added re-export would not silently satisfy these.+vi.mock('../services/meatspacePostStats.js', () => ({ getPostStats: vi.fn() }));+vi.mock('../services/meatspacePostRecommendations.js', () => ({ getPostRecommendations: vi.fn() }));+vi.mock('../services/meatspacePostAdaptive.js', () => ({+ resolveDrillConfig: vi.fn(),+ getAdaptivePreview: vi.fn(),+}));+vi.mock('../services/meatspacePost.js', () => ({+ getPostConfig: vi.fn(),+ updatePostConfig: vi.fn(),+ generateDrill: vi.fn(),+ getPostReviewReps: vi.fn(),+}));+vi.mock('../services/meatspacePostDrillCache.js', () => ({+ CACHEABLE_TYPES: ['compound-chain'],+ getCacheStats: vi.fn(() => ({})),+ requestCacheFill: vi.fn(),+ getCachedDrill: vi.fn(() => null),+ triggerReplenish: vi.fn(),+}));++import { getPostStats } from '../services/meatspacePostStats.js';+import { getPostRecommendations } from '../services/meatspacePostRecommendations.js';+import { getAdaptivePreview } from '../services/meatspacePostAdaptive.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import meatspacePostRoutes from './meatspacePostRoutes.js';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/meatspace', meatspacePostRoutes);+ app.use(errorMiddleware);+ return app;+}++describe('GET /api/meatspace/post/stats', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ getPostStats.mockResolvedValue({ sessionCount: 3 });+ });++ it('reads the aggregates from meatspacePostStats and defaults the window to 30 days', async () => {+ const res = await request(app).get('/api/meatspace/post/stats');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ sessionCount: 3 });+ expect(getPostStats).toHaveBeenCalledWith(30);+ });++ it('clamps an over-long window to a year and a non-positive one to all-time', async () => {+ await request(app).get('/api/meatspace/post/stats?days=4000');+ expect(getPostStats).toHaveBeenCalledWith(365);+ await request(app).get('/api/meatspace/post/stats?days=0');+ expect(getPostStats).toHaveBeenCalledWith(0);+ await request(app).get('/api/meatspace/post/stats?days=-7');+ expect(getPostStats).toHaveBeenCalledWith(0);+ });++ it('falls back to the 30-day default when days is not a number', async () => {+ await request(app).get('/api/meatspace/post/stats?days=abc');+ expect(getPostStats).toHaveBeenCalledWith(30);+ });+});++describe('GET /api/meatspace/post/recommendations', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ getPostRecommendations.mockResolvedValue({ recommendations: [] });+ });++ it('delegates to meatspacePostRecommendations with no limit by default', async () => {+ const res = await request(app).get('/api/meatspace/post/recommendations');+ expect(res.status).toBe(200);+ expect(getPostRecommendations).toHaveBeenCalledWith({});+ });++ it('clamps the requested limit into 1..10', async () => {+ await request(app).get('/api/meatspace/post/recommendations?limit=99');+ expect(getPostRecommendations).toHaveBeenCalledWith({ limit: 10 });+ await request(app).get('/api/meatspace/post/recommendations?limit=0');+ expect(getPostRecommendations).toHaveBeenCalledWith({ limit: 1 });+ });+});++describe('GET /api/meatspace/post/adaptive-preview', () => {+ it('delegates to the adaptive policy module', async () => {+ vi.clearAllMocks();+ getAdaptivePreview.mockResolvedValue({ enabled: true, drills: {} });+ const res = await request(makeApp()).get('/api/meatspace/post/adaptive-preview');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ enabled: true, drills: {} });+ expect(getAdaptivePreview).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/routes/meatspacePostRoutes.drill.test.js b/server/routes/meatspacePostRoutes.drill.test.jsindex 7690da8ec5..a6bc2b4b84 100644--- a/server/routes/meatspacePostRoutes.drill.test.js+++ b/server/routes/meatspacePostRoutes.drill.test.js@@ -30,7 +30,6 @@ vi.mock('../services/meatspacePostRhetoric.js', () => ({}));vi.mock('../services/meatspacePost.js', () => ({- resolveDrillConfig: vi.fn(),generateDrill: vi.fn(),getPostReviewReps: vi.fn(),// The memory branch reads the saved config to scope generateMemoryDrill's@@ -38,11 +37,22 @@ vi.mock('../services/meatspacePost.js', () => ({getPostConfig: vi.fn(),}));+// resolveDrillConfig moved to the adaptive policy module (#5690); the stats and+// recommendations siblings are stubbed because the route imports them too and+// they would otherwise link against the meatspacePost.js mock above.+vi.mock('../services/meatspacePostAdaptive.js', () => ({+ resolveDrillConfig: vi.fn(),+ getAdaptivePreview: vi.fn(),+}));+vi.mock('../services/meatspacePostStats.js', () => ({ getPostStats: vi.fn() }));+vi.mock('../services/meatspacePostRecommendations.js', () => ({ getPostRecommendations: vi.fn() }));+import { getCachedDrill, triggerReplenish } from '../services/meatspacePostDrillCache.js';import { generateLlmDrill } from '../services/meatspacePostLlm.js';import { generateMemoryDrill } from '../services/meatspacePostMemory.js';import { evaluateRhetoricAttempt } from '../services/meatspacePostRhetoric.js';-import { resolveDrillConfig, generateDrill, getPostReviewReps, getPostConfig } from '../services/meatspacePost.js';+import { generateDrill, getPostReviewReps, getPostConfig } from '../services/meatspacePost.js';+import { resolveDrillConfig } from '../services/meatspacePostAdaptive.js';import { errorMiddleware } from '../lib/errorHandler.js';import meatspacePostRoutes from './meatspacePostRoutes.js';diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.jsindex af5647e58f..625ed7eff4 100644--- a/server/routes/meatspacePostRoutes.js+++ b/server/routes/meatspacePostRoutes.js@@ -29,6 +29,11 @@ import {postProgressQuerySchema,} from '../lib/postValidation.js';import * as postService from '../services/meatspacePost.js';+// Named at their declaring modules, not through a re-export off meatspacePost.js+// (that convenience re-export closed a static import cycle — issue #5690).+import { getPostStats } from '../services/meatspacePostStats.js';+import { getPostRecommendations } from '../services/meatspacePostRecommendations.js';+import { resolveDrillConfig, getAdaptivePreview } from '../services/meatspacePostAdaptive.js';import * as memoryService from '../services/meatspacePostMemory.js';import { generateLlmDrill, scoreLlmDrill } from '../services/meatspacePostLlm.js';import { evaluateRhetoricAttempt } from '../services/meatspacePostRhetoric.js';@@ -119,7 +124,7 @@ router.post('/post/sessions', asyncHandler(async (req, res) => {router.get('/post/stats', asyncHandler(async (req, res) => {const rawDays = req.query.days != null ? parseInt(req.query.days, 10) : 30;const days = Number.isNaN(rawDays) ? 30 : rawDays > 0 ? Math.min(rawDays, 365) : 0;- const stats = await postService.getPostStats(days);+ const stats = await getPostStats(days);res.json(stats);}));@@ -150,7 +155,7 @@ router.get('/post/progress', asyncHandler(async (req, res) => {router.get('/post/recommendations', asyncHandler(async (req, res) => {const rawLimit = req.query.limit != null ? parseInt(req.query.limit, 10) : undefined;const limit = Number.isNaN(rawLimit) || rawLimit == null ? undefined : Math.max(1, Math.min(10, rawLimit));- const result = await postService.getPostRecommendations(limit != null ? { limit } : {});+ const result = await getPostRecommendations(limit != null ? { limit } : {});res.json(result);}));@@ -200,7 +205,7 @@ router.post('/post/drill', asyncHandler(async (req, res) => {// Adaptive difficulty (opt-in): when the Adaptive toggle is on, math drill// params are nudged from recent scored performance; otherwise config passes// through unchanged. Attaches an `adaptive` explainer when an adjustment ran.- const { config: effectiveConfig, adaptive, progression } = await postService.resolveDrillConfig(data.type, data.config);+ const { config: effectiveConfig, adaptive, progression } = await resolveDrillConfig(data.type, data.config);const drill = postService.generateDrill(data.type, effectiveConfig);if (!drill) {throw new ServerError('Unknown drill type', { status: 400, code: 'INVALID_DRILL_TYPE' });@@ -267,7 +272,7 @@ router.get('/post/review/reps', asyncHandler(async (req, res) => {* so the config UI can show what Adaptive will do before a session starts.*/router.get('/post/adaptive-preview', asyncHandler(async (req, res) => {- const preview = await postService.getAdaptivePreview();+ const preview = await getAdaptivePreview();res.json(preview);}));diff --git a/server/routes/meatspacePostRoutes.reminder.test.js b/server/routes/meatspacePostRoutes.reminder.test.jsindex 2fdc39f562..c8eadb6388 100644--- a/server/routes/meatspacePostRoutes.reminder.test.js+++ b/server/routes/meatspacePostRoutes.reminder.test.js@@ -17,6 +17,17 @@ vi.mock('../services/meatspacePost.js', () => ({updatePostConfig: vi.fn(),}));+// The route names each POST analytics/policy entry point at its declaring+// module (#5690), so a mocked meatspacePost.js needs these mocked too —+// otherwise the real siblings link against the mock and fail on the exports it+// does not stub.+vi.mock('../services/meatspacePostStats.js', () => ({ getPostStats: vi.fn() }));+vi.mock('../services/meatspacePostRecommendations.js', () => ({ getPostRecommendations: vi.fn() }));+vi.mock('../services/meatspacePostAdaptive.js', () => ({+ resolveDrillConfig: vi.fn(),+ getAdaptivePreview: vi.fn(),+}));+import * as postService from '../services/meatspacePost.js';import { errorMiddleware } from '../lib/errorHandler.js';import meatspacePostRoutes from './meatspacePostRoutes.js';diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex fdc951914f..99d3d2b192 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -13,7 +13,6 @@ import { deepMerge } from '../lib/objects.js';import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';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,@@ -55,10 +54,6 @@ import { todayInTimezone } from '../lib/timezone.js';import { getUserTimezone, userLocalToday as localToday } from './userTimezone.js';import { getStoredPostSession, listPostSessions, saveStoredPostSession } from './postRunStore.js';import { ServerError } from '../lib/errorHandler.js';-import { getPostStats } from './meatspacePostStats.js';--export { getPostStats } from './meatspacePostStats.js';-export { getPostRecommendations } from './meatspacePostRecommendations.js';// Re-export the shared streak helper so existing importers of// `computePostStreaks` from this module keep working after it moved to@@ -319,8 +314,8 @@ const DEFAULT_CONFIG = {};// Math tasks are logged under this coarse module in scored sessions, so the-// adaptive signal reads `byDrill['mental-math:<type>']`.-const MATH_MODULE = 'mental-math';+// adaptive signal in meatspacePostAdaptive.js reads `byDrill['mental-math:<type>']`.+export const MATH_MODULE = 'mental-math';async function ensureMeatspaceDir() {await ensureDir(MEATSPACE_DIR);@@ -1868,30 +1863,9 @@ export function generateDrill(type, config = {}) {}// =============================================================================-// ADAPTIVE DIFFICULTY+// PROGRESSIVE LADDERS — per-level history// =============================================================================-/**- * Read the recent performance signal for one math drill type from scored- * sessions. Returns { score, samples, completion } where `score` is now the avg- * ACCURACY (0-100, answered-only) — not the blended session score — so a- * fast-but-sloppy run and a slow-but-accurate run produce different adaptive- * directions (issue #2094). `completion` (0-1) lets adaptDrillConfig skip- * adaptation when the user barely reached the drill (too little signal).- */-async function getAdaptiveSignal(type) {- const stats = await getPostStats(ADAPTIVE_DEFAULTS.windowDays);- const key = `${MATH_MODULE}:${type}`;- const accuracy = stats.evidenceByDrillAccuracy?.[key];- const samples = stats.evidenceByDrillCount?.[key] || 0;- const completion = stats.evidenceByDrillCompletion?.[key];- return {- score: accuracy == null ? null : Math.round(accuracy * 100),- samples,- completion: completion == null ? null : completion,- };-}-/*** Aggregate multiplication performance per ladder level from scored history,* so the progressive ladder can decide whether each level has been *speed*@@ -1907,7 +1881,7 @@ async function getAdaptiveSignal(type) {** @returns {Promise<{stats: Record<number, {samples,accuracy,avgResponseMs}>, floorLevel: number}>}*/-async function getMultiplicationLevelStats(windowDays = MASTERY_DEFAULTS.windowDays) {+export async function getMultiplicationLevelStats(windowDays = MASTERY_DEFAULTS.windowDays) {const atDate = new Date();const [scoredSessions, training] = await Promise.all([getPostSessions(), getAllTrainingEntries()]);const sessions = skillEvidenceSessions(scoredSessions, training);@@ -1955,7 +1929,7 @@ async function getMultiplicationLevelStats(windowDays = MASTERY_DEFAULTS.windowDreturn { stats, floorLevel };}-async function getPowersLevelStats(windowDays = POWERS_MASTERY_DEFAULTS.windowDays) {+export async function getPowersLevelStats(windowDays = POWERS_MASTERY_DEFAULTS.windowDays) {const atDate = new Date();const [scoredSessions, training] = await Promise.all([getPostSessions(), getAllTrainingEntries()]);const sessions = skillEvidenceSessions(scoredSessions, training);@@ -2038,7 +2012,7 @@ export async function getPowersProgress() {** @returns {Promise<{stats: Record<number, {samples,attempts,accuracy,completion,incompleteSamples,avgResponseMs}>, floorLevel: number}>}*/-async function getCognitiveLevelStats(type, windowDays = COGNITIVE_MASTERY_DEFAULTS.windowDays) {+export async function getCognitiveLevelStats(type, windowDays = COGNITIVE_MASTERY_DEFAULTS.windowDays) {const atDate = new Date();const [scoredSessions, training] = await Promise.all([getPostSessions(), getAllTrainingEntries()]);const sessions = skillEvidenceSessions(scoredSessions, training);@@ -2123,151 +2097,6 @@ export async function getCognitiveProgress() {return out;}-/**- * Resolve the effective drill config for generation.- *- * - Multiplication with the progressive ladder ON (default): factor structure- * and difficulty come from mastery-gated level history, not the manual- * `maxDigits`. Returns a `progression` explainer.- * - Adaptive toggle ON: math drill params are nudged from recent scored- * performance within clamped bounds. Returns an `adaptive` explainer.- * - Otherwise (default): the caller's manual config passes through unchanged.- *- * @returns {{ config: object, adaptive: object|null, progression?: object|null }}- */-export async function resolveDrillConfig(type, requestedConfig = {}) {- const config = await getPostConfig();-- // Maintenance-review rep (issue #2096): a review rep targets a SPECIFIC lower- // rung on purpose, so bypass the progression override entirely and run the- // explicit level/factors the review scheduler chose. Without this the ladder- // would silently re-resolve the level up to the user's current rung, defeating- // the whole point of re-verifying a mastered-but-inactive skill.- if (requestedConfig?.review) {- return { config: requestedConfig, adaptive: null, progression: null };- }-- // Progressive multiplication ladder (default ON) — independent of the generic- // Adaptive toggle. Selects the factor structure by speed-gated mastery so a- // fresh user starts at single-digit × single-digit instead of a fixed hard- // difficulty. `maxDigits` is stripped so generation uses `factors`.- if (type === 'multiplication') {- const mulCfg = config?.mentalMath?.drillTypes?.multiplication || {};- if (mulCfg.progressive !== false) {- const { stats, floorLevel } = await getMultiplicationLevelStats(MASTERY_DEFAULTS.windowDays);- const progression = resolveMultiplicationLevel(stats, {}, floorLevel);- const { maxDigits: _drop, ...rest } = requestedConfig || {};- const effective = {- ...rest,- count: rest.count ?? mulCfg.count ?? 10,- level: progression.level,- factors: progression.factors,- };- return { config: effective, adaptive: null, progression };- }- }-- if (type === 'powers') {- const powersCfg = config?.mentalMath?.drillTypes?.powers || {};- if (powersCfg.progressive !== false) {- const { stats, floorLevel } = await getPowersLevelStats(POWERS_MASTERY_DEFAULTS.windowDays);- const progression = resolvePowersLevel(stats, {}, floorLevel);- const { bases: _bases, maxExponent: _maxExponent, ...rest } = requestedConfig || {};- return {- config: {- ...rest,- count: rest.count ?? powersCfg.count ?? 8,- level: progression.level,- technique: progression.technique,- },- adaptive: null,- progression,- };- }- }-- // Progressive cognitive ladders (default ON) — per-skill difficulty rungs- // (n-back n/stimulusMs, digit-span span/direction, schulte grid, mental-- // rotation transformation/options, Stroop interference mix). Selects the- // rung by exact-level completion + accuracy, with speed gates where latency- // is part of the skill; when off, the caller's manual knobs- // (incl. stimulusMs/showMs) pass through unchanged. reaction-time has no- // ladder and always passes through (issue #2095).- if (cognitiveLadder(type)) {- const cogCfg = config?.cognitive?.drillTypes?.[type] || {};- if (cogCfg.progressive !== false) {- const { stats, floorLevel } = await getCognitiveLevelStats(type);- const progression = resolveCognitiveProgression(type, stats, floorLevel);- const effective = {- ...requestedConfig,- ...cognitiveLevelConfig(type, progression.level),- level: progression.level,- };- return { config: effective, adaptive: null, progression };- }- return { config: requestedConfig, adaptive: null };- }-- if (!config?.adaptive?.enabled || !ADAPTIVE_SPECS[type]) {- return { config: requestedConfig, adaptive: null };- }- const signal = await getAdaptiveSignal(type);- const result = adaptDrillConfig(type, requestedConfig, signal);- return { config: result.config, adaptive: result };-}--/**- * Build a transparent per-type preview of the effective adaptive difficulty for- * every supported math drill, so the config UI can show what Adaptive will do- * before a session starts. `enabled` reflects the saved Adaptive toggle.- *- * Multiplication is a special case: `resolveDrillConfig` (above) hands- * multiplication's difficulty entirely to the progressive ladder whenever- * `progressive !== false` (the default) — the `maxDigits` Adaptive knob is- * short-circuited and never applied in that mode. Previewing it via- * `adaptDrillConfig` regardless would advertise a maxDigits adjustment that- * can never actually happen (issue #2099). So this mirrors resolveDrillConfig's- * own branch: ladder rung when progressive is on, the maxDigits Adaptive- * preview only when the user has turned progressive off.- */-export async function getAdaptivePreview() {- const config = await getPostConfig();- const enabled = !!config?.adaptive?.enabled;- const stats = await getPostStats(ADAPTIVE_DEFAULTS.windowDays);- const savedDrills = config?.mentalMath?.drillTypes || {};- const multiplicationProgressive = savedDrills.multiplication?.progressive !== false;- const powersProgressive = savedDrills.powers?.progressive !== false;-- const drills = {};- for (const type of Object.keys(ADAPTIVE_SPECS)) {- if (type === 'multiplication' && multiplicationProgressive) {- // Same source of truth resolveDrillConfig uses for the ladder rung —- // not the generic maxDigits Adaptive signal.- drills[type] = { ladder: true, ...(await getMultiplicationProgress()) };- continue;- }- if (type === 'powers' && powersProgressive) {- drills[type] = { ladder: true, ...(await getPowersProgress()) };- continue;- }- const key = `${MATH_MODULE}:${type}`;- const accuracy = stats.byDrillAccuracy?.[key];- const completion = stats.byDrillCompletion?.[key];- const signal = {- // Preview mirrors the live adaptive signal: accuracy (0-100), not the- // blended score, plus completion for the low-completion skip (issue #2094).- score: accuracy == null ? null : Math.round(accuracy * 100),- samples: stats.byDrillCount?.[key] || 0,- completion: completion == null ? null : completion,- };- // Base off the user's saved config so the preview matches what a session- // would actually use; adaptDrillConfig falls back to the spec base per field.- drills[type] = adaptDrillConfig(type, savedDrills[type] || {}, signal);- }-- return { enabled, windowDays: ADAPTIVE_DEFAULTS.windowDays, thresholds: { highScore: ADAPTIVE_DEFAULTS.highScore, lowScore: ADAPTIVE_DEFAULTS.lowScore, minSamples: ADAPTIVE_DEFAULTS.minSamples, minCompletion: ADAPTIVE_DEFAULTS.minCompletion }, drills };-}-// =============================================================================// SCORING (pure functions)// =============================================================================diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex c1dfb8437e..e5f88f586c 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -44,10 +44,7 @@ import {submitPostSession,updatePostConfig,postConfigEvents,- resolveDrillConfig,getMultiplicationProgress,- getAdaptivePreview,- getPostStats,getPostConfig,getPostSessions,getPostSession,@@ -61,6 +58,8 @@ import {POST_BENCHMARK_PROTOCOL,benchmarkCompatibility,} from './meatspacePost.js';+import { getPostStats } from './meatspacePostStats.js';+import { resolveDrillConfig, getAdaptivePreview } from './meatspacePostAdaptive.js';import { generateCognitiveDrill } from './meatspacePostCognitive.js';describe('Quick POST config', () => {diff --git a/server/services/meatspacePostAdaptive.js b/server/services/meatspacePostAdaptive.jsnew file mode 100644index 0000000000..f3eea31041--- /dev/null+++ b/server/services/meatspacePostAdaptive.js@@ -0,0 +1,194 @@+/**+ * POST adaptive difficulty + progressive-ladder resolution.+ *+ * This is the POLICY layer above the two data layers: `meatspacePost.js` owns+ * raw sessions and per-ladder level history, `meatspacePostStats.js` owns the+ * derived aggregates, and this module turns both into the effective config a+ * drill is generated with (and the preview of that decision for the config UI).+ *+ * It lives here rather than inside `meatspacePost.js` because the adaptive+ * signal is read from `getPostStats()`, and `meatspacePostStats.js` reads raw+ * sessions back out of `meatspacePost.js` — computing the signal in the data+ * module closed a static ESM cycle whose only other purpose was letting callers+ * write `import { getPostStats } from './meatspacePost.js'` (issue #5690).+ */+import { adaptDrillConfig, ADAPTIVE_SPECS, ADAPTIVE_DEFAULTS } from '../lib/postAdaptive.js';+import { resolveMultiplicationLevel, MASTERY_DEFAULTS } from '../lib/postMultiplicationLadder.js';+import { POWERS_MASTERY_DEFAULTS, resolvePowersLevel } from '../lib/postPowersLadder.js';+import { cognitiveLadder, cognitiveLevelConfig, resolveCognitiveProgression } from '../lib/postProgression.js';+import {+ MATH_MODULE,+ getPostConfig,+ getMultiplicationProgress,+ getPowersProgress,+ getMultiplicationLevelStats,+ getPowersLevelStats,+ getCognitiveLevelStats,+} from './meatspacePost.js';+import { getPostStats } from './meatspacePostStats.js';++/**+ * Read the recent performance signal for one math drill type from scored+ * sessions. Returns { score, samples, completion } where `score` is now the avg+ * ACCURACY (0-100, answered-only) — not the blended session score — so a+ * fast-but-sloppy run and a slow-but-accurate run produce different adaptive+ * directions (issue #2094). `completion` (0-1) lets adaptDrillConfig skip+ * adaptation when the user barely reached the drill (too little signal).+ */+async function getAdaptiveSignal(type) {+ const stats = await getPostStats(ADAPTIVE_DEFAULTS.windowDays);+ const key = `${MATH_MODULE}:${type}`;+ const accuracy = stats.evidenceByDrillAccuracy?.[key];+ const samples = stats.evidenceByDrillCount?.[key] || 0;+ const completion = stats.evidenceByDrillCompletion?.[key];+ return {+ score: accuracy == null ? null : Math.round(accuracy * 100),+ samples,+ completion: completion == null ? null : completion,+ };+}++/**+ * Resolve the effective drill config for generation.+ *+ * - Multiplication with the progressive ladder ON (default): factor structure+ * and difficulty come from mastery-gated level history, not the manual+ * `maxDigits`. Returns a `progression` explainer.+ * - Adaptive toggle ON: math drill params are nudged from recent scored+ * performance within clamped bounds. Returns an `adaptive` explainer.+ * - Otherwise (default): the caller's manual config passes through unchanged.+ *+ * @returns {{ config: object, adaptive: object|null, progression?: object|null }}+ */+export async function resolveDrillConfig(type, requestedConfig = {}) {+ const config = await getPostConfig();++ // Maintenance-review rep (issue #2096): a review rep targets a SPECIFIC lower+ // rung on purpose, so bypass the progression override entirely and run the+ // explicit level/factors the review scheduler chose. Without this the ladder+ // would silently re-resolve the level up to the user's current rung, defeating+ // the whole point of re-verifying a mastered-but-inactive skill.+ if (requestedConfig?.review) {+ return { config: requestedConfig, adaptive: null, progression: null };+ }++ // Progressive multiplication ladder (default ON) — independent of the generic+ // Adaptive toggle. Selects the factor structure by speed-gated mastery so a+ // fresh user starts at single-digit × single-digit instead of a fixed hard+ // difficulty. `maxDigits` is stripped so generation uses `factors`.+ if (type === 'multiplication') {+ const mulCfg = config?.mentalMath?.drillTypes?.multiplication || {};+ if (mulCfg.progressive !== false) {+ const { stats, floorLevel } = await getMultiplicationLevelStats(MASTERY_DEFAULTS.windowDays);+ const progression = resolveMultiplicationLevel(stats, {}, floorLevel);+ const { maxDigits: _drop, ...rest } = requestedConfig || {};+ const effective = {+ ...rest,+ count: rest.count ?? mulCfg.count ?? 10,+ level: progression.level,+ factors: progression.factors,+ };+ return { config: effective, adaptive: null, progression };+ }+ }++ if (type === 'powers') {+ const powersCfg = config?.mentalMath?.drillTypes?.powers || {};+ if (powersCfg.progressive !== false) {+ const { stats, floorLevel } = await getPowersLevelStats(POWERS_MASTERY_DEFAULTS.windowDays);+ const progression = resolvePowersLevel(stats, {}, floorLevel);+ const { bases: _bases, maxExponent: _maxExponent, ...rest } = requestedConfig || {};+ return {+ config: {+ ...rest,+ count: rest.count ?? powersCfg.count ?? 8,+ level: progression.level,+ technique: progression.technique,+ },+ adaptive: null,+ progression,+ };+ }+ }++ // Progressive cognitive ladders (default ON) — per-skill difficulty rungs+ // (n-back n/stimulusMs, digit-span span/direction, schulte grid, mental-+ // rotation transformation/options, Stroop interference mix). Selects the+ // rung by exact-level completion + accuracy, with speed gates where latency+ // is part of the skill; when off, the caller's manual knobs+ // (incl. stimulusMs/showMs) pass through unchanged. reaction-time has no+ // ladder and always passes through (issue #2095).+ if (cognitiveLadder(type)) {+ const cogCfg = config?.cognitive?.drillTypes?.[type] || {};+ if (cogCfg.progressive !== false) {+ const { stats, floorLevel } = await getCognitiveLevelStats(type);+ const progression = resolveCognitiveProgression(type, stats, floorLevel);+ const effective = {+ ...requestedConfig,+ ...cognitiveLevelConfig(type, progression.level),+ level: progression.level,+ };+ return { config: effective, adaptive: null, progression };+ }+ return { config: requestedConfig, adaptive: null };+ }++ if (!config?.adaptive?.enabled || !ADAPTIVE_SPECS[type]) {+ return { config: requestedConfig, adaptive: null };+ }+ const signal = await getAdaptiveSignal(type);+ const result = adaptDrillConfig(type, requestedConfig, signal);+ return { config: result.config, adaptive: result };+}++/**+ * Build a transparent per-type preview of the effective adaptive difficulty for+ * every supported math drill, so the config UI can show what Adaptive will do+ * before a session starts. `enabled` reflects the saved Adaptive toggle.+ *+ * Multiplication is a special case: `resolveDrillConfig` (above) hands+ * multiplication's difficulty entirely to the progressive ladder whenever+ * `progressive !== false` (the default) — the `maxDigits` Adaptive knob is+ * short-circuited and never applied in that mode. Previewing it via+ * `adaptDrillConfig` regardless would advertise a maxDigits adjustment that+ * can never actually happen (issue #2099). So this mirrors resolveDrillConfig's+ * own branch: ladder rung when progressive is on, the maxDigits Adaptive+ * preview only when the user has turned progressive off.+ */+export async function getAdaptivePreview() {+ const config = await getPostConfig();+ const enabled = !!config?.adaptive?.enabled;+ const stats = await getPostStats(ADAPTIVE_DEFAULTS.windowDays);+ const savedDrills = config?.mentalMath?.drillTypes || {};+ const multiplicationProgressive = savedDrills.multiplication?.progressive !== false;+ const powersProgressive = savedDrills.powers?.progressive !== false;++ const drills = {};+ for (const type of Object.keys(ADAPTIVE_SPECS)) {+ if (type === 'multiplication' && multiplicationProgressive) {+ // Same source of truth resolveDrillConfig uses for the ladder rung —+ // not the generic maxDigits Adaptive signal.+ drills[type] = { ladder: true, ...(await getMultiplicationProgress()) };+ continue;+ }+ if (type === 'powers' && powersProgressive) {+ drills[type] = { ladder: true, ...(await getPowersProgress()) };+ continue;+ }+ const key = `${MATH_MODULE}:${type}`;+ const accuracy = stats.byDrillAccuracy?.[key];+ const completion = stats.byDrillCompletion?.[key];+ const signal = {+ // Preview mirrors the live adaptive signal: accuracy (0-100), not the+ // blended score, plus completion for the low-completion skip (issue #2094).+ score: accuracy == null ? null : Math.round(accuracy * 100),+ samples: stats.byDrillCount?.[key] || 0,+ completion: completion == null ? null : completion,+ };+ // Base off the user's saved config so the preview matches what a session+ // would actually use; adaptDrillConfig falls back to the spec base per field.+ drills[type] = adaptDrillConfig(type, savedDrills[type] || {}, signal);+ }++ return { enabled, windowDays: ADAPTIVE_DEFAULTS.windowDays, thresholds: { highScore: ADAPTIVE_DEFAULTS.highScore, lowScore: ADAPTIVE_DEFAULTS.lowScore, minSamples: ADAPTIVE_DEFAULTS.minSamples, minCompletion: ADAPTIVE_DEFAULTS.minCompletion }, drills };+}diff --git a/server/services/meatspacePostImportCycles.test.js b/server/services/meatspacePostImportCycles.test.jsnew file mode 100644index 0000000000..af06dcf3e7--- /dev/null+++ b/server/services/meatspacePostImportCycles.test.js@@ -0,0 +1,85 @@+/**+ * Regression guard for the MeatSpace POST service ring (#5690).+ *+ * `meatspacePost.js` used to import `getPostStats` from `meatspacePostStats.js`+ * and re-export both that symbol and `getPostRecommendations`, purely so+ * callers could write `import { getPostStats } from './meatspacePost.js'`.+ * Both analytics modules import `meatspacePost.js` back for their raw inputs,+ * so each convenience forward closed a static ESM ring. In a static cycle+ * whichever member evaluates first sees `undefined` for the others' bindings,+ * so any future top-level `const` derived from an imported value in the ring+ * becomes a boot-time TDZ crash — and no behavior test notices until a load+ * order change surfaces it.+ *+ * The layering the guard pins: `meatspacePost.js` owns raw sessions and ladder+ * level history, `meatspacePostStats.js` derives the aggregates from it, and+ * `meatspacePostAdaptive.js` / `meatspacePostRecommendations.js` sit above BOTH+ * as the policy layer. Edges only ever point down, so a re-added re-export off+ * the data module fails here with the reason rather than as an opaque ring.+ */++import { describe, it, expect } from 'vitest';+import { fileURLToPath } from 'url';+import { dirname } from 'path';+import { buildStaticImportGraph, findImportCycles } from '../lib/staticImportGraph.js';++const SERVICES_DIR = dirname(fileURLToPath(import.meta.url));++const DATA_MODULE = 'meatspacePost.js';+// Every POST module that participates in the stats/recommendation/adaptive+// layering. A cycle anywhere in `server/services` is reported by the walk, but+// only one TOUCHING this cluster fails here — unrelated pre-existing cycles+// (the pipeline autopilot ring) have their own issues.+const CLUSTER = [+ DATA_MODULE,+ 'meatspacePostStats.js',+ 'meatspacePostRecommendations.js',+ 'meatspacePostAdaptive.js',+];++// The data module must not reach UP into the layers built on top of it — the+// exact edges (a plain import, or an `export … from` re-export) that closed the+// two rings this guard exists for.+const FORBIDDEN_UPWARD_EDGES = CLUSTER.filter(module => module !== DATA_MODULE);++describe('MeatSpace POST services — no static import cycles (#5690)', () => {+ const graph = buildStaticImportGraph(SERVICES_DIR);++ it('sees the whole services graph', () => {+ // A resolver gap would make every negative assertion below pass vacuously.+ expect(graph.size, 'services graph looks empty — did the scan root move?').toBeGreaterThan(100);+ for (const module of CLUSTER) expect([...graph.keys()], `${module} is missing from the graph`).toContain(module);+ });++ it('has no static import cycle touching the POST cluster', () => {+ const offending = findImportCycles(graph).filter(cycle =>+ CLUSTER.some(module => cycle.split(' -> ').includes(module)));+ expect(offending, `static import cycle(s) reintroduced:\n${offending.join('\n')}`).toEqual([]);+ });++ it('keeps meatspacePost.js from importing or re-exporting the layers above it', () => {+ const deps = graph.get(DATA_MODULE) || [];+ for (const module of FORBIDDEN_UPWARD_EDGES) {+ expect(+ deps,+ `${DATA_MODULE} must not depend on ${module} — that module reads raw POST data back out of it. Callers name the declaring module instead.`+ ).not.toContain(module);+ }+ });++ it('keeps the analytics layers naming the data module directly', () => {+ // The downward edges are the ones that SHOULD exist; asserting them keeps+ // the cycle assertion above from passing because an edge simply vanished.+ for (const module of ['meatspacePostStats.js', 'meatspacePostRecommendations.js', 'meatspacePostAdaptive.js']) {+ expect(graph.get(module) || [], `${module} must read its inputs from ${DATA_MODULE}`).toContain(DATA_MODULE);+ }+ expect(+ graph.get('meatspacePostAdaptive.js') || [],+ 'meatspacePostAdaptive.js must read the adaptive signal from meatspacePostStats.js'+ ).toContain('meatspacePostStats.js');+ expect(+ graph.get('meatspacePostRecommendations.js') || [],+ 'meatspacePostRecommendations.js must read getPostStats from meatspacePostStats.js'+ ).toContain('meatspacePostStats.js');+ });+});diff --git a/server/services/meatspacePostProgress.test.js b/server/services/meatspacePostProgress.test.jsindex 061c149490..d4779976dc 100644--- a/server/services/meatspacePostProgress.test.js+++ b/server/services/meatspacePostProgress.test.js@@ -27,7 +27,8 @@ vi.mock('../services/settings.js', () => ({getSettings: () => Promise.resolve(settingsState),}));-import { getPostProgress, getPostStats, benchmarkCompatibility, POST_BENCHMARK_PROTOCOL } from './meatspacePost.js';+import { getPostProgress, benchmarkCompatibility, POST_BENCHMARK_PROTOCOL } from './meatspacePost.js';+import { getPostStats } from './meatspacePostStats.js';import { getTrainingStats, getAllTrainingEntries } from './meatspacePostTraining.js';import { getUnifiedActivityStreak } from './postActivityStreak.js';import { postProgressQuerySchema } from '../lib/postValidation.js';diff --git a/server/services/meatspacePostRecommendations.js b/server/services/meatspacePostRecommendations.jsindex be7879b8f2..eea7297387 100644--- a/server/services/meatspacePostRecommendations.js+++ b/server/services/meatspacePostRecommendations.js@@ -1,14 +1,13 @@/*** POST "what to practice next" orchestration.*- * The public service re-exports this entry point. It imports the shared POST- * helpers from that service so persistence and recommendation policy remain- * independently testable without changing callers.+ * Imports the shared POST helpers from the persistence service and the derived+ * aggregates from the stats module, each named at its declaring module, so+ * persistence and recommendation policy stay independently loadable.*/import {getPostConfig,getPostSessions,- getPostStats,getMultiplicationProgress,getPowersProgress,getCognitiveProgress,@@ -20,6 +19,7 @@ import {practicedTodayFromActivity,recentPracticeFromActivity,} from './meatspacePost.js';+import { getPostStats } from './meatspacePostStats.js';import { orderByRecencyRotation } from '../lib/postRotation.js';import { MASTERY_DEFAULTS } from '../lib/postMultiplicationLadder.js';import { isMemoryItemEnabled, resolveTopicForDrillType } from '../lib/postTopics.js';diff --git a/server/services/meatspacePostRecommendations.test.js b/server/services/meatspacePostRecommendations.test.jsindex febee95f4a..2864c445e7 100644--- a/server/services/meatspacePostRecommendations.test.js+++ b/server/services/meatspacePostRecommendations.test.js@@ -36,7 +36,6 @@ import {composePostRecommendations,weakestSkillFromStats,stalledProgressions,- getPostRecommendations,updatePostConfig,isRecDrillRunnable,memoryPracticeDeepLink,@@ -45,6 +44,7 @@ import {recentPracticeFromActivity,weakestSkillsFromStats,} from './meatspacePost.js';+import { getPostRecommendations } from './meatspacePostRecommendations.js';import { atomicWrite } from '../lib/fileUtils.js';beforeEach(() => {diff --git a/server/services/meatspacePostStats.js b/server/services/meatspacePostStats.jsindex fe146721de..a82966266f 100644--- a/server/services/meatspacePostStats.js+++ b/server/services/meatspacePostStats.js@@ -1,8 +1,9 @@/*** POST aggregate statistics.*- * The persistence service keeps the public API stable by re-exporting this- * module. Shared session and legacy-task helpers intentionally stay there.+ * Reads raw sessions and the legacy-task helpers from the persistence service;+ * callers name THIS module for the derived aggregates rather than reaching for+ * a re-export off the persistence service (issue #5690).*/import { getPostSessions, deriveTaskAccuracy, deriveTaskCompletion } from './meatspacePost.js';import { getAllTrainingEntries } from './postTrainingLogStore.js';