peer-kit / test / vectors / generate-lampion.mjs
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/**
 * Provenance generator for test/vectors/lampion-client.json — the fixture that
 * pins LampionClient's world/local slot tracking (peer-kit 2.0.1, bug 2).
 *
 * Unlike generate.mjs (which extracted vectors from peer-kit's own retired
 * TypeScript), this one takes its ground truth from the OTHER side of the wire:
 * game5's ClojureScript client, which is the spec of record for lampion's
 * protocol. Every host frame here is built by game5's own frame builders, every
 * host tick by its own `tick-step!`, and every expected client position by its
 * own `apply-turn!` / `apply-move!` / `apply-fingerprint!` — so the fixture
 * cannot encode a misreading of game5, only game5.
 *
 * Point GAME5_TESTLIB at a game5 checkout's compiled test entry
 * (client/test-dist/testlib.js, written by `npm test` in that repo) and run:
 *
 *   GAME5_TESTLIB=<path to game5 client/test-dist/testlib.js> \
 *     node test/vectors/generate-lampion.mjs
 *
 * The ONLY logic transcribed here rather than imported is peer-kit's own bot
 * policy (the 3-tick action cooldown and the nearest-stair choice) — it has no
 * game5 counterpart. It is a closed loop: the modelled bot's action is queued on
 * the real host sim, so the recorded frames are the ones the real bot would
 * actually provoke, and test/lampion.test.mjs replays them into the real
 * LampionClient and compares both its internal fold and its sends.
 */
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

const testlib = process.env.GAME5_TESTLIB;
if (!testlib) {
  console.error("set GAME5_TESTLIB to a game5 checkout's client/test-dist/testlib.js");
  process.exit(1);
}
const lib = await import(testlib);

const OUT = dirname(fileURLToPath(import.meta.url));
const clone = (x) => JSON.parse(JSON.stringify(x));

/* ---------------------------------------------------------------- config ---- */

// game5's config.cljs, re-pinned by its own sim.json vector ("the constants the
// whole simulation is built from have not drifted").
const S = 12;
const RINGS = 6;
const TOP = 5;
const TICK_MS = 125;
const ROUND_TICKS = 720;
const A = { CCW: 0, CW: 1, UP: 2, DOWN: 3, ROT_CCW: 4, ROT_CW: 5 };

// The hill: game5's committed sim.json vector `levels[0]` — rollLevel(seed 1).
// Deliberately a level whose rots are ALL non-zero and whose ring 2 clockwork
// runs counter-clockwise, so a rotation-blind client is wrong from tick 1.
const LEVEL = {
  stairs: [[3, 6], [2, 8], [3, 5], [3], [3], []],
  rots: [5, 11, 5, 5, 1, 4],
  auto: [[49, 1], [44, 1], [34, -1], [27, 1], [19, 1], [0, 1]],
};

const IDS = [
  "12D3KooWAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "12D3KooWBbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
  "12D3KooWCcccccccccccccccccccccccccccccccccccccccccccc",
];
const SEAT = 0; // the seat the bot under test sits in

/* ------------------------------------------------------- the host, exactly -- */

const newHost = () => {
  const starts = Array.from(lib.spawnStarts(IDS.length));
  return {
    // game5 host-start-round's climber shape
    climbers: IDS.map((id, i) => ({
      id, ring: 0, slot: starts[i], pend: [],
      alive: true, lastMove: -99, lastRot: -99, best: 0, bestAt: 0,
    })),
    stairs: clone(LEVEL.stairs),
    // H.rots is a COPY: the level frame keeps the round's OPENING rotations
    rots: clone(LEVEL.rots),
    auto: clone(LEVEL.auto),
    starts,
  };
};

const hostTick = (h, n) => {
  const res = lib.tickStep(h.climbers, h.stairs, h.rots, h.auto, n);
  return lib.mkTk(n, res[0], res[1], lib.heartbeat(h.climbers, n));
};

// game5 game/send-snap: level.rots is EMPTY, the live set rides at top level.
const hostSnap = (h, n) =>
  lib.mkSn(1, TICK_MS, ROUND_TICKS, n, IDS.slice(),
    lib.mkLevel(h.stairs, [], h.auto), h.rots.slice(),
    h.climbers.map((p) => [p.ring, p.slot, p.alive ? 1 : 0]));

/* -------------------------------------------- the client fold, also exactly - */

// game5 game/apply-start's pg shape, and its rots/rotc seeding
const foldFromStart = () => {
  const starts = Array.from(lib.spawnStarts(IDS.length));
  return {
    pg: IDS.map((id, i) => ({
      id, color: i, nick: `n${i}`, ring: 0, slot: starts[i],
      alive: true, tgtA: starts[i], visA: starts[i], visR: 0,
    })),
    rots: clone(LEVEL.rots),
    rotc: clone(LEVEL.rots),
  };
};

// game5 game/apply-snap's pg shape, seeded from the snapshot's top-level rots
const foldFromSnap = (sn) => ({
  pg: sn.order.map((id, s) => {
    const e = sn.ps[s];
    return {
      id, color: s, nick: `n${s}`, ring: e[0], slot: e[1],
      alive: e[2] !== 0, tgtA: e[1], visA: e[1], visR: e[0],
    };
  }),
  rots: sn.rots.slice(),
  rotc: sn.rots.slice(),
});

// game5 game/apply-tick, in its exact order: rt, then mv, then fp
const foldTick = (f, tk) => {
  if (tk.rt) for (const e of tk.rt) lib.applyTurn(f.pg, f.rots, f.rotc, e[0], e[1]);
  if (tk.mv) for (const e of tk.mv) lib.applyMove(f.pg, e[0], e[1], e[2]);
  if (tk.fp) lib.applyFingerprint(f.pg, tk.fp);
};

/* ----------------------------------------- peer-kit's own bot policy, modelled */

const ringDist = (a, b) => {
  const d = Math.abs(a - b) % S;
  return Math.min(d, S - d);
};
const sMod = (x) => (((x % S) + S) % S);

/** The action LampionClient should choose in this state, or null where it
 *  coin-flips (no stairs on the ring it stands on). worldOf/localOf are game5's
 *  own, imported — the conversion is never re-derived here. */
const decide = (fold, stairs) => {
  const p = fold.pg[SEAT];
  const ring = p.ring;
  const slot = p.slot; // a WORLD slot
  const mine = stairs[ring] ?? [];
  if (mine.indexOf(lib.localOf(slot, ring, fold.rots)) >= 0) return { a: A.UP, target: slot };
  if (mine.length === 0) return { a: null, target: null };
  const worlds = mine.map((s) => lib.worldOf(s, ring, fold.rots));
  const target = worlds.reduce((best, w) => (ringDist(slot, w) < ringDist(slot, best) ? w : best));
  return { a: sMod(target - slot) <= 6 ? A.CW : A.CCW, target };
};

/* ------------------------------------------------------------ run A: from "st" */

const runFromStart = (ticks) => {
  const h = newHost();
  const fold = foldFromStart();
  const st = lib.mkSt(1, TICK_MS, ROUND_TICKS, IDS.slice(),
    lib.mkLevel(h.stairs, LEVEL.rots, h.auto), h.starts.slice());
  const out = { st: clone(st), expectAtStart: snap(fold), ticks: [] };
  let lastMove = -10;
  for (let n = 1; n <= ticks; n++) {
    const tk = hostTick(h, n);
    foldTick(fold, tk);
    const row = { frame: clone(tk), ...snap(fold), send: null };
    if (n - lastMove >= 3) {
      const d = decide(fold, h.stairs);
      row.send = d;
      lastMove = n;
      if (d.a !== null) lib.pushInput(h.climbers[SEAT], d.a);
    }
    out.ticks.push(row);
  }
  return out;
};

/** What the client under test must believe after this frame. */
const snap = (fold) => ({
  ring: fold.pg[SEAT].ring,
  slot: fold.pg[SEAT].slot,
  rots: fold.rots.slice(),
  local: lib.localOf(fold.pg[SEAT].slot, fold.pg[SEAT].ring, fold.rots),
});

/* ------------------------------------------- run B: a late join through "sn" -- */

// Seat 0 is scripted (not the bot) up to the snapshot, so the hill and the
// climbers are somewhere arbitrary by the time the newcomer arrives; both
// cranks fire early so ring 0 turns in BOTH directions before the snapshot.
const PRE_SCRIPT = {
  3: [[2, A.ROT_CCW]],
  6: [[1, A.ROT_CW]],
  9: [[0, A.CW]], 12: [[0, A.CW]], 15: [[0, A.UP]],
  18: [[0, A.CCW]], 21: [[0, A.CW]], 24: [[0, A.UP]],
  27: [[0, A.CW]], 30: [[1, A.ROT_CCW]], 33: [[0, A.CCW]],
};

const runFromSnap = (snapAt, ticks) => {
  const h = newHost();
  for (let n = 1; n <= snapAt; n++) {
    for (const [seat, a] of PRE_SCRIPT[n] ?? []) lib.pushInput(h.climbers[seat], a);
    hostTick(h, n);
  }
  const sn = clone(hostSnap(h, snapAt));
  const fold = foldFromSnap(sn);
  const out = { sn, expectAtSnap: snap(fold), ticks: [] };
  let lastMove = -10;
  for (let n = snapAt + 1; n <= snapAt + ticks; n++) {
    const tk = hostTick(h, n);
    foldTick(fold, tk);
    const row = { frame: clone(tk), ...snap(fold), send: null };
    if (n - lastMove >= 3) {
      const d = decide(fold, h.stairs);
      row.send = d;
      lastMove = n;
      if (d.a !== null) lib.pushInput(h.climbers[SEAT], d.a);
    }
    out.ticks.push(row);
  }
  return out;
};

/* ------------------------------------------------------------------- claims -- */

// The host-election truth table, answered by game5's OWN comparator
// (sim/bystander-claim-wins) — the rule a lampion browser applies to a foreign
// self-claim while it follows another host. `drive` is the frame that puts a
// LampionClient into that phase, so the test reaches every row through the wire
// instead of poking _phase.
const PHASES = [
  { phase: "idle", live: false, drive: null },
  { phase: "lobby", live: false, drive: "lo" },
  { phase: "countdown", live: true, drive: "st" },
  { phase: "playing", live: true, drive: "tk" },
  { phase: "roundover", live: true, drive: "ov" },
  { phase: "matchover", live: false, drive: "ma" },
];
const claims = [];
for (const p of PHASES) {
  for (const theirLive of [true, false]) {
    for (const [from, host] of [["aaa", "bbb"], ["bbb", "aaa"], ["mmm", "mmm"]]) {
      claims.push({
        phase: p.phase, drive: p.drive, incumbentLive: p.live, theirLive, from, host,
        out: Boolean(lib.bystanderClaimWins(theirLive, p.live, from, host)),
      });
    }
  }
}

/* --------------------------------------------------------------- worldLocal -- */

// game5's localOf/worldOf over every (offset, slot) pair — so the test can check
// peer-kit's conversion against a full table, not just the replay's states.
const worldLocal = [];
for (let off = 0; off < S; off++) {
  const rots = Array.from({ length: RINGS }, () => off);
  for (let v = 0; v < S; v++) {
    worldLocal.push([off, v, lib.worldOf(v, 0, rots), lib.localOf(v, 0, rots)]);
  }
}

/* -------------------------------------------------------------------- write -- */

const data = {
  _note:
    "Ground truth imported from game5's compiled CLJS client (game/sim.cljs, " +
    "game/frames.cljs): spawnStarts, tickStep, heartbeat, mkSt/mkTk/mkSn/mkLevel, " +
    "applyTurn/applyMove/applyFingerprint, worldOf/localOf. LEVEL is game5's own " +
    "sim.json vector levels[0] (rollLevel seed 1). See generate-lampion.mjs.",
  S, RINGS, TOP, actions: A,
  seat: SEAT,
  order: IDS,
  level: LEVEL,
  worldLocal,
  claims,
  fromStart: runFromStart(120),
  fromSnap: runFromSnap(24, 150),
};

writeFileSync(join(OUT, "lampion-client.json"), `${JSON.stringify(data)}\n`);
console.log("wrote lampion-client.json");
const ranks = data.fromStart.ticks.map((r) => r.ring);
console.log("fromStart rings reached:", [...new Set(ranks)].join(","),
  "| rt ticks:", data.fromStart.ticks.filter((r) => r.frame.rt).length,
  "| fp ticks:", data.fromStart.ticks.filter((r) => r.frame.fp).length,
  "| coin flips:", data.fromStart.ticks.filter((r) => r.send && r.send.a === null).length);
console.log("fromSnap rings reached:",
  [...new Set(data.fromSnap.ticks.map((r) => r.ring))].join(","),
  "| rt ticks:", data.fromSnap.ticks.filter((r) => r.frame.rt).length,
  "| coin flips:", data.fromSnap.ticks.filter((r) => r.send && r.send.a === null).length);

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/peer-kit.git