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
fix: persist POST runs atomically (#4441)
Adam Eivy7b970a5e2bc5
diff --git a/.changelog/next/fixed-issue-4441.md b/.changelog/next/fixed-issue-4441.mdnew file mode 100644index 0000000000..2165c980a3--- /dev/null+++ b/.changelog/next/fixed-issue-4441.md@@ -0,0 +1 @@+- Persist normalized POST runs and attempts atomically with idempotent training retries and truthful save failuresdiff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex f1f1d262ef..fb16dbc77a 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -164,7 +164,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useCatalogTypes` | Catalog ingredient type registry (system + user-defined) merged with the static fallback via a Provider/hook pair; synchronous fallback to the built-in six so first render never blanks. | Catalog list/picker/editor; anywhere the catalog type list/lookup is needed. || `useDeathClock` | 1-second countdown for death-clock display. | Mortality / death-clock surfaces. || `useGoalDetail` | All state + handlers backing the GoalDetailPanel (edit form, todos, milestones, plan/phases, check-ins, progress log, activity/calendar links). Loads activities + subcalendars on mount. | GoalDetailPanel composition shell; not intended for reuse outside the goals panel. |-| `usePostSession` | Post-render callback scheduling. | Generic post-action chaining. |+| `usePostSession` | MeatSpace POST drill-run state, refresh snapshots, scoring, and idempotent test/training saves. | POST launcher and drill runners. || `useRecordMerge` | Duplicate Universe/Series merge flow: open → dry-run preview → resolve field conflicts → execute, with an `onMerged` refresh callback. Drives `<MergeModal>`. | Surfacing the merge-duplicates UI anywhere (Sharing → Duplicates, Universes page). Don't re-implement the preview/execute dance. || `useProviderModels` | AI providers + two-step provider→model selection. | Any UI that picks a provider + model. || `useReviewerModelOptions` | Selectable model ids per model-taking reviewer for `ReviewerPicker`'s Model column — local-LLM ids from `/api/local-llm/status`, codex/claude/antigravity tiers from `/api/providers` (claude's list also spans installed Ollama ids for an Ollama-backed CLI; agy's collapses to base ids since the row has its own Effort cell). Returns `{ optionsByReviewer, freeText, unavailable, loaded, reviewers }`. | Every surface that renders `ReviewerPicker` (Code Review Defaults, TaskAddForm, ScheduleTab, SlashDoRunDrawer) — the picker never fetches; pass this as its `modelOptions`. |diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex 7ab1fc120f..91385fd5c2 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -1,5 +1,5 @@import { useState, useCallback, useRef, useEffect } from 'react';-import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingEntry } from '../services/api';+import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingRun } from '../services/api';import toast from '../components/ui/Toast';import { uuidv4 } from '../lib/uuid.js';import {@@ -30,12 +30,8 @@ function loadRunSnapshot() {try { snap = JSON.parse(raw); } catch { return null; } // corrupt storage → start freshif (!snap || typeof snap !== 'object') return null;if (snap.state === 'saving') {- // A scored session re-saves idempotently (client-supplied id → upsert), so- // restoring a mid-save run to `complete` is safe. A TRAINING save instead- // loops non-idempotent training-log writes; restoring it would let a re-save- // double-log every drill — and the entries were most likely already posted —- // so drop it rather than resume.- if (snap.isTraining) return null;+ // Both scored and training saves use stable client run/attempt ids, so an+ // interrupted request can safely return to the results screen and retry.snap.state = 'complete';}if (!RESTORABLE_STATES.has(snap.state)) return null;@@ -118,6 +114,8 @@ export function usePostSession() {// reload, under-counting time and inflating the speed bonus.const questionStartRef = useRef(restored?.questionStartedAt ?? Date.now());const drillStartRef = useRef(restored?.drillStartedAt ?? Date.now());+ const runStartedAtRef = useRef(restored?.runStartedAt ?? null);+ const runCompletedAtRef = useRef(restored?.runCompletedAt ?? null);const finishDrillRef = useRef(null);// Persist the live run to sessionStorage on every meaningful change; clear it@@ -144,6 +142,8 @@ export function usePostSession() {// refresh resumes the clock instead of restarting it.questionStartedAt: questionStartRef.current,drillStartedAt: drillStartRef.current,+ runStartedAt: runStartedAtRef.current,+ runCompletedAt: runCompletedAtRef.current,}));}, [runId, state, drills, currentDrillIndex, currentDrill, currentQuestionIndex, answers, drillResults, sessionScore, isTraining, tags]);@@ -160,6 +160,8 @@ export function usePostSession() {setDrillResults([]);setSavedSession(null);setLastAnswer(null);+ runStartedAtRef.current = new Date().toISOString();+ runCompletedAtRef.current = null;// New run → new client-side id (also the future /post/session/:id) and the// tags to submit, so both survive a mid-run refresh via the snapshot.setRunId(newRunId());@@ -197,6 +199,7 @@ export function usePostSession() {const isMemoryDrill = MEMORY_DRILL_TYPES.includes(currentDrill.type);const result = {+ id: newRunId(),module: isMemoryDrill ? 'memory' : 'mental-math',type: currentDrill.type,config: currentDrill.config,@@ -216,6 +219,7 @@ export function usePostSession() {if (currentDrillIndex + 1 < drills.length) {setState(STATES.BETWEEN_DRILLS);} else {+ runCompletedAtRef.current = new Date().toISOString();setSessionScore(computeSessionScoreFromResults(newResults));setState(STATES.COMPLETE);}@@ -381,12 +385,14 @@ export function usePostSession() {}}+ scoredResult = { ...scoredResult, id: scoredResult.id || newRunId() };const newResults = [...drillResults, scoredResult];setDrillResults(newResults);if (currentDrillIndex + 1 < drills.length) {setState(STATES.BETWEEN_DRILLS);} else {+ runCompletedAtRef.current = new Date().toISOString();setSessionScore(computeSessionScoreFromResults(newResults));setState(STATES.COMPLETE);}@@ -398,12 +404,13 @@ export function usePostSession() {// deterministically from drillData on submit. Mirrors completeLlmDrill's// advance/complete bookkeeping.const completeCognitiveDrill = useCallback((drillResult) => {- const newResults = [...drillResults, drillResult];+ const newResults = [...drillResults, { ...drillResult, id: drillResult.id || newRunId() }];setDrillResults(newResults);if (currentDrillIndex + 1 < drills.length) {setState(STATES.BETWEEN_DRILLS);} else {+ runCompletedAtRef.current = new Date().toISOString();setSessionScore(computeSessionScoreFromResults(newResults));setState(STATES.COMPLETE);}@@ -415,9 +422,11 @@ export function usePostSession() {// an explicit arg still wins per-key for a live save.const finalTags = { ...tags, ...(overrideTags || {}) };- // Training mode: log each drill to the training log, don't save scored session+ // Training mode: one validated batch + one transaction for the whole run.+ // Stable run/attempt ids make a failed-response retry idempotent.if (isTraining) {- for (const r of drillResults) {+ const trainingRunId = runId || newRunId();+ const attempts = drillResults.map((r, index) => {const questionCount = r.questions?.length || r.responses?.length || 0;// LLM drills score via completeLlmDrill, which stores the scored// responses under `r.responses` (with an `llmScore` field) rather@@ -449,18 +458,54 @@ export function usePostSession() {correct: (resp.llmScore ?? 0) >= LLM_TRAINING_CORRECT_THRESHOLD,})): undefined;- await submitTrainingEntry({+ const answeredCount = isLlmDrill+ ? (r.responses || []).length+ : (r.questions || []).filter((question) => question?.answered != null).length;+ const inputMode = r.inputMode || (+ isLlmDrill || MEMORY_DRILL_TYPES.includes(r.type)+ ? 'text'+ : r.module === 'cognitive' ? 'interactive' : 'numeric'+ );+ return {+ id: r.id || `${trainingRunId}:attempt:${index}`,module: r.module,drillType: r.type,+ ...(r.memoryItemId ? { memoryItemId: r.memoryItemId } : {}),+ difficulty: r.config || null,+ configVersion: r.configVersion || null,questionCount,correctCount,- totalMs: r.totalMs || 0,- ...(questions ? { questions } : {}),- }).catch(() => {});- }+ latencyMs: r.totalMs || 0,+ correct: questionCount > 0 ? correctCount === questionCount : null,+ score: r.score !== undefined ? r.score : (questionCount > 0 ? (correctCount / questionCount) * 100 : null),+ completion: r.completion !== undefined ? r.completion : (questionCount > 0 ? answeredCount / questionCount : null),+ hintUsed: (r.questions || []).some((question) => question?.hintUsed === true),+ confidence: r.confidence ?? null,+ inputMode,+ scorerProvenance: isLlmDrill ? 'server-llm' : 'client-deterministic',+ ...((questions || Array.isArray(r.questions)) ? { questions: questions || r.questions } : {}),+ };+ });+ const training = await submitTrainingRun({+ id: trainingRunId,+ mode: 'training',+ ...(runStartedAtRef.current ? { startedAt: runStartedAtRef.current } : {}),+ ...(runCompletedAtRef.current ? { completedAt: runCompletedAtRef.current } : {}),+ planned: {+ modules: [...new Set(attempts.map((attempt) => attempt.module))],+ drillTypes: attempts.map((attempt) => attempt.drillType),+ },+ attempts,+ }, { silent: true }).catch((err) => {+ toast.error(`Failed to save training session: ${err.message}`);+ setState(STATES.COMPLETE);+ return null;+ });+ if (!training) return null;+ setSavedSession(training);toast.success('Training session logged');setState(STATES.SAVED);- return { training: true };+ return { ...training, training: true };}const modules = [...new Set(drillResults.map(r => r.module))];@@ -504,6 +549,8 @@ export function usePostSession() {setSavedSession(null);setIsTraining(false);setRunId(null);+ runStartedAtRef.current = null;+ runCompletedAtRef.current = null;setTags({});setLastAnswer(null);clearRunSnapshot();diff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.jsindex e052ae7c9c..9ebed48009 100644--- a/client/src/hooks/usePostSession.test.js+++ b/client/src/hooks/usePostSession.test.js@@ -5,11 +5,11 @@ vi.mock('../services/api', () => ({generatePostDrill: vi.fn(),submitPostSession: vi.fn(),scorePostLlmDrill: vi.fn(),- submitTrainingEntry: vi.fn(),+ submitTrainingRun: vi.fn(),}));vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));-import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingEntry } from '../services/api';+import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingRun } from '../services/api';import { usePostSession } from './usePostSession';// Covers issue #2010: a memory drill completed inside a POST session must@@ -461,7 +461,7 @@ describe('usePostSession — LLM training-log correctCount (issue #2097)', () =>questions: [{ questionIndex: 0, items: ['firehouse'], llmScore: 90 }],evaluation: { overallScore: 90, scores: [{ score: 90 }] },});- submitTrainingEntry.mockResolvedValue({});+ submitTrainingRun.mockResolvedValue({ id: 'training-run' });const { result } = renderHook(() => usePostSession());@@ -484,12 +484,14 @@ describe('usePostSession — LLM training-log correctCount (issue #2097)', () =>await result.current.saveSession({});});- expect(submitTrainingEntry).toHaveBeenCalledWith(expect.objectContaining({+ expect(submitTrainingRun.mock.calls[0][0].attempts[0]).toEqual(expect.objectContaining({module: 'llm-drills',drillType: 'compound-chain',questionCount: 1,correctCount: 1,- totalMs: 5000,+ latencyMs: 5000,+ inputMode: 'text',+ scorerProvenance: 'server-llm',}));});@@ -502,7 +504,7 @@ describe('usePostSession — LLM training-log correctCount (issue #2097)', () =>questions: [{ questionIndex: 0, response: 'wrong', llmScore: 20 }],evaluation: { overallScore: 20, scores: [{ score: 20 }] },});- submitTrainingEntry.mockResolvedValue({});+ submitTrainingRun.mockResolvedValue({ id: 'training-run' });const { result } = renderHook(() => usePostSession());@@ -525,12 +527,50 @@ describe('usePostSession — LLM training-log correctCount (issue #2097)', () =>await result.current.saveSession({});});- expect(submitTrainingEntry).toHaveBeenCalledWith(expect.objectContaining({+ expect(submitTrainingRun.mock.calls[0][0].attempts[0]).toEqual(expect.objectContaining({drillType: 'bridge-word', questionCount: 1, correctCount: 0,}));});});+describe('usePostSession — atomic training-run save (#4441)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ sessionStorage.clear();+ });++ it('keeps a failed save retryable and reuses the same run and attempt ids', async () => {+ generatePostDrill.mockResolvedValue({+ type: 'doubling-chain', config: { steps: 1 },+ questions: [{ prompt: '2 x 2', expected: 4 }],+ });+ submitTrainingRun+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValueOnce({ id: 'saved-training-run', attemptCount: 1 });++ const { result } = renderHook(() => usePostSession());+ await act(async () => {+ await result.current.startSession([{ type: 'doubling-chain', config: {}, timeLimitSec: 60 }], true);+ });+ act(() => { result.current.submitAnswer('4'); });+ act(() => { result.current.acknowledgeAnswer(); });++ let first;+ await act(async () => { first = await result.current.saveSession({}); });+ expect(first).toBeNull();+ expect(result.current.state).toBe('complete');+ const firstPayload = submitTrainingRun.mock.calls[0][0];+ expect(firstPayload.attempts[0].inputMode).toBe('numeric');++ await act(async () => { await result.current.saveSession({}); });+ expect(result.current.state).toBe('saved');+ const retryPayload = submitTrainingRun.mock.calls[1][0];+ expect(retryPayload.id).toBe(firstPayload.id);+ expect(retryPayload.attempts.map((attempt) => attempt.id))+ .toEqual(firstPayload.attempts.map((attempt) => attempt.id));+ });+});+describe('usePostSession — LLM training-log per-question breakdown (issue #2114)', () => {beforeEach(() => {vi.clearAllMocks();@@ -550,7 +590,7 @@ describe('usePostSession — LLM training-log per-question breakdown (issue #211questions: [{ questionIndex: 0, prompt: 'fire', items: ['firehouse'], responseMs: 500, llmScore: 90, llmFeedback: 'Nice!' }],evaluation: { overallScore: 90, scores: [{ score: 90, feedback: 'Nice!' }] },});- submitTrainingEntry.mockResolvedValue({});+ submitTrainingRun.mockResolvedValue({ id: 'training-run' });const { result } = renderHook(() => usePostSession());@@ -573,7 +613,7 @@ describe('usePostSession — LLM training-log per-question breakdown (issue #211await result.current.saveSession({});});- expect(submitTrainingEntry).toHaveBeenCalledWith(expect.objectContaining({+ expect(submitTrainingRun.mock.calls[0][0].attempts[0]).toEqual(expect.objectContaining({drillType: 'compound-chain',questions: [expect.objectContaining({prompt: 'fire', items: ['firehouse'], score: 90, feedback: 'Nice!', correct: true,@@ -594,7 +634,7 @@ describe('usePostSession — LLM training-log per-question breakdown (issue #211questions: [{ questionIndex: 0, response: 'y', llmScore: 80 }],evaluation: { overallScore: 80, scores: [{ score: 80 }] },});- submitTrainingEntry.mockResolvedValue({});+ submitTrainingRun.mockResolvedValue({ id: 'training-run' });const { result } = renderHook(() => usePostSession());@@ -617,7 +657,7 @@ describe('usePostSession — LLM training-log per-question breakdown (issue #211await result.current.saveSession({});});- const entry = submitTrainingEntry.mock.calls[0][0];+ const entry = submitTrainingRun.mock.calls[0][0].attempts[0];expect(entry).not.toHaveProperty('questions');});});@@ -700,16 +740,17 @@ describe('usePostSession — refresh-safe run + idempotent submit (issue #2098)'expect(snap.drillResults).toHaveLength(1);});- it('does not restore a training run persisted mid-save (avoids double training-log)', () => {+ it('restores a training run persisted mid-save for an idempotent retry', () => {sessionStorage.setItem('post.activeRun', JSON.stringify({- runId: 'r1', state: 'saving', isTraining: true,+ runId: '11111111-1111-4111-8111-111111111111', state: 'saving', isTraining: true,drills: [{ type: 'compound-chain' }], currentDrillIndex: 0, currentDrill: null,currentQuestionIndex: 0, answers: [],drillResults: [{ module: 'llm-drills', type: 'compound-chain', score: 90 }],sessionScore: 90, tags: {},}));const { result } = renderHook(() => usePostSession());- expect(result.current.state).toBe('idle'); // training run is dropped, not resumed+ expect(result.current.state).toBe('complete');+ expect(result.current.drillResults).toHaveLength(1);});it('clears the persisted run on reset (no stale run resumes next mount)', async () => {diff --git a/client/src/services/README.md b/client/src/services/README.mdindex b0c7a78cf4..e9e7e0f546 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -77,7 +77,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiModelPersonality.js` | LLM personality self-profile tests: run, history, delete, scorer settings. || `apiGoals.js` | Identity / goals tracking. || `apiHealth.js` | Apple Health. |-| `apiMeatspace.js` | MeatSpace (genome + location). |+| `apiMeatspace.js` | MeatSpace health, genome, POST, memory-practice, and atomic POST training-run APIs. || `apiMortalLoom.js` | Mortality tracking. || `apiMoodBoard.js` | Mood boards (inspiration canvas + items). || `apiTribe.js` | Tribe people (relationship rings + contacts). |diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.jsindex fccbb60c00..9f13221ab9 100644--- a/client/src/services/apiMeatspace.js+++ b/client/src/services/apiMeatspace.js@@ -267,6 +267,11 @@ export const submitTrainingEntry = (data) => request('/meatspace/post/training',method: 'POST',body: JSON.stringify(data)});+export const submitTrainingRun = (data, options = {}) => request('/meatspace/post/training/runs', {+ method: 'POST',+ body: JSON.stringify(data),+ ...options+});export const getTrainingStats = (days) => request(`/meatspace/post/training/stats${days != null ? `?days=${days}` : ''}`);export const getTrainingEntries = (limit) => request(`/meatspace/post/training/entries${limit ? `?limit=${limit}` : ''}`);diff --git a/docs/COMPANION_APP_API.md b/docs/COMPANION_APP_API.mdindex 9426f06584..9e82b30a99 100644--- a/docs/COMPANION_APP_API.md+++ b/docs/COMPANION_APP_API.md@@ -162,26 +162,28 @@ are **not** interchangeable with these routes — pick per your need:`/api/meatspace/post/*` (`server/routes/meatspacePostRoutes.js`). These are theread/write endpoints for POST config, sessions, and progress on a single instance.-> **Note — POST progress does not cross-peer federate today.** The `meatspace`-> peer-sync category (`MEATSPACE_FILES` in `server/services/dataSync.js`) covers the-> daily-log and health-record files but **not** the POST files-> (`post-sessions.json`, `post-config.json`, …), so POST progress written to one-> instance stays local to it. Cross-instance POST reconciliation is a deferred-> follow-up (see below) — either add the POST files to the sync category or ship the-> iCloud import endpoint. A companion app that shows POST progress across instances-> must read each instance's `/api/meatspace/post/*` directly until then.+> **Note — POST progress is intentionally machine-local today.** Normalized+> history lives in PostgreSQL `post_runs` / `post_attempts` with no peer-sync+> cursor or record kind; cognitive-performance history never rides federation.+> A companion app that shows multiple instances must read each instance's+> `/api/meatspace/post/*` directly.| Method | Path | Purpose ||--------|------|---------|| `GET` / `PUT` | `/api/meatspace/post/config` | Read / update POST config. |-| `GET` | `/api/meatspace/post/sessions` | List training sessions. |-| `POST` | `/api/meatspace/post/sessions` | Record a session. |+| `GET` | `/api/meatspace/post/sessions` | List scored test sessions. |+| `POST` | `/api/meatspace/post/sessions` | Record an idempotent scored test session. |+| `POST` | `/api/meatspace/post/training/runs` | Atomically record one completed training run and all attempts. |+| `POST` | `/api/meatspace/post/training` | Backward-compatible single-attempt adapter. || `GET` | `/api/meatspace/post/progress` | Current progress. || `GET` | `/api/meatspace/post/stats` | Aggregate stats. || `GET` | `/api/meatspace/post/recommendations` | Recommended next drills. |-The app can *prompt* the user to run POST training from the phone and POST the-resulting session, or sync progress via the iCloud pattern below.+For a training run, generate one UUID run id and stable attempt ids before the+request. Retry the identical payload after transport failure; the server upserts+those ids in one transaction and returns success only after the full batch is+durable. Use `/sessions` only for scored tests, keeping training evidence out of+benchmark history.## 6. iCloud-JSON sync precedent (POST-progress reconciliation)@@ -192,16 +194,14 @@ is MortalLoom (`server/routes/mortalloom.js`, `server/services/mortalLoomStore.j- `POST /api/mortalloom/import` — non-destructive **by-id merge** of the sharediCloud JSON into `data/`.-A POST-progress iCloud reconciliation endpoint mirroring this-(`POST /api/…/import`, non-destructive by-id merge into `data/meatspace/post/*`) is-**out of scope for this foundation** and will be filed as its own follow-up. Until-it lands there is no cross-instance POST reconciliation — a companion app reads and-writes each instance's `/api/meatspace/post/*` routes directly (see the note in-§5).+A POST-progress iCloud reconciliation endpoint would need an explicit privacy+design before it can mirror this precedent. Until then there is no cross-instance+POST reconciliation — a companion app reads and writes each instance's+`/api/meatspace/post/*` routes directly (see the note in §5).## Deferred follow-ups (filed separately)-- POST-progress iCloud reconciliation import endpoint (mirrors `mortalloom.js`).+- Privacy-reviewed POST-progress reconciliation design (no federation by default).- Server-side audio/STT upload endpoint — only if on-device transcription isabandoned.- Push-notification / reminder plumbing to prompt POST training from the phone.diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 066acf7446..ef71b3261e 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -31,6 +31,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `catalog_ingredients` — typed creative records with JSONB payload, tags, embeddings, generated `search_tsv`, soft delete, sync sequence.- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges (the strongest argument for Postgres as the catalog graph store).- `memories` / `memory_links` — long-term memory + pgvector similarity.+- `post_runs` / `post_attempts` — normalized MeatSpace POST test, benchmark, and training history. A run owns its planned composition and lifecycle timestamps; attempts carry queryable module/drill, difficulty/config version, correctness/score, latency/completion, hint/confidence, input mode, and scorer provenance, with the compatibility payload retained in JSONB. The complete attempt set is replaced in one transaction and stable client ids make retries idempotent. Migrated from `data/meatspace/post-sessions.json` and `post-training-log.json` by `server/scripts/migratePostRunsToDB.js`; the sources are parked as `.imported` recovery copies. **Intentionally machine-local — never federated** because cognitive-performance history is personal activity data. Adapter: `server/services/postRunStore.js` (legacy JSON only under the dev/test file escape hatch).- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`.diff --git a/docs/features/post.md b/docs/features/post.mdindex 9ae8b27dc0..34fc2e429b 100644--- a/docs/features/post.md+++ b/docs/features/post.md@@ -41,7 +41,7 @@ The launcher offers two ways to start (`DrillTransition.jsx` handles the betweenThe session launcher (`PostSessionLauncher.jsx`) has a per-session Test/Train toggle:- **Test** — timed, scored, saved to session history (`POST /api/meatspace/post/sessions`).-- **Train** — immediate feedback, hints on wrong answers, not scored; entries go to a separate training log (`POST /api/meatspace/post/training`) with its own stats, streaks, and entries endpoints (`server/services/meatspacePostTraining.js` → `data/meatspace/post-training-log.json`).+- **Train** — immediate feedback and hints on wrong answers. The client saves the completed run once through `POST /api/meatspace/post/training/runs`; the server validates the full batch and commits the run plus every attempt in one PostgreSQL transaction. Stable run/attempt ids make retries idempotent. The results screen reports success only after that durable acknowledgement and leaves a failed save retryable. `POST /api/meatspace/post/training` remains as the backward-compatible one-entry adapter for standalone trainers and older clients.## Memory Builder@@ -61,7 +61,7 @@ Configurable memory training for songs, poems, sequences, speeches, or any order## Adaptive Difficulty-Opt-in adaptive tuning for math drills (`server/lib/postAdaptive.js`): recent scored performance nudges drill parameters, with a transparent preview of what would change (`GET /api/meatspace/post/adaptive-preview`). Multiplication is a special case: whenever the progressive ladder is on (the default), it owns multiplication's difficulty entirely and the preview reflects the ladder rung, not the generic `maxDigits` knob — the two are mutually exclusive per drill type, never blended.+Opt-in adaptive tuning for math drills (`server/lib/postAdaptive.js`): recent test and training attempts both inform skill evidence and nudge drill parameters, with a transparent preview of what would change (`GET /api/meatspace/post/adaptive-preview`). Training also feeds domain/drill progress, recommendations, progressive-ladder mastery, and mastered-skill retention scheduling. Benchmark/test history remains isolated: training never increments scored-session counts or changes the benchmark headline/overall score. Multiplication is a special case: whenever the progressive ladder is on (the default), it owns multiplication's difficulty entirely and the preview reflects the ladder rung, not the generic `maxDigits` knob — the two are mutually exclusive per drill type, never blended.## Drill Cache@@ -71,14 +71,15 @@ The four cacheable wordplay types are pre-generated so drills serve instantly (``server/services/meatspacePostReminder.js` schedules an optional daily POST reminder, re-registered whenever the config changes.-## Data Files+## Storage- `data/meatspace/post-config.json` — drill settings, enabled domains, time limits-- `data/meatspace/post-sessions.json` — scored test session history+- PostgreSQL `post_runs` + `post_attempts` — normalized test/benchmark/training history (machine-local; never federated)- `data/meatspace/post-memory-items.json` — memory builder content and mastery-- `data/meatspace/post-training-log.json` — unscored training/practice log- `data/meatspace/post-drill-cache.json` — pre-generated wordplay drills+On upgrade, `migratePostRunsToDB.js` imports the former `post-sessions.json` and `post-training-log.json` idempotently, preserves authored dates/timestamps, marks unknown legacy fields explicitly, and parks each source as `.imported`. The JSON implementation remains only for `NODE_ENV=test` / `MEMORY_BACKEND=file` development coverage.+## RoutesAll under `/api/meatspace` (`server/routes/meatspacePostRoutes.js`):@@ -90,7 +91,8 @@ All under `/api/meatspace` (`server/routes/meatspacePostRoutes.js`):- `GET /post/adaptive-preview` — adaptive-difficulty preview- `POST /post/score-llm` — score LLM drill responses- `GET /post/drill-cache/status`, `POST /post/drill-cache/fill` — wordplay cache-- `POST /post/training`, `GET /post/training/{stats,entries}` — training log+- `POST /post/training/runs` — atomic, idempotent completed training-run save+- `POST /post/training`, `GET /post/training/{stats,entries}` — one-entry compatibility adapter and training reads- `GET/POST /post/memory-items`, `GET/PUT/DELETE /post/memory-items/:id` — memory item CRUD- `GET /post/memory-items/due` — spaced-repetition due list- `POST /post/memory-items/:id/practice` — submit practice result, update masterydiff --git a/scripts/migrations/276-post-runs-db-import.js b/scripts/migrations/276-post-runs-db-import.jsnew file mode 100644index 0000000000..3855b134bc--- /dev/null+++ b/scripts/migrations/276-post-runs-db-import.js@@ -0,0 +1,13 @@+/**+ * Register the normalized POST run/attempt migration (#4441).+ *+ * The real legacy-file import needs a confirmed healthy PostgreSQL connection,+ * while this migration runner executes before the DB gate. The POST store runs+ * `server/scripts/migratePostRunsToDB.js` on its first PostgreSQL-backed access;+ * that importer is independently marker-gated and idempotent.+ */+export default {+ async up() {+ console.log('🧪 POST run migration: DB-backed legacy import runs on first POST store access');+ },+};diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.mdindex 3db45927ad..24b8fc470f 100644--- a/server/lib/db/schema/README.md+++ b/server/lib/db/schema/README.md@@ -21,6 +21,7 @@ Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by| `core.js` | `coreDdl` | Memory sync columns + the `schema_migrations` version tracker || `tribe.js` | `tribeDdl` | Tribe CRM — people, touchpoints, memory links (machine-local) || `humanActivity.js` | `humanActivityDdl` | Human-activity timeline event store (machine-local) |+| `post.js` | `postDdl` | MeatSpace POST normalized runs and attempts (machine-local) || `commissions.js` | `commissionsDdl` | Creative Commissions + feedback (machine-local) || `catalog.js` | `catalogDdl`, `catalogUserTypesDdl` | Catalog scraps/ingredients/tags/media + user-defined types || `media.js` | `mediaDdl` | Creative-director / music-video projects, mood boards, media assets |@@ -36,7 +37,7 @@ Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by### Composer (`index.js`)-- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `commissions`).+- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions`).- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →`universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` → `x` →`audit` DDL → audit triggers).diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.jsindex 2f439cc89b..13df998efe 100644--- a/server/lib/db/schema/index.js+++ b/server/lib/db/schema/index.js@@ -16,6 +16,7 @@import { coreDdl } from './core.js';import { tribeDdl } from './tribe.js';import { humanActivityDdl } from './humanActivity.js';+import { postDdl } from './post.js';import { commissionsDdl } from './commissions.js';import { catalogDdl, catalogUserTypesDdl } from './catalog.js';import { mediaDdl } from './media.js';@@ -33,6 +34,7 @@ export {coreDdl,tribeDdl,humanActivityDdl,+ postDdl,commissionsDdl,catalogDdl,catalogUserTypesDdl,@@ -51,13 +53,14 @@ export {};// Phase 1 — the `upgrades` list: memory-sync columns + migration tracker, then-// the machine-local Tribe / human-activity / commission tables. Run first,+// the machine-local Tribe / human-activity / POST / commission tables. Run first,// before the catalog block.export function buildUpgradeDdl() {return [...coreDdl,...tribeDdl,...humanActivityDdl,+ ...postDdl,...commissionsDdl,];}diff --git a/server/lib/db/schema/post.js b/server/lib/db/schema/post.jsnew file mode 100644index 0000000000..64d0ef7f2a--- /dev/null+++ b/server/lib/db/schema/post.js@@ -0,0 +1,44 @@+// MeatSpace POST run/attempt DDL (#4441) — normalized, machine-local practice+// evidence. These rows are intentionally excluded from federation and the+// generic record-audit stream: they can contain personal performance history.+export const postDdl = [+ `CREATE TABLE IF NOT EXISTS post_runs (+ id TEXT PRIMARY KEY,+ mode TEXT NOT NULL CHECK (mode IN ('benchmark', 'test', 'training')),+ local_day DATE NOT NULL,+ started_at TIMESTAMPTZ NOT NULL,+ completed_at TIMESTAMPTZ,+ status TEXT NOT NULL DEFAULT 'completed' CHECK (status IN ('planned', 'in_progress', 'completed')),+ planned JSONB NOT NULL DEFAULT '{}'::jsonb,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ legacy BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ )`,+ `CREATE INDEX IF NOT EXISTS idx_post_runs_mode_day ON post_runs (mode, local_day DESC)`,+ `CREATE INDEX IF NOT EXISTS idx_post_runs_started ON post_runs (started_at DESC)`,+ `CREATE TABLE IF NOT EXISTS post_attempts (+ id TEXT PRIMARY KEY,+ run_id TEXT NOT NULL REFERENCES post_runs(id) ON DELETE CASCADE,+ position INTEGER NOT NULL CHECK (position >= 0),+ module TEXT NOT NULL,+ drill_type TEXT NOT NULL,+ difficulty JSONB,+ config_version TEXT,+ correct BOOLEAN,+ score DOUBLE PRECISION CHECK (score IS NULL OR (score >= 0 AND score <= 100)),+ latency_ms BIGINT NOT NULL DEFAULT 0 CHECK (latency_ms >= 0),+ completion DOUBLE PRECISION CHECK (completion IS NULL OR (completion >= 0 AND completion <= 1)),+ hint_used BOOLEAN NOT NULL DEFAULT FALSE,+ confidence DOUBLE PRECISION CHECK (confidence IS NULL OR (confidence >= 0 AND confidence <= 1)),+ input_mode TEXT NOT NULL DEFAULT 'unknown',+ scorer_provenance TEXT NOT NULL DEFAULT 'unknown',+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ legacy BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ UNIQUE (run_id, position)+ )`,+ `CREATE INDEX IF NOT EXISTS idx_post_attempts_run ON post_attempts (run_id, position)`,+ `CREATE INDEX IF NOT EXISTS idx_post_attempts_skill ON post_attempts (module, drill_type)`,+];diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.jsindex d66fb2907b..33e5bd7f82 100644--- a/server/lib/db/schema/schema.test.js+++ b/server/lib/db/schema/schema.test.js@@ -25,7 +25,7 @@ import {} from './index.js';const DOMAIN_ARRAYS = [- 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'commissionsDdl',+ 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl','catalogDdl', 'catalogUserTypesDdl', 'mediaDdl', 'universesDdl','libraryDdl', 'pipelineDdl', 'writersRoomDdl', 'loraDdl', 'privacyDdl', 'stackerNewsDdl', 'xDdl','auditDdl',@@ -44,6 +44,7 @@ describe('db/schema barrel + composer (#2832)', () => {...schema.coreDdl,...schema.tribeDdl,...schema.humanActivityDdl,+ ...schema.postDdl,...schema.commissionsDdl,];expect(buildUpgradeDdl()).toEqual(expected);diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 9a968e03ca..abf828599c 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -150,6 +150,9 @@ const drillTypeConfigSchema = z.object({// Task result within a session// score is optional — the server recomputes it via scoreDrillconst taskResultSchema = z.object({+ // Stable client attempt id. Optional for legacy scored-session clients; the+ // store derives a deterministic id from run id + position when absent.+ id: z.string().min(1).max(200).optional(),module: z.enum(POST_MODULES),type: z.enum(DRILL_TYPES),config: drillTypeConfigSchema.optional().default({}),@@ -181,6 +184,10 @@ const taskResultSchema = z.object({misses: z.number().int().min(0).optional(),falseAlarms: z.number().int().min(0).optional(),correctRejections: z.number().int().min(0).optional(),+ hintUsed: z.boolean().optional(),+ confidence: z.number().min(0).max(1).nullable().optional(),+ inputMode: z.string().min(1).max(50).optional(),+ scorerProvenance: z.string().min(1).max(100).optional(),evaluation: z.object({score: z.number().min(0).max(100).optional(),breakdown: z.array(z.object({@@ -505,6 +512,10 @@ const trainingQuestionSchema = z.object({// Training log entry submissionexport const trainingEntrySchema = z.object({+ // Optional stable ids let newer callers retry through the legacy one-entry+ // adapter without duplication. Old callers remain valid and get server ids.+ id: z.string().min(1).max(200).optional(),+ runId: z.string().min(1).max(200).optional(),module: z.string(),// Training log entries also cover Morse (client-side scored, never a scored// POST session) — union in MORSE_DRILL_TYPES here rather than in the shared@@ -515,6 +526,64 @@ export const trainingEntrySchema = z.object({correctCount: z.number().int().min(0),totalMs: z.number().min(0),questions: z.array(trainingQuestionSchema).optional(),+ difficulty: z.record(z.string(), z.unknown()).nullable().optional(),+ configVersion: z.string().max(100).nullable().optional(),+ correct: z.boolean().nullable().optional(),+ score: z.number().min(0).max(100).nullable().optional(),+ completion: z.number().min(0).max(1).nullable().optional(),+ hintUsed: z.boolean().optional(),+ confidence: z.number().min(0).max(1).nullable().optional(),+ inputMode: z.string().min(1).max(50).optional(),+ scorerProvenance: z.string().min(1).max(100).optional(),+});++const trainingAttemptSchema = z.object({+ id: z.string().min(1).max(200),+ module: z.string().min(1).max(100),+ drillType: z.enum([...DRILL_TYPES, ...MORSE_DRILL_TYPES]),+ memoryItemId: z.string().min(1).max(200).nullable().optional(),+ difficulty: z.record(z.string(), z.unknown()).nullable().optional(),+ configVersion: z.string().max(100).nullable().optional(),+ questionCount: z.number().int().min(0),+ correctCount: z.number().int().min(0),+ latencyMs: z.number().min(0),+ // Deterministic drills retain answer/latency detail for ladder/adaptive+ // evidence; wordplay keeps its established compact training-question shape.+ questions: z.array(z.union([questionResultSchema, trainingQuestionSchema])).max(500).optional(),+ correct: z.boolean().nullable().optional(),+ score: z.number().min(0).max(100).nullable().optional(),+ completion: z.number().min(0).max(1).nullable().optional(),+ hintUsed: z.boolean().optional().default(false),+ confidence: z.number().min(0).max(1).nullable().optional(),+ inputMode: z.string().min(1).max(50).optional().default('unknown'),+ scorerProvenance: z.string().min(1).max(100).optional().default('post-client'),+}).superRefine((attempt, ctx) => {+ if (attempt.correctCount > attempt.questionCount) {+ ctx.addIssue({ code: 'custom', path: ['correctCount'], message: 'correctCount cannot exceed questionCount' });+ }+});++// Complete training-run batch. Validation finishes before the service opens a+// transaction, so malformed attempt N can never leave attempts 0..N-1 saved.+export const trainingRunSubmitSchema = z.object({+ id: z.string().uuid(),+ mode: z.literal('training').optional().default('training'),+ startedAt: z.string().datetime().optional(),+ completedAt: z.string().datetime().optional(),+ planned: z.object({+ modules: z.array(z.string().min(1).max(100)).max(20).optional(),+ drillTypes: z.array(z.enum([...DRILL_TYPES, ...MORSE_DRILL_TYPES])).max(100).optional(),+ }).optional(),+ attempts: z.array(trainingAttemptSchema).min(1).max(100),+}).superRefine((run, ctx) => {+ const ids = new Set();+ run.attempts.forEach((attempt, index) => {+ if (ids.has(attempt.id)) ctx.addIssue({ code: 'custom', path: ['attempts', index, 'id'], message: 'attempt ids must be unique within a run' });+ ids.add(attempt.id);+ });+ if (run.startedAt && run.completedAt && Date.parse(run.completedAt) < Date.parse(run.startedAt)) {+ ctx.addIssue({ code: 'custom', path: ['completedAt'], message: 'completedAt cannot precede startedAt' });+ }});export { LLM_DRILL_TYPES, MATH_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES, POST_MODULES, COGNITIVE_DRILL_TYPES, MORSE_DRILL_TYPES };diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.jsindex d80588972b..68aedfb41a 100644--- a/server/routes/meatspacePostRoutes.js+++ b/server/routes/meatspacePostRoutes.js@@ -24,6 +24,7 @@ import {LLM_DRILL_TYPES,MEMORY_DRILL_TYPES,trainingEntrySchema,+ trainingRunSubmitSchema,postProgressQuerySchema,} from '../lib/postValidation.js';import * as postService from '../services/meatspacePost.js';@@ -303,6 +304,16 @@ router.post('/post/training', asyncHandler(async (req, res) => {res.status(201).json(entry);}));+/**+ * POST /api/meatspace/post/training/runs+ * Atomically persist every attempt in one completed training run.+ */+router.post('/post/training/runs', asyncHandler(async (req, res) => {+ const data = validateRequest(trainingRunSubmitSchema, req.body);+ const run = await trainingService.submitTrainingRun(data);+ res.status(201).json(run);+}));+/*** GET /api/meatspace/post/training/stats* Training stats: practice counts, streaks, accuracy by drill typediff --git a/server/routes/meatspacePostRoutes.training.test.js b/server/routes/meatspacePostRoutes.training.test.jsnew file mode 100644index 0000000000..5e15d560f4--- /dev/null+++ b/server/routes/meatspacePostRoutes.training.test.js@@ -0,0 +1,66 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++vi.mock('../services/meatspacePostTraining.js', () => ({+ submitTrainingEntry: vi.fn(),+ submitTrainingRun: vi.fn(),+ getTrainingStats: vi.fn(),+ getTrainingEntries: vi.fn(),+}));++import * as trainingService from '../services/meatspacePostTraining.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;+}++const run = (overrides = {}) => ({+ id: '11111111-1111-4111-8111-111111111111',+ mode: 'training',+ attempts: [{+ id: 'attempt-1', module: 'mental-math', drillType: 'multiplication',+ questionCount: 2, correctCount: 1, latencyMs: 1200,+ }],+ ...overrides,+});++describe('POST /api/meatspace/post/training/runs (#4441)', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ trainingService.submitTrainingRun.mockResolvedValue({ id: run().id, attemptCount: 1 });+ });++ it('validates the complete batch before delegating', async () => {+ const response = await request(app).post('/api/meatspace/post/training/runs').send(run());+ expect(response.status).toBe(201);+ expect(trainingService.submitTrainingRun).toHaveBeenCalledWith(expect.objectContaining({+ id: run().id,+ attempts: [expect.objectContaining({ id: 'attempt-1', correctCount: 1 })],+ }));+ });++ it('rejects an invalid later attempt without calling the service', async () => {+ const response = await request(app).post('/api/meatspace/post/training/runs').send(run({+ attempts: [run().attempts[0], { ...run().attempts[0], id: 'attempt-2', correctCount: 3 }],+ }));+ expect(response.status).toBe(400);+ expect(trainingService.submitTrainingRun).not.toHaveBeenCalled();+ });++ it('rejects duplicate attempt ids before storage', async () => {+ const response = await request(app).post('/api/meatspace/post/training/runs').send(run({+ attempts: [run().attempts[0], { ...run().attempts[0] }],+ }));+ expect(response.status).toBe(400);+ expect(trainingService.submitTrainingRun).not.toHaveBeenCalled();+ });+});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 0dc0be3ea1..a201d4b0f0 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -68,6 +68,49 @@ CREATE TABLE IF NOT EXISTS schema_migrations (applied_at TIMESTAMPTZ DEFAULT NOW());+-- MeatSpace POST normalized run/attempt history. Machine-local: personal+-- performance evidence never rides federation.+CREATE TABLE IF NOT EXISTS post_runs (+ id TEXT PRIMARY KEY,+ mode TEXT NOT NULL CHECK (mode IN ('benchmark', 'test', 'training')),+ local_day DATE NOT NULL,+ started_at TIMESTAMPTZ NOT NULL,+ completed_at TIMESTAMPTZ,+ status TEXT NOT NULL DEFAULT 'completed' CHECK (status IN ('planned', 'in_progress', 'completed')),+ planned JSONB NOT NULL DEFAULT '{}'::jsonb,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ legacy BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);+CREATE INDEX IF NOT EXISTS idx_post_runs_mode_day ON post_runs (mode, local_day DESC);+CREATE INDEX IF NOT EXISTS idx_post_runs_started ON post_runs (started_at DESC);++CREATE TABLE IF NOT EXISTS post_attempts (+ id TEXT PRIMARY KEY,+ run_id TEXT NOT NULL REFERENCES post_runs(id) ON DELETE CASCADE,+ position INTEGER NOT NULL CHECK (position >= 0),+ module TEXT NOT NULL,+ drill_type TEXT NOT NULL,+ difficulty JSONB,+ config_version TEXT,+ correct BOOLEAN,+ score DOUBLE PRECISION CHECK (score IS NULL OR (score >= 0 AND score <= 100)),+ latency_ms BIGINT NOT NULL DEFAULT 0 CHECK (latency_ms >= 0),+ completion DOUBLE PRECISION CHECK (completion IS NULL OR (completion >= 0 AND completion <= 1)),+ hint_used BOOLEAN NOT NULL DEFAULT FALSE,+ confidence DOUBLE PRECISION CHECK (confidence IS NULL OR (confidence >= 0 AND confidence <= 1)),+ input_mode TEXT NOT NULL DEFAULT 'unknown',+ scorer_provenance TEXT NOT NULL DEFAULT 'unknown',+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ legacy BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ UNIQUE (run_id, position)+);+CREATE INDEX IF NOT EXISTS idx_post_attempts_run ON post_attempts (run_id, position);+CREATE INDEX IF NOT EXISTS idx_post_attempts_skill ON post_attempts (module, drill_type);+-- Memory relationships (bidirectional links)CREATE TABLE IF NOT EXISTS memory_links (source_id UUID REFERENCES memories(id) ON DELETE CASCADE,diff --git a/server/scripts/migratePostRunsToDB.js b/server/scripts/migratePostRunsToDB.jsnew file mode 100644index 0000000000..d36ad5443f--- /dev/null+++ b/server/scripts/migratePostRunsToDB.js@@ -0,0 +1,194 @@+/**+ * One-time POST history importer (#4441): scored sessions + training entries+ * from their legacy JSON files into normalized PostgreSQL runs/attempts.+ *+ * Rows use stable legacy-derived ids and ON CONFLICT upserts, so a crash before+ * the marker/rename is safe to retry. Source files are renamed only after one+ * transaction has imported both feeds successfully.+ */++import { rename, stat } from 'fs/promises';+import { join } from 'path';+import { PATHS, readJSONFile } from '../lib/fileUtils.js';+import { markerExists, writeMarker } from '../lib/migrationMarker.js';+import { mirrorTimestamp } from '../lib/pgTimestamp.js';+import { withTransaction } from '../lib/db.js';+import { saveNormalizedRunWithClient } from '../services/postRunDb.js';++const MARKER = 'post-runs.migrated.json';+const SESSIONS = 'post-sessions.json';+const TRAINING = 'post-training-log.json';++const validDay = (value, fallback) => {+ const candidate = String(value || '');+ if (/^\d{4}-\d{2}-\d{2}$/.test(candidate)) {+ const parsed = new Date(`${candidate}T00:00:00.000Z`);+ if (!Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === candidate) return candidate;+ }+ return fallback.slice(0, 10);+};+const bounded = (value, min, max, fallback = null) => {+ if (value == null || value === '' || typeof value === 'boolean') return fallback;+ const number = Number(value);+ return Number.isFinite(number) ? Math.min(max, Math.max(min, number)) : fallback;+};++async function parkLegacyFile(path) {+ const source = await stat(path).catch(() => null);+ if (!source) return false;+ const recoveryPath = `${path}.imported`;+ const recovery = await stat(recoveryPath).catch(() => null);+ if (recovery) return false; // retain the existing recovery copy+ await rename(path, recoveryPath);+ return true;+}++export function normalizeLegacyPostSession(session, index, now) {+ const id = typeof session?.id === 'string' && session.id ? session.id : `legacy-post-session:${index}`;+ const startedAt = mirrorTimestamp(session?.startedAt, mirrorTimestamp(session?.completedAt, now));+ const completedAt = mirrorTimestamp(session?.completedAt, startedAt);+ const tasks = Array.isArray(session?.tasks) ? session.tasks : [];+ const data = { ...(session || {}), id, legacy: true };+ return {+ id,+ mode: 'test',+ localDay: validDay(session?.date, startedAt),+ startedAt,+ completedAt,+ status: 'completed',+ planned: { cadence: session?.cadence || 'daily', modules: session?.modules || [] },+ data,+ legacy: true,+ attempts: tasks.map((task, position) => {+ const questions = Array.isArray(task?.questions) ? task.questions : [];+ const answered = questions.filter((question) => question?.answered != null);+ return {+ id: task?.id || `${id}:attempt:${position}`,+ module: task?.module || 'unknown',+ drillType: task?.type || 'unknown',+ difficulty: task?.config || null,+ configVersion: task?.configVersion || 'legacy',+ correct: answered.length ? answered.every((question) => question?.correct === true) : null,+ score: bounded(task?.score, 0, 100),+ latencyMs: bounded(task?.totalMs, 0, Number.MAX_SAFE_INTEGER, 0),+ completion: typeof task?.completion === 'number'+ ? bounded(task.completion, 0, 1)+ : questions.length ? answered.length / questions.length : null,+ hintUsed: questions.some((question) => question?.hintUsed === true),+ confidence: null,+ inputMode: task?.inputMode || 'unknown',+ scorerProvenance: task?.scorerProvenance || 'legacy',+ data: { ...(task || {}), legacy: true, inputMode: task?.inputMode || 'unknown', scorerProvenance: task?.scorerProvenance || 'legacy' },+ legacy: true,+ };+ }),+ };+}++export function normalizeLegacyTrainingEntry(entry, index, now) {+ const attemptId = typeof entry?.id === 'string' && entry.id ? entry.id : `legacy-training-attempt:${index}`;+ const id = typeof entry?.runId === 'string' && entry.runId ? entry.runId : `legacy-training-run:${attemptId}`;+ const startedAt = mirrorTimestamp(entry?.timestamp, now);+ const total = Number(entry?.questionCount ?? entry?.total) || 0;+ const correctCount = Number(entry?.correctCount ?? entry?.correct) || 0;+ const data = {+ ...(entry || {}), id: attemptId, runId: id, legacy: true,+ inputMode: entry?.inputMode || 'unknown',+ scorerProvenance: entry?.scorerProvenance || 'legacy',+ };+ return {+ id,+ mode: 'training',+ localDay: validDay(entry?.date, startedAt),+ startedAt,+ completedAt: startedAt,+ status: 'completed',+ planned: { modules: entry?.module ? [entry.module] : [] },+ data: { id, mode: 'training', legacy: true },+ legacy: true,+ attempts: [{+ id: attemptId,+ module: entry?.module || (entry?.memoryItemId ? 'memory' : 'unknown'),+ drillType: entry?.drillType || entry?.mode || 'unknown',+ difficulty: entry?.difficulty || null,+ configVersion: entry?.configVersion || 'legacy',+ correct: total > 0 ? correctCount === total : null,+ score: bounded(entry?.score, 0, 100, total > 0 ? bounded((correctCount / total) * 100, 0, 100) : null),+ latencyMs: bounded(entry?.totalMs, 0, Number.MAX_SAFE_INTEGER, 0),+ completion: total > 0 ? 1 : null,+ hintUsed: entry?.hintUsed === true,+ confidence: bounded(entry?.confidence, 0, 1),+ inputMode: entry?.inputMode || 'unknown',+ scorerProvenance: entry?.scorerProvenance || 'legacy',+ data,+ legacy: true,+ }],+ };+}++export function groupLegacyTrainingRuns(entries, now) {+ const grouped = new Map();+ entries.forEach((entry, index) => {+ const candidate = normalizeLegacyTrainingEntry(entry, index, now);+ const existing = grouped.get(candidate.id);+ if (!existing) {+ grouped.set(candidate.id, candidate);+ return;+ }+ existing.attempts.push(...candidate.attempts);+ if (candidate.startedAt < existing.startedAt) {+ existing.startedAt = candidate.startedAt;+ existing.localDay = candidate.localDay;+ }+ if (candidate.completedAt > existing.completedAt) existing.completedAt = candidate.completedAt;+ existing.planned.modules = [...new Set([+ ...(existing.planned.modules || []),+ ...(candidate.planned.modules || []),+ ])];+ });+ return [...grouped.values()];+}++export async function migratePostRunsToDB() {+ if (await markerExists(MARKER)) return { ok: true, reason: 'already-applied', runs: 0, attempts: 0 };++ const sessionsPath = join(PATHS.meatspace, SESSIONS);+ const trainingPath = join(PATHS.meatspace, TRAINING);+ const [sessionsStat, trainingStat] = await Promise.all([+ stat(sessionsPath).catch(() => null),+ stat(trainingPath).catch(() => null),+ ]);+ if (!sessionsStat && !trainingStat) return { ok: true, reason: 'fresh-install', runs: 0, attempts: 0 };++ const sessionsData = sessionsStat+ ? await readJSONFile(sessionsPath, null, { allowArray: false, strict: true })+ : { sessions: [] };+ const trainingData = trainingStat+ ? await readJSONFile(trainingPath, null, { allowArray: false, strict: true })+ : { entries: [] };+ if (!Array.isArray(sessionsData?.sessions)) throw new Error('Legacy POST sessions file is malformed');+ if (!Array.isArray(trainingData?.entries)) throw new Error('Legacy POST training log is malformed');++ const now = new Date().toISOString();+ const runs = [+ ...sessionsData.sessions.map((session, index) => normalizeLegacyPostSession(session, index, now)),+ ...groupLegacyTrainingRuns(trainingData.entries, now),+ ];+ await withTransaction(async (client) => {+ for (const run of runs) await saveNormalizedRunWithClient(client, run);+ });++ const renamed = [];+ try {+ if (sessionsStat && await parkLegacyFile(sessionsPath)) renamed.push(SESSIONS);+ if (trainingStat && await parkLegacyFile(trainingPath)) renamed.push(TRAINING);+ } catch (err) {+ console.warn(`⚠️ POST→DB import landed but legacy-file rename failed (${err.message}); next boot will retry idempotently`);+ return { ok: true, reason: 'imported-rename-failed', runs: runs.length, attempts: runs.reduce((sum, run) => sum + run.attempts.length, 0) };+ }++ const attempts = runs.reduce((sum, run) => sum + run.attempts.length, 0);+ await writeMarker(MARKER, { migratedAt: new Date().toISOString(), runs: runs.length, attempts, renamed });+ console.log(`🧪 POST→DB import: ${runs.length} run(s), ${attempts} attempt(s); legacy recovery copies retained`);+ return { ok: true, reason: 'imported', runs: runs.length, attempts };+}diff --git a/server/scripts/migratePostRunsToDB.test.js b/server/scripts/migratePostRunsToDB.test.jsnew file mode 100644index 0000000000..0193c4ef39--- /dev/null+++ b/server/scripts/migratePostRunsToDB.test.js@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';+import { groupLegacyTrainingRuns, normalizeLegacyPostSession, normalizeLegacyTrainingEntry } from './migratePostRunsToDB.js';++const NOW = '2026-08-17T12:00:00.000Z';++describe('legacy POST normalization (#4441)', () => {+ it('preserves scored ids/dates/timestamps and derives stable attempt ids', () => {+ const run = normalizeLegacyPostSession({+ id: 'session-1', date: '2026-08-16', startedAt: '2026-08-16T10:00:00.000Z',+ completedAt: '2026-08-16T10:05:00.000Z', modules: ['mental-math'],+ tasks: [{ module: 'mental-math', type: 'multiplication', totalMs: 5000, score: 80 }],+ }, 0, NOW);+ expect(run).toMatchObject({ id: 'session-1', mode: 'test', localDay: '2026-08-16', legacy: true });+ expect(run.attempts[0]).toMatchObject({+ id: 'session-1:attempt:0', inputMode: 'unknown', scorerProvenance: 'legacy', legacy: true,+ });+ });++ it('preserves training ids and marks irreconstructible provenance explicitly', () => {+ const run = normalizeLegacyTrainingEntry({+ id: 'entry-1', date: '2026-08-15', timestamp: '2026-08-15T09:00:00.000Z',+ module: 'memory', mode: 'spaced', correct: 4, total: 5, totalMs: 30000,+ }, 0, NOW);+ expect(run).toMatchObject({+ id: 'legacy-training-run:entry-1', mode: 'training', localDay: '2026-08-15', legacy: true,+ });+ expect(run.attempts[0]).toMatchObject({+ id: 'entry-1', drillType: 'spaced', inputMode: 'unknown', scorerProvenance: 'legacy', legacy: true,+ });+ });++ it('groups newer legacy-file entries that already share a run id', () => {+ const runs = groupLegacyTrainingRuns([+ { id: 'a-1', runId: 'run-1', date: '2026-08-15', timestamp: '2026-08-15T09:00:00.000Z', module: 'mental-math', drillType: 'powers' },+ { id: 'a-2', runId: 'run-1', date: '2026-08-15', timestamp: '2026-08-15T09:01:00.000Z', module: 'cognitive', drillType: 'stroop' },+ ], NOW);+ expect(runs).toHaveLength(1);+ expect(runs[0].attempts.map((attempt) => attempt.id)).toEqual(['a-1', 'a-2']);+ expect(runs[0].planned.modules).toEqual(['mental-math', 'cognitive']);+ });+});diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex a56ec5d749..3690c76a36 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -9,7 +9,7 @@ import { join } from 'path';import { randomUUID } from 'crypto';import { EventEmitter } from 'events';import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';-import { deepMerge, isPlainObject } from '../lib/objects.js';+import { deepMerge } from '../lib/objects.js';import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';import { resolveTopicForDrillType, isTopicEnabled, isMemoryItemEnabled } from '../lib/postTopics.js';import { adaptDrillConfig, ADAPTIVE_SPECS, ADAPTIVE_DEFAULTS } from '../lib/postAdaptive.js';@@ -38,6 +38,7 @@ import { getAllTrainingEntries } from './postTrainingLogStore.js';import { getMorseProgress, MAX_KOCH_LEVEL } from './meatspacePostMorse.js';import { computePostStreaks, computeUnifiedStreak, normalizeYmd, recordDayKey, withDerivedDayKeys, ymdToUTC, ymdShift } from '../lib/postStreak.js';import { getUserTimezone, todayInTimezone, userLocalToday as localToday } from '../lib/timezone.js';+import { getStoredPostSession, listPostSessions, saveStoredPostSession } from './postRunStore.js';// Re-export the shared streak helper so existing importers of// `computePostStreaks` from this module keep working after it moved to@@ -55,7 +56,6 @@ export { computePostStreaks };// first-visit/handled markers (#2666).const MEATSPACE_DIR = PATHS.meatspace;-const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');const CONFIG_FILE = join(MEATSPACE_DIR, 'post-config.json');// Tiny pub/sub (mirrors settingsEvents in server/services/settings.js) so@@ -227,15 +227,7 @@ export async function updatePostConfig(updates) {* that COUNT sessions opt in — a fake 0 there is a lie, not a default (#2726).*/async function loadSessions({ strict = false } = {}) {- const raw = await readJSONFile(SESSIONS_FILE, { sessions: [] }, { allowArray: false, strict });- // Under strict, a file that parsed to a non-countable shape is as untrustworthy as- // one that failed to parse — validate rather than silently substituting an empty.- if (strict && (!isPlainObject(raw) || !Array.isArray(raw.sessions))) {- throw new Error(`POST sessions malformed: ${SESSIONS_FILE}`);- }- const data = isPlainObject(raw) ? raw : { sessions: [] };- if (!Array.isArray(data.sessions)) data.sessions = [];- return data;+ return { sessions: await listPostSessions({ strict }) };}/**@@ -269,8 +261,7 @@ export async function getPostSessions(from, to, options) {* history row beside it shows the re-keyed one.*/export async function getPostSession(id) {- const data = await loadSessions();- const session = data.sessions.find(s => s.id === id);+ const session = await getStoredPostSession(id);if (!session) return null;return { ...session, date: recordDayKey(session, await getUserTimezone()) };}@@ -347,10 +338,10 @@ export async function submitPostSession(sessionData) {// clients / direct service callers) falls back to a fresh uuid.const sessionId = sessionData.id || randomUUID();const existingIndex = data.sessions.findIndex(s => s.id === sessionId);- const isNewSession = existingIndex < 0;+ let isNewSession = existingIndex < 0;const existing = isNewSession ? null : data.sessions[existingIndex];- const session = {+ let session = {id: sessionId,// Preserve the ORIGINAL day/start on an idempotent re-submit — a retry that// crosses midnight (or just arrives later) must not move the session to a@@ -367,11 +358,9 @@ export async function submitPostSession(sessionData) {tags: sessionData.tags || {}};- if (isNewSession) data.sessions.push(session);- else data.sessions[existingIndex] = session;- data.sessions.sort((a, b) => a.date.localeCompare(b.date));- await ensureMeatspaceDir();- await atomicWrite(SESSIONS_FILE, data);+ const stored = await saveStoredPostSession(session);+ session = stored.session;+ isNewSession = stored.isNew;console.log(`🧪 POST session ${isNewSession ? 'saved' : 'updated'}: score=${session.score} modules=${session.modules.join(',')}`);// A memory drill completed inside this session IS a review — mirror the@@ -663,6 +652,68 @@ export function deriveTaskAvgResponseMs(task) {return Math.round(timed.reduce((sum, q) => sum + q.responseMs, 0) / timed.length);}+function trainingEntryTask(entry) {+ const rawQuestionCount = Number(entry?.questionCount);+ const rawCorrectCount = Number(entry?.correctCount);+ const questionCount = Number.isFinite(rawQuestionCount) && rawQuestionCount > 0 ? rawQuestionCount : 0;+ const correctCount = Number.isFinite(rawCorrectCount)+ ? Math.max(0, Math.min(questionCount, rawCorrectCount))+ : 0;+ const accuracy = questionCount > 0 ? correctCount / questionCount : null;+ return {+ id: entry?.id,+ module: entry?.module,+ type: entry?.drillType,+ config: entry?.difficulty || {},+ questions: Array.isArray(entry?.questions) ? entry.questions : [],+ score: Number.isFinite(entry?.score) ? entry.score : (accuracy == null ? null : accuracy * 100),+ accuracy,+ completion: typeof entry?.completion === 'number' ? entry.completion : (questionCount > 0 ? 1 : null),+ avgResponseMs: questionCount > 0 ? (entry?.totalMs || 0) / questionCount : null,+ totalMs: entry?.totalMs || 0,+ totalCount: questionCount,+ };+}++function skillEvidenceSessions(sessions, training) {+ return [+ ...sessions,+ ...training.map((entry) => ({+ id: entry.runId || entry.id,+ date: entry.date,+ startedAt: entry.timestamp,+ completedAt: entry.timestamp,+ evidenceMode: 'training',+ tasks: [trainingEntryTask(entry)],+ })),+ ];+}++function summarizeSkillEvidence(sessions, training) {+ const accuracyLists = {};+ const completionLists = {};+ const counts = {};+ const add = (task) => {+ if (!task?.module || !task?.type) return;+ const key = `${task.module}:${task.type}`;+ counts[key] = (counts[key] || 0) + 1;+ const accuracy = deriveTaskAccuracy(task);+ if (accuracy != null) (accuracyLists[key] ||= []).push(accuracy);+ const completion = deriveTaskCompletion(task);+ if (completion != null) (completionLists[key] ||= []).push(completion);+ };+ for (const session of sessions) for (const task of session.tasks || []) add(task);+ for (const entry of training) add(trainingEntryTask(entry));+ const meanMap = (lists) => Object.fromEntries(+ Object.entries(lists).map(([key, values]) => [key, values.reduce((sum, value) => sum + value, 0) / values.length]),+ );+ return {+ evidenceByDrillCount: counts,+ evidenceByDrillAccuracy: meanMap(accuracyLists),+ evidenceByDrillCompletion: meanMap(completionLists),+ };+}+export async function getPostStats(days = 30) {const atDate = new Date();const sessions = await getPostSessions();@@ -684,6 +735,7 @@ export async function getPostStats(days = 30) {lastDate: unified.lastActiveDate,};let recent = sessions;+ let recentTraining = training;if (days > 0) {// Window the stats relative to the user's local today (day-string math via// UTC midnight, DST-safe) so the cutoff matches the tz-correct session dates.@@ -692,10 +744,16 @@ export async function getPostStats(days = 30) {const date = recordDayKey(s, timezone);return date && date >= cutoffStr;});+ recentTraining = training.filter((entry) => {+ const date = recordDayKey(entry, timezone);+ return date && date >= cutoffStr;+ });}+ const evidence = summarizeSkillEvidence(recent, recentTraining);+if (recent.length === 0) {- return { days, sessionCount: 0, overall: null, byModule: {}, byDrill: {}, byDrillCount: {}, byDrillAccuracy: {}, byDrillCompletion: {}, ...streaks };+ return { days, sessionCount: 0, overall: null, byModule: {}, byDrill: {}, byDrillCount: {}, byDrillAccuracy: {}, byDrillCompletion: {}, ...evidence, ...streaks };}const scores = recent.map(s => s.score);@@ -739,7 +797,7 @@ export async function getPostStats(days = 30) {const byDrillCompletion = {};for (const key of Object.keys(byDrillCompletionList)) byDrillCompletion[key] = avgFrac(byDrillCompletionList[key]);- return { days, sessionCount: recent.length, overall, byModule, byDrill, byDrillCount, byDrillAccuracy, byDrillCompletion, ...streaks };+ return { days, sessionCount: recent.length, overall, byModule, byDrill, byDrillCount, byDrillAccuracy, byDrillCompletion, ...evidence, ...streaks };}// =============================================================================@@ -873,6 +931,13 @@ export async function getPostProgress({ days = 90 } = {}) {const date = recordDayKey(e, timezone);if (!date) continue;ensureDay(date).minutes += (e.totalMs || 0) / 60000;+ const task = trainingEntryTask(e);+ const accuracy = deriveTaskAccuracy(task);+ const responseMs = deriveTaskAvgResponseMs(task);+ // Training updates skill/domain evidence, but it does not enter the scored+ // benchmark headline (`byDay.score`, session count, or overall score).+ pushMetricSeries(domainMap, task.module, date, task.score, accuracy, responseMs);+ pushMetricSeries(drillMap, task.type, date, task.score, accuracy, responseMs);}const byDay = Array.from(dayMap.entries())@@ -957,8 +1022,8 @@ const DRILL_LABEL = (type) =>* `"<module>:<type>"`.*/export function weakestSkillFromStats(stats) {- const acc = stats?.byDrillAccuracy || {};- const counts = stats?.byDrillCount || {};+ const acc = stats?.evidenceByDrillAccuracy || stats?.byDrillAccuracy || {};+ const counts = stats?.evidenceByDrillCount || stats?.byDrillCount || {};let worst = null;for (const [key, a] of Object.entries(acc)) {if (typeof a !== 'number' || Number.isNaN(a)) continue;@@ -1561,9 +1626,9 @@ export function generateDrill(type, config = {}) {async function getAdaptiveSignal(type) {const stats = await getPostStats(ADAPTIVE_DEFAULTS.windowDays);const key = `${MATH_MODULE}:${type}`;- const accuracy = stats.byDrillAccuracy?.[key];- const samples = stats.byDrillCount?.[key] || 0;- const completion = stats.byDrillCompletion?.[key];+ 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,@@ -1588,7 +1653,8 @@ async function getAdaptiveSignal(type) {*/async function getMultiplicationLevelStats(windowDays = MASTERY_DEFAULTS.windowDays) {const atDate = new Date();- const sessions = await getPostSessions();+ const [scoredSessions, training] = await Promise.all([getPostSessions(), getAllTrainingEntries()]);+ const sessions = skillEvidenceSessions(scoredSessions, training);// Window off the user's local today (DST-safe day math) so the cutoff stays// consistent with the tz-correct session dates submitPostSession now stamps// (issue #2681) — a UTC-day cutoff would skew the window edge by the tz offset.@@ -1635,7 +1701,8 @@ async function getMultiplicationLevelStats(windowDays = MASTERY_DEFAULTS.windowDasync function getPowersLevelStats(windowDays = POWERS_MASTERY_DEFAULTS.windowDays) {const atDate = new Date();- const sessions = await getPostSessions();+ const [scoredSessions, training] = await Promise.all([getPostSessions(), getAllTrainingEntries()]);+ const sessions = skillEvidenceSessions(scoredSessions, training);const timezone = await getUserTimezone();const todayStr = todayInTimezone(timezone, atDate);const cutoffStr = windowDays > 0 ? ymdShift(todayStr, -windowDays) : null;@@ -1718,7 +1785,8 @@ export async function getPowersProgress() {*/async function getCognitiveLevelStats(type, windowDays = COGNITIVE_MASTERY_DEFAULTS.windowDays) {const atDate = new Date();- const sessions = await getPostSessions();+ const [scoredSessions, training] = await Promise.all([getPostSessions(), getAllTrainingEntries()]);+ const sessions = skillEvidenceSessions(scoredSessions, training);// Window off the user's local today (DST-safe) so the cutoff stays consistent// with the tz-correct session dates submitPostSession now stamps (issue #2681).const timezone = await getUserTimezone();diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.jsindex fdcc659130..608c107e47 100644--- a/server/services/meatspacePostMemory.js+++ b/server/services/meatspacePostMemory.js@@ -19,10 +19,10 @@ import {mergeScheduleAdvance,scheduleOrDefault,} from '../lib/spacedRepetition.js';+import { listStoredTrainingEntries, saveStoredTrainingRun } from './postRunStore.js';const MEATSPACE_DIR = PATHS.meatspace;const MEMORY_ITEMS_FILE = join(MEATSPACE_DIR, 'post-memory-items.json');-const TRAINING_LOG_FILE = join(MEATSPACE_DIR, 'post-training-log.json');// =============================================================================// SPACED-REPETITION SCHEDULER (SM-2 inspired)@@ -386,15 +386,6 @@ async function saveMemoryItems(items) {await atomicWrite(MEMORY_ITEMS_FILE, { items });}-async function loadTrainingLog() {- return readJSONFile(TRAINING_LOG_FILE, { entries: [] }, { allowArray: false });-}--async function saveTrainingLog(log) {- await ensureDir(MEATSPACE_DIR);- await atomicWrite(TRAINING_LOG_FILE, log);-}-// =============================================================================// MEMORY ITEMS CRUD// =============================================================================@@ -626,9 +617,11 @@ export async function submitPractice(id, practiceData) {await saveMemoryItems(items);// Log the practice session- const log = await loadTrainingLog();- log.entries.push({- id: randomUUID(),+ const practiceId = randomUUID();+ const runId = `memory-practice:${practiceId}`;+ const record = {+ id: practiceId,+ runId,memoryItemId: id,mode,chunkId: chunkId || null,@@ -637,11 +630,35 @@ export async function submitPractice(id, practiceData) {totalMs: totalMs || 0,date: todayLocal,timestamp: now,+ inputMode: 'unknown',+ scorerProvenance: 'memory-practice',+ };+ await saveStoredTrainingRun({+ id: runId,+ mode: 'training',+ localDay: todayLocal,+ startedAt: now,+ completedAt: now,+ status: 'completed',+ planned: { modules: ['memory'] },+ data: { id: runId, mode: 'training' },+ attempts: [{+ id: practiceId,+ module: 'memory',+ drillType: mode || 'unknown',+ correct: results.length > 0 ? correctCount === results.length : null,+ score: results.length > 0 ? (correctCount / results.length) * 100 : null,+ latencyMs: totalMs || 0,+ completion: results.length > 0 ? 1 : null,+ hintUsed: results.some((result) => result?.hintUsed === true),+ inputMode: 'unknown',+ scorerProvenance: 'memory-practice',+ data: record,+ }],});- await saveTrainingLog(log);console.log(`🧠 Practice logged: "${item.title}" mode=${mode} ${correctCount}/${results.length} → next review in ${item.schedule.intervalDays}d`);- return { mastery: item.mastery, schedule: item.schedule, practiceId: log.entries[log.entries.length - 1].id };+ return { mastery: item.mastery, schedule: item.schedule, practiceId };}/**@@ -823,8 +840,7 @@ export async function getMastery(id) {}export async function getTrainingLog(memoryItemId, limit = 50) {- const log = await loadTrainingLog();- let entries = log.entries || [];+ let entries = await listStoredTrainingEntries();if (memoryItemId) entries = entries.filter(e => e.memoryItemId === memoryItemId);return entries.slice(-limit);}diff --git a/server/services/meatspacePostProgress.test.js b/server/services/meatspacePostProgress.test.jsindex 5cf5cb8ae2..d7a209da91 100644--- a/server/services/meatspacePostProgress.test.js+++ b/server/services/meatspacePostProgress.test.js@@ -133,6 +133,44 @@ describe('getPostProgress bucketing', () => {expect(p.series.byDrill['multiplication'][0].date).toBe(d);});+ it('uses training as skill evidence without contaminating scored history (#4441)', async () => {+ const d = todayStr();+ state.training = [{+ id: 'attempt-1', runId: 'run-1', date: d, timestamp: `${d}T12:00:00.000Z`,+ module: 'mental-math', drillType: 'multiplication', difficulty: { level: 0 },+ questionCount: 2, correctCount: 1, score: 50, completion: 1, totalMs: 4000,+ questions: [q(true), q(false)],+ }];++ const [progress, stats] = await Promise.all([+ getPostProgress({ days: 30 }),+ getPostStats(30),+ ]);+ expect(progress.series.byDomain['mental-math'][0]).toMatchObject({ date: d, score: 50, accuracy: 0.5 });+ expect(progress.series.byDrill.multiplication[0]).toMatchObject({ date: d, score: 50, accuracy: 0.5 });+ expect(progress.series.byDay[0]).toMatchObject({ date: d, score: null, sessions: 0 });+ expect(stats).toMatchObject({+ sessionCount: 0,+ overall: null,+ evidenceByDrillCount: { 'mental-math:multiplication': 1 },+ evidenceByDrillAccuracy: { 'mental-math:multiplication': 0.5 },+ });+ });++ it('preserves irreconstructible legacy training scores as unknown', async () => {+ const d = todayStr();+ state.training = [{+ id: 'legacy-attempt', runId: 'legacy-run', date: d, timestamp: `${d}T12:00:00.000Z`,+ module: 'mental-math', drillType: 'multiplication', legacy: true,+ inputMode: 'unknown', scorerProvenance: 'legacy', totalMs: 1000,+ }];++ const progress = await getPostProgress({ days: 30 });+ expect(progress.series.byDomain['mental-math'][0]).toMatchObject({+ date: d, score: null, accuracy: null,+ });+ });+it('includes a mastery block with the multiplication ladder and memory items', async () => {state.memoryItems = [{ id: 'm1', title: 'Elements', mastery: { overallPct: 42 }, schedule: { nextReview: '2000-01-01T00:00:00.000Z' } },diff --git a/server/services/meatspacePostTraining.js b/server/services/meatspacePostTraining.jsindex ec5fa05c94..79fa89791d 100644--- a/server/services/meatspacePostTraining.js+++ b/server/services/meatspacePostTraining.js@@ -9,46 +9,130 @@ import { randomUUID } from 'crypto';import { getUserTimezone, todayInTimezone, userLocalToday } from '../lib/timezone.js';import { recordDayKey, ymdShift } from '../lib/postStreak.js';import { getUnifiedActivityStreak } from './postActivityStreak.js';-import { loadTrainingLog, saveTrainingLog, getAllTrainingEntries } from './postTrainingLogStore.js';+import { getAllTrainingEntries } from './postTrainingLogStore.js';+import { saveStoredTrainingRun } from './postRunStore.js';export { getAllTrainingEntries };-/**- * Submit a training practice entry after a training-mode drill completes.- */-export async function submitTrainingEntry(entry) {- const data = await loadTrainingLog();+function trainingAttempt(runId, attempt, position, localDay, startedAt) {+ const questionCount = attempt.questionCount ?? attempt.questions?.length ?? 0;+ const correctCount = attempt.correctCount+ ?? attempt.questions?.filter((question) => question?.correct === true).length+ ?? 0;+ const score = attempt.score !== undefined+ ? attempt.score+ : (questionCount > 0 ? (correctCount / questionCount) * 100 : null);+ const id = attempt.id || `${runId}:attempt:${position}`;+ const record = {+ id,+ runId,+ date: localDay,+ timestamp: startedAt,+ module: attempt.module,+ drillType: attempt.drillType,+ ...(attempt.memoryItemId ? { memoryItemId: attempt.memoryItemId } : {}),+ questionCount,+ correctCount,+ totalMs: attempt.latencyMs ?? attempt.totalMs ?? 0,+ ...(Array.isArray(attempt.questions) ? { questions: attempt.questions } : {}),+ difficulty: attempt.difficulty !== undefined ? attempt.difficulty : (attempt.config ?? null),+ configVersion: attempt.configVersion || null,+ correct: attempt.correct !== undefined ? attempt.correct : (questionCount > 0 ? correctCount === questionCount : null),+ score,+ completion: attempt.completion !== undefined ? attempt.completion : (questionCount > 0 ? 1 : null),+ hintUsed: attempt.hintUsed === true,+ confidence: attempt.confidence ?? null,+ inputMode: attempt.inputMode || 'unknown',+ scorerProvenance: attempt.scorerProvenance || 'post-client',+ };+ return {+ id,+ module: record.module,+ drillType: record.drillType,+ difficulty: record.difficulty,+ configVersion: record.configVersion,+ correct: record.correct,+ score: record.score,+ latencyMs: record.totalMs,+ completion: record.completion,+ hintUsed: record.hintUsed,+ confidence: record.confidence,+ inputMode: record.inputMode,+ scorerProvenance: record.scorerProvenance,+ data: record,+ };+}++/** Atomically save a complete training run. Stable ids make retries idempotent. */+export async function submitTrainingRun(input) {const nowDate = new Date();const now = nowDate.toISOString();- // Stamp the entry's day in the user's local timezone (issue #2681). Training- // entries feed the SHARED unified streak (getUnifiedActivityStreak in- // postActivityStreak.js), which now compares against the user's local- // `today` — a bare UTC-day stamp here would- // date a local-evening practice on tomorrow's UTC day and drop it from today's- // streak. Derive the day from the SAME `nowDate` used for `timestamp` so a- // midnight boundary can't split them onto different days.- const todayLocal = await userLocalToday(nowDate);-- const record = {- id: randomUUID(),- date: todayLocal,- timestamp: now,- module: entry.module,- drillType: entry.drillType,- questionCount: entry.questionCount ?? 0,- correctCount: entry.correctCount ?? 0,- totalMs: entry.totalMs ?? 0,+ const startedAt = input.startedAt || now;+ const completedAt = input.completedAt || now;+ const localDay = await userLocalToday(new Date(startedAt));+ const run = {+ id: input.id,+ mode: 'training',+ localDay,+ startedAt,+ completedAt,+ status: 'completed',+ planned: input.planned || {+ modules: [...new Set(input.attempts.map((attempt) => attempt.module))],+ drillTypes: input.attempts.map((attempt) => attempt.drillType),+ },+ data: { id: input.id, mode: 'training', localDay, startedAt, completedAt },+ attempts: input.attempts.map((attempt, position) => trainingAttempt(input.id, attempt, position, localDay, startedAt)),};- // Per-question breakdown (issue #2114) is optional — only wordplay training- // currently supplies it. Gate on Array.isArray (not truthiness/length) so an- // absent field stays absent rather than being coerced to `[]`, keeping- // legacy/no-breakdown entries indistinguishable from before this change.- if (Array.isArray(entry.questions)) {- record.questions = entry.questions;+ const saved = await saveStoredTrainingRun(run);+ // Training is skill evidence, so a newly-saved run also reconciles the same+ // mastered-skill retention schedule as a scored session. Keep this AFTER the+ // atomic run transaction and gate it to first insert: a dropped-response retry+ // must not advance/reset retention twice. As with scored-session bookkeeping,+ // a secondary schedule failure cannot turn a durable save into a false 500.+ if (saved.isNew) {+ try {+ const { syncReviewScheduleForSession } = await import('./meatspacePost.js');+ await syncReviewScheduleForSession({+ tasks: saved.run.attempts.map((attempt) => ({+ ...(attempt.data || {}),+ module: attempt.module,+ type: attempt.drillType,+ config: attempt.difficulty || {},+ questions: attempt.data?.questions || [],+ score: attempt.score,+ accuracy: attempt.data?.questionCount > 0+ ? attempt.data.correctCount / attempt.data.questionCount+ : null,+ completion: attempt.completion,+ })),+ }, new Date(saved.run.completedAt || now));+ } catch (err) {+ console.error(`❌ POST training retention sync failed (run ${run.id} still saved): ${err.message}`);+ }}+ console.log(`🏋️ Training run ${saved.isNew ? 'saved' : 'updated'}: ${run.attempts.length} attempt(s)`);+ return {+ id: saved.run.id,+ mode: 'training',+ localDay: saved.run.localDay,+ startedAt: saved.run.startedAt,+ completedAt: saved.run.completedAt,+ attemptCount: saved.run.attempts.length,+ attempts: saved.run.attempts.map((attempt) => attempt.data),+ };+}- data.entries.push(record);- await saveTrainingLog(data);+/**+ * Submit a training practice entry after a training-mode drill completes.+ */+export async function submitTrainingEntry(entry) {+ const runId = entry.runId || (entry.id ? `training-entry:${entry.id}` : randomUUID());+ const result = await submitTrainingRun({+ id: runId,+ attempts: [{ ...entry, id: entry.id || randomUUID(), latencyMs: entry.totalMs }],+ });+ const record = result.attempts[0];console.log(`🏋️ Training logged: ${record.module}/${record.drillType} ${record.correctCount}/${record.questionCount}`);return record;}@@ -64,8 +148,7 @@ export async function submitTrainingEntry(entry) {*/export async function getTrainingStats(days = 30) {const atDate = new Date();- const data = await loadTrainingLog();- const allEntries = data.entries;+ const allEntries = await getAllTrainingEntries();const timezone = await getUserTimezone();const todayStr = todayInTimezone(timezone, atDate);diff --git a/server/services/meatspacePostTraining.test.js b/server/services/meatspacePostTraining.test.jsindex dbbb6ce495..989475892d 100644--- a/server/services/meatspacePostTraining.test.js+++ b/server/services/meatspacePostTraining.test.js@@ -23,6 +23,7 @@ vi.mock('../services/settings.js', () => ({import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';import {submitTrainingEntry,+ submitTrainingRun,getTrainingStats,getTrainingEntries,} from './meatspacePostTraining.js';@@ -52,7 +53,7 @@ describe('submitTrainingEntry', () => {expect(entry.id).toBeTruthy();expect(entry.date).toMatch(/^\d{4}-\d{2}-\d{2}$/);expect(entry.timestamp).toBeTruthy();- expect(atomicWrite).toHaveBeenCalledOnce();+ expect(atomicWrite.mock.calls.filter(([path]) => String(path).includes('post-training-log'))).toHaveLength(1);});it('persists a per-question breakdown when supplied (issue #2114)', async () => {@@ -105,6 +106,53 @@ describe('submitTrainingEntry', () => {expect(savedData.entries[0].id).toBe('old');expect(savedData.entries[1].module).toBe('llm-drills');});++ it('uses a supplied entry id as a stable compatibility-run retry key', async () => {+ let stored = { entries: [] };+ readJSONFile.mockImplementation(async () => stored);+ atomicWrite.mockImplementation(async (path, value) => {+ if (String(path).includes('post-training-log')) stored = value;+ });+ const entry = {+ id: 'stable-entry', module: 'mental-math', drillType: 'multiplication',+ questionCount: 2, correctCount: 2, totalMs: 1000,+ };++ await submitTrainingEntry(entry);+ await submitTrainingEntry(entry);++ expect(stored.entries).toHaveLength(1);+ expect(stored.entries[0]).toMatchObject({ id: 'stable-entry', runId: 'training-entry:stable-entry' });+ });+});++describe('submitTrainingRun (#4441)', () => {+ it('writes the full run once and replaces the same stable attempt ids on retry', async () => {+ let stored = { entries: [] };+ readJSONFile.mockImplementation(async () => stored);+ atomicWrite.mockImplementation(async (path, value) => {+ if (String(path).includes('post-training-log')) stored = value;+ });+ const payload = {+ id: '11111111-1111-4111-8111-111111111111',+ attempts: [+ { id: 'a-1', module: 'mental-math', drillType: 'multiplication', questionCount: 2, correctCount: 2, latencyMs: 1000 },+ { id: 'a-2', module: 'cognitive', drillType: 'stroop', questionCount: 2, correctCount: 1, latencyMs: 1500 },+ { id: 'a-3', module: 'memory', drillType: 'memory-fill-blank', memoryItemId: 'memory-1', questionCount: 1, correctCount: 1, latencyMs: 900 },+ ],+ };++ await submitTrainingRun(payload);+ const firstTimestamps = stored.entries.map((entry) => entry.timestamp);+ await submitTrainingRun(payload);++ expect(atomicWrite.mock.calls.filter(([path]) => String(path).includes('post-training-log'))).toHaveLength(2);+ expect(stored.entries).toHaveLength(3);+ expect(stored.entries.map((entry) => entry.id)).toEqual(['a-1', 'a-2', 'a-3']);+ expect(stored.entries.map((entry) => entry.runId)).toEqual([payload.id, payload.id, payload.id]);+ expect(stored.entries[2].memoryItemId).toBe('memory-1');+ expect(stored.entries.map((entry) => entry.timestamp)).toEqual(firstTimestamps);+ });});describe('getTrainingStats', () => {diff --git a/server/services/postRunDb.db.test.js b/server/services/postRunDb.db.test.jsnew file mode 100644index 0000000000..3269b8ed54--- /dev/null+++ b/server/services/postRunDb.db.test.js@@ -0,0 +1,81 @@+/** PostgreSQL atomicity/idempotency coverage for normalized POST runs (#4441). */+import { afterAll, describe, expect, it } from 'vitest';+import { checkHealth, close, ensureSchema, query, withTransaction } from '../lib/db.js';+import { saveNormalizedRun } from './postRunDb.js';++let dbReady = false;+let skipReason = '';+{+ const health = await checkHealth().catch((error) => ({ connected: false, error: error?.message }));+ if (!health.connected) skipReason = `Postgres not reachable (${health.error || 'no connection'})`;+ else {+ await ensureSchema().catch(() => {});+ const probe = await query(`SELECT to_regclass('public.post_runs') IS NOT NULL AS ok`).catch(() => ({ rows: [] }));+ dbReady = probe.rows[0]?.ok === true;+ if (!dbReady) skipReason = 'post_runs schema unavailable';+ }+}+if (!dbReady) console.log(`⏭️ postRunDb.db.test: skipping suite — ${skipReason}`);++const nonce = `post-test-${Date.now()}`;+const runIds = [`${nonce}-one`, `${nonce}-owner`, `${nonce}-rollback`, `${nonce}-concurrent`];+const db = { query, withTransaction };++function makeRun(id, attempts) {+ return {+ id, mode: 'training', localDay: '2026-08-17',+ startedAt: '2026-08-17T10:00:00.000Z', completedAt: '2026-08-17T10:05:00.000Z',+ status: 'completed', planned: {}, data: { id }, attempts,+ };+}++const attempt = (id, score = 80) => ({+ id, module: 'mental-math', drillType: 'multiplication', score,+ latencyMs: 1000, completion: 1, data: { id, score },+});++afterAll(async () => {+ if (dbReady) {+ await query(`DELETE FROM post_runs WHERE id = ANY($1::text[])`, [runIds]).catch(() => {});+ await close();+ }+});++describe.skipIf(!dbReady)('postRunDb transaction (#4441)', () => {+ it('upserts one run and its complete attempt set idempotently', async () => {+ await saveNormalizedRun(db, makeRun(runIds[0], [attempt(`${nonce}-a1`), attempt(`${nonce}-a2`)]));+ await saveNormalizedRun(db, makeRun(runIds[0], [attempt(`${nonce}-a2`), attempt(`${nonce}-a1`, 95)]));+ const result = await query(+ `SELECT count(*)::int AS count, max(score) AS max_score FROM post_attempts WHERE run_id = $1`,+ [runIds[0]],+ );+ expect(result.rows[0].count).toBe(2);+ expect(Number(result.rows[0].max_score)).toBe(95);+ });++ it('rolls back the run and earlier attempts when a later id collides', async () => {+ const sharedId = `${nonce}-shared`;+ await saveNormalizedRun(db, makeRun(runIds[1], [attempt(sharedId)]));+ await expect(saveNormalizedRun(db, makeRun(runIds[2], [+ attempt(`${nonce}-would-be-partial`), attempt(sharedId),+ ]))).rejects.toThrow(/another run/);+ const result = await query(+ `SELECT+ EXISTS(SELECT 1 FROM post_runs WHERE id = $1) AS run_exists,+ EXISTS(SELECT 1 FROM post_attempts WHERE id = $2) AS partial_exists`,+ [runIds[2], `${nonce}-would-be-partial`],+ );+ expect(result.rows[0]).toEqual({ run_exists: false, partial_exists: false });+ });++ it('serializes simultaneous first saves so only one is reported as new', async () => {+ const run = makeRun(runIds[3], [attempt(`${nonce}-concurrent-attempt`)]);+ const results = await Promise.all([+ saveNormalizedRun(db, run),+ saveNormalizedRun(db, run),+ ]);+ expect(results.map((result) => result.isNew).sort()).toEqual([false, true]);+ const stored = await query(`SELECT count(*)::int AS count FROM post_runs WHERE id = $1`, [runIds[3]]);+ expect(stored.rows[0].count).toBe(1);+ });+});diff --git a/server/services/postRunDb.js b/server/services/postRunDb.jsnew file mode 100644index 0000000000..9bfa88c390--- /dev/null+++ b/server/services/postRunDb.js@@ -0,0 +1,160 @@+/**+ * PostgreSQL leaf I/O for normalized MeatSpace POST runs (#4441).+ *+ * Every run save replaces that run's attempt set in one transaction. Stable+ * run/attempt ids therefore make retries idempotent, while a failure anywhere+ * rolls the complete save back instead of leaving a partial training session.+ */++const asIso = (value) => value instanceof Date ? value.toISOString() : value;+const asDay = (value) => value instanceof Date ? value.toISOString().slice(0, 10) : String(value || '').slice(0, 10);++function withPersistedTimes(run, existing) {+ const localDay = existing?.local_day ? asDay(existing.local_day) : run.localDay;+ const startedAt = existing?.started_at ? asIso(existing.started_at) : run.startedAt;+ const data = { ...(run.data || {}) };+ if (run.mode === 'test' || run.mode === 'benchmark') {+ data.date = localDay;+ data.startedAt = startedAt;+ } else {+ data.localDay = localDay;+ data.startedAt = startedAt;+ }+ return { ...run, localDay, startedAt, data };+}++/** Save one normalized run using an already-open transaction client. */+export async function saveNormalizedRunWithClient(client, input) {+ const attemptIds = new Set();+ for (const attempt of input.attempts || []) {+ if (attemptIds.has(attempt.id)) throw new Error(`Duplicate POST attempt id: ${attempt.id}`);+ attemptIds.add(attempt.id);+ }++ // A row lock cannot protect the first insert because no row exists yet.+ // Serialize transactions for the same client run id so concurrent retries+ // agree which one is the creation (retention side effects run only once).+ await client.query(`SELECT pg_advisory_xact_lock(hashtext($1))`, [input.id]);+ const existingResult = await client.query(+ `SELECT mode, local_day, started_at FROM post_runs WHERE id = $1 FOR UPDATE`,+ [input.id],+ );+ const existing = existingResult.rows[0] || null;+ if (existing && existing.mode !== input.mode) {+ throw new Error(`POST run ${input.id} already exists in mode ${existing.mode}`);+ }+ const run = withPersistedTimes(input, existing);++ await client.query(+ `INSERT INTO post_runs+ (id, mode, local_day, started_at, completed_at, status, planned, data, legacy)+ VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8::jsonb, $9)+ ON CONFLICT (id) DO UPDATE SET+ completed_at = EXCLUDED.completed_at,+ status = EXCLUDED.status,+ planned = EXCLUDED.planned,+ data = EXCLUDED.data,+ legacy = post_runs.legacy OR EXCLUDED.legacy,+ updated_at = NOW()`,+ [+ run.id, run.mode, run.localDay, run.startedAt, run.completedAt || null,+ run.status || 'completed', JSON.stringify(run.planned || {}),+ JSON.stringify(run.data || {}), run.legacy === true,+ ],+ );++ const attempts = run.attempts || [];+ if (attempts.length) {+ const collisions = await client.query(+ `SELECT id, run_id FROM post_attempts WHERE id = ANY($1::text[]) FOR UPDATE`,+ [attempts.map((attempt) => attempt.id)],+ );+ const foreign = collisions.rows.find((row) => row.run_id !== run.id);+ if (foreign) throw new Error(`POST attempt ${foreign.id} already belongs to another run`);+ // Move existing positions out of the unique (run_id, position) range before+ // the upserts. This lets a corrected retry reorder or shrink the attempt set+ // without transient uniqueness conflicts; the transaction hides the move.+ await client.query(+ `UPDATE post_attempts SET position = position + 1000000 WHERE run_id = $1`,+ [run.id],+ );+ }+ for (let position = 0; position < attempts.length; position += 1) {+ const attempt = attempts[position];+ await client.query(+ `INSERT INTO post_attempts+ (id, run_id, position, module, drill_type, difficulty, config_version,+ correct, score, latency_ms, completion, hint_used, confidence,+ input_mode, scorer_provenance, data, legacy)+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8, $9, $10, $11, $12,+ $13, $14, $15, $16::jsonb, $17)+ ON CONFLICT (id) DO UPDATE SET+ position = EXCLUDED.position,+ module = EXCLUDED.module,+ drill_type = EXCLUDED.drill_type,+ difficulty = EXCLUDED.difficulty,+ config_version = EXCLUDED.config_version,+ correct = EXCLUDED.correct,+ score = EXCLUDED.score,+ latency_ms = EXCLUDED.latency_ms,+ completion = EXCLUDED.completion,+ hint_used = EXCLUDED.hint_used,+ confidence = EXCLUDED.confidence,+ input_mode = EXCLUDED.input_mode,+ scorer_provenance = EXCLUDED.scorer_provenance,+ data = EXCLUDED.data,+ legacy = post_attempts.legacy OR EXCLUDED.legacy,+ updated_at = NOW()`,+ [+ attempt.id, run.id, position, attempt.module, attempt.drillType,+ attempt.difficulty == null ? null : JSON.stringify(attempt.difficulty),+ attempt.configVersion || null, attempt.correct ?? null, attempt.score ?? null,+ attempt.latencyMs || 0, attempt.completion ?? null, attempt.hintUsed === true,+ attempt.confidence ?? null, attempt.inputMode || 'unknown',+ attempt.scorerProvenance || 'unknown', JSON.stringify(attempt.data || {}),+ attempt.legacy === true,+ ],+ );+ }++ if (attempts.length) {+ await client.query(+ `DELETE FROM post_attempts WHERE run_id = $1 AND NOT (id = ANY($2::text[]))`,+ [run.id, attempts.map((attempt) => attempt.id)],+ );+ } else {+ await client.query(`DELETE FROM post_attempts WHERE run_id = $1`, [run.id]);+ }++ return { run, isNew: !existing };+}++export function saveNormalizedRun(db, run) {+ return db.withTransaction((client) => saveNormalizedRunWithClient(client, run));+}++export async function listScoredSessions(db, { strict: _strict = false } = {}) {+ const result = await db.query(+ `SELECT data FROM post_runs WHERE mode = 'test' ORDER BY started_at, id`,+ );+ return result.rows.map((row) => row.data);+}++export async function getScoredSession(db, id) {+ const result = await db.query(+ `SELECT data FROM post_runs WHERE id = $1 AND mode = 'test'`,+ [id],+ );+ return result.rows[0]?.data || null;+}++export async function listTrainingEntries(db, { strict: _strict = false } = {}) {+ const result = await db.query(+ `SELECT a.data+ FROM post_attempts a+ JOIN post_runs r ON r.id = a.run_id+ WHERE r.mode = 'training'+ ORDER BY r.started_at, r.id, a.position, a.id`,+ );+ return result.rows.map((row) => row.data);+}diff --git a/server/services/postRunStore.js b/server/services/postRunStore.jsnew file mode 100644index 0000000000..8af0086723--- /dev/null+++ b/server/services/postRunStore.js@@ -0,0 +1,185 @@+/**+ * Normalized POST run store dispatcher (#4441).+ * PostgreSQL is authoritative in normal installs; the legacy JSON layout stays+ * as the development/test escape hatch so existing focused suites need no DB.+ */++import { join } from 'path';+import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';+import { isPlainObject } from '../lib/objects.js';+import { createPgFileFacade, resolvePgBackend } from '../lib/pgFileFacade.js';+import { isTestRunner } from '../lib/db.js';+import {+ getScoredSession as getScoredSessionDb,+ listScoredSessions as listScoredSessionsDb,+ listTrainingEntries as listTrainingEntriesDb,+ saveNormalizedRun,+} from './postRunDb.js';++const MEATSPACE_DIR = PATHS.meatspace;+const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');+const TRAINING_FILE = join(MEATSPACE_DIR, 'post-training-log.json');++async function loadFileSessions({ strict = false } = {}) {+ const raw = await readJSONFile(SESSIONS_FILE, { sessions: [] }, { allowArray: false, strict });+ if (strict && (!isPlainObject(raw) || !Array.isArray(raw.sessions))) {+ throw new Error(`POST sessions malformed: ${SESSIONS_FILE}`);+ }+ return Array.isArray(raw?.sessions) ? raw.sessions : [];+}++async function loadFileTraining({ strict = false } = {}) {+ const raw = await readJSONFile(TRAINING_FILE, { entries: [] }, { allowArray: false, strict });+ if (strict && !Array.isArray(raw?.entries)) {+ throw new Error(`POST training log malformed: ${TRAINING_FILE}`);+ }+ return Array.isArray(raw?.entries) ? raw.entries : [];+}++function makeFileBackend() {+ return {+ name: 'file',+ listScoredSessions: loadFileSessions,+ getScoredSession: async (id) => (await loadFileSessions()).find((session) => session.id === id) || null,+ saveScoredSession: async (session) => {+ const sessions = await loadFileSessions();+ const index = sessions.findIndex((item) => item.id === session.id);+ const existing = index >= 0 ? sessions[index] : null;+ const persisted = {+ ...session,+ date: existing?.date ?? session.date,+ startedAt: existing?.startedAt ?? session.startedAt,+ };+ if (index >= 0) sessions[index] = persisted;+ else sessions.push(persisted);+ sessions.sort((a, b) => (a.date || '').localeCompare(b.date || ''));+ await ensureDir(MEATSPACE_DIR);+ await atomicWrite(SESSIONS_FILE, { sessions });+ return { session: persisted, isNew: index < 0 };+ },+ listTrainingEntries: loadFileTraining,+ saveTrainingRun: async (run) => {+ const entries = await loadFileTraining();+ const prior = new Map(entries.filter((entry) => entry.runId === run.id).map((entry) => [entry.id, entry]));+ const incomingIds = new Set(run.attempts.map((attempt) => attempt.id));+ const foreign = entries.find((entry) => entry.runId !== run.id && incomingIds.has(entry.id));+ if (foreign) throw new Error(`POST attempt ${foreign.id} already belongs to another run`);+ const firstPrior = prior.values().next().value;+ const persistedRun = prior.size+ ? {+ ...run,+ localDay: firstPrior.date || run.localDay,+ startedAt: firstPrior.timestamp || run.startedAt,+ }+ : run;+ const next = entries.filter((entry) => entry.runId !== run.id);+ for (const attempt of persistedRun.attempts) {+ const old = prior.get(attempt.id);+ next.push({+ ...(attempt.data || {}),+ id: attempt.id,+ runId: persistedRun.id,+ date: old?.date ?? persistedRun.localDay,+ timestamp: old?.timestamp ?? persistedRun.startedAt,+ });+ }+ await ensureDir(MEATSPACE_DIR);+ await atomicWrite(TRAINING_FILE, { entries: next });+ return { run: persistedRun, isNew: prior.size === 0 };+ },+ };+}++function makePgBackend(db) {+ return {+ name: 'postgres',+ listScoredSessions: (options) => listScoredSessionsDb(db, options),+ getScoredSession: (id) => getScoredSessionDb(db, id),+ saveScoredSession: async (session) => {+ const result = await saveNormalizedRun(db, scoredSessionRun(session));+ return { session: result.run.data, isNew: result.isNew };+ },+ listTrainingEntries: (options) => listTrainingEntriesDb(db, options),+ saveTrainingRun: (run) => saveNormalizedRun(db, run),+ };+}++const pgBackend = () => resolvePgBackend({+ requirement: 'MeatSpace POST history requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file)',+ migrate: async () => {+ const { migratePostRunsToDB } = await import('../scripts/migratePostRunsToDB.js');+ await migratePostRunsToDB();+ },+ loadDb: () => import('../lib/db.js'),+ makePg: makePgBackend,+});++const facade = createPgFileFacade({+ // Vitest's VITEST marker is the resilient test signal when a wrapper drops+ // NODE_ENV; never let a focused suite fall through to the live Postgres DB.+ isFile: () => process.env.MEMORY_BACKEND === 'file' || isTestRunner(),+ makeFile: makeFileBackend,+ makePg: pgBackend,+});+const backend = facade.getBackend;++function scoredTaskAttempt(sessionId, task, position) {+ const questions = Array.isArray(task.questions) ? task.questions : [];+ const answered = questions.filter((question) => question?.answered != null);+ return {+ id: task.id || `${sessionId}:attempt:${position}`,+ module: task.module,+ drillType: task.type,+ difficulty: task.config || null,+ configVersion: task.configVersion || null,+ correct: answered.length ? answered.every((question) => question.correct === true) : null,+ score: task.score ?? null,+ latencyMs: task.totalMs || 0,+ completion: task.completion ?? (questions.length ? answered.length / questions.length : null),+ hintUsed: questions.some((question) => question?.hintUsed === true),+ confidence: task.confidence ?? null,+ inputMode: task.inputMode || 'unknown',+ scorerProvenance: task.scorerProvenance || 'post-server',+ data: task,+ legacy: task.legacy === true,+ };+}++export function scoredSessionRun(session) {+ return {+ id: session.id,+ mode: 'test',+ localDay: session.date,+ startedAt: session.startedAt,+ completedAt: session.completedAt,+ status: 'completed',+ planned: { cadence: session.cadence, modules: session.modules },+ data: session,+ legacy: session.legacy === true,+ attempts: (session.tasks || []).map((task, position) => scoredTaskAttempt(session.id, task, position)),+ };+}++export async function listPostSessions(options) {+ return (await backend()).listScoredSessions(options);+}++export async function getStoredPostSession(id) {+ return (await backend()).getScoredSession(id);+}++export async function saveStoredPostSession(session) {+ return (await backend()).saveScoredSession(session);+}++export async function listStoredTrainingEntries(options) {+ return (await backend()).listTrainingEntries(options);+}++export async function saveStoredTrainingRun(run) {+ return (await backend()).saveTrainingRun(run);+}++export function _resetPostRunBackend() {+ facade.reset();+}diff --git a/server/services/postTrainingLogStore.js b/server/services/postTrainingLogStore.jsindex 75f4e2b0f8..2d86dc724b 100644--- a/server/services/postTrainingLogStore.js+++ b/server/services/postTrainingLogStore.js@@ -1,8 +1,7 @@/**- * POST training-log storage primitives — read/write of- * data/meatspace/post-training-log.json.+ * POST training-entry read boundary.*- * Extracted out of meatspacePostTraining.js so the raw data access has no+ * Extracted out of meatspacePostTraining.js so the storage read has no* dependency on that module. meatspacePost.js (via postActivityStreak.js)* needs training-log entries for the unified-streak/progress aggregation;* importing them from meatspacePostTraining.js would create a static@@ -11,48 +10,25 @@* This module sits below both, with no imports of either.*/-import { join } from 'path';-import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';import { withDerivedDayKeys } from '../lib/postStreak.js';import { getUserTimezone } from '../lib/timezone.js';--const MEATSPACE_DIR = PATHS.meatspace;-const TRAINING_LOG_FILE = join(MEATSPACE_DIR, 'post-training-log.json');--/**- * @param {{ strict?: boolean }} [options] - `strict: true` throws when the training- * log is present-but-unreadable/corrupt rather than falling back to an empty log.- * See `loadSessions` in meatspacePost.js for the rationale (#2726).- */-export async function loadTrainingLog({ strict = false } = {}) {- const data = await readJSONFile(TRAINING_LOG_FILE, { entries: [] }, { allowArray: false, strict });- if (strict && !Array.isArray(data?.entries)) {- throw new Error(`POST training log malformed: ${TRAINING_LOG_FILE}`);- }- if (!Array.isArray(data.entries)) data.entries = [];- return data;-}--export async function saveTrainingLog(data) {- await ensureDir(MEATSPACE_DIR);- await atomicWrite(TRAINING_LOG_FILE, data);-}+import { listStoredTrainingEntries } from './postRunStore.js';/*** All training-log entries in chronological (append) order — the feed the* unified progress aggregation reads (both meatspacePostTraining and- * meatspacePostMemory practice write to the same `post-training-log.json`).+ * meatspacePostMemory practice write normalized training runs).** Each entry's `date` is RE-DERIVED from its `timestamp` in the user's CURRENT* timezone (issue #4168), so a `settings.timezone` change re-keys existing* practice history on read rather than leaving it frozen in the zone that was- * active when it was written. `loadTrainingLog` above stays raw — the write- * paths must round-trip the stored record untouched.+ * active when it was written. The normalized store keeps the authored day as a+ * cache; readers still derive from the attempt timestamp.*- * @param {{ strict?: boolean }} [options] - `strict: true` throws rather than- * reporting an unreadable log as zero entries (#2726).+ * @param {{ strict?: boolean }} [options] - file-backend compatibility option;+ * `strict: true` throws rather than reporting a corrupt legacy log as empty.*/export async function getAllTrainingEntries(options) {- const data = await loadTrainingLog(options);- return withDerivedDayKeys(data.entries, await getUserTimezone());+ const entries = await listStoredTrainingEntries(options);+ return withDerivedDayKeys(entries, await getUserTimezone());}diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex aa8105df4e..2e23efca0f 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -13,6 +13,7 @@ export const DB_TEST_INCLUDE = ['services/catalogDB.test.js','services/catalogDB.facets.db.test.js','services/humanActivity.db.test.js',+ 'services/postRunDb.db.test.js','services/memoryDB.db.test.js','services/privacySubjects.db.test.js','services/privacyVault.db.test.js',