@fraczak/k 8.8.0 → 9.0.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 (94) 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 +902 -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 +6 -4
  10. package/DOCS/README.md +3 -2
  11. package/DOCS/REPL.md +16 -12
  12. package/README.md +132 -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 -5
  21. package/backends/llvm/src/llvm.mjs +4 -111
  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 +0 -16
  25. package/backends/wasm/README.md +2 -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 +10 -56
  30. package/browser/repl-browser.mjs +9 -8
  31. package/browser/shims/buffer.mjs +31 -2
  32. package/browser/shims/child_process.mjs +26 -0
  33. package/browser/shims/fs.mjs +3 -1
  34. package/codecs/djson.mjs +2 -3
  35. package/codecs/int.mjs +66 -14
  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 +482 -0
  43. package/ktvm/fixtures/integer-streaming.k +477 -0
  44. package/ktvm/index.mjs +119 -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 +543 -0
  58. package/ktvm/specialize.mjs +538 -0
  59. package/ktvm/test-conformance.mjs +597 -0
  60. package/ktvm/test-ktvm.mjs +1376 -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 +4413 -0
  67. package/ktvm/wasm/test-wasm.mjs +426 -0
  68. package/ktvm/wire.mjs +489 -0
  69. package/lib/djson.k +175 -173
  70. package/lib/generic.k +82 -97
  71. package/lib/ieee.k +110 -115
  72. package/lib/integer.k +25 -31
  73. package/package.json +1 -9
  74. package/repl.mjs +101 -20
  75. package/scripts/build-repl-html.mjs +40 -18
  76. package/scripts/perf-bigint-compare.mjs +275 -0
  77. package/scripts/perf-ieee.mjs +9 -229
  78. package/scripts/perf-int.mjs +14 -272
  79. package/scripts/perf-multiplication.mjs +8 -54
  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-djson-methods.mjs +0 -1
  85. package/tests/test-djson.mjs +0 -1
  86. package/tests/test-generic.mjs +5 -7
  87. package/tests/test-repl-html.mjs +72 -15
  88. package/tests/test-repl.mjs +27 -20
  89. package/tests/test-structural-values.mjs +1 -1
  90. package/DOCS/POLYMORPHIC_IR.md +0 -86
  91. package/access-table.mjs +0 -343
  92. package/pkir.mjs +0 -772
  93. package/tests/test-access-table.mjs +0 -213
  94. package/tests/test-pkir.mjs +0 -530
package/ktvm/vm.mjs ADDED
@@ -0,0 +1,2225 @@
1
+ /**
2
+ * Strictly Iterative Small-Step Reference Virtual Machine for concrete `kTVM`.
3
+ *
4
+ * Implements DOCS/KTVM_SPEC.md §5–§7:
5
+ * - Explicit heap demand stack (zero host call-stack recursion)
6
+ * - Dual-schema `(prodSchema, consSchema)` + `aligned` enforcement
7
+ * - O(1) zero-copy `splice`, same-scope `MUX -> DEMUX` bundle fusion
8
+ * - Strict K partiality via `drain` / `barrier` / `gate`
9
+ * - Ordered backtracking `spec` with exact `replay` rollback, upstream-failure
10
+ * abort, and last-branch tail splice
11
+ * - Sequential sibling settlement (`after %tok` / `as %tok`)
12
+ * - Compiled `kernel` execution (`reg`, LIFO `BitStack`, `yield`, `handoff`,
13
+ * `chunk_table`, `stack_table`, `fsm_table`)
14
+ * - Configurable runtime quotas (`maxBitDequeBytes`, `maxNodes`, `maxSteps`)
15
+ */
16
+
17
+ import { KTVMSchemaError, collectSwitchOuterIO, unpackInt32Base64 } from "./ast.mjs";
18
+ import { parseModule } from "./parser.mjs";
19
+ import {
20
+ CHAN_STATUS,
21
+ BitDeque,
22
+ BitStack,
23
+ QuotaTracker
24
+ } from "./bit-deque.mjs";
25
+ import {
26
+ compileSchemaExprToPlist,
27
+ isUnitSchema,
28
+ mooreMinimize,
29
+ productFields,
30
+ schemasEquivalent,
31
+ unionTagInfo
32
+ } from "./schema.mjs";
33
+ import {
34
+ DPDA_RESULT,
35
+ createDpdaCoerce,
36
+ createDpdaCopy,
37
+ createDpdaSkip,
38
+ decodeDequeToValue,
39
+ encodePayloadToDeque,
40
+ frameEnvelopedWire,
41
+ splitEnvelopedWire,
42
+ stepDpdaCoerce,
43
+ stepDpdaCopy,
44
+ stepDpdaSkip
45
+ } from "./wire.mjs";
46
+ import { choiceWidth } from "../codecs/runtime/prefix-codec.mjs";
47
+ import { validateModule } from "./validator.mjs";
48
+ import { specializeKTVM } from "./specialize.mjs";
49
+
50
+ // --- Table Compilation Helpers ---
51
+
52
+ function applyInputCompress(rawVal, inpSpec) {
53
+ const comp = inpSpec.compress;
54
+ if (!comp || comp.ident === "none") return rawVal;
55
+ if (typeof comp === "object" && Array.isArray(comp.lut)) {
56
+ return comp.lut[rawVal] ?? 0;
57
+ }
58
+ if (typeof comp === "object" && typeof comp.mask === "number") {
59
+ // Bit extraction (PEXT-style) over `raw_bits`
60
+ let out = 0;
61
+ let bitPos = 0;
62
+ const mask = comp.mask >>> 0;
63
+ for (let i = 0; i < (inpSpec.raw_bits || 32); i++) {
64
+ if ((mask >>> i) & 1) {
65
+ out |= ((rawVal >>> i) & 1) << bitPos;
66
+ bitPos++;
67
+ }
68
+ }
69
+ return out;
70
+ }
71
+ return rawVal;
72
+ }
73
+
74
+ function normalizeTableEntry(val) {
75
+ if (!val || typeof val !== "object") return null;
76
+ const kind = val.kind?.ident ?? val.kind;
77
+ return {
78
+ kind,
79
+ next_q: val.next_q ?? 0,
80
+ exit: val.exit ?? 0,
81
+ shift: Array.isArray(val.shift) ? val.shift : (typeof val.shift === "number" ? [val.shift] : []),
82
+ emit_word: Array.isArray(val.emit_word)
83
+ ? val.emit_word
84
+ : (typeof val.emit_word === "number" ? [val.emit_word] : []),
85
+ emit_len: Array.isArray(val.emit_len)
86
+ ? val.emit_len
87
+ : (typeof val.emit_len === "number" ? [val.emit_len] : []),
88
+ // stack_table fields
89
+ shift_stream: val.shift_stream ?? 0,
90
+ pop_stack: val.pop_stack ?? 0,
91
+ push_stack_word: val.push_stack_word ?? 0,
92
+ push_stack_len: val.push_stack_len ?? 0,
93
+ emit_word_single: typeof val.emit_word === "number" ? val.emit_word : (Array.isArray(val.emit_word) ? (val.emit_word[0] ?? 0) : 0),
94
+ emit_len_single: typeof val.emit_len === "number" ? val.emit_len : (Array.isArray(val.emit_len) ? (val.emit_len[0] ?? 0) : 0)
95
+ };
96
+ }
97
+
98
+ function compileTableDecl(decl) {
99
+ const flat = new Map();
100
+ if (Array.isArray(decl.entries)) {
101
+ for (const row of decl.entries) {
102
+ flat.set(row.index, normalizeTableEntry(row.value));
103
+ }
104
+ } else if (decl.packedBase64 && decl.props?.stride) {
105
+ // Compact packed Int32 format: stride words per entry
106
+ // [kindCode (0=CONT,1=EXIT,2=NEED_MORE,3=FAIL), next_q, exit, shift0, ..., emitWord0, ..., emitLen0, ...]
107
+ const arr = unpackInt32Base64(decl.packedBase64);
108
+ const stride = decl.props.stride;
109
+ const nIn = (decl.props.inputs || []).length || 1;
110
+ const nOut = (decl.props.outputs || []).length || 1;
111
+ const kindNames = ["CONT", "EXIT", "NEED_MORE", "FAIL"];
112
+ const count = Math.floor(arr.length / stride);
113
+ for (let i = 0; i < count; i++) {
114
+ const base = i * stride;
115
+ const kCode = arr[base];
116
+ const nextQ = arr[base + 1];
117
+ const exit = arr[base + 2];
118
+ const shift = [];
119
+ for (let p = 0; p < nIn; p++) shift.push(arr[base + 3 + p]);
120
+ const emit_word = [];
121
+ for (let o = 0; o < nOut; o++) emit_word.push(arr[base + 3 + nIn + o] >>> 0);
122
+ const emit_len = [];
123
+ for (let o = 0; o < nOut; o++) emit_len.push(arr[base + 3 + nIn + nOut + o]);
124
+ flat.set(i, {
125
+ kind: kindNames[kCode] || "FAIL",
126
+ next_q: nextQ,
127
+ exit,
128
+ shift,
129
+ emit_word,
130
+ emit_len
131
+ });
132
+ }
133
+ }
134
+ return { decl, flat };
135
+ }
136
+
137
+ // --- Runtime Engine ---
138
+
139
+ export class KTVMRuntime {
140
+ constructor(mod, { quota = null } = {}) {
141
+ if (mod.layer !== "mono") {
142
+ throw new KTVMSchemaError("KTVMRuntime only executes concrete 'mono' modules; specialize first");
143
+ }
144
+ this.mod = mod;
145
+ this.quota = quota instanceof QuotaTracker ? quota : new QuotaTracker(quota || {});
146
+
147
+ this.schemaMap = new Map((mod.schemas || []).map((s) => [s.name, s]));
148
+ this.procMap = new Map((mod.procs || []).map((p) => [p.name, p]));
149
+ this.kernelMap = new Map((mod.kernels || []).map((k) => [k.name, k]));
150
+ this.tableMap = new Map((mod.tables || []).map((t) => [t.name, compileTableDecl(t)]));
151
+ this.plistCache = new Map();
152
+
153
+ this.nextNodeId = 1;
154
+ this.nextChanId = 1;
155
+ this.nextBarrierId = 1;
156
+ this.nextScopeId = 1;
157
+
158
+ this.scopes = new Map();
159
+ this._createScope(0, null);
160
+
161
+ this.telemetry = {
162
+ steps: 0,
163
+ peakActiveNodes: 0,
164
+ peakBitDequeBytes: 0,
165
+ splices: 0,
166
+ spliceBitsCopied: 0,
167
+ muxDemuxFusions: 0,
168
+ tableLookups: 0,
169
+ specRollbacks: 0,
170
+ specUpstreamAborts: 0,
171
+ specTailSplices: 0,
172
+ afterSettlements: 0
173
+ };
174
+ }
175
+
176
+ resolvePlist(schemaExpr) {
177
+ const key = JSON.stringify(schemaExpr);
178
+ let pl = this.plistCache.get(key);
179
+ if (!pl) {
180
+ pl = mooreMinimize(compileSchemaExprToPlist(schemaExpr, this.schemaMap, { allowOpen: false }), 0).plist;
181
+ this.plistCache.set(key, pl);
182
+ }
183
+ return pl;
184
+ }
185
+
186
+ _createScope(scopeId, parentId) {
187
+ this.scopes.set(scopeId, {
188
+ id: scopeId,
189
+ parent: parentId,
190
+ nodes: new Set(),
191
+ chans: new Set(),
192
+ barriers: new Set(),
193
+ children: new Set()
194
+ });
195
+ if (parentId !== null && this.scopes.has(parentId)) {
196
+ this.scopes.get(parentId).children.add(scopeId);
197
+ }
198
+ }
199
+
200
+ _allocChan(scopeId, plist, name = "") {
201
+ const id = this.nextChanId++;
202
+ const ch = new BitDeque(id, {
203
+ name: name || `%c${id}`,
204
+ prodSchema: plist,
205
+ prodNodeId: 0,
206
+ consSchema: plist,
207
+ consNodeId: 0,
208
+ aligned: true,
209
+ scope: scopeId,
210
+ quota: this.quota
211
+ });
212
+ const sc = this.scopes.get(scopeId);
213
+ if (sc) sc.chans.add(ch);
214
+ return ch;
215
+ }
216
+
217
+ _allocBarrier(scopeId, name = "") {
218
+ const b = {
219
+ id: this.nextBarrierId++,
220
+ name,
221
+ scope: scopeId,
222
+ guards: new Set(),
223
+ status: "PENDING" // PENDING | PASSED | FAILED
224
+ };
225
+ const sc = this.scopes.get(scopeId);
226
+ if (sc) sc.barriers.add(b);
227
+ return b;
228
+ }
229
+
230
+ _allocNode(scopeId, kind, props) {
231
+ this.quota.addNode();
232
+ const node = {
233
+ id: this.nextNodeId++,
234
+ kind,
235
+ scope: scopeId,
236
+ retired: false,
237
+ inputs: [],
238
+ outputs: [],
239
+ ...props
240
+ };
241
+ const sc = this.scopes.get(scopeId);
242
+ if (sc) sc.nodes.add(node);
243
+ for (const ch of node.inputs) {
244
+ if (ch) ch.cons = node;
245
+ }
246
+ for (const ch of node.outputs) {
247
+ if (ch) ch.prod = node;
248
+ }
249
+ return node;
250
+ }
251
+
252
+ _retireNode(node) {
253
+ if (!node || node.retired) return;
254
+ node.retired = true;
255
+ this.quota.removeNode();
256
+ const sc = this.scopes.get(node.scope);
257
+ if (sc) sc.nodes.delete(node);
258
+ // Clean up any kernel-local BitStacks and private unshift buffers
259
+ if (node.stacks) {
260
+ for (const st of node.stacks.values()) st.release();
261
+ node.stacks.clear();
262
+ }
263
+ if (node.unshiftBufs) {
264
+ for (const ub of node.unshiftBufs.values()) ub.release();
265
+ node.unshiftBufs.clear();
266
+ }
267
+ for (const ch of node.inputs) {
268
+ if (ch && ch.cons === node) ch.cons = null;
269
+ }
270
+ for (const ch of node.outputs) {
271
+ if (ch && ch.prod === node) ch.prod = null;
272
+ }
273
+ }
274
+
275
+ _rebindOutput(prodNode, oldCh, newCh) {
276
+ if (!prodNode) return;
277
+ for (let i = 0; i < prodNode.outputs.length; i++) {
278
+ if (prodNode.outputs[i] === oldCh) prodNode.outputs[i] = newCh;
279
+ }
280
+ if (prodNode.portMap) {
281
+ for (const [k, v] of prodNode.portMap.entries()) {
282
+ if (v === oldCh) prodNode.portMap.set(k, newCh);
283
+ }
284
+ }
285
+ if (prodNode.env) {
286
+ for (const [k, v] of prodNode.env.entries()) {
287
+ if (v === oldCh) prodNode.env.set(k, newCh);
288
+ }
289
+ }
290
+ if (prodNode.activeChild) {
291
+ for (const st of prodNode.activeChild.staged) {
292
+ if (st.parentOut === oldCh) st.parentOut = newCh;
293
+ }
294
+ }
295
+ }
296
+
297
+ _cancelInput(ch) {
298
+ if (!ch) return;
299
+ ch.cons = null;
300
+ // Note: if upstream producer belongs to an inner chain with no other consumers,
301
+ // releasing unread bits immediately frees quota.
302
+ if (!ch.isOpen) {
303
+ ch.release();
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Section 3.3 O(1) Zero-Copy Channel Splice: `splice(src -> dst)`.
309
+ */
310
+ _splice(src, dst) {
311
+ if (src === dst) return;
312
+ this.telemetry.splices += 1;
313
+
314
+ if (src.isFailed) {
315
+ dst.fail();
316
+ src.prod = null;
317
+ src.cons = null;
318
+ src.release();
319
+ return;
320
+ }
321
+
322
+ if (!src.aligned) {
323
+ throw new Error(`kTVM invariant violation: splice on unaligned source channel ${src.name}`);
324
+ }
325
+ if (!schemasEquivalent(src.consSchema, src.consNodeId, dst.prodSchema, dst.prodNodeId)) {
326
+ throw new Error(`kTVM invariant violation: splice schema mismatch (${src.name} -> ${dst.name})`);
327
+ }
328
+
329
+ let copied = 0;
330
+ if (dst.length === 0) {
331
+ dst.adoptBufferFrom(src);
332
+ } else if (src.length === 0) {
333
+ // Nothing to move from src
334
+ } else if (dst.length <= src.length) {
335
+ copied = src.unshiftFromDeque(dst);
336
+ dst.adoptBufferFrom(src);
337
+ } else {
338
+ copied = dst.pushFromDeque(src);
339
+ }
340
+ this.telemetry.spliceBitsCopied += copied;
341
+
342
+ // Transfer upstream producer obligation & status to `dst` while preserving `dst`'s consumer view
343
+ dst.prodSchema = src.prodSchema;
344
+ dst.prodNodeId = src.prodNodeId;
345
+ dst.status = src.status;
346
+ dst.prod = src.prod;
347
+
348
+ if (src.prod) {
349
+ this._rebindOutput(src.prod, src, dst);
350
+ }
351
+
352
+ src.prod = null;
353
+ src.cons = null;
354
+ src.release();
355
+ }
356
+
357
+ _destroyScope(scopeId) {
358
+ const sc = this.scopes.get(scopeId);
359
+ if (!sc) return;
360
+ // Destroy child scopes first (explicit iterative stack)
361
+ const stack = [scopeId];
362
+ const order = [];
363
+ while (stack.length > 0) {
364
+ const id = stack.pop();
365
+ const s = this.scopes.get(id);
366
+ if (!s) continue;
367
+ order.push(s);
368
+ for (const cid of s.children) stack.push(cid);
369
+ }
370
+ for (let i = order.length - 1; i >= 0; i--) {
371
+ const s = order[i];
372
+ for (const n of [...s.nodes]) {
373
+ if (n.kind === "spec" && n.activeChild) {
374
+ for (const t of n.activeChild.taps) t.replay.release();
375
+ }
376
+ this._retireNode(n);
377
+ }
378
+ for (const ch of [...s.chans]) {
379
+ ch.prod = null;
380
+ ch.cons = null;
381
+ ch.release();
382
+ }
383
+ s.chans.clear();
384
+ s.barriers.clear();
385
+ if (s.parent !== null && this.scopes.has(s.parent)) {
386
+ this.scopes.get(s.parent).children.delete(s.id);
387
+ }
388
+ this.scopes.delete(s.id);
389
+ }
390
+ }
391
+
392
+ // --- Network Instantiation ---
393
+
394
+ _instantiateBlock(stmts, scopeId, outerEnv, outerBarriers = new Map(), outerTokens = new Map()) {
395
+ const env = new Map(outerEnv);
396
+ const barriers = new Map(outerBarriers);
397
+ const tokens = new Map(outerTokens);
398
+
399
+ // Track which channels in this block are consumed/produced before a `switch`
400
+ const consumedVars = new Set();
401
+ const producedVars = new Set();
402
+
403
+ const markC = (v) => consumedVars.add(v);
404
+ const markP = (v) => producedVars.add(v);
405
+
406
+ for (const s of stmts) {
407
+ switch (s.op) {
408
+ case "chan": {
409
+ const pl = this.resolvePlist(s.schema);
410
+ env.set(s.name, this._allocChan(scopeId, pl, s.name));
411
+ break;
412
+ }
413
+ case "barrier": {
414
+ barriers.set(s.name, this._allocBarrier(scopeId, s.name));
415
+ break;
416
+ }
417
+ case "drain": {
418
+ const src = env.get(s.src);
419
+ const pl = this.resolvePlist(s.schema);
420
+ const bar = s.barrier ? barriers.get(s.barrier) : null;
421
+ markC(s.src);
422
+ const node = this._allocNode(scopeId, "drain", {
423
+ inputs: [src],
424
+ outputs: [],
425
+ schema: pl,
426
+ barrier: bar,
427
+ dpda: createDpdaSkip(pl, 0),
428
+ dpdaDone: false
429
+ });
430
+ if (bar) bar.guards.add(node);
431
+ break;
432
+ }
433
+ case "gate": {
434
+ const bar = barriers.get(s.barrier);
435
+ const src = env.get(s.src);
436
+ const dst = env.get(s.dst);
437
+ markC(s.src);
438
+ markP(s.dst);
439
+ this._allocNode(scopeId, "gate", {
440
+ inputs: [src],
441
+ outputs: [dst],
442
+ barrier: bar
443
+ });
444
+ break;
445
+ }
446
+ case "splice": {
447
+ const src = env.get(s.src);
448
+ const dst = env.get(s.dst);
449
+ markC(s.src);
450
+ markP(s.dst);
451
+ this._allocNode(scopeId, "splice", {
452
+ inputs: [src],
453
+ outputs: [dst]
454
+ });
455
+ break;
456
+ }
457
+ case "coerce": {
458
+ const src = env.get(s.src);
459
+ const dst = env.get(s.dst);
460
+ const sPl = this.resolvePlist(s.srcSchema);
461
+ const dPl = this.resolvePlist(s.dstSchema);
462
+ markC(s.src);
463
+ markP(s.dst);
464
+ this._allocNode(scopeId, "coerce", {
465
+ inputs: [src],
466
+ outputs: [dst],
467
+ srcSchema: sPl,
468
+ dstSchema: dPl,
469
+ dpda: null
470
+ });
471
+ break;
472
+ }
473
+ case "const_unit": {
474
+ const dst = env.get(s.dst);
475
+ markP(s.dst);
476
+ this._allocNode(scopeId, "const_unit", {
477
+ inputs: [],
478
+ outputs: [dst]
479
+ });
480
+ break;
481
+ }
482
+ case "tee": {
483
+ const src = env.get(s.src);
484
+ const dsts = s.dsts.map((v) => env.get(v));
485
+ markC(s.src);
486
+ for (const v of s.dsts) markP(v);
487
+ this._allocNode(scopeId, "tee", {
488
+ inputs: [src],
489
+ outputs: dsts
490
+ });
491
+ break;
492
+ }
493
+ case "wrap": {
494
+ const src = env.get(s.src);
495
+ const dst = env.get(s.dst);
496
+ markC(s.src);
497
+ markP(s.dst);
498
+ this._allocNode(scopeId, "wrap", {
499
+ inputs: [src],
500
+ outputs: [dst],
501
+ tag: s.tag
502
+ });
503
+ break;
504
+ }
505
+ case "match": {
506
+ const src = env.get(s.src);
507
+ const dst = env.get(s.dst);
508
+ markC(s.src);
509
+ markP(s.dst);
510
+ this._allocNode(scopeId, "match", {
511
+ inputs: [src],
512
+ outputs: [dst],
513
+ tag: s.tag
514
+ });
515
+ break;
516
+ }
517
+ case "demux": {
518
+ const src = env.get(s.src);
519
+ const pl = this.resolvePlist(s.schema);
520
+ const pf = productFields(pl, 0);
521
+ const byLabel = new Map(s.fields.map((f) => [f.label, env.get(f.name)]));
522
+ const orderedOuts = pf.map((f) => byLabel.get(f.label));
523
+ markC(s.src);
524
+ for (const f of s.fields) markP(f.name);
525
+ this._allocNode(scopeId, "demux", {
526
+ inputs: [src],
527
+ outputs: orderedOuts,
528
+ schema: pl,
529
+ fields: pf,
530
+ fieldIdx: 0,
531
+ dpda: null
532
+ });
533
+ break;
534
+ }
535
+ case "mux": {
536
+ const dst = env.get(s.dst);
537
+ const pl = this.resolvePlist(s.schema);
538
+ const pf = productFields(pl, 0);
539
+ const byLabel = new Map(s.fields.map((f) => [f.label, env.get(f.name)]));
540
+ const orderedIns = pf.map((f) => byLabel.get(f.label));
541
+ for (const f of s.fields) markC(f.name);
542
+ markP(s.dst);
543
+ this._allocNode(scopeId, "mux", {
544
+ inputs: orderedIns,
545
+ outputs: [dst],
546
+ schema: pl,
547
+ fields: pf,
548
+ fieldIdx: 0
549
+ });
550
+ break;
551
+ }
552
+ case "spawn": {
553
+ const ins = s.inputs.map((v) => env.get(v));
554
+ const outs = s.outputs.map((v) => env.get(v));
555
+ for (const v of s.inputs) markC(v);
556
+ for (const v of s.outputs) markP(v);
557
+ const afterToken = s.after ? tokens.get(s.after) : null;
558
+ const node = this._allocNode(scopeId, "spawn", {
559
+ inputs: ins,
560
+ outputs: outs,
561
+ target: s.target,
562
+ afterToken
563
+ });
564
+ if (s.token) {
565
+ tokens.set(s.token, { outputs: [...outs], settled: false, originNode: node });
566
+ }
567
+ break;
568
+ }
569
+ case "exec": {
570
+ const ins = s.inputs.map((v) => env.get(v));
571
+ const outs = s.outputs.map((v) => env.get(v));
572
+ for (const v of s.inputs) markC(v);
573
+ for (const v of s.outputs) markP(v);
574
+ this._instantiateKernel(s.target, scopeId, ins, outs);
575
+ break;
576
+ }
577
+ case "switch": {
578
+ // Determine the exact outer channels consumed/produced by this switch's arms
579
+ // (supports both terminal switches and mid-block / nested switches!).
580
+ const firstBody = s.arms.length > 0 ? s.arms[0].body : (s.defaultBody || []);
581
+ const { cons: swCons, prod: swProd } = collectSwitchOuterIO(firstBody, env);
582
+ const remIn = [...swCons].map((v) => env.get(v));
583
+ const remOut = [...swProd].map((v) => env.get(v));
584
+ for (const v of swCons) markC(v);
585
+ for (const v of swProd) markP(v);
586
+ const inspectChans = s.inputs.map((v) => env.get(v));
587
+ this._allocNode(scopeId, "switch", {
588
+ inputs: remIn,
589
+ outputs: remOut,
590
+ inspectVars: s.inputs,
591
+ inspectChans,
592
+ arms: s.arms,
593
+ defaultBody: s.defaultBody,
594
+ env: new Map(env),
595
+ barriers: new Map(barriers),
596
+ tokens: new Map(tokens)
597
+ });
598
+ break;
599
+ }
600
+ case "spec": {
601
+ const ins = s.inputs.map((v) => env.get(v));
602
+ const outs = s.outputs.map((v) => env.get(v));
603
+ for (const v of s.inputs) markC(v);
604
+ for (const v of s.outputs) markP(v);
605
+ this._allocNode(scopeId, "spec", {
606
+ inputs: ins,
607
+ outputs: outs,
608
+ inVars: s.inputs,
609
+ outVars: s.outputs,
610
+ branches: s.branches,
611
+ branchIdx: 0,
612
+ activeChild: null
613
+ });
614
+ break;
615
+ }
616
+ default:
617
+ throw new Error(`Unsupported runtime instruction '${s.op}' in mono kTVM`);
618
+ }
619
+ }
620
+ }
621
+
622
+ _instantiateKernel(kernelName, scopeId, ins, outs) {
623
+ const kDecl = this.kernelMap.get(kernelName);
624
+ if (!kDecl) throw new Error(`Unknown kernel '${kernelName}'`);
625
+ const portMap = new Map();
626
+ const ownedInputs = new Set();
627
+ const ownedOutputs = new Set();
628
+ for (let i = 0; i < kDecl.inputs.length; i++) {
629
+ portMap.set(kDecl.inputs[i].name, ins[i]);
630
+ ownedInputs.add(kDecl.inputs[i].name);
631
+ }
632
+ for (let i = 0; i < kDecl.outputs.length; i++) {
633
+ portMap.set(kDecl.outputs[i].name, outs[i]);
634
+ ownedOutputs.add(kDecl.outputs[i].name);
635
+ }
636
+ const regs = new Map((kDecl.regs || []).map((r) => [r.name, r.init ?? 0]));
637
+ const stacks = new Map((kDecl.stacks || []).map((s) => [s.name, new BitStack(this.quota)]));
638
+ const blockMap = new Map(kDecl.blocks.map((b) => [b.label, b]));
639
+
640
+ return this._allocNode(scopeId, "kernel", {
641
+ inputs: [...ins],
642
+ outputs: [...outs],
643
+ kernelDecl: kDecl,
644
+ blockMap,
645
+ pc: "entry",
646
+ stmtIdx: 0,
647
+ regs,
648
+ stacks,
649
+ unshiftBufs: new Map(),
650
+ temps: new Map(),
651
+ portMap,
652
+ ownedInputs,
653
+ ownedOutputs,
654
+ pendingDpda: null,
655
+ yieldThreshold: 64
656
+ });
657
+ }
658
+
659
+ // --- Small-Step Node Transitions ---
660
+
661
+ _stepNode(node) {
662
+ this.quota.tickStep();
663
+ this.telemetry.steps = this.quota.steps;
664
+
665
+ switch (node.kind) {
666
+ case "const_unit":
667
+ return this._stepConstUnit(node);
668
+ case "splice":
669
+ return this._stepSplice(node);
670
+ case "coerce":
671
+ return this._stepCoerce(node);
672
+ case "wrap":
673
+ return this._stepWrap(node);
674
+ case "match":
675
+ return this._stepMatch(node);
676
+ case "demux":
677
+ return this._stepDemux(node);
678
+ case "mux":
679
+ return this._stepMux(node);
680
+ case "tee":
681
+ return this._stepTee(node);
682
+ case "drain":
683
+ return this._stepDrain(node);
684
+ case "gate":
685
+ return this._stepGate(node);
686
+ case "switch":
687
+ return this._stepSwitch(node);
688
+ case "spec":
689
+ return this._stepSpec(node);
690
+ case "tap":
691
+ return this._stepTap(node);
692
+ case "spawn":
693
+ return this._stepSpawn(node);
694
+ case "kernel":
695
+ return this._stepKernel(node);
696
+ default:
697
+ throw new Error(`Unknown node kind '${node.kind}'`);
698
+ }
699
+ }
700
+
701
+ _stepConstUnit(node) {
702
+ const out = node.outputs[0];
703
+ this._retireNode(node);
704
+ out.close();
705
+ return null;
706
+ }
707
+
708
+ _stepSplice(node) {
709
+ const src = node.inputs[0];
710
+ const dst = node.outputs[0];
711
+ this._retireNode(node);
712
+ this._splice(src, dst);
713
+ return null;
714
+ }
715
+
716
+ _stepCoerce(node) {
717
+ const src = node.inputs[0];
718
+ const dst = node.outputs[0];
719
+ if (!node.dpda) {
720
+ if (src.aligned && schemasEquivalent(src.consSchema, src.consNodeId, dst.prodSchema, dst.prodNodeId)) {
721
+ this._retireNode(node);
722
+ this._splice(src, dst);
723
+ return null;
724
+ }
725
+ node.dpda = createDpdaCoerce(src.consSchema, src.consNodeId, dst.prodSchema, dst.prodNodeId);
726
+ }
727
+ const res = stepDpdaCoerce(src, dst, node.dpda);
728
+ if (res === DPDA_RESULT.NEED_BITS) {
729
+ if (src.isOpen) return { needPull: src };
730
+ this._retireNode(node);
731
+ dst.fail();
732
+ this._cancelInput(src);
733
+ return null;
734
+ }
735
+ if (res === DPDA_RESULT.FAILED) {
736
+ this._retireNode(node);
737
+ dst.fail();
738
+ this._cancelInput(src);
739
+ return null;
740
+ }
741
+ // DONE: ensure src settles cleanly (CLOSED, 0 leftover bits)
742
+ if (src.isOpen) return { needPull: src };
743
+ if (src.isFailed || src.length > 0) {
744
+ this._retireNode(node);
745
+ dst.fail();
746
+ this._cancelInput(src);
747
+ return null;
748
+ }
749
+ this._retireNode(node);
750
+ src.release();
751
+ dst.close();
752
+ return null;
753
+ }
754
+
755
+ _stepWrap(node) {
756
+ const src = node.inputs[0];
757
+ const dst = node.outputs[0];
758
+ const info = unionTagInfo(dst.prodSchema, dst.prodNodeId, node.tag);
759
+ if (!info) {
760
+ this._retireNode(node);
761
+ dst.fail();
762
+ this._cancelInput(src);
763
+ return null;
764
+ }
765
+ if (info.width > 0) {
766
+ dst.pushBits(info.ordinal, info.width);
767
+ }
768
+ dst.prodNodeId = info.targetId;
769
+
770
+ if (src.aligned && schemasEquivalent(src.consSchema, src.consNodeId, dst.prodSchema, dst.prodNodeId)) {
771
+ this._retireNode(node);
772
+ this._splice(src, dst);
773
+ return null;
774
+ }
775
+ // Degrade in-place to `coerce`
776
+ node.kind = "coerce";
777
+ node.dpda = null;
778
+ return null;
779
+ }
780
+
781
+ _stepMatch(node) {
782
+ const src = node.inputs[0];
783
+ const dst = node.outputs[0];
784
+ const info = unionTagInfo(src.consSchema, src.consNodeId, node.tag);
785
+ if (!info) {
786
+ this._retireNode(node);
787
+ dst.fail();
788
+ this._cancelInput(src);
789
+ return null;
790
+ }
791
+ if (info.width > 0) {
792
+ if (src.length < info.width) {
793
+ if (src.isOpen) return { needPull: src };
794
+ this._retireNode(node);
795
+ dst.fail();
796
+ this._cancelInput(src);
797
+ return null;
798
+ }
799
+ const ord = src.peekBits(info.width);
800
+ if (ord !== info.ordinal) {
801
+ this._retireNode(node);
802
+ dst.fail();
803
+ this._cancelInput(src);
804
+ return null;
805
+ }
806
+ src.shiftBits(info.width);
807
+ }
808
+ src.consNodeId = info.targetId;
809
+ src.aligned = true;
810
+
811
+ if (schemasEquivalent(src.consSchema, src.consNodeId, dst.prodSchema, dst.prodNodeId)) {
812
+ this._retireNode(node);
813
+ this._splice(src, dst);
814
+ return null;
815
+ }
816
+ node.kind = "coerce";
817
+ node.dpda = null;
818
+ return null;
819
+ }
820
+
821
+ _stepDemux(node) {
822
+ const src = node.inputs[0];
823
+ const outs = node.outputs;
824
+ const fields = node.fields;
825
+
826
+ // Same-scope MUX -> DEMUX O(1) bundle fusion!
827
+ if (
828
+ node.fieldIdx === 0 &&
829
+ (outs.length === 0 || outs[0].length === 0) &&
830
+ src.length === 0 &&
831
+ src.aligned &&
832
+ src.prod &&
833
+ src.prod.kind === "mux" &&
834
+ src.prod.scope === node.scope &&
835
+ src.prod.fieldIdx === 0 &&
836
+ schemasEquivalent(src.consSchema, src.consNodeId, src.prod.schema, 0)
837
+ ) {
838
+ const muxNode = src.prod;
839
+ const muxIns = [...muxNode.inputs];
840
+ const demuxOuts = [...outs];
841
+ this._retireNode(muxNode);
842
+ this._retireNode(node);
843
+ src.prod = null;
844
+ src.cons = null;
845
+ src.release();
846
+ for (let i = 0; i < demuxOuts.length; i++) {
847
+ this._splice(muxIns[i], demuxOuts[i]);
848
+ }
849
+ this.telemetry.muxDemuxFusions += 1;
850
+ return null;
851
+ }
852
+
853
+ if (fields.length === 0) {
854
+ if (src.isOpen) return { needPull: src };
855
+ this._retireNode(node);
856
+ src.release();
857
+ return null;
858
+ }
859
+
860
+ if (fields.length === 1) {
861
+ src.consSchema = node.schema;
862
+ src.consNodeId = fields[0].targetId;
863
+ src.aligned = true;
864
+ const dst0 = outs[0];
865
+ this._retireNode(node);
866
+ this._splice(src, dst0);
867
+ return null;
868
+ }
869
+
870
+ // Stream fields 0 .. m-2 with DPDA copy, then zero-copy splice final field m-1!
871
+ while (node.fieldIdx < fields.length - 1) {
872
+ const i = node.fieldIdx;
873
+ const dst = outs[i];
874
+ if (!node.dpda) {
875
+ node.dpda = createDpdaCopy(node.schema, fields[i].targetId);
876
+ }
877
+ const res = stepDpdaCopy(src, dst, node.dpda);
878
+ if (res === DPDA_RESULT.NEED_BITS) {
879
+ if (src.isOpen) return { needPull: src };
880
+ this._failRemainingDemux(node, i);
881
+ return null;
882
+ }
883
+ if (res === DPDA_RESULT.FAILED) {
884
+ this._failRemainingDemux(node, i);
885
+ return null;
886
+ }
887
+ // Field i complete!
888
+ dst.close();
889
+ node.dpda = null;
890
+ node.fieldIdx += 1;
891
+ }
892
+
893
+ // Final field m-1: `src` now sits at exact aligned boundary of fields[m-1]!
894
+ const lastIdx = fields.length - 1;
895
+ src.consSchema = node.schema;
896
+ src.consNodeId = fields[lastIdx].targetId;
897
+ src.aligned = true;
898
+ const lastDst = outs[lastIdx];
899
+ this._retireNode(node);
900
+ this._splice(src, lastDst);
901
+ return null;
902
+ }
903
+
904
+ _failRemainingDemux(node, fromIdx) {
905
+ const src = node.inputs[0];
906
+ const outs = [...node.outputs];
907
+ this._retireNode(node);
908
+ for (let j = fromIdx; j < outs.length; j++) {
909
+ outs[j].fail();
910
+ }
911
+ this._cancelInput(src);
912
+ }
913
+
914
+ _stepMux(node) {
915
+ const ins = node.inputs;
916
+ const dst = node.outputs[0];
917
+ const fields = node.fields;
918
+
919
+ // Symmetric same-scope MUX -> DEMUX O(1) bundle fusion!
920
+ if (
921
+ node.fieldIdx === 0 &&
922
+ dst.length === 0 &&
923
+ dst.aligned &&
924
+ dst.cons &&
925
+ dst.cons.kind === "demux" &&
926
+ dst.cons.scope === node.scope &&
927
+ dst.cons.fieldIdx === 0 &&
928
+ (dst.cons.outputs.length === 0 || dst.cons.outputs[0].length === 0) &&
929
+ schemasEquivalent(dst.consSchema, dst.consNodeId, node.schema, 0) &&
930
+ schemasEquivalent(dst.cons.schema, 0, node.schema, 0)
931
+ ) {
932
+ const demuxNode = dst.cons;
933
+ const muxIns = [...ins];
934
+ const demuxOuts = [...demuxNode.outputs];
935
+ this._retireNode(node);
936
+ this._retireNode(demuxNode);
937
+ dst.prod = null;
938
+ dst.cons = null;
939
+ dst.release();
940
+ for (let i = 0; i < demuxOuts.length; i++) {
941
+ this._splice(muxIns[i], demuxOuts[i]);
942
+ }
943
+ this.telemetry.muxDemuxFusions += 1;
944
+ return null;
945
+ }
946
+
947
+ if (fields.length === 0) {
948
+ this._retireNode(node);
949
+ dst.close();
950
+ return null;
951
+ }
952
+
953
+ if (fields.length === 1) {
954
+ const in0 = ins[0];
955
+ dst.prodSchema = node.schema;
956
+ dst.prodNodeId = fields[0].targetId;
957
+ this._retireNode(node);
958
+ this._splice(in0, dst);
959
+ return null;
960
+ }
961
+
962
+ // Stream fields 0 .. m-2, then O(1) tail-splice final field m-1!
963
+ while (node.fieldIdx < fields.length - 1) {
964
+ const i = node.fieldIdx;
965
+ const src = ins[i];
966
+ if (src.length > 0) {
967
+ dst.pushFromDeque(src);
968
+ }
969
+ if (src.isFailed) {
970
+ this._retireNode(node);
971
+ dst.fail();
972
+ for (let j = i; j < ins.length; j++) this._cancelInput(ins[j]);
973
+ return null;
974
+ }
975
+ if (src.isOpen) {
976
+ return { needPull: src };
977
+ }
978
+ // src is CLOSED and empty
979
+ src.cons = null;
980
+ src.release();
981
+ node.fieldIdx += 1;
982
+ }
983
+
984
+ // Final field m-1: narrow prodSchema and execute O(1) tail-splice!
985
+ const lastIdx = fields.length - 1;
986
+ const lastSrc = ins[lastIdx];
987
+ dst.prodSchema = node.schema;
988
+ dst.prodNodeId = fields[lastIdx].targetId;
989
+ this._retireNode(node);
990
+ this._splice(lastSrc, dst);
991
+ return null;
992
+ }
993
+
994
+ _stepTee(node) {
995
+ const src = node.inputs[0];
996
+ const liveOuts = node.outputs.filter((o) => o && o.isOpen);
997
+
998
+ if (liveOuts.length === 0) {
999
+ this._retireNode(node);
1000
+ this._cancelInput(src);
1001
+ return null;
1002
+ }
1003
+
1004
+ // Single-survivor splice degradation
1005
+ if (
1006
+ liveOuts.length === 1 &&
1007
+ src.aligned &&
1008
+ schemasEquivalent(src.consSchema, src.consNodeId, liveOuts[0].prodSchema, liveOuts[0].prodNodeId)
1009
+ ) {
1010
+ const only = liveOuts[0];
1011
+ this._retireNode(node);
1012
+ this._splice(src, only);
1013
+ return null;
1014
+ }
1015
+
1016
+ if (src.length > 0) {
1017
+ const chunk = src.length > 30 ? 30 : src.length;
1018
+ const bits = src.shiftBits(chunk);
1019
+ for (const o of liveOuts) o.pushBits(bits, chunk);
1020
+ // After transferring bits, if src still has bits we can transfer up to 256 bits per step
1021
+ let burst = chunk;
1022
+ while (src.length > 0 && burst < 256) {
1023
+ const c = src.length > 30 ? 30 : src.length;
1024
+ const b = src.shiftBits(c);
1025
+ for (const o of liveOuts) o.pushBits(b, c);
1026
+ burst += c;
1027
+ }
1028
+ return null;
1029
+ }
1030
+
1031
+ if (src.isOpen) {
1032
+ return { needPull: src };
1033
+ }
1034
+ if (src.isClosed) {
1035
+ this._retireNode(node);
1036
+ src.release();
1037
+ for (const o of liveOuts) o.close();
1038
+ return null;
1039
+ }
1040
+ // src.isFailed
1041
+ this._retireNode(node);
1042
+ src.release();
1043
+ for (const o of liveOuts) o.fail();
1044
+ return null;
1045
+ }
1046
+
1047
+ _stepDrain(node) {
1048
+ const src = node.inputs[0];
1049
+ const bar = node.barrier;
1050
+
1051
+ if (!node.dpdaDone) {
1052
+ const res = stepDpdaSkip(src, node.dpda);
1053
+ if (res === DPDA_RESULT.NEED_BITS) {
1054
+ if (src.isOpen) return { needPull: src };
1055
+ this._failBarrierDrain(node);
1056
+ return null;
1057
+ }
1058
+ if (res === DPDA_RESULT.FAILED) {
1059
+ this._failBarrierDrain(node);
1060
+ return null;
1061
+ }
1062
+ node.dpdaDone = true;
1063
+ }
1064
+
1065
+ // Verify source reaches CLOSED cleanly (catches failed unit producers!)
1066
+ if (src.isOpen) return { needPull: src };
1067
+ if (src.isFailed || src.length > 0) {
1068
+ this._failBarrierDrain(node);
1069
+ return null;
1070
+ }
1071
+
1072
+ this._retireNode(node);
1073
+ src.release();
1074
+ if (bar) {
1075
+ bar.guards.delete(node);
1076
+ if (bar.status === "PENDING" && bar.guards.size === 0) {
1077
+ bar.status = "PASSED";
1078
+ }
1079
+ }
1080
+ return null;
1081
+ }
1082
+
1083
+ _failBarrierDrain(node) {
1084
+ const src = node.inputs[0];
1085
+ const bar = node.barrier;
1086
+ this._retireNode(node);
1087
+ this._cancelInput(src);
1088
+ if (bar) {
1089
+ bar.guards.delete(node);
1090
+ bar.status = "FAILED";
1091
+ }
1092
+ }
1093
+
1094
+ _stepGate(node) {
1095
+ const bar = node.barrier;
1096
+ const src = node.inputs[0];
1097
+ const dst = node.outputs[0];
1098
+
1099
+ if (bar.status === "PENDING") {
1100
+ if (bar.guards.size === 0) {
1101
+ bar.status = "PASSED";
1102
+ } else {
1103
+ // Drive first pending guard drain directly!
1104
+ const nextGuard = bar.guards.values().next().value;
1105
+ return { needStepNode: nextGuard };
1106
+ }
1107
+ }
1108
+
1109
+ if (bar.status === "PASSED") {
1110
+ this._retireNode(node);
1111
+ this._splice(src, dst);
1112
+ return null;
1113
+ }
1114
+
1115
+ // bar.status === "FAILED"
1116
+ this._retireNode(node);
1117
+ dst.fail();
1118
+ this._cancelInput(src);
1119
+ return null;
1120
+ }
1121
+
1122
+ _stepSwitch(node) {
1123
+ const inspectChans = node.inspectChans;
1124
+ const tags = new Array(inspectChans.length).fill(null);
1125
+
1126
+ // Determine which positions are actually tested by any arm
1127
+ const tested = new Uint8Array(inspectChans.length);
1128
+ for (const arm of node.arms) {
1129
+ for (let j = 0; j < arm.patterns.length; j++) {
1130
+ if (arm.patterns[j].kind === "tag") tested[j] = 1;
1131
+ }
1132
+ }
1133
+
1134
+ for (let j = 0; j < inspectChans.length; j++) {
1135
+ if (!tested[j]) continue;
1136
+ const ch = inspectChans[j];
1137
+ const [kind, edges] = ch.consSchema[ch.consNodeId];
1138
+ if (kind !== "closed-union" || edges.length === 0) {
1139
+ return this._failSwitch(node);
1140
+ }
1141
+ const w = choiceWidth(edges.length);
1142
+ let ord = 0;
1143
+ if (w > 0) {
1144
+ if (ch.length < w) {
1145
+ if (ch.isOpen) return { needPull: ch };
1146
+ return this._failSwitch(node);
1147
+ }
1148
+ ord = ch.peekBits(w);
1149
+ }
1150
+ if (ord >= edges.length) {
1151
+ return this._failSwitch(node);
1152
+ }
1153
+ tags[j] = edges[ord][0];
1154
+ }
1155
+
1156
+ // Match first matching arm (patterns are prefix-disjoint)
1157
+ let chosenBody = null;
1158
+ for (const arm of node.arms) {
1159
+ let ok = true;
1160
+ for (let j = 0; j < arm.patterns.length; j++) {
1161
+ const p = arm.patterns[j];
1162
+ if (p.kind === "tag" && tags[j] !== p.tag) {
1163
+ ok = false;
1164
+ break;
1165
+ }
1166
+ }
1167
+ if (ok) {
1168
+ chosenBody = arm.body;
1169
+ break;
1170
+ }
1171
+ }
1172
+ if (!chosenBody) chosenBody = node.defaultBody;
1173
+ if (!chosenBody) return this._failSwitch(node);
1174
+
1175
+ const { scope, env, barriers, tokens } = node;
1176
+ this._retireNode(node);
1177
+ this._instantiateBlock(chosenBody, scope, env, barriers, tokens);
1178
+ return null;
1179
+ }
1180
+
1181
+ _failSwitch(node) {
1182
+ const outs = [...node.outputs];
1183
+ const ins = [...node.inputs];
1184
+ this._retireNode(node);
1185
+ for (const o of outs) o.fail();
1186
+ for (const i of ins) this._cancelInput(i);
1187
+ return null;
1188
+ }
1189
+
1190
+ _stepTap(node) {
1191
+ const parentCh = node.parentCh;
1192
+ const childCh = node.outputs[0];
1193
+ const replay = node.replay;
1194
+
1195
+ if (parentCh.length > 0) {
1196
+ const chunk = parentCh.length > 30 ? 30 : parentCh.length;
1197
+ const bits = parentCh.shiftBits(chunk);
1198
+ replay.pushBits(bits, chunk);
1199
+ childCh.pushBits(bits, chunk);
1200
+ return null;
1201
+ }
1202
+ if (parentCh.isOpen) {
1203
+ return { needPull: parentCh };
1204
+ }
1205
+ if (parentCh.isClosed) {
1206
+ this._retireNode(node);
1207
+ childCh.close();
1208
+ return null;
1209
+ }
1210
+ // parentCh.isFailed
1211
+ node.sawUpstreamFailure = true;
1212
+ this._retireNode(node);
1213
+ childCh.fail();
1214
+ return null;
1215
+ }
1216
+
1217
+ _stepSpec(node) {
1218
+ const branches = node.branches;
1219
+ const parentIns = node.inputs;
1220
+ const parentOuts = node.outputs;
1221
+
1222
+ // Empty choice -> fail immediately
1223
+ if (branches.length === 0) {
1224
+ this._retireNode(node);
1225
+ for (const o of parentOuts) o.fail();
1226
+ for (const i of parentIns) this._cancelInput(i);
1227
+ return null;
1228
+ }
1229
+
1230
+ // Immediate upstream failure check
1231
+ for (const pIn of parentIns) {
1232
+ if (pIn.isFailed) {
1233
+ this.telemetry.specUpstreamAborts += 1;
1234
+ if (node.activeChild) this._destroyScope(node.activeChild.scopeId);
1235
+ this._retireNode(node);
1236
+ for (const o of parentOuts) o.fail();
1237
+ return null;
1238
+ }
1239
+ }
1240
+
1241
+ if (!node.activeChild) {
1242
+ // Rule 3: Last-branch tail splice!
1243
+ if (node.branchIdx === branches.length - 1) {
1244
+ this.telemetry.specTailSplices += 1;
1245
+ const br = branches[node.branchIdx];
1246
+ const scope = node.scope;
1247
+ const env = new Map();
1248
+ for (let i = 0; i < node.inVars.length; i++) env.set(node.inVars[i], parentIns[i]);
1249
+ for (let i = 0; i < node.outVars.length; i++) env.set(node.outVars[i], parentOuts[i]);
1250
+ this._retireNode(node);
1251
+ this._instantiateBlock(br.body, scope, env);
1252
+ return null;
1253
+ }
1254
+
1255
+ // Speculative branch i < k - 1: create child scope + TAPs + staging outputs
1256
+ const childScopeId = this.nextScopeId++;
1257
+ this._createScope(childScopeId, node.scope);
1258
+
1259
+ const taps = [];
1260
+ const env = new Map();
1261
+ for (let i = 0; i < parentIns.length; i++) {
1262
+ const pIn = parentIns[i];
1263
+ const replay = new BitDeque(this.nextChanId++, {
1264
+ name: `%replay_${pIn.name}`,
1265
+ prodSchema: pIn.consSchema,
1266
+ prodNodeId: pIn.consNodeId,
1267
+ consSchema: pIn.consSchema,
1268
+ consNodeId: pIn.consNodeId,
1269
+ scope: childScopeId,
1270
+ quota: this.quota
1271
+ });
1272
+ const childIn = new BitDeque(this.nextChanId++, {
1273
+ name: `%tap_${pIn.name}`,
1274
+ prodSchema: pIn.consSchema,
1275
+ prodNodeId: pIn.consNodeId,
1276
+ consSchema: pIn.consSchema,
1277
+ consNodeId: pIn.consNodeId,
1278
+ aligned: pIn.aligned,
1279
+ scope: childScopeId,
1280
+ quota: this.quota
1281
+ });
1282
+ this.scopes.get(childScopeId).chans.add(childIn);
1283
+ const tapNode = this._allocNode(childScopeId, "tap", {
1284
+ inputs: [],
1285
+ outputs: [childIn],
1286
+ parentCh: pIn,
1287
+ replay,
1288
+ sawUpstreamFailure: false
1289
+ });
1290
+ pIn.cons = tapNode;
1291
+ taps.push({ parentCh: pIn, childCh: childIn, replay, tapNode });
1292
+ env.set(node.inVars[i], childIn);
1293
+ }
1294
+
1295
+ const staged = [];
1296
+ for (let i = 0; i < parentOuts.length; i++) {
1297
+ const pOut = parentOuts[i];
1298
+ const childOut = new BitDeque(this.nextChanId++, {
1299
+ name: `%stage_${pOut.name}`,
1300
+ prodSchema: pOut.prodSchema,
1301
+ prodNodeId: pOut.prodNodeId,
1302
+ consSchema: pOut.prodSchema,
1303
+ consNodeId: pOut.prodNodeId,
1304
+ aligned: true,
1305
+ scope: childScopeId,
1306
+ quota: this.quota
1307
+ });
1308
+ this.scopes.get(childScopeId).chans.add(childOut);
1309
+ staged.push({ childOut, parentOut: pOut });
1310
+ env.set(node.outVars[i], childOut);
1311
+ }
1312
+
1313
+ this._instantiateBlock(branches[node.branchIdx].body, childScopeId, env);
1314
+ node.activeChild = { scopeId: childScopeId, taps, staged };
1315
+ }
1316
+
1317
+ const { scopeId, taps, staged } = node.activeChild;
1318
+
1319
+ // Check failure of any staging output
1320
+ const anyFailed = staged.some((st) => st.childOut.isFailed);
1321
+ if (anyFailed) {
1322
+ const upstreamFailed = taps.some((t) => t.parentCh.isFailed || t.tapNode.sawUpstreamFailure);
1323
+ if (upstreamFailed) {
1324
+ // Rule 1 (Upstream Failure Abort): fail outputs immediately, DO NOT try branch i+1!
1325
+ this.telemetry.specUpstreamAborts += 1;
1326
+ for (const t of taps) {
1327
+ if (t.parentCh.cons === t.tapNode) t.parentCh.cons = null;
1328
+ t.replay.release();
1329
+ }
1330
+ node.activeChild = null;
1331
+ this._destroyScope(scopeId);
1332
+ this._retireNode(node);
1333
+ for (const o of parentOuts) o.fail();
1334
+ return null;
1335
+ }
1336
+
1337
+ // Local mismatch rollback: destroy child scope, restore parent inputs bit-for-bit!
1338
+ this.telemetry.specRollbacks += 1;
1339
+ for (const t of taps) {
1340
+ if (t.parentCh.cons === t.tapNode) t.parentCh.cons = node;
1341
+ }
1342
+ node.activeChild = null;
1343
+ this._destroyScope(scopeId);
1344
+ for (const t of taps) {
1345
+ t.parentCh.unshiftFromDeque(t.replay);
1346
+ t.replay.release();
1347
+ }
1348
+ node.branchIdx += 1;
1349
+ return null;
1350
+ }
1351
+
1352
+ // Check commit (all staging outputs CLOSED)
1353
+ const allClosed = staged.every((st) => st.childOut.isClosed);
1354
+ if (allClosed) {
1355
+ for (const t of taps) {
1356
+ // If branch left unread tapped bits, return them to parentCh
1357
+ if (t.childCh.length > 0) {
1358
+ t.parentCh.unshiftFromDeque(t.childCh);
1359
+ }
1360
+ if (t.parentCh.cons === t.tapNode) t.parentCh.cons = null;
1361
+ t.replay.release();
1362
+ }
1363
+ // Splice staged outputs to parent outputs BEFORE destroying child scope!
1364
+ const splicePairs = staged.map((st) => ({ src: st.childOut, dst: st.parentOut }));
1365
+ const childSc = this.scopes.get(scopeId);
1366
+ for (const p of splicePairs) {
1367
+ if (childSc) childSc.chans.delete(p.src);
1368
+ }
1369
+ node.activeChild = null;
1370
+ this._retireNode(node);
1371
+ for (const p of splicePairs) {
1372
+ this._splice(p.src, p.dst);
1373
+ }
1374
+ this._destroyScope(scopeId);
1375
+ return null;
1376
+ }
1377
+
1378
+ // Drive first still-OPEN staging output!
1379
+ const nextOpen = staged.find((st) => st.childOut.isOpen);
1380
+ return { needPull: nextOpen.childOut };
1381
+ }
1382
+
1383
+ _stepSpawn(node) {
1384
+ // Pre-expansion sequential sibling settlement (`after %tok`)!
1385
+ if (node.afterToken && !node.afterToken.settled) {
1386
+ const pendingOut = node.afterToken.outputs.find((ch) => ch.isOpen);
1387
+ if (pendingOut) {
1388
+ return { needPull: pendingOut };
1389
+ }
1390
+ node.afterToken.settled = true;
1391
+ this.telemetry.afterSettlements += 1;
1392
+ }
1393
+
1394
+ const proc = this.procMap.get(node.target);
1395
+ if (!proc) throw new Error(`Unknown proc '${node.target}'`);
1396
+
1397
+ const env = new Map();
1398
+ for (let i = 0; i < proc.inputs.length; i++) env.set(proc.inputs[i].name, node.inputs[i]);
1399
+ for (let i = 0; i < proc.outputs.length; i++) env.set(proc.outputs[i].name, node.outputs[i]);
1400
+
1401
+ const scope = node.scope;
1402
+ this._retireNode(node);
1403
+ this._instantiateBlock(proc.body, scope, env);
1404
+ return null;
1405
+ }
1406
+
1407
+ _getKernelUnshiftBuf(node, portName) {
1408
+ let ub = node.unshiftBufs.get(portName);
1409
+ if (!ub) {
1410
+ ub = new BitDeque(this.nextChanId++, { name: `%ub_${portName}`, scope: node.scope, quota: this.quota });
1411
+ node.unshiftBufs.set(portName, ub);
1412
+ }
1413
+ return ub;
1414
+ }
1415
+
1416
+ _flushKernelUnshiftBuf(node, portName, dst) {
1417
+ const ub = node.unshiftBufs.get(portName);
1418
+ if (!ub) return;
1419
+ node.unshiftBufs.delete(portName);
1420
+ if (ub.length > 0) {
1421
+ if (dst.length === 0) dst.adoptBufferFrom(ub);
1422
+ else dst.pushFromDeque(ub);
1423
+ }
1424
+ ub.release();
1425
+ }
1426
+
1427
+ // --- Compiled Kernel Execution ---
1428
+
1429
+ _stepKernel(node) {
1430
+ const blk = node.blockMap.get(node.pc);
1431
+ if (!blk) throw new Error(`Kernel ${node.kernelDecl.name}: missing block '${node.pc}'`);
1432
+
1433
+ // Execute statements in current basic block
1434
+ while (node.stmtIdx < blk.stmts.length) {
1435
+ const s = blk.stmts[node.stmtIdx];
1436
+ switch (s.op) {
1437
+ case "peek_bits": {
1438
+ const ch = node.portMap.get(s.src);
1439
+ const needed = s.offset + s.width;
1440
+ if (ch.length < needed) {
1441
+ if (ch.isOpen) return { needPull: ch };
1442
+ if (ch.isFailed) return this._failKernel(node);
1443
+ // CLOSED with insufficient bits -> jump to `onEof`
1444
+ node.pc = s.onEof;
1445
+ node.stmtIdx = 0;
1446
+ return null;
1447
+ }
1448
+ node.temps.set(s.dst, ch.peekBitsAt(s.offset, s.width));
1449
+ node.stmtIdx += 1;
1450
+ break;
1451
+ }
1452
+ case "shift_bits": {
1453
+ const ch = node.portMap.get(s.src);
1454
+ if (ch.length < s.width) {
1455
+ if (ch.isOpen) return { needPull: ch };
1456
+ return this._failKernel(node);
1457
+ }
1458
+ ch.shiftBits(s.width);
1459
+ ch.aligned = false;
1460
+ node.stmtIdx += 1;
1461
+ break;
1462
+ }
1463
+ case "shift_tag": {
1464
+ const ch = node.portMap.get(s.src);
1465
+ if (ch.length < s.width) {
1466
+ if (ch.isOpen) return { needPull: ch };
1467
+ return this._failKernel(node);
1468
+ }
1469
+ ch.shiftBits(s.width);
1470
+ ch.consSchema = this.resolvePlist(s.nextSchema);
1471
+ ch.consNodeId = 0;
1472
+ ch.aligned = true;
1473
+ node.stmtIdx += 1;
1474
+ break;
1475
+ }
1476
+ case "push_bits": {
1477
+ const ch = node.portMap.get(s.dst);
1478
+ ch.pushBits(parseInt(s.bits, 2), s.width);
1479
+ node.stmtIdx += 1;
1480
+ break;
1481
+ }
1482
+ case "unshift_bits": {
1483
+ const ub = this._getKernelUnshiftBuf(node, s.dst);
1484
+ ub.unshiftBits(parseInt(s.bits, 2), s.width);
1485
+ node.stmtIdx += 1;
1486
+ break;
1487
+ }
1488
+ case "set_reg": {
1489
+ node.regs.set(s.reg, s.value);
1490
+ node.stmtIdx += 1;
1491
+ break;
1492
+ }
1493
+ case "stack_push": {
1494
+ node.stacks.get(s.stack).push(parseInt(s.bits, 2), s.width);
1495
+ node.stmtIdx += 1;
1496
+ break;
1497
+ }
1498
+ case "stack_pop": {
1499
+ const st = node.stacks.get(s.stack);
1500
+ if (st.length < s.width) {
1501
+ node.pc = s.onEmpty;
1502
+ node.stmtIdx = 0;
1503
+ return null;
1504
+ }
1505
+ node.temps.set(s.dst, st.pop(s.width));
1506
+ node.stmtIdx += 1;
1507
+ break;
1508
+ }
1509
+ case "stack_clear": {
1510
+ node.stacks.get(s.stack).clear();
1511
+ node.stmtIdx += 1;
1512
+ break;
1513
+ }
1514
+ case "drain_guard": {
1515
+ const ch = node.portMap.get(s.src);
1516
+ if (!node.pendingDpda) {
1517
+ const pl = this.resolvePlist(s.schema);
1518
+ node.pendingDpda = { kind: "skip", state: createDpdaSkip(pl, 0), done: false };
1519
+ }
1520
+ if (!node.pendingDpda.done) {
1521
+ const res = stepDpdaSkip(ch, node.pendingDpda.state);
1522
+ if (res === DPDA_RESULT.NEED_BITS) {
1523
+ if (ch.isOpen) return { needPull: ch };
1524
+ return this._failKernel(node);
1525
+ }
1526
+ if (res === DPDA_RESULT.FAILED) return this._failKernel(node);
1527
+ node.pendingDpda.done = true;
1528
+ }
1529
+ if (ch.isOpen) return { needPull: ch };
1530
+ if (ch.isFailed || ch.length > 0) return this._failKernel(node);
1531
+ node.pendingDpda = null;
1532
+ node.ownedInputs.delete(s.src);
1533
+ ch.cons = null;
1534
+ ch.release();
1535
+ node.stmtIdx += 1;
1536
+ break;
1537
+ }
1538
+ case "dpda_copy": {
1539
+ const src = node.portMap.get(s.src);
1540
+ const dst = node.portMap.get(s.dst);
1541
+ if (!node.pendingDpda) {
1542
+ const pl = this.resolvePlist(s.schema);
1543
+ node.pendingDpda = { kind: "copy", state: createDpdaCopy(pl, 0) };
1544
+ }
1545
+ const res = stepDpdaCopy(src, dst, node.pendingDpda.state);
1546
+ if (res === DPDA_RESULT.NEED_BITS) {
1547
+ if (src.isOpen) return { needPull: src };
1548
+ return this._failKernel(node);
1549
+ }
1550
+ if (res === DPDA_RESULT.FAILED) return this._failKernel(node);
1551
+ node.pendingDpda = null;
1552
+ node.stmtIdx += 1;
1553
+ break;
1554
+ }
1555
+ case "dpda_coerce": {
1556
+ const src = node.portMap.get(s.src);
1557
+ const dst = node.portMap.get(s.dst);
1558
+ if (!node.pendingDpda) {
1559
+ const sPl = this.resolvePlist(s.srcSchema);
1560
+ const dPl = this.resolvePlist(s.dstSchema);
1561
+ node.pendingDpda = { kind: "coerce", state: createDpdaCoerce(sPl, 0, dPl, 0) };
1562
+ }
1563
+ const res = stepDpdaCoerce(src, dst, node.pendingDpda.state);
1564
+ if (res === DPDA_RESULT.NEED_BITS) {
1565
+ if (src.isOpen) return { needPull: src };
1566
+ return this._failKernel(node);
1567
+ }
1568
+ if (res === DPDA_RESULT.FAILED) return this._failKernel(node);
1569
+ node.pendingDpda = null;
1570
+ node.stmtIdx += 1;
1571
+ break;
1572
+ }
1573
+ case "splice": {
1574
+ const src = node.portMap.get(s.src);
1575
+ const dst = node.portMap.get(s.dst);
1576
+ this._flushKernelUnshiftBuf(node, s.dst, dst);
1577
+ node.ownedInputs.delete(s.src);
1578
+ node.ownedOutputs.delete(s.dst);
1579
+ if (src.cons === node) src.cons = null;
1580
+ if (dst.prod === node) dst.prod = null;
1581
+ this._splice(src, dst);
1582
+ node.stmtIdx += 1;
1583
+ break;
1584
+ }
1585
+ case "close": {
1586
+ const dst = node.portMap.get(s.dst);
1587
+ this._flushKernelUnshiftBuf(node, s.dst, dst);
1588
+ node.ownedOutputs.delete(s.dst);
1589
+ if (dst.prod === node) dst.prod = null;
1590
+ dst.close();
1591
+ node.stmtIdx += 1;
1592
+ break;
1593
+ }
1594
+ case "yield": {
1595
+ const dst = node.portMap.get(s.dst);
1596
+ node.yieldThreshold = s.threshold;
1597
+ node.stmtIdx += 1;
1598
+ if (dst.length >= s.threshold && dst.cons !== null) {
1599
+ return { yielded: true };
1600
+ }
1601
+ break;
1602
+ }
1603
+ default:
1604
+ throw new Error(`Unsupported kernel stmt '${s.op}'`);
1605
+ }
1606
+ }
1607
+
1608
+ // Execute block terminator
1609
+ const t = blk.term;
1610
+ switch (t.op) {
1611
+ case "goto":
1612
+ node.pc = t.target;
1613
+ node.stmtIdx = 0;
1614
+ return null;
1615
+ case "retire":
1616
+ this._retireNode(node);
1617
+ return null;
1618
+ case "fail":
1619
+ return this._failKernel(node);
1620
+ case "handoff": {
1621
+ const ins = t.inputs.map((v) => node.portMap.get(v));
1622
+ const outs = t.outputs.map((v) => node.portMap.get(v));
1623
+ const scope = node.scope;
1624
+ this._retireNode(node);
1625
+ if (this.kernelMap.has(t.target)) {
1626
+ this._instantiateKernel(t.target, scope, ins, outs);
1627
+ } else {
1628
+ this._allocNode(scope, "spawn", {
1629
+ inputs: ins,
1630
+ outputs: outs,
1631
+ target: t.target,
1632
+ afterToken: null
1633
+ });
1634
+ }
1635
+ return null;
1636
+ }
1637
+ case "switch_bits": {
1638
+ const val = node.temps.get(t.src);
1639
+ let next = t.defaultTarget;
1640
+ for (const c of t.cases) {
1641
+ if (parseInt(c.bits, 2) === val) {
1642
+ next = c.target;
1643
+ break;
1644
+ }
1645
+ }
1646
+ if (!next) return this._failKernel(node);
1647
+ node.pc = next;
1648
+ node.stmtIdx = 0;
1649
+ return null;
1650
+ }
1651
+ case "switch_reg": {
1652
+ const val = node.regs.get(t.reg);
1653
+ const found = t.cases.find((c) => c.value === val);
1654
+ if (!found) return this._failKernel(node);
1655
+ node.pc = found.target;
1656
+ node.stmtIdx = 0;
1657
+ return null;
1658
+ }
1659
+ case "table_step":
1660
+ return this._execTableStep(node, t);
1661
+ case "stack_table_step":
1662
+ return this._execStackTableStep(node, t);
1663
+ case "fsm_table_step":
1664
+ return this._execFsmTableStep(node, t);
1665
+ default:
1666
+ throw new Error(`Unsupported kernel terminator '${t.op}'`);
1667
+ }
1668
+ }
1669
+
1670
+ _failKernel(node) {
1671
+ const ownedOuts = [...node.ownedOutputs].map((v) => node.portMap.get(v));
1672
+ const ownedIns = [...node.ownedInputs].map((v) => node.portMap.get(v));
1673
+ this._retireNode(node);
1674
+ for (const o of ownedOuts) if (o) o.fail();
1675
+ for (const i of ownedIns) this._cancelInput(i);
1676
+ return null;
1677
+ }
1678
+
1679
+ _execTableStep(node, t) {
1680
+ const compiled = this.tableMap.get(t.table);
1681
+ if (!compiled || compiled.flat.size === 0) {
1682
+ // Unpopulated/placeholder table -> fall back seamlessly to exact `short` CFG!
1683
+ node.pc = t.exits.short || t.exits.fail;
1684
+ node.stmtIdx = 0;
1685
+ return null;
1686
+ }
1687
+
1688
+ const inputsSpec = compiled.decl.props.inputs || [];
1689
+ const outputsSpec = compiled.decl.props.outputs || [];
1690
+ const inChs = t.inputs.map((v) => node.portMap.get(v));
1691
+ const outChs = t.outputs.map((v) => node.portMap.get(v));
1692
+
1693
+ // Hot burst (bounded to keep cooperative yield and quota responsive)
1694
+ for (let iter = 0; iter < 32; iter++) {
1695
+ // Cooperative yield check if downstream consumer exists (skip unshift-mode outputs!)
1696
+ for (let o = 0; o < outChs.length; o++) {
1697
+ const mode = outputsSpec[o]?.mode?.ident ?? outputsSpec[o]?.mode ?? "push";
1698
+ if (mode !== "unshift" && outChs[o].cons !== null && outChs[o].length >= node.yieldThreshold) {
1699
+ return { yielded: true };
1700
+ }
1701
+ }
1702
+
1703
+ // Refill / check input buffers
1704
+ for (let p = 0; p < inChs.length; p++) {
1705
+ const ch = inChs[p];
1706
+ const wRaw = inputsSpec[p].raw_bits;
1707
+ if (ch.length < wRaw) {
1708
+ if (ch.isFailed) {
1709
+ node.pc = t.exits.fail;
1710
+ node.stmtIdx = 0;
1711
+ return null;
1712
+ }
1713
+ if (ch.isOpen) return { needPull: ch };
1714
+ // CLOSED with < wRaw bits -> exact bit-level CFG fallback!
1715
+ node.pc = t.exits.short;
1716
+ node.stmtIdx = 0;
1717
+ return null;
1718
+ }
1719
+ }
1720
+
1721
+ // Compute flat index: (((q << W_eff0) | c0) << W_eff1) | c1 ...
1722
+ let idx = node.regs.get(t.reg);
1723
+ for (let p = 0; p < inChs.length; p++) {
1724
+ const spec = inputsSpec[p];
1725
+ const raw = inChs[p].peekBits(spec.raw_bits);
1726
+ const eff = applyInputCompress(raw, spec);
1727
+ const wEff = spec.eff_bits ?? spec.raw_bits;
1728
+ idx = (idx << wEff) | eff;
1729
+ }
1730
+
1731
+ const entry = compiled.flat.get(idx);
1732
+ this.telemetry.tableLookups += 1;
1733
+ if (!entry) {
1734
+ node.pc = t.exits.short || t.exits.fail;
1735
+ node.stmtIdx = 0;
1736
+ return null;
1737
+ }
1738
+
1739
+ if (entry.kind === "NEED_MORE") {
1740
+ node.pc = t.exits.short;
1741
+ node.stmtIdx = 0;
1742
+ return null;
1743
+ }
1744
+ if (entry.kind === "FAIL") {
1745
+ node.pc = t.exits.fail;
1746
+ node.stmtIdx = 0;
1747
+ return null;
1748
+ }
1749
+
1750
+ // Apply shifts & emits
1751
+ for (let p = 0; p < inChs.length; p++) {
1752
+ const sh = entry.shift[p] ?? 0;
1753
+ if (sh > 0) inChs[p].shiftBits(sh);
1754
+ }
1755
+ for (let o = 0; o < outChs.length; o++) {
1756
+ const elen = entry.emit_len[o] ?? 0;
1757
+ if (elen > 0) {
1758
+ const eword = entry.emit_word[o] ?? 0;
1759
+ const mode = outputsSpec[o]?.mode?.ident ?? outputsSpec[o]?.mode ?? "push";
1760
+ if (mode === "unshift") {
1761
+ const ub = this._getKernelUnshiftBuf(node, t.outputs[o]);
1762
+ ub.unshiftBits(eword, elen);
1763
+ } else {
1764
+ outChs[o].pushBits(eword, elen);
1765
+ }
1766
+ }
1767
+ }
1768
+
1769
+ if (entry.kind === "EXIT") {
1770
+ node.pc = t.exits[String(entry.exit)];
1771
+ node.stmtIdx = 0;
1772
+ return null;
1773
+ }
1774
+ node.regs.set(t.reg, entry.next_q);
1775
+ // kind === "CONT" -> continue hot loop!
1776
+ this.quota.tickStep();
1777
+ this.telemetry.steps = this.quota.steps;
1778
+ }
1779
+ return null;
1780
+ }
1781
+
1782
+ _execStackTableStep(node, t) {
1783
+ const compiled = this.tableMap.get(t.table);
1784
+ if (!compiled || compiled.flat.size === 0) {
1785
+ node.pc = t.exits.short || t.exits.fail;
1786
+ node.stmtIdx = 0;
1787
+ return null;
1788
+ }
1789
+
1790
+ const props = compiled.decl.props;
1791
+ const wStream = props.stream_bits;
1792
+ const wStack = props.stack_bits ?? 0;
1793
+ const stackEncoding = props.stack_encoding?.ident ?? props.stack_encoding ?? "bits";
1794
+ const stackStride = stackEncoding === "depth_only"
1795
+ ? (wStack + 1)
1796
+ : ((1 << (wStack + 1)) - 1);
1797
+ const outMode = props.output_mode?.ident ?? props.output_mode ?? "push";
1798
+
1799
+ const inCh = node.portMap.get(t.input);
1800
+ const outCh = node.portMap.get(t.output);
1801
+ const st = node.stacks.get(t.stack);
1802
+
1803
+ for (let iter = 0; iter < 32; iter++) {
1804
+ if (outMode !== "unshift" && outCh.cons !== null && outCh.length >= node.yieldThreshold) {
1805
+ return { yielded: true };
1806
+ }
1807
+
1808
+ if (inCh.length < wStream) {
1809
+ if (inCh.isFailed) {
1810
+ node.pc = t.exits.fail;
1811
+ node.stmtIdx = 0;
1812
+ return null;
1813
+ }
1814
+ if (inCh.isOpen) return { needPull: inCh };
1815
+ node.pc = t.exits.short;
1816
+ node.stmtIdx = 0;
1817
+ return null;
1818
+ }
1819
+
1820
+ const q = node.regs.get(t.reg);
1821
+ const sBits = inCh.peekBits(wStream);
1822
+ const d = Math.min(st.length, wStack);
1823
+ let stCode = 0;
1824
+ if (stackEncoding === "depth_only") {
1825
+ stCode = d;
1826
+ } else if (d > 0) {
1827
+ stCode = ((1 << d) - 1) + st.peekTop(d);
1828
+ }
1829
+
1830
+ const idx = (((q << wStream) | sBits) * stackStride) + stCode;
1831
+ const entry = compiled.flat.get(idx);
1832
+ this.telemetry.tableLookups += 1;
1833
+ if (!entry || entry.kind === "NEED_MORE") {
1834
+ node.pc = t.exits.short;
1835
+ node.stmtIdx = 0;
1836
+ return null;
1837
+ }
1838
+ if (entry.kind === "FAIL") {
1839
+ node.pc = t.exits.fail;
1840
+ node.stmtIdx = 0;
1841
+ return null;
1842
+ }
1843
+
1844
+ if (entry.shift_stream > 0) inCh.shiftBits(entry.shift_stream);
1845
+ if (entry.pop_stack > 0) st.pop(entry.pop_stack);
1846
+ if (entry.push_stack_len > 0) st.push(entry.push_stack_word, entry.push_stack_len);
1847
+ if (entry.emit_len_single > 0) {
1848
+ if (outMode === "unshift") {
1849
+ const ub = this._getKernelUnshiftBuf(node, t.output);
1850
+ ub.unshiftBits(entry.emit_word_single, entry.emit_len_single);
1851
+ } else {
1852
+ outCh.pushBits(entry.emit_word_single, entry.emit_len_single);
1853
+ }
1854
+ }
1855
+ if (entry.kind === "EXIT") {
1856
+ node.pc = t.exits[String(entry.exit)];
1857
+ node.stmtIdx = 0;
1858
+ return null;
1859
+ }
1860
+ node.regs.set(t.reg, entry.next_q);
1861
+ this.quota.tickStep();
1862
+ this.telemetry.steps = this.quota.steps;
1863
+ }
1864
+ return null;
1865
+ }
1866
+
1867
+ _execFsmTableStep(node, t) {
1868
+ const compiled = this.tableMap.get(t.table);
1869
+ if (!compiled || compiled.flat.size === 0) {
1870
+ node.pc = t.exits.short || t.exits.fail;
1871
+ node.stmtIdx = 0;
1872
+ return null;
1873
+ }
1874
+
1875
+ const props = compiled.decl.props;
1876
+ const wRaw = props.input_bits;
1877
+ const outModes = props.output_modes || [];
1878
+ const inCh = node.portMap.get(t.input);
1879
+ const outChs = t.outputs.map((v) => node.portMap.get(v));
1880
+
1881
+ if (inCh.length < wRaw) {
1882
+ if (inCh.isFailed) {
1883
+ node.pc = t.exits.fail;
1884
+ node.stmtIdx = 0;
1885
+ return null;
1886
+ }
1887
+ if (inCh.isOpen) return { needPull: inCh };
1888
+ node.pc = t.exits.short;
1889
+ node.stmtIdx = 0;
1890
+ return null;
1891
+ }
1892
+
1893
+ const idx = inCh.peekBits(wRaw);
1894
+ const entry = compiled.flat.get(idx);
1895
+ this.telemetry.tableLookups += 1;
1896
+ if (!entry || entry.kind === "NEED_MORE") {
1897
+ node.pc = t.exits.short;
1898
+ node.stmtIdx = 0;
1899
+ return null;
1900
+ }
1901
+ if (entry.kind === "FAIL") {
1902
+ node.pc = t.exits.fail;
1903
+ node.stmtIdx = 0;
1904
+ return null;
1905
+ }
1906
+
1907
+ const sh = entry.shift[0] ?? 0;
1908
+ if (sh > 0) inCh.shiftBits(sh);
1909
+ for (let o = 0; o < outChs.length; o++) {
1910
+ const elen = entry.emit_len[o] ?? 0;
1911
+ if (elen > 0) {
1912
+ const eword = entry.emit_word[o] ?? 0;
1913
+ const mode = outModes[o]?.ident ?? outModes[o] ?? "push";
1914
+ if (mode === "unshift") {
1915
+ const ub = this._getKernelUnshiftBuf(node, t.outputs[o]);
1916
+ ub.unshiftBits(eword, elen);
1917
+ } else {
1918
+ outChs[o].pushBits(eword, elen);
1919
+ }
1920
+ }
1921
+ }
1922
+
1923
+ if (entry.kind === "EXIT") {
1924
+ node.pc = t.exits[String(entry.exit)];
1925
+ node.stmtIdx = 0;
1926
+ return null;
1927
+ }
1928
+ return null;
1929
+ }
1930
+
1931
+ // --- Strictly Iterative Demand-Driven Pull Scheduler ---
1932
+
1933
+ /**
1934
+ * Drive all `rootOuts` to completion (`CLOSED` or `FAILED`) using an explicit
1935
+ * heap demand stack (zero host call-stack recursion).
1936
+ */
1937
+ driveToCompletion(rootOuts) {
1938
+ // Demand stack frames: { kind: "chan", ch } | { kind: "node", node }
1939
+ const demandStack = [];
1940
+
1941
+ for (const rootOut of rootOuts) {
1942
+ while (rootOut.isOpen) {
1943
+ if (!rootOut.prod) {
1944
+ throw new Error(`Deadlock/unproduced channel '${rootOut.name}' is OPEN with no producer`);
1945
+ }
1946
+ demandStack.push({ kind: "chan", ch: rootOut });
1947
+
1948
+ while (demandStack.length > 0) {
1949
+ const top = demandStack[demandStack.length - 1];
1950
+ let targetNode = null;
1951
+
1952
+ if (top.kind === "chan") {
1953
+ const ch = top.ch;
1954
+ if (!ch.isOpen || !ch.prod) {
1955
+ demandStack.pop();
1956
+ continue;
1957
+ }
1958
+ targetNode = ch.prod;
1959
+ } else {
1960
+ if (top.node.retired) {
1961
+ demandStack.pop();
1962
+ continue;
1963
+ }
1964
+ targetNode = top.node;
1965
+ }
1966
+
1967
+ const outcome = this._stepNode(targetNode);
1968
+
1969
+ if (outcome && outcome.needPull) {
1970
+ if (outcome.needPull.isOpen && !outcome.needPull.prod) {
1971
+ throw new Error(
1972
+ `Deadlock/unproduced channel '${outcome.needPull.name}' pulled by ${targetNode.kind} (${targetNode.kernelDecl?.name || targetNode.target || ""})`
1973
+ );
1974
+ }
1975
+ demandStack.push({ kind: "chan", ch: outcome.needPull });
1976
+ } else if (outcome && outcome.needStepNode) {
1977
+ demandStack.push({ kind: "node", node: outcome.needStepNode });
1978
+ } else if (outcome && outcome.yielded) {
1979
+ // Cooperative yield: pop current producer frame so downstream consumer resumes!
1980
+ demandStack.pop();
1981
+ } else {
1982
+ // Normal progress: if we were fulfilling an upstream pull on an internal channel
1983
+ // that now has readable finalized bits (or settled), pop back to its consumer immediately!
1984
+ if (top.kind === "chan") {
1985
+ const ch = top.ch;
1986
+ if (!ch.isOpen || (demandStack.length > 1 && ch.length > 0)) {
1987
+ demandStack.pop();
1988
+ }
1989
+ } else if (top.node.retired) {
1990
+ demandStack.pop();
1991
+ }
1992
+ }
1993
+ }
1994
+ }
1995
+ }
1996
+
1997
+ this.telemetry.peakActiveNodes = this.quota.peakNodes;
1998
+ this.telemetry.peakBitDequeBytes = this.quota.peakBitDequeBytes;
1999
+ this.telemetry.steps = this.quota.steps;
2000
+ }
2001
+
2002
+ /**
2003
+ * Execute an entry procedure or kernel on pre-populated closed input `BitDeque`s.
2004
+ */
2005
+ run(entryName, inputDeques) {
2006
+ const entry = entryName || this.mod.entry;
2007
+ if (!entry) throw new Error("KTVMRuntime.run requires an entry name");
2008
+
2009
+ const proc = this.procMap.get(entry);
2010
+ const kern = this.kernelMap.get(entry);
2011
+ const target = proc || kern;
2012
+ if (!target) throw new Error(`Unknown entry '${entry}'`);
2013
+ if (target.inputs.length !== inputDeques.length) {
2014
+ throw new Error(`Entry '${entry}' expects ${target.inputs.length} inputs, got ${inputDeques.length}`);
2015
+ }
2016
+
2017
+ const rootIns = inputDeques.map((dq, i) => {
2018
+ const expectedPl = this.resolvePlist(target.inputs[i].schema);
2019
+ dq.prodSchema = expectedPl;
2020
+ dq.prodNodeId = 0;
2021
+ dq.consSchema = expectedPl;
2022
+ dq.consNodeId = 0;
2023
+ dq.aligned = true;
2024
+ dq.scope = 0;
2025
+ if (!dq.quota) {
2026
+ dq.quota = this.quota;
2027
+ this.quota.addBufferBytes(dq.words.byteLength);
2028
+ }
2029
+ return dq;
2030
+ });
2031
+
2032
+ const outputPlists = target.outputs.map((o) => this.resolvePlist(o.schema));
2033
+ const rootOuts = target.outputs.map((o, i) => this._allocChan(0, outputPlists[i], o.name));
2034
+
2035
+ if (proc) {
2036
+ this._allocNode(0, "spawn", {
2037
+ inputs: rootIns,
2038
+ outputs: rootOuts,
2039
+ target: entry,
2040
+ afterToken: null
2041
+ });
2042
+ } else {
2043
+ this._instantiateKernel(entry, 0, rootIns, rootOuts);
2044
+ }
2045
+
2046
+ this.driveToCompletion(rootOuts);
2047
+
2048
+ const anyFailed = rootOuts.some((o) => o.isFailed);
2049
+ if (anyFailed) {
2050
+ this._destroyScope(0);
2051
+ return {
2052
+ status: "FAILED",
2053
+ outputDeques: [],
2054
+ outputPlists,
2055
+ telemetry: { ...this.telemetry }
2056
+ };
2057
+ }
2058
+
2059
+ // Detach rootOuts from scope 0 before cleanup so callers can consume them!
2060
+ const rootSc = this.scopes.get(0);
2061
+ if (rootSc) {
2062
+ for (const o of rootOuts) rootSc.chans.delete(o);
2063
+ }
2064
+ this._destroyScope(0);
2065
+
2066
+ return {
2067
+ status: "OK",
2068
+ outputDeques: rootOuts,
2069
+ outputPlists,
2070
+ telemetry: { ...this.telemetry }
2071
+ };
2072
+ }
2073
+ }
2074
+
2075
+ // --- High-Level Runners ---
2076
+
2077
+ function cloneDequeBits(src) {
2078
+ const copy = new BitDeque(-99, {
2079
+ prodSchema: src.prodSchema,
2080
+ prodNodeId: src.prodNodeId,
2081
+ consSchema: src.consSchema,
2082
+ consNodeId: src.consNodeId,
2083
+ aligned: src.aligned
2084
+ });
2085
+ let off = 0;
2086
+ let rem = src.length;
2087
+ while (rem > 0) {
2088
+ const chunk = rem > 30 ? 30 : rem;
2089
+ copy.pushBits(src.peekBitsAt(off, chunk), chunk);
2090
+ off += chunk;
2091
+ rem -= chunk;
2092
+ }
2093
+ if (src.isClosed) copy.close();
2094
+ return copy;
2095
+ }
2096
+
2097
+ /**
2098
+ * Execute a `kTVM` (or `kTVM-P` with `inputPlists`) module on K `Value`s or `BitDeque`s.
2099
+ */
2100
+ export function executeKTVM(moduleOrSource, inputsArg, opts = {}) {
2101
+ const parsed = typeof moduleOrSource === "string" ? parseModule(moduleOrSource) : moduleOrSource;
2102
+ const entryName = opts.entry || parsed.entry;
2103
+ const rawInputs = Array.isArray(inputsArg) ? inputsArg : [inputsArg];
2104
+
2105
+ let monoMod = parsed;
2106
+ let monoEntry = entryName;
2107
+
2108
+ if (parsed.layer === "poly") {
2109
+ if (!opts.inputPlists) {
2110
+ throw new KTVMSchemaError("Executing a 'poly' kTVM-P module requires `opts.inputPlists` or `executeKTVMWire`");
2111
+ }
2112
+ const spec = specializeKTVM(parsed, entryName, opts.inputPlists, {
2113
+ useCache: opts.useCache !== false,
2114
+ validate: opts.validate !== false
2115
+ });
2116
+ monoMod = spec.module;
2117
+ monoEntry = spec.entry;
2118
+ } else if (opts.validate !== false) {
2119
+ validateModule(monoMod, { verifyTables: opts.verifyTables !== false });
2120
+ }
2121
+
2122
+ const quota = new QuotaTracker(opts.quota || {});
2123
+ const vm = new KTVMRuntime(monoMod, { quota });
2124
+ const target = vm.procMap.get(monoEntry) || vm.kernelMap.get(monoEntry);
2125
+ if (!target) throw new Error(`Unknown entry '${monoEntry}'`);
2126
+
2127
+ const inputDeques = rawInputs.map((item, i) => {
2128
+ if (item instanceof BitDeque) {
2129
+ if (item.isOpen) item.close();
2130
+ return item;
2131
+ }
2132
+ const pl = vm.resolvePlist(target.inputs[i].schema);
2133
+ const dq = new BitDeque(10000 + i, { prodSchema: pl, consSchema: pl, quota });
2134
+ encodePayloadToDeque(item, pl, dq, 0);
2135
+ dq.close();
2136
+ return dq;
2137
+ });
2138
+
2139
+ const res = vm.run(monoEntry, inputDeques);
2140
+ if (res.status === "FAILED") {
2141
+ return { status: "FAILED", telemetry: res.telemetry };
2142
+ }
2143
+
2144
+ const values = opts.decodeValues === false
2145
+ ? null
2146
+ : res.outputDeques.map((dq, i) => {
2147
+ const tmp = cloneDequeBits(dq);
2148
+ const val = decodeDequeToValue(tmp, res.outputPlists[i], 0, { exact: true });
2149
+ tmp.release();
2150
+ return val;
2151
+ });
2152
+
2153
+ return {
2154
+ status: "OK",
2155
+ outputDeques: res.outputDeques,
2156
+ values,
2157
+ value: values ? values[0] : null,
2158
+ outputPlists: res.outputPlists,
2159
+ telemetry: res.telemetry
2160
+ };
2161
+ }
2162
+
2163
+ /**
2164
+ * Full end-to-end enveloped `k-wire` execution:
2165
+ * enveloped wire bytes -> split header -> boundary specialization (`kTVM-P` -> `kTVM`)
2166
+ * -> iterative execution -> framed enveloped output `k-wire` bytes.
2167
+ */
2168
+ export function executeKTVMWire(moduleOrSource, envelopedWireBuffer, opts = {}) {
2169
+ const parsed = typeof moduleOrSource === "string" ? parseModule(moduleOrSource) : moduleOrSource;
2170
+ const entryName = opts.entry || parsed.entry;
2171
+ const quota = new QuotaTracker(opts.quota || {});
2172
+
2173
+ // 1. Split & validate incoming k-wire envelope strictly iteratively
2174
+ const { plist: inPlist, payloadDeque } = splitEnvelopedWire(envelopedWireBuffer, { quota });
2175
+
2176
+ // 2. Boundary specialization / compatibility check (throws KTVMSchemaError on mismatch)
2177
+ let spec;
2178
+ try {
2179
+ spec = specializeKTVM(parsed, entryName, inPlist, {
2180
+ useCache: opts.useCache !== false,
2181
+ validate: opts.validate !== false
2182
+ });
2183
+ } catch (err) {
2184
+ payloadDeque.release();
2185
+ throw err;
2186
+ }
2187
+
2188
+ if (parsed.layer === "mono" && opts.validate !== false) {
2189
+ validateModule(spec.module, { verifyTables: opts.verifyTables !== false });
2190
+ }
2191
+
2192
+ // 3. Execute concrete mono module
2193
+ const vm = new KTVMRuntime(spec.module, { quota });
2194
+ const res = vm.run(spec.entry, [payloadDeque]);
2195
+ if (res.status === "FAILED") {
2196
+ return {
2197
+ status: "FAILED",
2198
+ specialized: spec,
2199
+ telemetry: res.telemetry
2200
+ };
2201
+ }
2202
+
2203
+ const outDeque = res.outputDeques[0];
2204
+ const outPlist = res.outputPlists[0];
2205
+
2206
+ let value = null;
2207
+ if (opts.decodeValue !== false) {
2208
+ const tmp = cloneDequeBits(outDeque);
2209
+ value = decodeDequeToValue(tmp, outPlist, 0, { exact: true });
2210
+ tmp.release();
2211
+ }
2212
+
2213
+ // 4. Frame output payload with derived closed output schema header
2214
+ const wire = frameEnvelopedWire(outPlist, outDeque);
2215
+ outDeque.release();
2216
+
2217
+ return {
2218
+ status: "OK",
2219
+ wire,
2220
+ value,
2221
+ outputPlist: outPlist,
2222
+ specialized: spec,
2223
+ telemetry: res.telemetry
2224
+ };
2225
+ }