import { describe, it, expect } from 'vitest' import { encodeFrame, decodeFrame, messageFrame, errorFrame } from './frame.js' import { toWireState, projectActionToWire, projectResolvedEffect, projectInspectAuthentic } from './adapt.js' import type { WireAction } from './adapt.js' import { applyWireEvent } from './apply.js' import { balance, timerFor } from '../engine/config.js' import { reduce } from '../engine/reducer.js' import { projectFor } from '../engine/selectors.js' import { setup } from '../engine/testutil.js' import type { Action } from '../engine/actions.js' import type { Did, GameState } from '../engine/types.js' import type { ProjectedState } from '../engine/selectors.js' const config = balance({ playerCount: 4, roundDurationMs: 600_000, resourceCount: 2 }).config function engineState(): ProjectedState { return { code: 'WXYZ', phase: 'round', now: 1000, config, startedAt: 500, endsAt: 600_500, resources: { wood: 3, stone: 0 }, players: { 'did:a': { did: 'did:a', handle: 'alice', spriteRef: null, role: 'saboteur', status: 'alive', pos: { x: 10.7, y: 20.2 }, facing: 'south', carrying: { resourceId: 'wood', authentic: null }, active: { stationId: 's1', startedAt: 0, endsAt: 2000, kind: null }, dest: null, path: [], }, }, stations: { s1: { id: 's1', pos: { x: 5.9, y: 5.1 }, area: { x: 0, y: 0, w: 32, h: 32 }, slotCount: 2, state: 'working', collect: ['wood'], deposit: [], scoreboard: [], meeting: false, }, }, debris: {}, vote: null, outcome: null, seq: 7, } } describe('frame codec', () => { it('round-trips a header + body', () => { const bytes = encodeFrame({ op: 1, t: '#event' }, { seq: 5, hi: 'there', nested: { a: [1, 2, 3] } }) const { header, body } = decodeFrame(bytes) expect(header).toEqual({ op: 1, t: '#event' }) expect(body).toEqual({ seq: 5, hi: 'there', nested: { a: [1, 2, 3] } }) }) it('messageFrame / errorFrame helpers', () => { expect(decodeFrame(messageFrame('#snapshot', { x: 1 })).header).toEqual({ op: 1, t: '#snapshot' }) const err = decodeFrame(errorFrame('GameNotFound', 'WXYZ')) expect(err.header).toEqual({ op: -1 }) expect(err.body).toEqual({ error: 'GameNotFound', message: 'WXYZ' }) }) }) describe('toWireState', () => { it('converts maps to arrays, rounds coords, and omits redacted/null fields', () => { const w = toWireState(engineState()) // maps -> arrays of entries expect(w.resources).toEqual([ { resourceId: 'wood', amount: 3 }, { resourceId: 'stone', amount: 0 }, ]) expect(w.config.targets.every((t) => typeof t.target === 'number')).toBe(true) expect(w.players).toHaveLength(1) const p = w.players[0]! // float -> integer pixels expect(p.pos).toEqual({ x: 11, y: 20 }) // null role/spriteRef omitted; carrying.authentic (null) omitted; active.kind (null) omitted expect('spriteRef' in p).toBe(false) expect(p.carrying).toEqual({ resourceId: 'wood' }) expect('authentic' in p.carrying!).toBe(false) expect('kind' in p.active!).toBe(false) expect(w.players[0]!.role).toBe('saboteur') // engine projection already decided visibility }) }) describe('projectActionToWire redaction', () => { const roundStarted: Action = { type: 'roundStarted', serverTime: 100, roles: { 'did:a': 'saboteur', 'did:b': 'worker' }, spawns: { 'did:a': { x: 1.4, y: 2.6 }, 'did:b': { x: 3, y: 4 } }, endsAt: 600_100, } it('reveals only the viewer’s own role; spawns stay public', () => { const forA = projectActionToWire(roundStarted, 'did:a') as { roles?: unknown[]; spawns: unknown[] } expect(forA.roles).toEqual([{ did: 'did:a', role: 'saboteur' }]) expect(forA.spawns).toHaveLength(2) const forB = projectActionToWire(roundStarted, 'did:b') as { roles?: { did: string }[] } expect(forB.roles).toEqual([{ did: 'did:b', role: 'worker' }]) const forSpectator = projectActionToWire(roundStarted, null) as { roles?: unknown } expect('roles' in forSpectator).toBe(false) }) it('hides the activity choice and slot from non-actors', () => { const started: Action = { type: 'actionStarted', serverTime: 100, did: 'did:a', stationId: 's1', slot: 1, kind: 'sabotage', endsAt: 8100, } const actor = projectActionToWire(started, 'did:a') as { kind?: string; slot?: number } expect(actor.kind).toBe('sabotage') expect(actor.slot).toBe(1) const other = projectActionToWire(started, 'did:b') as Record expect('kind' in other).toBe(false) expect('slot' in other).toBe(false) expect(other.stationId).toBe('s1') // station + dwell time are public }) it('hides resolve RNG from non-actors', () => { const resolved: Action = { type: 'actionResolved', serverTime: 100, did: 'did:a', rng: { sabotageTriggered: true }, } expect((projectActionToWire(resolved, 'did:a') as { rng?: unknown }).rng).toEqual({ sabotageTriggered: true }) expect('rng' in (projectActionToWire(resolved, 'did:b') as object)).toBe(false) }) it('gives the moving player their full path stub but others only the next two waypoints', () => { const moved: Action = { type: 'playerMoved', serverTime: 100, did: 'did:a', pos: { x: 1, y: 1 }, facing: 'east', path: [ { x: 10, y: 10 }, { x: 20, y: 20 }, { x: 30, y: 30 }, { x: 40, y: 40 }, ], } const self = projectActionToWire(moved, 'did:a') as { path?: unknown[] } expect(self.path).toHaveLength(4) const other = projectActionToWire(moved, 'did:b') as { path?: unknown[] } expect(other.path).toEqual([{ x: 10, y: 10 }, { x: 20, y: 20 }]) }) it('reveals a setDestination target only to the actor', () => { const dest: Action = { type: 'setDestination', serverTime: 100, did: 'did:a', target: { x: 50, y: 60 } } expect((projectActionToWire(dest, 'did:a') as { target?: unknown }).target).toEqual({ x: 50, y: 60 }) expect('target' in (projectActionToWire(dest, 'did:b') as object)).toBe(false) expect('target' in (projectActionToWire(dest, null) as object)).toBe(false) }) }) describe('applyWireEvent (client fold)', () => { it('adds a joined player and folds roundStarted role + spawn', () => { let state = toWireState({ ...engineState(), phase: 'lobby', players: {}, startedAt: null, endsAt: null, }) state = applyWireEvent(state, projectActionToWire( { type: 'playerJoined', serverTime: 1, did: 'did:a', handle: 'alice', spriteRef: null, pos: { x: 2, y: 2 } }, 'did:a', ))! expect(state.players.map((p) => p.did)).toEqual(['did:a']) state = applyWireEvent(state, projectActionToWire( { type: 'roundStarted', serverTime: 2, roles: { 'did:a': 'worker' }, spawns: { 'did:a': { x: 9, y: 9 } }, endsAt: 1000, }, 'did:a', ))! expect(state.phase).toBe('round') expect(state.players[0]!.role).toBe('worker') expect(state.players[0]!.pos).toEqual({ x: 9, y: 9 }) }) it('folds itemDropped (debris from public carry type) and clears the carry', () => { const state = toWireState(engineState()) // did:a carries wood const ev = projectActionToWire( { type: 'itemDropped', serverTime: 10, did: 'did:a', debrisId: 'x1', pos: { x: 7, y: 8 } }, 'did:b', ) const next = applyWireEvent(state, ev)! expect(next.debris).toEqual([{ id: 'x1', pos: { x: 7, y: 8 }, resourceId: 'wood' }]) expect(next.players[0]!.carrying).toBeUndefined() }) it('folds debrisInspected only when the authentic value is present (inspector)', () => { let state = toWireState(engineState()) state = applyWireEvent( state, projectActionToWire({ type: 'itemDropped', serverTime: 10, did: 'did:a', debrisId: 'x1', pos: { x: 0, y: 0 } }, 'did:b'), )! // observer (no authentic attached) → unchanged const obs = applyWireEvent(state, projectActionToWire({ type: 'debrisInspected', serverTime: 11, did: 'did:c', debrisId: 'x1' }, 'did:b'))! expect(obs.debris[0]!.authentic).toBeUndefined() // inspector (server attaches authentic) → learns it const insp = applyWireEvent(state, { ...(projectActionToWire({ type: 'debrisInspected', serverTime: 11, did: 'did:c', debrisId: 'x1' }, 'did:c') as object), authentic: false, } as WireAction)! expect(insp.debris[0]!.authentic).toBe(false) }) it('folds a vote: opened (via callVote) → cast → ended(kick)', () => { let state = toWireState(engineState()) // a successful callVote opens the vote as its resolution's effect (no standalone vote-start action) state = applyWireEvent(state, { $type: 'town.deception.defs#actionResolved', serverTime: 1, did: 'did:b', effect: { voteOpened: { startedAt: 1, endsAt: 5000 } }, } as WireAction)! expect(state.vote).toEqual({ startedAt: 1, endsAt: 5000, ballots: [] }) state = applyWireEvent(state, projectActionToWire({ type: 'voteCast', serverTime: 2, voterDid: 'did:b', targetDid: 'did:a' }, 'did:b'))! expect(state.vote!.ballots).toEqual([{ voter: 'did:b', target: 'did:a' }]) state = applyWireEvent(state, projectActionToWire({ type: 'voteEnded', serverTime: 3, kickedDid: 'did:a' }, 'did:b'))! expect(state.vote).toBeUndefined() expect(state.players.find((p) => p.did === 'did:a')!.status).toBe('kicked') }) }) // --- the load-bearing invariant: folding an enriched event === re-projecting -- // // For every dispatched action and every viewer, applying the (enriched) projected event onto the // projected prev-state must reproduce the projected next-state exactly. This is what guarantees an // observer can maintain correct state from the #event stream alone. describe('fold ≡ project (engine-driven round)', () => { const SAB = 'did:s' const OBS = 'did:a' const viewers: (Did | null)[] = [SAB, OBS, null] /** Mirror the server's per-viewer event construction (projected action + enrichment). */ function wireFor(action: Action, prev: GameState, next: GameState, viewer: Did | null): WireAction { const wire = projectActionToWire(action, viewer) as Record if (action.type === 'actionResolved') { const e = projectResolvedEffect(prev, next, action.did, viewer) if (e) wire.effect = e } else if (action.type === 'debrisInspected') { const a = projectInspectAuthentic(next, action.debrisId, action.did, viewer) if (a !== undefined) wire.authentic = a } return wire as WireAction } // seq/now come from the envelope at runtime; normalize them out of the structural comparison. const norm = (s: ProjectedState): ProjectedState => ({ ...s, seq: 0, now: 0 }) function step(state: GameState, action: Action): GameState { const next = reduce(state, action) for (const v of viewers) { const folded = applyWireEvent(toWireState(projectFor(state, v)), wireFor(action, state, next, v)) expect(folded, `${action.type} folds for ${v ?? 'spectator'}`).not.toBeNull() expect(norm(folded!), `${action.type} fold ≡ project for ${v ?? 'spectator'}`).toEqual( norm(toWireState(projectFor(next, v))), ) } return next } function activity( state: GameState, did: string, stationId: string, slot: number, kind: Parameters[0], at: number, rng?: { sabotageTriggered?: boolean; fakeRepairExtra?: number }, ): GameState { const endsAt = at + timerFor(kind, state.config) // collect/pretendCollect need a resource; default to the station's first collectable const resourceId = kind === 'collect' || kind === 'pretendCollect' ? state.stations[stationId]?.collect[0] : undefined let s = step(state, { type: 'actionStarted', serverTime: at, did, stationId, slot, kind, resourceId, endsAt }) s = step(s, rng ? { type: 'actionResolved', serverTime: endsAt, did, rng } : { type: 'actionResolved', serverTime: endsAt, did }) return s } it('every activity in a round folds identically to a re-projection, per viewer', () => { // DIDS = ['did:s'(saboteur), 'did:a', 'did:b', 'did:c']; all spawn at origin, inside res-0's area. let s = setup({ startRound: true }) // resources = ['wood','stone','wheat','ore'] s = activity(s, 'did:a', 'res-wood', 0, 'collect', 10) // worker collects real wood s = activity(s, SAB, 'res-wood', 0, 'sabotage', 3_000) // saboteur arms res-wood (hidden from OBS) s = activity(s, 'did:b', 'res-wood', 0, 'inspect', 12_000) // did:b learns it (per-viewer reveal) s = activity(s, 'did:a', 'deposit', 0, 'deposit', 21_000) // bank the real wood (resources++ public) s = activity(s, SAB, 'res-stone', 0, 'pretendCollect', 24_000) // saboteur carries a fake s = activity(s, 'did:c', 'res-wood', 0, 'collect', 26_000, { sabotageTriggered: true }) // breaks (public) s = activity(s, SAB, 'deposit', 0, 'fakeDeposit', 28_000) // fake deposit vanishes (no resource change) expect(s.resources.wood).toBe(1) s = activity(s, 'did:b', 'meeting', 0, 'callVote', 30_000) // opens a vote — folds via voteOpened expect(s.vote).not.toBeNull() }) it('roundEnded folds phase/outcome, and the follow-up snapshot reveals all roles', () => { const s = setup({ startRound: true }) const action: Action = { type: 'roundEnded', serverTime: 100, outcome: 'saboteur' } const ended = reduce(s, action) for (const v of viewers) { const folded = applyWireEvent(toWireState(projectFor(s, v)), projectActionToWire(action, v))! expect(folded.phase).toBe('ended') expect(folded.outcome).toBe('saboteur') // the fold itself doesn't reveal — the server's follow-up snapshot of the ended state does: const snap = toWireState(projectFor(ended, v)) expect(snap.players.every((p) => p.role != null)).toBe(true) expect(snap.players.filter((p) => p.role === 'saboteur')).toHaveLength(1) } }) })