board / client / test / helpers / app-fakes.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
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
/**
 * Implementation-agnostic doubles + scripted scenarios for board's own layer
 * (everything above the vendored p2p lib, which rooms-kit's fixtures cover).
 *
 * Every function here is driven by BOTH `test/vectors/generate.mjs` (against the
 * TypeScript, to produce the fixtures) and `test/*.test.mjs` (against the
 * ClojureScript build, to check them). Nothing in this file knows which
 * implementation it is running: the classes arrive as arguments and hard-private
 * members are reached through a `priv(obj, name)` adapter — `__t[name]` for the
 * TS build, `obj["_" + name]` for the port.
 *
 * `Date.now` and `performance.now` are pinned while a script runs, so
 * timestamps and every throttle decision land in the transcripts as exact
 * numbers. Two traps dev/docs/CLJS.md records are avoided by construction:
 *
 *  - the whole `Date` constructor is replaced, not just `Date.now` (V8 reads the
 *    system clock for `new Date()` and app/boards.ts's default label does
 *    exactly that);
 *  - every array snapshot is taken BY VALUE (`snap`), because the tools mutate
 *    point arrays and element specs in place — a captured reference would record
 *    the final state, not the state at capture.
 */

const RealDate = Date;

export const T0 = 1_700_000_000_000;

/** Pins `Date` (constructor included) and `performance.now` for `fn`. */
export async function withClock(t0, fn) {
  let now = t0;
  let perf = 0;
  class FrozenDate extends RealDate {
    constructor(...args) {
      if (args.length === 0) super(now);
      else super(...args);
    }
  }
  FrozenDate.now = () => now;
  FrozenDate.parse = RealDate.parse;
  FrozenDate.UTC = RealDate.UTC;
  const realPerf = globalThis.performance;
  globalThis.Date = FrozenDate;
  globalThis.performance = { now: () => perf };
  try {
    return await fn({
      tick: (ms) => (now += ms),
      now: () => now,
      perfTick: (ms) => (perf += ms),
      perfNow: () => perf,
    });
  } finally {
    globalThis.Date = RealDate;
    globalThis.performance = realPerf;
  }
}

/**
 * Drain every pending async step, including WebCrypto.
 *
 * `crypto.subtle.*` promises settle on the platform's task queue, NOT the
 * microtask queue: a `for (…) await Promise.resolve()` drain records a state in
 * which nothing was ever verified. The first pass of these fixtures did exactly
 * that and produced an empty `members`/`pending` fold with no error at all —
 * the "check for the coverage you assumed you had" trap from dev/docs/CLJS.md.
 */
export async function settle(rounds = 12) {
  for (let i = 0; i < rounds; i++) await new Promise((r) => setTimeout(r, 0));
}

/**
 * Drain until the observed value stops changing (chat's harness, verbatim) —
 * for machinery whose step count is not known up front.
 */
export async function settleUntil(probe, max = 200) {
  let prev = probe();
  for (let i = 0; i < max; i++) {
    await new Promise((r) => setTimeout(r, 0));
    const now = probe();
    if (now === prev && i > 2) return;
    prev = now;
  }
  throw new Error("settleUntil: never quiesced");
}

/** Deep copy through JSON — the by-value snapshot rule, in one place. */
export const snap = (x) => (x === undefined ? undefined : JSON.parse(JSON.stringify(x)));

/** Key order of a plain object, which IS the wire order (dev/docs/CLJS.md). */
export const keysOf = (o) => (o && typeof o === "object" ? Object.keys(o) : null);

/** The seed rooms-kit's fixtures use, so author ids line up across repos. */
export const SEED = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE";
export const SEED2 = "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI";
export const SEED3 = "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM";
/** A 43-char base64url pub that is NOT a real key — enough for id-less paths. */
export const FAKE_PUB = "bnoc3Smwt4_ROvTFWY_v9O8qlxZuPKby5Pv8zYBQW_E";

/** A valid 22-char element id (16 random bytes, base64url) for hand-built ops. */
export const EL = (n) => `elemid${String(n).padStart(2, "0")}${"A".repeat(20)}`.slice(0, 22);

// ------------------------------------------------------------------ doubles --

/** The slice of RoomLog that app/state.ts and app/images.ts actually touch. */
export function fakeBoardLog(myAuthorId = FAKE_PUB) {
  let n = 0;
  return {
    myAuthorId,
    appended: [],
    imgCalls: [],
    pruneCalls: [],
    getCalls: [],
    onAppended: null,
    onImageStored: null,
    imageChunkBytes: 0,
    async append(op) {
      // the wire bytes, byte-exact: canonical serialisation is JSON.stringify
      // in key-insertion order (dev/docs/CLJS.md), never pr-str
      this.appended.push(JSON.stringify(op));
      return `hash${++n}`;
    },
    async putImage(data) {
      this.imgCalls.push(data.length);
      return { cid: "bafkreiFAKEIMAGECID", bytes: data.length };
    },
    async getImage(cid) {
      this.getCalls.push(cid);
      return null;
    },
    async pruneImages(keep, dropped) {
      this.pruneCalls.push([[...keep].sort(), [...dropped]]);
    },
    async close() {},
  };
}

/** The slice of Net that app/state.ts actually touches. */
export function fakeBoardNet(myId = "12D3KooWSELF") {
  return {
    myId,
    sent: [],
    async broadcast(payload) {
      this.sent.push(["broadcast", JSON.stringify(payload), keysOf(payload)]);
    },
    async sendTo(peer, payload) {
      this.sent.push(["sendTo", peer, JSON.stringify(payload), keysOf(payload)]);
    },
  };
}

/** A log entry as RoomLog.emit hands it to onEntry. */
export const entry = (hash, from, clock, op) => ({ hash, from, clock, op });

/** The slice of Scene that app/tools.ts actually touches. */
export function fakeScene(Camera, themeFor) {
  const painters = [];
  return {
    painters,
    invalidated: 0,
    woken: 0,
    camera: new Camera(),
    theme: themeFor("black"),
    cssSize: { w: 800, h: 600 },
    host: {
      addEventListener() {},
      getBoundingClientRect: () => ({ left: 0, top: 0, width: 800, height: 600 }),
    },
    addPainter(p) {
      painters.push(p);
    },
    invalidate() {
      this.invalidated++;
    },
    wakeOverlay() {
      this.woken++;
    },
    setMode() {},
  };
}

/** A PointerEvent as InputRouter hands one to the tool. */
export const pev = (over = {}) => ({
  pointerId: 1,
  pointerType: "mouse",
  pressure: 0,
  button: 0,
  shiftKey: false,
  clientX: 0,
  clientY: 0,
  preventDefault() {},
  stopPropagation() {},
  ...over,
});

// ------------------------------------------------------------------ scripts --

/**
 * app/ops.ts: the stroke codec (THE geometry contract), the untrusted-input
 * sanitisers with their exact key ORDER, and the bbox/hit-test geometry.
 */
export async function opsScript(M) {
  const out = { codec: [], rounding: [], sanitizeElement: [], sanitizePatch: [], bbox: [], geometry: [] };

  // ---- the fixed-point delta codec -----------------------------------------
  const codecCases = [
    { name: "empty", pts: [] },
    { name: "single-coord", pts: [5] },
    { name: "one-point", pts: [10, 20] },
    { name: "two-points", pts: [10, 20, 11, 21] },
    { name: "exact-hundredths", pts: [1.23, 4.56, 7.89, 0.01] },
    { name: "sub-hundredth", pts: [0.001, 0.004, 0.006, 0.009] },
    { name: "negative", pts: [-1.005, -2.015, -3.025, -4.035] },
    { name: "half-up-at-.005", pts: [0, 0, 0.005, 0.015, 0.025, 0.035] },
    { name: "negative-half", pts: [0, 0, -0.005, -0.015, -0.025, -0.035] },
    { name: "big-jump", pts: [0, 0, 1000.5, -2000.25] },
    { name: "odd-length", pts: [1, 2, 3] },
    { name: "drift-accumulation", pts: [0, 0, 0.333, 0.333, 0.666, 0.666, 0.999, 0.999] },
    { name: "origin-not-round", pts: [3.14159, 2.71828, 3.14159, 2.71828] },
  ];
  for (const c of codecCases) {
    const enc = M.encodePts(c.pts);
    out.codec.push({
      name: c.name,
      input: c.pts,
      enc: snap(enc),
      encKeys: keysOf(enc),
      dec: snap(M.decodePts(enc)),
    });
  }

  // rounding edge cases stated on their own, because an off-by-one here
  // silently corrupts geometry on every deployed client
  for (const v of [0.004, 0.005, 0.006, -0.004, -0.005, -0.006, 0.015, 0.025, 1.005, 2.675]) {
    out.rounding.push([v, Math.round(v * 100), snap(M.encodePts([0, 0, v, v]))]);
  }

  // ---- sanitizeElement: every kind, every rejection ------------------------
  const id = EL(1);
  const elCases = [
    ["reject-null", null],
    ["reject-non-object", 7],
    ["reject-bad-id", { id: "short", k: "note" }],
    ["reject-unknown-kind", { id, k: "widget" }],
    ["stroke-plain", { id, k: "stroke", x: 1.5, y: 2.5, pts: [100, -100, 50, 50], w: 3, c: 2 }],
    ["stroke-pressure", { id, k: "stroke", x: 0, y: 0, pts: [10, 10, 20, 20], w: 2, c: 0, prs: [10, 200, 128] }],
    ["stroke-pressure-wrong-len", { id, k: "stroke", x: 0, y: 0, pts: [10, 10], w: 2, c: 0, prs: [1] }],
    ["stroke-odd-pts", { id, k: "stroke", x: 0, y: 0, pts: [1, 2, 3], w: 2, c: 0 }],
    ["stroke-nan-pt", { id, k: "stroke", x: 0, y: 0, pts: [1, Number.NaN], w: 2, c: 0 }],
    ["stroke-clamped", { id, k: "stroke", x: 1e12, y: -1e12, pts: [1e12, -1e12], w: 1e9, c: 99 }],
    ["stroke-zero-width", { id, k: "stroke", x: 0, y: 0, pts: [], w: 0, c: 0 }],
    ["stroke-fractional-pts", { id, k: "stroke", x: 0, y: 0, pts: [1.4, 1.5, -1.5, 2.6], w: 2, c: 1 }],
    ["text-plain", { id, k: "text", x: 3, y: 4, text: "hello", size: 18, c: 1 }],
    ["text-wrap", { id, k: "text", x: 0, y: 0, text: "wrapped", size: 400, c: 0, wrap: 10 }],
    ["text-empty", { id, k: "text", x: 0, y: 0, text: "   ".replace(/ /g, "\u0000"), size: 18, c: 0 }],
    ["text-control-chars", { id, k: "text", x: 0, y: 0, text: "a\u0000b\tc\nd\u007fe", size: 5, c: 0 }],
    ["note-plain", { id, k: "note", x: 1, y: 2, w: 180, h: 120, text: "note", c: 3 }],
    ["note-defaults", { id, k: "note", x: 0, y: 0 }],
    ["img-plain", { id, k: "img", x: 1, y: 2, w: 100, h: 80, cid: "bafyCID", mime: "image/webp", bytes: 4096, iw: 200, ih: 160 }],
    ["img-mime-coerced", { id, k: "img", x: 0, y: 0, w: 1, h: 1, cid: "c", mime: "image/gif", bytes: 1, iw: 1, ih: 1 }],
    ["img-zero-bytes", { id, k: "img", x: 0, y: 0, w: 1, h: 1, cid: "c", mime: "image/jpeg", bytes: 0, iw: 1, ih: 1 }],
    ["img-no-cid", { id, k: "img", x: 0, y: 0, w: 1, h: 1, bytes: 1, iw: 1, ih: 1 }],
    ["shape-rect", { id, k: "shape", shape: "rect", x: 0, y: 0, w: 50, h: -25, c: 4, sw: 3 }],
    ["shape-fill", { id, k: "shape", shape: "ellipse", x: 0, y: 0, w: 10, h: 10, c: 4, sw: 3, fill: 5 }],
    ["shape-fill-null", { id, k: "shape", shape: "line", x: 0, y: 0, w: 10, h: 10, c: 4, sw: 3, fill: null }],
    ["shape-bad", { id, k: "shape", shape: "star", x: 0, y: 0, w: 1, h: 1, c: 0, sw: 1 }],
    ["conn-free", { id, k: "conn", a: { x: 1, y: 2 }, b: { x: 3, y: 4 }, c: 1, sw: 2 }],
    ["conn-attached", { id, k: "conn", a: { el: EL(2), side: "n" }, b: { el: EL(3) }, c: 1, sw: 2, arrow: "both" }],
    ["conn-bad-side", { id, k: "conn", a: { el: EL(2), side: "q" }, b: { x: 0, y: 0 }, c: 1, sw: 2, arrow: "none" }],
    ["conn-bad-anchor", { id, k: "conn", a: { el: "nope" }, b: { x: 0, y: 0 }, c: 1, sw: 2 }],
  ];
  for (const [name, raw] of elCases) {
    const got = M.sanitizeElement(raw);
    out.sanitizeElement.push({ name, out: snap(got), keys: keysOf(got) });
  }

  // ---- sanitizePatch: the widest object in the app (13 possible fields) ----
  const patchCases = [
    ["null", null],
    ["empty", {}],
    ["all-fields", {
      x: 1.5, y: -2.5, w: 3, h: 4, text: "t\u0000x", size: 999, c: 12,
      sw: 500, fill: 3, wrap: 5, a: { x: 1, y: 2 }, b: { el: EL(2), side: "e" }, arrow: "both",
    }],
    ["fill-null", { fill: null }],
    ["fill-bad", { fill: "red" }],
    ["arrow-bad", { arrow: "middle" }],
    ["anchor-bad", { a: { el: "nope" } }],
    ["clamps", { x: 1e30, y: -1e30, w: 1e30, h: -1e30, size: 0, sw: 0, wrap: 1 }],
    ["only-text", { text: "ok" }],
    ["nan", { x: Number.NaN }],
  ];
  for (const [name, raw] of patchCases) {
    const got = M.sanitizePatch(raw);
    out.sanitizePatch.push({ name, out: snap(got), keys: keysOf(got) });
  }

  // ---- bbox geometry -------------------------------------------------------
  const bboxEls = [
    M.sanitizeElement({ id, k: "stroke", x: 10, y: 10, pts: [500, 500, -1000, 250], w: 4, c: 0 }),
    M.sanitizeElement({ id, k: "stroke", x: 7, y: 8, pts: [], w: 4, c: 0 }),
    M.sanitizeElement({ id, k: "text", x: 0, y: 0, text: "one\ntwo", size: 20, c: 0 }),
    M.sanitizeElement({ id, k: "text", x: 0, y: 0, text: "wrapped text", size: 10, c: 0, wrap: 50 }),
    M.sanitizeElement({ id, k: "note", x: -5, y: -5, w: 100, h: 50, text: "", c: 0 }),
    M.sanitizeElement({ id, k: "img", x: 1, y: 1, w: 10, h: 20, cid: "c", mime: "image/jpeg", bytes: 9, iw: 4, ih: 8 }),
    M.sanitizeElement({ id, k: "shape", shape: "rect", x: 10, y: 10, w: -20, h: -30, c: 0, sw: 6 }),
    M.sanitizeElement({ id, k: "conn", a: { x: 1, y: 2 }, b: { x: 30, y: 4 }, c: 0, sw: 1 }),
    M.sanitizeElement({ id, k: "conn", a: { el: EL(2) }, b: { el: EL(3) }, c: 0, sw: 1 }),
    M.sanitizeElement({ id, k: "conn", a: { el: EL(2) }, b: { x: 9, y: 9 }, c: 0, sw: 1 }),
  ];
  for (const el of bboxEls) out.bbox.push({ spec: snap(el), bbox: snap(M.elementBBox(el)) });

  const A = { x0: 0, y0: 0, x1: 10, y1: 10 };
  const B = { x0: 5, y0: -5, x1: 20, y1: 3 };
  const C = { x0: 11, y0: 11, x1: 12, y1: 12 };
  out.geometry.push(["union", snap(M.bboxUnion(A, B)), keysOf(M.bboxUnion(A, B))]);
  out.geometry.push(["intersects-yes", M.bboxIntersects(A, B)]);
  out.geometry.push(["intersects-no", M.bboxIntersects(A, C)]);
  out.geometry.push(["intersects-touching", M.bboxIntersects(A, { x0: 10, y0: 10, x1: 11, y1: 11 })]);
  for (const c of [
    [5, 5, 0, 0, 10, 0],
    [-5, 0, 0, 0, 10, 0],
    [15, 0, 0, 0, 10, 0],
    [0, 0, 3, 4, 3, 4],
    [1, 1, 0, 0, 0, 0],
  ]) {
    out.geometry.push(["distToSegment", c, M.distToSegment(...c)]);
  }

  out.limits = { MAX_PTS: M.MAX_PTS };
  out.validId = [
    [id, M.validId(id)],
    ["", M.validId("")],
    ["a".repeat(22), M.validId("a".repeat(22))],
    ["a".repeat(23), M.validId("a".repeat(23))],
    ["a".repeat(21) + "+", M.validId("a".repeat(21) + "+")],
    [null, M.validId(null)],
  ];
  await withClock(T0, () => {
    out.clampTs = [
      ["number", M.clampTs(1234)],
      ["nan", M.clampTs(Number.NaN)],
      ["string", M.clampTs("x")],
      ["negative", M.clampTs(-5)],
      ["future", M.clampTs(T0 + 10_000_000)],
      ["undefined", M.clampTs(undefined)],
    ];
  });
  return out;
}

/**
 * app/tools.ts driven end to end: the log ops and live broadcasts a real
 * gesture produces, with their key order. THE wire surface of a whiteboard.
 */
export async function toolsScript(M, priv, resetRandom) {
  const out = { pen: null, penSplit: null, note: null, text: null, shapes: [], conn: [], select: [], hit: [] };
  // newElementId() is 16 real random bytes; the deterministic stream makes the
  // ids themselves part of the fixture, so the port must produce them too
  resetRandom(1);

  const mk = () => {
    const scene = fakeScene(M.Camera, M.themeFor);
    const log = fakeBoardLog();
    const net = fakeBoardNet();
    const store = new M.BoardStore(net, log, "me", { appSalt: M.APP_SALT, roomId: "ROOM" }, null);
    const style = { c: 2, sw: 3, fill: false };
    const edits = [];
    const sels = [];
    const tools = new M.ToolController({
      scene,
      store,
      style,
      editText: (at, initial, size, wrap, commit) => edits.push({ at: snap(at), initial, size, wrap, commit }),
      onSelection: (sel) => sels.push(sel.map((r) => r.spec.id)),
    });
    return { scene, log, net, store, style, tools, edits, sels };
  };

  // ---- pen: down/move*/up -> one add op, throttled draw previews ----------
  await withClock(T0, async (clock) => {
    const c = mk();
    c.tools.setTool("pen");
    c.tools.down(0, 0, pev({ pointerType: "pen", pressure: 0.5 }));
    for (const [x, y] of [[10, 0], [20, 5], [30, 15], [40, 30]]) {
      clock.perfTick(60); // > DRAW_BCAST_MS: one preview per move
      c.tools.move(x, y, pev({ pointerType: "pen", pressure: 0.9 }));
    }
    clock.perfTick(60);
    c.tools.up(40, 30, pev({ pointerType: "pen", pressure: 0.9 }));
    await Promise.resolve();
    out.pen = { appended: [...c.log.appended], broadcasts: snap(c.net.sent) };
  });

  // ---- pen with mouse pressure (uniform 128 -> no prs field) --------------
  await withClock(T0, async (clock) => {
    const c = mk();
    c.tools.setTool("pen");
    c.tools.down(0, 0, pev());
    clock.perfTick(60);
    c.tools.move(5, 5, pev());
    clock.perfTick(60);
    c.tools.up(5, 5, pev());
    await Promise.resolve();
    out.penNoPressure = { appended: [...c.log.appended] };
  });

  // ---- auto-split at MAX_PTS ----------------------------------------------
  await withClock(T0, async (clock) => {
    const c = mk();
    c.tools.setTool("pen");
    c.tools.down(0, 0, pev());
    // 1.5 screen px thinning at z=1 -> step 2 world units is always accepted
    for (let i = 1; i <= M.MAX_PTS / 2 + 4; i++) {
      clock.perfTick(1);
      c.tools.move(i * 2, 0, pev());
    }
    clock.perfTick(60);
    c.tools.up(0, 0, pev());
    await Promise.resolve();
    const ops = c.log.appended.map((s) => JSON.parse(s));
    out.penSplit = {
      count: ops.length,
      ptsLengths: ops.map((o) => o.el.pts.length),
      firstOrigin: [ops[0].el.x, ops[0].el.y],
      // the split continues seamlessly: the new stroke starts at the last point
      secondOrigin: ops[1] ? [ops[1].el.x, ops[1].el.y] : null,
      keys: ops.map((o) => Object.keys(o.el)),
    };
  });

  // ---- input thinning: a move closer than 1.5/z screen px is dropped ------
  await withClock(T0, async (clock) => {
    const c = mk();
    c.tools.setTool("pen");
    c.tools.down(0, 0, pev());
    clock.perfTick(60);
    c.tools.move(0.5, 0, pev()); // below the threshold
    out.thinning = { afterNear: snap(priv(c.tools, "pts")()) };
    c.tools.move(5, 0, pev()); // above it
    out.thinning.afterFar = snap(priv(c.tools, "pts")());
  });

  // ---- cancel: the terminating draw frame other peers need ---------------
  await withClock(T0, async (clock) => {
    const c = mk();
    c.tools.setTool("pen");
    c.tools.down(0, 0, pev());
    clock.perfTick(60);
    c.tools.move(9, 9, pev());
    c.tools.cancel();
    await settle();
    out.cancel = { appended: [...c.log.appended], broadcasts: snap(c.net.sent) };
  });

  // ---- note / text --------------------------------------------------------
  await withClock(T0, async () => {
    const c = mk();
    c.tools.setTool("note");
    c.tools.down(100, 100, pev());
    await Promise.resolve();
    c.edits[0].commit("sticky");
    await Promise.resolve();
    out.note = { appended: [...c.log.appended], editText: c.edits.map((e) => [snap(e.at), e.initial, e.size, e.wrap]) };
  });
  await withClock(T0, async () => {
    const c = mk();
    c.tools.setTool("text");
    c.tools.down(7, 8, pev());
    await Promise.resolve();
    c.edits[0].commit("  typed  ");
    await Promise.resolve();
    const empty = mk();
    empty.tools.setTool("text");
    empty.tools.down(0, 0, pev());
    empty.edits[0].commit("   ");
    await Promise.resolve();
    out.text = {
      appended: [...c.log.appended],
      editText: c.edits.map((e) => [snap(e.at), e.initial, e.size, e.wrap]),
      blankAppended: [...empty.log.appended],
    };
  });

  // ---- shapes -------------------------------------------------------------
  for (const tool of ["rect", "ellipse", "line", "arrow"]) {
    for (const fill of [false, true]) {
      await withClock(T0, async () => {
        const c = mk();
        c.style.fill = fill;
        c.tools.setTool(tool);
        c.tools.down(10, 20, pev());
        c.tools.move(60, 5, pev());
        c.tools.up(60, 5, pev());
        await Promise.resolve();
        out.shapes.push({ tool, fill, appended: [...c.log.appended] });
      });
    }
  }
  // below MIN_DRAG -> nothing appended
  await withClock(T0, async () => {
    const c = mk();
    c.tools.setTool("rect");
    c.tools.down(0, 0, pev());
    c.tools.up(1, 1, pev());
    await Promise.resolve();
    out.shapeTooSmall = [...c.log.appended];
  });

  // ---- connector: free-free and attached ---------------------------------
  await withClock(T0, async () => {
    const c = mk();
    c.tools.setTool("conn");
    c.tools.down(0, 0, pev());
    c.tools.up(100, 50, pev());
    await Promise.resolve();
    out.conn.push({ name: "free-free", appended: [...c.log.appended] });
  });
  await withClock(T0, async () => {
    const c = mk();
    // a note to attach to
    c.store.applyEntry(entry("h1", FAKE_PUB, 1, {
      t: "add", ts: T0, name: "a",
      el: { id: EL(9), k: "note", x: 0, y: 0, w: 100, h: 100, text: "", c: 0 },
    }));
    c.tools.setTool("conn");
    c.tools.down(50, 2, pev()); // near the north side
    c.tools.up(400, 400, pev());
    await Promise.resolve();
    out.conn.push({ name: "attached-n", appended: [...c.log.appended] });
    out.conn.push({ name: "anchorAt-centre", out: snap(priv(c.tools, "anchorAt")(50, 50)) });
    out.conn.push({ name: "anchorAt-miss", out: snap(priv(c.tools, "anchorAt")(999, 999)) });
  });
  await withClock(T0, async () => {
    const c = mk();
    c.tools.setTool("conn");
    c.tools.down(0, 0, pev());
    c.tools.up(1, 1, pev()); // zero-length free-free is rejected
    await Promise.resolve();
    out.conn.push({ name: "degenerate", appended: [...c.log.appended] });
  });

  // ---- select: move, resize, marquee -------------------------------------
  await withClock(T0, async (clock) => {
    const c = mk();
    c.store.applyEntry(entry("h1", FAKE_PUB, 1, {
      t: "add", ts: T0, name: "a",
      el: { id: EL(1), k: "note", x: 0, y: 0, w: 100, h: 100, text: "", c: 0 },
    }));
    c.store.applyEntry(entry("h2", FAKE_PUB, 2, {
      t: "add", ts: T0, name: "a",
      el: { id: EL(2), k: "note", x: 200, y: 200, w: 50, h: 50, text: "", c: 0 },
    }));
    c.tools.setTool("select");
    c.tools.down(50, 50, pev());
    clock.perfTick(60);
    c.tools.move(70, 90, pev());
    c.tools.up(70, 90, pev());
    await Promise.resolve();
    out.select.push({ name: "move", appended: [...c.log.appended], broadcasts: snap(c.net.sent), sels: snap(c.sels) });

    // resize via the bottom-right handle of the single selection
    const c2 = mk();
    c2.store.applyEntry(entry("h1", FAKE_PUB, 1, {
      t: "add", ts: T0, name: "a",
      el: { id: EL(1), k: "note", x: 0, y: 0, w: 100, h: 100, text: "", c: 0 },
    }));
    c2.tools.setTool("select");
    c2.tools.down(50, 50, pev());
    c2.tools.up(50, 50, pev());
    c2.log.appended.length = 0;
    c2.net.sent.length = 0;
    c2.tools.down(100, 100, pev()); // on the handle
    clock.perfTick(60);
    c2.tools.move(150, 130, pev());
    c2.tools.up(150, 130, pev());
    await Promise.resolve();
    out.select.push({ name: "resize", appended: [...c2.log.appended], broadcasts: snap(c2.net.sent) });

    // marquee
    const c3 = mk();
    for (const [i, x] of [[1, 0], [2, 200]]) {
      c3.store.applyEntry(entry(`h${i}`, FAKE_PUB, i, {
        t: "add", ts: T0, name: "a",
        el: { id: EL(i), k: "note", x, y: 0, w: 50, h: 50, text: "", c: 0 },
      }));
    }
    c3.tools.setTool("select");
    c3.tools.down(-10, -10, pev());
    c3.tools.move(100, 100, pev());
    c3.tools.up(100, 100, pev());
    out.select.push({ name: "marquee", sels: snap(c3.sels) });

    // delete selection
    const c4 = mk();
    c4.store.applyEntry(entry("h1", FAKE_PUB, 1, {
      t: "add", ts: T0, name: "a",
      el: { id: EL(1), k: "note", x: 0, y: 0, w: 50, h: 50, text: "", c: 0 },
    }));
    c4.tools.setTool("select");
    c4.tools.down(10, 10, pev());
    c4.tools.up(10, 10, pev());
    c4.log.appended.length = 0;
    c4.tools.deleteSelection();
    await Promise.resolve();
    out.select.push({ name: "delete", appended: [...c4.log.appended], sels: snap(c4.sels) });
  });

  // ---- eraser -------------------------------------------------------------
  await withClock(T0, async () => {
    const c = mk();
    c.store.applyEntry(entry("h1", FAKE_PUB, 1, {
      t: "add", ts: T0, name: "a",
      el: { id: EL(1), k: "note", x: 0, y: 0, w: 50, h: 50, text: "", c: 0 },
    }));
    c.tools.setTool("eraser");
    c.tools.down(10, 10, pev());
    c.tools.move(20, 20, pev());
    c.tools.up(20, 20, pev());
    await Promise.resolve();
    out.eraser = { appended: [...c.log.appended] };
  });

  // ---- hit testing --------------------------------------------------------
  await withClock(T0, async () => {
    const c = mk();
    const specs = [
      { id: EL(1), k: "stroke", x: 0, y: 0, pts: [10000, 0], w: 2, c: 0 },
      { id: EL(2), k: "note", x: 200, y: 0, w: 50, h: 50, text: "", c: 0 },
      { id: EL(3), k: "shape", shape: "rect", x: 400, y: 0, w: 100, h: 100, c: 0, sw: 4 },
      { id: EL(4), k: "shape", shape: "rect", x: 600, y: 0, w: 100, h: 100, c: 0, sw: 4, fill: 1 },
      { id: EL(5), k: "shape", shape: "line", x: 800, y: 0, w: 100, h: 0, c: 0, sw: 4 },
      { id: EL(6), k: "conn", a: { x: 1000, y: 0 }, b: { x: 1100, y: 0 }, c: 0, sw: 4, arrow: "end" },
    ];
    specs.forEach((el, i) =>
      c.store.applyEntry(entry(`h${i}`, FAKE_PUB, i + 1, { t: "add", ts: T0, name: "a", el })),
    );
    for (const [x, y, slop] of [
      [50, 0, 1], [50, 30, 1], [225, 25, 1], [450, 50, 1], [402, 50, 1],
      [399, 50, 1], [400, 0, 1], [650, 50, 1], [850, 0, 1], [850, 40, 1],
      [1050, 0, 1], [1050, 50, 1], [50, 0, 40],
    ]) {
      const hit = c.tools.hitTest(x, y, slop);
      out.hit.push([x, y, slop, hit ? hit.spec.id : null]);
    }
  });

  return out;
}

/** app/state.ts: the projector — the whole convergence contract. */
export async function projectorScript(M, priv) {
  const out = { scripts: [] };

  const run = async (name, fn) =>
    withClock(T0, async (clock) => {
      const log = fakeBoardLog();
      const net = fakeBoardNet();
      const store = new M.BoardStore(net, log, "me", { appSalt: M.APP_SALT, roomId: "ROOM" }, null);
      const changes = [];
      store.onChange = (b) => changes.push(snap(b) ?? null);
      const imgs = [];
      store.onImageElement = (id, cid) => imgs.push(["in", id, cid]);
      store.onImageGone = (cids) => imgs.push(["gone", [...cids]]);
      const ctrl = [];
      store.onControlOp = (e) => ctrl.push(snap(e));
      await fn({ store, log, net, clock });
      out.scripts.push({
        name,
        entryCount: store.entryCount,
        // by VALUE: the tools and the drag path mutate specs in place
        elements: store.elements().map((r) => ({
          spec: snap(r.spec),
          keys: keysOf(r.spec),
          author: r.author,
          authorName: r.authorName,
          addClock: r.addClock,
          addHash: r.addHash,
          bbox: snap(r.bbox),
          source: r.source,
        })),
        changes,
        imgs,
        ctrl,
        appended: [...log.appended],
        sent: snap(net.sent),
        pending: [...priv(store, "pending")().keys()].sort(),
        tombs: [...priv(store, "tombs")()].sort(),
      });
    });

  const add = (hash, from, clock, el, name = "auth") => entry(hash, from, clock, { t: "add", ts: T0, name, el });
  const note = (id, over = {}) => ({ id, k: "note", x: 0, y: 0, w: 100, h: 100, text: "", c: 0, ...over });

  await run("add-and-zorder", async ({ store }) => {
    store.applyEntry(add("hb", FAKE_PUB, 2, note(EL(2))));
    store.applyEntry(add("ha", FAKE_PUB, 1, note(EL(1))));
    store.applyEntry(add("hc", FAKE_PUB, 2, note(EL(3)))); // same clock, later hash
  });

  await run("duplicate-add-earliest-wins", async ({ store }) => {
    store.applyEntry(add("hz", FAKE_PUB, 5, note(EL(1), { text: "late" })));
    store.applyEntry(add("ha", FAKE_PUB, 2, note(EL(1), { text: "early" })));
    store.applyEntry(add("hb", FAKE_PUB, 9, note(EL(1), { text: "ignored" })));
  });

  await run("edit-lww-per-field", async ({ store }) => {
    store.applyEntry(add("h1", FAKE_PUB, 1, note(EL(1))));
    store.applyEntry(entry("h2", FAKE_PUB, 5, { t: "edit", ts: T0, name: "a", id: EL(1), p: { x: 50, c: 3 } }));
    // older clock: must NOT win on x, but sets a field nobody set yet
    store.applyEntry(entry("h3", FAKE_PUB, 2, { t: "edit", ts: T0, name: "a", id: EL(1), p: { x: 999, text: "t" } }));
    // same clock, greater hash: wins
    store.applyEntry(entry("h9", FAKE_PUB, 5, { t: "edit", ts: T0, name: "a", id: EL(1), p: { x: 7 } }));
    // same clock, smaller hash: loses
    store.applyEntry(entry("h0", FAKE_PUB, 5, { t: "edit", ts: T0, name: "a", id: EL(1), p: { x: -7 } }));
  });

  await run("edit-fill-null-clears", async ({ store }) => {
    store.applyEntry(add("h1", FAKE_PUB, 1, { id: EL(1), k: "shape", shape: "rect", x: 0, y: 0, w: 10, h: 10, c: 1, sw: 2, fill: 4 }));
    store.applyEntry(entry("h2", FAKE_PUB, 2, { t: "edit", ts: T0, name: "a", id: EL(1), p: { fill: null } }));
  });

  await run("edit-before-add-buffered", async ({ store }) => {
    store.applyEntry(entry("h1", FAKE_PUB, 1, { t: "edit", ts: T0, name: "a", id: EL(1), p: { x: 42 } }));
    store.applyEntry(add("h2", FAKE_PUB, 2, note(EL(1))));
  });

  await run("del-is-terminal", async ({ store }) => {
    store.applyEntry(add("h1", FAKE_PUB, 1, note(EL(1))));
    store.applyEntry(entry("h2", FAKE_PUB, 2, { t: "del", ts: T0, name: "a", ids: [EL(1)] }));
    store.applyEntry(add("h3", FAKE_PUB, 3, note(EL(1)))); // no resurrection
    store.applyEntry(entry("h4", FAKE_PUB, 4, { t: "edit", ts: T0, name: "a", id: EL(1), p: { x: 1 } }));
  });

  await run("del-before-add", async ({ store }) => {
    store.applyEntry(entry("h1", FAKE_PUB, 1, { t: "del", ts: T0, name: "a", ids: [EL(1), "bogus"] }));
    store.applyEntry(add("h2", FAKE_PUB, 2, note(EL(1))));
  });

  await run("images-in-and-gone", async ({ store }) => {
    const img = (id, cid) => ({ id, k: "img", x: 0, y: 0, w: 10, h: 10, cid, mime: "image/jpeg", bytes: 9, iw: 4, ih: 8 });
    store.applyEntry(add("h1", FAKE_PUB, 1, img(EL(1), "cidA")));
    store.applyEntry(add("h2", FAKE_PUB, 2, img(EL(2), "cidA"))); // shared cid
    store.applyEntry(add("h3", FAKE_PUB, 3, img(EL(3), "cidB")));
    store.applyEntry(entry("h4", FAKE_PUB, 4, { t: "del", ts: T0, name: "a", ids: [EL(1), EL(3)] }));
  });

  await run("base-gate", async ({ store }) => {
    store.applyEntry(add("h1", FAKE_PUB, 1, note(EL(1))));
    store.applyEntry(add("h5", FAKE_PUB, 5, note(EL(2))));
    store.setBaseGate({ clock: 3, hash: "h3" });
    store.applyEntry(add("h7", FAKE_PUB, 7, note(EL(3)))); // past the gate: ignored
    store.applyEntry(entry("hv", FAKE_PUB, 1_000_007, { t: "add", ts: T0, name: "a", el: note(EL(4)) }), "vault");
    store.setBaseGate(null); // relax
    store.applyEntry(add("h8", FAKE_PUB, 8, note(EL(5))));
  });

  await run("gate-boundary", async ({ store }) => {
    store.setBaseGate({ clock: 3, hash: "h3" });
    store.applyEntry(add("h3", FAKE_PUB, 3, note(EL(1)))); // equal: folds
    store.applyEntry(add("h4", FAKE_PUB, 3, note(EL(2)))); // same clock, bigger hash: gated
    store.applyEntry(add("h2", FAKE_PUB, 3, note(EL(3)))); // same clock, smaller hash: folds
  });

  await run("control-ops-routed", async ({ store }) => {
    for (const op of [
      { t: "mode", ts: T0, name: "a", mode: "strict", epoch: 1, approvals: "any" },
      { t: "cert", ts: T0, xPub: FAKE_PUB, xSig: "sig" },
      { t: "jreq", ts: T0, name: "a", msg: "m", xPub: FAKE_PUB, xSig: "sig" },
      { t: "approve", ts: T0, to: FAKE_PUB, toX: FAKE_PUB, name: "a", epoch: 1, wrap: {} },
      { t: "deny", ts: T0, to: FAKE_PUB },
      { t: "remove", ts: T0, to: FAKE_PUB, epoch: 2, chain: {}, wraps: [] },
      { t: "sealed", e: 1, iv: "iv", ct: "ct" },
    ]) {
      store.applyEntry(entry("h", FAKE_PUB, 1, op));
    }
  });

  await run("writes", async ({ store }) => {
    await store.addElement(M.sanitizeElement(note(EL(1))));
    await store.editElement(EL(1), { x: 5 });
    await store.deleteElements([EL(1), EL(2)]);
    await store.deleteElements([]);
    await store.appendControl({ t: "deny", ts: T0, to: FAKE_PUB });
    store.setName("renamed");
    store.onChannelOpen("12D3KooWPEER");
  });

  await run("anchor-resolution", async ({ store }) => {
    store.applyEntry(add("h1", FAKE_PUB, 1, note(EL(1), { x: 10, y: 20, w: 100, h: 40 })));
    out.anchors = [
      ["free", snap(store.resolveAnchor({ x: 1, y: 2 }))],
      ["n", snap(store.resolveAnchor({ el: EL(1), side: "n" }))],
      ["s", snap(store.resolveAnchor({ el: EL(1), side: "s" }))],
      ["e", snap(store.resolveAnchor({ el: EL(1), side: "e" }))],
      ["w", snap(store.resolveAnchor({ el: EL(1), side: "w" }))],
      ["c", snap(store.resolveAnchor({ el: EL(1), side: "c" }))],
      ["none", snap(store.resolveAnchor({ el: EL(1) }))],
      ["missing", snap(store.resolveAnchor({ el: EL(9) }))],
    ];
  });

  out.vaultClockOffset = M.VAULT_CLOCK_OFFSET;
  return out;
}

/** app/state.ts live (non-logged) payload handling — the validator IS the wire. */
export async function liveScript(M) {
  const out = { messages: [], broadcasts: [], idFields: [] };

  await withClock(T0, async () => {
    const log = fakeBoardLog();
    const net = fakeBoardNet();
    const store = new M.BoardStore(net, log, "me", { appSalt: M.APP_SALT, roomId: "ROOM" }, null);
    const seen = [];
    store.onPeerCursor = (p, x, y, tool) => seen.push(["cur", p, x, y, tool ?? null]);
    store.onPeerDraw = (p, d) => seen.push(["draw", p, snap(d), keysOf(d)]);
    store.onPeerDrag = (p, d) => seen.push(["drag", p, snap(d), keysOf(d)]);
    store.onPeerName = (p, n) => seen.push(["name", p, n]);
    store.onRoomSync = (p, d) => seen.push(["roomsync", p, snap(d)]);

    const cases = [
      ["null", null],
      ["not-object", 7],
      ["unknown-kind", { kind: "nope" }],
      ["cur-ok", { kind: "cur", x: 1.25, y: -3.5 }],
      ["cur-tool", { kind: "cur", x: 0, y: 0, tool: "a".repeat(30) }],
      ["cur-nan", { kind: "cur", x: Number.NaN, y: 0 }],
      ["cur-missing", { kind: "cur", x: 0 }],
      ["draw-ok", { kind: "draw", id: EL(1), seg: [1, 2, 3, 4], w: 5, c: 3 }],
      ["draw-done", { kind: "draw", id: EL(1), seg: [], w: 5, c: 3, done: true }],
      ["draw-bad-id", { kind: "draw", id: "x", seg: [], w: 1, c: 1 }],
      ["draw-long-seg", { kind: "draw", id: EL(1), seg: new Array(513).fill(0), w: 1, c: 1 }],
      ["draw-nan-seg", { kind: "draw", id: EL(1), seg: [1, Number.NaN], w: 1, c: 1 }],
      ["draw-clamped", { kind: "draw", id: EL(1), seg: [0, 0], w: 1e9, c: 99 }],
      ["draw-bad-w", { kind: "draw", id: EL(1), seg: [0, 0], w: "3", c: "2" }],
      ["draw-not-array", { kind: "draw", id: EL(1), seg: "x", w: 1, c: 1 }],
      ["drag-ok", { kind: "drag", id: EL(1), x: 5, y: 6, w: 7, h: 8 }],
      ["drag-partial", { kind: "drag", id: EL(1), x: 5 }],
      ["drag-clamped", { kind: "drag", id: EL(1), x: 1e30, y: -1e30 }],
      ["drag-bad-id", { kind: "drag", id: "x" }],
      ["hello", { kind: "hello", name: "a".repeat(60) }],
      ["name", { kind: "name", name: "peer" }],
      ["name-missing", { kind: "name" }],
      ["roomsync-no-self", { kind: "roomsync", rooms: [], gone: [] }],
      ["blive-no-opener", { kind: "blive", e: 1, iv: "i", ct: "c" }],
    ];
    for (const [name, p] of cases) {
      const before = seen.length;
      store.onMessage("12D3KooWA", p);
      out.messages.push({ name, emitted: snap(seen.slice(before)) });
    }
    // drain the roomsync chain so nothing lands after the snapshot
    await settle();
  });

  // ---- blive: strict-mode inner envelope re-dispatch ----------------------
  await withClock(T0, async () => {
    const net = fakeBoardNet();
    const store = new M.BoardStore(net, fakeBoardLog(), "me", { appSalt: M.APP_SALT, roomId: "ROOM" }, null);
    const seen = [];
    store.onPeerCursor = (p, x, y) => seen.push(["cur", p, x, y]);
    store.liveOpener = async (p) => (p.e === 1 ? { kind: "cur", x: p.iv.length, y: p.ct.length } : null);
    store.onMessage("12D3KooWA", { kind: "blive", e: 1, iv: "iiii", ct: "cc" });
    store.onMessage("12D3KooWA", { kind: "blive", e: 2, iv: "i", ct: "c" });
    // a nested blive must not recurse
    store.liveOpener = async () => ({ kind: "blive", e: 1, iv: "i", ct: "c" });
    store.onMessage("12D3KooWA", { kind: "blive", e: 1, iv: "i", ct: "c" });
    await settle();
    out.blive = snap(seen);
  });

  // ---- broadcast: plain vs sealed ----------------------------------------
  await withClock(T0, async () => {
    const net = fakeBoardNet();
    const store = new M.BoardStore(net, fakeBoardLog(), "me", { appSalt: M.APP_SALT, roomId: "ROOM" }, null);
    store.broadcast({ kind: "cur", x: 1, y: 2 });
    store.broadcast({ kind: "name", name: "n" });
    await settle();
    out.broadcasts.push({ name: "plain", sent: snap(net.sent) });

    const net2 = fakeBoardNet();
    const store2 = new M.BoardStore(net2, fakeBoardLog(), "me", { appSalt: M.APP_SALT, roomId: "ROOM" }, null);
    store2.liveSealer = async (p) => ({ e: 3, iv: "IV", ct: `CT:${p.kind}` });
    store2.broadcast({ kind: "cur", x: 1, y: 2 });
    store2.broadcast({ kind: "draw", id: EL(1), seg: [], w: 1, c: 1 });
    store2.broadcast({ kind: "drag", id: EL(1), x: 1 });
    // identity flows stay outer-only: strangers must be able to knock
    store2.broadcast({ kind: "name", name: "n" });
    await settle();
    out.broadcasts.push({ name: "sealed", sent: snap(net2.sent) });
  });

  // ---- idFields: the identity announcement shape -------------------------
  await withClock(T0, async () => {
    for (const [name, self] of [
      ["none", null],
      ["bare", { pub: FAKE_PUB, sig: "SIG" }],
      ["hue", { pub: FAKE_PUB, sig: "SIG", hue: 210 }],
      ["glyph", { pub: FAKE_PUB, sig: "SIG", hue: null, glyph: "star" }],
      ["both", { pub: FAKE_PUB, sig: "SIG", hue: 0, glyph: "star" }],
    ]) {
      const net = fakeBoardNet();
      const store = new M.BoardStore(net, fakeBoardLog(), "me", { appSalt: M.APP_SALT, roomId: "ROOM" }, self);
      store.onChannelOpen("12D3KooWB");
      await settle();
      out.idFields.push({ name, sent: snap(net.sent) });
    }
  });

  return out;
}

/**
 * Same-identity device sync: a board list is accepted only from a peer whose
 * VERIFIED identity is our own. Real Ed25519 assertions, real verification.
 */
export async function deviceSyncScript(M, Identity, localStorageStub) {
  const out = [];
  // self-contained TOFU state: the "self" case binds the display name "dev" to
  // one key, so the "stranger" case (same name, different key) must report
  // keyChanged — which only holds if the store starts empty here
  localStorageStub.clear();
  const me = await Identity.fromSeed(SEED);
  const other = await Identity.fromSeed(SEED2);
  const roomId = "ROOMID";
  const myPeer = "12D3KooWSELF";

  for (const [name, signer] of [["self", me], ["stranger", other]]) {
    const peer = "12D3KooWPEER";
    const sig = await signer.assert(M.APP_SALT, roomId, peer);
    const net = fakeBoardNet(myPeer);
    const store = new M.BoardStore(net, fakeBoardLog(), "me", { appSalt: M.APP_SALT, roomId }, {
      pub: me.publicKeyB64,
      sig: await me.assert(M.APP_SALT, roomId, myPeer),
    });
    const events = [];
    store.onPeerIdentity = (p, id) => events.push(["ident", p, id.pub, id.fp.emoji, snap(id.verdict)]);
    store.onSelfDevice = (p) => events.push(["selfDevice", p]);
    store.onRoomSync = (p, payload) => events.push(["roomsync", p, snap(payload)]);
    store.onMessage(peer, { kind: "hello", name: "dev", idPub: signer.publicKeyB64, idSig: sig });
    store.onMessage(peer, { kind: "roomsync", rooms: [{ s: "x" }], gone: [] });
    await settle();
    // a second roomsync from the same peer is ignored
    store.onMessage(peer, { kind: "roomsync", rooms: [{ s: "y" }], gone: [] });
    await settle();
    out.push({ name, events: snap(events), sent: snap(net.sent) });
  }

  // a forged assertion never yields an identity
  {
    const peer = "12D3KooWFORGE";
    const store = new M.BoardStore(fakeBoardNet(), fakeBoardLog(), "me", { appSalt: M.APP_SALT, roomId }, null);
    const events = [];
    store.onPeerIdentity = (p, id) => events.push(["ident", p, id.pub]);
    store.onMessage(peer, { kind: "hello", name: "x", idPub: me.publicKeyB64, idSig: "A".repeat(86) });
    await settle();
    out.push({ name: "forged", events: snap(events) });
  }
  return out;
}

/** app/trust.ts: TOFU + explicit verification, and the stored JSON. */
export async function trustScript(M, localStorageStub) {
  const out = [];
  localStorageStub.clear();
  const step = (label, v) => out.push({ label, v: snap(v), storage: localStorageStub.snapshot() });

  step("first-sight", M.trustObserve("Ana", FAKE_PUB));
  step("same-again", M.trustObserve("Ana", FAKE_PUB));
  step("key-changed", M.trustObserve("ana", "OTHERPUB_OTHERPUB_OTHERPUB_OTHERPUB_OTHERPU"));
  step("case-and-space", M.trustObserve("  ANA  ", FAKE_PUB));
  M.trustSetVerified(FAKE_PUB, "Ana", true);
  step("verified", M.trustIsVerified(FAKE_PUB));
  step("observe-after-verify", M.trustObserve("Ana", FAKE_PUB));
  M.trustSetVerified(FAKE_PUB, "Ana", false);
  step("unverified", M.trustIsVerified(FAKE_PUB));
  // attacker-chosen names must land on own properties, never the prototype
  step("proto-name", M.trustObserve("__proto__", FAKE_PUB));
  step("ctor-name", M.trustObserve("constructor", FAKE_PUB));
  step("proto-again", M.trustObserve("__proto__", "ZZZ_ZZZ_ZZZ_ZZZ_ZZZ_ZZZ_ZZZ_ZZZ_ZZZ_ZZZ_ZZZ"));
  localStorageStub.clear();
  localStorageStub.setItem(M.nsKey("trust"), "{{{not json");
  step("corrupt-store", M.trustObserve("Ana", FAKE_PUB));
  return out;
}

/** app/boards.ts: the local board directory and its cross-device merge. */
export async function boardsScript(M, localStorageStub) {
  const out = [];
  const S = (c) => c.repeat(43);
  const P = (c) => `${c.repeat(43)}.${"p".repeat(43)}`;

  const step = (label, v) => out.push({ label, v: snap(v), storage: localStorageStub.snapshot() });

  await withClock(T0, async (clock) => {
    localStorageStub.clear();
    let changes = 0;
    M.setOnRoomsChanged(() => changes++);

    step("touch-new", M.touchRoom(S("a")));
    clock.tick(60_000);
    step("touch-second", M.touchRoom(P("b")));
    clock.tick(60_000);
    step("revisit-first", M.touchRoom(S("a")));
    M.renameRoom(S("a"), "  My board  ".trim());
    step("renamed", M.loadRooms());
    M.renameRoom(S("a"), "");
    step("rename-empty-keeps", M.loadRooms());
    M.renameRoom(S("z"), "nope");
    step("rename-unknown", M.loadRooms());
    M.forgetRoom(P("b"));
    step("forgotten", M.loadRooms());
    clock.tick(60_000);
    step("rejoin-beats-tombstone", M.touchRoom(P("b")));
    step("build-sync", M.buildRoomSync());
    out.push({ label: "onRoomsChanged-fired", v: changes > 0 });
    M.setOnRoomsChanged(null);
  });

  // ---- mergeRooms -------------------------------------------------------
  const mergeCase = async (label, seed, remote, current) =>
    withClock(T0 + 3_600_000, async () => {
      localStorageStub.clear();
      if (seed) localStorageStub.setItem(M.nsKey("boards"), JSON.stringify(seed.rooms ?? []));
      if (seed) localStorageStub.setItem(M.nsKey("boards-gone"), JSON.stringify(seed.gone ?? []));
      const added = M.mergeRooms(remote, current ?? S("a"));
      out.push({ label: `merge:${label}`, v: { added, rooms: snap(M.loadRooms()) }, storage: localStorageStub.snapshot() });
    });

  await mergeCase("not-array", null, { rooms: "x", gone: [] });
  await mergeCase("fresh", null, { rooms: [{ s: S("c"), label: "C", ts: T0 }], gone: [] });
  await mergeCase("bad-secret", null, { rooms: [{ s: "short", label: "X", ts: T0 }], gone: [] });
  await mergeCase(
    "control-chars-and-clamp",
    null,
    { rooms: [{ s: S("c"), label: "a\u0000b\u001fc", ts: T0 + 1e12 }], gone: [] },
  );
  await mergeCase(
    "dedupe-newest-wins",
    null,
    { rooms: [{ s: S("c"), label: "old", ts: T0 }, { s: S("c"), label: "new", ts: T0 + 5000 }], gone: [] },
  );
  await mergeCase(
    "rename-wins-by-lts",
    { rooms: [{ s: S("c"), label: "local", ts: T0 + 100, lts: 5 }] },
    { rooms: [{ s: S("c"), label: "remote", ts: T0, lts: 10 }], gone: [] },
  );
  await mergeCase(
    "rename-loses-by-lts",
    { rooms: [{ s: S("c"), label: "local", ts: T0, lts: 20 }] },
    { rooms: [{ s: S("c"), label: "remote", ts: T0, lts: 10 }], gone: [] },
  );
  await mergeCase(
    "tombstone-blocks-older",
    { gone: [{ s: S("c"), ts: T0 + 1000 }] },
    { rooms: [{ s: S("c"), label: "R", ts: T0 }], gone: [] },
  );
  await mergeCase(
    "newer-entry-beats-tombstone",
    { gone: [{ s: S("c"), ts: T0 }] },
    { rooms: [{ s: S("c"), label: "R", ts: T0 + 1000 }], gone: [] },
  );
  await mergeCase(
    "current-board-survives-tombstone",
    { gone: [{ s: S("a"), ts: T0 + 1e6 }] },
    { rooms: [{ s: S("a"), label: "R", ts: T0 }], gone: [] },
    S("a"),
  );
  await mergeCase(
    "remote-forget-wins",
    { rooms: [{ s: S("c"), label: "local", ts: T0 }] },
    { rooms: [], gone: [{ s: S("c"), ts: T0 + 1000 }] },
  );
  await mergeCase(
    "remote-forget-loses",
    { rooms: [{ s: S("c"), label: "local", ts: T0 + 5000 }] },
    { rooms: [], gone: [{ s: S("c"), ts: T0 }] },
  );
  await mergeCase(
    "remote-forget-of-current-ignored",
    { rooms: [{ s: S("a"), label: "here", ts: T0 }] },
    { rooms: [], gone: [{ s: S("a"), ts: T0 + 1e6 }] },
    S("a"),
  );
  await mergeCase("gone-not-array", null, { rooms: [], gone: "x" });

  return out;
}

/** lib/epoch.ts: the strict-board keyring. Deterministic IVs via det-random. */
export async function epochScript(M, resetRandom, hex) {
  const out = { grants: [], sealed: [], live: [], chain: [], cascade: [] };
  const SALT = M.APP_SALT;
  const ROOM = "ROOMID";

  // ---- grant codec ------------------------------------------------------
  const g = { v: "V".repeat(43), e: "E".repeat(43), n: 3 };
  const enc = M.encodeGrant(g);
  out.grants.push({ name: "roundtrip", bytes: hex(enc), json: new TextDecoder().decode(enc), keys: keysOf(g), back: snap(M.decodeGrant(enc)) });
  const te = new TextEncoder();
  for (const [name, s] of [
    ["not-json", "{{{"],
    ["missing-n", JSON.stringify({ v: "V".repeat(43), e: "E".repeat(43) })],
    ["short-v", JSON.stringify({ v: "V", e: "E".repeat(43), n: 1 })],
    ["bad-charset", JSON.stringify({ v: "+".repeat(43), e: "E".repeat(43), n: 1 })],
    ["n-not-number", JSON.stringify({ v: "V".repeat(43), e: "E".repeat(43), n: "1" })],
  ]) {
    out.grants.push({ name, back: snap(M.decodeGrant(te.encode(s))) });
  }

  // ---- op sealing (byte-exact under the deterministic IV stream) --------
  {
    resetRandom(7);
    const kr = new M.EpochKeyring(SALT, ROOM);
    out.epochSecretShape = { len: M.EpochKeyring.newEpochSecret().length };
    resetRandom(7);
    kr.addEpoch(1, "A".repeat(43));
    kr.addEpoch(2, "B".repeat(43));
    kr.addEpoch(2, "C".repeat(43)); // already installed: ignored
    out.current = kr.current;
    out.has = [kr.has(1), kr.has(2), kr.has(3)];
    out.epochSecret = [kr.epochSecret(1), kr.epochSecret(3)];

    const inner = { t: "add", ts: 1, name: "n", el: { id: EL(1), k: "note", x: 0, y: 0, w: 1, h: 1, text: "", c: 0 } };
    const sealed = await kr.sealOp(inner);
    out.sealed.push({ name: "epoch2", op: snap(sealed), keys: keysOf(sealed) });
    out.sealed.push({ name: "reopen", back: snap(await kr.openOp(sealed)) });
    out.sealed.push({ name: "wrong-epoch", back: snap(await kr.openOp({ ...sealed, e: 1 })) });
    out.sealed.push({ name: "unknown-epoch", back: snap(await kr.openOp({ ...sealed, e: 9 })) });
    out.sealed.push({ name: "bad-epoch-0", back: snap(await kr.openOp({ ...sealed, e: 0 })) });
    out.sealed.push({ name: "bad-epoch-huge", back: snap(await kr.openOp({ ...sealed, e: 2_000_000 })) });
    out.sealed.push({ name: "bad-epoch-float", back: snap(await kr.openOp({ ...sealed, e: 1.5 })) });
    out.sealed.push({
      name: "tampered",
      back: snap(await kr.openOp({ ...sealed, ct: M.toB64(new Uint8Array(M.fromB64(sealed.ct).length).fill(9)) })),
    });

    const live = await kr.sealLive({ kind: "cur", x: 1, y: 2 });
    out.live.push({ name: "sealed", p: snap(live), keys: keysOf(live) });
    out.live.push({ name: "reopen", back: snap(await kr.openLive(live)) });
    out.live.push({ name: "bad-epoch", back: snap(await kr.openLive({ ...live, e: 0 })) });
    out.live.push({ name: "unknown-epoch", back: snap(await kr.openLive({ ...live, e: 9 })) });
  }

  // ---- keychain + cascade ----------------------------------------------
  {
    resetRandom(11);
    const kr = new M.EpochKeyring(SALT, ROOM);
    kr.addEpoch(1, "A".repeat(43));
    kr.addEpoch(2, "B".repeat(43));
    const c2 = await kr.sealChain(2);
    kr.addEpoch(3, "C".repeat(43));
    const c3 = await kr.sealChain(3);
    out.chain.push({ n: 2, box: snap(c2), keys: keysOf(c2) });
    out.chain.push({ n: 3, box: snap(c3), keys: keysOf(c3) });

    // a fresh keyring holding only epoch 3 cascades back to 1
    const kr2 = new M.EpochKeyring(SALT, ROOM);
    kr2.addEpoch(3, "C".repeat(43));
    await kr2.cascade(new Map([[2, c2], [3, c3]]));
    out.cascade.push({ name: "full", current: kr2.current, held: [1, 2, 3].map((n) => kr2.epochSecret(n)) });

    // a gap stops the cascade
    const kr3 = new M.EpochKeyring(SALT, ROOM);
    kr3.addEpoch(3, "C".repeat(43));
    await kr3.cascade(new Map([[3, c3]]));
    out.cascade.push({ name: "gap", held: [1, 2, 3].map((n) => kr3.epochSecret(n)) });

    // a corrupt box stops it too
    const kr4 = new M.EpochKeyring(SALT, ROOM);
    kr4.addEpoch(3, "C".repeat(43));
    await kr4.cascade(new Map([[3, { iv: c3.iv, ct: M.toB64(new Uint8Array(48).fill(1)) }], [2, c2]]));
    out.cascade.push({ name: "corrupt", held: [1, 2, 3].map((n) => kr4.epochSecret(n)) });
  }

  // ---- cross-epoch isolation: E_2 content is unreadable with E_1 only ---
  {
    resetRandom(3);
    const writer = new M.EpochKeyring(SALT, ROOM);
    writer.addEpoch(1, "A".repeat(43));
    writer.addEpoch(2, "B".repeat(43));
    const s2 = await writer.sealOp({ t: "del", ts: 1, name: "n", ids: [EL(1)] });
    const reader = new M.EpochKeyring(SALT, ROOM);
    reader.addEpoch(1, "A".repeat(43));
    out.isolation = { epoch: s2.e, withE1Only: snap(await reader.openOp(s2)) };
  }

  // ---- the AADs bind to the roomId -------------------------------------
  {
    resetRandom(5);
    const a = new M.EpochKeyring(SALT, "ROOM-A");
    a.addEpoch(1, "A".repeat(43));
    const s = await a.sealOp({ t: "del", ts: 1, name: "n", ids: [] });
    const b = new M.EpochKeyring(SALT, "ROOM-B");
    b.addEpoch(1, "A".repeat(43));
    out.aadBinding = snap(await b.openOp(s));
  }
  return out;
}

/** lib/wrapbox.ts (id-kit/xkey): X25519 identity, certs, sealed-box wraps. */
export async function wrapboxScript(M, Identity, resetRandom, hex) {
  const out = {};
  const SALT = M.APP_SALT;
  const CTX = "ROOMID";
  const me = await Identity.fromSeed(SEED);
  const you = await Identity.fromSeed(SEED2);

  const xa = await M.deriveXKeyPair(SEED, SALT);
  const xb = await M.deriveXKeyPair(SEED2, SALT);
  const xaAgain = await M.deriveXKeyPair(SEED, SALT);
  const xaOtherSalt = await M.deriveXKeyPair(SEED, "other.salt/v1");
  out.derive = {
    pubA: xa.pubB64,
    pubB: xb.pubB64,
    deterministic: xa.pubB64 === xaAgain.pubB64,
    saltSeparated: xa.pubB64 !== xaOtherSalt.pubB64,
  };

  const certA = await M.signXCert(me, SALT, xa.pubB64);
  out.cert = {
    sig: certA,
    verifies: await M.verifyXCert(SALT, me.publicKeyB64, xa.pubB64, certA),
    wrongSigner: await M.verifyXCert(SALT, you.publicKeyB64, xa.pubB64, certA),
    wrongKey: await M.verifyXCert(SALT, me.publicKeyB64, xb.pubB64, certA),
    wrongSalt: await M.verifyXCert("other.salt/v1", me.publicKeyB64, xa.pubB64, certA),
    garbage: await M.verifyXCert(SALT, me.publicKeyB64, xa.pubB64, "A".repeat(86)),
  };

  resetRandom(23);
  const payload = new TextEncoder().encode('{"v":"secret","e":"epoch","n":1}');
  const w = await M.wrapTo(SALT, CTX, you.publicKeyB64, xb.pubB64, payload);
  out.wrap = { keys: keysOf(w), to: w.to, toX: w.toX, ephPub: w.ephPub, iv: w.iv, ct: w.ct };
  out.unwrap = {
    ok: hex(await M.unwrap(SALT, CTX, w, xb)),
    wrongRecipient: snap(await M.unwrap(SALT, CTX, w, xa)),
    wrongCtx: snap(await M.unwrap(SALT, "OTHER", w, xb)),
    wrongSalt: snap(await M.unwrap("other.salt/v1", CTX, w, xb)),
    tampered: snap(await M.unwrap(SALT, CTX, { ...w, ct: M.toB64(new Uint8Array(M.fromB64(w.ct).length).fill(7)) }, xb)),
  };
  return out;
}

/** lib/policy.ts: the deterministic control-plane fold. */
export async function policyScript(M, Identity) {
  const out = [];
  const SALT = M.APP_SALT;
  const creator = await Identity.fromSeed(SEED);
  const member = await Identity.fromSeed(SEED2);
  const stranger = await Identity.fromSeed(SEED3);
  const xc = await M.deriveXKeyPair(SEED, SALT);
  const xm = await M.deriveXKeyPair(SEED2, SALT);
  const xs = await M.deriveXKeyPair(SEED3, SALT);
  const certOf = async (id, x) => M.signXCert(id, SALT, x.pubB64);

  const state = (f) => {
    const s = f.state;
    return {
      mode: s.mode,
      approvals: s.approvals,
      epoch: s.epoch,
      members: [...s.members.entries()].sort(),
      removed: [...s.removed].sort(),
      pending: snap(s.pending),
      myWraps: snap(s.myWraps),
      chains: [...s.chains.entries()].map(([k, v]) => [k, snap(v)]).sort((a, b) => a[0] - b[0]),
      strictSince: snap(s.strictSince),
    };
  };

  const CP = creator.publicKeyB64;
  const MP = member.publicKeyB64;
  const SP = stranger.publicKeyB64;

  out.push(["isControlOp", ["mode", "cert", "jreq", "approve", "deny", "remove", "add", "sealed", "rekey"].map((t) => [t, M.isControlOp(t)])]);

  // no creatorPub -> never leaves link mode
  {
    const f = new M.AccessFold(SALT, null, MP);
    f.ingest(entry("h1", CP, 1, { t: "mode", ts: 1, name: "c", mode: "strict", epoch: 1, approvals: "any" }));
    await settle();
    out.push(["no-creator", { strictCapable: f.strictCapable, creatorPub: f.creatorPub, state: state(f) }]);
  }
  // a malformed creatorPub is dropped
  {
    const f = new M.AccessFold(SALT, "not-a-pub", MP);
    out.push(["bad-creator", { strictCapable: f.strictCapable, creatorPub: f.creatorPub }]);
  }

  // the happy path, as the MEMBER sees it
  {
    const f = new M.AccessFold(SALT, CP, MP);
    const cCert = await certOf(creator, xc);
    const mCert = await certOf(member, xm);
    f.ingest(entry("h1", CP, 1, { t: "cert", ts: 1, xPub: xc.pubB64, xSig: cCert }));
    f.ingest(entry("h2", MP, 2, { t: "cert", ts: 2, xPub: xm.pubB64, xSig: mCert }));
    await settle();
    out.push(["certs", state(f)]);
    f.ingest(entry("h3", MP, 3, { t: "jreq", ts: 3, name: "M", msg: "let me\u0000in", xPub: xm.pubB64, xSig: mCert }));
    await settle();
    out.push(["jreq-pending", state(f)]);
    const wrap = { to: MP, toX: xm.pubB64, ephPub: "E", iv: "IV", ct: "CT" };
    f.ingest(entry("h4", CP, 4, { t: "approve", ts: 4, to: MP, toX: xm.pubB64, name: "c", epoch: 1, wrap }));
    await settle();
    out.push(["approved", state(f)]);
    f.ingest(entry("h5", CP, 5, {
      t: "mode", ts: 5, name: "c", mode: "strict", epoch: 1, approvals: "any",
      wraps: [wrap, { to: SP, toX: xs.pubB64, ephPub: "E", iv: "IV", ct: "OTHER" }],
    }));
    await settle();
    out.push(["strict", state(f)]);
    f.ingest(entry("h6", CP, 6, {
      t: "remove", ts: 6, to: MP, epoch: 2, chain: { iv: "CIV", ct: "CCT" },
      wraps: [{ to: MP, toX: xm.pubB64, ephPub: "E", iv: "IV", ct: "REMOVED" }],
    }));
    await settle();
    out.push(["removed", state(f)]);
    f.ingest(entry("h7", CP, 7, { t: "mode", ts: 7, name: "c", mode: "link", epoch: 2, approvals: "any" }));
    await settle();
    out.push(["relaxed", state(f)]);
  }

  // an unverified cert never enters the fold
  {
    const f = new M.AccessFold(SALT, CP, MP);
    f.ingest(entry("h1", MP, 1, { t: "cert", ts: 1, xPub: xm.pubB64, xSig: "A".repeat(86) }));
    f.ingest(entry("h2", MP, 2, { t: "jreq", ts: 2, name: "M", msg: "", xPub: xm.pubB64, xSig: "A".repeat(86) }));
    await settle();
    out.push(["unverified-cert", state(f)]);
  }

  // only the creator's mode/remove count
  {
    const f = new M.AccessFold(SALT, CP, MP);
    f.ingest(entry("h1", MP, 1, { t: "mode", ts: 1, name: "m", mode: "strict", epoch: 5, approvals: "creator" }));
    f.ingest(entry("h2", MP, 2, { t: "remove", ts: 2, to: CP, epoch: 3, chain: { iv: "a", ct: "b" }, wraps: [] }));
    await settle();
    out.push(["non-creator-control", state(f)]);
  }

  // approvals:"creator" blocks member approvals
  {
    const f = new M.AccessFold(SALT, CP, MP);
    const mCert = await certOf(member, xm);
    const sCert = await certOf(stranger, xs);
    f.ingest(entry("h1", CP, 1, { t: "mode", ts: 1, name: "c", mode: "strict", epoch: 1, approvals: "creator" }));
    f.ingest(entry("h2", CP, 2, { t: "approve", ts: 2, to: MP, toX: xm.pubB64, name: "c", epoch: 1, wrap: { to: MP, toX: xm.pubB64, ephPub: "E", iv: "I", ct: "C" } }));
    f.ingest(entry("h3", MP, 3, { t: "approve", ts: 3, to: SP, toX: xs.pubB64, name: "m", epoch: 1, wrap: { to: SP, toX: xs.pubB64, ephPub: "E", iv: "I", ct: "C" } }));
    await settle();
    out.push(["approvals-creator-only", state(f)]);
    void mCert;
    void sCert;
  }

  // a member approval overrides nothing when the member is removed; a creator
  // approval overrides a standing removal
  {
    const f = new M.AccessFold(SALT, CP, SP);
    f.ingest(entry("h1", CP, 1, { t: "approve", ts: 1, to: SP, toX: xs.pubB64, name: "c", epoch: 1, wrap: { to: SP, toX: xs.pubB64, ephPub: "E", iv: "I", ct: "C1" } }));
    f.ingest(entry("h2", CP, 2, { t: "remove", ts: 2, to: SP, epoch: 2, chain: { iv: "a", ct: "b" }, wraps: [] }));
    f.ingest(entry("h3", MP, 3, { t: "approve", ts: 3, to: SP, toX: xs.pubB64, name: "m", epoch: 2, wrap: { to: SP, toX: xs.pubB64, ephPub: "E", iv: "I", ct: "C2" } }));
    await settle();
    out.push(["member-approve-after-removal", state(f)]);
    f.ingest(entry("h4", CP, 4, { t: "approve", ts: 4, to: SP, toX: xs.pubB64, name: "c", epoch: 2, wrap: { to: SP, toX: xs.pubB64, ephPub: "E", iv: "I", ct: "C3" } }));
    await settle();
    out.push(["creator-approve-after-removal", state(f)]);
  }

  // deny hides a request; the fold is order-independent (sorted by clock, hash)
  {
    const mCert = await certOf(member, xm);
    const sCert = await certOf(stranger, xs);
    const ops = [
      entry("hb", MP, 2, { t: "jreq", ts: 2, name: "M", msg: "hi", xPub: xm.pubB64, xSig: mCert }),
      entry("ha", MP, 1, { t: "cert", ts: 1, xPub: xm.pubB64, xSig: mCert }),
      entry("hc", CP, 3, { t: "deny", ts: 3, to: MP }),
      // a second identity that IS let in, so the compared states are non-trivial
      entry("hd", SP, 4, { t: "cert", ts: 4, xPub: xs.pubB64, xSig: sCert }),
      entry("he", SP, 5, { t: "jreq", ts: 5, name: "S", msg: "hey", xPub: xs.pubB64, xSig: sCert }),
      entry("hf", CP, 6, { t: "approve", ts: 6, to: SP, toX: xs.pubB64, name: "c", epoch: 1, wrap: { to: SP, toX: xs.pubB64, ephPub: "E", iv: "I", ct: "CS" } }),
      entry("hg", CP, 7, { t: "mode", ts: 7, name: "c", mode: "strict", epoch: 1, approvals: "any" }),
    ];
    const f1 = new M.AccessFold(SALT, CP, CP);
    for (const e of ops) f1.ingest(e);
    await settle();
    const f2 = new M.AccessFold(SALT, CP, CP);
    for (const e of [...ops].reverse()) f2.ingest(e);
    await settle();
    out.push(["deny-order-independent", { forward: state(f1), reverse: state(f2), equal: JSON.stringify(state(f1)) === JSON.stringify(state(f2)) }]);
  }

  // duplicate hashes are ingested once
  {
    const f = new M.AccessFold(SALT, CP, CP);
    const e = entry("h1", CP, 1, { t: "mode", ts: 1, name: "c", mode: "strict", epoch: 4, approvals: "any" });
    f.ingest(e);
    f.ingest(e);
    f.ingest(entry("h1", CP, 9, { t: "mode", ts: 9, name: "c", mode: "link", epoch: 9, approvals: "any" }));
    await settle();
    out.push(["dedupe-by-hash", state(f)]);
  }

  // epoch clamping and the wraps cap
  {
    const f = new M.AccessFold(SALT, CP, MP);
    const many = Array.from({ length: 200 }, (_, i) => ({ to: MP, toX: xm.pubB64, ephPub: "E", iv: "I", ct: `C${i}` }));
    f.ingest(entry("h1", CP, 1, { t: "mode", ts: 1, name: "c", mode: "strict", epoch: 9_999_999, approvals: "any", wraps: many }));
    await settle();
    const s = state(f);
    out.push(["epoch-clamp-and-wrap-cap", { epoch: s.epoch, wraps: s.myWraps.length, lastCt: s.myWraps.at(-1)?.wrap.ct }]);
  }

  // non-content ops are not ingested at all
  {
    const f = new M.AccessFold(SALT, CP, CP);
    f.ingest(entry("h1", CP, 1, { t: "add", ts: 1, name: "c", el: {} }));
    await settle();
    out.push(["content-op-ignored", state(f)]);
  }
  return out;
}

/**
 * lib/mailbox.ts end to end — copied verbatim from chat's harness, because
 * board's lib/mailbox.ts is byte-identical to chat's pre-CLJS ancestor APART
 * from three queueCap lines (a drop-oldest since RETIRED with the cap itself:
 * the outgoing queue is uncapped now, per the no-silent-drop rule), and the
 * fixture it recorded (vectors/mailbox.json) therefore describes board's
 * TypeScript exactly. Run green against it in BOARD_TS=1 mode before the port.
 */
export async function mailboxScript(M) {
  const { MailboxAuth, MailboxClient, MailboxSync, RoomCrypto, APP_SALT, nsKey, priv, localStorageStub } = M;
  const { installDetRandom, resetRandom, restoreRandom } = await import("./det-random.mjs");
  const hex = (u8) => [...u8].map((b) => b.toString(16).padStart(2, "0")).join("");
  const out = {};
  const realFetch = globalThis.fetch;

  return withClock(T0, async (clock) => {
    try {
      localStorageStub.clear();

      // ---- auth: open mint, cached until 5 min before expiry --------------
      let mints = 0;
      const urls = [];
      globalThis.fetch = async (url) => {
        urls.push(String(url));
        mints++;
        return { ok: true, status: 200, json: async () => ({ token: `tok${mints}`, ttl: 3600 }) };
      };
      const auth = new MailboxAuth("https://relay.example/mint", "MBX ROOM/ID");
      out.auth = { first: await auth.get() };
      out.auth.cached = await auth.get();
      clock.tick(3600_000 - 300_000 - 1);
      out.auth.stillCached = await auth.get();
      clock.tick(2);
      out.auth.reminted = await auth.get();
      auth.invalidate();
      out.auth.afterInvalidate = await auth.get();
      out.auth.urls = urls.slice();
      out.auth.mints = mints;

      // ---- client: status → typed result table ---------------------------
      const reqs = [];
      let respond = null;
      let mintN = 0;
      globalThis.fetch = async (url, init) => {
        // the mint and the message endpoint are DIFFERENT requests: every
        // MailboxClient call first pulls a bearer from MailboxAuth, so a stub
        // that answers both with the deposit response makes every case "net"
        if (String(url).includes("/mint")) {
          return { ok: true, status: 200, json: async () => ({ token: `tok${++mintN}`, ttl: 3600 }) };
        }
        reqs.push([String(url), init?.method ?? "GET", init?.headers?.authorization ?? null]);
        return respond();
      };
      const mkClient = () => new MailboxClient("https://relay.example/mbx/", "MBX ROOM/ID", new MailboxAuth("https://relay.example/mint", "MBX ROOM/ID"));
      out.deposit = {};
      const depositCases = {
        created: () => ({ ok: true, status: 201, json: async () => ({ deduped: false, seq: "0001" }) }),
        deduped: () => ({ ok: true, status: 200, json: async () => ({ deduped: true, seq: "0001" }) }),
        "no-json": () => ({ ok: true, status: 200, json: async () => { throw new Error("x"); } }),
        "too-large": () => ({ ok: false, status: 413, json: async () => ({}) }),
        auth: () => ({ ok: false, status: 401, json: async () => ({}) }),
        forbidden: () => ({ ok: false, status: 403, json: async () => ({}) }),
        throttled: () => ({ ok: false, status: 429, json: async () => ({}) }),
        full: () => ({ ok: false, status: 507, json: async () => ({}) }),
        server: () => ({ ok: false, status: 500, json: async () => ({}) }),
      };
      for (const [label, impl] of Object.entries(depositCases)) {
        respond = impl;
        out.deposit[label] = JSON.parse(JSON.stringify(await mkClient().deposit(new Uint8Array([1, 2, 3]))));
      }
      respond = async () => { throw new Error("offline"); };
      out.deposit.network = JSON.parse(JSON.stringify(await mkClient().deposit(new Uint8Array([1]))));

      out.replay = {};
      reqs.length = 0;
      respond = () => ({ ok: true, status: 200, json: async () => ({ messages: [{ seq: "0002", id: "i", ts: 1, payload: "AQ==" }], has_more: true, oldest_seq: "0001", latest_seq: "0009" }) });
      out.replay.page = JSON.parse(JSON.stringify(await mkClient().replay("0001", 100)));
      out.replay.noCursor = JSON.parse(JSON.stringify(await mkClient().replay(null, 50)));
      respond = () => ({ ok: true, status: 200, json: async () => ({}) });
      out.replay.empty = JSON.parse(JSON.stringify(await mkClient().replay(null, 10)));
      respond = () => ({ ok: false, status: 401, json: async () => ({}) });
      out.replay.auth = JSON.parse(JSON.stringify(await mkClient().replay(null, 10)));
      out.replay.urls = reqs.map((r) => r[0]);
      out.replay.reqs = reqs.map((r) => [r[0], r[1], r[2]]);

      // ---- sync: envelope bytes, queue persistence, dedup ----------------
      const rc = await RoomCrypto.create("X".repeat(43), APP_SALT, "12D3KooWMbx");
      const cipher = await rc.mbxCipher();
      const keys = {
        cursor: nsKey("mbx-cursor:R"),
        queue: nsKey("mbx-queue:R"),
        sent: nsKey("mbx-sent:R"),
        retry: nsKey("mbx-retry:R"),
        ident: nsKey("mbx-ident:R"),
      };
      out.keys = keys;

      // A real CID + block so the 0x01 envelope is byte-checkable. The entry
      // hash is a base58btc dag-cbor CID, exactly as OrbitDB produces.
      const { CID } = await import("multiformats/cid");
      const { base58btc } = await import("multiformats/bases/base58");
      const { sha256 } = await import("multiformats/hashes/sha2");
      const entryBlock = new Uint8Array([0xa1, 0x61, 0x61, 0x01]); // dag-cbor {a:1}
      const entryCid = CID.createV1(0x71, await sha256.digest(entryBlock));
      const entryHash = entryCid.toString(base58btc);
      const imgBlock = new Uint8Array([9, 9, 9]);
      const imgCid = CID.createV1(0x55, await sha256.digest(imgBlock));
      const identBlock = new Uint8Array([1, 2, 3, 4]);
      const identCid = CID.createV1(0x71, await sha256.digest(identBlock));

      const deposits = [];
      const client = {
        async deposit(payload) {
          deposits.push(hex(payload));
          return { ok: true, deduped: false, seq: `s${deposits.length}` };
        },
        async replay() {
          return { ok: false, kind: "net" };
        },
      };
      const log = {
        onAppended: null,
        onImageStored: null,
        imageChunkBytes: null,
        async sealedEntryBytes(h) {
          return h === entryHash ? entryBlock : null;
        },
        async rawBlock() {
          return imgBlock;
        },
        myIdentityBlock() {
          return { cid: identCid, bytes: identBlock };
        },
        async imageDagBlocks() {
          return [{ cid: imgCid, bytes: imgBlock }];
        },
        async hasEntry() {
          return false;
        },
        async decodeSealedEntry() {
          return null;
        },
        async putEntryBlock() {},
        async putRawBlock(cid) {
          rawPuts.push(cid.toString());
        },
        async putIdentityBlock(cid) {
          identPuts.push(cid.toString());
        },
        async ingestEntry() {
          return "rejected";
        },
        async entryMeta() {
          return null;
        },
        async emitUnseen() {},
        async pinImageIfLocal() {
          return true;
        },
      };
      const rawPuts = [];
      const identPuts = [];

      installDetRandom();
      resetRandom(77);
      const sync = new MailboxSync({ log, client, cipher, maxMessageKb: 64, keys, hasIdentity: true });
      out.stateEmpty = JSON.parse(JSON.stringify(sync.state));
      // the identity record is enqueued once, ahead of the first entry
      sync.enqueueEntry(entryHash);
      out.queueAfterEntry = JSON.parse(localStorageStub.getItem(keys.queue));
      await settleUntil(() => deposits.length);
      out.deposits = deposits.slice();
      out.identFlag = localStorageStub.getItem(keys.ident);
      out.sent = JSON.parse(localStorageStub.getItem(keys.sent) ?? "[]");
      // a re-enqueue of a deposited hash is dropped
      sync.enqueueEntry(entryHash);
      out.queueAfterRepeat = JSON.parse(localStorageStub.getItem(keys.queue) ?? "[]");
      // the identity envelope is 0x02 | mbx-seal(cid||block); random IV, so its
      // bytes are pinned only under the deterministic stream above
      out.identEnvelopePrefix = out.deposits.map((d) => d.slice(0, 2));

      // queue-shape fixtures (localStorage JSON: key order is on disk)
      out.qItemShapes = {
        entry: JSON.stringify({ t: "entry", hash: entryHash }),
        img: JSON.stringify({ t: "img", cid: imgCid.toString(), group: "root" }),
        ident: JSON.stringify({ t: "ident" }),
      };

      // an over-cap payload is dropped exactly like a 413
      const small = new MailboxSync({ log, client, cipher, maxMessageKb: 0, keys: { ...keys, queue: nsKey("mbx-queue:S") }, hasIdentity: false });
      small.enqueueEntry(entryHash);
      await settleUntil(() => (localStorageStub.getItem(nsKey("mbx-queue:S")) ?? "").length);
      out.overCapQueue = JSON.parse(localStorageStub.getItem(nsKey("mbx-queue:S")) ?? "[]");

      // replay: prefix classification, CID re-hash, sealed identity blocks
      const toB64 = (u8) => Buffer.from(u8).toString("base64");
      const cat = (...parts) => {
        const n = parts.reduce((a, p) => a + p.length, 0);
        const o = new Uint8Array(n);
        let off = 0;
        for (const p of parts) {
          o.set(p, off);
          off += p.length;
        }
        return o;
      };
      const sync2 = new MailboxSync({ log, client, cipher, maxMessageKb: 64, keys: { ...keys, queue: nsKey("mbx-queue:P") }, hasIdentity: false });
      const process = priv(sync2, "processMessage");
      const cases = {
        "raw-image-block": toB64(cat(new Uint8Array([1]), imgCid.bytes, imgBlock)),
        "wrong-prefix": toB64(cat(new Uint8Array([9]), imgCid.bytes, imgBlock)),
        "too-short": toB64(new Uint8Array([1])),
        "cid-mismatch": toB64(cat(new Uint8Array([1]), imgCid.bytes, new Uint8Array([8, 8, 8]))),
        "sealed-not-ours": toB64(cat(new Uint8Array([2]), new Uint8Array(40))),
        garbage: toB64(cat(new Uint8Array([1]), new Uint8Array([255, 255, 255, 255]))),
      };
      out.processed = {};
      for (const [label, payload] of Object.entries(cases)) {
        rawPuts.length = 0;
        identPuts.length = 0;
        const collected = [];
        await process({ seq: "1", id: "i", ts: 1, payload }, collected);
        out.processed[label] = { rawPuts: rawPuts.slice(), identPuts: identPuts.slice(), collected: collected.length };
      }
      // a real sealed identity record round-trips and is stored
      const sealedIdent = await cipher.seal(cat(identCid.bytes, identBlock));
      rawPuts.length = 0;
      identPuts.length = 0;
      await process({ seq: "1", id: "i", ts: 1, payload: toB64(cat(new Uint8Array([2]), sealedIdent)) }, []);
      out.processed["sealed-identity"] = { rawPuts: rawPuts.slice(), identPuts: identPuts.slice(), collected: 0 };

      restoreRandom();
      localStorageStub.clear();
      return out;
    } finally {
      restoreRandom();
      globalThis.fetch = realFetch;
    }
  });
}

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/board.git