| 1 | import test from 'node:test'; |
| 2 | import assert from 'node:assert/strict'; |
| 3 | import { readFileSync } from 'node:fs'; |
| 4 | import { PetWorld } from '../dist/core/pet-world.js'; |
| 5 | import { PetNative } from '../dist/core/pet-native.js'; |
| 6 | import { compilePetTelemetry, encodePetJSONL } from '../dist/core/pet-telemetry.js'; |
| 7 | import { petDemoEvents } from '../dist/core/pet-demo.js'; |
| 8 | import { stableHash } from '../dist/core/model.js'; |
| 9 | |
| 10 | const points = readFileSync(new URL('../public/whale-points.tsv', import.meta.url), 'utf8').trim().split('\n').map(row => row.trim().split(/\s+/).map(Number)); |
| 11 | const tape = compilePetTelemetry(petDemoEvents(), 80_000); |
| 12 | const motion = tick => tick % 107 < 71; |
| 13 | const equal = (a, b) => { |
| 14 | assert.deepEqual(a.frame, b.frame); |
| 15 | assert.deepEqual(a.sim.checkpoint(), b.sim.checkpoint()); |
| 16 | assert.deepEqual(a.voices, b.voices); |
| 17 | }; |
| 18 | |
| 19 | test('recording segments preserve exact continuation and replay while retiring only durably archived input', () => { |
| 20 | const reference = new PetWorld(points, tape), world = new PetWorld(points, tape, [], 2, true); |
| 21 | let prepared, archive, archivedEnd; |
| 22 | for (let tick = 0; tick < 1400; tick++) { |
| 23 | if (tick % 97 === 0) { reference.interact('food', .2, -.15); world.interact('food', .2, -.15); } |
| 24 | if (tick === 600) { |
| 25 | archive = JSON.parse(JSON.stringify(world.recording())); archivedEnd = JSON.parse(JSON.stringify(world.checkpoint())); |
| 26 | const before = JSON.stringify(world.recording()); prepared = world.prepareSegment(); |
| 27 | assert.equal(JSON.stringify(world.recording()), before, 'preparation cannot retire history before storage succeeds'); |
| 28 | archive = structuredClone(prepared.archive); |
| 29 | assert.ok(archive.tape.every(b => b.simTimeMs <= world.frame.timeMs), 'future telemetry belongs to the active segment, not every archive'); |
| 30 | assert.ok(archive.interactions.every(e => e.timeMs <= world.frame.timeMs)); |
| 31 | const pieces = []; for (let i = 0; ; i++) { const part = world.recordingChunk(i, true); if (part === null) break; pieces.push(part); } |
| 32 | assert.equal(pieces.join(''), JSON.stringify(archive)); |
| 33 | equal(PetWorld.fromRecording(points, prepared.recording), world); |
| 34 | } |
| 35 | if (tick === 609) { |
| 36 | prepared.commit(); equal(world, reference); |
| 37 | assert.ok(world.tape[0].sequence > 0); assert.ok(world.interactions.length < reference.interactions.length); |
| 38 | assert.throws(() => prepared.commit(), /changed/); |
| 39 | const restored = PetWorld.fromRecording(points, JSON.parse(JSON.stringify(world.recording()))); |
| 40 | equal(restored, world); |
| 41 | } |
| 42 | const opts = { motion: motion(tick), sensitivity: 1 }; |
| 43 | reference.step(1 / 30, opts); world.step(1 / 30, opts); equal(world, reference); |
| 44 | } |
| 45 | const replay = PetWorld.fromRecording(points, { ...world.recording(), checkpoint: undefined }); |
| 46 | for (let tick = Math.round(replay.frame.timeMs * 30 / 1000); tick < 1400; tick++) replay.step(1 / 30, { motion: motion(tick), sensitivity: 1 }); |
| 47 | equal(replay, world); |
| 48 | const earlier = PetWorld.fromRecording(points, archive); |
| 49 | assert.deepEqual(earlier.sim.checkpoint(), archivedEnd.sim); |
| 50 | assert.equal(earlier.frame.timeMs, 20_000); |
| 51 | const chunks = []; for (let i = 0; ; i++) { const chunk = world.recordingChunk(i); if (chunk === null) break; chunks.push(chunk); } |
| 52 | assert.equal(chunks.join(''), JSON.stringify(world.recording())); |
| 53 | for (const edit of [r => delete r.start, r => r.start.history++, r => r.start.historyStart++, |
| 54 | r => r.checkpoint.historyStart++, r => r.petReplayVersion = 1, r => r.start.sim.expressionVersion = 1]) { |
| 55 | const corrupt = structuredClone(world.recording()); edit(corrupt); |
| 56 | assert.throws(() => PetWorld.fromRecording(points, corrupt)); |
| 57 | } |
| 58 | }); |
| 59 | |
| 60 | test('native rotation retains a bounded active history and does not retrigger old approval or score state', () => { |
| 61 | const live = new PetNative(JSON.stringify(points), '', '[]', true); |
| 62 | let archived = 0, largest = 0; |
| 63 | for (let step = 0; step < 180; step++) { |
| 64 | const at = step * 5000; |
| 65 | live.observeEngine(JSON.stringify({ event: 'tool_call_started', tool_call_id: String(step), tool_name: 'exec_command' }), at); |
| 66 | live.advanceEngine(at + 5000, false, false); |
| 67 | largest = Math.max(largest, JSON.parse(live.recording()).tape.length); |
| 68 | if (live.needsSegment()) { |
| 69 | const before = live.snapshot(), outgoing = live.recording(true), next = live.prepareSegment(); |
| 70 | assert.equal(live.recording(true), outgoing); |
| 71 | const restored = new PetNative(JSON.stringify(points)); restored.restoreRecording(next); |
| 72 | assert.equal(restored.snapshot(), before); |
| 73 | live.commitSegment(); assert.equal(live.snapshot(), before); archived++; |
| 74 | } |
| 75 | } |
| 76 | assert.equal(archived, 2); assert.ok(largest <= 1040); |
| 77 | const resumed = new PetNative(JSON.stringify(points)); resumed.restoreRecording(live.recording(true)); |
| 78 | assert.equal(resumed.snapshot(), live.snapshot()); |
| 79 | const offset = resumed.resumeEngine(); resumed.advanceEngine(offset + 800, false, true); |
| 80 | assert.equal(JSON.parse(resumed.snapshot()).state.observed, 0); |
| 81 | assert.equal(JSON.parse(resumed.snapshot()).needs, 'none'); |
| 82 | assert.ok(Buffer.byteLength(resumed.recording(true)) < 1024 * 1024); |
| 83 | }); |
| 84 | |
| 85 | test('chunked exports preserve the complete versioned recording and exact checkpoint beyond the autosave bound', () => { |
| 86 | for (const count of [0, 1, 16, 17, 32_000]) { |
| 87 | const tape = count ? compilePetTelemetry([], count * 400) : []; |
| 88 | const world = new PetWorld(points, tape); |
| 89 | // Cross both kinds of chunk boundary, including pending interactions. |
| 90 | for (let i = 0; i < 17; i++) world.interact('food', i / 20, -.2); |
| 91 | world.step(.1); world.interact('attention', -.2, .3); |
| 92 | const chunks = []; |
| 93 | for (let i = 0; ; i++) { |
| 94 | const chunk = world.recordingChunk(i); if (chunk === null) break; |
| 95 | chunks.push(chunk); |
| 96 | } |
| 97 | const text = chunks.join(''), recording = JSON.parse(text); |
| 98 | assert.equal(text, JSON.stringify({ petReplayVersion: 1, expressionVersion: 2, tape: world.tape, |
| 99 | interactions: world.interactions, checkpoint: world.checkpoint() })); |
| 100 | const restored = PetWorld.restore(points, recording.tape, recording.interactions, recording.checkpoint); |
| 101 | equal(world, restored); world.step(.1); restored.step(.1); equal(world, restored); |
| 102 | if (count === 32_000) { |
| 103 | assert.ok(Buffer.byteLength(text) > 8 * 1024 * 1024); |
| 104 | assert.ok(Math.max(...chunks.map(c => Buffer.byteLength(c))) < 512 * 1024); |
| 105 | } |
| 106 | assert.throws(() => world.recordingChunk(-1)); |
| 107 | assert.throws(() => world.recordingChunk(.5)); |
| 108 | } |
| 109 | const native = new PetNative(JSON.stringify(points), encodePetJSONL(tape)); |
| 110 | const chunks = []; |
| 111 | for (let i = 0; ; i++) { const part = native.recordingChunk(i); if (part === null) break; chunks.push(part); } |
| 112 | assert.equal(chunks.join(''), native.recording(true)); |
| 113 | }); |
| 114 | |
| 115 | test('JSON checkpoints continue exact particles, seeded behaviour, pod identities, interactions and score across motion changes', () => { |
| 116 | for (const input of [[], tape]) { |
| 117 | const world = new PetWorld(points, input); |
| 118 | for (let tick = 0; tick < 800; tick++) { |
| 119 | if (tick === 210) { world.interact('food', .3, -.2); world.interact('attention', -.2, .1); } |
| 120 | world.step(1 / 30, { motion: motion(tick), sensitivity: 1 }); |
| 121 | } |
| 122 | // Preserve pending same-tick interactions and a fractional display remainder. |
| 123 | world.interact('food', -.1, .3); world.interact('attention', .4, .2); |
| 124 | world.step(.013, { motion: true, sensitivity: 1 }); |
| 125 | const checkpoint = JSON.parse(JSON.stringify(world.checkpoint())); |
| 126 | const restored = PetWorld.restore(points, world.tape, world.interactions, checkpoint); |
| 127 | equal(restored, world); |
| 128 | for (let tick = 800; tick < 1160; tick++) { |
| 129 | if (tick === 813) { restored.interact('attention', .2, .1); world.interact('attention', .2, .1); } |
| 130 | const opts = { motion: motion(tick), sensitivity: 1 }; |
| 131 | world.step(1 / 30, opts); restored.step(1 / 30, opts); equal(restored, world); |
| 132 | } |
| 133 | checkpoint.sim.particles[0][0] = 7; |
| 134 | assert.notEqual(restored.sim.p[0].x, 7, 'restoration owns its state instead of aliasing the imported checkpoint'); |
| 135 | } |
| 136 | }); |
| 137 | |
| 138 | test('checkpoint restore rejects a different recording, authored body, malformed physics and invalid clocks without altering the source', () => { |
| 139 | const world = new PetWorld(points, tape); world.step(8); |
| 140 | const checkpoint = world.checkpoint(), before = JSON.stringify(checkpoint); |
| 141 | for (const edit of [c => c.petCheckpointVersion = 2, c => c.tick = -1, c => c.random = 2 ** 32, |
| 142 | c => c.frame.timeMs++, c => c.sim.body[0][0] = .99, c => c.sim.particles[0][0] = Infinity, |
| 143 | c => c.sim.particles[0] = [], c => c.score[0] = -.5, c => c.members = [{ id: 'x', slot: 8, phase: 1, present: true }], |
| 144 | c => c.voices = [{ id: 'bad', start: 0, duration: 1, frequency: 9e9, gain: .1, pan: 0, kind: 'tone' }]]) { |
| 145 | const copy = structuredClone(checkpoint); edit(copy); |
| 146 | assert.throws(() => PetWorld.restore(points, tape, [], copy)); |
| 147 | } |
| 148 | const other = structuredClone(tape); other[0].activity = .99; |
| 149 | assert.throws(() => PetWorld.restore(points, other, [], checkpoint), /recording/); |
| 150 | assert.equal(JSON.stringify(world.checkpoint()), before); |
| 151 | }); |
| 152 | |
| 153 | test('the native JSON boundary restores exact state and leaves its old world intact after a rejected checkpoint', () => { |
| 154 | const a = new PetNative(JSON.stringify(points), encodePetJSONL(tape)); |
| 155 | for (let i = 0; i < 970; i++) a.step(1 / 30, motion(i)); |
| 156 | const b = new PetNative(JSON.stringify(points), encodePetJSONL(tape)); |
| 157 | b.restoreCheckpoint(a.checkpoint()); assert.equal(b.snapshot(), a.snapshot()); |
| 158 | for (let i = 970; i < 1050; i++) assert.equal(b.step(1 / 30, motion(i)), a.step(1 / 30, motion(i))); |
| 159 | const before = b.snapshot(); |
| 160 | assert.throws(() => b.restoreCheckpoint('{"petCheckpointVersion":99}')); |
| 161 | assert.equal(b.snapshot(), before); |
| 162 | }); |
| 163 | |
| 164 | test('doze and wake survive a checkpoint without consuming another random choice or retriggering the old score', () => { |
| 165 | const world = new PetWorld(points); |
| 166 | for (let i = 0; i < 9; i++) world.step(10, { motion: false, sensitivity: 1 }); |
| 167 | assert.equal(world.frame.behaviour, 'doze'); |
| 168 | const copy = PetWorld.restore(points, world.tape, world.interactions, JSON.parse(JSON.stringify(world.checkpoint()))); |
| 169 | world.interact('attention', .2, .1); copy.interact('attention', .2, .1); |
| 170 | for (let i = 0; i < 100; i++) { |
| 171 | world.step(1 / 30); copy.step(1 / 30); equal(copy, world); |
| 172 | if (i === 0) assert.equal(copy.frame.behaviour, 'wake'); |
| 173 | } |
| 174 | }); |
| 175 | |
| 176 | test('a native live habitat keeps accepted history but resumes with an explicit gap and no stale human request', () => { |
| 177 | const live = new PetNative(JSON.stringify(points), '', '[]', true); |
| 178 | live.observeEngine(JSON.stringify({event: 'approval_required', id: 'request-a'}), 0); |
| 179 | live.advanceEngine(3200, true, true); |
| 180 | const before = JSON.parse(live.snapshot()); |
| 181 | assert.equal(before.state.channel, 'human'); |
| 182 | const saved = live.recording(true), recording = JSON.parse(saved); |
| 183 | const restored = new PetNative(JSON.stringify(points), '', '[]', true); |
| 184 | restored.restoreRecording(saved); |
| 185 | assert.equal(restored.snapshot(), live.snapshot()); |
| 186 | const offset = restored.resumeEngine(); |
| 187 | assert.ok(offset >= before.timeMs && offset <= before.timeMs + 800); |
| 188 | assert.equal(JSON.parse(restored.snapshot()).state.observed, 0); |
| 189 | assert.deepEqual(JSON.parse(restored.recording()).tape, recording.tape); |
| 190 | // Shell waiting alone cannot resurrect a historical approval request. |
| 191 | restored.advanceEngine(offset + 1200, false, true); |
| 192 | assert.equal(JSON.parse(restored.snapshot()).state.observed, 0); |
| 193 | assert.equal(JSON.parse(restored.snapshot()).needs, 'none'); |
| 194 | restored.observeEngine(JSON.stringify({event: 'approval_required', id: 'request-b'}), offset + 1300); |
| 195 | restored.advanceEngine(offset + 2000, false, true); |
| 196 | assert.equal(JSON.parse(restored.snapshot()).state.channel, 'human'); |
| 197 | const current = restored.snapshot(); |
| 198 | assert.throws(() => restored.restoreRecording('{"petReplayVersion":2}')); |
| 199 | assert.equal(restored.snapshot(), current); |
| 200 | }); |
| 201 | |
| 202 | test('the initial native live checkpoint and a source that has already expired can both resume', () => { |
| 203 | for (const at of [0, 9200]) { |
| 204 | const a = new PetNative(JSON.stringify(points), '', '[]', true); |
| 205 | a.advanceEngine(at, false, false); |
| 206 | const b = new PetNative(JSON.stringify(points), '', '[]', true); |
| 207 | b.restoreRecording(a.recording(true)); |
| 208 | assert.equal(b.snapshot(), a.snapshot()); |
| 209 | const offset = b.resumeEngine(); |
| 210 | b.advanceEngine(offset + 400, false, false); |
| 211 | assert.equal(JSON.parse(b.snapshot()).state.observed, 0); |
| 212 | } |
| 213 | }); |
| 214 | |
| 215 | test('incremental history checksums retain the version-one wire value across appended gaps, replacements and Unicode identities', () => { |
| 216 | const packet = structuredClone(tape[0]); packet.agentIds = ['alpha', '鲸', '🌊']; |
| 217 | for (const input of [compilePetTelemetry([]), tape]) { |
| 218 | const world = new PetWorld(points, input); |
| 219 | const check = () => assert.equal(world.checkpoint().history, stableHash(JSON.stringify([world.tape, world.interactions]))); |
| 220 | check(); world.step(2); world.acceptTelemetry(packet); check(); |
| 221 | world.interact('food', .2, -.1); world.interact('attention', -.3, .2); check(); |
| 222 | world.acceptTelemetry({ ...packet, attention: .7 }); check(); |
| 223 | world.step(1); world.acceptTelemetry(packet); check(); |
| 224 | world.interact('food', .1, -.2); check(); |
| 225 | const restored = PetWorld.restore(points, world.tape, world.interactions, world.checkpoint()); |
| 226 | assert.equal(restored.checkpoint().history, world.checkpoint().history); |
| 227 | } |
| 228 | }); |
| 229 |