Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

stop POST's daily routine looping on the drill you just finished

[._.]/ Adam Eivy2ddc7ddae7fd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 114d135918..60eebf20d6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -160,3 +160,5 @@
- **[issue-3485] Three.js model generation can now be narrowed to a subject family, so the model is judged against a checklist it did not write itself.** The assembly-coverage gate has always carried an honest limit: it proves a spec built everything it promised, never that it promised enough — a component nobody noticed is never inventoried, never specified, and passes every check clean. Picking one of five coarse families (character, vehicle, weapon, building, device) on the create form or the workspace splices a curated checklist into the generation prompt — the components a reconstruction of that family is usually judged on, the material zones worth separating, the axes to judge the result on, and the orbit views that expose the usual failures — and lets the coverage gate warn on a required component the spec never mentions anywhere. That warning feeds the unsteered refinement pass, so "you never accounted for the trigger guard" becomes something the next run is actually told. The checklist is deliberately framed as a floor rather than a ceiling, in the prompt and in the panel: it names the limitations escape hatch for a component the reference genuinely does not show, and it says outright that a spec inventorying only the checklist has under-observed its reference — a thin taxonomy that teaches the model to stop early would be worse than none. Family is optional and defaults to General, which splices nothing at all: an existing model, and anyone who does not pick a family, gets the byte-identical prompt that shipped before this. The workspace renders the chosen family's checklist under the coverage panel with each component marked accounted-for or not, so the orbit views worth checking are next to the preview you would check them in. The field is additive on the record, so no migration is needed and a model generated before this reads back as General. A family id this build does not ship — a record written by a build with a larger taxonomy, then downgraded or restored from a backup — degrades to no checklist everywhere rather than failing the record: the picker shows General instead of pinning itself to a value it has no option for, and the server coerces rather than rejecting the refine request, which would otherwise have left that model permanently un-refinable.
- **Canon entries can be removed from a universe's Cast, Places and Objects buckets.** Every other bucket on a universe page — the Other category variations, the Composite sheets — has always carried a trailing X to drop an entry you no longer want, but the three canon trunks had no way to remove anything at all: an entry pulled in by an over-eager prose extraction, added from the Catalog by mistake, or simply written out of the world was stuck in the universe forever. All five buckets now behave the same way, with the same X in the same place on the card. Removal is deliberately narrow and says so in the button's tooltip and the confirming toast: the entry leaves *this universe's canon list* and nothing else is touched. Its rendered reference images and character reference sheets stay in the gallery, where they remain previewable and re-attachable to another entry, and the shared Catalog ingredient an entry may be linked to is left alone — that row is a universe-independent record other universes and series can embed, so deleting canon must not delete it. Locked entries are removable, because the lock exists to stop AI refine/differentiate passes from rewriting an entry, not to stop the user from deciding it does not belong. The removal goes through its own endpoint that filters the array inside the universe's write queue rather than composing the surviving list on the client and PATCHing it back from a possibly-stale read — the existing PATCH path already shields rendered images and reference-sheet pointers against that race, but not a sibling entry's pinned primary image, its lock state, or a description a refine rewrote while you were clicking. The card disappears on click and is restored, whole and in place, if the write fails. Because a universe merges across machines as a whole record by last-write-wins, the removal propagates to your peers on the next sync without any tombstone, and neither the catalog projection nor the boot reconciler — both of which only ever read canon and write outward — can put the entry back.
+
+- **[issue-3563] "Continue Today's Routine" in POST no longer hands you the same drill over and over.** The routine always took the #1 recommendation, but the two signals that produce most recommendations — your weakest drill by recent accuracy, and a ladder you are partway up but not advancing — are windowed averages that a single rep barely moves. So the drill sitting at #1 before a run was still at #1 after it, and clicking Continue re-served the test just finished, indefinitely (Digit Span, in the report). Recommendations now know what you have already practiced today, from both scored sessions and the training log — Morse, Wordplay and Memory practice never post a scored session, so counting only sessions would have missed three of the surfaces that offer the Continue button. Anything already practiced today sinks below everything that has not been, which is enough for the routine to advance to the next thing on its own. Already-practiced items are demoted rather than dropped, so a day where you have done everything still shows what is up next instead of an empty panel, and each row in "Up next" now carries a Done today badge so the reordering reads as deliberate; they are still clickable, since practicing the same drill twice in a day is allowed — just not what the routine hands you. When nothing new is left, Continue ends the routine at the launcher and says so, rather than looping. A due memory item is matched by its item id and a ladder by its drill type, so switching off one practice mode cannot mark an unrelated one done, and the fallback "run a full self-test" is discharged only by an actual scored session.
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsx
index 9612e999fc..3461fc1c6f 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx
@@ -3,6 +3,7 @@ import { Link } from 'react-router';
import { Zap, History, Settings, Play, Brain, BookOpen, Dumbbell, Timer, Radio, Target, TrendingUp, TrendingDown, Minus, Compass, ArrowRight, ChevronRight, Layers } from 'lucide-react';
import { getPostReviewReps, getPostRecommendations, getMorseProgress, getPostProgress, getMemoryItems } from '../../../services/api';
import { FormField } from '../../ui/FormField';
+import Pill from '../../ui/Pill';
import { enabledApiProviderFilter } from '../../../utils/providers';
import useProviderModels from '../../../hooks/useProviderModels.js';
import { DOMAINS, DRILL_TO_DOMAIN, DRILL_LABELS, computeDomainAverages, computeGoalProgress, isTopicEnabled, selectMemoryItemForDrill, resolveTopicForDrillType } from './constants';
@@ -552,7 +553,14 @@ export default function PostSessionLauncher({
const topRec = recommendations[0] || null;
const topRecAction = recAction(topRec);
const primaryAction = topRecAction
- ? { ...topRecAction, label: `Start: ${topRec.title}`, detail: topRec.detail || null }
+ // Once everything in the rotation has been practiced today the top rec is
+ // one of those (they're demoted, not dropped) — say so on the CTA, matching
+ // the "Done today" badge the same rec carries in Up next (#3563).
+ ? {
+ ...topRecAction,
+ label: `Start: ${topRec.title}`,
+ detail: [topRec.detail, topRec.practicedToday ? 'Already done today' : null].filter(Boolean).join(' · ') || null,
+ }
: (hasSessionDrills
? { onClick: handleStart, label: `Start: ${mode === 'train' ? 'Full Training' : 'Full POST'}`, detail: null }
: null);
@@ -848,6 +856,10 @@ export default function PostSessionLauncher({
<div className="text-sm text-white truncate">{rec.title}</div>
{rec.detail && <div className="text-xs text-gray-500 truncate">{rec.detail}</div>}
</div>
+ {/* The server sinks these to the bottom, so the badge
+ explains the reorder. Still clickable — a second rep is
+ allowed, just not what the routine hands you (#3563). */}
+ {rec.practicedToday && <Pill tone="context" size="xs" className="shrink-0">Done today</Pill>}
<ArrowRight size={14} className="text-gray-600 group-hover:text-port-accent shrink-0" />
</>
);
diff --git a/client/src/components/meatspace/tabs/PostTab.continueRoutine.test.jsx b/client/src/components/meatspace/tabs/PostTab.continueRoutine.test.jsx
index 3d3868c289..06f0295caa 100644
--- a/client/src/components/meatspace/tabs/PostTab.continueRoutine.test.jsx
+++ b/client/src/components/meatspace/tabs/PostTab.continueRoutine.test.jsx
@@ -18,10 +18,13 @@ import PostTab from './PostTab';
const settle = () => act(async () => {});
-const { getPostRecommendations } = vi.hoisted(() => ({
+const { getPostRecommendations, toastSuccess } = vi.hoisted(() => ({
getPostRecommendations: vi.fn().mockResolvedValue({ recommendations: [] }),
+ toastSuccess: vi.fn(),
}));
+vi.mock('../../ui/Toast', () => ({ default: { success: toastSuccess, error: vi.fn() } }));
+
vi.mock('../../../services/api', () => ({
getPostConfig: () => Promise.resolve({}),
getPostRecommendations,
@@ -86,8 +89,8 @@ const renderAt = (path, props) => render(
</MemoryRouter>,
);
-const recommend = (deepLink) => getPostRecommendations.mockResolvedValueOnce({
- recommendations: [{ id: 'rec-1', kind: 'memory-due', title: 'Practice this again', deepLink, priority: 0 }],
+const recommend = (deepLink, extra = {}) => getPostRecommendations.mockResolvedValueOnce({
+ recommendations: [{ id: 'rec-1', kind: 'memory-due', title: 'Practice this again', deepLink, priority: 0, ...extra }],
});
// Drive one surface from "finish the drill" through "Continue".
@@ -103,6 +106,7 @@ describe('PostTab continueDailyRoutine', () => {
beforeEach(() => {
getPostRecommendations.mockReset();
getPostRecommendations.mockResolvedValue({ recommendations: [] });
+ toastSuccess.mockClear();
});
it('restarts the Morse drill in place, preserving the ?ref reference tab', async () => {
@@ -179,6 +183,32 @@ describe('PostTab continueDailyRoutine', () => {
expect(screen.getByTestId('loc').textContent).toBe('/post/launcher');
});
+ // Issue #3563 — the server sinks anything already practiced today to the
+ // bottom, so a top rec still flagged means the rotation is exhausted. Before
+ // this, the routine re-ran the drill just finished forever (a stalled/weakest
+ // digit-span signal barely moves on one rep, so it stayed rec #0).
+ it('ends the routine at the launcher when the top rec was already practiced today', async () => {
+ recommend('/post/morse/copy', { practicedToday: true });
+ renderAt('/post/morse/copy', { tab: 'morse', subtab: 'copy' });
+ await settle();
+
+ await finishAndContinue('Morse');
+
+ expect(screen.getByTestId('loc').textContent).toBe('/post/launcher');
+ expect(toastSuccess).toHaveBeenCalledWith(expect.stringMatching(/today's routine/i));
+ });
+
+ it('still restarts in place when the top rec has NOT been practiced today', async () => {
+ recommend('/post/morse/copy', { practicedToday: false });
+ renderAt('/post/morse/copy', { tab: 'morse', subtab: 'copy' });
+ await settle();
+
+ await finishAndContinue('Morse');
+
+ expect(screen.getByTestId('loc').textContent).toBe('/post/morse/copy?run=1');
+ expect(toastSuccess).not.toHaveBeenCalled();
+ });
+
it('routes a launcher recommendation through the autostart param, not a restart', async () => {
recommend('/post/launcher');
renderAt('/post/morse/copy', { tab: 'morse', subtab: 'copy' });
diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsx
index 4076c690c8..5716af49c4 100644
--- a/client/src/components/meatspace/tabs/PostTab.jsx
+++ b/client/src/components/meatspace/tabs/PostTab.jsx
@@ -3,6 +3,7 @@ import { useNavigate, useLocation } from 'react-router';
import { Loader } from 'lucide-react';
import { getPostConfig, getPostRecommendations, getPostSessions, getPostStats } from '../../../services/api';
import { usePostSession } from '../../../hooks/usePostSession';
+import toast from '../../ui/Toast';
import PostSessionLauncher from '../post/PostSessionLauncher';
import PostDrillRunner from '../post/PostDrillRunner';
import PostLlmDrillRunner from '../post/PostLlmDrillRunner';
@@ -108,7 +109,11 @@ export default function PostTab({ tab = 'launcher', subtab, mode }) {
async function continueDailyRoutine() {
const result = await getPostRecommendations(1).catch(() => null);
const recommendation = result?.recommendations?.[0];
- if (!recommendation) {
+ // The server sinks anything already practiced today to the bottom, so a top
+ // rec still flagged means nothing NEW is left in the rotation — end at the
+ // launcher rather than handing back the drill just finished (issue #3563).
+ if (!recommendation || recommendation.practicedToday) {
+ if (recommendation) toast.success("That's everything in today's routine — nice work");
navigate('/post/launcher');
return;
}
diff --git a/server/lib/README.md b/server/lib/README.md
index ea54e01ad6..b9c406c537 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -265,7 +265,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `postPowersLadder.js` | Pure technique-anchored Powers ladder — cumulative named-method pools, full supported-pair registry, and speed+accuracy mastery progression built on `postProgression.js`. |
| `postProgression.js` | Generic mastery-gated progression ladder (extracted from `postMultiplicationLadder.js`) — `createProgression({ levels, describeLevel, speedTargetForLevel? })` resolves a user's current rung from per-level stats with an anti-demotion floor. Also defines the cognitive-drill ladders (n-back / digit-span / schulte / mental-rotation / stroop) and their level→generator-config mapping. |
| `postTopics.js` | Pure POST practice-topic registry — `POST_TOPICS` (`{ id, label, module, surface, drillTypes }`) is the single source of truth for "what am I studying?", plus `resolveTopicForDrillType` / `isTopicEnabled` / `isMemoryItemEnabled`. Gates session composition and recommendations, including Memory's composed and dedicated practice routes plus standalone Morse. Mirrored to the client's post `constants.js` (parity test). |
-| `postStreak.js` | Pure DST-safe POST practice-streak math — the single `computePostStreaks` implementation shared by scored sessions and the training log, plus `computeUnifiedStreak` (a day is active with EITHER a session or a practice entry). |
+| `postStreak.js` | Pure DST-safe POST practice-streak math — the single `computePostStreaks` implementation shared by scored sessions and the training log, plus `computeUnifiedStreak` (a day is active with EITHER a session or a practice entry) and `normalizeYmd` (day-key prefix for a date that may be a full ISO timestamp). |
| `planIds.js` | Utilities for PLAN.md `[slug]` IDs. |
| `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. |
| `renderTargets.js` | Render-target alphabet (#3231): `RENDER_TARGET`/`RENDER_TARGETS` name every creative surface that enqueues renders (universe-bible, sprite-reference, music-video, …) — the keys into `settings.renderDefaults` — plus the `RENDER_TARGET_BACKEND_AUTO` fall-through sentinel. Dependency-free leaf; resolved per surface by `services/imageGen/cloudProviderConfig.js#resolveRenderTargetConfig`. |
diff --git a/server/lib/postStreak.js b/server/lib/postStreak.js
index 92a2470614..fd4f292070 100644
--- a/server/lib/postStreak.js
+++ b/server/lib/postStreak.js
@@ -13,7 +13,7 @@
// A date key is always the local `YYYY-MM-DD` prefix. Session dates are stored
// that way already; some training-log entries (memory practice) store a full
// ISO timestamp, so normalize both to the day prefix before any set math.
-function normalizeYmd(value) {
+export function normalizeYmd(value) {
if (!value) return null;
return String(value).split('T')[0];
}
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index aae1e582e4..19cbfc6df2 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -36,7 +36,7 @@ import { applySessionToReviewSchedule, getDueReviews, getRetentionReport } from
// meatspacePostTraining.js would close that into a 3-file circular import.
import { getAllTrainingEntries } from './postTrainingLogStore.js';
import { getMorseProgress, MAX_KOCH_LEVEL } from './meatspacePostMorse.js';
-import { computePostStreaks, computeUnifiedStreak, ymdToUTC, ymdShift } from '../lib/postStreak.js';
+import { computePostStreaks, computeUnifiedStreak, normalizeYmd, ymdToUTC, ymdShift } from '../lib/postStreak.js';
import { userLocalToday as localToday } from '../lib/timezone.js';
// Re-export the shared streak helper so existing importers of
@@ -1011,6 +1011,10 @@ export function stalledProgressions(mulProgress, powersProgress, cogProgress, mo
* 4. Stalled ladder progressions (N more reps to advance)
* When nothing is actionable (e.g. a fresh install with no history), a single
* sensible default ("run a full POST") is returned so the panel is never empty.
+ *
+ * `practicedToday` (from `practicedTodayFromActivity`) then demotes — never
+ * drops — anything already practiced today, and stamps each rec with the flag
+ * the daily routine reads to know it has run out of new work (issue #3563).
*/
// The built-in Elements Song has its own study surface (`/post/memory/elements`)
// rather than the generic per-item practice route.
@@ -1048,14 +1052,64 @@ export function memoryItemIdFromReview(review) {
return itemId || null;
}
+/**
+ * What the user has already practiced today, from BOTH scored POST sessions and
+ * the training log (Morse/Wordplay/Memory practice never post a scored session).
+ * Pure — exported for unit tests.
+ *
+ * "Continue Today's Routine" walks this recommendation list one item at a time,
+ * but every signal feeding it (weakest recent accuracy, stalled ladder) is a
+ * windowed average that a single rep barely moves — so without a
+ * what-have-I-already-done gate the same drill stays pinned at the top and the
+ * routine hands back the drill just finished, forever (issue #3563).
+ *
+ * @param {Array} sessions - all scored sessions (`{ date, tasks: [{ type }] }`)
+ * @param {Array} trainingEntries - all training-log entries
+ * @param {string|null} todayStr - the user's local `YYYY-MM-DD`
+ * @returns {{ drillTypes: Set<string>, memoryItemIds: Set<string>, completedSession: boolean }}
+ */
+export function practicedTodayFromActivity(sessions = [], trainingEntries = [], todayStr = null) {
+ const drillTypes = new Set();
+ const memoryItemIds = new Set();
+ let completedSession = false;
+ // No resolvable local day ⇒ report nothing practiced rather than guessing, so
+ // the routine degrades to its pre-#3563 ordering instead of silently demoting.
+ const today = normalizeYmd(todayStr);
+ if (!today) return { drillTypes, memoryItemIds, completedSession };
+
+ // Both feeds go through normalizeYmd: session dates are stored as the day
+ // prefix already, but some training-log entries (memory practice) carry a full
+ // ISO timestamp, and a raw `!==` would read those as not-practiced.
+ for (const session of sessions || []) {
+ if (normalizeYmd(session?.date) !== today) continue;
+ completedSession = true;
+ for (const task of session.tasks || []) {
+ if (task?.type) drillTypes.add(task.type);
+ }
+ }
+ for (const entry of trainingEntries || []) {
+ if (normalizeYmd(entry?.date) !== today) continue;
+ // Training entries are two shapes sharing one log: drill practice carries
+ // `drillType`, memory practice carries `memoryItemId` + `mode`.
+ if (entry.drillType) drillTypes.add(entry.drillType);
+ if (entry.memoryItemId) memoryItemIds.add(entry.memoryItemId);
+ }
+ return { drillTypes, memoryItemIds, completedSession };
+}
+
export function composePostRecommendations({
dueMemoryItems = [],
dueReviews = [],
weakestSkill = null,
stalled = [],
hasHistory = false,
+ practicedToday = null,
limit = RECOMMENDATION_LIMIT,
} = {}) {
+ // Copied into Sets so an array-shaped `practicedToday` (a JSON round-trip, or
+ // a test literal) works the same as the live Set-bearing one.
+ const doneTypes = new Set(practicedToday?.drillTypes || []);
+ const doneItems = new Set(practicedToday?.memoryItemIds || []);
const recs = [];
for (const item of dueMemoryItems) {
@@ -1066,10 +1120,12 @@ export function composePostRecommendations({
detail: 'Due for spaced-repetition practice',
deepLink: memoryPracticeDeepLink(item.id),
drillType: 'memory-sequence',
+ memoryItemId: item.id,
});
}
for (const review of dueReviews) {
+ const reviewItemId = review.kind === 'memory' ? memoryItemIdFromReview(review) : null;
// A memory-chunk re-verification can't run through the launcher's review-rep
// path (getPostReviewReps only regenerates multiplication/cognitive reps —
// memory retention lives under /post/memory), so route it there instead of a
@@ -1083,9 +1139,10 @@ export function composePostRecommendations({
? 'Needs a refresh — last review slipped'
: 'Maintenance rep due',
deepLink: review.kind === 'memory'
- ? memoryPracticeDeepLink(memoryItemIdFromReview(review))
+ ? memoryPracticeDeepLink(reviewItemId)
: '/post/launcher',
drillType: review.drillType || null,
+ memoryItemId: reviewItemId,
});
}
@@ -1127,7 +1184,25 @@ export function composePostRecommendations({
});
}
- return recs.slice(0, Math.max(1, limit)).map((r, i) => ({ ...r, priority: i }));
+ // One rule, applied after the list is built, so a rec kind added later inherits
+ // it instead of shipping an undefined flag. A rec's identity is whatever it
+ // actually sends the user to practice: a memory ITEM for the two memory-shaped
+ // recs, a drill TYPE for the ladder/weak-skill ones, and — for the "run a full
+ // self-test" fallback, which names neither — any scored session at all.
+ const isPracticedToday = (rec) => {
+ if (rec.memoryItemId) return doneItems.has(rec.memoryItemId);
+ if (rec.drillType) return doneTypes.has(rec.drillType);
+ return Boolean(practicedToday?.completedSession);
+ };
+ // Demoted, not dropped: a fully-practiced day should still show what's up next
+ // rather than an empty panel. `sort` is stable, so the priority order above is
+ // preserved within each group; callers that want to STOP (the daily routine)
+ // read the flag on the top rec.
+ const ordered = recs
+ .map(rec => ({ ...rec, practicedToday: isPracticedToday(rec) }))
+ .sort((a, b) => a.practicedToday - b.practicedToday);
+
+ return ordered.slice(0, Math.max(1, limit)).map((r, i) => ({ ...r, priority: i }));
}
// Coarse module → config key for the enabled-drill lookup.
@@ -1202,7 +1277,7 @@ export function isRecDrillRunnable(config, module, type, memoryItemId = null) {
* config can actually run.
*/
export async function getPostRecommendations({ limit = RECOMMENDATION_LIMIT } = {}) {
- const [dueMemoryItems, dueReviews, stats, mulProgress, powersProgress, cogProgress, morse, sessions, config] = await Promise.all([
+ const [dueMemoryItems, dueReviews, stats, mulProgress, powersProgress, cogProgress, morse, sessions, config, training, todayStr] = await Promise.all([
getDueMemoryItems(),
getDueReviews(new Date(), Infinity),
getPostStats(MASTERY_DEFAULTS.windowDays),
@@ -1212,6 +1287,8 @@ export async function getPostRecommendations({ limit = RECOMMENDATION_LIMIT } =
getMorseProgress(MASTERY_DEFAULTS.windowDays),
getPostSessions(),
getPostConfig(),
+ getAllTrainingEntries(),
+ localToday(),
]);
// Weakest skill — drop it unless the drill is currently runnable; a memory
@@ -1262,6 +1339,7 @@ export async function getPostRecommendations({ limit = RECOMMENDATION_LIMIT } =
weakestSkill,
stalled,
hasHistory: sessions.length > 0,
+ practicedToday: practicedTodayFromActivity(sessions, training, todayStr),
limit,
}),
};
diff --git a/server/services/meatspacePostRecommendations.test.js b/server/services/meatspacePostRecommendations.test.js
index 372f03fa6b..1f8b12b6e4 100644
--- a/server/services/meatspacePostRecommendations.test.js
+++ b/server/services/meatspacePostRecommendations.test.js
@@ -4,7 +4,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// (composePostRecommendations / weakestSkillFromStats / stalledProgressions)
// need no mocks; getPostRecommendations is exercised through the same
// mocked-fileUtils harness the other POST service tests use.
-const state = { sessions: [], memoryItems: [], reviewSchedule: { skills: {} }, morse: { kochLevel: null, settings: null, rounds: [] }, config: {} };
+const state = { sessions: [], training: [], memoryItems: [], reviewSchedule: { skills: {} }, morse: { kochLevel: null, settings: null, rounds: [] }, config: {} };
vi.mock('../lib/fileUtils.js', () => ({
atomicWrite: vi.fn().mockResolvedValue(undefined),
@@ -13,7 +13,7 @@ vi.mock('../lib/fileUtils.js', () => ({
readJSONFile: vi.fn((path, defaultValue) => {
if (typeof path === 'string') {
if (path.includes('post-sessions')) return Promise.resolve({ sessions: state.sessions });
- if (path.includes('post-training-log')) return Promise.resolve({ entries: [] });
+ if (path.includes('post-training-log')) return Promise.resolve({ entries: state.training });
if (path.includes('memory-items')) return Promise.resolve({ items: state.memoryItems });
if (path.includes('post-review-schedule')) return Promise.resolve(state.reviewSchedule);
if (path.includes('post-morse')) return Promise.resolve(state.morse);
@@ -39,11 +39,13 @@ import {
isRecDrillRunnable,
memoryPracticeDeepLink,
memoryItemIdFromReview,
+ practicedTodayFromActivity,
} from './meatspacePost.js';
import { atomicWrite } from '../lib/fileUtils.js';
beforeEach(() => {
state.sessions = [];
+ state.training = [];
state.memoryItems = [];
state.reviewSchedule = { skills: {} };
state.morse = { kochLevel: null, settings: null, rounds: [] };
@@ -401,6 +403,136 @@ describe('composePostRecommendations priority + composition', () => {
});
});
+// "Continue Today's Routine" used to loop on one drill forever: it always took
+// the #1 rec, and the signals behind that rec (windowed accuracy, ladder stall)
+// barely move on a single rep, so it handed back the test just finished
+// (issue #3563).
+describe('practicedTodayFromActivity', () => {
+ it('collects scored-session drill types for the local day only', () => {
+ const done = practicedTodayFromActivity([
+ { date: '2026-08-05', tasks: [{ type: 'digit-span' }, { type: 'n-back' }] },
+ { date: '2026-08-04', tasks: [{ type: 'multiplication' }] },
+ ], [], '2026-08-05');
+ expect([...done.drillTypes].sort()).toEqual(['digit-span', 'n-back']);
+ expect(done.completedSession).toBe(true);
+ });
+
+ it('collects both training-log shapes: drill practice and memory practice', () => {
+ const done = practicedTodayFromActivity([], [
+ { date: '2026-08-05', module: 'morse', drillType: 'morse-copy' },
+ { date: '2026-08-05', memoryItemId: 'song', mode: 'spaced' },
+ { date: '2026-08-04', drillType: 'wordplay-anagram' },
+ ], '2026-08-05');
+ expect([...done.drillTypes]).toEqual(['morse-copy']);
+ expect([...done.memoryItemIds]).toEqual(['song']);
+ // Practice-only days never complete a scored session.
+ expect(done.completedSession).toBe(false);
+ });
+
+ it('normalizes an ISO-timestamped entry date to its day prefix', () => {
+ // Some training-log entries (memory practice) store a full ISO timestamp; a
+ // raw `!==` would read those as not-practiced and re-loop the routine.
+ const done = practicedTodayFromActivity([], [
+ { date: '2026-08-05T21:14:03.000Z', drillType: 'morse-copy' },
+ ], '2026-08-05');
+ expect([...done.drillTypes]).toEqual(['morse-copy']);
+ });
+
+ it('reports nothing practiced when the local day cannot be resolved', () => {
+ const done = practicedTodayFromActivity([{ date: '2026-08-05', tasks: [{ type: 'digit-span' }] }], [], null);
+ expect(done.drillTypes.size).toBe(0);
+ expect(done.completedSession).toBe(false);
+ });
+});
+
+describe('composePostRecommendations already-practiced demotion (issue #3563)', () => {
+ const stalledDigitSpan = { drillType: 'digit-span', label: 'Digit Span', remaining: 3, nextLabel: 'Level 4', deepLink: '/post/launcher' };
+ const stalledMultiplication = { drillType: 'multiplication', label: 'Multiplication', remaining: 5, nextLabel: '2×2-digit', deepLink: '/post/launcher' };
+
+ it('sinks a stalled drill already practiced today below one that is not', () => {
+ const recs = composePostRecommendations({
+ stalled: [stalledDigitSpan, stalledMultiplication],
+ hasHistory: true,
+ practicedToday: { drillTypes: ['digit-span'] },
+ });
+ expect(recs.map(r => r.drillType)).toEqual(['multiplication', 'digit-span']);
+ expect(recs.map(r => r.practicedToday)).toEqual([false, true]);
+ // Priority is re-stamped AFTER the sort, so it still reads 0..n-1.
+ expect(recs.map(r => r.priority)).toEqual([0, 1]);
+ });
+
+ it('demotes rather than drops, so a fully-practiced day still shows what is next', () => {
+ const recs = composePostRecommendations({
+ stalled: [stalledDigitSpan],
+ hasHistory: true,
+ practicedToday: { drillTypes: ['digit-span'] },
+ });
+ expect(recs).toHaveLength(1);
+ expect(recs[0].practicedToday).toBe(true);
+ });
+
+ it('preserves the priority order within each group', () => {
+ const recs = composePostRecommendations({
+ dueMemoryItems: [{ id: 'song', title: 'Elements' }],
+ weakestSkill: { key: 'cognitive:n-back', type: 'n-back', accuracy: 0.5 },
+ stalled: [stalledDigitSpan, stalledMultiplication],
+ hasHistory: true,
+ practicedToday: { drillTypes: ['n-back', 'digit-span'] },
+ });
+ expect(recs.map(r => r.kind)).toEqual(['memory-due', 'stalled-progression', 'weak-skill', 'stalled-progression']);
+ expect(recs.map(r => r.drillType)).toEqual(['memory-sequence', 'multiplication', 'n-back', 'digit-span']);
+ });
+
+ it('marks a due memory item practiced by its ITEM id, not its drill type', () => {
+ const recs = composePostRecommendations({
+ dueMemoryItems: [{ id: 'song', title: 'Elements' }, { id: 'pi', title: 'Pi' }],
+ // Both recs carry drillType 'memory-sequence'; only the item id separates them.
+ practicedToday: { memoryItemIds: ['song'], drillTypes: ['memory-sequence'] },
+ });
+ expect(recs.map(r => r.id)).toEqual(['memory-due:pi', 'memory-due:song']);
+ expect(recs.map(r => r.practicedToday)).toEqual([false, true]);
+ });
+
+ it('marks a memory-chunk re-verification by its item id and a ladder one by its drill', () => {
+ const recs = composePostRecommendations({
+ dueReviews: [
+ { skillId: 'memory:song:c1', label: 'Elements — Chorus', kind: 'memory', status: 'due' },
+ { skillId: 'multiplication:L1', label: 'Multiplication 1×2', drillType: 'multiplication', kind: 'multiplication', status: 'due' },
+ ],
+ practicedToday: { memoryItemIds: ['song'], drillTypes: [] },
+ });
+ expect(recs.map(r => r.practicedToday)).toEqual([false, true]);
+ expect(recs[0].drillType).toBe('multiplication');
+ });
+
+ it('treats the fallback "run a full POST" as done once a scored session lands today', () => {
+ const done = composePostRecommendations({ hasHistory: true, practicedToday: { completedSession: true } });
+ expect(done[0].kind).toBe('default');
+ expect(done[0].practicedToday).toBe(true);
+ const notDone = composePostRecommendations({ hasHistory: true, practicedToday: { completedSession: false } });
+ expect(notDone[0].practicedToday).toBe(false);
+ });
+
+ it('accepts the Set-bearing shape practicedTodayFromActivity returns', () => {
+ const recs = composePostRecommendations({
+ stalled: [stalledDigitSpan, stalledMultiplication],
+ practicedToday: practicedTodayFromActivity([{ date: 'D', tasks: [{ type: 'digit-span' }] }], [], 'D'),
+ });
+ expect(recs.map(r => r.drillType)).toEqual(['multiplication', 'digit-span']);
+ });
+
+ it('leaves the order untouched when nothing has been practiced today', () => {
+ const recs = composePostRecommendations({
+ weakestSkill: { key: 'cognitive:digit-span', type: 'digit-span', accuracy: 0.4 },
+ stalled: [stalledMultiplication],
+ hasHistory: true,
+ practicedToday: { drillTypes: [], memoryItemIds: [] },
+ });
+ expect(recs.map(r => r.kind)).toEqual(['weak-skill', 'stalled-progression']);
+ expect(recs.every(r => r.practicedToday === false)).toBe(true);
+ });
+});
+
describe('getPostRecommendations (integration)', () => {
it('surfaces a due memory item as the top recommendation', async () => {
// A memory item overdue for review: nextReview in the past.
@@ -422,6 +554,29 @@ describe('getPostRecommendations (integration)', () => {
}
});
+ it('stops handing back today\'s digit-span drill once it has been practiced (issue #3563)', async () => {
+ // The exact loop the user hit: a stalled digit-span ladder pinned the #1
+ // rec, "Continue Today's Routine" took rec[0], and the drill it started was
+ // the drill just finished. Seed a scored session containing digit-span for
+ // today plus a Morse practice track that has NOT been touched.
+ const today = new Date().toISOString().slice(0, 10);
+ state.sessions = [{
+ id: 's1', date: today, score: 60, durationMs: 60000,
+ tasks: [{ module: 'cognitive', type: 'digit-span', score: 60, accuracy: 0.4, completion: 1 }],
+ }];
+ state.morse = { kochLevel: 3, settings: { kochLevel: 3 }, rounds: [] };
+ // Memory off, so the only recs left are the drill-shaped ones.
+ state.config = { memory: { enabled: false }, topics: { memory: { enabled: false } } };
+
+ const { recommendations } = await getPostRecommendations();
+ const digitSpan = recommendations.filter(r => r.drillType === 'digit-span');
+ expect(digitSpan.length).toBeGreaterThan(0);
+ for (const rec of digitSpan) expect(rec.practicedToday).toBe(true);
+ // Something the user has NOT done today outranks it, so the routine advances.
+ expect(recommendations[0].practicedToday).toBe(false);
+ expect(recommendations[0].drillType).not.toBe('digit-span');
+ });
+
it('never returns an empty list on a fresh install', async () => {
// A fresh install still has the built-in Elements Song memory item (which
// may be due) so the list is never empty; every entry carries a deep link.