Builds replayable combat logs with first-class undo/redo, unified verification tooling, fast indexed log queries, and stricter CI.

feat(combat): add first-class undo and redo controls

Add undo and redo controls to the combat UI so the DM can recover from recent
actions without leaving the encounter view.

Undo and redo operate on the current encounter's combat history. Empty stacks
produce clear feedback instead of failing silently. Redo order follows normal
stack behavior after multiple undos.

This makes combat history actionable during play, not just visible in the log.

feat(logs): make combat logs replayable

Replace plain combat log messages with structured combat events that can be
used by the UI, exported as JSON, replayed, and verified.

Each new log entry records the action type, encounter identity, participant
identity, a small action delta, undo intent, and a turn snapshot. Download and
copy now export the event stream as JSON so a saved combat log is useful for
offline analysis and debugging.

Legacy logs remain viewable, but new logs use the structured event format.

feat(logs): make undo and redo transactional

Apply undo and redo as single storage operations so the encounter state and log
state cannot drift apart.

Server storage applies the encounter update and the log undone flag inside one
SQLite transaction. Firebase storage uses a batch write for the same behavior.
The storage contract now includes undo/redo semantics.

This replaces fragile multi-write undo behavior where a failure could update
the encounter without marking the log, or mark the log without updating the
encounter.

feat(combat): add unified replay and verification tool

Add one combat CLI for replaying live combat and verifying combat logs.

Replay drives the live backend through the same shared combat logic used by the
app, writes a JSON event log to an explicit output path, and automatically
verifies the result. Verification checks for DM-visible combat problems such as
skipped turns, double actions, bad round changes, and unexpected turn order
changes.

The tool uses the same JSON event stream produced by log downloads, supports
verbose turn output, and handles Ctrl-C by ending the encounter, writing the
partial log, and verifying what was captured.

fix(perf): keep long combat logging fast

Remove the combat-time log query bottleneck that made long replays slow as log
volume grew.

Combat controls no longer subscribe to the log collection just to keep undo and
redo state warm. Undo and redo now query the latest matching encounter log only
when clicked. Server collection queries support exact filters, ordering,
limits, and offsets, and SQLite indexes keep latest-log and per-encounter log
lookups fast.

Also fix duplicate WebSocket handler registration so realtime updates do not
double-fire under write load.

fix(turns): make toggle active a status change

Make toggle active a roster/status edit instead of a turn advance.

Deactivating the current participant no longer passes the turn or increments
the round. The current turn stays where it is until the DM explicitly clicks
Next Turn, and Next Turn skips inactive participants during normal rotation.

This matches the initiative design: slot order is stable, toggle active does
not move participants, and round changes only come from explicit turn advance.

chore(ci): make warnings and hangs fail fast

Tighten test and build checks so failures are visible instead of noisy or
silent.

Builds run with CI enabled so warnings fail production builds. The full test
command runs app, shared, and server suites with hard timeouts so hangs fail
quickly. Static eslint coverage fails on warnings as well as errors.

Tests were updated around the new async combat logging flow, structured log
events, transactional undo, replay verification, and toggle-active semantics.
This commit is contained in:
david raistrick
2026-07-06 10:33:28 -04:00
parent 9f8b09c7d9
commit 2569cc4497
51 changed files with 4465 additions and 2164 deletions
+52 -54
View File
@@ -1,4 +1,4 @@
// Combat integrity test: replay exact op sequence through pure turn.js,
// Combat integrity test: replay exact op sequence through async turn.js,
// assert rotation + state invariants per round. This IS the test the audit
// was supposed to be. Deterministic (seeded RNG). RED on current code = BUG-5.
//
@@ -6,8 +6,11 @@
// damage, heal (cleric), conditions, toggleActive, deathSave,
// removeParticipant, addParticipant, updateParticipant, pause/resume,
// reorderParticipants, revive-between-rounds.
//
// Rewritten for async turn.js API: funcs are awaited, take ctx, write own logs.
const shared = require('@ttrpg/shared');
const { mockCtx } = require('./_helpers');
const {
makeParticipant, buildCharacterParticipant, buildMonsterParticipant,
startEncounter, nextTurn, togglePause,
@@ -70,22 +73,17 @@ function currentParticipant(e) {
return (e.participants || []).find(x => x.id === e.currentTurnParticipantId) || null;
}
// Apply a result patch if present.
function apply(e, result) {
if (!result || !result.patch) return e;
return { ...e, ...result.patch };
}
describe('combat integrity (100 rounds, full op coverage)', () => {
jest.setTimeout(30000);
const ROUNDS = 100;
const violations = [];
test('every round visits each active participant exactly once', () => {
test('every round visits each active participant exactly once', async () => {
const { ctx } = mockCtx();
_seed = 12345; // reset for reproducibility
let e = setupEncounter();
e = apply(e, startEncounter(e));
e = await startEncounter(e, ctx);
let totalTurns = 0;
let lastPaused = false;
@@ -102,15 +100,15 @@ describe('combat integrity (100 rounds, full op coverage)', () => {
while (e.round === startRound && guard < cap) {
// resume if paused (must precede nextTurn)
if (lastPaused) { e = apply(e, togglePause(e)); lastPaused = false; }
if (lastPaused) { e = await togglePause(e, ctx); lastPaused = false; }
// advance
let t;
try { t = nextTurn(e); } catch (err) {
try {
e = await nextTurn(e, ctx);
} catch (err) {
violations.push({ round: roundN, type: 'nextTurn-throws', msg: err.message });
break;
}
e = apply(e, t);
totalTurns++;
// only count if turn belongs to THIS round (no wrap)
if (e.round === startRound) seenThisRound.push(e.currentTurnParticipantId);
@@ -120,58 +118,58 @@ describe('combat integrity (100 rounds, full op coverage)', () => {
// 1. damage
if (actor) {
const foes = e.participants.filter(
p => p.id !== actor.id && p.currentHp > 0 && p.isActive !== false
part => part.id !== actor.id && part.currentHp > 0 && part.isActive !== false
);
if (foes.length > 0) {
const tgt = pick(foes);
const dmg = 1 + rnd(5);
e = apply(e, applyHpChange(e, tgt.id, 'damage', dmg));
e = await applyHpChange(e, tgt.id, 'damage', dmg, ctx);
}
}
// 2. heal (cleric)
if (actor && actor.name === 'Cleric' && totalTurns % 2 === 0) {
const wounded = e.participants
.filter(p => p.currentHp > 0 && p.currentHp < p.maxHp && p.isActive !== false)
.filter(part => part.currentHp > 0 && part.currentHp < part.maxHp && part.isActive !== false)
.sort((a,b)=>(a.currentHp/a.maxHp)-(b.currentHp/b.maxHp));
if (wounded.length > 0) {
const tgt = wounded[0];
const amt = 2 + rnd(5);
e = apply(e, applyHpChange(e, tgt.id, 'heal', amt));
e = await applyHpChange(e, tgt.id, 'heal', amt, ctx);
}
}
// 3. conditions
if (condQueue.length > 0) {
const cond = condQueue[0];
const living = e.participants.filter(p => p.currentHp > 0 && p.isActive !== false);
const living = e.participants.filter(part => part.currentHp > 0 && part.isActive !== false);
if (living.length > 0) {
const tgt = pick(living);
try { e = apply(e, toggleCondition(e, tgt.id, cond)); condQueue.shift(); }
try { e = await toggleCondition(e, tgt.id, cond, ctx); condQueue.shift(); }
catch (err) { condQueue.shift(); }
}
} else if (totalTurns % 6 === 0) {
const living = e.participants.filter(p => p.currentHp > 0 && p.isActive !== false);
const living = e.participants.filter(part => part.currentHp > 0 && part.isActive !== false);
if (living.length > 0) {
const tgt = pick(living);
const cond = pick([...CONDITIONS, ...CUSTOM_CONDITIONS]);
try { e = apply(e, toggleCondition(e, tgt.id, cond)); } catch (err) {}
try { e = await toggleCondition(e, tgt.id, cond, ctx); } catch (err) {}
}
}
// 4. toggleParticipantActive
if (totalTurns % 9 === 0) {
const living = e.participants.filter(p => p.currentHp > 0);
const living = e.participants.filter(part => part.currentHp > 0);
if (living.length > 0) {
const tgt = pick(living);
try { e = apply(e, toggleParticipantActive(e, tgt.id)); } catch (err) {}
try { e = await toggleParticipantActive(e, tgt.id, ctx); } catch (err) {}
}
}
// 5. deathSave
if (actor && actor.currentHp <= 0 && !actor.isNpc) {
try { e = apply(e, deathSave(e, actor.id, 'fail', 1)); } catch (err) {}
try { const r = await deathSave(e, actor.id, 'fail', 1, ctx); e = r.enc; } catch (err) {}
}
// 6. removeParticipant
if (totalTurns % 5 === 0) {
const dead = e.participants.find(p => (p.isDying || p.currentHp <= 0) && (p.isNpc || p.name.startsWith('Goblin') || p.name === 'OrcBoss' || p.name === 'Wolf'));
if (dead) { try { e = apply(e, removeParticipant(e, dead.id)); } catch (err) {} }
const dead = e.participants.find(part => (part.isDying || part.currentHp <= 0) && (part.isNpc || part.name.startsWith('Goblin') || part.name === 'OrcBoss' || part.name === 'Wolf'));
if (dead) { try { e = await removeParticipant(e, dead.id, ctx); } catch (err) {} }
}
// 7. addParticipant
if (totalTurns % 10 === 0 && reinforcementsAdded < 4) {
@@ -180,27 +178,27 @@ describe('combat integrity (100 rounds, full op coverage)', () => {
{ name:`Summon${reinforcementsAdded+1}`, maxHp:80, initMod:4 },
]);
const built = buildMonsterParticipant(spec).participant;
try { e = apply(e, addParticipant(e, built)); reinforcementsAdded++; } catch (err) {}
try { e = await addParticipant(e, built, ctx); reinforcementsAdded++; } catch (err) {}
}
// 8. updateParticipant
if (totalTurns % 7 === 0) {
const living = e.participants.filter(p => p.currentHp > 0);
const living = e.participants.filter(part => part.currentHp > 0);
if (living.length > 0) {
const tgt = pick(living);
try { e = apply(e, updateParticipant(e, tgt.id, { notes:`edited@turn${totalTurns}` })); } catch (err) {}
try { e = await updateParticipant(e, tgt.id, { notes:`edited@turn${totalTurns}` }, ctx); } catch (err) {}
}
}
// 9. pause
if (totalTurns % 12 === 0 && !lastPaused) { e = apply(e, togglePause(e)); lastPaused = true; }
if (totalTurns % 12 === 0 && !lastPaused) { e = await togglePause(e, ctx); lastPaused = true; }
// 10. reorderParticipants (mirror replay's buggy signature usage — swallowed no-op)
if (totalTurns % 8 === 0 && lastReorder !== totalTurns) {
const living = e.participants.filter(p => p.currentHp > 0 && p.isActive !== false);
const living = e.participants.filter(part => part.currentHp > 0 && part.isActive !== false);
if (living.length >= 2) {
const tgt = living[0];
const newInit = (tgt.initiative || 0) + 1;
try {
const reordered = [...e.participants].map(p => p.id === tgt.id ? { ...p, initiative: newInit } : p);
e = apply(e, reorderParticipants(e, reordered));
const reordered = [...e.participants].map(part => part.id === tgt.id ? { ...part, initiative: newInit } : part);
e = await reorderParticipants(e, reordered); // array as draggedId throws → swallowed
lastReorder = totalTurns;
} catch (err) {}
}
@@ -215,20 +213,19 @@ describe('combat integrity (100 rounds, full op coverage)', () => {
const uniq = new Set(seenThisRound);
if (uniq.size !== seenThisRound.length) {
violations.push({ round: roundN, type: 'rotation-dupe',
seen: seenThisRound.map(id => e.participants.find(p=>p.id===id)?.name||id) });
seen: seenThisRound.map(id => e.participants.find(part=>part.id===id)?.name||id) });
}
// turnOrderIds no dup
const orderUniq = new Set(e.turnOrderIds);
if (orderUniq.size !== e.turnOrderIds.length) {
violations.push({ round: roundN, type: 'turnOrder-dup-id', order: e.turnOrderIds });
}
// currentTurn valid + active
// currentTurn valid. It may be inactive immediately after DM toggles
// current actor inactive; toggle-active is status edit, not turn advance.
// Next Turn is responsible for skipping inactive current.
if (e.currentTurnParticipantId) {
const ct = e.participants.find(p => p.id === e.currentTurnParticipantId);
const ct = e.participants.find(part => part.id === e.currentTurnParticipantId);
if (!ct) violations.push({ round: roundN, type: 'currentTurn-missing' });
else if (ct.isActive === false && e.isStarted) {
violations.push({ round: roundN, type: 'currentTurn-inactive', id: ct.id });
}
}
// HP bounds
for (const part of e.participants) {
@@ -247,11 +244,11 @@ describe('combat integrity (100 rounds, full op coverage)', () => {
// queue drains them through toggleCondition which proves acceptance)
// revive dead between rounds
const dead = e.participants.filter(p => p.currentHp <= 0 || p.isActive === false);
const dead = e.participants.filter(part => part.currentHp <= 0 || part.isActive === false);
for (const d of dead) {
try {
if (d.isActive === false) e = apply(e, toggleParticipantActive(e, d.id));
e = apply(e, applyHpChange(e, d.id, 'heal', d.maxHp));
if (d.isActive === false) e = await toggleParticipantActive(e, d.id, ctx);
e = await applyHpChange(e, d.id, 'heal', d.maxHp, ctx);
} catch (err) {}
}
}
@@ -270,25 +267,26 @@ describe('combat integrity (100 rounds, full op coverage)', () => {
// Custom (freeform) condition strings: UI contract.
// toggleCondition must accept ANY string, not just built-ins.
test('custom condition strings survive add/remove round-trip', () => {
test('custom condition strings survive add/remove round-trip', async () => {
const { ctx } = mockCtx();
let e = setupEncounter();
e = apply(e, startEncounter(e));
e = await startEncounter(e, ctx);
const tgt = e.participants[0].id;
// add custom (not in built-ins)
e = apply(e, toggleCondition(e, tgt, 'hexed'));
let p = e.participants.find(x => x.id === tgt);
expect(p.conditions).toContain('hexed');
e = await toggleCondition(e, tgt, 'hexed', ctx);
let part = e.participants.find(x => x.id === tgt);
expect(part.conditions).toContain('hexed');
// emoji-bearing custom id
e = apply(e, toggleCondition(e, tgt, '🛡️blessed'));
p = e.participants.find(x => x.id === tgt);
expect(p.conditions).toContain('🛡️blessed');
e = await toggleCondition(e, tgt, '🛡️blessed', ctx);
part = e.participants.find(x => x.id === tgt);
expect(part.conditions).toContain('🛡️blessed');
// remove
e = apply(e, toggleCondition(e, tgt, 'hexed'));
p = e.participants.find(x => x.id === tgt);
expect(p.conditions).not.toContain('hexed');
expect(p.conditions).toContain('🛡️blessed');
e = await toggleCondition(e, tgt, 'hexed', ctx);
part = e.participants.find(x => x.id === tgt);
expect(part.conditions).not.toContain('hexed');
expect(part.conditions).toContain('🛡️blessed');
});
});