peer-kit / test / vectors / generate.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
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
/**
 * Golden-vector extractor — run against the TypeScript implementation while it
 * was still canon (v1.3.0, HEAD 8105f14), per dev/docs/CLJS.md: "splice the
 * real modules into a harness rather than transcribing their logic into a
 * generator". Here the real modules ARE `dist/` (tsc output of src/), so this
 * script imports them directly and dumps their observable behaviour verbatim.
 *
 * The vectors it writes are the contract the ClojureScript port must satisfy
 * byte-for-byte — above all the host sims, the valley-blocks engine and the
 * gyms, which the RL trainer scores promotions against: a silent divergence
 * there corrupts training without any other test failing.
 *
 *   node test/vectors/generate.mjs            # writes test/vectors/*.json
 *
 * Deliberately NOT re-runnable against the CLJS build: it reaches into
 * internal dist paths (dist/core/…, dist/games/host/…) that the TS layout
 * exposed. `test/vectors.test.mjs` is what re-checks the vectors afterwards,
 * through the public package surface. Kept in the tree as the provenance
 * record for every fixture below.
 */
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

const OUT = dirname(fileURLToPath(import.meta.url));
const write = (name, data) => {
  writeFileSync(join(OUT, `${name}.json`), `${JSON.stringify(data, null, 2)}\n`);
  console.log(`wrote ${name}.json`);
};

/* ------------------------------------------------------------------ rng ---- */

const { mulberry32 } = await import("../../dist/games/host/rng.js");

{
  const seeds = [0, 1, 9, 11, 42, 1337, 424242, 0x7fffffff, 0xdeadbeef, -1];
  const out = seeds.map((seed) => {
    const rng = mulberry32(seed);
    return { seed, values: Array.from({ length: 24 }, () => rng()) };
  });
  write("rng", out);
}

/* -------------------------------------------------------------- framing ---- */

// lpEncode is module-private; its contract is "mirror @libp2p/utils'
// LengthPrefixedDecoder default", so the vector pins the encoder shape by
// round-tripping real frames through the real decoder and recording the bytes.
{
  const { LengthPrefixedDecoder } = await import("@libp2p/utils");
  const lpEncode = (bytes) => {
    const prefix = [];
    let n = bytes.length;
    while (n >= 0x80) {
      prefix.push((n & 0x7f) | 0x80);
      n >>>= 7;
    }
    prefix.push(n);
    const out = new Uint8Array(prefix.length + bytes.length);
    out.set(prefix, 0);
    out.set(bytes, prefix.length);
    return out;
  };
  const te = new TextEncoder();
  const td = new TextDecoder();

  // `pad` is described, not embedded: the fixture stays small while the frame
  // it pins stays exact (the test rebuilds it from `padChar`/`padLength`).
  const specs = [
    { frame: {} },
    { frame: { t: "hi", nick: "gazda", score: 0 } },
    { frame: { t: "in", d: 3 } },
    { frame: { t: "ro", host: "aaa", ps: [["aaa", "gazda", 0, 0]], live: 1 } },
    { frame: { t: "big" }, padChar: "x", padLength: 200 },
    { frame: { t: "bigger" }, padChar: "y", padLength: 20000 },
  ];
  const build = (s) => (s.padChar ? { ...s.frame, pad: s.padChar.repeat(s.padLength) } : s.frame);
  const frames = specs.map(build);
  const encoded = specs.map((s) => {
    const json = JSON.stringify(build(s));
    const bytes = lpEncode(te.encode(json));
    return {
      ...s,
      jsonLength: json.length,
      // the varint prefix in full, plus the total, so a port is checked
      // without embedding 20 KB of payload
      prefix: [...bytes.subarray(0, bytes.length - te.encode(json).length)],
      totalLength: bytes.length,
    };
  });

  // one concatenated stream of every frame, decoded in a single chunk: proves
  // the port's decoder handles coalesced frames the way the live stream does
  const stream = new Uint8Array(
    encoded.reduce((n, e) => n + e.totalLength, 0),
  );
  {
    let off = 0;
    for (const f of frames) {
      const b = lpEncode(te.encode(JSON.stringify(f)));
      stream.set(b, off);
      off += b.length;
    }
  }
  const dec = new LengthPrefixedDecoder({ maxDataLength: 64 * 1024 });
  const decoded = [];
  for (const chunk of dec.decode(stream)) decoded.push(td.decode(chunk.subarray()));

  write("framing", {
    maxFrameBytes: 64 * 1024,
    encoded,
    decodedLengths: decoded.map((d) => d.length),
    decodedShort: decoded.filter((d) => d.length <= 200),
  });
}

/* ---------------------------------------------------------- room-crypto ---- */

{
  const rc = await import("../../dist/core/room-crypto.js");
  const { RoomCrypto, newRoomSecret, toB64, fromB64, toB64url, fromB64url } = rc;

  const b64cases = [
    [],
    [0],
    [255],
    [0, 1, 2],
    [1, 2, 3, 4],
    [251, 252, 253, 254, 255],
    [...Array(32).keys()],
  ];
  const b64 = b64cases.map((arr) => {
    const bytes = new Uint8Array(arr);
    const s = toB64(bytes);
    const u = toB64url(bytes);
    return {
      bytes: arr,
      b64: s,
      b64url: u,
      roundTripB64: [...fromB64(s)],
      roundTripB64url: [...fromB64url(u)],
    };
  });

  // roomId is HKDF(secret, salt=appSalt, info="roomid") — fully deterministic
  const secrets = [
    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    "f3q9Xk2LmQ7zR4tYbN8pV1cJ0sD6hG5wA2eK9uI3oM4",
    toB64url(new Uint8Array([...Array(32).keys()])),
  ];
  const salts = ["game1.ardegazu.ro/v2", "game4.ardegazu.ro/v2", "chat.ardegazu.ro/v2"];
  const roomIds = [];
  for (const secret of secrets) {
    for (const appSalt of salts) {
      const r = await RoomCrypto.create(secret, appSalt);
      roomIds.push({ secret, appSalt, roomId: r.roomId });
    }
  }

  // sealHello's IV carries a random 4-byte epoch, so the ciphertext is not
  // reproducible. Decryption IS: capture real envelopes here and require the
  // port to open them (and to reject the tampered/mismatched ones).
  const sealed = [];
  const tamper = (ct) => {
    const i = Math.floor(ct.length / 2);
    const c = ct[i] === "A" ? "B" : "A";
    return ct.slice(0, i) + c + ct.slice(i + 1);
  };
  {
    const secret = secrets[1];
    const appSalt = salts[0];
    const A = "12D3KooWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    const B = "12D3KooWbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
    const idBlock = { pub: "p".repeat(43), sig: "s".repeat(86), name: "gazda", hue: 200 };
    for (const extra of [undefined, { id: idBlock }]) {
      // a fresh RoomCrypto per envelope keeps each fixture independent
      const s = await RoomCrypto.create(secret, appSalt);
      const env = await s.sealHello(A, B, extra);
      const o = await RoomCrypto.create(secret, appSalt);
      sealed.push({
        secret,
        appSalt,
        from: A,
        to: B,
        env,
        plaintext: await o.openHello(A, B, env),
        // the same envelope must NOT open under a swapped peer pair, a
        // different salt, or a tampered ciphertext
        rejectSwappedPair: await o.openHello(B, A, env),
        rejectWrongSalt: await (await RoomCrypto.create(secret, salts[1])).openHello(A, B, env),
        // flip one character in the MIDDLE of the ciphertext: mangling the
        // tail can land on base64 padding and decode to the same bytes
        tamperedCt: tamper(env.ct),
        rejectTampered: await o.openHello(A, B, { ...env, ct: tamper(env.ct) }),
      });
    }
    // malformed envelopes are rejected without throwing
    const o = await RoomCrypto.create(secret, appSalt);
    sealed.push({
      malformed: [
        await o.openHello(A, B, null),
        await o.openHello(A, B, { v: 1, iv: "x", ct: "y" }),
        await o.openHello(A, B, { v: 2, iv: 5, ct: "y" }),
        await o.openHello(A, B, { v: 2, iv: "x" }),
      ],
    });
  }

  write("room-crypto", {
    b64,
    roomIds,
    sealed,
    newRoomSecretShape: { length: newRoomSecret().length, re: "^[A-Za-z0-9_-]{43}$" },
    tooShortSecretThrows: await RoomCrypto.create("AAAA", "s").then(
      () => null,
      (e) => e.message,
    ),
  });
}

/* --------------------------------------------------------- vendored id ---- */
/**
 * The drift tripwire for retiring src/vendor/: every one of these outputs is
 * produced by the vendored TypeScript translation TODAY, and the real
 * ardegazu-id-kit / ardegazu-social-kit must reproduce it exactly once the
 * vendor directory is deleted. Ed25519 is deterministic, so signatures are
 * fixtures, not round trips.
 */
{
  const { Identity, verifyAssertion, verifyRaw } = await import("../../dist/vendor/id/identity.js");
  const { clampProfile, hueOfPub, effectiveHue, colorOfPub, EMPTY_PROFILE, MAX_NAME_LEN } =
    await import("../../dist/vendor/id/profile.js");
  const { deriveXKeyPair, deriveSuiteXKeyPair, signXCert, verifyXCert, SUITE_SALT } =
    await import("../../dist/vendor/id/xkey.js");

  const seeds = [
    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    "f3q9Xk2LmQ7zR4tYbN8pV1cJ0sD6hG5wA2eK9uI3oM4",
    "Zm9vYmFyYmF6cXV1eDEyMzQ1Njc4OTBhYmNkZWZnaGk",
  ];
  const identities = [];
  for (const seed of seeds) {
    const id = await Identity.fromSeed(seed);
    const x = await deriveSuiteXKeyPair(seed);
    const xs = await signXCert(id, SUITE_SALT, x.pubB64);
    const assertions = [
      ["game1.ardegazu.ro/v2", "roomA", "peer1"],
      ["game4.ardegazu.ro/v2", "roomB", "peer2"],
    ];
    identities.push({
      seed,
      publicKeyB64: id.publicKeyB64,
      fingerprint: id.fingerprint,
      hueOfPub: hueOfPub(id.publicKeyB64),
      colorOfPub: colorOfPub(id.publicKeyB64),
      xPubB64: x.pubB64,
      xPriv: [...x.priv],
      xCertSig: xs,
      xCertVerifies: await verifyXCert(SUITE_SALT, id.publicKeyB64, x.pubB64, xs),
      xCertRejectsWrongSalt: await verifyXCert("nope", id.publicKeyB64, x.pubB64, xs),
      boardSaltXPub: (await deriveXKeyPair(seed, "board.ardegazu.ro/v1")).pubB64,
      assertions: await Promise.all(
        assertions.map(async ([salt, roomId, peerId]) => {
          const sig = await id.assert(salt, roomId, peerId);
          return {
            salt,
            roomId,
            peerId,
            sig,
            verified: await verifyAssertion(salt, roomId, peerId, id.publicKeyB64, sig),
            rejectsWrongRoom: await verifyAssertion(salt, "other", peerId, id.publicKeyB64, sig),
            rejectsWrongSalt: await verifyAssertion("other", roomId, peerId, id.publicKeyB64, sig),
          };
        }),
      ),
      signRawB64url: await (async () => {
        const sig = await id.signRaw(new TextEncoder().encode("hello vector"));
        return toB64urlLocal(sig);
      })(),
    });
  }

  const profiles = [
    undefined,
    null,
    42,
    "str",
    {},
    { name: "  Gazda  ", hue: 200, glyph: "🐢x", lang: "ro" },
    { name: "x".repeat(80), hue: 359.9, glyph: "  ", lang: "RO" },
    { name: 5, hue: -1, glyph: 7, lang: "rom" },
    { name: "🦊🐢🐼", hue: 360, glyph: "🦋", lang: "hu" },
    { name: "a", hue: NaN, glyph: "", lang: "en" },
  ];

  write("vendor-id", {
    SUITE_SALT,
    EMPTY_PROFILE,
    MAX_NAME_LEN,
    identities,
    clampProfile: profiles.map((p) => ({ in: p ?? null, out: clampProfile(p) })),
    effectiveHue: [
      { pub: "abc", profile: null, out: effectiveHue("abc", null) },
      { pub: "abc", profile: { hue: 10 }, out: effectiveHue("abc", { hue: 10 }) },
      { pub: "abc", profile: { hue: 400 }, out: effectiveHue("abc", { hue: 400 }) },
    ],
    verifyRawRejectsGarbage: await verifyRaw("x", "y", new Uint8Array(3)),
  });

  function toB64urlLocal(bytes) {
    let s = "";
    for (const b of bytes) s += String.fromCharCode(b);
    return btoa(s).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
  }
}

/* ----------------------------------------------------- vendored social ---- */

{
  const { buildFriendLink, parseFriendLink, sanitizeFriend } =
    await import("../../dist/vendor/social/friends.js");
  const { SUITE_APPS } = await import("../../dist/vendor/social/invites.js");
  const consts = await import("../../dist/vendor/social/consts.js");
  const { canon, sha256B64url } = await import("../../dist/vendor/social/canon.js");
  const { roomHash, receiptHash, isoWeek, lbRoomId, lbTopic, MIN_SIGNERS } =
    await import("../../dist/vendor/social/receipts.js");
  const { pairChannel, selfChannel, inboxRoomId, envCtx } =
    await import("../../dist/vendor/social/pair.js");

  // A friend link is only parseable if its X25519 cert actually verifies, so
  // build `me` from a real seed rather than a made-up triple.
  const { Identity: Id } = await import("../../dist/vendor/id/identity.js");
  const { deriveSuiteXKeyPair: dxk, signXCert: sxc, SUITE_SALT: SS } =
    await import("../../dist/vendor/id/xkey.js");
  const meSeed = "f3q9Xk2LmQ7zR4tYbN8pV1cJ0sD6hG5wA2eK9uI3oM4";
  const meId = await Id.fromSeed(meSeed);
  const meX = await dxk(meSeed);
  const me = {
    pub: meId.publicKeyB64,
    x: meX.pubB64,
    xs: await sxc(meId, SS, meX.pubB64),
    name: "gazdă  ăîâșț",
  };
  const link = buildFriendLink("https://ardegazu.ro/", me);

  const friends = [
    null,
    {},
    { pub: me.pub },
    { pub: me.pub, x: me.x, xs: me.xs, name: "  Gazda  ", state: "friend", addedTs: 123 },
    { pub: "short", x: me.x, xs: me.xs },
    { pub: me.pub, x: me.x, xs: me.xs, state: "nonsense", note: "n".repeat(400), addedTs: -5 },
  ];

  write("vendor-social", {
    consts: Object.fromEntries(
      Object.entries(consts).filter(([, v]) => typeof v === "string" || typeof v === "number"),
    ),
    SUITE_APPS,
    MIN_SIGNERS,
    friendLink: {
      me,
      link,
      parsed: await parseFriendLink(link),
      parsedFromFragment: await parseFriendLink(link.slice(link.indexOf("#"))),
      parseGarbage: await Promise.all(
        [
          "",
          "#f=nope",
          "https://ardegazu.ro/",
          // right shape, forged cert — must be refused, not merely reshaped
          `#add=${me.pub}.${me.x}.${"A".repeat(86)}`,
        ].map((s) => parseFriendLink(s)),
      ),
    },
    sanitizeFriend: friends.map((f) => ({ in: f, out: sanitizeFriend(f) })),
    canon: [
      canon({ b: 1, a: 2 }),
      canon({ a: [3, { d: 4, c: 5 }] }),
      canon(null),
      canon("s"),
      canon(1),
    ],
    sha256B64url: await Promise.all(["", "abc", "the ghost shuns the parlour"].map(sha256B64url)),
    receipts: {
      roomHash: await roomHash("roomid-xyz"),
      receiptHash: await receiptHash({
        v: 1,
        g: "game1.ardegazu.ro/v2",
        m: "match-1",
        r: "rh",
        ts: 1700000000000,
        n: 2,
        sc: [
          { p: "a".repeat(43), nm: "one", s: 5 },
          { p: "b".repeat(43), nm: "two", s: 3 },
        ],
      }),
      isoWeek: [0, 1700000000000, 1704067200000, 1735689600000].map(isoWeek),
      lbRoomId: await lbRoomId("game1.ardegazu.ro/v2", "2024-W01"),
      lbTopic: await lbTopic("game1.ardegazu.ro/v2"),
    },
    pair: await (async () => {
      // both sides of one friendship must derive the SAME channel from their
      // own halves — the static-static DH property the whole social lane rests
      // on, so the fixture proves it rather than asserting one side's output
      const { deriveSuiteXKeyPair } = await import("../../dist/vendor/id/xkey.js");
      const { Identity } = await import("../../dist/vendor/id/identity.js");
      const seedA = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
      const seedB = "f3q9Xk2LmQ7zR4tYbN8pV1cJ0sD6hG5wA2eK9uI3oM4";
      const [idA, idB] = await Promise.all([Identity.fromSeed(seedA), Identity.fromSeed(seedB)]);
      const [xA, xB] = await Promise.all([deriveSuiteXKeyPair(seedA), deriveSuiteXKeyPair(seedB)]);
      const shape = async (ch, tagPubs) => ({
        id: ch.id,
        topic: ch.topic,
        mailboxRoomId: ch.mailboxRoomId,
        ctx: ch.ctx,
        tags: Object.fromEntries(await Promise.all(tagPubs.map(async (p) => [p, await ch.tagOf(p)]))),
      });
      const chA = await pairChannel(xA, idA.publicKeyB64, idB.publicKeyB64, xB.pubB64);
      const chB = await pairChannel(xB, idB.publicKeyB64, idA.publicKeyB64, xA.pubB64);
      const self = await selfChannel(seedA);
      // a real seal from A, opened by B: proves the port's AES-GCM/AAD wiring
      const wire = await chA.seal(idA.publicKeyB64, { hello: "pair", n: 7 });
      return {
        seeds: { seedA, seedB },
        pubs: { a: idA.publicKeyB64, b: idB.publicKeyB64 },
        fromA: await shape(chA, [idA.publicKeyB64, idB.publicKeyB64]),
        fromB: await shape(chB, [idA.publicKeyB64, idB.publicKeyB64]),
        self: await shape(self, [idA.publicKeyB64]),
        crossOpen: await chB.open(wire, [idA.publicKeyB64, idB.publicKeyB64]),
        crossOpenWrongMembers: await chB.open(wire, [idB.publicKeyB64]),
        crossOpenGarbage: await chB.open("not json", [idA.publicKeyB64]),
        inboxRoomId: await inboxRoomId(idA.publicKeyB64),
        envCtx: envCtx(idA.publicKeyB64),
      };
    })(),
  });
}

/* ------------------------------------------------------------ séance sim --- */

{
  const { SeanceSim, CANDLES, REVEAL_MS, walkMs, START_BELL_MS, OVER_LOBBY_MS, PICK_GRACE_MS } =
    await import("../../dist/games/host/seance-sim.js");

  const consts = {
    CANDLES,
    REVEAL_MS,
    START_BELL_MS,
    OVER_LOBBY_MS,
    PICK_GRACE_MS,
    walkMs: [1, 2, 3, 5, 9, 10, 20].map((b) => [b, walkMs(b)]),
  };

  /** A full séance conducted with a seeded rng and a scripted pick policy. */
  const trace = (seed, ids, policy) => {
    const wins = new Map(ids.map((id) => [id, 0]));
    const log = [];
    const sim = new SeanceSim({
      rng: mulberry32(seed),
      now: () => 0,
      roster: () => ids.map((id, i) => [id, id, i, wins.get(id)]),
      addWin: (id) => wins.set(id, wins.get(id) + 1),
    });
    const rec = (label, emit) =>
      log.push({
        label,
        frames: emit.frames,
        next: emit.next === undefined ? "unchanged" : emit.next,
        matchEnd: emit.matchEnd ?? null,
        state: {
          running: sim.running,
          bell: sim.bell,
          order: [...sim.order],
          candles: [...sim.candles],
          mediumSeat: sim.mediumSeat,
          hintNot: sim.hintNot,
          haunt: sim.haunt,
          inWalk: sim.inWalk,
        },
      });

    rec("start", sim.start(1, ids));
    for (let step = 0; step < 40; step++) {
      const bell = sim.step("bell");
      rec("bell", bell);
      if (!sim.running) break;
      // the medium and the guests decide from what the sim just published
      for (let s = 0; s < ids.length; s++) {
        const r = policy(s, sim);
        if (r !== null) rec(`pick:${s}:${r}`, sim.pick(ids[s], r));
      }
      const resolve = sim.step("resolve");
      rec("resolve", resolve);
      if (resolve.next?.step === "end") {
        rec("end", sim.step("end"));
        rec("lobby", sim.step("lobby"));
        break;
      }
    }
    rec("snapshot", sim.snapshot("late"));
    return { seed, ids, wins: [...wins], log };
  };

  const traces = [
    // seat 0 always walks into the ghost, seat 1 always dodges, seat 2 stays
    trace(9, ["aaa", "bbb", "ccc"], (s, sim) =>
      s === 0 ? sim.haunt : s === 1 ? (sim.haunt + 1) % 3 : null),
    // the medium uses the hint, everyone else rotates deterministically
    trace(11, ["p0", "p1", "p2", "p3"], (s, sim) =>
      s === sim.mediumSeat ? sim.hintNot : (sim.bell + s) % 3),
    // solo séance: the manor takes the last candle, winner is null
    trace(5, ["solo"], (_s, sim) => sim.haunt),
    // out-of-range and duplicate picks are ignored / overwrite
    trace(3, ["x0", "x1"], (s, sim) => (s === 0 ? 7 : sim.haunt)),
  ];

  // peerGone: a mid-walk departure can end the séance without a resolve
  const gone = (() => {
    const ids = ["aaa", "bbb"];
    const wins = new Map(ids.map((id) => [id, 0]));
    const sim = new SeanceSim({
      rng: mulberry32(2),
      now: () => 0,
      roster: () => ids.map((id, i) => [id, id, i, wins.get(id)]),
      addWin: (id) => wins.set(id, wins.get(id) + 1),
    });
    const out = [];
    out.push(sim.start(1, ids));
    out.push(sim.step("bell"));
    out.push(sim.peerGone("bbb"));
    out.push({ running: sim.running, candles: [...sim.candles] });
    out.push(sim.peerGone("bbb")); // idempotent
    out.push(sim.pick("aaa", 1)); // séance over — no emit
    return out;
  })();

  write("seance-sim", { consts, traces, peerGone: gone });
}

/* --------------------------------------------------------- neon-grid sim --- */

{
  const ng = await import("../../dist/games/host/neon-grid-sim.js");
  const { NeonGridSim, GW, GH, WIN_SCORE, DX, DY, COUNTDOWN_MS, OVER_ROUND_MS, OVER_MATCH_MS, MATCH_LOBBY_MS } = ng;

  const consts = { GW, GH, WIN_SCORE, DX: [...DX], DY: [...DY], COUNTDOWN_MS, OVER_ROUND_MS, OVER_MATCH_MS, MATCH_LOBBY_MS };

  const gridDigest = (grid) => {
    // run-length of the authoritative grid — compact and exact
    const runs = [];
    let v = grid[0];
    let c = 0;
    for (const g of grid) {
      if (g === v) c++;
      else {
        runs.push(v, c);
        v = g;
        c = 1;
      }
    }
    runs.push(v, c);
    return runs;
  };

  // Named policies so the replay in test/vectors.test.mjs reproduces the exact
  // input order (and therefore the exact turn queueing) from the fixture.
  const POLICIES = {
    straight: () => null,
    turnEvery5: (r, tick) => (r.id === "aaa" && tick % 5 === 0 ? (tick / 5) & 3 : null),
    reverseAtZero: (r, tick) => (tick === 0 ? (r.id === "aaa" ? 2 : 0) : null),
    spiral7: (r, tick) => (tick % 7 === 0 ? (tick / 7 + Number(r.id.slice(1))) & 3 : null),
    alwaysUp: () => 0,
  };

  const trace = (riders, policyId, maxTicks) => {
    const policy = POLICIES[policyId];
    const scores = new Map(riders.map((r) => [r.id, 0]));
    const log = [];
    const sim = new NeonGridSim({
      roster: () => riders.map((r) => [r.id, r.id, r.color, scores.get(r.id)]),
      addScore: (id) => scores.set(id, scores.get(id) + 1),
      resetScores: () => riders.forEach((r) => scores.set(r.id, 0)),
    });
    const rec = (label, emit) =>
      log.push({
        label,
        frames: emit.frames,
        next: emit.next === undefined ? "unchanged" : emit.next,
        matchEnd: emit.matchEnd ?? null,
        state: { running: sim.running, round: sim.round, tickMs: sim.tickMs, tickN: sim.tickN },
      });
    sim.newMatch();
    rec("startRound", sim.startRound(riders));
    for (let t = 0; t < maxTicks; t++) {
      for (const r of riders) {
        const d = policy(r, t, sim);
        if (d !== null) sim.input(r.id, d);
      }
      const emit = sim.step("tick");
      rec("tick", emit);
      if (!sim.running) break;
    }
    rec("snapshot", sim.snapshot("late"));
    // maxTicks is part of the fixture: a trace that has not resolved by then
    // stops there, and the replay must stop at exactly the same tick
    return { riders, policyId, maxTicks, scores: [...scores], grid: gridDigest(sim.grid), log };
  };

  const two = [
    { id: "aaa", color: 0 },
    { id: "bbb", color: 1 },
  ];
  const three = [
    { id: "p0", color: 0 },
    { id: "p1", color: 1 },
    { id: "p2", color: 2 },
  ];

  const traces = [
    // straight into the head-on: the canonical draw at tick 36
    trace(two, "straight", 40),
    // one turns every 5 ticks, the other rides straight
    trace(two, "turnEvery5", 60),
    // 180° reversals are rejected at tick time; a queue caps at 3
    trace(two, "reverseAtZero", 40),
    // three riders, deterministic spiral
    trace(three, "spiral7", 60),
    // solo round: the sim's <=0 end rule
    trace([{ id: "solo", color: 0 }], "alwaysUp", 40),
  ];

  // a champion crossing WIN_SCORE flips the round end into the match end
  const champion = (() => {
    const riders = two;
    const scores = new Map([["aaa", WIN_SCORE - 1], ["bbb", 0]]);
    const sim = new NeonGridSim({
      roster: () => riders.map((r) => [r.id, r.id, r.color, scores.get(r.id)]),
      addScore: (id) => scores.set(id, scores.get(id) + 1),
      resetScores: () => riders.forEach((r) => scores.set(r.id, 0)),
    });
    const out = [];
    out.push(sim.startRound(riders));
    sim.peerGone("bbb"); // bbb dies next tick, aaa wins the round and the match
    let emit;
    for (let i = 0; i < 5 && sim.running; i++) {
      emit = sim.step("tick");
      out.push(emit);
    }
    out.push(sim.step("match"));
    out.push(sim.step("lobby"));
    out.push({ scores: [...scores] });
    return out;
  })();

  write("neon-grid-sim", { consts, traces, champion });
}

/* ------------------------------------------------- valley-blocks core/eng --- */

{
  const core = await import("../../dist/games/host/valley-blocks-core.js");
  const { ValleyBlocksEngine } = await import("../../dist/games/host/valley-blocks-engine.js");
  const proto = await import("../../dist/games/host/valley-blocks-protocol.js");

  const shapes = {};
  for (const t of core.PIECE_TYPES) {
    shapes[t] = [0, 1, 2, 3].map((r) => core.cellsFor(t, r).map((c) => [...c]));
    // out-of-range rotations normalize
    shapes[`${t}:wrap`] = [-1, 4, 7].map((r) => core.cellsFor(t, r).map((c) => [...c]));
  }
  const kicks = {};
  for (const t of core.PIECE_TYPES) {
    kicks[t] = [0, 1, 2, 3].flatMap((from) =>
      [true, false].map((cw) => ({ from, cw, kicks: core.kicksFor(t, from, cw).map((k) => [...k]) })),
    );
  }

  const scoring = {
    LINES_PER_LEVEL: core.LINES_PER_LEVEL,
    SOFT_DROP_POINTS: core.SOFT_DROP_POINTS,
    HARD_DROP_POINTS: core.HARD_DROP_POINTS,
    COLS: core.COLS,
    ROWS: core.ROWS,
    HIDDEN_ROWS: core.HIDDEN_ROWS,
    TOTAL_ROWS: core.TOTAL_ROWS,
    pointsForLines: [0, 1, 2, 3, 4, 5].flatMap((n) => [1, 3, 12].map((l) => [n, l, core.pointsForLines(n, l)])),
    gravitySeconds: [1, 2, 5, 10, 15, 19, 20, 21, 30].map((l) => [l, core.gravitySeconds(l)]),
    levelForLines: [0, 1, 9, 10, 11, 99, 100].map((n) => [n, core.levelForLines(n)]),
    snakeInterval: [1, 2, 5, 10, 15, 20, 30].map((l) => [l, core.snakeInterval(l)]),
    snakeDuration: [1, 2, 5, 10, 15, 20, 30].map((l) => [l, core.snakeDuration(l)]),
  };

  // Bag: the 7-bag sequence a seed deals. Identical sequences per seed are
  // what make every seat's board match in a live round.
  const bags = [1, 7, 42, 424243, 0x51ed].map((seed) => {
    const bag = new core.Bag(mulberry32(seed));
    return { seed, peek5: bag.peek(5), sequence: Array.from({ length: 35 }, () => bag.next()) };
  });

  // Engine: scripted input traces. `rev` and score/lines/level are the
  // observable surface plus boardStateOf's wire shape.
  const engineTrace = (seed, script) => {
    const events = [];
    const e = new ValleyBlocksEngine(seed, {
      onLock: () => events.push("lock"),
      onGameOver: () => events.push("over"),
      onLinesCleared: (n, rows) => events.push(`clear:${n}:${rows.join(",")}`),
      onLevelUp: (l) => events.push(`level:${l}`),
      onSnakeStart: () => events.push("snake+"),
      onSnakeEnd: () => events.push("snake-"),
      onHold: () => events.push("hold"),
      onHardDrop: () => events.push("hd"),
      onMove: () => events.push("mv"),
      onRotate: () => events.push("rot"),
    });
    const log = [];
    const snap = (label) =>
      log.push({
        label,
        rev: e.rev,
        score: e.score,
        lines: e.lines,
        level: e.level,
        over: e.over,
        active: { ...e.active },
        hold: e.hold,
        holdUsed: e.holdUsed,
        ghostY: e.over ? null : e.ghostY,
        nextQueue: e.nextQueue,
        snake: e.snake ? { segments: e.snake.segments.map((s) => [...s]), dir: e.snake.dir, turbo: e.snake.turbo } : null,
        board: proto.boardStateOf(e),
      });
    snap("spawn");
    for (const [op, arg] of script) {
      switch (op) {
        case "update": e.update(arg); break;
        case "move": e.move(arg); break;
        case "rotate": e.rotate(arg); break;
        case "hardDrop": e.hardDrop(); break;
        case "hold": e.holdPiece(); break;
        case "soft": e.setSoftDrop(arg); break;
        case "softStep": e.softStep(); break;
      }
      snap(`${op}${arg === undefined ? "" : `:${arg}`}`);
      if (e.over) break;
    }
    return { seed, events, log };
  };

  const engines = [
    // pure hard-drop column packing: locks fast, clears lines, tops out
    engineTrace(424243, Array.from({ length: 60 }, () => ["hardDrop"])),
    // rotate + shuffle left, then drop — exercises SRS kicks and lock delay
    engineTrace(7, [
      ["rotate", true], ["rotate", true], ["move", -1], ["move", -1], ["move", -1],
      ["hardDrop"], ["hold"], ["rotate", false], ["move", 1], ["hardDrop"],
      ["update", 0.5], ["update", 0.5], ["update", 0.5], ["update", 0.5],
      ["soft", true], ["update", 0.1], ["update", 0.1], ["soft", false],
      ["softStep"], ["softStep"], ["hardDrop"],
    ]),
    // gravity only, small steps: the guideline fall curve and lock delay
    engineTrace(1, Array.from({ length: 120 }, () => ["update", 0.05])),
  ];

  // The snake schedule is drawn from mulberry32(seed ^ 0x5f356495), separate
  // from the bag's rng, so duel players are offered snakes at the same piece
  // indices. A pure hard-drop game tops out in a dozen pieces and never sees
  // one — so play with the real stock brain (the same code the gym runs) and
  // pin every snake episode it is offered, plus a scripted steer of the first.
  const brainForSnakes = await import("../../dist/games/valley-blocks-brain.js");
  const snakes = [424243, 7, 1, 99].map((seed) => {
    const e = new ValleyBlocksEngine(seed);
    const at = [];
    let pieces = 0;
    for (let i = 0; i < 2000 && !e.over; i++) {
      if (e.snake) {
        const entry = {
          piece: pieces,
          duration: e.snake.duration,
          entry: e.snake.segments.map((s) => [...s]),
          steps: [],
        };
        // scripted steering, verbatim the gym's bounded loop
        let budget = 200;
        while (e.snake && budget-- > 0) {
          brainForSnakes.snakeStep(e);
          if (e.snake) entry.steps.push([e.snake.segments[0][0], e.snake.segments[0][1], e.snake.dir]);
        }
        if (e.snake) e.hardDrop();
        entry.scoreAfter = e.score;
        entry.linesAfter = e.lines;
        at.push(entry);
        continue;
      }
      const cands = brainForSnakes.enumeratePlacements(e);
      if (!cands.length) e.hardDrop();
      else brainForSnakes.executePlacement(e, cands[brainForSnakes.stockPick(cands)]);
      pieces++;
    }
    return {
      seed,
      snakeGapRng: (() => {
        // the gap draw itself: SNAKE_MIN_GAP + floor(SNAKE_GAP_SPREAD·r²)
        const r = mulberry32(seed ^ 0x5f356495);
        return Array.from({ length: 12 }, () => {
          const v = r();
          return [v, 6 + Math.floor(15 * v * v)];
        });
      })(),
      snakeCount: at.length,
      snakeOffers: at.slice(0, 6),
      finalScore: e.score,
      finalLines: e.lines,
      over: e.over,
    };
  });

  write("valley-blocks-core", {
    shapes,
    kicks,
    scoring,
    bags,
    engines,
    snakes,
    protocol: {
      MAX_PLAYERS: proto.MAX_PLAYERS,
      STATE_INTERVAL_MS: proto.STATE_INTERVAL_MS,
      PING_INTERVAL_MS: proto.PING_INTERVAL_MS,
    },
  });
}

/* --------------------------------------------------- valley-blocks brain --- */

{
  const brain = await import("../../dist/games/valley-blocks-brain.js");
  const { ValleyBlocksEngine } = await import("../../dist/games/host/valley-blocks-engine.js");
  const { COLS, TOTAL_ROWS } = await import("../../dist/games/host/valley-blocks-core.js");

  // hand-built occupancy grids: flat, empty, holed, well, jagged, near-full
  const gridFrom = (rows) => {
    const g = new Uint8Array(TOTAL_ROWS * COLS);
    rows.forEach((row, i) => {
      const y = TOTAL_ROWS - rows.length + i;
      for (let x = 0; x < COLS; x++) if (row[x] === "#") g[y * COLS + x] = 1;
    });
    return g;
  };
  const boards = {
    empty: gridFrom([]),
    flat1: gridFrom(["##########"]),
    hole: gridFrom(["#########.", "##########"]),
    well: gridFrom(["####.#####", "####.#####", "##########"]),
    jagged: gridFrom(["#.#.#.#.#.", "##.##.##.#", "##########"]),
    tower: gridFrom(Array.from({ length: 18 }, () => "#........#")),
    nearFull: gridFrom(Array.from({ length: 19 }, () => "#########.")),
  };
  const metrics = Object.fromEntries(
    Object.entries(boards).map(([k, g]) => [k, brain.boardMetrics(g)]),
  );

  // real candidate sets from real engines: every field of every VBCandidate.
  // The afterstate grid is pinned by a SHA-256 of its bytes rather than
  // inlined — exact, and it keeps the fixture from ballooning past a megabyte.
  const rle = (g) => {
    const runs = [];
    let v = g[0];
    let c = 0;
    for (const x of g) {
      if (x === v) c++;
      else {
        runs.push(v, c);
        v = x;
        c = 1;
      }
    }
    runs.push(v, c);
    return runs;
  };
  const { createHash } = await import("node:crypto");
  const gridDigest = (g) => createHash("sha256").update(g).digest("hex").slice(0, 32);
  const candidateSets = [];
  for (const seed of [424243, 7, 1]) {
    const e = new ValleyBlocksEngine(seed);
    for (let drop = 0; drop < 12 && !e.over; drop++) {
      const cands = brain.enumeratePlacements(e);
      candidateSets.push({
        seed,
        drop,
        piece: e.active.type,
        hold: e.hold,
        holdUsed: e.holdUsed,
        count: cands.length,
        candidates: cands.map((c) => ({
          useHold: c.useHold,
          rotation: c.rotation,
          x: c.x,
          cleared: c.cleared,
          landingRow: c.landingRow,
          erodedCells: c.erodedCells,
          gridSha: gridDigest(c.grid),
          score: brain.dellacherieScore(c),
          plan: brain.planOf(c),
        })),
        stockPick: brain.stockPick(cands),
      });
      if (cands.length) brain.executePlacement(e, cands[brain.stockPick(cands)]);
      else e.hardDrop();
      let budget = 200;
      while (e.snake && budget-- > 0) brain.snakeStep(e);
      if (e.snake) e.hardDrop();
    }
  }

  // a full stock-brain game: the Dellacherie baseline the promotion gate uses
  const stockGames = [424243, 7, 1, 31337].map((seed) => {
    const e = new ValleyBlocksEngine(seed);
    const trail = [];
    for (let n = 0; n < 400 && !e.over; n++) {
      const cands = brain.enumeratePlacements(e);
      if (!cands.length) {
        e.hardDrop();
      } else {
        const idx = brain.stockPick(cands);
        trail.push([n, cands.length, idx, cands[idx].rotation, cands[idx].x, cands[idx].useHold ? 1 : 0]);
        brain.executePlacement(e, cands[idx]);
      }
      let budget = 200;
      while (e.snake && budget-- > 0) brain.snakeStep(e);
      if (e.snake) e.hardDrop();
    }
    return { seed, placements: trail.length, score: e.score, lines: e.lines, level: e.level, trail };
  });

  // placementStep, input by input — the live client's paced path
  const stepped = (() => {
    const e = new ValleyBlocksEngine(7);
    const cands = brain.enumeratePlacements(e);
    const plan = brain.planOf(cands[cands.length - 1]);
    const seq = [];
    for (let i = 0; i < 40; i++) {
      const r = brain.placementStep(e, plan);
      seq.push({ r, plan: { ...plan }, x: e.active.x, rotation: e.active.rotation, score: e.score });
      if (r === "done") break;
    }
    return { target: cands[cands.length - 1], seq };
  })();

  // stockPick edge cases
  const picks = {
    empty: brain.stockPick([]),
    tieTakesFirst: brain.stockPick([
      { useHold: false, rotation: 0, x: 0, cleared: 0, landingRow: 0, erodedCells: 0, grid: boards.flat1 },
      { useHold: false, rotation: 1, x: 1, cleared: 0, landingRow: 0, erodedCells: 0, grid: boards.flat1 },
    ]),
  };

  write("valley-blocks-brain", {
    metrics,
    boardsRle: Object.fromEntries(Object.entries(boards).map(([k, g]) => [k, rle(g)])),
    candidateSets,
    stockGames,
    stepped,
    picks,
  });
}

/* ------------------------------------------------- valley-blocks referee --- */

{
  const vs = await import("../../dist/games/host/valley-blocks-sim.js");
  const { ValleyBlocksSim, ROUND_LOBBY_MS, DEFAULT_MODE, DEFAULT_TARGET } = vs;

  const board = (score, over) => ({ grid: ".".repeat(200), score, lines: 0, level: 1, snake: null, over });

  const run = (mode, target, ids, script) => {
    const wins = new Map(ids.map((id) => [id, 0]));
    const sim = new ValleyBlocksSim({
      roster: () => ids.map((id) => [id, id.toUpperCase(), wins.get(id)]),
      addWin: (id) => wins.set(id, wins.get(id) + 1),
      mode,
      target,
    });
    const log = [];
    const rec = (label, emit) =>
      log.push({
        label,
        frames: emit.frames,
        next: emit.next === undefined ? "unchanged" : emit.next,
        matchEnd: emit.matchEnd ?? null,
        running: sim.running,
      });
    rec("start", sim.startRound(ids, 424243));
    for (const [op, a, b, c] of script) {
      if (op === "bs") rec(`bs:${a}:${b}:${c}`, sim.onBoardState(a, sim.round, ids.indexOf(a), board(b, c)));
      if (op === "left") rec(`left:${a}`, sim.playerLeft(a));
      if (op === "snap") rec("snap", sim.snapshot("late"));
      if (op === "spoof") rec(`spoof:${a}`, sim.onBoardState(a, sim.round, 99, board(1, false)));
      if (op === "stale") rec(`stale:${a}`, sim.onBoardState(a, sim.round + 7, ids.indexOf(a), board(1, false)));
    }
    return { mode, target, ids, wins: [...wins], log };
  };

  const two = ["aaa", "bbb"];
  const three = ["p0", "p1", "p2"];
  const runs = [
    // race-survival: crossing the target wins on the spot
    run("race-survival", 1000, two, [["bs", "aaa", 500, false], ["snap", null], ["bs", "aaa", 1000, false]]),
    // survival: the target is ignored; last board standing wins
    run("survival", 1000, two, [["bs", "aaa", 9999, false], ["bs", "bbb", 0, true]]),
    // race: survivorship is ignored; only the target (or all-out) decides
    run("race", 1000, two, [["bs", "bbb", 0, true], ["bs", "aaa", 10, false], ["bs", "aaa", 1000, false]]),
    // everyone tops out: highest score takes it
    run("race-survival", 99999, three, [
      ["bs", "p0", 300, true], ["bs", "p1", 700, true], ["bs", "p2", 100, true],
    ]),
    // a leaver stays in the pool as `left` and can never win
    run("race-survival", 500, two, [["left", "aaa"], ["bs", "bbb", 20, false], ["bs", "bbb", 500, false]]),
    // seat spoofing and stale rounds are refused
    run("race-survival", 1000, two, [["spoof", "aaa"], ["stale", "aaa"], ["bs", "aaa", 1000, false]]),
  ];

  // startRound refuses a solo round and a double start
  const guards = (() => {
    const sim = new ValleyBlocksSim({ roster: () => [], addWin: () => {} });
    const solo = sim.startRound(["only"], 1);
    const ok = sim.startRound(["a", "b"], 1);
    const again = sim.startRound(["a", "b"], 2);
    return { solo, ok, again, defaults: { mode: sim.mode, target: sim.target } };
  })();

  write("valley-blocks-sim", {
    consts: { ROUND_LOBBY_MS, DEFAULT_MODE, DEFAULT_TARGET },
    targetFloor: new ValleyBlocksSim({ roster: () => [], addWin: () => {}, target: 3 }).target,
    runs,
    guards,
  });
}

/* ----------------------------------------------------------------- gyms --- */
/**
 * Full episode traces: reset() then a FIXED action sequence, recording every
 * observation, reward, done flag and the terminal state. These are the
 * fixtures the RL trainer's promotion gates ultimately rest on.
 */
{
  const { SeanceGym } = await import("../../dist/gym/seance.js");
  const { NeonGridGym } = await import("../../dist/gym/neon-grid.js");
  const { ValleyBlocksGym } = await import("../../dist/gym/valley-blocks.js");

  const u8 = (v) => (v instanceof Uint8Array ? { u8rle: rleOf(v) } : v);
  function rleOf(g) {
    const runs = [];
    let v = g[0];
    let c = 0;
    for (const x of g) {
      if (x === v) c++;
      else {
        runs.push(v, c);
        v = x;
        c = 1;
      }
    }
    runs.push(v, c);
    return runs;
  }
  const scrub = (x) => JSON.parse(JSON.stringify(x, (_k, v) => u8(v)));

  /* --- séance --- */
  const seanceEpisodes = [];
  for (const [players, seed] of [[3, 11], [4, 7], [2, 5], [1, 3]]) {
    const gym = new SeanceGym({ players, seed });
    const eps = [];
    for (let ep = 0; ep < 3; ep++) {
      const steps = [];
      let views = gym.reset();
      steps.push({ reset: scrub(views) });
      for (let n = 0; n < 40; n++) {
        // fixed, view-derived policy — no ambient randomness
        const actions = views.map((v) =>
          v.isMedium ? v.hintNot : (v.bell + v.seat) % 3 === 0 ? null : (v.bell + v.seat) % 3,
        );
        const r = gym.step(actions);
        steps.push({ actions, ...scrub(r) });
        if (r.done) break;
        views = r.views;
      }
      eps.push(steps);
    }
    seanceEpisodes.push({ players, seed, eps });
  }
  write("gym-seance", seanceEpisodes);

  /* --- neon-grid --- */
  const ngEpisodes = [];
  for (const players of [2, 3, 4]) {
    const gym = new NeonGridGym({ players });
    const eps = [];
    for (let ep = 0; ep < 2; ep++) {
      const steps = [];
      let views = gym.reset();
      steps.push({ reset: scrub(views) });
      for (let n = 0; n < 400; n++) {
        // wall-aware but fully deterministic: turn on a fixed cadence
        const actions = views.map((v) =>
          !v.alive ? null : (v.tickN + v.seat) % 11 === 0 ? (v.dir + 1) % 4 : null,
        );
        const r = gym.step(actions);
        steps.push({ actions, rewards: r.rewards, done: r.done, winner: r.winner });
        if (r.done) {
          steps.push({ terminalViews: scrub(r.views) });
          break;
        }
        views = r.views;
      }
      eps.push(steps);
    }
    ngEpisodes.push({ players, eps });
  }
  write("gym-neon-grid", ngEpisodes);

  /* --- valley-blocks --- */
  const vbEpisodes = [];
  for (const [players, seed, mode, target] of [
    [2, 424242, "race-survival", 5000],
    [2, 7, "survival", 5000],
    [3, 1, "race", 2000],
  ]) {
    const gym = new ValleyBlocksGym({ players, seed, mode, target, maxPlacements: 120 });
    const eps = [];
    for (let ep = 0; ep < 2; ep++) {
      const steps = [];
      let views = gym.reset();
      // the first views carry the whole candidate surface — record it once,
      // in full, then track the compact per-step signal
      steps.push({
        reset: views.map((v) => ({
          seat: v.seat, over: v.over, score: v.score, lines: v.lines, level: v.level,
          piece: v.piece, hold: v.hold, canHold: v.canHold, mode: v.mode, target: v.target,
          rivals: v.rivals, candidateCount: v.candidates.length,
          candidateKeys: Object.keys(v.candidates[0] ?? {}).sort(),
          candidates: v.candidates.map((c) => [c.useHold ? 1 : 0, c.rotation, c.x, c.cleared, c.landingRow, c.erodedCells]),
        })),
      });
      for (let n = 0; n < 200; n++) {
        // deterministic index policy: cycle the candidate list by step number
        const actions = views.map((v, s) =>
          v.candidates.length ? (n + s) % v.candidates.length : null,
        );
        const r = gym.step(actions);
        steps.push({
          actions,
          rewards: r.rewards,
          done: r.done,
          winner: r.winner,
          reason: r.reason,
          scores: r.views.map((v) => v.score),
          lines: r.views.map((v) => v.lines),
          over: r.views.map((v) => v.over),
          pieces: r.views.map((v) => v.piece),
          candidateCounts: r.views.map((v) => v.candidates.length),
        });
        if (r.done) break;
        views = r.views;
      }
      eps.push(steps);
    }
    vbEpisodes.push({ players, seed, mode, target, eps });
  }
  write("gym-valley-blocks", vbEpisodes);
}

/* ----------------------------------------------------------- host driver --- */
/**
 * The live driver over the in-memory hub with mocked time: the frames a hosted
 * room actually puts on the wire, in order. Timers are advanced by a fake
 * clock the harness owns, so the trace is deterministic.
 */
{
  const { Hub, FakeClock } = await import("../helpers/mock-hub.mjs");
  const { SeanceClient } = await import("../../dist/games/seance.js");
  const { NeonGridClient } = await import("../../dist/games/neon-grid.js");
  const { ValleyBlocksClient } = await import("../../dist/games/valley-blocks.js");
  const { walkMs } = await import("../../dist/games/host/seance-sim.js");

  const out = {};

  /* --- séance: bot host + one guest, both scripted --- */
  {
    const clock = new FakeClock();
    const hub = new Hub();
    const hostPeer = hub.join("aaa-host");
    let haunt = () => -1;
    const host = new SeanceClient(hostPeer, {
      app: "seance", roomSecret: "s", nick: "gazda", keepAliveMs: 0, actDelayMs: 0,
      onTurn: () => haunt(),
      host: { rng: mulberry32(9), match: { minPlayers: 2, expectedPlayers: 2, maxMatches: 1 } },
    });
    haunt = () => host.host.sim.haunt;
    hostPeer.emit("roster", []);
    const guestPeer = hub.join("bbb-guest");
    const guest = new SeanceClient(guestPeer, {
      app: "seance", roomSecret: "s", nick: "oaspe", keepAliveMs: 0, actDelayMs: 0,
      onTurn: () => (host.host.sim.haunt + 1) % 3,
    });
    hub.openAll();
    await clock.drain();
    clock.tick(2600);
    for (let bell = 1; bell <= 6; bell++) {
      await clock.drain();
      clock.tick(walkMs(bell) + 500);
      await clock.drain();
      clock.tick(6500);
      await clock.drain();
      if (!host.host.sim.running) break;
    }
    await clock.drain();
    out.seance = {
      wire: hostPeer.sent,
      hostId: host.hostId,
      guestHostId: guest.hostId,
      guestWins: guest.wins,
      hostWins: host.wins,
      hostView: host.view(),
      guestView: guest.view(),
    };
  }

  /* --- séance split-brain: concede to lower, reassert against higher --- */
  {
    const hub = new Hub();
    const hostPeer = hub.join("mmm-host");
    const host = new SeanceClient(hostPeer, {
      app: "seance", roomSecret: "s", nick: "gazda", keepAliveMs: 0, host: {},
    });
    hostPeer.emit("roster", []);
    hub.join("zzz-late");
    const beforeHigh = hostPeer.sent.length;
    hostPeer.emit("message", "zzz-late", { t: "ro", host: "zzz-late", ps: [["zzz-late", "tarziu", 0, 0]] });
    const afterHigh = { hostId: host.hostId, sentSince: hostPeer.sent.slice(beforeHigh) };
    hub.join("aaa-early");
    hostPeer.emit("message", "aaa-early", { t: "ro", host: "aaa-early", ps: [["aaa-early", "devreme", 0, 0]] });
    out.seanceSplitBrain = {
      afterHigh,
      afterLow: { hostId: host.hostId, hosting: host.hosting, simRunning: host.host.sim.running },
    };
  }

  /* --- neon-grid: hosted round to the head-on draw, then round 2 --- */
  {
    const clock = new FakeClock();
    const hub = new Hub();
    const hostPeer = hub.join("aaa-host");
    const host = new NeonGridClient(hostPeer, {
      app: "neon-grid", roomSecret: "s", nick: "gazda", keepAliveMs: 0,
      onTick: () => null,
      host: { match: { minPlayers: 2, expectedPlayers: 2 } },
    });
    hostPeer.emit("roster", []);
    const guestPeer = hub.join("bbb-guest");
    const guest = new NeonGridClient(guestPeer, {
      app: "neon-grid", roomSecret: "s", nick: "oaspe", keepAliveMs: 0, onTick: () => null,
    });
    hub.openAll();
    await clock.drain();
    clock.tick(3000);
    hub.join("ccc-late");
    hostPeer.emit("message", "ccc-late", { t: "hi", nick: "tarziu", score: 0 });
    for (let i = 0; i < 40; i++) clock.tick(80);
    await clock.drain();
    clock.tick(3200);
    await clock.drain();
    out.neonGrid = {
      wire: hostPeer.sent,
      tickCount: hostPeer.sent.filter(([, f]) => f.t === "tk").length,
      starts: hostPeer.sent.filter(([, f]) => f.t === "st").map(([, f]) => ({ round: f.round, tickMs: f.tickMs, starts: f.starts })),
      guestSeat: guest.seat,
      guestView: { ...guest.view(), grid: undefined, heads: guest.view().heads },
    };
  }

  /* --- valley-blocks: hosted round, referee verdict from real boards --- */
  {
    const clock = new FakeClock();
    const hub = new Hub();
    const hostPeer = hub.join("aaa-host");
    const host = new ValleyBlocksClient(hostPeer, {
      app: "valley-blocks", roomSecret: "s", nick: "gazda", keepAliveMs: 0,
      pace: { inputMs: 0, thinkMs: () => 0 },
      host: { rng: mulberry32(4), match: { minPlayers: 2, expectedPlayers: 2, maxMatches: 1 }, target: 800 },
    });
    hostPeer.emit("roster", []);
    const guestPeer = hub.join("bbb-guest");
    const guest = new ValleyBlocksClient(guestPeer, {
      app: "valley-blocks", roomSecret: "s", nick: "oaspe", keepAliveMs: 0, forfeit: true,
    });
    hub.openAll();
    await clock.drain();
    for (let i = 0; i < 200; i++) {
      clock.tick(50);
      await clock.drain();
      if (hostPeer.sent.some(([, f]) => f.t === "ov")) break;
    }
    out.valleyBlocks = {
      st: hostPeer.sent.find(([, f]) => f.t === "st")?.[1],
      ov: hostPeer.sent.find(([, f]) => f.t === "ov")?.[1],
      ro: hostPeer.sent.filter(([, f]) => f.t === "ro").map(([, f]) => f),
      guestSeat: guest.seat,
      hostSeat: host.seat,
    };
  }

  write("host-driver", out);
}

console.log("all vectors written");

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