@fraczak/k 8.9.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/DOCS/ARCHITECTURE.md +5 -4
  3. package/DOCS/DICTIONARY.md +2 -2
  4. package/DOCS/FILE_FORMATS.md +11 -9
  5. package/DOCS/KIR_V1.md +5 -1
  6. package/DOCS/KTVM_SPEC.md +907 -0
  7. package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
  8. package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
  9. package/DOCS/PROFILING_AND_TRACING.md +13 -4
  10. package/DOCS/README.md +3 -2
  11. package/DOCS/REPL.md +16 -12
  12. package/README.md +138 -2
  13. package/backend-api.mjs +31 -16
  14. package/backends/llvm/README.md +4 -5
  15. package/backends/llvm/bin/k-llvm-build.mjs +7 -19
  16. package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
  17. package/backends/llvm/bin/k-llvm.mjs +11 -33
  18. package/backends/llvm/src/cli.mjs +2 -12
  19. package/backends/llvm/src/executable.mjs +7 -95
  20. package/backends/llvm/src/kvm2llvm.mjs +1 -7
  21. package/backends/llvm/src/llvm.mjs +4 -113
  22. package/backends/llvm/tests/k-llvm-run.mjs +1 -6
  23. package/backends/llvm/tests/perf-support.mjs +3 -5
  24. package/backends/llvm/tests/test-llvm.mjs +2 -16
  25. package/backends/wasm/README.md +7 -3
  26. package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
  27. package/backends/wasm/bin/k-wasm.mjs +4 -6
  28. package/backends/wasm/src/cli.mjs +8 -24
  29. package/backends/wasm/src/wasm.mjs +60 -57
  30. package/backends/wasm/tests/test-wasm.mjs +41 -2
  31. package/browser/repl-browser.mjs +9 -8
  32. package/browser/shims/buffer.mjs +31 -2
  33. package/browser/shims/child_process.mjs +26 -0
  34. package/browser/shims/fs.mjs +3 -1
  35. package/codecs/runtime/prefix-codec.mjs +67 -1
  36. package/conformance/run.mjs +17 -2
  37. package/harness/adapters/ktvm-llvm.mjs +118 -0
  38. package/harness/adapters/ktvm-wasm.mjs +104 -0
  39. package/harness/adapters/ktvm.mjs +133 -0
  40. package/harness/registry.mjs +9 -0
  41. package/ktvm/ast.mjs +218 -0
  42. package/ktvm/bit-deque.mjs +497 -0
  43. package/ktvm/fixtures/integer-streaming.k +477 -0
  44. package/ktvm/index.mjs +130 -0
  45. package/ktvm/llvm/index.mjs +202 -0
  46. package/ktvm/llvm/lower-c.mjs +1258 -0
  47. package/ktvm/llvm/runtime.h +3542 -0
  48. package/ktvm/llvm/test-llvm.mjs +476 -0
  49. package/ktvm/lower-kir.mjs +2221 -0
  50. package/ktvm/optimize/fuse-kernel.mjs +2111 -0
  51. package/ktvm/optimize/index.mjs +116 -0
  52. package/ktvm/optimize/mwtr.mjs +283 -0
  53. package/ktvm/optimize/simplify-procs.mjs +5250 -0
  54. package/ktvm/optimize/synthesize-tables.mjs +1105 -0
  55. package/ktvm/parser.mjs +1101 -0
  56. package/ktvm/printer.mjs +281 -0
  57. package/ktvm/schema.mjs +1134 -0
  58. package/ktvm/specialize.mjs +538 -0
  59. package/ktvm/test-conformance.mjs +597 -0
  60. package/ktvm/test-ktvm.mjs +1805 -0
  61. package/ktvm/test-optimize.mjs +598 -0
  62. package/ktvm/validator.mjs +1280 -0
  63. package/ktvm/vm.mjs +2225 -0
  64. package/ktvm/wasm/index.mjs +331 -0
  65. package/ktvm/wasm/lower-wasm.mjs +1272 -0
  66. package/ktvm/wasm/runtime.wat +4404 -0
  67. package/ktvm/wasm/test-wasm.mjs +429 -0
  68. package/ktvm/wire.mjs +679 -0
  69. package/package.json +1 -9
  70. package/paper/Makefile +8 -5
  71. package/paper/k-transducer-compiler.pdf +0 -0
  72. package/paper/k-transducer-compiler.tex +658 -0
  73. package/paper/replay-diagnostic.mjs +63 -0
  74. package/repl.mjs +101 -20
  75. package/scripts/build-repl-html.mjs +40 -18
  76. package/scripts/perf-bigint-compare.mjs +12 -16
  77. package/scripts/perf-ieee.mjs +14 -232
  78. package/scripts/perf-int.mjs +16 -274
  79. package/scripts/perf-multiplication.mjs +116 -121
  80. package/scripts/perf-poly.mjs +9 -263
  81. package/scripts/run-tests.mjs +5 -2
  82. package/scripts/test-package.mjs +15 -3
  83. package/tests/README.md +3 -3
  84. package/tests/test-repl-html.mjs +72 -15
  85. package/tests/test-repl.mjs +24 -17
  86. package/DOCS/POLYMORPHIC_IR.md +0 -86
  87. package/access-table.mjs +0 -343
  88. package/pkir.mjs +0 -772
  89. package/tests/test-access-table.mjs +0 -213
  90. package/tests/test-pkir.mjs +0 -530
@@ -0,0 +1,1805 @@
1
+ /**
2
+ * Comprehensive Milestone 1 test suite for standalone `kTVM` (`k/ktvm/`).
3
+ *
4
+ * Covers:
5
+ * 1. Parser, printer, and canonical JSON (`format: "k-tvm"`) round-trip on all
6
+ * 4 worked examples from DOCS/KTVM_SPEC.md §10.
7
+ * 2. Static validator positive & negative checks (SPSC linearity, local DAG
8
+ * acyclicity, mono schema strictness, dual-schema typing, and always-on
9
+ * static table-to-CFG bisimulation verification).
10
+ * 3. Polymorphism & boundary specialization (`reverse.ktvmp` on `list[int[]]`
11
+ * and `list[product{a:int[], b:bits[]}]`, opaque preservation, cache hits,
12
+ * `KTVMSchemaError` on incompatible envelopes, `project`, `guard`, dead
13
+ * `switch` arm pruning, Moore-equivalent `coerce -> splice`).
14
+ * 4. Operational semantics & zero-copy rewrites (O(1) tail-splice in `reverse`,
15
+ * same-scope `MUX -> DEMUX` bundle fusion, strict partiality `drain`/`barrier`/`gate`,
16
+ * `spec` local rollback + upstream-failure abort + tail-splice, `tee` fan-out,
17
+ * `after %tok` bounded-node sequential sibling settlement).
18
+ * 5. Compiled kernels (`_lsb_add` with bisimulation-verified `chunk_table` + O(1)
19
+ * tail splice, `_lsb_trim` with virtual LIFO `BitStack` + `stack_table`).
20
+ * 6. Hardening & quotas (`maxBitDequeBytes`, `maxNodes`, `maxSteps`, malformed
21
+ * `k-wire` envelopes, and 4,096-bit strictly iterative stress tests).
22
+ */
23
+
24
+ import assert from "node:assert/strict";
25
+ import { Value } from "../Value.mjs";
26
+ import { encodeToWire, decodeWire, propertyListToPattern } from "../codecs/runtime/prefix-codec.mjs";
27
+ import {
28
+ KTVM_FORMAT,
29
+ KTVM_VERSION,
30
+ KTVMSyntaxError,
31
+ KTVMValidationError,
32
+ KTVMSchemaError,
33
+ KTVMQuotaError,
34
+ BitDeque,
35
+ BitStack,
36
+ parseModule,
37
+ printModule,
38
+ moduleToJSON,
39
+ moduleFromJSON,
40
+ packInt32Base64,
41
+ compileSchemaExprToPlist,
42
+ mooreKey,
43
+ schemasEquivalent,
44
+ normalizeNodeList,
45
+ nodeListComplete,
46
+ stepNodeListTag,
47
+ stepNodeListLabel,
48
+ wireLanguageKey,
49
+ wireLanguagesEqual,
50
+ productFields,
51
+ validateModule,
52
+ specializeKTVM,
53
+ clearSpecializationCache,
54
+ executeKTVM,
55
+ executeKTVMWire,
56
+ splitWireHeaderOnly,
57
+ splitEnvelopedWire,
58
+ encodePayloadToDeque,
59
+ decodeDequeToValue,
60
+ encodeValueToEnvelopedWire,
61
+ DPDA_RESULT,
62
+ createSchemaCursor,
63
+ cursorNodeList,
64
+ stepSchemaCursor,
65
+ scanBufferAlignedOffset
66
+ } from "./index.mjs";
67
+
68
+ // --- Helpers to build K Values cleanly ---
69
+
70
+ const UNIT = Value.product({});
71
+
72
+ function bitsFromBigIntLSB(n) {
73
+ let v = BigInt(n);
74
+ const digits = [];
75
+ while (v > 0n) {
76
+ digits.push((v & 1n) === 1n ? "1" : "0");
77
+ v >>= 1n;
78
+ }
79
+ let cur = Value.variant("_", UNIT);
80
+ for (let i = digits.length - 1; i >= 0; i--) {
81
+ cur = Value.variant(digits[i], cur);
82
+ }
83
+ return cur;
84
+ }
85
+
86
+ function bitsToBigIntLSB(val) {
87
+ let acc = 0n;
88
+ let shift = 0n;
89
+ let cur = val;
90
+ while (cur.tag !== "_") {
91
+ if (cur.tag === "1") acc |= (1n << shift);
92
+ shift += 1n;
93
+ cur = cur.value;
94
+ }
95
+ return acc;
96
+ }
97
+
98
+ function bitsFromString(str) {
99
+ let cur = Value.variant("_", UNIT);
100
+ for (let i = str.length - 1; i >= 0; i--) {
101
+ cur = Value.variant(str[i], cur);
102
+ }
103
+ return cur;
104
+ }
105
+
106
+ function bitsToString(val) {
107
+ let s = "";
108
+ let cur = val;
109
+ while (cur.tag !== "_") {
110
+ s += cur.tag;
111
+ cur = cur.value;
112
+ }
113
+ return s;
114
+ }
115
+
116
+ function makeIntVal(n) {
117
+ const sign = n < 0 ? "-" : "+";
118
+ const mag = n < 0 ? -n : n;
119
+ return Value.variant(sign, bitsFromBigIntLSB(mag));
120
+ }
121
+
122
+ function intValToNumber(v) {
123
+ const mag = Number(bitsToBigIntLSB(v.value));
124
+ return v.tag === "-" ? -mag : mag;
125
+ }
126
+
127
+ function makeList(items) {
128
+ let cur = Value.variant("nil", UNIT);
129
+ for (let i = items.length - 1; i >= 0; i--) {
130
+ cur = Value.variant("cons", Value.product({ car: items[i], cdr: cur }));
131
+ }
132
+ return cur;
133
+ }
134
+
135
+ function listToArray(v) {
136
+ const out = [];
137
+ let cur = v;
138
+ while (cur.tag === "cons") {
139
+ out.push(cur.value.product.car);
140
+ cur = cur.value.product.cdr;
141
+ }
142
+ assert.equal(cur.tag, "nil");
143
+ return out;
144
+ }
145
+
146
+ // --- Test Harness ---
147
+
148
+ let passed = 0;
149
+ let failed = 0;
150
+
151
+ function test(name, fn) {
152
+ try {
153
+ fn();
154
+ passed++;
155
+ console.log(` PASS ${name}`);
156
+ } catch (err) {
157
+ failed++;
158
+ console.error(` FAIL ${name}`);
159
+ console.error(err);
160
+ }
161
+ }
162
+
163
+ // --- Reusable Worked-Example Modules ---
164
+
165
+ const REVERSE_KTVMP = `
166
+ ktvm 0.1 poly entry @reverse;
167
+
168
+ schema $list[$X] = union {
169
+ cons: product { car: $X, cdr: $list[$X] },
170
+ nil: unit
171
+ };
172
+
173
+ proc @reverse[$X](%in: $list[$X]) -> (%out: $list[$X]) {
174
+ chan %acc_u : unit;
175
+ chan %acc : $list[$X];
176
+ const_unit -> %acc_u;
177
+ wrap |nil %acc_u -> %acc;
178
+ spawn @_reverse[$X](%in, %acc) -> (%out);
179
+ }
180
+
181
+ proc @_reverse[$X](%xs: $list[$X], %acc: $list[$X]) -> (%out: $list[$X]) {
182
+ switch (%xs) {
183
+ case (/nil): {
184
+ chan %u : unit;
185
+ barrier %b;
186
+ match /nil %xs -> %u;
187
+ drain %u : unit -> %b;
188
+ gate %b, %acc -> %out;
189
+ }
190
+ case (/cons): {
191
+ chan %cell : product { car: $X, cdr: $list[$X] };
192
+ chan %car : $X;
193
+ chan %cdr : $list[$X];
194
+ chan %newcell : product { car: $X, cdr: $list[$X] };
195
+ chan %newacc : $list[$X];
196
+ match /cons %xs -> %cell;
197
+ demux %cell : product { car: $X, cdr: $list[$X] } -> (car: %car, cdr: %cdr);
198
+ mux (car: %car, cdr: %acc) -> %newcell : product { car: $X, cdr: $list[$X] };
199
+ wrap |cons %newcell -> %newacc;
200
+ spawn @_reverse[$X](%cdr, %newacc) -> (%out);
201
+ }
202
+ }
203
+ }
204
+ `;
205
+
206
+ // Build a real, exact 2-bit x 2-bit (1 tag per port, 32 entries) chunk_table for `_lsb_add`!
207
+ function buildLsbAdd2x2Entries() {
208
+ // Tag codes: 0 -> 0b00 (0), 1 -> 0b01 (1), _ -> 0b10 (2), 0b11 (3) = invalid
209
+ // Exits: 0 = exit_zero_done, 1 = exit_carry_done, 2 = exit_splice_y, 3 = exit_splice_x
210
+ const rows = [];
211
+ for (let c = 0; c < 2; c++) {
212
+ for (let tx = 0; tx < 4; tx++) {
213
+ for (let ty = 0; ty < 4; ty++) {
214
+ const idx = (c << 4) | (tx << 2) | ty;
215
+ if (tx === 3 || ty === 3) {
216
+ rows.push(`${idx} => { kind: FAIL };`);
217
+ continue;
218
+ }
219
+ if (tx === 2 && ty === 2) {
220
+ rows.push(`${idx} => { kind: EXIT, exit: ${c}, shift: [2, 2], emit_word: [0], emit_len: [0] };`);
221
+ } else if (tx === 2) {
222
+ if (c === 0) {
223
+ rows.push(`${idx} => { kind: EXIT, exit: 2, shift: [2, 0], emit_word: [0], emit_len: [0] };`);
224
+ } else {
225
+ const sum = ty + 1;
226
+ const outTag = sum & 1; // 0->0b00, 1->0b01
227
+ const nextC = sum >> 1;
228
+ rows.push(`${idx} => { kind: CONT, next_q: ${nextC}, shift: [0, 2], emit_word: [${outTag}], emit_len: [2] };`);
229
+ }
230
+ } else if (ty === 2) {
231
+ if (c === 0) {
232
+ rows.push(`${idx} => { kind: EXIT, exit: 3, shift: [0, 2], emit_word: [0], emit_len: [0] };`);
233
+ } else {
234
+ const sum = tx + 1;
235
+ const outTag = sum & 1;
236
+ const nextC = sum >> 1;
237
+ rows.push(`${idx} => { kind: CONT, next_q: ${nextC}, shift: [2, 0], emit_word: [${outTag}], emit_len: [2] };`);
238
+ }
239
+ } else {
240
+ const sum = tx + ty + c;
241
+ const outTag = sum & 1;
242
+ const nextC = sum >> 1;
243
+ rows.push(`${idx} => { kind: CONT, next_q: ${nextC}, shift: [2, 2], emit_word: [${outTag}], emit_len: [2] };`);
244
+ }
245
+ }
246
+ }
247
+ }
248
+ return rows.join("\n ");
249
+ }
250
+
251
+ function makeLsbAddModule(tableEntriesStr) {
252
+ return `
253
+ ktvm 0.1 mono entry @lsb_add;
254
+
255
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
256
+
257
+ proc @lsb_add(%x: $bits, %y: $bits) -> (%out: $bits) total {
258
+ exec @_lsb_add_kernel(%x, %y) -> (%out);
259
+ }
260
+
261
+ kernel @_lsb_add_kernel(%x: $bits, %y: $bits) -> (%out: $bits) total tmc {
262
+ reg c : enum(2) = 0;
263
+
264
+ entry:
265
+ yield %out, 64;
266
+ table_step &tab_lsb_add, c, (%x, %y), (%out) -> exits {
267
+ short: slow_step,
268
+ 0: exit_zero_done,
269
+ 1: exit_carry_done,
270
+ 2: exit_splice_y,
271
+ 3: exit_splice_x,
272
+ fail: err
273
+ };
274
+
275
+ slow_step:
276
+ %tx = peek_bits %x, @0, 2 else err;
277
+ %ty = peek_bits %y, @0, 2 else err;
278
+ switch_bits %tx {
279
+ case 0b10: goto x_end;
280
+ case 0b00: goto x_0;
281
+ case 0b01: goto x_1;
282
+ default: goto err;
283
+ }
284
+
285
+ x_end:
286
+ switch_bits %ty {
287
+ case 0b10: goto both_end;
288
+ case 0b00: goto x_end_y_nz;
289
+ case 0b01: goto x_end_y_nz;
290
+ default: goto err;
291
+ }
292
+
293
+ both_end:
294
+ shift_tag %x, 2 -> unit;
295
+ shift_tag %y, 2 -> unit;
296
+ drain_guard %x : unit;
297
+ drain_guard %y : unit;
298
+ switch_reg c {
299
+ case 0: goto exit_zero_done;
300
+ case 1: goto exit_carry_done;
301
+ }
302
+
303
+ x_end_y_nz:
304
+ switch_reg c {
305
+ case 0: goto x_end_splice_y;
306
+ case 1: goto x_end_prop_carry;
307
+ }
308
+
309
+ x_end_splice_y:
310
+ shift_tag %x, 2 -> unit;
311
+ drain_guard %x : unit;
312
+ goto exit_splice_y;
313
+
314
+ x_end_prop_carry:
315
+ shift_tag %y, 2 -> $bits;
316
+ switch_bits %ty {
317
+ case 0b00: goto emit_1_c0;
318
+ case 0b01: goto emit_0_c1;
319
+ default: goto err;
320
+ }
321
+
322
+ x_0:
323
+ switch_bits %ty {
324
+ case 0b10: goto y_end_x0;
325
+ case 0b00: goto add_00;
326
+ case 0b01: goto add_01;
327
+ default: goto err;
328
+ }
329
+
330
+ x_1:
331
+ switch_bits %ty {
332
+ case 0b10: goto y_end_x1;
333
+ case 0b00: goto add_01;
334
+ case 0b01: goto add_11;
335
+ default: goto err;
336
+ }
337
+
338
+ y_end_x0:
339
+ switch_reg c {
340
+ case 0: goto y_end_splice_x;
341
+ case 1: goto y_end_x0_c1;
342
+ }
343
+
344
+ y_end_x1:
345
+ switch_reg c {
346
+ case 0: goto y_end_splice_x;
347
+ case 1: goto y_end_x1_c1;
348
+ }
349
+
350
+ y_end_splice_x:
351
+ shift_tag %y, 2 -> unit;
352
+ drain_guard %y : unit;
353
+ goto exit_splice_x;
354
+
355
+ y_end_x0_c1:
356
+ shift_tag %x, 2 -> $bits;
357
+ goto emit_1_c0;
358
+
359
+ y_end_x1_c1:
360
+ shift_tag %x, 2 -> $bits;
361
+ goto emit_0_c1;
362
+
363
+ add_00:
364
+ shift_tag %x, 2 -> $bits;
365
+ shift_tag %y, 2 -> $bits;
366
+ switch_reg c {
367
+ case 0: goto emit_0_c0;
368
+ case 1: goto emit_1_c0;
369
+ }
370
+
371
+ add_01:
372
+ shift_tag %x, 2 -> $bits;
373
+ shift_tag %y, 2 -> $bits;
374
+ switch_reg c {
375
+ case 0: goto emit_1_c0;
376
+ case 1: goto emit_0_c1;
377
+ }
378
+
379
+ add_11:
380
+ shift_tag %x, 2 -> $bits;
381
+ shift_tag %y, 2 -> $bits;
382
+ switch_reg c {
383
+ case 0: goto emit_0_c1;
384
+ case 1: goto emit_1_c1;
385
+ }
386
+
387
+ emit_0_c0:
388
+ push_bits %out, 0b00, 2;
389
+ set_reg c, 0;
390
+ goto entry;
391
+
392
+ emit_1_c0:
393
+ push_bits %out, 0b01, 2;
394
+ set_reg c, 0;
395
+ goto entry;
396
+
397
+ emit_0_c1:
398
+ push_bits %out, 0b00, 2;
399
+ set_reg c, 1;
400
+ goto entry;
401
+
402
+ emit_1_c1:
403
+ push_bits %out, 0b01, 2;
404
+ set_reg c, 1;
405
+ goto entry;
406
+
407
+ exit_zero_done:
408
+ push_bits %out, 0b10, 2;
409
+ close %out;
410
+ retire;
411
+
412
+ exit_carry_done:
413
+ push_bits %out, 0b01, 2;
414
+ push_bits %out, 0b10, 2;
415
+ close %out;
416
+ retire;
417
+
418
+ exit_splice_y:
419
+ splice %y -> %out;
420
+ retire;
421
+
422
+ exit_splice_x:
423
+ splice %x -> %out;
424
+ retire;
425
+
426
+ err:
427
+ fail;
428
+ }
429
+
430
+ table &tab_lsb_add chunk_table {
431
+ states: 2;
432
+ inputs: [
433
+ { port: 0, raw_bits: 2, eff_bits: 2, compress: none },
434
+ { port: 1, raw_bits: 2, eff_bits: 2, compress: none }
435
+ ];
436
+ outputs: [ { port: 0, mode: push, max_emit_bits: 2 } ];
437
+ verified_against: @_lsb_add_kernel;
438
+ mwtr: { rho: 4.0, bytes: 128, budget_class: "L1" };
439
+ entries {
440
+ ${tableEntriesStr}
441
+ }
442
+ }
443
+ `;
444
+ }
445
+
446
+ // Online virtual-stack `_lsb_trim` kernel with real `stack_table` (W_s = 2, W_k = 1, depth_only)
447
+ function buildLsbTrimStackTableEntries() {
448
+ // mode: 0 = scan, 1 = flush
449
+ // sBits (2b): 0=0b00 ('0'), 1=0b01 ('1'), 2=0b10 ('_'), 3=0b11 (invalid)
450
+ // depth_only (W_k = 1, stride = 2): d=0 (empty), d=1 (non-empty)
451
+ const rows = [];
452
+ for (let mode = 0; mode < 2; mode++) {
453
+ for (let sBits = 0; sBits < 4; sBits++) {
454
+ for (let d = 0; d < 2; d++) {
455
+ const idx = (((mode << 2) | sBits) * 2) + d;
456
+ if (mode === 1) {
457
+ // flush deferred '0's from stack before reading next input!
458
+ if (d === 1) {
459
+ rows.push(`${idx} => { kind: CONT, next_q: 1, shift_stream: 0, pop_stack: 1, push_stack_word: 0, push_stack_len: 0, emit_word: 0, emit_len: 2 };`);
460
+ } else {
461
+ // stack empty -> emit deferred '1', back to scan!
462
+ rows.push(`${idx} => { kind: CONT, next_q: 0, shift_stream: 0, pop_stack: 0, push_stack_word: 0, push_stack_len: 0, emit_word: 1, emit_len: 2 };`);
463
+ }
464
+ continue;
465
+ }
466
+ // mode === 0 (scan)
467
+ if (sBits === 3) {
468
+ rows.push(`${idx} => { kind: FAIL };`);
469
+ } else if (sBits === 2) {
470
+ // '_': exit to scan_eof (clears stack and emits '_')
471
+ rows.push(`${idx} => { kind: EXIT, exit: 0, shift_stream: 2, pop_stack: 0, push_stack_word: 0, push_stack_len: 0, emit_word: 0, emit_len: 0 };`);
472
+ } else if (sBits === 0) {
473
+ // '0': defer onto stack z
474
+ rows.push(`${idx} => { kind: CONT, next_q: 0, shift_stream: 2, pop_stack: 0, push_stack_word: 0, push_stack_len: 1, emit_word: 0, emit_len: 0 };`);
475
+ } else {
476
+ // '1': if stack empty emit '1' immediately; else pop 1 zero, emit '0', switch to flush!
477
+ if (d === 0) {
478
+ rows.push(`${idx} => { kind: CONT, next_q: 0, shift_stream: 2, pop_stack: 0, push_stack_word: 0, push_stack_len: 0, emit_word: 1, emit_len: 2 };`);
479
+ } else {
480
+ rows.push(`${idx} => { kind: CONT, next_q: 1, shift_stream: 2, pop_stack: 1, push_stack_word: 0, push_stack_len: 0, emit_word: 0, emit_len: 2 };`);
481
+ }
482
+ }
483
+ }
484
+ }
485
+ }
486
+ return rows.join("\n ");
487
+ }
488
+
489
+ const LSB_TRIM_KTVM = `
490
+ ktvm 0.1 mono entry @lsb_trim;
491
+
492
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
493
+
494
+ proc @lsb_trim(%in: $bits) -> (%out: $bits) total {
495
+ exec @_lsb_trim_kernel(%in) -> (%out);
496
+ }
497
+
498
+ kernel @_lsb_trim_kernel(%in: $bits) -> (%out: $bits) total tmc {
499
+ reg mode : enum(2) = 0;
500
+ stack z : bits;
501
+
502
+ entry:
503
+ yield %out, 64;
504
+ stack_table_step &tab_lsb_trim, mode, %in, z, %out -> exits {
505
+ short: slow_step,
506
+ 0: exit_eof_after_shift,
507
+ fail: err
508
+ };
509
+
510
+ slow_step:
511
+ switch_reg mode {
512
+ case 0: goto scan;
513
+ case 1: goto flush;
514
+ }
515
+
516
+ scan:
517
+ %t = peek_bits %in, @0, 2 else err;
518
+ switch_bits %t {
519
+ case 0b10: goto scan_eof;
520
+ case 0b00: goto scan_zero;
521
+ case 0b01: goto scan_one;
522
+ default: goto err;
523
+ }
524
+
525
+ scan_eof:
526
+ shift_tag %in, 2 -> unit;
527
+ goto exit_eof_after_shift;
528
+
529
+ exit_eof_after_shift:
530
+ drain_guard %in : unit;
531
+ stack_clear z;
532
+ push_bits %out, 0b10, 2;
533
+ close %out;
534
+ retire;
535
+
536
+ scan_zero:
537
+ shift_tag %in, 2 -> $bits;
538
+ stack_push z, 0b0, 1;
539
+ goto entry;
540
+
541
+ scan_one:
542
+ shift_tag %in, 2 -> $bits;
543
+ %_top = stack_pop z, 1 else emit_one_scan;
544
+ push_bits %out, 0b00, 2;
545
+ set_reg mode, 1;
546
+ goto entry;
547
+
548
+ flush:
549
+ %_top = stack_pop z, 1 else emit_one_scan;
550
+ push_bits %out, 0b00, 2;
551
+ goto entry;
552
+
553
+ emit_one_scan:
554
+ push_bits %out, 0b01, 2;
555
+ set_reg mode, 0;
556
+ goto entry;
557
+
558
+ err:
559
+ fail;
560
+ }
561
+
562
+ table &tab_lsb_trim stack_table {
563
+ states: 2;
564
+ stream_bits: 2;
565
+ stack_bits: 1;
566
+ stack_encoding: depth_only;
567
+ output_mode: push;
568
+ mwtr: { rho: 2.0, bytes: 128, budget_class: "L1" };
569
+ entries {
570
+ ${buildLsbTrimStackTableEntries()}
571
+ }
572
+ }
573
+ `;
574
+
575
+ // ============================================================================
576
+ console.log("\n=== 1. Parser, Printer, JSON Artifact & BitDeque/BitStack ADT ===");
577
+ // ============================================================================
578
+
579
+ test("BitDeque push/unshift/peek/shift/wrap-around/adopt across 32-bit boundaries", () => {
580
+ const dq = new BitDeque(1, { initialWords: 2 }); // 64-bit initial ring
581
+ dq.pushBits(0b10110, 5);
582
+ dq.unshiftBits(0b110, 3);
583
+ assert.equal(dq.toBitString(), "11010110");
584
+ assert.equal(dq.peekBits(8), 0b11010110);
585
+ assert.equal(dq.peekBitsAt(3, 5), 0b10110);
586
+
587
+ // Force ring wrap & growth past 64 bits
588
+ for (let i = 0; i < 20; i++) {
589
+ dq.pushBits(0xdeadbeef >>> 0, 32);
590
+ assert.equal(dq.shiftBits(8), i === 0 ? 0b11010110 : 0xef);
591
+ // keep shifting to exercise wrap-around
592
+ if (i === 0) {
593
+ assert.equal(dq.shiftBits(24), 0xdeadbe);
594
+ } else {
595
+ assert.equal(dq.shiftBits(24), 0xdeadbe);
596
+ }
597
+ }
598
+ assert.equal(dq.shiftBits(8), 0xef);
599
+ assert.equal(dq.length, 0);
600
+
601
+ // Test unshiftFromDeque + adoptBufferFrom
602
+ const a = new BitDeque(2);
603
+ const b = new BitDeque(3);
604
+ a.pushBits(0b101011, 6);
605
+ b.pushBits(0b11001, 5);
606
+ b.unshiftFromDeque(a);
607
+ assert.equal(a.length, 0);
608
+ assert.equal(b.toBitString(), "10101111001");
609
+ a.adoptBufferFrom(b);
610
+ assert.equal(b.length, 0);
611
+ assert.equal(a.toBitString(), "10101111001");
612
+ a.release();
613
+ b.release();
614
+ dq.release();
615
+ });
616
+
617
+ test("BitStack push/peekTop/pop/grow/clear LIFO fidelity", () => {
618
+ const st = new BitStack(null, 1);
619
+ st.push(0b10, 2);
620
+ assert.equal(st.peekTop(2), 0b10);
621
+ st.push(1, 1);
622
+ assert.equal(st.pop(1), 1);
623
+ assert.equal(st.pop(2), 0b10);
624
+ assert.equal(st.length, 0);
625
+ // Push > 200 bits to force growth
626
+ for (let i = 0; i < 200; i++) st.push(i & 1, 1);
627
+ for (let i = 199; i >= 0; i--) assert.equal(st.pop(1), i & 1);
628
+ st.release();
629
+ });
630
+
631
+ test("Round-trip parse -> print -> re-parse -> JSON export/import on all worked examples", () => {
632
+ const sources = [
633
+ REVERSE_KTVMP,
634
+ makeLsbAddModule(buildLsbAdd2x2Entries()),
635
+ LSB_TRIM_KTVM,
636
+ `
637
+ ktvm 0.1 mono entry @branch_demo;
638
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
639
+ proc @id(%x: $bits) -> (%o: $bits) total { splice %x -> %o; }
640
+ proc @branch_demo(%x: $bits) -> (%o: $bits) branching {
641
+ chan %x0 : $bits; chan %x1 : $bits;
642
+ chan %a : $bits; chan %b : $bits;
643
+ barrier %bar;
644
+ tee %x -> (%x0, %x1);
645
+ spawn @id(%x0) -> (%a) as %t0;
646
+ spawn @id(%x1) -> (%b) after %t0;
647
+ drain %a : $bits -> %bar;
648
+ gate %bar, %b -> %o;
649
+ }
650
+ `
651
+ ];
652
+ for (const src of sources) {
653
+ const ast1 = parseModule(src);
654
+ const printed1 = printModule(ast1);
655
+ const ast2 = parseModule(printed1);
656
+ const printed2 = printModule(ast2);
657
+ assert.equal(printed1, printed2, "printer must be idempotent");
658
+
659
+ const json = moduleToJSON(ast1);
660
+ assert.equal(json.format, KTVM_FORMAT);
661
+ assert.equal(json.formatVersion, KTVM_VERSION);
662
+ const hydrated = moduleFromJSON(JSON.parse(JSON.stringify(json)));
663
+ assert.equal(printModule(hydrated), printed1, "JSON artifact round-trip must be lossless");
664
+ }
665
+ });
666
+
667
+ test("Parser rejects malformed syntax with KTVMSyntaxError", () => {
668
+ assert.throws(() => parseModule("ktvm 0.1 bogus;"), KTVMSyntaxError);
669
+ assert.throws(() => parseModule("ktvm 0.1 mono; proc bad() -> () {}"), KTVMSyntaxError);
670
+ });
671
+
672
+ // ============================================================================
673
+ console.log("\n=== 2. Static Validator & Always-On Table-to-CFG Bisimulation ===");
674
+ // ============================================================================
675
+
676
+ test("Validator accepts valid poly and mono modules (including verified _lsb_add chunk_table)", () => {
677
+ assert.equal(validateModule(parseModule(REVERSE_KTVMP)).ok, true);
678
+ assert.equal(validateModule(parseModule(makeLsbAddModule(buildLsbAdd2x2Entries()))).ok, true);
679
+ assert.equal(validateModule(parseModule(LSB_TRIM_KTVM)).ok, true);
680
+ });
681
+
682
+ test("Validator catches SPSC linearity violations (double-consume, unproduced, unused)", () => {
683
+ assert.throws(
684
+ () => validateModule(parseModule(`
685
+ ktvm 0.1 mono entry @bad;
686
+ schema $b = union { _: unit };
687
+ proc @bad(%x: $b) -> (%o: $b) {
688
+ chan %d : $b;
689
+ splice %x -> %o;
690
+ splice %x -> %d;
691
+ drain %d : $b;
692
+ }
693
+ `)),
694
+ KTVMValidationError
695
+ );
696
+ assert.throws(
697
+ () => validateModule(parseModule(`
698
+ ktvm 0.1 mono entry @bad;
699
+ schema $b = union { _: unit };
700
+ proc @bad(%x: $b) -> (%o: $b) {
701
+ drain %x : $b;
702
+ }
703
+ `)),
704
+ KTVMValidationError
705
+ );
706
+ });
707
+
708
+ test("Validator catches local channel DAG cycle", () => {
709
+ assert.throws(
710
+ () => validateModule(parseModule(`
711
+ ktvm 0.1 mono entry @cyc;
712
+ schema $b = union { _: unit };
713
+ proc @cyc(%x: $b) -> (%o: $b) {
714
+ chan %a : $b;
715
+ chan %b : $b;
716
+ splice %a -> %b;
717
+ splice %b -> %a;
718
+ splice %x -> %o;
719
+ }
720
+ `)),
721
+ KTVMValidationError
722
+ );
723
+ });
724
+
725
+ test("Validator rejects open/any schemas and polymorphic ops in mono modules", () => {
726
+ assert.throws(
727
+ () => validateModule(parseModule(`
728
+ ktvm 0.1 mono entry @p;
729
+ schema $open = open_product { a: unit ... };
730
+ proc @p(%x: $open) -> (%o: $open) { splice %x -> %o; }
731
+ `)),
732
+ KTVMValidationError
733
+ );
734
+ });
735
+
736
+ test("Validator rejects schema mismatch in mono splice", () => {
737
+ assert.throws(
738
+ () => validateModule(parseModule(`
739
+ ktvm 0.1 mono entry @bad;
740
+ schema $a = union { x: unit, y: unit };
741
+ schema $b = union { x: unit, z: unit };
742
+ proc @bad(%in: $a) -> (%out: $b) { splice %in -> %out; }
743
+ `)),
744
+ KTVMValidationError
745
+ );
746
+ });
747
+
748
+ test("Static table-to-CFG bisimulation catches an intentionally corrupted chunk_table entry!", () => {
749
+ const goodEntries = buildLsbAdd2x2Entries();
750
+ // Corrupt entry 0 (c=0, tx=0, ty=0): change emit_word from [0] to [1]!
751
+ const badEntries = goodEntries.replace(
752
+ "0 => { kind: CONT, next_q: 0, shift: [2, 2], emit_word: [0], emit_len: [2] };",
753
+ "0 => { kind: CONT, next_q: 0, shift: [2, 2], emit_word: [1], emit_len: [2] };"
754
+ );
755
+ const badMod = parseModule(makeLsbAddModule(badEntries));
756
+ assert.throws(
757
+ () => validateModule(badMod, { verifyTables: true }),
758
+ (err) => err instanceof KTVMValidationError && /bisimulation/i.test(err.message)
759
+ );
760
+ // Opt-out flag skips bisimulation check
761
+ assert.equal(validateModule(badMod, { verifyTables: false }).ok, true);
762
+ });
763
+
764
+ // ============================================================================
765
+ console.log("\n=== 3. Polymorphism, Boundary Specialization & Opaque Payloads ===");
766
+ // ============================================================================
767
+
768
+ test("Specialize reverse.ktvmp for list[int[]], execute enveloped k-wire, verify bit-exactness & O(1) tail-splice", () => {
769
+ clearSpecializationCache();
770
+ const listIntSchemaMod = parseModule(`
771
+ ktvm 0.1 mono;
772
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
773
+ schema $int = union { "+": $bits, "-": $bits };
774
+ schema $list_int = union { cons: product { car: $int, cdr: $list_int }, nil: unit };
775
+ `);
776
+ const listIntPlist = compileSchemaExprToPlist(
777
+ { kind: "ref", name: "$list_int", args: [] },
778
+ listIntSchemaMod.schemas
779
+ );
780
+
781
+ const inputNums = [1, -2, 3, 0, 42, -1023, 7, 15, -99, 256];
782
+ const inputVal = makeList(inputNums.map(makeIntVal));
783
+ const inWire = encodeToWire(inputVal, listIntPlist);
784
+
785
+ const r1 = executeKTVMWire(REVERSE_KTVMP, inWire);
786
+ assert.equal(r1.status, "OK");
787
+ assert.equal(r1.specialized.cached, false);
788
+ const outNums = listToArray(r1.value).map(intValToNumber);
789
+ assert.deepEqual(outNums, [...inputNums].reverse());
790
+
791
+ // Verify output wire decodes identically via K's canonical `decodeWire`!
792
+ const decodedByK = decodeWire(r1.wire, { eager: true }).value;
793
+ assert.deepEqual(listToArray(decodedByK).map(intValToNumber), [...inputNums].reverse());
794
+
795
+ // Second call hits specialization cache!
796
+ const r2 = executeKTVMWire(REVERSE_KTVMP, inWire);
797
+ assert.equal(r2.status, "OK");
798
+ assert.equal(r2.specialized.cached, true);
799
+ assert.deepEqual(r2.wire, r1.wire);
800
+
801
+ // Verify O(1) tail-splice behavior: total spliceBitsCopied scales O(total input bits), NOT O(n^2)!
802
+ const longNums = Array.from({ length: 80 }, (_, i) => i + 1);
803
+ const longWire = encodeToWire(makeList(longNums.map(makeIntVal)), listIntPlist);
804
+ const rLong = executeKTVMWire(REVERSE_KTVMP, longWire);
805
+ assert.equal(rLong.status, "OK");
806
+ assert.deepEqual(listToArray(rLong.value).map(intValToNumber), [...longNums].reverse());
807
+ // For 80 ints (~16 bits each -> ~1,400 bits total), O(n^2) would copy > 50,000 bits;
808
+ // O(1) tail-splice copies ONLY the prepended car + 1-bit cons tag (~1,600 bits)!
809
+ assert.ok(
810
+ rLong.telemetry.spliceBitsCopied < 4000,
811
+ `Expected O(n) splice bits copied, got ${rLong.telemetry.spliceBitsCopied}`
812
+ );
813
+ });
814
+
815
+ test("Specialize reverse.ktvmp on list[product { a: int[], b: bits[] }] preserving opaque product payload", () => {
816
+ const schemaMod = parseModule(`
817
+ ktvm 0.1 mono;
818
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
819
+ schema $int = union { "+": $bits, "-": $bits };
820
+ schema $pair = product { a: $int, b: $bits };
821
+ schema $list_pair = union { cons: product { car: $pair, cdr: $list_pair }, nil: unit };
822
+ `);
823
+ const listPairPlist = compileSchemaExprToPlist(
824
+ { kind: "ref", name: "$list_pair", args: [] },
825
+ schemaMod.schemas
826
+ );
827
+
828
+ const items = [
829
+ Value.product({ a: makeIntVal(5), b: bitsFromString("101") }),
830
+ Value.product({ a: makeIntVal(-12), b: bitsFromString("00110") }),
831
+ Value.product({ a: makeIntVal(0), b: bitsFromString("") })
832
+ ];
833
+ const inWire = encodeToWire(makeList(items), listPairPlist);
834
+
835
+ const res = executeKTVMWire(REVERSE_KTVMP, inWire);
836
+ assert.equal(res.status, "OK");
837
+ // Check access profile recognized `$X` as an opaque product!
838
+ const profiles = Object.values(res.specialized.accessProfiles);
839
+ assert.ok(profiles.some((p) => p.opaqueParams.includes("$X")));
840
+
841
+ const outArr = listToArray(res.value);
842
+ assert.equal(outArr.length, 3);
843
+ assert.equal(intValToNumber(outArr[0].product.a), 0);
844
+ assert.equal(bitsToString(outArr[0].product.b), "");
845
+ assert.equal(intValToNumber(outArr[1].product.a), -12);
846
+ assert.equal(bitsToString(outArr[1].product.b), "00110");
847
+ assert.equal(intValToNumber(outArr[2].product.a), 5);
848
+ assert.equal(bitsToString(outArr[2].product.b), "101");
849
+ });
850
+
851
+ test("Boundary specialization rejects incompatible input envelope with KTVMSchemaError", () => {
852
+ const bitsSchemaMod = parseModule(`
853
+ ktvm 0.1 mono;
854
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
855
+ `);
856
+ const bitsPlist = compileSchemaExprToPlist(
857
+ { kind: "ref", name: "$bits", args: [] },
858
+ bitsSchemaMod.schemas
859
+ );
860
+ const badWire = encodeToWire(bitsFromString("101"), bitsPlist);
861
+ assert.throws(() => executeKTVMWire(REVERSE_KTVMP, badWire), KTVMSchemaError);
862
+ });
863
+
864
+ test("Polymorphic project .f on open_product + guard ?$P + dead switch arm pruning + Moore coerce collapse", () => {
865
+ const polyMod = `
866
+ ktvm 0.1 poly entry @pick_a;
867
+
868
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
869
+ schema $bits_alias = union { 0: $bits_alias, 1: $bits_alias, _: unit };
870
+ schema $has_a = open_product { a: $bits ... };
871
+
872
+ proc @pick_a(%in: $has_a) -> (%out: $bits_alias) {
873
+ chan %a1 : $bits;
874
+ chan %a2 : $bits;
875
+ project .a %in : $has_a -> %a1 : $bits;
876
+ guard ?$bits %a1 -> %a2;
877
+ coerce %a2 : $bits -> %out : $bits_alias;
878
+ }
879
+ `;
880
+
881
+ const recSchemaMod = parseModule(`
882
+ ktvm 0.1 mono;
883
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
884
+ schema $rec = product { a: $bits, b: $bits, c: unit };
885
+ `);
886
+ const recPlist = compileSchemaExprToPlist({ kind: "ref", name: "$rec", args: [] }, recSchemaMod.schemas);
887
+ const val = Value.product({
888
+ a: bitsFromString("1101"),
889
+ b: bitsFromString("000"),
890
+ c: UNIT
891
+ });
892
+ const wire = encodeToWire(val, recPlist);
893
+
894
+ const res = executeKTVMWire(polyMod, wire);
895
+ assert.equal(res.status, "OK");
896
+ assert.equal(bitsToString(res.value), "1101");
897
+
898
+ // Confirm Moore-equivalent `coerce` collapsed into `splice` and `project` lowered to `demux`+`drain`+`gate`!
899
+ const specText = printModule(res.specialized.module);
900
+ assert.ok(!specText.includes("project"), "project must be eliminated in mono");
901
+ assert.ok(!specText.includes("guard"), "guard must be eliminated in mono");
902
+ assert.ok(!specText.includes("coerce"), "Moore-equivalent coerce must collapse to splice");
903
+ assert.ok(specText.includes("demux") && specText.includes("drain") && specText.includes("gate"));
904
+ });
905
+
906
+ // ============================================================================
907
+ console.log("\n=== 4. Operational Semantics, Rewrites, Partiality, Spec & After ===");
908
+ // ============================================================================
909
+
910
+ test("Same-scope MUX -> wrap |cons -> match /cons -> DEMUX performs O(1) zero-copy bundle fusion", () => {
911
+ const fusionMod = `
912
+ ktvm 0.1 mono entry @swap_via_cons;
913
+
914
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
915
+ schema $pair = product { a: $bits, b: $bits };
916
+ schema $box = union { box: $pair, empty: unit };
917
+
918
+ proc @swap_via_cons(%x: $bits, %y: $bits) -> (%out: $pair) {
919
+ chan %p1 : $pair;
920
+ chan %bx : $box;
921
+ chan %p2 : $pair;
922
+ chan %a : $bits;
923
+ chan %b : $bits;
924
+
925
+ mux (a: %x, b: %y) -> %p1 : $pair;
926
+ wrap |box %p1 -> %bx;
927
+ match /box %bx -> %p2;
928
+ demux %p2 : $pair -> (a: %a, b: %b);
929
+ mux (a: %b, b: %a) -> %out : $pair;
930
+ }
931
+ `;
932
+
933
+ const res = executeKTVM(fusionMod, [bitsFromString("101100"), bitsFromString("01")]);
934
+ assert.equal(res.status, "OK");
935
+ assert.equal(bitsToString(res.value.product.a), "01");
936
+ assert.equal(bitsToString(res.value.product.b), "101100");
937
+ assert.ok(
938
+ res.telemetry.muxDemuxFusions >= 1,
939
+ `Expected MUX->DEMUX fusion, got ${res.telemetry.muxDemuxFusions}`
940
+ );
941
+ });
942
+
943
+ test("Strict K partiality: failing discarded sibling fails gated output via drain/barrier/gate", () => {
944
+ const partialMod = `
945
+ ktvm 0.1 mono entry @keep_second_strict;
946
+
947
+ schema $ab = union { a: unit, b: unit };
948
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
949
+
950
+ proc @keep_second_strict(%flag: $ab, %val: $bits) -> (%out: $bits) {
951
+ chan %u : unit;
952
+ barrier %bar;
953
+ match /a %flag -> %u;
954
+ drain %u : unit -> %bar;
955
+ gate %bar, %val -> %out;
956
+ }
957
+ `;
958
+
959
+ const ok = executeKTVM(partialMod, [Value.variant("a", UNIT), bitsFromString("101")]);
960
+ assert.equal(ok.status, "OK");
961
+ assert.equal(bitsToString(ok.value), "101");
962
+
963
+ // When %flag is /b, match /a fails -> drain fails %bar -> gate fails %out!
964
+ const fail = executeKTVM(partialMod, [Value.variant("b", UNIT), bitsFromString("101")]);
965
+ assert.equal(fail.status, "FAILED");
966
+ });
967
+
968
+ test("spec: (a) local mismatch rolls back bit-exact replay; (b) upstream failure aborts skipping branch 1", () => {
969
+ const specMod = `
970
+ ktvm 0.1 mono entry @try_ab;
971
+
972
+ schema $tag = union { a: $bits, b: $bits, c: $bits };
973
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
974
+
975
+ proc @try_ab(%in: $tag) -> (%out: $bits) {
976
+ spec (%in) -> (%out) {
977
+ branch 0: {
978
+ // Only succeeds if /a AND leading bit is 1!
979
+ chan %p : $bits;
980
+ chan %rest : $bits;
981
+ match /a %in -> %p;
982
+ match /1 %p -> %rest;
983
+ wrap |0 %rest -> %out;
984
+ }
985
+ branch 1: {
986
+ // Fallback: if /a with leading bit 0, match it (proving exact rollback of BOTH /a AND bit 0!)
987
+ chan %p : $bits;
988
+ chan %rest : $bits;
989
+ match /a %in -> %p;
990
+ match /0 %p -> %rest;
991
+ wrap |1 %rest -> %out;
992
+ }
993
+ branch 2: {
994
+ // Last branch (tail-spliced!): match /b
995
+ match /b %in -> %out;
996
+ }
997
+ }
998
+ }
999
+
1000
+ // Pipeline testing Rule 1 (Upstream Failure Abort): upstream match /a fails on /c,
1001
+ // so downstream spec MUST abort immediately WITHOUT running branch 1!
1002
+ proc @upstream_abort_test(%raw: $tag) -> (%out: $bits) {
1003
+ chan %mid : $bits;
1004
+ match /a %raw -> %mid;
1005
+ spec (%mid) -> (%out) {
1006
+ branch 0: {
1007
+ match /1 %mid -> %out;
1008
+ }
1009
+ branch 1: {
1010
+ // Would succeed if invoked on a non-failed input, or fail with a rollback counter
1011
+ splice %mid -> %out;
1012
+ }
1013
+ }
1014
+ }
1015
+ `;
1016
+
1017
+ // Branch 0 commits directly
1018
+ const r0 = executeKTVM(specMod, [Value.variant("a", bitsFromString("101"))]);
1019
+ assert.equal(r0.status, "OK");
1020
+ assert.equal(bitsToString(r0.value), "001");
1021
+ assert.equal(r0.telemetry.specRollbacks, 0);
1022
+
1023
+ // Branch 0 fails after consuming /a AND inspecting '0' -> exact replay rollback -> branch 1 succeeds!
1024
+ const r1 = executeKTVM(specMod, [Value.variant("a", bitsFromString("011"))]);
1025
+ assert.equal(r1.status, "OK");
1026
+ assert.equal(bitsToString(r1.value), "111");
1027
+ assert.equal(r1.telemetry.specRollbacks, 1);
1028
+
1029
+ // Branches 0 & 1 fail -> branch 2 tail-splices cleanly!
1030
+ const r2 = executeKTVM(specMod, [Value.variant("b", bitsFromString("110"))]);
1031
+ assert.equal(r2.status, "OK");
1032
+ assert.equal(bitsToString(r2.value), "110");
1033
+ assert.equal(r2.telemetry.specRollbacks, 2);
1034
+ assert.equal(r2.telemetry.specTailSplices, 1);
1035
+
1036
+ // All branches fail -> FAILED
1037
+ const r3 = executeKTVM(specMod, [Value.variant("c", bitsFromString("1"))]);
1038
+ assert.equal(r3.status, "FAILED");
1039
+
1040
+ // Upstream failure abort: %mid fails upstream because %raw is /c -> spec MUST abort immediately!
1041
+ const rAbort = executeKTVM(specMod, [Value.variant("c", bitsFromString("1"))], {
1042
+ entry: "@upstream_abort_test"
1043
+ });
1044
+ assert.equal(rAbort.status, "FAILED");
1045
+ assert.equal(rAbort.telemetry.specUpstreamAborts, 1);
1046
+ assert.equal(rAbort.telemetry.specRollbacks, 0, "upstream failure must NOT roll back to branch 1");
1047
+ });
1048
+
1049
+ test("after %tok sequential sibling settlement bounds peak active nodes on binary tree recursion", () => {
1050
+ // Binary tree recursion of depth d (2^d leaves): without `after`, concurrent expansion
1051
+ // could live-materialize both subtrees simultaneously; WITH `after %t0`, left settles
1052
+ // completely before right expands -> O(d) peak nodes!
1053
+ const treeMod = `
1054
+ ktvm 0.1 mono entry @tree_eval;
1055
+
1056
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1057
+
1058
+ proc @tree_eval(%d: $bits) -> (%out: $bits) branching {
1059
+ switch (%d) {
1060
+ case (/_): {
1061
+ chan %u : unit;
1062
+ barrier %b;
1063
+ chan %z : unit;
1064
+ match /_ %d -> %u;
1065
+ drain %u : unit -> %b;
1066
+ const_unit -> %z;
1067
+ chan %res : $bits;
1068
+ wrap |_ %z -> %res;
1069
+ gate %b, %res -> %out;
1070
+ }
1071
+ case (/0): {
1072
+ chan %rest : $bits;
1073
+ chan %r0 : $bits;
1074
+ chan %r1 : $bits;
1075
+ chan %a : $bits;
1076
+ chan %b : $bits;
1077
+ barrier %bar;
1078
+ match /0 %d -> %rest;
1079
+ tee %rest -> (%r0, %r1);
1080
+ spawn @tree_eval(%r0) -> (%a) as %t0;
1081
+ spawn @tree_eval(%r1) -> (%b) after %t0;
1082
+ drain %a : $bits -> %bar;
1083
+ gate %bar, %b -> %out;
1084
+ }
1085
+ case (/1): {
1086
+ chan %rest : $bits;
1087
+ match /1 %d -> %rest;
1088
+ spawn @tree_eval(%rest) -> (%out);
1089
+ }
1090
+ }
1091
+ }
1092
+ `;
1093
+
1094
+ // Depth 8 -> 2^8 = 256 recursive calls, but peak live nodes stays O(depth) (< 60)!
1095
+ const res = executeKTVM(treeMod, [bitsFromString("00000000")]);
1096
+ assert.equal(res.status, "OK");
1097
+ assert.equal(bitsToString(res.value), "");
1098
+ assert.ok(res.telemetry.afterSettlements >= 255, `expected >= 255 after settlements, got ${res.telemetry.afterSettlements}`);
1099
+ assert.ok(
1100
+ res.telemetry.peakActiveNodes < 80,
1101
+ `Expected O(depth) peak nodes (< 80) for 2^8 tree, got ${res.telemetry.peakActiveNodes}`
1102
+ );
1103
+ });
1104
+
1105
+ // ============================================================================
1106
+ console.log("\n=== 5. Accelerated Kernels: TMC _lsb_add & Virtual-Stack _lsb_trim ===");
1107
+ // ============================================================================
1108
+
1109
+ test("TMC _lsb_add kernel with bisimulation-verified chunk_table matches BigInt addition across edge cases", () => {
1110
+ const modSrc = makeLsbAddModule(buildLsbAdd2x2Entries());
1111
+ const pairs = [
1112
+ [0n, 0n],
1113
+ [0n, 1n],
1114
+ [1n, 0n],
1115
+ [1n, 1n],
1116
+ [7n, 1n],
1117
+ [255n, 1n],
1118
+ [123456n, 987654n],
1119
+ [(1n << 200n) - 1n, 1n], // 200-bit carry chain!
1120
+ [(1n << 256n) + 42n, 5n], // uneven lengths (triggers O(1) tail splice!)
1121
+ [3n, (1n << 300n) + 12345n] // symmetric uneven lengths (exit_splice_y)
1122
+ ];
1123
+
1124
+ for (const [a, b] of pairs) {
1125
+ const res = executeKTVM(modSrc, [bitsFromBigIntLSB(a), bitsFromBigIntLSB(b)]);
1126
+ assert.equal(res.status, "OK");
1127
+ assert.equal(bitsToBigIntLSB(res.value), a + b, `${a} + ${b}`);
1128
+ assert.ok(res.telemetry.tableLookups >= 1, "chunk_table must be executed");
1129
+ }
1130
+ });
1131
+
1132
+ test("Virtual-stack _lsb_trim kernel with stack_table trims trailing zeros including 4,096-bit stream", () => {
1133
+ const cases = [
1134
+ ["", ""],
1135
+ ["0", ""],
1136
+ ["00000000", ""],
1137
+ ["1", "1"],
1138
+ ["10000", "1"],
1139
+ ["001001000", "001001"],
1140
+ ["0101010000000", "010101"],
1141
+ ["0".repeat(2000) + "1" + "0".repeat(2095), "0".repeat(2000) + "1"]
1142
+ ];
1143
+
1144
+ for (const [inp, expected] of cases) {
1145
+ const res = executeKTVM(LSB_TRIM_KTVM, [bitsFromString(inp)]);
1146
+ assert.equal(res.status, "OK");
1147
+ assert.equal(bitsToString(res.value), expected, `trim(${inp.slice(0, 20)}...)`);
1148
+ assert.ok(res.telemetry.tableLookups >= 1, "stack_table must be executed");
1149
+ }
1150
+ });
1151
+
1152
+ // ============================================================================
1153
+ console.log("\n=== 6. Runtime Quotas, Malformed k-wire & Deep Iterative Stress ===");
1154
+ // ============================================================================
1155
+
1156
+ test("Runtime quotas enforce maxSteps, maxNodes, and maxBitDequeBytes with KTVMQuotaError", () => {
1157
+ const modSrc = makeLsbAddModule(buildLsbAdd2x2Entries());
1158
+ const bigA = bitsFromBigIntLSB((1n << 256n) - 1n);
1159
+ const bigB = bitsFromBigIntLSB(1n);
1160
+
1161
+ // Confirm single-kernel TMC executes in literally 1 live node!
1162
+ const okSingle = executeKTVM(modSrc, [bigA, bigB]);
1163
+ assert.equal(okSingle.telemetry.peakActiveNodes, 1);
1164
+
1165
+ assert.throws(
1166
+ () => executeKTVM(modSrc, [bigA, bigB], { quota: { maxSteps: 5 } }),
1167
+ (err) => err instanceof KTVMQuotaError && err.quotaKind === "maxSteps"
1168
+ );
1169
+ assert.throws(
1170
+ () => executeKTVM(modSrc, [bigA, bigB], { quota: { maxNodes: 0 } }),
1171
+ (err) => err instanceof KTVMQuotaError && err.quotaKind === "maxNodes"
1172
+ );
1173
+ assert.throws(
1174
+ () => executeKTVM(modSrc, [bigA, bigB], { quota: { maxBitDequeBytes: 32 } }),
1175
+ (err) => err instanceof KTVMQuotaError && err.quotaKind === "maxBitDequeBytes"
1176
+ );
1177
+ });
1178
+
1179
+ test("Malformed k-wire envelopes (truncated, invalid ordinal, nonzero padding) are cleanly rejected", () => {
1180
+ const bitsMod = parseModule(`
1181
+ ktvm 0.1 mono;
1182
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1183
+ `);
1184
+ const bitsPlist = compileSchemaExprToPlist({ kind: "ref", name: "$bits", args: [] }, bitsMod.schemas);
1185
+ const validWire = encodeToWire(bitsFromString("101"), bitsPlist);
1186
+
1187
+ // 1. Truncated wire
1188
+ assert.throws(() => splitEnvelopedWire(validWire.slice(0, validWire.length - 1)));
1189
+
1190
+ // 2. Nonzero trailing byte padding (flip LSB of last byte if it's padding, or add an extra byte)
1191
+ const paddedBad = new Uint8Array(validWire.length + 1);
1192
+ paddedBad.set(validWire);
1193
+ paddedBad[paddedBad.length - 1] = 0x01;
1194
+ assert.throws(() => splitEnvelopedWire(paddedBad));
1195
+
1196
+ // 3. Invalid 0b11 ordinal directly in BitDeque passed to _lsb_trim
1197
+ const badDq = new BitDeque(999, { prodSchema: bitsPlist, consSchema: bitsPlist });
1198
+ badDq.pushBits(0b11, 2); // invalid 3rd ordinal on 3-tag union!
1199
+ badDq.close();
1200
+ const res = executeKTVM(LSB_TRIM_KTVM, [badDq]);
1201
+ assert.equal(res.status, "FAILED");
1202
+ });
1203
+
1204
+ test("Strictly iterative 4,096-bit k-wire encode + execute + decode with zero host stack overflow", () => {
1205
+ const bitsMod = parseModule(`
1206
+ ktvm 0.1 mono;
1207
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1208
+ `);
1209
+ const bitsPlist = compileSchemaExprToPlist({ kind: "ref", name: "$bits", args: [] }, bitsMod.schemas);
1210
+
1211
+ const deepStr = "10".repeat(2048); // 4,096 nested union constructors!
1212
+ const deepVal = bitsFromString(deepStr);
1213
+
1214
+ // Strictly iterative payload encode & decode
1215
+ const dq = new BitDeque(500, { prodSchema: bitsPlist, consSchema: bitsPlist });
1216
+ encodePayloadToDeque(deepVal, bitsPlist, dq, 0);
1217
+ dq.close();
1218
+ assert.equal(dq.length, 4097 * 2);
1219
+
1220
+ // Run through `_lsb_add` (+ 1) strictly iteratively!
1221
+ const oneDq = new BitDeque(501, { prodSchema: bitsPlist, consSchema: bitsPlist });
1222
+ encodePayloadToDeque(bitsFromString("1"), bitsPlist, oneDq, 0);
1223
+ oneDq.close();
1224
+
1225
+ const res = executeKTVM(makeLsbAddModule(buildLsbAdd2x2Entries()), [dq, oneDq]);
1226
+ assert.equal(res.status, "OK");
1227
+ assert.equal(bitsToBigIntLSB(res.value), bitsToBigIntLSB(deepVal) + 1n);
1228
+
1229
+ // Verify iterative decode on output deque directly
1230
+ const outVal = decodeDequeToValue(res.outputDeques[0], bitsPlist, 0, { exact: true });
1231
+ assert.equal(bitsToBigIntLSB(outVal), bitsToBigIntLSB(deepVal) + 1n);
1232
+ });
1233
+
1234
+ test("Dead switch arm pruning on open_union + non-equivalent coerce (tag widening)", () => {
1235
+ const polyMod = `
1236
+ ktvm 0.1 poly entry @widen_ab;
1237
+
1238
+ schema $in_open = open_union { a: unit ... };
1239
+ schema $out_wide = union { a: unit, b: unit, c: unit, d: unit };
1240
+
1241
+ proc @widen_ab(%in: $in_open) -> (%out: $out_wide) {
1242
+ switch (%in) {
1243
+ case (/a): {
1244
+ coerce %in : $in_open -> %out : $out_wide;
1245
+ }
1246
+ case (/b): {
1247
+ coerce %in : $in_open -> %out : $out_wide;
1248
+ }
1249
+ case (/c): {
1250
+ coerce %in : $in_open -> %out : $out_wide;
1251
+ }
1252
+ }
1253
+ }
1254
+ `;
1255
+
1256
+ // Supply concrete closed union with ONLY { a, b } (1-bit tag!), missing /c!
1257
+ const abMod = parseModule(`
1258
+ ktvm 0.1 mono;
1259
+ schema $ab = union { a: unit, b: unit };
1260
+ `);
1261
+ const abPlist = compileSchemaExprToPlist({ kind: "ref", name: "$ab", args: [] }, abMod.schemas);
1262
+
1263
+ const rA = executeKTVMWire(polyMod, encodeToWire(Value.variant("a", UNIT), abPlist));
1264
+ assert.equal(rA.status, "OK");
1265
+ assert.equal(rA.value.tag, "a");
1266
+ // Verify dead `/c` arm was statically pruned in specialized mono module!
1267
+ const specText = printModule(rA.specialized.module);
1268
+ assert.ok(!specText.includes("case (/c)"), "unreachable /c switch arm must be pruned");
1269
+ // Verify output wire is 2-bit tag widened `{ a, b, c, d }` decoded cleanly by K's decodeWire
1270
+ assert.equal(decodeWire(rA.wire, { eager: true }).value.tag, "a");
1271
+
1272
+ const rB = executeKTVMWire(polyMod, encodeToWire(Value.variant("b", UNIT), abPlist));
1273
+ assert.equal(rB.status, "OK");
1274
+ assert.equal(decodeWire(rB.wire, { eager: true }).value.tag, "b");
1275
+ });
1276
+
1277
+ test("packed_base64 chunk_table + fsm_table_step + kernel handoff work end-to-end", () => {
1278
+ // Pack a tiny 4-entry fsm_table for flipping a single leading bit on $bits and handing off to @id!
1279
+ const fsmMod = `
1280
+ ktvm 0.1 mono entry @flip_first_bit;
1281
+
1282
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1283
+
1284
+ proc @id_tail(%x: $bits) -> (%o: $bits) total {
1285
+ splice %x -> %o;
1286
+ }
1287
+
1288
+ proc @flip_first_bit(%x: $bits) -> (%o: $bits) total {
1289
+ exec @_flip_head(%x) -> (%o);
1290
+ }
1291
+
1292
+ kernel @_flip_head(%x: $bits) -> (%o: $bits) total {
1293
+ entry:
1294
+ fsm_table_step &tab_flip, %x, (%o) -> exits {
1295
+ short: err,
1296
+ 0: handoff_tail,
1297
+ 1: done_empty,
1298
+ fail: err
1299
+ };
1300
+
1301
+ handoff_tail:
1302
+ handoff @id_tail(%x) -> (%o);
1303
+
1304
+ done_empty:
1305
+ drain_guard %x : unit;
1306
+ push_bits %o, 0b10, 2;
1307
+ close %o;
1308
+ retire;
1309
+
1310
+ err:
1311
+ fail;
1312
+ }
1313
+
1314
+ table &tab_flip fsm_table {
1315
+ input_bits: 2;
1316
+ output_modes: [ push ];
1317
+ entries {
1318
+ 0 => { kind: EXIT, exit: 0, shift: [2], emit_word: [1], emit_len: [2] };
1319
+ 1 => { kind: EXIT, exit: 0, shift: [2], emit_word: [0], emit_len: [2] };
1320
+ 2 => { kind: EXIT, exit: 1, shift: [2], emit_word: [0], emit_len: [0] };
1321
+ 3 => { kind: FAIL };
1322
+ }
1323
+ }
1324
+ `;
1325
+
1326
+ const r0 = executeKTVM(fsmMod, [bitsFromString("0110")]);
1327
+ assert.equal(r0.status, "OK");
1328
+ assert.equal(bitsToString(r0.value), "1110");
1329
+ assert.equal(r0.telemetry.tableLookups, 1);
1330
+
1331
+ const r1 = executeKTVM(fsmMod, [bitsFromString("100")]);
1332
+ assert.equal(r1.status, "OK");
1333
+ assert.equal(bitsToString(r1.value), "000");
1334
+
1335
+ const rEmpty = executeKTVM(fsmMod, [bitsFromString("")]);
1336
+ assert.equal(rEmpty.status, "OK");
1337
+ assert.equal(bitsToString(rEmpty.value), "");
1338
+
1339
+ // Also verify packed_base64 Int32 encoding round-trip + execution on _lsb_add!
1340
+ // Stride = 7: [kindCode (0=CONT,1=EXIT,2=NEED_MORE,3=FAIL), next_q, exit, sh0, sh1, emitWord0, emitLen0]
1341
+ const packed = new Int32Array(32 * 7);
1342
+ for (let c = 0; c < 2; c++) {
1343
+ for (let tx = 0; tx < 4; tx++) {
1344
+ for (let ty = 0; ty < 4; ty++) {
1345
+ const idx = (c << 4) | (tx << 2) | ty;
1346
+ const b = idx * 7;
1347
+ if (tx === 3 || ty === 3) {
1348
+ packed[b] = 3; // FAIL
1349
+ } else if (tx === 2 && ty === 2) {
1350
+ packed[b] = 1; packed[b + 2] = c; packed[b + 3] = 2; packed[b + 4] = 2;
1351
+ } else if (tx === 2) {
1352
+ if (c === 0) {
1353
+ packed[b] = 1; packed[b + 2] = 2; packed[b + 3] = 2; packed[b + 4] = 0;
1354
+ } else {
1355
+ const sum = ty + 1;
1356
+ packed[b] = 0; packed[b + 1] = sum >> 1; packed[b + 3] = 0; packed[b + 4] = 2;
1357
+ packed[b + 5] = sum & 1; packed[b + 6] = 2;
1358
+ }
1359
+ } else if (ty === 2) {
1360
+ if (c === 0) {
1361
+ packed[b] = 1; packed[b + 2] = 3; packed[b + 3] = 0; packed[b + 4] = 2;
1362
+ } else {
1363
+ const sum = tx + 1;
1364
+ packed[b] = 0; packed[b + 1] = sum >> 1; packed[b + 3] = 2; packed[b + 4] = 0;
1365
+ packed[b + 5] = sum & 1; packed[b + 6] = 2;
1366
+ }
1367
+ } else {
1368
+ const sum = tx + ty + c;
1369
+ packed[b] = 0; packed[b + 1] = sum >> 1; packed[b + 3] = 2; packed[b + 4] = 2;
1370
+ packed[b + 5] = sum & 1; packed[b + 6] = 2;
1371
+ }
1372
+ }
1373
+ }
1374
+ }
1375
+ const b64 = packInt32Base64(packed);
1376
+ const packedSrc = makeLsbAddModule("").replace(
1377
+ /entries \{[\s\S]*?\}/,
1378
+ `stride: 7;\n packed_base64 "${b64}";`
1379
+ );
1380
+ const parsedPacked = parseModule(packedSrc);
1381
+ assert.equal(printModule(parseModule(printModule(parsedPacked))), printModule(parsedPacked));
1382
+ const rPack = executeKTVM(parsedPacked, [bitsFromBigIntLSB(99999n), bitsFromBigIntLSB(12345n)]);
1383
+ assert.equal(rPack.status, "OK");
1384
+ assert.equal(bitsToBigIntLSB(rPack.value), 112344n);
1385
+ assert.ok(rPack.telemetry.tableLookups >= 10);
1386
+ });
1387
+
1388
+ // ============================================================================
1389
+ // 7. s-Language Node-List Derivatives, Wire Equivalence & Aligned Scanner
1390
+ // ============================================================================
1391
+
1392
+ function compileSchemaSnippet(src, refName) {
1393
+ const mod = parseModule(`ktvm 0.1 mono;\n${src}`);
1394
+ return compileSchemaExprToPlist({ kind: "ref", name: refName, args: [] }, mod.schemas);
1395
+ }
1396
+
1397
+ test("Node-list prefix derivatives: unit/product normalization, tag/label steps, and cycle checks", () => {
1398
+ const listPlist = compileSchemaSnippet(
1399
+ `
1400
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1401
+ schema $int = union { +: $bits, -: $bits };
1402
+ schema $list = union { cons: product { car: $int, cdr: $list }, nil: unit };
1403
+ `,
1404
+ "$list"
1405
+ );
1406
+
1407
+ // Initial list root is already a union (`closed-union` at node 0)
1408
+ assert.deepEqual(normalizeNodeList(listPlist, [0]), [0]);
1409
+ assert.equal(nodeListComplete(listPlist, [0]), false);
1410
+
1411
+ // Step /cons -> expands product { car: $int, cdr: $list } into [intId, listId]
1412
+ const sCons = stepNodeListLabel(listPlist, [0], "cons");
1413
+ assert.equal(sCons.ok, true);
1414
+ assert.equal(sCons.label, "cons");
1415
+ assert.equal(sCons.ordinal, 0);
1416
+ assert.equal(sCons.width, 1);
1417
+ assert.equal(sCons.nextNodes.length, 2);
1418
+ const [intId, listId] = sCons.nextNodes;
1419
+ assert.equal(listId, 0);
1420
+
1421
+ // Step sign `+` on [intId, listId] -> [bitsId, listId]
1422
+ const sPlus = stepNodeListLabel(listPlist, sCons.nextNodes, "+");
1423
+ assert.equal(sPlus.ok, true);
1424
+ assert.equal(sPlus.width, 1);
1425
+ const [bitsId, tailListId] = sPlus.nextNodes;
1426
+ assert.equal(tailListId, 0);
1427
+
1428
+ // Step bit `1` then `_` (unit!) on [bitsId, listId] -> collapses unit, leaving [listId]
1429
+ const sOne = stepNodeListTag(listPlist, sPlus.nextNodes, 1);
1430
+ assert.equal(sOne.ok, true);
1431
+ assert.equal(sOne.label, "1");
1432
+ assert.equal(sOne.width, 2);
1433
+ assert.deepEqual(sOne.nextNodes, [bitsId, 0]);
1434
+
1435
+ const sTerm = stepNodeListLabel(listPlist, sOne.nextNodes, "_");
1436
+ assert.equal(sTerm.ok, true);
1437
+ assert.deepEqual(sTerm.nextNodes, [0]);
1438
+
1439
+ // Step /nil -> unit eliminates completely to []
1440
+ const sNil = stepNodeListLabel(listPlist, sTerm.nextNodes, "nil");
1441
+ assert.equal(sNil.ok, true);
1442
+ assert.deepEqual(sNil.nextNodes, []);
1443
+ assert.equal(nodeListComplete(listPlist, sNil.nextNodes), true);
1444
+
1445
+ // Error cases: stepping complete list, bad ordinal, unknown label
1446
+ assert.equal(stepNodeListTag(listPlist, [], 0).ok, false);
1447
+ assert.equal(stepNodeListTag(listPlist, [bitsId], 3).ok, false);
1448
+ assert.equal(stepNodeListLabel(listPlist, [0], "missing").ok, false);
1449
+
1450
+ // Shared unit-product diamond must normalize cleanly in linear time (not a cycle!)
1451
+ const unitDiamond = [
1452
+ ["closed-product", [["a", 1], ["b", 1]]],
1453
+ ["closed-product", [["c", 2], ["d", 2]]],
1454
+ ["closed-product", []]
1455
+ ];
1456
+ assert.deepEqual(normalizeNodeList(unitDiamond, [0]), []);
1457
+ assert.equal(nodeListComplete(unitDiamond, [0]), true);
1458
+
1459
+ // True unguarded product cycle must throw KTVMSchemaError
1460
+ const cyclicProd = [
1461
+ ["closed-product", [["a", 1]]],
1462
+ ["closed-product", [["b", 0]]]
1463
+ ];
1464
+ assert.throws(() => normalizeNodeList(cyclicProd, [0]), KTVMSchemaError);
1465
+ });
1466
+
1467
+ test("Bit-level s-language equivalence (wireLanguagesEqual) vs structural schemasEquivalent", () => {
1468
+ const bitsInt1 = compileSchemaSnippet(
1469
+ `
1470
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1471
+ schema $int = union { +: $bits, -: $bits };
1472
+ schema $pair = product { a: $int, b: $bits };
1473
+ `,
1474
+ "$pair"
1475
+ );
1476
+ const bitsInt2 = compileSchemaSnippet(
1477
+ `
1478
+ schema $b = union { x0: $b, x1: $b, z: unit };
1479
+ schema $i = union { neg: $b, pos: $b };
1480
+ schema $p = product { first: $i, second: $b };
1481
+ `,
1482
+ "$p"
1483
+ );
1484
+ // Renamed labels: same bit language, distinct structural Moore schemas!
1485
+ assert.equal(wireLanguagesEqual(bitsInt1, [0], bitsInt2, [0]), true);
1486
+ assert.equal(schemasEquivalent(bitsInt1, 0, bitsInt2, 0), false);
1487
+
1488
+ // Product associativity: {{A, B}, C} vs {A, {B, C}} and node-list [A, B, C]
1489
+ const leftAssoc = compileSchemaSnippet(
1490
+ `
1491
+ schema $u2 = union { a: unit, b: unit };
1492
+ schema $u3 = union { a: unit, b: unit, c: unit };
1493
+ schema $s = product { ab: product { a: $u2, b: $u3 }, c: $u2 };
1494
+ `,
1495
+ "$s"
1496
+ );
1497
+ const rightAssoc = compileSchemaSnippet(
1498
+ `
1499
+ schema $u2 = union { x: unit, y: unit };
1500
+ schema $u3 = union { x: unit, y: unit, z: unit };
1501
+ schema $s = product { a: $u2, bc: product { b: $u3, c: $u2 } };
1502
+ `,
1503
+ "$s"
1504
+ );
1505
+ assert.equal(wireLanguagesEqual(leftAssoc, [0], rightAssoc, [0]), true);
1506
+ assert.equal(schemasEquivalent(leftAssoc, 0, rightAssoc, 0), false);
1507
+ const flatNodes = normalizeNodeList(leftAssoc, [0]);
1508
+ assert.equal(flatNodes.length, 3);
1509
+ assert.equal(wireLanguagesEqual(leftAssoc, flatNodes, rightAssoc, [0]), true);
1510
+
1511
+ // Unit elimination and 1-tag union elimination
1512
+ const plainInt = compileSchemaSnippet(
1513
+ `
1514
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1515
+ schema $int = union { +: $bits, -: $bits };
1516
+ `,
1517
+ "$int"
1518
+ );
1519
+ const wrappedInt = compileSchemaSnippet(
1520
+ `
1521
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1522
+ schema $int = union { +: $bits, -: $bits };
1523
+ schema $wrap = product { a: unit, b: union { only: $int }, c: product { u: unit } };
1524
+ `,
1525
+ "$wrap"
1526
+ );
1527
+ assert.equal(wireLanguagesEqual(plainInt, 0, wrappedInt, 0), true);
1528
+
1529
+ // Dead union branch elimination (`<a:{}, b:{}, c:{}, d:<>>` == `<a:{}, b:{}, c:{}>`)
1530
+ const threeTag = [
1531
+ ["closed-union", [["a", 1], ["b", 1], ["c", 1]]],
1532
+ ["closed-product", []]
1533
+ ];
1534
+ const fourWithDead = [
1535
+ ["closed-union", [["a", 1], ["b", 1], ["c", 1], ["d", 2]]],
1536
+ ["closed-product", []],
1537
+ ["closed-union", []]
1538
+ ];
1539
+ assert.equal(wireLanguagesEqual(threeTag, 0, fourWithDead, 0), true);
1540
+
1541
+ // Prime suffix factoring (R2 & R3):
1542
+ // 1) 4-tag union == product of two 2-tag unions == nested 2-tag unions (all = {00,01,10,11})
1543
+ const fourTag = compileSchemaSnippet(`schema $s = union { a: unit, b: unit, c: unit, d: unit };`, "$s");
1544
+ const twoByTwo = compileSchemaSnippet(
1545
+ `
1546
+ schema $bit = union { 0: unit, 1: unit };
1547
+ schema $s = product { a: $bit, b: $bit };
1548
+ `,
1549
+ "$s"
1550
+ );
1551
+ const nestedTwo = compileSchemaSnippet(
1552
+ `
1553
+ schema $bit = union { 0: unit, 1: unit };
1554
+ schema $s = union { a: $bit, b: $bit };
1555
+ `,
1556
+ "$s"
1557
+ );
1558
+ assert.equal(wireLanguagesEqual(fourTag, 0, twoByTwo, 0), true);
1559
+ assert.equal(wireLanguagesEqual(fourTag, 0, nestedTwo, 0), true);
1560
+
1561
+ // 2) `int[] = < +: bits[], -: bits[] >` == `{ a_sign: < +: unit, -: unit >, b_mag: bits[] }`
1562
+ const splitInt = compileSchemaSnippet(
1563
+ `
1564
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1565
+ schema $sign = union { +: unit, -: unit };
1566
+ schema $s = product { a_sign: $sign, b_mag: $bits };
1567
+ `,
1568
+ "$s"
1569
+ );
1570
+ assert.equal(wireLanguagesEqual(plainInt, 0, splitInt, 0), true);
1571
+
1572
+ // 3) Recursive unrolling (`< 0: S, 1: {} >` == `< 0: < 0: S, 1: {} >, 1: {} >`)
1573
+ const rec1 = compileSchemaSnippet(`schema $s = union { 0: $s, 1: unit };`, "$s");
1574
+ const rec2 = compileSchemaSnippet(`schema $s = union { 0: union { 0: $s, 1: unit }, 1: unit };`, "$s");
1575
+ assert.equal(wireLanguagesEqual(rec1, 0, rec2, 0), true);
1576
+
1577
+ // Negative cases: MUST return false when bit languages differ!
1578
+ const twoTag = compileSchemaSnippet(`schema $s = union { a: unit, b: unit };`, "$s");
1579
+ assert.equal(wireLanguagesEqual(twoTag, 0, threeTag, 0), false);
1580
+
1581
+ const ordAB = compileSchemaSnippet(
1582
+ `
1583
+ schema $u2 = union { a: unit, b: unit };
1584
+ schema $u3 = union { a: unit, b: unit, c: unit };
1585
+ schema $s = product { a: $u2, b: $u3 };
1586
+ `,
1587
+ "$s"
1588
+ );
1589
+ const ordBA = compileSchemaSnippet(
1590
+ `
1591
+ schema $u2 = union { a: unit, b: unit };
1592
+ schema $u3 = union { a: unit, b: unit, c: unit };
1593
+ schema $s = product { a: $u3, b: $u2 };
1594
+ `,
1595
+ "$s"
1596
+ );
1597
+ assert.equal(wireLanguagesEqual(ordAB, 0, ordBA, 0), false);
1598
+
1599
+ const rev1 = compileSchemaSnippet(
1600
+ `
1601
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1602
+ schema $s = union { a: $bits, b: unit };
1603
+ `,
1604
+ "$s"
1605
+ );
1606
+ const rev2 = compileSchemaSnippet(
1607
+ `
1608
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1609
+ schema $s = union { a: unit, b: $bits };
1610
+ `,
1611
+ "$s"
1612
+ );
1613
+ assert.equal(wireLanguagesEqual(rev1, 0, rev2, 0), false);
1614
+
1615
+ // Empty language vs unit language
1616
+ const emptyPlist = [["closed-union", []]];
1617
+ const unitPlist = [["closed-product", []]];
1618
+ const unprodCycle = [["closed-union", [["a", 0], ["b", 0]]]];
1619
+ assert.equal(wireLanguageKey(emptyPlist, 0), "EMPTY");
1620
+ assert.equal(wireLanguageKey(unprodCycle, 0), "EMPTY");
1621
+ assert.equal(wireLanguageKey(unitPlist, 0), "EPS");
1622
+ assert.equal(wireLanguagesEqual(emptyPlist, 0, unitPlist, 0), false);
1623
+ assert.equal(wireLanguagesEqual(emptyPlist, 0, unprodCycle, 0), true);
1624
+ });
1625
+
1626
+ test("Unified SchemaCursor, BitDeque node-list getters, and scanBufferAlignedOffset", () => {
1627
+ const listPlist = compileSchemaSnippet(
1628
+ `
1629
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1630
+ schema $int = union { +: $bits, -: $bits };
1631
+ schema $list = union { cons: product { car: $int, cdr: $list }, nil: unit };
1632
+ `,
1633
+ "$list"
1634
+ );
1635
+
1636
+ // BitDeque prodNodeList / consNodeList getters
1637
+ const emptyChan = new BitDeque(700);
1638
+ assert.deepEqual(emptyChan.prodNodeList, []);
1639
+ assert.deepEqual(emptyChan.consNodeList, []);
1640
+ emptyChan.release();
1641
+
1642
+ const typedChan = new BitDeque(701, {
1643
+ prodSchema: listPlist,
1644
+ prodNodeId: 0,
1645
+ consSchema: listPlist,
1646
+ consNodeId: 0
1647
+ });
1648
+ assert.deepEqual(typedChan.prodNodeList, [0]);
1649
+ assert.deepEqual(typedChan.consNodeList, [0]);
1650
+ typedChan.release();
1651
+
1652
+ // Build list `[+5, -13, +0]` and encode to enveloped k-wire bytes
1653
+ const elems = [
1654
+ Value.variant("+", bitsFromBigIntLSB(5n)),
1655
+ Value.variant("-", bitsFromBigIntLSB(13n)),
1656
+ Value.variant("+", bitsFromBigIntLSB(0n))
1657
+ ];
1658
+ let listVal = Value.variant("nil", UNIT);
1659
+ for (let i = elems.length - 1; i >= 0; i--) {
1660
+ listVal = Value.variant("cons", Value.product({ car: elems[i], cdr: listVal }));
1661
+ }
1662
+ const wire = encodeValueToEnvelopedWire(listVal, listPlist);
1663
+ const { plist: hdrPlist, headerBitLen } = splitWireHeaderOnly(wire);
1664
+
1665
+ // Walk the raw enveloped buffer strictly via node-list aligned offsets!
1666
+ let offset = headerBitLen;
1667
+ let nodes = [0];
1668
+ const decodedElems = [];
1669
+
1670
+ while (true) {
1671
+ const tagStep = scanBufferAlignedOffset(wire, offset, hdrPlist, nodes, { mode: "tag" });
1672
+ assert.equal(tagStep.ok, true);
1673
+ offset = tagStep.bitOffset;
1674
+ nodes = tagStep.nodes;
1675
+ if (tagStep.label === "nil") {
1676
+ assert.equal(tagStep.complete, true);
1677
+ assert.deepEqual(nodes, []);
1678
+ break;
1679
+ }
1680
+ assert.equal(tagStep.label, "cons");
1681
+ assert.equal(nodes.length, 2);
1682
+ const elemStart = offset;
1683
+ const elemNodeId = nodes[0];
1684
+
1685
+ // Skip the complete head `int[]` sub-value to reach the aligned `cdr` offset
1686
+ const valStep = scanBufferAlignedOffset(wire, offset, hdrPlist, nodes, { mode: "value" });
1687
+ assert.equal(valStep.ok, true);
1688
+ assert.equal(valStep.headNodeId, elemNodeId);
1689
+ const elemEnd = valStep.bitOffset;
1690
+
1691
+ // Independently slice [elemStart..elemEnd) into a fresh BitDeque and decode under elemNodeId
1692
+ const sliceDq = new BitDeque(702);
1693
+ for (let b = elemStart; b < elemEnd; b++) {
1694
+ const bit = (wire[b >>> 3] >>> (7 - (b & 7))) & 1;
1695
+ sliceDq.pushBits(bit, 1);
1696
+ }
1697
+ sliceDq.close();
1698
+ const elemVal = decodeDequeToValue(sliceDq, hdrPlist, elemNodeId, { exact: true });
1699
+ sliceDq.release();
1700
+ decodedElems.push({ sign: elemVal.tag, mag: bitsToBigIntLSB(elemVal.value) });
1701
+
1702
+ offset = elemEnd;
1703
+ nodes = valStep.nodes;
1704
+ assert.deepEqual(nodes, [0]); // back at aligned `[listNodeId]`!
1705
+ }
1706
+
1707
+ assert.deepEqual(decodedElems, [
1708
+ { sign: "+", mag: 5n },
1709
+ { sign: "-", mag: 13n },
1710
+ { sign: "+", mag: 0n }
1711
+ ]);
1712
+ const trailingPadBits = wire.length * 8 - offset;
1713
+ assert.ok(trailingPadBits >= 0 && trailingPadBits < 8);
1714
+
1715
+ // Resumable SchemaCursor fed 1 bit at a time across a multi-node list [intId, listId]
1716
+ const intNodeId = stepNodeListLabel(listPlist, [0], "cons").nextNodes[0];
1717
+ const srcFull = new BitDeque(703);
1718
+ encodePayloadToDeque(elems[0], listPlist, srcFull, intNodeId);
1719
+ encodePayloadToDeque(listVal, listPlist, srcFull, 0);
1720
+ const fullBits = srcFull.toBitString();
1721
+ srcFull.release();
1722
+
1723
+ const streamIn = new BitDeque(704);
1724
+ const streamOut = new BitDeque(705);
1725
+ const cursor = createSchemaCursor(listPlist, [intNodeId, 0]);
1726
+ assert.deepEqual(cursorNodeList(cursor), [intNodeId, 0]);
1727
+
1728
+ let res = DPDA_RESULT.NEED_BITS;
1729
+ for (let i = 0; i < fullBits.length; i++) {
1730
+ streamIn.pushBits(fullBits[i] === "1" ? 1 : 0, 1);
1731
+ res = stepSchemaCursor(streamIn, cursor, streamOut);
1732
+ if (i < fullBits.length - 1) {
1733
+ assert.equal(res, DPDA_RESULT.NEED_BITS);
1734
+ assert.ok(cursorNodeList(cursor).length >= 1);
1735
+ }
1736
+ }
1737
+ assert.equal(res, DPDA_RESULT.DONE);
1738
+ assert.deepEqual(cursorNodeList(cursor), []);
1739
+ assert.equal(streamOut.toBitString(), fullBits);
1740
+ streamIn.release();
1741
+ streamOut.release();
1742
+
1743
+ // Nested product: whole-field skip vs flattened leaf skip
1744
+ const nestedProd = compileSchemaSnippet(
1745
+ `
1746
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1747
+ schema $int = union { +: $bits, -: $bits };
1748
+ schema $inner = product { p: $int, q: $bits };
1749
+ schema $outer = product { first: $inner, second: $int };
1750
+ `,
1751
+ "$outer"
1752
+ );
1753
+ const outerVal = Value.product({
1754
+ first: Value.product({
1755
+ p: Value.variant("+", bitsFromBigIntLSB(3n)),
1756
+ q: bitsFromBigIntLSB(6n)
1757
+ }),
1758
+ second: Value.variant("-", bitsFromBigIntLSB(9n))
1759
+ });
1760
+ const outerWire = encodeValueToEnvelopedWire(outerVal, nestedProd);
1761
+ const outerHdr = splitWireHeaderOnly(outerWire);
1762
+ const topFields = productFields(outerHdr.plist, 0);
1763
+ const fieldIds = topFields.map((f) => f.targetId);
1764
+
1765
+ // Skip whole `first` (`$inner`) in one step -> leaves `[second]`
1766
+ const afterFirst = scanBufferAlignedOffset(outerWire, outerHdr.headerBitLen, outerHdr.plist, fieldIds, {
1767
+ mode: "value"
1768
+ });
1769
+ assert.equal(afterFirst.ok, true);
1770
+ assert.deepEqual(afterFirst.nodes, [fieldIds[1]]);
1771
+ assert.equal(afterFirst.complete, false);
1772
+
1773
+ // Decode `second` directly from `afterFirst.bitOffset`
1774
+ const afterSecond = scanBufferAlignedOffset(outerWire, afterFirst.bitOffset, outerHdr.plist, afterFirst.nodes, {
1775
+ mode: "value"
1776
+ });
1777
+ assert.equal(afterSecond.ok, true);
1778
+ assert.deepEqual(afterSecond.nodes, []);
1779
+ assert.equal(afterSecond.complete, true);
1780
+
1781
+ // Error checks in scanBufferAlignedOffset: truncated `cons` (bit 0 = cons, missing car/cdr),
1782
+ // invalid ordinal 0b11, out-of-bounds bit offset, and 0-bit union cycle.
1783
+ assert.equal(
1784
+ scanBufferAlignedOffset(new Uint8Array([0b00000000]), 0, listPlist, [0], { mode: "value", totalBits: 1 }).ok,
1785
+ false
1786
+ );
1787
+ const bitsOnly = compileSchemaSnippet(`schema $bits = union { 0: $bits, 1: $bits, _: unit };`, "$bits");
1788
+ assert.equal(
1789
+ scanBufferAlignedOffset(new Uint8Array([0b11000000]), 0, bitsOnly, [0], { mode: "tag", totalBits: 2 }).ok,
1790
+ false
1791
+ );
1792
+ assert.equal(
1793
+ scanBufferAlignedOffset(new Uint8Array([0]), 9, bitsOnly, [0], { mode: "value" }).ok,
1794
+ false
1795
+ );
1796
+ const zeroUnionCycle = [["closed-union", [["loop", 0]]]];
1797
+ assert.equal(
1798
+ scanBufferAlignedOffset(new Uint8Array([0]), 0, zeroUnionCycle, [0], { mode: "value" }).ok,
1799
+ false
1800
+ );
1801
+ });
1802
+
1803
+ // --- Summary ---
1804
+ console.log(`\nResults: ${passed} passed, ${failed} failed.`);
1805
+ if (failed > 0) process.exit(1);