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([issue-2092]): serialize morse writes, recompute correctness, keep insertion errors

Adam Eivy26b0184294d5
diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsx
index 50a934355c..9bd5b671d8 100644
--- a/client/src/components/meatspace/post/MorseTrainer.jsx
+++ b/client/src/components/meatspace/post/MorseTrainer.jsx
@@ -857,16 +857,22 @@ function ModeGrid({ onPick }) {
const ROUND_SIZE = 10;
// Flatten per-question copy results ({ prompt, guess, correct, responseMs }) into
-// per-character sent→guessed items for the server's confusion matrix. Each prompt
-// is aligned positionally with its guess: a missing/short guess yields '' (a miss,
-// scored wrong). The question's responseMs is attributed to each of its characters.
+// per-character sent→guessed items for the server's confusion matrix. Aligned
+// positionally over the LONGER of prompt/guess so nothing is silently dropped:
+// - a missing/short guess char yields guessed '' (a miss, scored wrong);
+// - an EXTRA typed char beyond the prompt yields sent '' (an insertion). An
+// insertion has no transmitted character, so the server excludes empty-sent
+// items from the confusion matrix / per-character mastery, but still counts
+// them in the round's accuracy — so a `K`→`KM` round reads as an error, not a
+// perfect copy. The question's responseMs is attributed to each character.
export function resultsToItems(results) {
const items = [];
for (const r of results) {
const promptChars = (r.prompt || '').toUpperCase().split('');
const guessChars = (r.guess || '').toUpperCase().split('');
- for (let i = 0; i < promptChars.length; i++) {
- const sent = promptChars[i];
+ const len = Math.max(promptChars.length, guessChars.length);
+ for (let i = 0; i < len; i++) {
+ const sent = promptChars[i] ?? '';
const guessed = guessChars[i] ?? '';
items.push({ sent, guessed, correct: sent === guessed, responseMs: r.responseMs ?? 0 });
}
diff --git a/client/src/components/meatspace/post/MorseTrainer.test.jsx b/client/src/components/meatspace/post/MorseTrainer.test.jsx
index b465ace64e..e85ceae7a7 100644
--- a/client/src/components/meatspace/post/MorseTrainer.test.jsx
+++ b/client/src/components/meatspace/post/MorseTrainer.test.jsx
@@ -244,6 +244,16 @@ describe('resultsToItems (per-character flatten for the confusion matrix)', () =
expect(items[2]).toEqual({ sent: 'S', guessed: '', correct: false, responseMs: 0 });
});
+ it('records an extra typed character as an empty-sent insertion error', () => {
+ // K→KM: K is a correct copy, but the extra M must not vanish (which would
+ // read as a perfect round) — it becomes an empty-sent error item.
+ const items = resultsToItems([{ prompt: 'K', guess: 'KM', correct: false, responseMs: 100 }]);
+ expect(items).toEqual([
+ { sent: 'K', guessed: 'K', correct: true, responseMs: 100 },
+ { sent: '', guessed: 'M', correct: false, responseMs: 100 },
+ ]);
+ });
+
it('flattens a multi-question round into per-character items', () => {
const items = resultsToItems([
{ prompt: 'K', guess: 'K', correct: true, responseMs: 100 },
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index 4109ce4966..1b6c40e0b7 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -315,10 +315,14 @@ export const memoryDrillRequestSchema = z.object({
const MORSE_MAX_KOCH_LEVEL = 41;
// One recorded prompt→guess character within a Morse round. `guessed` is
-// nullable ('' or null = a miss, distinct from a wrong character); the server
-// recomputes accuracy from these so `correct` is advisory.
+// nullable ('' or null = a miss, distinct from a wrong character); `sent` may be
+// '' for an insertion (an extra typed character with no transmitted counterpart)
+// — the server drops empty-sent items from the confusion matrix but still counts
+// them against round accuracy. The `sent` key must still be present (a missing
+// key is rejected); the server recomputes `correct` from the pair, so it's
+// advisory here.
const morseRoundItemSchema = z.object({
- sent: z.string().min(1).max(8),
+ sent: z.string().max(8),
guessed: z.string().max(16).nullable().optional(),
correct: z.boolean().optional(),
responseMs: z.number().min(0).optional().default(0),
diff --git a/server/services/meatspacePostMorse.js b/server/services/meatspacePostMorse.js
index f35c5144f7..fc7e0393dd 100644
--- a/server/services/meatspacePostMorse.js
+++ b/server/services/meatspacePostMorse.js
@@ -67,15 +67,33 @@ async function saveMorseProgress(data) {
await atomicWrite(MORSE_FILE, data);
}
+// Serialize every read-modify-write against the single shared progress file so
+// the two mutating paths can't clobber each other. A round that advances the
+// Koch level fires BOTH a level PUT (updatePrefs) and a round POST from the
+// client at once; without this tail their load→mutate→save cycles interleave
+// and whichever saves last drops the other's change (the just-earned level, or
+// the just-finished round). atomicWrite makes each file write atomic but not the
+// surrounding read-modify-write — see CLAUDE.md "serialize writes server-side".
+let morseWriteTail = Promise.resolve();
+function withMorseWriteTail(fn) {
+ const run = morseWriteTail.then(fn, fn);
+ // The tail must never stay rejected (that would reject every future write);
+ // callers still receive the real result/rejection via `run`.
+ morseWriteTail = run.then(() => {}, () => {});
+ return run;
+}
+
function normalizeItems(items) {
return (Array.isArray(items) ? items : []).map((it) => {
const sent = String(it?.sent ?? '').toUpperCase();
// Absent/null guess (a miss) normalizes to '' — distinct from a wrong guess.
const guessed = it?.guessed == null ? '' : String(it.guessed).toUpperCase();
+ // correct is recomputed from the normalized pair (not trusted from the
+ // client) so the stored accuracy can't drift from the sent/guessed record.
return {
sent,
guessed,
- correct: typeof it?.correct === 'boolean' ? it.correct : sent === guessed,
+ correct: sent === guessed,
responseMs: Number.isFinite(it?.responseMs) ? Math.max(0, Math.round(it.responseMs)) : 0,
};
});
@@ -87,30 +105,32 @@ function normalizeItems(items) {
* can't drift from the recorded sent/guessed pairs.
*/
export async function appendMorseRound(round) {
- const data = await loadMorseProgress();
- const now = new Date().toISOString();
- const items = normalizeItems(round.items);
- const correctCount = items.filter((i) => i.correct).length;
- const accuracy = items.length > 0 ? Math.round((correctCount / items.length) * 100) : 0;
-
- const record = {
- id: randomUUID(),
- date: now.split('T')[0],
- timestamp: now,
- mode: MORSE_MODES.includes(round.mode) ? round.mode : 'copy',
- kochLevel: typeof round.kochLevel === 'number' ? clampLevel(round.kochLevel) : (data.kochLevel ?? DEFAULT_KOCH_LEVEL),
- wpm: Number.isFinite(round.wpm) ? round.wpm : null,
- farnsworthWpm: Number.isFinite(round.farnsworthWpm) ? round.farnsworthWpm : null,
- items,
- accuracy,
- durationMs: Number.isFinite(round.durationMs) ? Math.max(0, Math.round(round.durationMs)) : 0,
- };
+ return withMorseWriteTail(async () => {
+ const data = await loadMorseProgress();
+ const now = new Date().toISOString();
+ const items = normalizeItems(round.items);
+ const correctCount = items.filter((i) => i.correct).length;
+ const accuracy = items.length > 0 ? Math.round((correctCount / items.length) * 100) : 0;
+
+ const record = {
+ id: randomUUID(),
+ date: now.split('T')[0],
+ timestamp: now,
+ mode: MORSE_MODES.includes(round.mode) ? round.mode : 'copy',
+ kochLevel: typeof round.kochLevel === 'number' ? clampLevel(round.kochLevel) : (data.kochLevel ?? DEFAULT_KOCH_LEVEL),
+ wpm: Number.isFinite(round.wpm) ? round.wpm : null,
+ farnsworthWpm: Number.isFinite(round.farnsworthWpm) ? round.farnsworthWpm : null,
+ items,
+ accuracy,
+ durationMs: Number.isFinite(round.durationMs) ? Math.max(0, Math.round(round.durationMs)) : 0,
+ };
- data.rounds.push(record);
- if (data.rounds.length > MAX_ROUNDS) data.rounds = data.rounds.slice(-MAX_ROUNDS);
- await saveMorseProgress(data);
- console.log(`📻 Morse round logged: ${record.mode} ${correctCount}/${items.length} (${accuracy}%) @ Koch ${record.kochLevel}`);
- return record;
+ data.rounds.push(record);
+ if (data.rounds.length > MAX_ROUNDS) data.rounds = data.rounds.slice(-MAX_ROUNDS);
+ await saveMorseProgress(data);
+ console.log(`📻 Morse round logged: ${record.mode} ${correctCount}/${items.length} (${accuracy}%) @ Koch ${record.kochLevel}`);
+ return record;
+ });
}
/**
@@ -120,26 +140,28 @@ export async function appendMorseRound(round) {
* device clobbering a real server level with its own stale localStorage value.
*/
export async function setKochLevel({ kochLevel, adopt = false, settings } = {}) {
- const data = await loadMorseProgress();
- const alreadySet = data.kochLevel != null;
+ return withMorseWriteTail(async () => {
+ const data = await loadMorseProgress();
+ const alreadySet = data.kochLevel != null;
- let adopted = false;
- if (adopt) {
- if (!alreadySet) {
+ let adopted = false;
+ if (adopt) {
+ if (!alreadySet) {
+ data.kochLevel = clampLevel(kochLevel);
+ adopted = true;
+ }
+ // else: keep the server's authoritative level; adoption is a no-op.
+ } else {
data.kochLevel = clampLevel(kochLevel);
- adopted = true;
}
- // else: keep the server's authoritative level; adoption is a no-op.
- } else {
- data.kochLevel = clampLevel(kochLevel);
- }
- if (settings && typeof settings === 'object') {
- data.settings = { ...(data.settings || {}), ...settings };
- }
+ if (settings && typeof settings === 'object') {
+ data.settings = { ...(data.settings || {}), ...settings };
+ }
- await saveMorseProgress(data);
- return { kochLevel: data.kochLevel ?? DEFAULT_KOCH_LEVEL, kochLevelSet: data.kochLevel != null, adopted, settings: data.settings };
+ await saveMorseProgress(data);
+ return { kochLevel: data.kochLevel ?? DEFAULT_KOCH_LEVEL, kochLevelSet: data.kochLevel != null, adopted, settings: data.settings };
+ });
}
/**
@@ -186,7 +208,10 @@ export async function getMorseProgress(days = 30) {
for (const r of rounds) {
for (const it of (r.items || [])) {
const sent = it.sent;
- if (!sent) continue; // items always key on the sent character
+ // Empty sent = an insertion (an extra typed char with no transmitted
+ // counterpart): it counted against the round's accuracy on append, but has
+ // no character to attribute a confusion / mastery entry to, so skip it here.
+ if (!sent) continue;
const guessed = it.guessed || '∅'; // '∅' = a miss / empty guess (a real bucket)
confusionMatrix[sent] ||= {};
confusionMatrix[sent][guessed] = (confusionMatrix[sent][guessed] || 0) + 1;
diff --git a/server/services/meatspacePostMorse.test.js b/server/services/meatspacePostMorse.test.js
index ff9e1b7534..4643f19351 100644
--- a/server/services/meatspacePostMorse.test.js
+++ b/server/services/meatspacePostMorse.test.js
@@ -56,6 +56,18 @@ describe('appendMorseRound', () => {
expect(round.accuracy).toBe(0);
});
+ it('counts an empty-sent insertion against round accuracy', async () => {
+ // K→KM flattens to [{K,K},{'',M}] — the insertion drops accuracy to 50%.
+ const round = await appendMorseRound({
+ mode: 'copy',
+ items: [
+ { sent: 'K', guessed: 'K', correct: true },
+ { sent: '', guessed: 'M', correct: false },
+ ],
+ });
+ expect(round.accuracy).toBe(50);
+ });
+
it('appends to existing rounds', async () => {
readJSONFile.mockResolvedValue({ kochLevel: 3, settings: null, rounds: [{ id: 'old' }] });
await appendMorseRound({ mode: 'copy', items: [{ sent: 'K', guessed: 'K', correct: true }] });
@@ -65,6 +77,26 @@ describe('appendMorseRound', () => {
});
});
+describe('serialized writes (no lost update between round POST and level PUT)', () => {
+ it('a concurrent round append and level change both persist', async () => {
+ // Back the mocked file with a real in-memory store so a lost read-modify-
+ // write would actually drop one of the two mutations.
+ let store = { kochLevel: null, settings: null, rounds: [] };
+ readJSONFile.mockImplementation(async () => JSON.parse(JSON.stringify(store)));
+ atomicWrite.mockImplementation(async (_path, data) => { store = JSON.parse(JSON.stringify(data)); });
+
+ // These are exactly the two writes the client fires at once when a round
+ // advances the Koch level. Serialized, both must land.
+ await Promise.all([
+ appendMorseRound({ mode: 'copy', items: [{ sent: 'K', guessed: 'K', correct: true }] }),
+ setKochLevel({ kochLevel: 7 }),
+ ]);
+
+ expect(store.rounds).toHaveLength(1); // the finished round survived
+ expect(store.kochLevel).toBe(7); // the level advance survived
+ });
+});
+
describe('setKochLevel', () => {
it('sets the level explicitly (advance/reset)', async () => {
const res = await setKochLevel({ kochLevel: 7 });
@@ -149,6 +181,27 @@ describe('getMorseProgress', () => {
expect(p.confusionPairs[0]).toEqual({ sent: 'M', guessed: 'R', count: 2 });
});
+ it('excludes empty-sent insertions from the confusion matrix and mastery', async () => {
+ readJSONFile.mockResolvedValue({
+ kochLevel: 5,
+ settings: null,
+ rounds: [
+ {
+ id: 'r1', date: today(), mode: 'copy',
+ items: [
+ { sent: 'K', guessed: 'K', correct: true },
+ { sent: '', guessed: 'M', correct: false }, // insertion — no sent
+ ],
+ },
+ ],
+ });
+ const p = await getMorseProgress(30);
+ // The insertion contributes no confusion cell and no character in mastery.
+ expect(p.confusionMatrix['']).toBeUndefined();
+ expect(p.charAccuracy.map((c) => c.char)).toEqual(['K']);
+ expect(p.confusionPairs).toEqual([]);
+ });
+
it('builds a per-mode trend series with effective WPM', async () => {
readJSONFile.mockResolvedValue({
kochLevel: 5,