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

fix: rotate POST daily practice across eligible drills instead of repeating one (#5319)

[._.]/ Adam Eivy506058246556
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsx
index 11d3683de7..7137e004a8 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx
@@ -186,6 +186,11 @@ export default function PostSessionLauncher({
// recommendation also biases the Quick session's drill picks.
const [recommendations, setRecommendations] = useState([]);
const [recommendationsLoaded, setRecommendationsLoaded] = useState(false);
+ // Compact multi-day practice window from the same endpoint (issue #5319), so
+ // the Quick session rotates its per-domain picks off exactly the signal the
+ // server used to order the recommendations. null = not loaded / load failed,
+ // which composeQuickSession degrades to its previous fixed ordering.
+ const [recentPractice, setRecentPractice] = useState(null);
// Current effective Morse WPM — fetched only when a Morse WPM goal is set, so
// that goal can render progress (issue #2100). null when unset/unavailable.
const [morseWpm, setMorseWpm] = useState(null);
@@ -201,8 +206,14 @@ export default function PostSessionLauncher({
useEffect(() => {
getPostReviewReps(5).then(r => setReviewReps(r?.reps || [])).catch(() => setReviewReps([]));
getPostRecommendations()
- .then(r => setRecommendations(r?.recommendations || []))
- .catch(() => setRecommendations([]))
+ .then(r => {
+ setRecommendations(r?.recommendations || []);
+ setRecentPractice(r?.recentPractice || null);
+ })
+ .catch(() => {
+ setRecommendations([]);
+ setRecentPractice(null);
+ })
.finally(() => setRecommendationsLoaded(true));
getMemoryItems({ silent: true })
.then(items => setMemoryItemsState({ status: 'ready', items: Array.isArray(items) ? items : [] }))
@@ -458,6 +469,7 @@ export default function PostSessionLauncher({
toleranceSec: QUICK_DURATION_TOLERANCE_SEC,
observedDurations: deriveQuickObservedDurations(recentSessions),
memoryItemIds: quickMemoryItemIds,
+ recentPractice,
});
function handleQuickDurationChange(event) {
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
index e383260db7..dfe86895c9 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
@@ -652,6 +652,27 @@ describe('PostSessionLauncher topic gating (issue #3252)', () => {
expect(types).toEqual(['bridge-word', 'pun-wordplay']);
});
+ // Issue #5319: the launcher threads the endpoint's recency window into the
+ // Quick composer. Without it the composer keeps resolving each domain to its
+ // registry-order drill, so the same practice comes back day after day.
+ it("rotates a Quick domain off the recency window the recommendations endpoint reports", async () => {
+ const onStart = vi.fn();
+ getPostRecommendations.mockResolvedValue({
+ recommendations: [],
+ recentPractice: { dayKey: "2026-03-02", drillTypes: ["multiplication"], memoryItemIds: [] },
+ });
+ renderWith({
+ ...llmConfig({ verbal: { enabled: false }, imagination: { enabled: false } }),
+ mentalMath: { enabled: true, drillTypes: { multiplication: { enabled: true, count: 10 }, powers: { enabled: true, count: 5 } } },
+ sessionModules: ["mental-math", "llm-drills"],
+ }, onStart);
+ await waitFor(() => expect(getPostRecommendations).toHaveBeenCalled());
+ fireEvent.click(await screen.findByRole("button", { name: /Quick 5 Min/ }));
+
+ const mathDrills = onStart.mock.calls[0][0].filter(drill => drill.domain === "math");
+ expect(mathDrills.map(drill => drill.type)).toEqual(["powers"]);
+ });
+
it('a disabled topic is excluded from Quick sessions too, not just Full POST', async () => {
const onStart = vi.fn();
// The Quick button only renders with ≥2 composable domains, so keep math in
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index ce39e06832..d0e0bd0459 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -19,6 +19,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `navFeatures.js` | `filterNavByFeatures(navEntries, isFeatureEnabled)` — drops nav-manifest entries whose optional instance feature (`post`, `datadog`, `jira`, `gsd`) is off. The single gate for BROWSE surfaces (sidebar, ⌘K); routes stay reachable by URL, bookmark, and voice. Pair with `useInstanceFeatures`. |
| `postQuickSession.js` | Pure Quick POST duration presets, local-observation estimator, deterministic budget composer, and preview metadata. |
+| `postRotation.js` | Pure deterministic day-based rotation for POST practice selection — `orderByRecencyRotation` sorts candidates fresh-before-recently-practiced, then by priority, and rotates equivalent ones by local day. Mirrored from `server/lib/postRotation.js`. |
---
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index fc21ea669a..74c102bca5 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -138,6 +138,7 @@ export * from './midiPlayback.js';
export * from './pianoKeyboard.js';
export * from './pitchDetect.js';
export * from './postQuickSession.js';
+export * from './postRotation.js';
export * from './seriesReviewProgress.js';
export * from './powersBreakdown.js';
export * from './promptStageGroups.js';
diff --git a/client/src/lib/postQuickSession.js b/client/src/lib/postQuickSession.js
index d02fca105c..b3806682ba 100644
--- a/client/src/lib/postQuickSession.js
+++ b/client/src/lib/postQuickSession.js
@@ -2,6 +2,8 @@
// estimator and composer side-effect free makes the time-budget contract easy
// to test and keeps provider calls out of the planning path.
+import { orderByRecencyRotation } from './postRotation.js';
+
export const QUICK_DURATION_MINUTES = [3, 5, 10, 15];
export const DEFAULT_QUICK_DURATION_MINUTES = 5;
export const QUICK_DURATION_TOLERANCE_SEC = 30;
@@ -141,16 +143,39 @@ function inferSource(rep) {
return 'math';
}
-function candidateForDomain(domain, drills, recommendation, memoryItemIds = {}) {
+/**
+ * Normalize the server's `recentPractice` payload into a membership test.
+ * A memory drill's identity is its ITEM — practicing the Elements Song must not
+ * make every other memory item look recently practiced (issue #5319) — while
+ * every other drill is identified by its type.
+ */
+function recentPracticeMatcher({ drillTypes = [], memoryItemIds = [] } = {}) {
+ const types = new Set(drillTypes);
+ const items = new Set(memoryItemIds);
+ return (candidate, memoryItemId) => (
+ candidate?.source === 'memory' && memoryItemId
+ ? items.has(memoryItemId)
+ : types.has(candidate?.type)
+ );
+}
+
+function candidateForDomain(domain, drills, recommendation, memoryItemIds = {}, { dayKey = null, isRecent = () => false } = {}) {
const list = drills || [];
if (!list.length) return null;
+ const memoryItemIdFor = drill => drill.memoryItemId ?? memoryItemIds[drill.type];
+ const recentDrill = drill => isRecent(drill, memoryItemIdFor(drill));
const recommended = recommendation?.drillType
? list.find(drill => drill.type === recommendation.drillType)
: null;
- const pick = recommended || list[0];
+ // The recommendation wins its domain only while it is still fresh. Once it
+ // has been practiced inside the window, this domain rotates to another
+ // enabled candidate instead of re-serving registry-order `list[0]`.
+ const pick = (recommended && !recentDrill(recommended))
+ ? recommended
+ : orderByRecencyRotation(list, { dayKey, isRecent: recentDrill })[0];
const quickConfig = pick.quickConfig || buildQuickDrillConfig({
...pick,
- memoryItemId: pick.memoryItemId ?? memoryItemIds[pick.type],
+ memoryItemId: memoryItemIdFor(pick),
});
return {
kind: 'drill',
@@ -178,9 +203,16 @@ function reviewCandidate(rep) {
}
/**
- * Compose a stable Quick plan. The top recommendation wins its domain, due
- * review reps come next, and remaining domains are then admitted in their
- * existing registry order while the target+tolerance budget has room.
+ * Compose a stable Quick plan. A still-fresh top recommendation wins its
+ * domain, due review reps come next, and remaining domains are then admitted
+ * while the target+tolerance budget has room.
+ *
+ * `recentPractice` (from the recommendations endpoint: `{ dayKey, drillTypes,
+ * memoryItemIds }`) is what keeps a multi-drill domain from serving the same
+ * registry-order drill every day — within a domain, candidates practiced in the
+ * window sink, and equally-eligible ones rotate by local day. Omitting it
+ * restores the previous fixed ordering, so the plan is still deterministic when
+ * the recommendations fetch fails.
*/
export function composeQuickSession({
domainEntries = [],
@@ -190,13 +222,18 @@ export function composeQuickSession({
toleranceSec = QUICK_DURATION_TOLERANCE_SEC,
observedDurations = {},
memoryItemIds = {},
+ recentPractice = null,
} = {}) {
const targetDurationSec = normalizeQuickDurationMinutes(durationMinutes) * 60;
const budgetSec = targetDurationSec + Math.max(0, toleranceSec);
+ const rotation = {
+ dayKey: recentPractice?.dayKey || null,
+ isRecent: recentPracticeMatcher(recentPractice || {}),
+ };
const domains = domainEntries
.map(entry => ({
domain: entry.domain,
- candidate: candidateForDomain(entry.domain, entry.drills, recommendation, memoryItemIds),
+ candidate: candidateForDomain(entry.domain, entry.drills, recommendation, memoryItemIds, rotation),
}))
.filter(entry => entry.candidate);
diff --git a/client/src/lib/postQuickSession.test.js b/client/src/lib/postQuickSession.test.js
index 3fdf217a5a..2b5ee77f4b 100644
--- a/client/src/lib/postQuickSession.test.js
+++ b/client/src/lib/postQuickSession.test.js
@@ -76,5 +76,63 @@ describe('postQuickSession', () => {
type: 'multiplication', source: 'math', cfg: { count: 8, steps: 4, maxDigits: 2 },
})).toMatchObject({ count: 5, steps: 4, maxDigits: 2 });
});
+
+ // Issue #5319: a domain with several enabled drills used to resolve to
+ // registry-order list[0] forever, so Quick Session served the same drill every
+ // day. Recency + a local-day rotation replace that fixed order — without
+ // introducing randomness, which would break re-requesting the same plan.
+ describe("recent-practice rotation (issue #5319)", () => {
+ const twoMathDrills = [
+ { domain: "math", drills: [
+ { type: "multiplication", source: "math", cfg: { count: 5, steps: 2 } },
+ { type: "powers", source: "math", cfg: { count: 5 } },
+ ] },
+ ];
+ const pickedMathType = (recentPractice, recommendation = null) => composeQuickSession({
+ durationMinutes: 15, domainEntries: twoMathDrills, recommendation, recentPractice,
+ }).selected.find(candidate => candidate.domain === "math").type;
+
+ it("skips the registry-first drill once it was practiced in the window", () => {
+ expect(pickedMathType(null)).toBe("multiplication");
+ expect(pickedMathType({ dayKey: "2026-03-02", drillTypes: ["multiplication"] })).toBe("powers");
+ });
+
+ it("drops the recommendation preference only when the recommended drill is itself recent", () => {
+ const rec = { drillType: "powers" };
+ expect(pickedMathType({ dayKey: "2026-03-02", drillTypes: [] }, rec)).toBe("powers");
+ expect(pickedMathType({ dayKey: "2026-03-02", drillTypes: ["powers"] }, rec)).toBe("multiplication");
+ });
+
+ it("rotates equally-eligible drills across days and repeats within one day", () => {
+ const heads = ["2026-03-01", "2026-03-02"].map(dayKey => pickedMathType({ dayKey, drillTypes: [] }));
+ expect(new Set(heads).size).toBe(2);
+ const plan = { dayKey: "2026-03-02", drillTypes: [] };
+ expect(pickedMathType(plan)).toBe(pickedMathType(plan));
+ });
+
+ it("keeps the only candidate in a domain even when it is recent", () => {
+ const plan = composeQuickSession({
+ durationMinutes: 15,
+ domainEntries: [{ domain: "cognitive", drills: [{ type: "n-back", source: "cognitive", cfg: { length: 20 } }] }],
+ recentPractice: { dayKey: "2026-03-02", drillTypes: ["n-back"] },
+ });
+ expect(plan.selected.map(c => c.type)).toEqual(["n-back"]);
+ });
+
+ it("identifies a memory drill by its ITEM, so practicing one item does not sink the others", () => {
+ const memoryDomain = [{ domain: "memory", drills: [
+ { type: "memory-sequence", source: "memory", cfg: { count: 3 }, memoryItemId: "elements-song" },
+ { type: "memory-fill-blank", source: "memory", cfg: { count: 3 }, memoryItemId: "example-poem" },
+ ] }];
+ const picked = composeQuickSession({
+ durationMinutes: 15,
+ domainEntries: memoryDomain,
+ // Elements practiced; the sibling ITEM must stay eligible even though
+ // the type-level signal would otherwise mark the whole domain recent.
+ recentPractice: { dayKey: "2026-03-02", drillTypes: ["memory-sequence"], memoryItemIds: ["elements-song"] },
+ }).selected.find(candidate => candidate.domain === "memory");
+ expect(picked.type).toBe("memory-fill-blank");
+ });
+ });
});
// @vitest-environment node
diff --git a/client/src/lib/postRotation.js b/client/src/lib/postRotation.js
new file mode 100644
index 0000000000..bdf2992455
--- /dev/null
+++ b/client/src/lib/postRotation.js
@@ -0,0 +1,89 @@
+/**
+ * Deterministic day-based rotation for POST practice selection (issue #5319).
+ *
+ * Every POST "what should I practice?" surface used to resolve equivalent
+ * candidates by input order, so the same drill won the top slot every day —
+ * Elements from the memory tier, digit-span from the heuristic tiers. These
+ * helpers replace that fixed order with a rotation keyed by the local day, so
+ * the choice varies across days while staying repeatable for the same day and
+ * the same inputs (no randomness — the daily routine must be reproducible).
+ *
+ * Pure, dependency-free, and MIRRORED from `server/lib/postRotation.js` so the
+ * client's Quick-session domain picks and the server's recommendation tiers
+ * rotate identically. Keep the two files in sync — the server-side
+ * `postRotation.mirror.test.js` fails when their code diverges.
+ */
+
+/**
+ * Days since the epoch for a `YYYY-MM-DD` local day label, as a rotation seed.
+ * Returns null when the label isn't parseable, so callers fall back to plain
+ * priority order rather than rotating off a garbage seed.
+ */
+function dayOrdinal(dayKey) {
+ if (typeof dayKey !== 'string') return null;
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dayKey.trim());
+ if (!match) return null;
+ const [, y, m, d] = match;
+ const at = Date.UTC(Number(y), Number(m) - 1, Number(d));
+ return Number.isNaN(at) ? null : Math.floor(at / 86400000);
+}
+
+/**
+ * Offset into a list of `length` equivalent candidates for the given local day.
+ * Always in range; 0 for an unparseable day or an empty list.
+ */
+export function dayRotationIndex(dayKey, length) {
+ const size = Math.trunc(length) || 0;
+ if (size <= 1) return 0;
+ const ordinal = dayOrdinal(dayKey);
+ if (ordinal === null) return 0;
+ return ((ordinal % size) + size) % size;
+}
+
+/**
+ * Order a priority-ranked candidate list so that:
+ * 1. candidates NOT practiced inside the recency window come first,
+ * 2. within that, lower `rank` (higher priority) comes first,
+ * 3. and genuinely equivalent candidates — same recency bucket, same rank —
+ * rotate by local day instead of resolving to input order.
+ *
+ * Nothing is dropped, so a caller that wants the whole tier keeps every entry
+ * and a caller that wants one pick reads `[0]`. With a single candidate (or no
+ * day key) the input order is returned unchanged, which is what makes "fall
+ * back to the only available option" free.
+ *
+ * @param {Array} candidates
+ * @param {object} [options]
+ * @param {string|null} [options.dayKey] - local `YYYY-MM-DD`
+ * @param {(candidate: any) => boolean} [options.isRecent] - practiced in the window
+ * @param {(candidate: any) => number} [options.rank] - lower is higher priority
+ * @returns {Array} a new, reordered array
+ */
+export function orderByRecencyRotation(candidates, { dayKey = null, isRecent = () => false, rank = () => 0 } = {}) {
+ const list = (candidates || []).filter(Boolean);
+ if (list.length <= 1) return list;
+
+ const decorated = list.map((candidate, index) => ({
+ candidate,
+ index,
+ recent: isRecent(candidate) ? 1 : 0,
+ rank: Number(rank(candidate)) || 0,
+ }));
+ decorated.sort((a, b) => (a.recent - b.recent) || (a.rank - b.rank) || (a.index - b.index));
+
+ const out = [];
+ let start = 0;
+ while (start < decorated.length) {
+ let end = start;
+ while (
+ end < decorated.length
+ && decorated[end].recent === decorated[start].recent
+ && decorated[end].rank === decorated[start].rank
+ ) end += 1;
+ const group = decorated.slice(start, end);
+ const offset = dayRotationIndex(dayKey, group.length);
+ out.push(...group.slice(offset), ...group.slice(0, offset));
+ start = end;
+ }
+ return out.map(entry => entry.candidate);
+}
diff --git a/server/lib/README.md b/server/lib/README.md
index 9c6c5ef0f9..d4e82b9667 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -372,6 +372,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `spacedRepetition.js` | The shared SM-2-inspired review scheduler, extracted from `services/meatspacePostMemory.js` when SongBook practice became its second consumer (#4102). One four-field schedule shape (`{ ease, intervalDays, nextReview, lastReviewed }`, no `repetitions` counter — the 0 → 1 → 6 → `round(prev * ease)` ladder derives from the previous interval, so a schedule round-trips through import/export/federation on those four fields alone). `advanceSchedule(schedule, ratio, now)` is the core (ease clamped to `MIN_EASE`..`MAX_EASE`, interval capped at `MAX_INTERVAL_DAYS` so `new Date(now + interval*DAY)` can't overflow into an Invalid Date; quality < 3 zeroes the interval to resurface the record but still applies the ease penalty). `mergeScheduleAdvance(prev, advanced, now)` gates interval GROWTH to once per review day (a shrink always applies) for UIs that submit per chunk/section; `isSameReviewDay` is that gate's own predicate, reusable by callers gating their own once-a-day progression. `scheduleOrDefault(record, schedule?)` is the read-path fallback — a record with no schedule derives one anchored to its `updatedAt`/`createdAt` (stable and in the past → due now), so "due" can't flap between two reads a millisecond apart. `ratioToQuality` / `qualityToRatio` are exact inverses over the integers, so a self-graded 0..5 review lands on the quality the user picked. `isScheduleDue` treats an absent/unparseable `nextReview` as due — a record we can't schedule is one to surface, never one to hide forever. Pure. |
| `songPractice.js` | SongBook repertoire practice scheduling (#4102) — the pure core behind `POST /api/brain/songbook/:id/practice`. `applySongPractice(song, quality, now)` → `{ stage, practice }`, the exact partial to hand `brainStorage.updateWith`: it advances the shared `spacedRepetition` schedule from a 0..5 self-grade and moves the song's `stage` along `SONG_STAGE_ORDER` (≥ `SONG_PROMOTE_MIN_QUALITY` promotes, ≤ `SONG_REGRESS_MAX_QUALITY` regresses, a 3 holds). Promotion is gated to once per practice day (regression never is), and a practiced song floors at `learning` — `new` means "never picked up", which stops being true after one session. `songPracticeOrDefault(song)` derives the schedule on READ for every song predating the feature (nothing is backfilled to disk: a migration would restamp `updatedAt` on every record and spray federation churn, and would break the `data.reference/` seeds' byte-identity). `nextSongStage` no-ops on a stage this install doesn't recognize, so a practice log can't rewrite a value synced from a newer peer. `isSongDue(song, now)` mirrors the client's `songDueAt` in `client/src/components/songbook/constants.js`. Pure. |
| `postTopics.js` | Pure POST practice-topic registry — `POST_TOPICS` (`{ id, label, module, surface, drillTypes }`) is the single source of truth for "what am I studying?", plus `resolveTopicForDrillType` / `isTopicEnabled` / `isMemoryItemEnabled`. Gates session composition and recommendations, including Memory's composed and dedicated practice routes plus standalone Morse. Mirrored to the client's post `constants.js` (parity test). |
+| `postRotation.js` | Pure deterministic day-based rotation for POST practice selection — `orderByRecencyRotation` sorts candidates fresh-before-recently-practiced, then by priority, and rotates equivalent ones by local day so a tier never pins to one drill. Mirrored at `client/src/lib/postRotation.js`. |
| `postStreak.js` | Pure DST-safe POST practice-streak math — the single `computePostStreaks` implementation shared by scored sessions and the training log, plus `computeUnifiedStreak` (a day is active with EITHER a session or a practice entry), `normalizeYmd` (day-key prefix for a date that may be a full ISO timestamp), and `recordDayKey` / `withDerivedDayKeys` (re-derive a record's day key from its `startedAt`/`completedAt`/`timestamp` instant, so readers ignore a `date` frozen in a previously-configured timezone). |
| `activeDays.js` | Cross-domain "days active" set math (#4120) — `unionActiveDayKeys(sources, timezone)` unions several domains' stored date values into one sorted array of user-local `YYYY-MM-DD` keys (`.length` is the honest day count; summing per-domain counts would double-count any day logged in two domains), and `toUserDayKey(value, timezone)` is its per-value normalizer. Owns the day-boundary reconciliation between POST (stamps `userLocalToday()`) and the health logs (stamp the server-local `getDateString()`): a value carrying an INSTANT (the pre-#2681 full-ISO shape some legacy training entries still store) is re-keyed into the user's timezone rather than `split('T')[0]`'d to the UTC day, while a value that is already a bare day LABEL is taken as authored — there is no instant left to re-derive from, so retro-normalizing stored health keys is out of scope by construction, not by omission. Non-day values are dropped rather than coerced. Pure. |
| `planIds.js` | Utilities for PLAN.md `[slug]` IDs. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 2f8837b210..e6c63d4880 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -13223,7 +13223,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 264
+ "line": 269
}
]
},
@@ -13245,7 +13245,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 240
+ "line": 245
}
]
},
@@ -13278,7 +13278,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 157
+ "line": 162
}
]
},
@@ -13289,7 +13289,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 316
+ "line": 321
}
]
},
@@ -13300,7 +13300,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 305
+ "line": 310
}
]
},
@@ -13311,7 +13311,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 513
+ "line": 518
}
]
},
@@ -13322,7 +13322,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 411
+ "line": 416
}
]
},
@@ -13333,7 +13333,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 440
+ "line": 445
}
]
},
@@ -13344,7 +13344,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 461
+ "line": 466
}
]
},
@@ -13355,7 +13355,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 430
+ "line": 435
}
]
},
@@ -13366,7 +13366,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 450
+ "line": 455
}
]
},
@@ -13377,7 +13377,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 482
+ "line": 487
}
]
},
@@ -13388,7 +13388,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 503
+ "line": 508
}
]
},
@@ -13399,7 +13399,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 493
+ "line": 498
}
]
},
@@ -13410,7 +13410,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 471
+ "line": 476
}
]
},
@@ -13421,7 +13421,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 421
+ "line": 426
}
]
},
@@ -13432,7 +13432,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 397
+ "line": 402
}
]
},
@@ -13443,7 +13443,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 386
+ "line": 391
}
]
},
@@ -13454,7 +13454,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 375
+ "line": 380
}
]
},
@@ -13465,7 +13465,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 223
+ "line": 228
}
]
},
@@ -13476,7 +13476,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 229
+ "line": 234
}
]
},
@@ -13498,7 +13498,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 145
+ "line": 150
}
]
},
@@ -13509,7 +13509,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 252
+ "line": 257
}
]
},
@@ -13520,7 +13520,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 287
+ "line": 292
}
]
},
@@ -13531,7 +13531,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 273
+ "line": 278
}
]
},
@@ -13586,7 +13586,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 330
+ "line": 335
}
]
},
@@ -13597,7 +13597,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 361
+ "line": 366
}
]
},
@@ -13608,7 +13608,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 340
+ "line": 345
}
]
},
@@ -13619,7 +13619,7 @@
"sources": [
{
"source": "server/routes/meatspacePostRoutes.js",
- "line": 350
+ "line": 355
}
]
},
diff --git a/server/lib/index.js b/server/lib/index.js
index f7171e6804..c33434fc9b 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -345,6 +345,7 @@ export * from './postAppliedNumeracy.js';
export * from './postMultiplicationLadder.js';
export * from './postPowersLadder.js';
export * from './postProgression.js';
+export * from './postRotation.js';
export * from './postStreak.js';
export * from './activeDays.js';
export * from './postTopics.js';
diff --git a/server/lib/postRotation.js b/server/lib/postRotation.js
new file mode 100644
index 0000000000..adbda7b583
--- /dev/null
+++ b/server/lib/postRotation.js
@@ -0,0 +1,89 @@
+/**
+ * Deterministic day-based rotation for POST practice selection (issue #5319).
+ *
+ * Every POST "what should I practice?" surface used to resolve equivalent
+ * candidates by input order, so the same drill won the top slot every day —
+ * Elements from the memory tier, digit-span from the heuristic tiers. These
+ * helpers replace that fixed order with a rotation keyed by the local day, so
+ * the choice varies across days while staying repeatable for the same day and
+ * the same inputs (no randomness — the daily routine must be reproducible).
+ *
+ * Pure, dependency-free, and MIRRORED to `client/src/lib/postRotation.js` so the
+ * server's recommendation tiers and the client's Quick-session domain picks
+ * rotate identically. Keep the two files in sync — `postRotation.mirror.test.js`
+ * fails when their code diverges.
+ */
+
+/**
+ * Days since the epoch for a `YYYY-MM-DD` local day label, as a rotation seed.
+ * Returns null when the label isn't parseable, so callers fall back to plain
+ * priority order rather than rotating off a garbage seed.
+ */
+function dayOrdinal(dayKey) {
+ if (typeof dayKey !== 'string') return null;
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dayKey.trim());
+ if (!match) return null;
+ const [, y, m, d] = match;
+ const at = Date.UTC(Number(y), Number(m) - 1, Number(d));
+ return Number.isNaN(at) ? null : Math.floor(at / 86400000);
+}
+
+/**
+ * Offset into a list of `length` equivalent candidates for the given local day.
+ * Always in range; 0 for an unparseable day or an empty list.
+ */
+export function dayRotationIndex(dayKey, length) {
+ const size = Math.trunc(length) || 0;
+ if (size <= 1) return 0;
+ const ordinal = dayOrdinal(dayKey);
+ if (ordinal === null) return 0;
+ return ((ordinal % size) + size) % size;
+}
+
+/**
+ * Order a priority-ranked candidate list so that:
+ * 1. candidates NOT practiced inside the recency window come first,
+ * 2. within that, lower `rank` (higher priority) comes first,
+ * 3. and genuinely equivalent candidates — same recency bucket, same rank —
+ * rotate by local day instead of resolving to input order.
+ *
+ * Nothing is dropped, so a caller that wants the whole tier keeps every entry
+ * and a caller that wants one pick reads `[0]`. With a single candidate (or no
+ * day key) the input order is returned unchanged, which is what makes "fall
+ * back to the only available option" free.
+ *
+ * @param {Array} candidates
+ * @param {object} [options]
+ * @param {string|null} [options.dayKey] - local `YYYY-MM-DD`
+ * @param {(candidate: any) => boolean} [options.isRecent] - practiced in the window
+ * @param {(candidate: any) => number} [options.rank] - lower is higher priority
+ * @returns {Array} a new, reordered array
+ */
+export function orderByRecencyRotation(candidates, { dayKey = null, isRecent = () => false, rank = () => 0 } = {}) {
+ const list = (candidates || []).filter(Boolean);
+ if (list.length <= 1) return list;
+
+ const decorated = list.map((candidate, index) => ({
+ candidate,
+ index,
+ recent: isRecent(candidate) ? 1 : 0,
+ rank: Number(rank(candidate)) || 0,
+ }));
+ decorated.sort((a, b) => (a.recent - b.recent) || (a.rank - b.rank) || (a.index - b.index));
+
+ const out = [];
+ let start = 0;
+ while (start < decorated.length) {
+ let end = start;
+ while (
+ end < decorated.length
+ && decorated[end].recent === decorated[start].recent
+ && decorated[end].rank === decorated[start].rank
+ ) end += 1;
+ const group = decorated.slice(start, end);
+ const offset = dayRotationIndex(dayKey, group.length);
+ out.push(...group.slice(offset), ...group.slice(0, offset));
+ start = end;
+ }
+ return out.map(entry => entry.candidate);
+}
diff --git a/server/lib/postRotation.mirror.test.js b/server/lib/postRotation.mirror.test.js
new file mode 100644
index 0000000000..b020ca785f
--- /dev/null
+++ b/server/lib/postRotation.mirror.test.js
@@ -0,0 +1,38 @@
+/**
+ * Mirror parity test for server/lib/postRotation.js ↔ client/src/lib/postRotation.js
+ *
+ * The whole module is mirrored: the server's recommendation tiers and the
+ * client's Quick-session domain picks must rotate identically, or the two
+ * surfaces disagree about which drill is "next" on the same day.
+ *
+ * Comments are stripped before diffing (see lib/mirrorParity.js), so the header
+ * pointing at the twin file may differ; code logic may not.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { resolve, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { compareDeclaration } from './mirrorParity.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const SERVER_PATH = resolve(__dirname, 'postRotation.js');
+const CLIENT_PATH = resolve(__dirname, '../../client/src/lib/postRotation.js');
+
+const MIRRORED_NAMES = ['dayOrdinal', 'dayRotationIndex', 'orderByRecencyRotation'];
+
+describe('postRotation server↔client mirror parity', () => {
+ const serverSrc = readFileSync(SERVER_PATH, 'utf8');
+ const clientSrc = readFileSync(CLIENT_PATH, 'utf8');
+
+ for (const name of MIRRORED_NAMES) {
+ it(`${name} is present and identical on both sides (code only)`, () => {
+ const { serverDecl, clientDecl, serverNorm, clientNorm } =
+ compareDeclaration(serverSrc, clientSrc, name);
+
+ expect(serverDecl, `server/lib/postRotation.js is missing declaration: ${name}`).not.toBeNull();
+ expect(clientDecl, `client/src/lib/postRotation.js is missing declaration: ${name}`).not.toBeNull();
+ expect(clientNorm, `"${name}" code diverged between server and client`).toBe(serverNorm);
+ });
+ }
+});
diff --git a/server/lib/postRotation.test.js b/server/lib/postRotation.test.js
new file mode 100644
index 0000000000..6bfc3daf51
--- /dev/null
+++ b/server/lib/postRotation.test.js
@@ -0,0 +1,68 @@
+import { describe, it, expect } from 'vitest';
+import { dayRotationIndex, orderByRecencyRotation } from './postRotation.js';
+
+// The regression these guard: POST's practice tiers used to resolve equivalent
+// candidates by input order, so one drill held the top slot every day. Rotation
+// has to vary ACROSS days while staying reproducible WITHIN a day — a random
+// pick would break "Continue Today's Routine", which re-requests the list.
+describe('postRotation', () => {
+ describe('dayRotationIndex', () => {
+ it('advances by one candidate per local day and wraps', () => {
+ expect(dayRotationIndex('2026-03-01', 3)).toBe(dayRotationIndex('2026-03-04', 3));
+ const walk = ['2026-03-01', '2026-03-02', '2026-03-03'].map(day => dayRotationIndex(day, 3));
+ expect([...new Set(walk)].sort()).toEqual([0, 1, 2]);
+ });
+
+ it('degrades to 0 rather than rotating off an unusable day or list', () => {
+ expect(dayRotationIndex(null, 4)).toBe(0);
+ expect(dayRotationIndex('not-a-day', 4)).toBe(0);
+ expect(dayRotationIndex('2026-03-01', 1)).toBe(0);
+ expect(dayRotationIndex('2026-03-01', 0)).toBe(0);
+ });
+ });
+
+ describe('orderByRecencyRotation', () => {
+ const dayKey = '2026-03-02';
+
+ it('sinks recently-practiced candidates below fresh ones', () => {
+ const order = orderByRecencyRotation(['a', 'b', 'c'], {
+ dayKey,
+ isRecent: (c) => c === 'a' || c === 'b',
+ });
+ expect(order[0]).toBe('c');
+ expect(order).toHaveLength(3);
+ });
+
+ it('keeps a higher-priority candidate ahead of a rotation preference', () => {
+ const ranked = [{ id: 'weak', rank: 0.2 }, { id: 'mid', rank: 0.6 }, { id: 'strong', rank: 0.9 }];
+ for (const day of ['2026-03-01', '2026-03-02', '2026-03-03']) {
+ expect(orderByRecencyRotation(ranked, { dayKey: day, rank: (c) => c.rank })[0].id).toBe('weak');
+ }
+ });
+
+ it('rotates equally-ranked candidates across days but is stable within one day', () => {
+ const list = ['alpha', 'beta', 'gamma'];
+ const heads = ['2026-03-01', '2026-03-02', '2026-03-03'].map(day => orderByRecencyRotation(list, { dayKey: day })[0]);
+ expect(new Set(heads).size).toBe(3);
+ expect(orderByRecencyRotation(list, { dayKey })).toEqual(orderByRecencyRotation(list, { dayKey }));
+ });
+
+ it('still returns every candidate when all of them are recent, rotating among them', () => {
+ const list = ['alpha', 'beta', 'gamma'];
+ const order = orderByRecencyRotation(list, { dayKey, isRecent: () => true });
+ expect([...order].sort()).toEqual([...list].sort());
+ expect(order[0]).toBe(orderByRecencyRotation(list, { dayKey })[0]);
+ });
+
+ it('returns the only available candidate untouched, recent or not', () => {
+ expect(orderByRecencyRotation(['solo'], { dayKey, isRecent: () => true })).toEqual(['solo']);
+ expect(orderByRecencyRotation([], { dayKey })).toEqual([]);
+ expect(orderByRecencyRotation(null, { dayKey })).toEqual([]);
+ });
+
+ it('falls back to input order when there is no usable day key', () => {
+ const list = ['alpha', 'beta', 'gamma'];
+ expect(orderByRecencyRotation(list, { dayKey: null })).toEqual(list);
+ });
+ });
+});
diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.js
index 76fe9a265a..af5647e58f 100644
--- a/server/routes/meatspacePostRoutes.js
+++ b/server/routes/meatspacePostRoutes.js
@@ -141,6 +141,11 @@ router.get('/post/progress', asyncHandler(async (req, res) => {
* skill re-verifications, the weakest recent skill, and stalled ladder
* progressions — each with a deep link into the exact drill/mode. Never empty
* (falls back to a sensible default when nothing specific is actionable).
+ *
+ * Also returns `recentPractice` (`{ dayKey, drillTypes, memoryItemIds }`), the
+ * three-local-day window used to rotate the heuristic tiers (issue #5319). The
+ * client hands it straight back to `composeQuickSession` so the Quick session
+ * rotates its per-domain picks off exactly the same signal.
*/
router.get('/post/recommendations', asyncHandler(async (req, res) => {
const rawLimit = req.query.limit != null ? parseInt(req.query.limit, 10) : undefined;
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index c8f8524aaf..fdc951914f 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -1274,33 +1274,44 @@ const DRILL_LABEL = (type) =>
String(type || '').replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
/**
- * The single weakest scored drill by recent (windowed) accuracy — the drill
- * whose `byDrillAccuracy` is lowest among drills with at least one sample.
- * Pure; reads the shape `getPostStats` returns. `null` when there's no
- * accuracy signal yet (fresh install / all drills without derivable accuracy).
- * Returns `{ key, module, type, accuracy, samples }` where `key` is
- * `"<module>:<type>"`.
+ * EVERY scored drill with an accuracy signal, ranked weakest-first. Pure; reads
+ * the shape `getPostStats` returns. Empty when there's no accuracy signal yet
+ * (fresh install / all drills without derivable accuracy). Each entry is
+ * `{ key, module, type, accuracy, samples }` where `key` is `"<module>:<type>"`.
+ *
+ * Ranked rather than single-valued because the caller has to keep looking past
+ * the weakest drill when that one is disabled, excluded by `sessionModules`, or
+ * was already practiced inside the recency window (issue #5319) — stopping at
+ * the first candidate is what used to pin the tier to one drill forever.
*/
-export function weakestSkillFromStats(stats) {
+export function weakestSkillsFromStats(stats) {
const acc = stats?.evidenceByDrillAccuracy || stats?.byDrillAccuracy || {};
const counts = stats?.evidenceByDrillCount || stats?.byDrillCount || {};
- let worst = null;
+ const ranked = [];
for (const [key, a] of Object.entries(acc)) {
if (typeof a !== 'number' || Number.isNaN(a)) continue;
const samples = counts[key] || 0;
if (samples < 1) continue;
- if (!worst || a < worst.accuracy) {
- const sep = key.indexOf(':');
- worst = {
- key,
- module: sep >= 0 ? key.slice(0, sep) : null,
- type: sep >= 0 ? key.slice(sep + 1) : key,
- accuracy: a,
- samples,
- };
- }
+ const sep = key.indexOf(':');
+ ranked.push({
+ key,
+ module: sep >= 0 ? key.slice(0, sep) : null,
+ type: sep >= 0 ? key.slice(sep + 1) : key,
+ accuracy: a,
+ samples,
+ });
}
- return worst;
+ // Stable: equal-accuracy drills keep their `Object.entries` order here, and
+ // the day rotation in `orderByRecencyRotation` is what breaks that tie later.
+ return ranked.sort((a, b) => a.accuracy - b.accuracy);
+}
+
+/**
+ * The single weakest scored drill by recent (windowed) accuracy — the head of
+ * `weakestSkillsFromStats`. `null` when there's no accuracy signal yet.
+ */
+export function weakestSkillFromStats(stats) {
+ return weakestSkillsFromStats(stats)[0] || null;
}
/**
@@ -1435,28 +1446,24 @@ export function memoryItemIdFromReview(review) {
* @param {string} [timezone] - user timezone for re-keying legacy ISO dates
* @returns {{ drillTypes: Set<string>, memoryItemIds: Set<string>, completedSession: boolean }}
*/
-export function practicedTodayFromActivity(sessions = [], trainingEntries = [], todayStr = null, timezone) {
+function activityOnDays(sessions, trainingEntries, dayKeys, timezone) {
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, timezone);
- if (!today) return { drillTypes, memoryItemIds, completedSession };
// Both feeds go through recordDayKey, which re-derives the day from each
- // record's own instant in the CURRENT timezone (#4168) — a raw `!==` against
+ // record's own instant in the CURRENT timezone (#4168) — matching against
// the stored `date` would read a record written under a previous timezone (or
// a memory-practice entry carrying a full ISO timestamp) as not-practiced.
for (const session of sessions || []) {
- if (recordDayKey(session, timezone) !== today) continue;
+ if (!dayKeys.has(recordDayKey(session, timezone))) continue;
completedSession = true;
for (const task of session.tasks || []) {
if (task?.type) drillTypes.add(task.type);
}
}
for (const entry of trainingEntries || []) {
- if (recordDayKey(entry, timezone) !== today) continue;
+ if (!dayKeys.has(recordDayKey(entry, timezone))) 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);
@@ -1465,6 +1472,56 @@ export function practicedTodayFromActivity(sessions = [], trainingEntries = [],
return { drillTypes, memoryItemIds, completedSession };
}
+export function practicedTodayFromActivity(sessions = [], trainingEntries = [], todayStr = null, timezone) {
+ // 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, timezone);
+ if (!today) return { drillTypes: new Set(), memoryItemIds: new Set(), completedSession: false };
+ return activityOnDays(sessions, trainingEntries, new Set([today]), timezone);
+}
+
+/**
+ * How many local calendar days the heuristic-tier recency window spans — today
+ * plus the previous two. Wide enough that a drill practiced yesterday yields to
+ * something else, narrow enough that a three-drill rotation still comes back
+ * around every third day.
+ */
+export const RECENT_PRACTICE_WINDOW_DAYS = 3;
+
+/**
+ * What the user has practiced across the last `windowDays` LOCAL calendar days,
+ * from both scored sessions and the training log (issue #5319).
+ *
+ * This is the multi-day sibling of `practicedTodayFromActivity`, and it feeds a
+ * different decision. `practicedToday` demotes an already-completed rec in
+ * EVERY tier — including schedule-driven due memory items and due reviews. This
+ * window only reorders the two HEURISTIC tiers (weakest skill, stalled ladder),
+ * whose signals are windowed averages a single rep barely moves, so the same
+ * drill would otherwise stay pinned to the top slot day after day. A genuinely
+ * due item is never deprioritized by it.
+ *
+ * Pure — exported for unit tests. Carries no prompts or session content, only
+ * drill types and memory item ids, and persists nothing.
+ *
+ * @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`
+ * @param {string} [timezone] - user timezone for re-keying legacy ISO dates
+ * @param {number} [windowDays] - calendar days to look back over, including today
+ * @returns {{ dayKey: string|null, drillTypes: Set<string>, memoryItemIds: Set<string> }}
+ */
+export function recentPracticeFromActivity(sessions = [], trainingEntries = [], todayStr = null, timezone, windowDays = RECENT_PRACTICE_WINDOW_DAYS) {
+ // No resolvable local day ⇒ no window, and callers fall back to plain
+ // priority order rather than rotating off a guessed day.
+ const today = normalizeYmd(todayStr, timezone);
+ if (!today) return { dayKey: null, drillTypes: new Set(), memoryItemIds: new Set() };
+
+ const span = Math.max(1, Math.trunc(windowDays) || 1);
+ const days = new Set(Array.from({ length: span }, (_, i) => ymdShift(today, -i)));
+ const { drillTypes, memoryItemIds } = activityOnDays(sessions, trainingEntries, days, timezone);
+ return { dayKey: today, drillTypes, memoryItemIds };
+}
+
export function composePostRecommendations({
dueMemoryItems = [],
dueReviews = [],
diff --git a/server/services/meatspacePostRecommendations.js b/server/services/meatspacePostRecommendations.js
index 19eccb3e93..be7879b8f2 100644
--- a/server/services/meatspacePostRecommendations.js
+++ b/server/services/meatspacePostRecommendations.js
@@ -12,13 +12,15 @@ import {
getMultiplicationProgress,
getPowersProgress,
getCognitiveProgress,
- weakestSkillFromStats,
+ weakestSkillsFromStats,
stalledProgressions,
isRecDrillRunnable,
memoryItemIdFromReview,
composePostRecommendations,
practicedTodayFromActivity,
+ recentPracticeFromActivity,
} from './meatspacePost.js';
+import { orderByRecencyRotation } from '../lib/postRotation.js';
import { MASTERY_DEFAULTS } from '../lib/postMultiplicationLadder.js';
import { isMemoryItemEnabled, resolveTopicForDrillType } from '../lib/postTopics.js';
import { getDueMemoryItems } from './meatspacePostMemory.js';
@@ -51,12 +53,25 @@ export async function getPostRecommendations({ limit = RECOMMENDATION_LIMIT } =
]);
const todayStr = todayInTimezone(timezone, atDate);
- let weakestSkill = weakestSkillFromStats(stats);
- if (weakestSkill) {
- weakestSkill = isRecDrillRunnable(config, weakestSkill.module, weakestSkill.type)
- ? { ...weakestSkill, deepLink: weakestSkill.module === 'memory' ? '/post/memory' : '/post/launcher' }
- : null;
- }
+ // Multi-day window that varies the HEURISTIC tiers only (issue #5319). The
+ // schedule-driven tiers below never consult it — a genuinely due item still
+ // wins the top slot even when it was practiced yesterday.
+ const recentPractice = recentPracticeFromActivity(sessions, training, todayStr, timezone);
+ const practicedRecently = (drillType) => Boolean(drillType) && recentPractice.drillTypes.has(drillType);
+
+ // Every ranked candidate is filtered for runnability BEFORE selection, so a
+ // disabled or module-excluded weakest drill no longer sinks the whole tier —
+ // the next eligible one takes its place (issue #5319).
+ const runnableWeakest = weakestSkillsFromStats(stats)
+ .filter((skill) => isRecDrillRunnable(config, skill.module, skill.type))
+ .map((skill) => ({ ...skill, deepLink: skill.module === 'memory' ? '/post/memory' : '/post/launcher' }));
+ const weakestSkill = orderByRecencyRotation(runnableWeakest, {
+ dayKey: recentPractice.dayKey,
+ isRecent: (skill) => practicedRecently(skill.type),
+ // Accuracy IS the priority here — rotation only breaks ties between drills
+ // the user is equally weak at, so a genuinely weaker skill still leads.
+ rank: (skill) => skill.accuracy,
+ })[0] || null;
const enabledDueMemoryItems = dueMemoryItems
.filter((item) => isMemoryItemEnabled(config, item.id));
@@ -64,11 +79,18 @@ export async function getPostRecommendations({ limit = RECOMMENDATION_LIMIT } =
if (review.kind === 'memory') return isMemoryItemEnabled(config, memoryItemIdFromReview(review));
return isRecDrillRunnable(config, recModuleForDrillType(review.drillType, 'cognitive'), review.drillType);
});
- const stalled = stalledProgressions(mulProgress, powersProgress, cogProgress, {
+ const runnableStalled = stalledProgressions(mulProgress, powersProgress, cogProgress, {
kochLevel: morse?.kochLevel,
kochLevelSet: morse?.kochLevelSet,
maxKochLevel: MAX_KOCH_LEVEL,
}).filter((stall) => isRecDrillRunnable(config, recModuleForDrillType(stall.drillType, 'cognitive'), stall.drillType));
+ // Every stalled ladder is equally "N reps from the next rung", so this tier
+ // has no intrinsic priority — it used to resolve to ladder-construction order
+ // and pin one drill. Recency first, then a day rotation across the rest.
+ const stalled = orderByRecencyRotation(runnableStalled, {
+ dayKey: recentPractice.dayKey,
+ isRecent: (stall) => practicedRecently(stall.drillType),
+ });
return {
recommendations: composePostRecommendations({
@@ -80,5 +102,13 @@ export async function getPostRecommendations({ limit = RECOMMENDATION_LIMIT } =
practicedToday: practicedTodayFromActivity(sessions, training, todayStr, timezone),
limit,
}),
+ // The client's Quick-session composer rotates its own domain picks off the
+ // same window and day key, so both surfaces agree on what counts as
+ // "already practiced lately". Sets are serialized as arrays for JSON.
+ recentPractice: {
+ dayKey: recentPractice.dayKey,
+ drillTypes: [...recentPractice.drillTypes],
+ memoryItemIds: [...recentPractice.memoryItemIds],
+ },
};
}
diff --git a/server/services/meatspacePostRecommendations.test.js b/server/services/meatspacePostRecommendations.test.js
index 579d8a4a60..febee95f4a 100644
--- a/server/services/meatspacePostRecommendations.test.js
+++ b/server/services/meatspacePostRecommendations.test.js
@@ -42,6 +42,8 @@ import {
memoryPracticeDeepLink,
memoryItemIdFromReview,
practicedTodayFromActivity,
+ recentPracticeFromActivity,
+ weakestSkillsFromStats,
} from './meatspacePost.js';
import { atomicWrite } from '../lib/fileUtils.js';
@@ -674,3 +676,147 @@ describe('memoryItemIdFromReview', () => {
expect(memoryItemIdFromReview(null)).toBeNull();
});
});
+
+// Issue #5319: the heuristic tiers (weakest skill, stalled ladder) are driven by
+// windowed averages a single rep barely moves, so before this they resolved to
+// one fixed drill and the daily routine handed back the same practice every day.
+describe('recentPracticeFromActivity (issue #5319)', () => {
+ const day = (offset) => new Date(Date.UTC(2026, 2, 10 - offset)).toISOString().slice(0, 10);
+
+ it('collects drill types and memory items across the three-day window, from BOTH feeds', () => {
+ const recent = recentPracticeFromActivity(
+ [{ date: day(1), tasks: [{ type: 'digit-span' }] }],
+ [
+ { date: day(2), drillType: 'morse-copy' },
+ { date: day(0), memoryItemId: 'elements-song' },
+ ],
+ day(0),
+ 'UTC',
+ );
+ expect(recent.dayKey).toBe(day(0));
+ expect([...recent.drillTypes].sort()).toEqual(['digit-span', 'morse-copy']);
+ expect([...recent.memoryItemIds]).toEqual(['elements-song']);
+ });
+
+ it('excludes activity older than the window so a rotation comes back around', () => {
+ const recent = recentPracticeFromActivity(
+ [{ date: day(3), tasks: [{ type: 'digit-span' }] }],
+ [],
+ day(0),
+ 'UTC',
+ );
+ expect(recent.drillTypes.has('digit-span')).toBe(false);
+ });
+
+ it('re-derives each record\'s day in the CURRENT timezone, not its stored date', () => {
+ // Written under a UTC-ish zone as "the 10th", but its instant is the 11th in
+ // Tokyo — the window must read it as the local day it actually happened on.
+ const recent = recentPracticeFromActivity(
+ [{ date: '2026-03-10', startedAt: '2026-03-10T16:00:00.000Z', tasks: [{ type: 'n-back' }] }],
+ [],
+ '2026-03-11',
+ 'Asia/Tokyo',
+ );
+ expect(recent.drillTypes.has('n-back')).toBe(true);
+ });
+
+ it('reports an empty window rather than guessing when the local day is unresolvable', () => {
+ const recent = recentPracticeFromActivity([{ date: day(0), tasks: [{ type: 'n-back' }] }], [], null, 'UTC');
+ expect(recent.dayKey).toBeNull();
+ expect(recent.drillTypes.size).toBe(0);
+ });
+});
+
+describe('weakestSkillsFromStats ranking (issue #5319)', () => {
+ it('ranks every sampled drill weakest-first so the caller can skip ineligible ones', () => {
+ const stats = {
+ byDrillAccuracy: { 'cognitive:digit-span': 0.4, 'mental-math:powers': 0.6, 'cognitive:n-back': 0.5 },
+ byDrillCount: { 'cognitive:digit-span': 3, 'mental-math:powers': 3, 'cognitive:n-back': 3 },
+ };
+ expect(weakestSkillsFromStats(stats).map(s => s.type)).toEqual(['digit-span', 'n-back', 'powers']);
+ // The single-value helper stays the head of that list.
+ expect(weakestSkillFromStats(stats).type).toBe('digit-span');
+ });
+});
+
+describe('getPostRecommendations drill rotation (issue #5319)', () => {
+ // Two enabled cognitive drills, both scored, both stalled — the exact shape
+ // that used to pin digit-span to the #1 slot indefinitely.
+ const scored = (date, type, accuracy) => ({
+ id: `s-${date}-${type}`, date, score: Math.round(accuracy * 100), durationMs: 60000,
+ tasks: [{ module: 'cognitive', type, score: Math.round(accuracy * 100), accuracy, completion: 1, questions: [{ answered: 'x', correct: false }] }],
+ });
+ // Memory off so the drill-shaped recs are the whole list.
+ const drillsOnlyConfig = { memory: { enabled: false }, topics: { memory: { enabled: false } } };
+
+ beforeEach(() => {
+ settingsState.timezone = 'UTC';
+ state.config = drillsOnlyConfig;
+ });
+
+ it('advances the top recommendation across days instead of repeating one drill', async () => {
+ vi.useFakeTimers();
+ // Baseline history OUTSIDE the three-day window, so both drills carry an
+ // accuracy signal and neither starts out "recently practiced".
+ state.sessions = [scored('2026-03-04', 'digit-span', 0.4), scored('2026-03-04', 'n-back', 0.4)];
+
+ const heads = [];
+ // Three consecutive days. Each day the user practices whatever was
+ // recommended, which is what feeds the next day's recency window.
+ for (const today of ['2026-03-10', '2026-03-11', '2026-03-12']) {
+ vi.setSystemTime(new Date(`${today}T12:00:00.000Z`));
+ const { recommendations } = await getPostRecommendations();
+ const head = recommendations[0];
+ expect(head.drillType, 'expected a drill-shaped top recommendation').toBeTruthy();
+ heads.push(head.drillType);
+ state.sessions = [...state.sessions, scored(today, head.drillType, 0.4)];
+ }
+ // Nothing is served two days running, and the rotation actually varies.
+ expect(new Set(heads).size).toBeGreaterThan(1);
+ expect(heads[0]).not.toBe(heads[1]);
+ expect(heads[1]).not.toBe(heads[2]);
+ });
+
+ it('picks the next eligible weakest skill when the lowest-accuracy one is excluded', async () => {
+ const today = new Date().toISOString().slice(0, 10);
+ state.sessions = [scored(today, 'digit-span', 0.3), scored(today, 'n-back', 0.5)];
+ // digit-span is weakest but the user switched that ONE drill off — the tier
+ // must walk past it rather than dropping the whole weak-skill slot.
+ state.config = { ...drillsOnlyConfig, cognitive: { drillTypes: { 'digit-span': { enabled: false } } } };
+
+ const { recommendations } = await getPostRecommendations();
+ const weak = recommendations.find(r => r.kind === 'weak-skill');
+ expect(weak?.drillType).toBe('n-back');
+ });
+
+ it('never deprioritizes a genuinely due memory item for being practiced yesterday', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-03-11T12:00:00.000Z'));
+ state.config = {};
+ state.memoryItems = [{
+ id: 'raven', title: 'Example Poem', type: 'poem', content: { chunks: [] },
+ schedule: { ease: 2.5, intervalDays: 1, nextReview: '2026-03-10T00:00:00.000Z' },
+ mastery: { overallPct: 40, chunks: {} },
+ }];
+ // Practiced YESTERDAY (inside the heuristic window) but not today, so the
+ // unchanged same-day demotion doesn't apply either.
+ state.training = [{ date: '2026-03-10', memoryItemId: 'raven', mode: 'spaced' }];
+
+ const { recommendations } = await getPostRecommendations();
+ expect(recommendations[0].kind).toBe('memory-due');
+ expect(recommendations[0].practicedToday).toBe(false);
+ expect(recommendations.find(r => r.id === 'memory-due:raven')).toBeTruthy();
+ });
+
+ it('reports the window it used so the client rotates Quick session off the same signal', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-03-11T12:00:00.000Z'));
+ state.sessions = [scored('2026-03-10', 'digit-span', 0.4)];
+ state.training = [{ date: '2026-03-11', memoryItemId: 'elements-song', mode: 'spaced' }];
+
+ const { recentPractice } = await getPostRecommendations();
+ expect(recentPractice.dayKey).toBe('2026-03-11');
+ expect(recentPractice.drillTypes).toContain('digit-span');
+ expect(recentPractice.memoryItemIds).toContain('elements-song');
+ });
+});