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

feat: vary daily POST challenges and revisit missed elements

[._.]/ Adam Eivyc5bcf1c322b1
diff --git a/client/src/components/meatspace/post/ElementsSong.jsx b/client/src/components/meatspace/post/ElementsSong.jsx
index fd80bcaa5d..25a0656b68 100644
--- a/client/src/components/meatspace/post/ElementsSong.jsx
+++ b/client/src/components/meatspace/post/ElementsSong.jsx
@@ -1,3 +1,4 @@
+import { shuffle } from '../../../../../server/lib/arrayUtils.js';
import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { ChevronLeft, ChevronRight, BookOpen, Zap, Target, Check, X, SkipForward, Loader, Search, Eye, BarChart3, Gauge, Layers, RotateCw, ShieldCheck } from 'lucide-react';
import { submitMemoryPractice, getMemoryMastery, getMemoryItem, attestMemoryMastery } from '../../../services/api';
@@ -699,7 +700,7 @@ function LearnMode({ item, onBack, onComplete }) {
// Element [symbol, info] entries ordered weakest-mastery-first, so both the
// study deck and the flash quiz surface the least-known elements first.
function weakestFirstElements(elementMap, mastery) {
- return Object.entries(elementMap).sort((a, b) => {
+ return shuffle(Object.entries(elementMap)).sort((a, b) => {
const progressA = elementMasteryProgress(mastery.elements?.[a[0]]);
const progressB = elementMasteryProgress(mastery.elements?.[b[0]]);
return progressA.accuracy - progressB.accuracy;
@@ -877,18 +878,17 @@ function ElementStudyMode({ item, mastery, onBack, onComplete }) {
function ElementFlashMode({ item, mastery, onBack, onComplete }) {
const elementMap = item.content?.elementMap || {};
- // Build the quiz once per item/mastery — without memoization the Math.random()
- // shuffle below re-runs on every render (e.g. each keystroke), reshuffling the
- // deck and swapping the current question mid-answer.
- const questions = useMemo(() => {
- // Prioritize weak elements, then shuffle the weakest slice for quiz variety.
- return weakestFirstElements(elementMap, mastery).slice(0, 15).sort(() => Math.random() - 0.5).map(([symbol, info]) => {
+ // Own the queue for this mounted practice session so answers can schedule
+ // retries without reshuffling the current question on each keystroke.
+ const [questions, setQuestions] = useState(() => {
+ // Randomize ties before choosing the weak slice, then interleave the deck.
+ return shuffle(weakestFirstElements(elementMap, mastery).slice(0, 15)).map(([symbol, info]) => {
const askSymbol = Math.random() > 0.5;
return askSymbol
? { prompt: info.name, expected: symbol, element: symbol, label: 'What symbol?' }
: { prompt: `${symbol} (${info.atomicNumber})`, expected: info.name, element: symbol, label: 'What element?' };
});
- }, [elementMap, mastery]);
+ });
const [idx, setIdx] = useState(0);
const [answer, setAnswer] = useState('');
@@ -935,7 +935,7 @@ function ElementFlashMode({ item, mastery, onBack, onComplete }) {
if (idx >= questions.length) {
const correct = results.filter(r => r.correct).length;
- const pct = Math.round((correct / results.length) * 100);
+ const pct = results.length ? Math.round((correct / results.length) * 100) : 0;
const scoreColor = pct >= 80 ? 'text-port-success' : pct >= 50 ? 'text-port-warning' : 'text-port-error';
return (
@@ -972,7 +972,25 @@ function ElementFlashMode({ item, mastery, onBack, onComplete }) {
const q = questions[idx];
function check(skipped = false) {
+ if (showResult) return;
const isCorrect = !skipped && answer.trim().toLowerCase() === q.expected.toLowerCase();
+ // Corrective feedback now, retrieval after three other questions. Each
+ // target gets at most two retries; the whole practice stays under 45 turns.
+ if (!isCorrect && (q.retry || 0) < 2) {
+ setQuestions(previous => {
+ const deck = [...previous];
+ const alternatives = previous.filter(candidate => candidate.element !== q.element);
+ if (!alternatives.length) return deck;
+ const gap = 3;
+ const missing = Math.max(0, gap - (deck.length - idx - 1));
+ if (deck.length + missing + 1 > 45) return deck;
+ for (let i = 0; i < missing; i++) {
+ deck.push({ ...alternatives[i % alternatives.length], retry: 2 });
+ }
+ deck.splice(idx + gap + 1, 0, { ...q, retry: (q.retry || 0) + 1 });
+ return deck;
+ });
+ }
setResults(prev => [...prev, { correct: isCorrect, expected: q.expected, answered: answer.trim(), element: q.element }]);
setShowResult(isCorrect ? 'correct' : 'wrong');
}
@@ -987,6 +1005,7 @@ function ElementFlashMode({ item, mastery, onBack, onComplete }) {
<span className="text-gray-500 text-sm ml-auto">{idx + 1} / {questions.length}</span>
</div>
+ <p className="text-sm text-gray-400">Missed pairs return after other questions for another recall attempt. Up to 45 questions; unfinished learning carries into future practice.</p>
<div className="w-full h-1.5 bg-port-border rounded-full overflow-hidden">
<div className="h-full bg-emerald-500 rounded-full transition-all" style={{ width: `${((idx + 1) / questions.length) * 100}%` }} />
</div>
@@ -997,7 +1016,7 @@ function ElementFlashMode({ item, mastery, onBack, onComplete }) {
{showResult ? (
<div className={`mt-6 text-lg font-medium ${showResult === 'correct' ? 'text-port-success' : 'text-port-error'}`}>
- {showResult === 'correct' ? 'Correct!' : `Wrong — answer: ${q.expected}`}
+ {showResult === 'correct' ? 'Correct!' : `Answer: ${q.expected}. Study this pairing before continuing.`}
</div>
) : (
<input
diff --git a/client/src/components/meatspace/post/ElementsSong.test.jsx b/client/src/components/meatspace/post/ElementsSong.test.jsx
index 7d0f3d8aed..6a7aafd59d 100644
--- a/client/src/components/meatspace/post/ElementsSong.test.jsx
+++ b/client/src/components/meatspace/post/ElementsSong.test.jsx
@@ -269,7 +269,7 @@ describe('ElementsSong — Element Flash recall test', () => {
// gone) must advance to question 2 rather than doing nothing.
fireEvent.keyDown(window, { key: 'Enter' });
await settle();
- expect(screen.getByText('2 / 2')).toBeInTheDocument();
+ expect(screen.getByText('2 / 5')).toBeInTheDocument();
expect(screen.getByRole('textbox')).toBeInTheDocument();
});
@@ -293,11 +293,85 @@ describe('ElementsSong — Element Flash recall test', () => {
const nextBtn = screen.getByText('Next');
fireEvent.keyDown(nextBtn, { key: 'Enter' });
await settle();
- expect(screen.getByText('1 / 2')).toBeInTheDocument();
+ expect(screen.getByText('1 / 5')).toBeInTheDocument();
// A genuine click on Next still advances exactly once.
fireEvent.click(nextBtn);
await settle();
- expect(screen.getByText('2 / 2')).toBeInTheDocument();
+ expect(screen.getByText('2 / 5')).toBeInTheDocument();
});
});
+
+
+describe('Element Flash learning cadence', () => {
+ it('interleaves a missed pairing with three questions, then saves both retrieval attempts', async () => {
+ const deck = { ...item, content: { ...item.content, elementMap: {
+ ...item.content.elementMap,
+ Li: { name: 'Lithium', atomicNumber: 3 },
+ Be: { name: 'Beryllium', atomicNumber: 4 },
+ } } };
+ render(<ElementsSong item={deck} mode="element-flash" onBack={() => {}} />);
+ await settle();
+ const current = () => {
+ const label = screen.getByText(/What (symbol|element)\?/);
+ const prompt = label.previousElementSibling.textContent;
+ const [symbol, info] = Object.entries(deck.content.elementMap).find(([sym, info]) =>
+ prompt === info.name || prompt.startsWith(`${sym} (`));
+ return { symbol, answer: label.textContent === 'What symbol?' ? symbol : info.name };
+ };
+ const missed = current().symbol;
+ fireEvent.click(screen.getByRole('button', { name: 'Skip' }));
+ expect(screen.getByText(/Answer: .*Study this pairing/)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Next' }));
+ for (let i = 0; i < 3; i++) {
+ expect(current().symbol).not.toBe(missed);
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: current().answer } });
+ fireEvent.click(screen.getByRole('button', { name: 'Check' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Next' }));
+ }
+ expect(current().symbol).toBe(missed);
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: current().answer } });
+ fireEvent.click(screen.getByRole('button', { name: 'Check' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Next' }));
+ fireEvent.click(screen.getByText('Save Progress'));
+ await settle();
+ const attempts = submitMemoryPractice.mock.calls[0][1].results;
+ expect(attempts).toHaveLength(5);
+ expect(attempts.filter(r => r.element === missed).map(r => r.correct)).toEqual([false, true]);
+ });
+
+ it('finishes within 45 turns even when every answer is missed', async () => {
+ render(<ElementsSong item={item} mode="element-flash" onBack={() => {}} />);
+ await settle();
+ let turns = 0;
+ while (screen.queryByRole('button', { name: 'Skip' }) && turns < 46) {
+ fireEvent.click(screen.getByRole('button', { name: 'Skip' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Next' }));
+ turns++;
+ }
+ expect(turns).toBeLessThanOrEqual(45);
+ expect(screen.getByText('Element Flash Complete')).toBeInTheDocument();
+ });
+});
+
+
+it('samples beyond the first fifteen equally weak elements before building the quiz', async () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);
+ const elementMap = Object.fromEntries(Array.from({ length: 20 }, (_, i) =>
+ [`E${i}`, { name: `Example Element ${i}`, atomicNumber: i }]));
+ render(<ElementsSong item={{ ...item, content: { ...item.content, elementMap } }} mode="element-flash" onBack={() => {}} />);
+ await settle();
+ const seen = [];
+ for (let i = 0; i < 15; i++) {
+ const prompt = screen.getByText('What element?').previousElementSibling.textContent;
+ const symbol = prompt.split(' ')[0];
+ seen.push(symbol);
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: elementMap[symbol].name } });
+ fireEvent.click(screen.getByRole('button', { name: 'Check' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Next' }));
+ }
+ random.mockRestore();
+ expect(seen).toContain('E15');
+ expect(new Set(seen).size).toBe(15);
+ expect(screen.getByText('Element Flash Complete')).toBeInTheDocument();
+});
diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.js
index 51dc04e9b9..f1864f8db8 100644
--- a/client/src/services/apiMeatspace.js
+++ b/client/src/services/apiMeatspace.js
@@ -190,7 +190,7 @@ export const getPostReviewReps = (limit, options = {}) => request(
export const getPostRecommendations = (limit, options = {}) => request(
`/meatspace/post/recommendations${limit != null ? `?limit=${limit}` : ''}`,
{ silent: true, ...options }
-);
+).then(result => ({ ...result, recommendations: result.dailyRecommendations ?? result.recommendations }));
export const getPostMultiplicationProgress = () => request('/meatspace/post/multiplication-progress');
export const getPostPowersProgress = () => request('/meatspace/post/powers-progress');
// `options` so a caller with its own catch can pass `{ silent: true }` and not
diff --git a/client/src/services/apiMeatspace.test.js b/client/src/services/apiMeatspace.test.js
index 9f44c1d7a9..398b71dc86 100644
--- a/client/src/services/apiMeatspace.test.js
+++ b/client/src/services/apiMeatspace.test.js
@@ -83,3 +83,16 @@ describe('apiMeatspace double-toast wrappers forward options', () => {
});
});
// @vitest-environment node
+
+
+it('uses the daily mix for every recommendation consumer and falls back on older servers', async () => {
+ const { getPostRecommendations } = await import('./apiMeatspace.js');
+ const legacy = [{ id: 'memory-due:example' }];
+ const daily = [{ id: 'daily:n-back' }];
+ request.mockResolvedValue({ recommendations: legacy, dailyRecommendations: daily });
+ expect((await getPostRecommendations(1)).recommendations).toEqual(daily);
+ request.mockResolvedValue({ recommendations: legacy, dailyRecommendations: [] });
+ expect((await getPostRecommendations()).recommendations).toEqual([]);
+ request.mockResolvedValue({ recommendations: legacy });
+ expect((await getPostRecommendations()).recommendations).toEqual(legacy);
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 89c6f0073c..9c106e22bc 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -464,7 +464,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `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`. |
+| `postRotation.js` | Pure deterministic day-based rotation for POST practice selection — `shuffleForDay` supplies a stable pseudorandom daily mix; `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. |
@@ -512,7 +512,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `sourceScan.js` | Lexer-assisted primitives shared by the whole-tree source-scan guard suites, so the timer rule and the socket rule cannot drift on what "owns its rejection" means. `blankLiterals(src)` blanks comment/string/template/regex CONTENT to spaces while preserving length, so a brace inside a literal cannot skew a bracket walk and a caller can still read a literal (a socket event name) out of the original string at the same offset; `matchBracket(src, open)` returns the index past the matching `)`/`]`/`}`; `parseCallbackAt(blanked, from, limit)` parses the function expression at `from` (`async`/`function`/either arrow spelling, skipping the parameter list as a unit so a `= {}` default is not mistaken for the body) and returns `{isAsync, start, text}`; `unguardedAwaits(body)` returns the awaited chains that neither sit inside a `try`/`catch` nor END in `.catch(…)`. `blankComments(src)` is the weaker LINE-based stripper the per-line `child_process` rule needs. Callers: `childProcess.guards.test.js`, `server/timerCallbackConventions.test.js`, `server/sockets/asyncHandlerGuard.test.js`, `server/process-safety-net.test.js`. |
| `apiOperationContracts.js` | Detailed operation metadata for intentionally public APIs. It consumes the canonical route Zod contracts and feeds both public and internal OpenAPI documents. |
| `apiRegistry.js` | Single source of truth for which PortOS services are externally-callable HTTP APIs (`voice`, `sdapi`). `API_REGISTRY` declares each API's `publicPrefixes` (read/compute-safe surface only) + defaults; `isRegistryPublic(settings, path)` tells `authGate` when an `exposed && !requireAuth` API re-opens its prefix; `resolveApiAccess(settings)` merges persisted `apiAccess` flags for the Settings UI + OpenAPI docs. |
-| `arrayUtils.js` | `shuffle(arr)` — Fisher-Yates shuffle (new array, never mutates). The canonical uniform shuffle — never `arr.sort(() => Math.random() - 0.5)`, which is biased. Shared by `meatspacePostCognitive.js` (Schulte table / mental rotation) and `meatspacePostMemory.js` (memory drill generators). `dedupeByKey(items, keyOf, pick?)` — one survivor per key, first-seen order. **Required before any multi-row `INSERT … ON CONFLICT (key) DO UPDATE`**: Postgres refuses the whole statement ("ON CONFLICT DO UPDATE command cannot affect row a second time") when its VALUES list names one conflict key twice, and the rows a batcher joins usually come from something that promises no uniqueness (a disk scan, a peer payload). `DO NOTHING` upserts are exempt. `pick(held, candidate)` defaults to last-seen-wins (what a sequential one-row upsert loop leaves); pass a comparator when the table's conflict rule isn't "latest write" — `memorySync.applyRemoteChanges` keeps the newest `updatedAt` so a peer's payload ordering can't flip a last-writer-wins outcome. Used by `services/mediaAssetIndex/db.js` and `services/memorySync.js`. |
+| `arrayUtils.js` | `shuffle(arr, random?)` — Fisher-Yates shuffle (new array, never mutates). The canonical uniform shuffle — never `arr.sort(() => Math.random() - 0.5)`, which is biased. Shared by `meatspacePostCognitive.js` (Schulte table / mental rotation) and `meatspacePostMemory.js` (memory drill generators). `dedupeByKey(items, keyOf, pick?)` — one survivor per key, first-seen order. **Required before any multi-row `INSERT … ON CONFLICT (key) DO UPDATE`**: Postgres refuses the whole statement ("ON CONFLICT DO UPDATE command cannot affect row a second time") when its VALUES list names one conflict key twice, and the rows a batcher joins usually come from something that promises no uniqueness (a disk scan, a peer payload). `DO NOTHING` upserts are exempt. `pick(held, candidate)` defaults to last-seen-wins (what a sequential one-row upsert loop leaves); pass a comparator when the table's conflict rule isn't "latest write" — `memorySync.applyRemoteChanges` keeps the newest `updatedAt` so a peer's payload ordering can't flip a last-writer-wins outcome. Used by `services/mediaAssetIndex/db.js` and `services/memorySync.js`. |
| `assetRoutePrefixes.js` | Import-free leaf holding the URL prefixes the server owns: `ASSET_ROUTE_PREFIXES` (every `/data/**` static mount) and `SERVER_OWNED_PREFIXES` (what must never reach the SPA fallback, each with the exact `spaPaths` that ARE client routes). `scripts/dev-proxy-drift.test.js` checks the dev proxy's `^/data/` wildcard against the mounts, pins the route-registration order in `server/index.js` (a router added below the terminators is shadowed), and fails if a client route — from `NAV_COMMANDS` or `App.jsx`'s nested `<Route>` tree — is ever added under a server-owned prefix without being declared. |
| `asyncMutex.js` | Promise-based async mutex. |
| `concurrencyGate.js` | `createConcurrencyGate(limit)` → `run(fn)` — cap on simultaneous async work for ONE module-scoped budget, released FIFO. Sibling to `mapWithConcurrency.js`, which caps in-flight work *within one array map*; a gate is shared state, so several call sites fanning out at the same remote respect one budget instead of each respecting its own while the host sees the sum. `createMutex` (`asyncMutex.js`) is this with `limit` fixed at 1 — prefer it for mutual exclusion. Note the budget is per-MODULE, not per-host: two modules calling one host each get their own gate. Used by `huggingFaceCatalog.js` (4) and `ollamaRegistryCatalog.js` (16), whose cold catalog-enrichment bursts otherwise arrive at a free public API as a thundering herd — which the Hub answers with an HTTP/2 GOAWAY that surfaces as a bare `fetch failed`. |
diff --git a/server/lib/arrayUtils.js b/server/lib/arrayUtils.js
index a76022808b..1afd908314 100644
--- a/server/lib/arrayUtils.js
+++ b/server/lib/arrayUtils.js
@@ -9,10 +9,10 @@
* (that comparator violates the sort contract and skews toward certain
* permutations depending on the engine's sort algorithm).
*/
-export function shuffle(arr) {
+export function shuffle(arr, random = Math.random) {
const out = [...arr];
for (let i = out.length - 1; i > 0; i--) {
- const j = Math.floor(Math.random() * (i + 1));
+ const j = Math.floor(random() * (i + 1));
[out[i], out[j]] = [out[j], out[i]];
}
return out;
diff --git a/server/lib/postRotation.js b/server/lib/postRotation.js
index eed438d65b..642a53da05 100644
--- a/server/lib/postRotation.js
+++ b/server/lib/postRotation.js
@@ -1,3 +1,5 @@
+import { shuffle } from './arrayUtils.js';
+
/**
* Deterministic day-based rotation for POST practice selection (issue #5319).
*
@@ -6,7 +8,7 @@
* 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).
+ * the same inputs. The daily mix uses seeded randomness to stay reproducible.
*
* Pure and dependency-free: `client/src/lib/postRotation.js` re-exports it, so
* the server's recommendation tiers and the client's Quick-session domain picks
@@ -87,3 +89,14 @@ export function orderByRecencyRotation(candidates, { dayKey = null, isRecent = (
}
return out.map(entry => entry.candidate);
}
+
+/** Stable pseudorandom daily order; selection does not move after each answer. */
+export function shuffleForDay(candidates, dayKey) {
+ let seed = dayOrdinal(dayKey) ?? 0;
+ return shuffle(candidates, () => {
+ seed = (seed + 0x6D2B79F5) | 0;
+ let value = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ value ^= value + Math.imul(value ^ (value >>> 7), 61 | value);
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
+ });
+}
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index f902501a8a..a32c608e40 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -1461,6 +1461,7 @@ function activityOnDays(sessions, trainingEntries, dayKeys, timezone) {
completedSession = true;
for (const task of session.tasks || []) {
if (task?.type) drillTypes.add(task.type);
+ if (task?.memoryItemId) memoryItemIds.add(task.memoryItemId);
}
}
for (const entry of trainingEntries || []) {
diff --git a/server/services/meatspacePostRecommendations.js b/server/services/meatspacePostRecommendations.js
index eea7297387..bc133d3410 100644
--- a/server/services/meatspacePostRecommendations.js
+++ b/server/services/meatspacePostRecommendations.js
@@ -17,13 +17,14 @@ import {
memoryItemIdFromReview,
composePostRecommendations,
practicedTodayFromActivity,
+ memoryPracticeDeepLink,
recentPracticeFromActivity,
} from './meatspacePost.js';
import { getPostStats } from './meatspacePostStats.js';
-import { orderByRecencyRotation } from '../lib/postRotation.js';
+import { orderByRecencyRotation, shuffleForDay } from '../lib/postRotation.js';
import { MASTERY_DEFAULTS } from '../lib/postMultiplicationLadder.js';
-import { isMemoryItemEnabled, resolveTopicForDrillType } from '../lib/postTopics.js';
-import { getDueMemoryItems } from './meatspacePostMemory.js';
+import { POST_TOPICS, isMemoryItemEnabled, resolveTopicForDrillType } from '../lib/postTopics.js';
+import { getDueMemoryItems, getMemoryItems, isMemoryItemDue } from './meatspacePostMemory.js';
import { getDueReviews } from './meatspacePostReview.js';
import { getAllTrainingEntries } from './postTrainingLogStore.js';
import { getMorseProgress, MAX_KOCH_LEVEL } from './meatspacePostMorse.js';
@@ -92,14 +93,43 @@ export async function getPostRecommendations({ limit = RECOMMENDATION_LIMIT } =
isRecent: (stall) => practicedRecently(stall.drillType),
});
+ // Build the daily set independently of mastery signals. Keep items practiced
+ // today in the pool after their due date advances, so completion cannot swap
+ // another challenge into the day's fixed five slots.
+ const practicedToday = practicedTodayFromActivity(sessions, training, todayStr, timezone);
+ const memoryItems = await getMemoryItems();
+ const dailyPool = POST_TOPICS.filter(topic => topic.module !== 'memory').flatMap(topic =>
+ topic.drillTypes.filter(type => isRecDrillRunnable(config, topic.module || topic.id, type)).map(type => ({
+ id: `daily:${type}`, kind: 'daily-mix',
+ title: type.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase()),
+ detail: "Today's challenge mix", drillType: type,
+ deepLink: topic.id === 'morse' ? `/post/morse/${type.replace('morse-', '')}` : '/post/launcher',
+ practicedToday: practicedToday.drillTypes.has(type),
+ })));
+ dailyPool.push(...memoryItems.filter(item =>
+ isRecDrillRunnable(config, 'memory', item.id === 'elements-song' ? 'memory-element-flash' : 'memory-sequence', item.id)
+ && (isMemoryItemDue(item, atDate) || practicedToday.memoryItemIds.has(item.id))
+ ).map(item => ({
+ id: `daily:memory:${item.id}`, kind: 'daily-mix', title: `Practice "${item.title}"`,
+ detail: 'Spaced-repetition practice', memoryItemId: item.id, drillType: null,
+ deepLink: memoryPracticeDeepLink(item.id),
+ practicedToday: practicedToday.memoryItemIds.has(item.id),
+ })));
+ const dailyRecommendations = shuffleForDay(dailyPool.sort((a, b) => a.id.localeCompare(b.id)), todayStr)
+ .slice(0, RECOMMENDATION_LIMIT)
+ .sort((a, b) => Number(a.practicedToday) - Number(b.practicedToday))
+ .slice(0, Math.max(1, limit))
+ .map((rec, priority) => ({ ...rec, priority }));
+
return {
+ dailyRecommendations,
recommendations: composePostRecommendations({
dueMemoryItems: enabledDueMemoryItems,
dueReviews: enabledDueReviews,
weakestSkill,
stalled,
hasHistory: sessions.length > 0,
- practicedToday: practicedTodayFromActivity(sessions, training, todayStr, timezone),
+ practicedToday,
limit,
}),
// The client's Quick-session composer rotates its own domain picks off the
diff --git a/server/services/meatspacePostRecommendations.test.js b/server/services/meatspacePostRecommendations.test.js
index 2864c445e7..950a569944 100644
--- a/server/services/meatspacePostRecommendations.test.js
+++ b/server/services/meatspacePostRecommendations.test.js
@@ -820,3 +820,40 @@ describe('getPostRecommendations drill rotation (issue #5319)', () => {
expect(recentPractice.memoryItemIds).toContain('elements-song');
});
});
+
+
+describe('daily challenge mix', () => {
+ it('keeps a fixed five-challenge set through completion, varies by local day, and needs no mastery history', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-03-11T12:00:00Z'));
+ state.config = { topics: { memory: { enabled: false }, morse: { enabled: false }, wordplay: { enabled: false }, verbal: { enabled: false }, imagination: { enabled: false } } };
+ const first = (await getPostRecommendations()).dailyRecommendations;
+ expect(first).toHaveLength(5);
+ expect(new Set(first.map(r => r.id)).size).toBe(5);
+ expect((await getPostRecommendations({ limit: 1 })).dailyRecommendations[0]).toEqual(first[0]);
+ for (const rec of first) {
+ state.training.push({ date: '2026-03-11', drillType: rec.drillType });
+ }
+ const done = (await getPostRecommendations()).dailyRecommendations;
+ expect(done.map(r => r.id).sort()).toEqual(first.map(r => r.id).sort());
+ expect(done.every(r => r.practicedToday)).toBe(true);
+ vi.setSystemTime(new Date('2026-03-12T12:00:00Z'));
+ expect((await getPostRecommendations()).dailyRecommendations.map(r => r.id)).not.toEqual(first.map(r => r.id));
+ });
+
+ it('retains a completed memory slot after its review date advances and honors disabled topics', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-03-11T12:00:00Z'));
+ state.config = { topics: { math: { enabled: false }, cognitive: { enabled: false }, morse: { enabled: false }, wordplay: { enabled: false }, verbal: { enabled: false }, imagination: { enabled: false } } };
+ const first = (await getPostRecommendations()).dailyRecommendations;
+ expect(first).toHaveLength(1);
+ expect(first[0].memoryItemId).toBe('elements-song');
+ state.memoryItems = [{ id: 'elements-song', title: 'Example Elements', content: {}, schedule: { nextReview: '2026-03-15T00:00:00Z' }, mastery: { overallPct: 10 } }];
+ state.training = [{ date: '2026-03-11', memoryItemId: 'elements-song', mode: 'element-flash' }];
+ const done = (await getPostRecommendations()).dailyRecommendations;
+ expect(done[0].id).toBe(first[0].id);
+ expect(done[0].practicedToday).toBe(true);
+ state.config.topics.memory = { enabled: false };
+ expect((await getPostRecommendations()).dailyRecommendations).toEqual([]);
+ });
+});