@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
@@ -0,0 +1,2221 @@
1
+ /**
2
+ * KIR-P -> kTVM-P / concrete kTVM Lowering Compiler.
3
+ *
4
+ * Implements Milestone 2 (DOCS/KTVM_SPEC.md §11.1):
5
+ * - Consumes canonical `KIR-P` (`objectToKIRP(obj)`) or a `k-object` directly.
6
+ * - Lowers all 11 KIR-P expression ops (`identity`, `empty`, `filter`, `code`,
7
+ * `dot`, `div`, `vid`, `ref`, `comp`, `product`, `union`) plus identity
8
+ * intrinsics (`_log!`).
9
+ * - Performs:
10
+ * * Exact `KIR-P` pattern-graph unification against concrete closed `k-wire`
11
+ * envelopes (with `KTVMSchemaError` on structural contradiction and clean
12
+ * fallback signaling for non-converged recursive relations).
13
+ * * Product `demux`-hoisting & common leading `match /tag`-hoisting so
14
+ * K's let-free `{ .xs /cons .cdr ..., .xs /cons .car ... }` compiles into
15
+ * single-pass zero-tee streaming `kTVM` networks.
16
+ * * Leading-guard prefix-disjoint analysis routing disjoint `union`s to
17
+ * zero-buffering `switch` and overlapping/backtracking `union`s to `spec`.
18
+ * * Static `isBranchingRecursive` SCC analysis inserting `after %tok`
19
+ * sequential sibling settlement on branching tree recursion.
20
+ * * Static validation via `validateModule` (always-on).
21
+ */
22
+
23
+ import codes from "../codes.mjs";
24
+ import { isIdentityIntrinsic, isIntrinsic, unsupportedIntrinsic } from "../intrinsics.mjs";
25
+ import { objectToKIRP, relationPatternPropertyList, retypeObjectRelationForBackend } from "../kir.mjs";
26
+ import { KTVMSchemaError, S, createModule } from "./ast.mjs";
27
+ import {
28
+ canonicalizePlistOrder,
29
+ compareLabels,
30
+ isClosedPlist,
31
+ mooreKey,
32
+ mooreMinimize,
33
+ plistToSchemaAst,
34
+ productFieldInfo,
35
+ productFields,
36
+ schemasEquivalent,
37
+ subPlist,
38
+ unionTagInfo
39
+ } from "./schema.mjs";
40
+ import { validateModule } from "./validator.mjs";
41
+ import { executeKTVM, executeKTVMWire } from "./vm.mjs";
42
+ import { splitEnvelopedWire } from "./wire.mjs";
43
+
44
+ const UNIT_PLIST = [["closed-product", []]];
45
+
46
+ function sanitizeIdent(raw, fallback = "r") {
47
+ const s = String(raw || "")
48
+ .replace(/^@/, "")
49
+ .replace(/[^A-Za-z0-9_]/g, "_")
50
+ .replace(/^_+/, "");
51
+ if (!s) return fallback;
52
+ return /^[A-Za-z_]/.test(s) ? s.slice(0, 32) : `r_${s.slice(0, 30)}`;
53
+ }
54
+
55
+ function normalizeKIR(kirOrObject) {
56
+ if (!kirOrObject || typeof kirOrObject !== "object") {
57
+ throw new Error("kTVM lowering requires a KIR-P or k-object");
58
+ }
59
+ if (kirOrObject.format === "k-ir" && kirOrObject.layer === "KIR-P") {
60
+ return { kir: kirOrObject, sourceObject: null };
61
+ }
62
+ if (kirOrObject.format === "k-object") {
63
+ return { kir: objectToKIRP(kirOrObject), sourceObject: kirOrObject };
64
+ }
65
+ throw new Error(`Unsupported input format for kTVM lowering: '${kirOrObject.format}'`);
66
+ }
67
+
68
+ function makeCodeLookup(kir) {
69
+ const table = kir.codes || {};
70
+ return (hash) => {
71
+ let cur = table[hash] || codes.find(hash);
72
+ const seen = new Set([hash]);
73
+ while (cur && cur.code === "ref" && cur.ref) {
74
+ if (seen.has(cur.ref)) break;
75
+ seen.add(cur.ref);
76
+ cur = table[cur.ref] || codes.find(cur.ref);
77
+ }
78
+ return cur || null;
79
+ };
80
+ }
81
+
82
+ function resolveRelHash(kir, name) {
83
+ if (!name) return null;
84
+ if (kir.rels?.[name]) return name;
85
+ const alias = kir.relAlias?.[name];
86
+ if (alias && kir.rels?.[alias]) return alias;
87
+ if (alias) {
88
+ for (const k of Object.keys(kir.rels || {})) {
89
+ if (kir.relAlias?.[k] === alias) return k;
90
+ }
91
+ }
92
+ return null;
93
+ }
94
+
95
+ function buildDisplayNameMap(kir) {
96
+ const map = new Map();
97
+ for (const [alias, hash] of Object.entries(kir.relAlias || {})) {
98
+ if (!map.has(hash)) map.set(hash, alias);
99
+ }
100
+ return map;
101
+ }
102
+
103
+ // --- Code Hash -> Closed Property-List Graph ---
104
+
105
+ function codeHashToPlist(codeHash, findCode) {
106
+ const nodes = [];
107
+ const memo = new Map();
108
+
109
+ function visit(h) {
110
+ let def = findCode(h);
111
+ if (!def) {
112
+ throw new KTVMSchemaError(`Unknown K code hash '${h}'`);
113
+ }
114
+ if (memo.has(h)) return memo.get(h);
115
+ const id = nodes.length;
116
+ memo.set(h, id);
117
+ const slot = [def.code === "product" ? "closed-product" : "closed-union", []];
118
+ nodes.push(slot);
119
+ const edgeObj = def[def.code] || {};
120
+ const labels = Object.keys(edgeObj).sort(compareLabels);
121
+ slot[1] = labels.map((l) => [l, visit(edgeObj[l])]);
122
+ return id;
123
+ }
124
+
125
+ visit(codeHash);
126
+ return mooreMinimize(canonicalizePlistOrder(nodes, 0), 0).plist;
127
+ }
128
+
129
+ // --- Mutable Local Pattern Graph for KIR-P Relation Unification ---
130
+
131
+ class LocalPatternGraph {
132
+ constructor(kirPatternGraph, findCode) {
133
+ this.findCode = findCode;
134
+ this.nodes = []; // { kind, edges: Map<label, targetId> }
135
+ this.parent = []; // union-find parent (-1 if root)
136
+ this.kirIdToLocal = new Map();
137
+ this.codeMemo = new Map();
138
+
139
+ const kirNodes = kirPatternGraph?.nodes || [];
140
+ for (const kn of kirNodes) {
141
+ const id = this._newNode("any");
142
+ this.kirIdToLocal.set(kn.id, id);
143
+ }
144
+
145
+ for (const kn of kirNodes) {
146
+ const id = this.kirIdToLocal.get(kn.id);
147
+ const node = this.nodes[id];
148
+ if (kn.kind === "type") {
149
+ const def = findCode(kn.code);
150
+ if (!def) {
151
+ throw new KTVMSchemaError(`KIR type node '${kn.code}' missing code definition`);
152
+ }
153
+ node.kind = def.code === "product" ? "closed-product" : "closed-union";
154
+ if (kn.edges && kn.edges.length > 0) {
155
+ for (const e of kn.edges) {
156
+ node.edges.set(e.label, this.kirIdToLocal.get(e.target));
157
+ }
158
+ } else {
159
+ // Expand edges directly from code definition
160
+ this.codeMemo.set(kn.code, id);
161
+ const edgeObj = def[def.code] || {};
162
+ for (const l of Object.keys(edgeObj).sort(compareLabels)) {
163
+ node.edges.set(l, this._importCode(edgeObj[l]));
164
+ }
165
+ }
166
+ } else {
167
+ node.kind = kn.kind;
168
+ for (const e of kn.edges || []) {
169
+ node.edges.set(e.label, this.kirIdToLocal.get(e.target));
170
+ }
171
+ }
172
+ }
173
+ }
174
+
175
+ _newNode(kind) {
176
+ const id = this.nodes.length;
177
+ this.nodes.push({ kind, edges: new Map() });
178
+ this.parent.push(-1);
179
+ return id;
180
+ }
181
+
182
+ _importCode(codeHash) {
183
+ if (this.codeMemo.has(codeHash)) return this.codeMemo.get(codeHash);
184
+ const def = this.findCode(codeHash);
185
+ if (!def) throw new KTVMSchemaError(`Unknown code hash '${codeHash}'`);
186
+ const kind = def.code === "product" ? "closed-product" : "closed-union";
187
+ const id = this._newNode(kind);
188
+ this.codeMemo.set(codeHash, id);
189
+ const edgeObj = def[def.code] || {};
190
+ for (const l of Object.keys(edgeObj).sort(compareLabels)) {
191
+ this.nodes[id].edges.set(l, this._importCode(edgeObj[l]));
192
+ }
193
+ return id;
194
+ }
195
+
196
+ importConcretePlist(plist, rootId = 0) {
197
+ const idMap = new Map();
198
+ const visit = (oldId) => {
199
+ if (idMap.has(oldId)) return idMap.get(oldId);
200
+ const [kind, edges] = plist[oldId];
201
+ const newId = this._newNode(kind);
202
+ idMap.set(oldId, newId);
203
+ for (const [label, target] of edges) {
204
+ this.nodes[newId].edges.set(label, visit(target));
205
+ }
206
+ return newId;
207
+ };
208
+ return visit(rootId);
209
+ }
210
+
211
+ find(id) {
212
+ let cur = id;
213
+ while (this.parent[cur] !== -1) cur = this.parent[cur];
214
+ let x = id;
215
+ while (this.parent[x] !== -1) {
216
+ const p = this.parent[x];
217
+ this.parent[x] = cur;
218
+ x = p;
219
+ }
220
+ return cur;
221
+ }
222
+
223
+ nodeOf(id) {
224
+ return this.nodes[this.find(id)];
225
+ }
226
+
227
+ /**
228
+ * Unify pattern node `patId` against concrete closed `plist` at `cRoot`,
229
+ * mutating `this` in-place so shared `any` / open nodes become concrete.
230
+ */
231
+ unifyWithConcrete(patId, concretePlist, cRoot = 0, { strictClosedUnion = false } = {}) {
232
+ const visited = new Set();
233
+
234
+ const step = (pid, cid) => {
235
+ const rep = this.find(pid);
236
+ const key = `${rep}@${cid}`;
237
+ if (visited.has(key)) return;
238
+ visited.add(key);
239
+
240
+ const node = this.nodes[rep];
241
+ const [cKind, cEdges] = concretePlist[cid];
242
+ const cMap = new Map(cEdges);
243
+
244
+ if (node.kind === "any") {
245
+ // Bind `any` to concrete subgraph!
246
+ const imported = this.importConcretePlist(concretePlist, cid);
247
+ this.parent[rep] = imported;
248
+ return;
249
+ }
250
+
251
+ if (node.kind === "closed-product") {
252
+ if (cKind !== "closed-product") {
253
+ throw new KTVMSchemaError(`Expected closed-product, got ${cKind}`);
254
+ }
255
+ if (node.edges.size !== cEdges.length) {
256
+ throw new KTVMSchemaError(
257
+ `Closed product field mismatch: expected [${[...node.edges.keys()].join(", ")}], got [${cEdges.map(([l]) => l).join(", ")}]`
258
+ );
259
+ }
260
+ for (const [label, tId] of node.edges.entries()) {
261
+ if (!cMap.has(label)) {
262
+ throw new KTVMSchemaError(`Closed product missing field '${label}'`);
263
+ }
264
+ step(tId, cMap.get(label));
265
+ }
266
+ return;
267
+ }
268
+
269
+ if (node.kind === "open-product") {
270
+ if (cKind !== "closed-product") {
271
+ throw new KTVMSchemaError(`Expected product for open-product, got ${cKind}`);
272
+ }
273
+ for (const [label, tId] of node.edges.entries()) {
274
+ if (!cMap.has(label)) {
275
+ throw new KTVMSchemaError(`Input product missing required field '${label}'`);
276
+ }
277
+ step(tId, cMap.get(label));
278
+ }
279
+ // Close to concrete product, adding extra fields from concrete envelope
280
+ node.kind = "closed-product";
281
+ for (const [label, cTarget] of cEdges) {
282
+ if (!node.edges.has(label)) {
283
+ node.edges.set(label, this.importConcretePlist(concretePlist, cTarget));
284
+ }
285
+ }
286
+ return;
287
+ }
288
+
289
+ if (node.kind === "closed-union" || node.kind === "open-union") {
290
+ if (cKind !== "closed-union") {
291
+ throw new KTVMSchemaError(`Expected union, got ${cKind}`);
292
+ }
293
+ let sharedCount = 0;
294
+ const unhandled = [];
295
+ for (const [label] of cEdges) {
296
+ if (node.edges.has(label)) sharedCount++;
297
+ else unhandled.push(label);
298
+ }
299
+ if (node.kind === "closed-union") {
300
+ if (strictClosedUnion && unhandled.length > 0) {
301
+ throw new KTVMSchemaError(
302
+ `Input union carries unhandled tag(s): ${unhandled.join(", ")}`
303
+ );
304
+ }
305
+ if (node.edges.size > 0 && sharedCount === 0) {
306
+ throw new KTVMSchemaError(
307
+ `Disjoint closed-union tags: contract [${[...node.edges.keys()].join(", ")}] vs input [${cEdges.map(([l]) => l).join(", ")}]`
308
+ );
309
+ }
310
+ } else {
311
+ // open-union
312
+ if (node.edges.size > 0 && sharedCount === 0) {
313
+ throw new KTVMSchemaError(
314
+ `Disjoint open-union tags: contract [${[...node.edges.keys()].join(", ")}] vs input [${cEdges.map(([l]) => l).join(", ")}]`
315
+ );
316
+ }
317
+ }
318
+
319
+ // Unify every shared tag payload
320
+ for (const [label, cTarget] of cEdges) {
321
+ if (node.edges.has(label)) {
322
+ step(node.edges.get(label), cTarget);
323
+ }
324
+ }
325
+ // For `closed-union`, keep its contract tag set intact so a value-derived
326
+ // subtype at one field (e.g. `den = <_>`) never deletes valid tags (`0`, `1`)
327
+ // needed by another field sharing the same closed-union node (`num = <1:<_>>`)!
328
+ if (node.kind === "closed-union") {
329
+ return;
330
+ }
331
+ // For `open-union`: refine/merge with concrete tags
332
+ if (node.concreteUnified) {
333
+ for (const [label, cTarget] of cEdges) {
334
+ if (!node.edges.has(label)) {
335
+ node.edges.set(label, this.importConcretePlist(concretePlist, cTarget));
336
+ }
337
+ }
338
+ return;
339
+ }
340
+ const newEdges = new Map();
341
+ for (const [label, cTarget] of cEdges) {
342
+ if (node.edges.has(label)) {
343
+ newEdges.set(label, node.edges.get(label));
344
+ } else {
345
+ newEdges.set(label, this.importConcretePlist(concretePlist, cTarget));
346
+ }
347
+ }
348
+ node.kind = "closed-union";
349
+ node.edges = newEdges;
350
+ node.concreteUnified = true;
351
+ return;
352
+ }
353
+
354
+ throw new KTVMSchemaError(`Unsupported pattern kind '${node.kind}'`);
355
+ };
356
+
357
+ step(patId, cRoot);
358
+ }
359
+
360
+ /**
361
+ * Extract a property-list graph rooted at `patId`.
362
+ * If `closeOpenUnions = true`, converts remaining `open-union` nodes (e.g.
363
+ * unannotated variant outputs like `_classify_bits`) into `closed-union`.
364
+ */
365
+ extractPlist(patId, { closeOpenUnions = false } = {}) {
366
+ const remap = new Map();
367
+ const out = [];
368
+
369
+ const dfs = (id) => {
370
+ const rep = this.find(id);
371
+ if (remap.has(rep)) return remap.get(rep);
372
+ const node = this.nodes[rep];
373
+ let kind = node.kind;
374
+ if (closeOpenUnions && kind === "open-union") kind = "closed-union";
375
+ const newId = out.length;
376
+ remap.set(rep, newId);
377
+ const slot = [kind, []];
378
+ out.push(slot);
379
+ const labels = [...node.edges.keys()].sort(compareLabels);
380
+ slot[1] = labels.map((l) => [l, dfs(node.edges.get(l))]);
381
+ return newId;
382
+ };
383
+
384
+ dfs(patId);
385
+ const canon = canonicalizePlistOrder(out, 0);
386
+ return isClosedPlist(canon) ? mooreMinimize(canon, 0).plist : canon;
387
+ }
388
+ }
389
+
390
+ // --- Closed Schema Combinators (Join, Product, Singleton Union, Filter) ---
391
+
392
+ function composeClosedProductPlist(fieldEntries) {
393
+ // fieldEntries: [{ label, plist }]
394
+ const sorted = [...fieldEntries].sort((a, b) => compareLabels(a.label, b.label));
395
+ if (sorted.length === 0) return UNIT_PLIST;
396
+ const nodes = [["closed-product", []]];
397
+ for (const { label, plist } of sorted) {
398
+ const base = nodes.length;
399
+ for (const [kind, edges] of plist) {
400
+ nodes.push([kind, edges.map(([l, t]) => [l, t + base])]);
401
+ }
402
+ nodes[0][1].push([label, base]);
403
+ }
404
+ return mooreMinimize(canonicalizePlistOrder(nodes, 0), 0).plist;
405
+ }
406
+
407
+ function composeSingletonUnionPlist(tag, payloadPlist) {
408
+ const nodes = [["closed-union", [[tag, 1]]]];
409
+ for (const [kind, edges] of payloadPlist) {
410
+ nodes.push([kind, edges.map(([l, t]) => [l, t + 1])]);
411
+ }
412
+ return mooreMinimize(canonicalizePlistOrder(nodes, 0), 0).plist;
413
+ }
414
+
415
+ /**
416
+ * Least upper bound (structural join) of two closed k-wire property-list graphs.
417
+ */
418
+ function joinTwoClosedPlists(pA, pB) {
419
+ if (schemasEquivalent(pA, 0, pB, 0)) return pA;
420
+ const nodes = [];
421
+ const pairMemo = new Map();
422
+ const singleMemoA = new Map();
423
+ const singleMemoB = new Map();
424
+
425
+ function copyOnly(pl, id, memo) {
426
+ if (memo.has(id)) return memo.get(id);
427
+ const nid = nodes.length;
428
+ memo.set(id, nid);
429
+ const [kind, edges] = pl[id];
430
+ const slot = [kind, []];
431
+ nodes.push(slot);
432
+ slot[1] = edges.map(([l, t]) => [l, copyOnly(pl, t, memo)]);
433
+ return nid;
434
+ }
435
+
436
+ function joinNodes(iA, iB) {
437
+ const key = `${iA}|${iB}`;
438
+ if (pairMemo.has(key)) return pairMemo.get(key);
439
+ const [kA, eA] = pA[iA];
440
+ const [kB, eB] = pB[iB];
441
+ if (kA !== kB) {
442
+ throw new KTVMSchemaError(`Incompatible branch output schemas: ${kA} vs ${kB}`);
443
+ }
444
+ const mapA = new Map(eA);
445
+ const mapB = new Map(eB);
446
+
447
+ if (kA === "closed-product") {
448
+ if (mapA.size !== mapB.size) {
449
+ throw new KTVMSchemaError(
450
+ `Incompatible product branch outputs: [${[...mapA.keys()].join(",")}] vs [${[...mapB.keys()].join(",")}]`
451
+ );
452
+ }
453
+ const nid = nodes.length;
454
+ pairMemo.set(key, nid);
455
+ const slot = ["closed-product", []];
456
+ nodes.push(slot);
457
+ const labels = [...mapA.keys()].sort(compareLabels);
458
+ for (const l of labels) {
459
+ if (!mapB.has(l)) {
460
+ throw new KTVMSchemaError(`Incompatible product branch outputs: missing '${l}'`);
461
+ }
462
+ slot[1].push([l, joinNodes(mapA.get(l), mapB.get(l))]);
463
+ }
464
+ return nid;
465
+ }
466
+
467
+ // closed-union: union of tags, joining shared tag payloads
468
+ const nid = nodes.length;
469
+ pairMemo.set(key, nid);
470
+ const slot = ["closed-union", []];
471
+ nodes.push(slot);
472
+ const allLabels = [...new Set([...mapA.keys(), ...mapB.keys()])].sort(compareLabels);
473
+ for (const l of allLabels) {
474
+ if (mapA.has(l) && mapB.has(l)) {
475
+ slot[1].push([l, joinNodes(mapA.get(l), mapB.get(l))]);
476
+ } else if (mapA.has(l)) {
477
+ slot[1].push([l, copyOnly(pA, mapA.get(l), singleMemoA)]);
478
+ } else {
479
+ slot[1].push([l, copyOnly(pB, mapB.get(l), singleMemoB)]);
480
+ }
481
+ }
482
+ return nid;
483
+ }
484
+
485
+ joinNodes(0, 0);
486
+ return mooreMinimize(canonicalizePlistOrder(nodes, 0), 0).plist;
487
+ }
488
+
489
+ function joinClosedPlists(plists) {
490
+ if (plists.length === 0) return UNIT_PLIST;
491
+ let acc = plists[0];
492
+ for (let i = 1; i < plists.length; i++) {
493
+ acc = joinTwoClosedPlists(acc, plists[i]);
494
+ }
495
+ return acc;
496
+ }
497
+
498
+ /**
499
+ * Intersect a concrete closed `inPlist` with a (possibly open) `filterPlist`.
500
+ * Returns `{ status: "ALWAYS_TRUE" | "ALWAYS_FALSE" | "RUNTIME_FILTER", plist }`.
501
+ */
502
+ function intersectConcreteWithFilter(inPlist, filterPlist) {
503
+ const nodes = [];
504
+ const memo = new Map();
505
+ const copyMemo = new Map();
506
+ let empty = false;
507
+
508
+ function copyConcrete(cId) {
509
+ if (copyMemo.has(cId)) return copyMemo.get(cId);
510
+ const nid = nodes.length;
511
+ copyMemo.set(cId, nid);
512
+ const [k, e] = inPlist[cId];
513
+ const slot = [k, []];
514
+ nodes.push(slot);
515
+ slot[1] = e.map(([l, t]) => [l, copyConcrete(t)]);
516
+ return nid;
517
+ }
518
+
519
+ function intersect(cId, fId) {
520
+ const key = `${cId}|${fId}`;
521
+ if (memo.has(key)) return memo.get(key);
522
+ const [cKind, cEdges] = inPlist[cId];
523
+ const [fKind, fEdges] = filterPlist[fId];
524
+ const cMap = new Map(cEdges);
525
+ const fMap = new Map(fEdges);
526
+
527
+ if (fKind === "any") {
528
+ return copyConcrete(cId);
529
+ }
530
+
531
+ if (fKind === "closed-product" || fKind === "open-product") {
532
+ if (cKind !== "closed-product") return -1;
533
+ if (fKind === "closed-product" && cEdges.length !== fEdges.length) return -1;
534
+ for (const [l] of fEdges) {
535
+ if (!cMap.has(l)) return -1;
536
+ }
537
+ const nid = nodes.length;
538
+ memo.set(key, nid);
539
+ const slot = ["closed-product", []];
540
+ nodes.push(slot);
541
+ for (const [l, cT] of cEdges) {
542
+ const child = fMap.has(l) ? intersect(cT, fMap.get(l)) : copyConcrete(cT);
543
+ if (child < 0) return -1;
544
+ slot[1].push([l, child]);
545
+ }
546
+ return nid;
547
+ }
548
+
549
+ if (fKind === "closed-union" || fKind === "open-union") {
550
+ if (cKind !== "closed-union") return -1;
551
+ const nid = nodes.length;
552
+ memo.set(key, nid);
553
+ const slot = ["closed-union", []];
554
+ nodes.push(slot);
555
+ for (const [l, cT] of cEdges) {
556
+ if (fMap.has(l)) {
557
+ const child = intersect(cT, fMap.get(l));
558
+ if (child >= 0) slot[1].push([l, child]);
559
+ } else if (fKind === "open-union") {
560
+ slot[1].push([l, copyConcrete(cT)]);
561
+ }
562
+ }
563
+ if (slot[1].length === 0) return -1;
564
+ return nid;
565
+ }
566
+
567
+ return -1;
568
+ }
569
+
570
+ const root = intersect(0, 0);
571
+ if (root < 0 || empty) return { status: "ALWAYS_FALSE", plist: null };
572
+ const narrowed = mooreMinimize(canonicalizePlistOrder(nodes, root), 0).plist;
573
+ if (schemasEquivalent(inPlist, 0, narrowed, 0)) {
574
+ return { status: "ALWAYS_TRUE", plist: inPlist };
575
+ }
576
+ return { status: "RUNTIME_FILTER", plist: narrowed };
577
+ }
578
+
579
+ // --- Static Analysis Helpers (Used Paths, Leading Guards, Branching SCC) ---
580
+
581
+ function ignoresInput(exp) {
582
+ if (!exp) return false;
583
+ switch (exp.op) {
584
+ case "product":
585
+ if (exp.fields.length === 0) return true;
586
+ return exp.fields.every((f) => ignoresInput(f.expr));
587
+ case "comp":
588
+ return exp.items.length > 0 && ignoresInput(exp.items[0]);
589
+ default:
590
+ return false;
591
+ }
592
+ }
593
+
594
+ /**
595
+ * Compute which top-level fields of `inScope` an expression reads:
596
+ * - `null` => ignores input completely (constant `{}` / `{} |nil`)
597
+ * - `"ALL"` => reads the whole input (cannot demux into individual fields)
598
+ * - `Set<label>` => ONLY reads those specific top-level `.label` fields!
599
+ */
600
+ function analyzeFieldUses(exp) {
601
+ if (!exp) return "ALL";
602
+ switch (exp.op) {
603
+ case "identity":
604
+ case "div":
605
+ case "vid":
606
+ case "ref":
607
+ case "filter":
608
+ case "code":
609
+ return "ALL";
610
+ case "empty":
611
+ return "ALL";
612
+ case "dot":
613
+ return new Set([exp.label]);
614
+ case "comp": {
615
+ if (exp.items.length === 0) return "ALL";
616
+ const first = exp.items[0];
617
+ if (first.op === "identity") {
618
+ return exp.items.length === 1 ? "ALL" : analyzeFieldUses({ op: "comp", items: exp.items.slice(1) });
619
+ }
620
+ return analyzeFieldUses(first);
621
+ }
622
+ case "product": {
623
+ if (exp.fields.length === 0) return null;
624
+ const merged = new Set();
625
+ let anyUsed = false;
626
+ for (const f of exp.fields) {
627
+ const sub = analyzeFieldUses(f.expr);
628
+ if (sub === "ALL") return "ALL";
629
+ if (sub !== null) {
630
+ anyUsed = true;
631
+ for (const l of sub) merged.add(l);
632
+ }
633
+ }
634
+ return anyUsed ? merged : null;
635
+ }
636
+ case "union": {
637
+ if (exp.items.length === 0) return "ALL";
638
+ const merged = new Set();
639
+ let anyUsed = false;
640
+ for (const br of exp.items) {
641
+ const sub = analyzeFieldUses(br);
642
+ if (sub === "ALL") return "ALL";
643
+ if (sub !== null) {
644
+ anyUsed = true;
645
+ for (const l of sub) merged.add(l);
646
+ }
647
+ }
648
+ return anyUsed ? merged : null;
649
+ }
650
+ default:
651
+ return "ALL";
652
+ }
653
+ }
654
+
655
+ /**
656
+ * Check if every use of top-level field `fieldLabel` inside `exp` begins with
657
+ * `.fieldLabel /tag` (for the SAME `tag`). Returns `tag` or `null`.
658
+ */
659
+ function findCommonLeadingTagOnField(exp, fieldLabel) {
660
+ let foundTag = undefined; // undefined = unused so far, null = conflict/non-div
661
+ function visit(e) {
662
+ if (foundTag === null || !e) return;
663
+ switch (e.op) {
664
+ case "dot":
665
+ if (e.label === fieldLabel) foundTag = null;
666
+ return;
667
+ case "comp": {
668
+ if (e.items.length === 0) return;
669
+ const [first, ...rest] = e.items;
670
+ if (first.op === "identity") {
671
+ visit({ op: "comp", items: rest });
672
+ return;
673
+ }
674
+ if (first.op === "dot") {
675
+ if (first.label !== fieldLabel) return;
676
+ // Look at next step in `rest` (skipping leading identities)
677
+ let idx = 0;
678
+ while (idx < rest.length && rest[idx].op === "identity") idx++;
679
+ const next = rest[idx];
680
+ if (next && next.op === "div") {
681
+ if (foundTag === undefined) foundTag = next.tag;
682
+ else if (foundTag !== next.tag) foundTag = null;
683
+ } else {
684
+ foundTag = null;
685
+ }
686
+ return;
687
+ }
688
+ visit(first);
689
+ return;
690
+ }
691
+ case "product":
692
+ for (const f of e.fields) visit(f.expr);
693
+ return;
694
+ case "union":
695
+ for (const b of e.items) visit(b);
696
+ return;
697
+ default:
698
+ return;
699
+ }
700
+ }
701
+ visit(exp);
702
+ return typeof foundTag === "string" ? foundTag : null;
703
+ }
704
+
705
+ /**
706
+ * Rewrite every `.fieldLabel /tag ...` occurrence inside `exp` (at top-level
707
+ * input position) into `.fieldLabel ...` once `/tag` has been hoisted!
708
+ */
709
+ function peelLeadingTagOnField(exp, fieldLabel, tag) {
710
+ if (!exp) return exp;
711
+ switch (exp.op) {
712
+ case "comp": {
713
+ if (exp.items.length === 0) return exp;
714
+ const [first, ...rest] = exp.items;
715
+ if (first.op === "identity") {
716
+ return { ...exp, items: [first, ...peelLeadingTagOnField({ op: "comp", items: rest }, fieldLabel, tag).items] };
717
+ }
718
+ if (first.op === "dot" && first.label === fieldLabel) {
719
+ let idx = 0;
720
+ while (idx < rest.length && rest[idx].op === "identity") idx++;
721
+ if (rest[idx] && rest[idx].op === "div" && rest[idx].tag === tag) {
722
+ const remaining = rest.slice(idx + 1);
723
+ if (remaining.length === 0) return first;
724
+ return { ...exp, items: [first, ...remaining] };
725
+ }
726
+ }
727
+ return { ...exp, items: [peelLeadingTagOnField(first, fieldLabel, tag), ...rest] };
728
+ }
729
+ case "product":
730
+ return {
731
+ ...exp,
732
+ fields: exp.fields.map((f) => ({ ...f, expr: peelLeadingTagOnField(f.expr, fieldLabel, tag) }))
733
+ };
734
+ case "union":
735
+ return {
736
+ ...exp,
737
+ items: exp.items.map((b) => peelLeadingTagOnField(b, fieldLabel, tag))
738
+ };
739
+ default:
740
+ return exp;
741
+ }
742
+ }
743
+
744
+ /**
745
+ * Compute sound leading head-tag guards `Map<key, Set<tag>> | "DEAD"`
746
+ * where `key` is `""` for root input or `label` for top-level field `.label`.
747
+ */
748
+ function computeLeadingGuards(exp) {
749
+ if (!exp) return new Map();
750
+ switch (exp.op) {
751
+ case "empty":
752
+ return "DEAD";
753
+ case "div": {
754
+ const m = new Map();
755
+ m.set("", new Set([exp.tag]));
756
+ return m;
757
+ }
758
+ case "identity":
759
+ case "dot":
760
+ case "vid":
761
+ case "ref":
762
+ case "filter":
763
+ case "code":
764
+ return new Map();
765
+ case "comp": {
766
+ if (exp.items.length === 0) return new Map();
767
+ const [first, ...rest] = exp.items;
768
+ if (first.op === "identity") {
769
+ return computeLeadingGuards({ op: "comp", items: rest });
770
+ }
771
+ if (first.op === "dot") {
772
+ const sub = computeLeadingGuards({ op: "comp", items: rest });
773
+ if (sub === "DEAD") return "DEAD";
774
+ const shifted = new Map();
775
+ if (sub.has("")) shifted.set(first.label, new Set(sub.get("")));
776
+ return shifted;
777
+ }
778
+ return computeLeadingGuards(first);
779
+ }
780
+ case "product": {
781
+ const merged = new Map();
782
+ for (const f of exp.fields) {
783
+ const sub = computeLeadingGuards(f.expr);
784
+ if (sub === "DEAD") return "DEAD";
785
+ for (const [k, tags] of sub.entries()) {
786
+ if (!merged.has(k)) {
787
+ merged.set(k, new Set(tags));
788
+ } else {
789
+ const inter = new Set([...merged.get(k)].filter((t) => tags.has(t)));
790
+ if (inter.size === 0) return "DEAD";
791
+ merged.set(k, inter);
792
+ }
793
+ }
794
+ }
795
+ return merged;
796
+ }
797
+ case "union": {
798
+ const liveSubs = [];
799
+ for (const b of exp.items) {
800
+ const sub = computeLeadingGuards(b);
801
+ if (sub !== "DEAD") liveSubs.push(sub);
802
+ }
803
+ if (liveSubs.length === 0) return "DEAD";
804
+ const common = new Map();
805
+ for (const [k, tags] of liveSubs[0].entries()) {
806
+ let inAll = true;
807
+ const unionSet = new Set(tags);
808
+ for (let i = 1; i < liveSubs.length; i++) {
809
+ const other = liveSubs[i].get(k);
810
+ if (!other) {
811
+ inAll = false;
812
+ break;
813
+ }
814
+ for (const t of other) unionSet.add(t);
815
+ }
816
+ if (inAll) common.set(k, unionSet);
817
+ }
818
+ return common;
819
+ }
820
+ default:
821
+ return new Map();
822
+ }
823
+ }
824
+
825
+ /**
826
+ * Compute strongly connected component & branching-recursion status for a relation
827
+ * in `kir.rels` (matches `BlueprintRegistryV2.isBranchingRecursive`).
828
+ */
829
+ function analyzeBranchingSCC(kir, relHash) {
830
+ const directRefs = (h) => {
831
+ const rel = kir.rels?.[h];
832
+ const refs = new Set();
833
+ if (!rel) return refs;
834
+ const walk = (e) => {
835
+ if (!e) return;
836
+ if (e.op === "ref") {
837
+ const target = resolveRelHash(kir, e.ref);
838
+ if (target) refs.add(target);
839
+ } else if (e.items) e.items.forEach(walk);
840
+ else if (e.fields) e.fields.forEach((f) => walk(f.expr));
841
+ };
842
+ walk(rel.body);
843
+ return refs;
844
+ };
845
+
846
+ const reachable = new Set();
847
+ const q = [...directRefs(relHash)];
848
+ for (let i = 0; i < q.length; i++) {
849
+ const h = q[i];
850
+ if (reachable.has(h)) continue;
851
+ reachable.add(h);
852
+ for (const nxt of directRefs(h)) {
853
+ if (!reachable.has(nxt)) q.push(nxt);
854
+ }
855
+ }
856
+ if (!reachable.has(relHash)) return { scc: new Set(), isBranching: false };
857
+
858
+ const scc = new Set([relHash]);
859
+ for (const h of reachable) {
860
+ if (h === relHash) continue;
861
+ const seen = new Set();
862
+ const stack = [...directRefs(h)];
863
+ while (stack.length > 0) {
864
+ const cur = stack.pop();
865
+ if (cur === relHash) {
866
+ scc.add(h);
867
+ break;
868
+ }
869
+ if (seen.has(cur) || !reachable.has(cur)) continue;
870
+ seen.add(cur);
871
+ for (const nxt of directRefs(cur)) stack.push(nxt);
872
+ }
873
+ }
874
+
875
+ const maxCalls = (e) => {
876
+ if (!e) return 0;
877
+ if (e.op === "ref") {
878
+ const t = resolveRelHash(kir, e.ref);
879
+ return t && scc.has(t) ? 1 : 0;
880
+ }
881
+ if (e.op === "comp") return e.items.reduce((a, c) => a + maxCalls(c), 0);
882
+ if (e.op === "product") return e.fields.reduce((a, f) => a + maxCalls(f.expr), 0);
883
+ if (e.op === "union") return Math.max(0, ...e.items.map(maxCalls));
884
+ return 0;
885
+ };
886
+
887
+ let isBranching = false;
888
+ for (const h of scc) {
889
+ if (maxCalls(kir.rels[h]?.body) >= 2) {
890
+ isBranching = true;
891
+ break;
892
+ }
893
+ }
894
+ return { scc, isBranching };
895
+ }
896
+
897
+ // --- Monomorphizing Compiler: KIR-P + S_in -> Concrete Validated `mono` kTVM ---
898
+
899
+ const COMPILE_CACHE = new WeakMap();
900
+
901
+ export function compileKIRToKTVM(
902
+ kirOrObject,
903
+ entryName,
904
+ concreteInputPlist,
905
+ { validate = true, verifyTables = true, allowRetypeFallback = true, useCache = true } = {}
906
+ ) {
907
+ const { kir, sourceObject } = normalizeKIR(kirOrObject);
908
+ const resolvedEntry = resolveRelHash(kir, entryName || kir.main);
909
+ if (!resolvedEntry) {
910
+ throw new KTVMSchemaError(`Unknown entry relation '${entryName || kir.main}'`);
911
+ }
912
+ if (!Array.isArray(concreteInputPlist) || concreteInputPlist.length === 0) {
913
+ throw new KTVMSchemaError("compileKIRToKTVM requires a closed concrete k-wire input pattern");
914
+ }
915
+ const closedInput = concreteInputPlist.map(([kind, edges]) => {
916
+ if (kind === "open-union") return ["closed-union", edges];
917
+ if (kind === "open-product") return ["closed-product", edges];
918
+ return [kind, edges];
919
+ });
920
+ if (!isClosedPlist(closedInput)) {
921
+ throw new KTVMSchemaError("compileKIRToKTVM requires a closed concrete k-wire input pattern");
922
+ }
923
+
924
+ const normalizedIn = mooreMinimize(closedInput, 0).plist;
925
+ const inKey = mooreKey(normalizedIn, 0);
926
+
927
+ if (useCache) {
928
+ let byKir = COMPILE_CACHE.get(kirOrObject);
929
+ if (byKir && byKir.has(`${resolvedEntry}::${inKey}`)) {
930
+ return { ...byKir.get(`${resolvedEntry}::${inKey}`), cached: true };
931
+ }
932
+ }
933
+
934
+ try {
935
+ const res = compileKIRInternal(kir, resolvedEntry, normalizedIn, { validate, verifyTables });
936
+ if (useCache) {
937
+ let byKir = COMPILE_CACHE.get(kirOrObject);
938
+ if (!byKir) {
939
+ byKir = new Map();
940
+ COMPILE_CACHE.set(kirOrObject, byKir);
941
+ }
942
+ byKir.set(`${resolvedEntry}::${inKey}`, res);
943
+ }
944
+ return { ...res, cached: false };
945
+ } catch (err) {
946
+ // Optional fallback for non-converged `.ko` relations via retypeObjectRelationForBackend
947
+ if (allowRetypeFallback && sourceObject && !(err instanceof KTVMSchemaError)) {
948
+ const retyped = retypeObjectRelationForBackend(sourceObject, resolvedEntry, normalizedIn);
949
+ const res = compileKIRInternal(retyped.kir, retyped.entryName, normalizedIn, { validate, verifyTables });
950
+ return { ...res, cached: false, retyped: true };
951
+ }
952
+ throw err;
953
+ }
954
+ }
955
+
956
+ function compileKIRInternal(kir, entryHash, entryInPlist, { validate, verifyTables }) {
957
+ const findCode = makeCodeLookup(kir);
958
+ const displayNames = buildDisplayNameMap(kir);
959
+
960
+ // Deduplicated concrete schemas for emitted `mono` module
961
+ const schemaByMoore = new Map();
962
+ const emittedSchemas = [];
963
+ let schemaSeq = 0;
964
+
965
+ function internSchema(plist, hint = "S") {
966
+ const min = mooreMinimize(plist, 0);
967
+ if (min.plist[0][0] === "closed-product" && min.plist[0][1].length === 0) {
968
+ return { expr: S.unit(), plist: min.plist };
969
+ }
970
+ if (schemaByMoore.has(min.key)) return schemaByMoore.get(min.key);
971
+ const prefix = `$${sanitizeIdent(hint, "S")}_${schemaSeq++}`;
972
+ const { decls, rootExpr } = plistToSchemaAst(min.plist, prefix);
973
+ for (const d of decls) emittedSchemas.push(d);
974
+ const rec = { expr: rootExpr, plist: min.plist };
975
+ schemaByMoore.set(min.key, rec);
976
+ return rec;
977
+ }
978
+
979
+ const sccCache = new Map();
980
+ function getSccInfo(h) {
981
+ if (!sccCache.has(h)) sccCache.set(h, analyzeBranchingSCC(kir, h));
982
+ return sccCache.get(h);
983
+ }
984
+
985
+ const specMemo = new Map(); // `${relHash}::${mooreKey(inPlist)}` -> { procName, inPlist, outPlist }
986
+ const emittedProcs = [];
987
+ let procSeq = 0;
988
+
989
+ function specializeRel(relHash, inPlist, isEntry = false, callerDesiredOut = null) {
990
+ const inMin = mooreMinimize(inPlist, 0);
991
+ const outHintMin = callerDesiredOut ? mooreMinimize(callerDesiredOut, 0) : null;
992
+ const memoKey = `${relHash}::${inMin.key}::${outHintMin ? outHintMin.key : "*"}`;
993
+ if (specMemo.has(memoKey)) return specMemo.get(memoKey);
994
+
995
+ const rel = kir.rels[relHash];
996
+ if (!rel) throw new KTVMSchemaError(`Unknown KIR relation '${relHash}'`);
997
+
998
+ const niceName = sanitizeIdent(displayNames.get(relHash) || relHash, "rel");
999
+ const procName = `@${niceName}_${procSeq++}`;
1000
+
1001
+ // Build local pattern graph and unify `inputPattern` with concrete `inPlist`
1002
+ const lpg = new LocalPatternGraph(rel.patternGraph, findCode);
1003
+ const localInId = lpg.kirIdToLocal.get(rel.inputPattern);
1004
+ const localOutId = lpg.kirIdToLocal.get(rel.outputPattern);
1005
+
1006
+ if (localInId != null) {
1007
+ lpg.unifyWithConcrete(localInId, inMin.plist, 0, { strictClosedUnion: isEntry });
1008
+ }
1009
+ // If caller supplies a concrete expected return schema (binding output-only
1010
+ // type parameters like `nil = {} |nil : list[X]`), unify `outputPattern` too!
1011
+ if (outHintMin && localOutId != null) {
1012
+ try {
1013
+ lpg.unifyWithConcrete(localOutId, outHintMin.plist, 0, { strictClosedUnion: false });
1014
+ } catch {
1015
+ // Ignore if caller expects a supertype/coercion; coerce at call site handles it!
1016
+ }
1017
+ }
1018
+
1019
+ // Try predicting closed output schema before lowering body (essential for recursion!)
1020
+ let predictedOut = null;
1021
+ if (localOutId != null) {
1022
+ const candidate = lpg.extractPlist(localOutId, { closeOpenUnions: true });
1023
+ if (isClosedPlist(candidate)) {
1024
+ predictedOut = mooreMinimize(candidate, 0).plist;
1025
+ }
1026
+ }
1027
+ if (!predictedOut && outHintMin) {
1028
+ predictedOut = outHintMin.plist;
1029
+ }
1030
+
1031
+ const lpgClosedOut = (exp) => {
1032
+ const patId = exp?.patterns?.[1];
1033
+ if (patId == null || !lpg.kirIdToLocal.has(patId)) return null;
1034
+ const cand = lpg.extractPlist(lpg.kirIdToLocal.get(patId), { closeOpenUnions: true });
1035
+ return isClosedPlist(cand) ? cand : null;
1036
+ };
1037
+
1038
+ const sccInfo = getSccInfo(relHash);
1039
+ const isRecursive = sccInfo.scc.size > 0;
1040
+
1041
+ if (isRecursive && !predictedOut) {
1042
+ throw new KTVMSchemaError(
1043
+ `Non-converged recursive relation '${niceName}' could not close output schema statically`
1044
+ );
1045
+ }
1046
+
1047
+ const specRec = {
1048
+ procName,
1049
+ inPlist: inMin.plist,
1050
+ outPlist: predictedOut
1051
+ };
1052
+ if (predictedOut) {
1053
+ specMemo.set(memoKey, specRec);
1054
+ }
1055
+
1056
+ // Lower relation body into network statements
1057
+ let varSeq = 0;
1058
+ const freshVar = (p = "v") => `%${sanitizeIdent(p, "v")}_${varSeq++}`;
1059
+
1060
+ const emitChan = (stmts, plist, hint = "v") => {
1061
+ const name = freshVar(hint);
1062
+ const sRec = internSchema(plist, hint);
1063
+ stmts.push({ op: "chan", name, schema: sRec.expr });
1064
+ return name;
1065
+ };
1066
+
1067
+ const emitBarrier = (stmts) => {
1068
+ const name = freshVar("bar");
1069
+ stmts.push({ op: "barrier", name });
1070
+ return name;
1071
+ };
1072
+
1073
+ const emitCoerceOrSplice = (stmts, srcVar, srcPlist, dstVar, dstPlist) => {
1074
+ if (schemasEquivalent(srcPlist, 0, dstPlist, 0)) {
1075
+ stmts.push({ op: "splice", src: srcVar, dst: dstVar });
1076
+ } else {
1077
+ const sRec = internSchema(srcPlist, "cs");
1078
+ const dRec = internSchema(dstPlist, "cd");
1079
+ stmts.push({
1080
+ op: "coerce",
1081
+ src: srcVar,
1082
+ srcSchema: sRec.expr,
1083
+ dst: dstVar,
1084
+ dstSchema: dRec.expr
1085
+ });
1086
+ }
1087
+ };
1088
+
1089
+ function liveChansOf(scope) {
1090
+ if (scope.kind === "none") return [];
1091
+ if (scope.kind === "single") return [{ varName: scope.varName, plist: scope.plist }];
1092
+ return [...scope.fields.values()];
1093
+ }
1094
+
1095
+ function drainScope(scope, stmts) {
1096
+ const live = liveChansOf(scope);
1097
+ if (live.length === 0) return null;
1098
+ const bar = emitBarrier(stmts);
1099
+ for (const { varName, plist } of live) {
1100
+ const sRec = internSchema(plist, "dr");
1101
+ stmts.push({ op: "drain", src: varName, schema: sRec.expr, barrier: bar });
1102
+ }
1103
+ return bar;
1104
+ }
1105
+
1106
+ function failScope(scope, desiredOut, stmts) {
1107
+ const outPl = desiredOut || UNIT_PLIST;
1108
+ const outVar = emitChan(stmts, outPl, "fail");
1109
+ const live = liveChansOf(scope).map((x) => x.varName);
1110
+ stmts.push({ op: "spec", inputs: live, outputs: [outVar], branches: [] });
1111
+ return { outVar, outPlist: outPl, alwaysFails: true };
1112
+ }
1113
+
1114
+ function materializeSingle(scope, stmts) {
1115
+ if (scope.kind === "single") return { varName: scope.varName, plist: scope.plist };
1116
+ if (scope.kind === "none") {
1117
+ const u = emitChan(stmts, UNIT_PLIST, "u");
1118
+ stmts.push({ op: "const_unit", dst: u });
1119
+ return { varName: u, plist: UNIT_PLIST };
1120
+ }
1121
+ const entries = [...scope.fields.entries()].sort(([a], [b]) => compareLabels(a, b));
1122
+ if (entries.length === 0) {
1123
+ const u = emitChan(stmts, UNIT_PLIST, "u");
1124
+ stmts.push({ op: "const_unit", dst: u });
1125
+ return { varName: u, plist: UNIT_PLIST };
1126
+ }
1127
+ const prodPl = composeClosedProductPlist(entries.map(([label, f]) => ({ label, plist: f.plist })));
1128
+ const outVar = emitChan(stmts, prodPl, "mat");
1129
+ const sRec = internSchema(prodPl, "mat");
1130
+ stmts.push({
1131
+ op: "mux",
1132
+ fields: entries.map(([label, f]) => ({ label, name: f.varName })),
1133
+ dst: outVar,
1134
+ schema: sRec.expr
1135
+ });
1136
+ return { varName: outVar, plist: prodPl };
1137
+ }
1138
+
1139
+ function maybeDemuxScope(scope, exprUses, stmts) {
1140
+ if (scope.kind !== "single") return scope;
1141
+ if (scope.plist[0][0] !== "closed-product") return scope;
1142
+ const pf = productFields(scope.plist, 0);
1143
+ if (!pf || pf.length === 0) return scope;
1144
+ if (exprUses === "ALL" || exprUses === null) return scope;
1145
+
1146
+ const fields = new Map();
1147
+ const demuxFields = [];
1148
+ for (const f of pf) {
1149
+ const fPl = subPlist(scope.plist, f.targetId);
1150
+ const v = emitChan(stmts, fPl, f.label);
1151
+ fields.set(f.label, { varName: v, plist: fPl });
1152
+ demuxFields.push({ label: f.label, name: v });
1153
+ }
1154
+ const sRec = internSchema(scope.plist, "dm");
1155
+ stmts.push({ op: "demux", src: scope.varName, schema: sRec.expr, fields: demuxFields });
1156
+ return { kind: "fields", plist: scope.plist, fields };
1157
+ }
1158
+
1159
+ /**
1160
+ * Lower `exp` consuming every live channel in `scope` exactly once and
1161
+ * returning `{ outVar, outPlist, lastSccToken? }`.
1162
+ */
1163
+ function lowerExp(exp, scope, desiredOut, stmts, afterToken = null) {
1164
+ switch (exp.op) {
1165
+ case "identity": {
1166
+ const single = materializeSingle(scope, stmts);
1167
+ return { outVar: single.varName, outPlist: single.plist };
1168
+ }
1169
+
1170
+ case "empty": {
1171
+ return failScope(scope, desiredOut, stmts);
1172
+ }
1173
+
1174
+ case "dot": {
1175
+ if (scope.kind === "fields") {
1176
+ if (!scope.fields.has(exp.label)) {
1177
+ return failScope(scope, desiredOut, stmts);
1178
+ }
1179
+ const chosen = scope.fields.get(exp.label);
1180
+ const others = [...scope.fields.entries()].filter(([l]) => l !== exp.label);
1181
+ if (others.length === 0) {
1182
+ return { outVar: chosen.varName, outPlist: chosen.plist };
1183
+ }
1184
+ const bar = emitBarrier(stmts);
1185
+ for (const [, f] of others) {
1186
+ stmts.push({ op: "drain", src: f.varName, schema: internSchema(f.plist, "dr").expr, barrier: bar });
1187
+ }
1188
+ const gated = emitChan(stmts, chosen.plist, exp.label);
1189
+ stmts.push({ op: "gate", barrier: bar, src: chosen.varName, dst: gated });
1190
+ return { outVar: gated, outPlist: chosen.plist };
1191
+ }
1192
+
1193
+ const single = materializeSingle(scope, stmts);
1194
+ const pf = productFields(single.plist, 0);
1195
+ const fInfo = productFieldInfo(single.plist, 0, exp.label);
1196
+ if (!pf || !fInfo) {
1197
+ return failScope({ kind: "single", ...single }, desiredOut, stmts);
1198
+ }
1199
+ const targetPl = subPlist(single.plist, fInfo.targetId);
1200
+ if (pf.length === 1) {
1201
+ const outVar = emitChan(stmts, targetPl, exp.label);
1202
+ stmts.push({
1203
+ op: "demux",
1204
+ src: single.varName,
1205
+ schema: internSchema(single.plist, "dm").expr,
1206
+ fields: [{ label: exp.label, name: outVar }]
1207
+ });
1208
+ return { outVar, outPlist: targetPl };
1209
+ }
1210
+ const bar = emitBarrier(stmts);
1211
+ const demuxFields = [];
1212
+ let chosenVar = null;
1213
+ const drains = [];
1214
+ for (const f of pf) {
1215
+ const fPl = subPlist(single.plist, f.targetId);
1216
+ const v = emitChan(stmts, fPl, f.label);
1217
+ demuxFields.push({ label: f.label, name: v });
1218
+ if (f.label === exp.label) chosenVar = v;
1219
+ else drains.push({ src: v, plist: fPl });
1220
+ }
1221
+ stmts.push({
1222
+ op: "demux",
1223
+ src: single.varName,
1224
+ schema: internSchema(single.plist, "dm").expr,
1225
+ fields: demuxFields
1226
+ });
1227
+ for (const d of drains) {
1228
+ stmts.push({ op: "drain", src: d.src, schema: internSchema(d.plist, "dr").expr, barrier: bar });
1229
+ }
1230
+ const outVar = emitChan(stmts, targetPl, exp.label);
1231
+ stmts.push({ op: "gate", barrier: bar, src: chosenVar, dst: outVar });
1232
+ return { outVar, outPlist: targetPl };
1233
+ }
1234
+
1235
+ case "div": {
1236
+ const single = materializeSingle(scope, stmts);
1237
+ const info = unionTagInfo(single.plist, 0, exp.tag);
1238
+ if (!info) {
1239
+ return failScope({ kind: "single", ...single }, desiredOut, stmts);
1240
+ }
1241
+ const targetPl = subPlist(single.plist, info.targetId);
1242
+ const outVar = emitChan(stmts, targetPl, "m");
1243
+ stmts.push({ op: "match", tag: exp.tag, src: single.varName, dst: outVar });
1244
+ return { outVar, outPlist: targetPl };
1245
+ }
1246
+
1247
+ case "vid": {
1248
+ const single = materializeSingle(scope, stmts);
1249
+ // Determine target union schema: prefer `desiredOut` if compatible!
1250
+ let outPl = null;
1251
+ if (desiredOut) {
1252
+ const info = unionTagInfo(desiredOut, 0, exp.tag);
1253
+ if (info) {
1254
+ outPl = desiredOut;
1255
+ }
1256
+ }
1257
+ if (!outPl) {
1258
+ // Check if KIR-P outPattern already closed to a concrete union containing `exp.tag`
1259
+ const outPatId = exp.patterns?.[1];
1260
+ const localId = outPatId != null ? lpg.kirIdToLocal.get(outPatId) : null;
1261
+ if (localId != null) {
1262
+ const cand = lpg.extractPlist(localId, { closeOpenUnions: true });
1263
+ if (isClosedPlist(cand)) {
1264
+ const info = unionTagInfo(cand, 0, exp.tag);
1265
+ if (info) {
1266
+ const targetSub = subPlist(cand, info.targetId);
1267
+ if (schemasEquivalent(single.plist, 0, targetSub, 0)) {
1268
+ outPl = cand;
1269
+ }
1270
+ }
1271
+ }
1272
+ }
1273
+ }
1274
+ if (!outPl) {
1275
+ outPl = composeSingletonUnionPlist(exp.tag, single.plist);
1276
+ }
1277
+ const info = unionTagInfo(outPl, 0, exp.tag);
1278
+ const expectedPayload = subPlist(outPl, info.targetId);
1279
+ let payloadVar = single.varName;
1280
+ if (!schemasEquivalent(single.plist, 0, expectedPayload, 0)) {
1281
+ payloadVar = emitChan(stmts, expectedPayload, "wp");
1282
+ emitCoerceOrSplice(stmts, single.varName, single.plist, payloadVar, expectedPayload);
1283
+ }
1284
+ const outVar = emitChan(stmts, outPl, "w");
1285
+ stmts.push({ op: "wrap", tag: exp.tag, src: payloadVar, dst: outVar });
1286
+ return { outVar, outPlist: outPl };
1287
+ }
1288
+
1289
+ case "filter":
1290
+ case "code": {
1291
+ const single = materializeSingle(scope, stmts);
1292
+ let filterPlist = null;
1293
+ if (exp.op === "code") {
1294
+ filterPlist = codeHashToPlist(exp.code, findCode);
1295
+ } else {
1296
+ const patId = exp.patterns?.[0];
1297
+ const localId = patId != null ? lpg.kirIdToLocal.get(patId) : null;
1298
+ if (localId != null) {
1299
+ filterPlist = lpg.extractPlist(localId, { closeOpenUnions: false });
1300
+ }
1301
+ }
1302
+ if (!filterPlist) {
1303
+ return { outVar: single.varName, outPlist: single.plist };
1304
+ }
1305
+ const check = intersectConcreteWithFilter(single.plist, filterPlist);
1306
+ if (check.status === "ALWAYS_TRUE") {
1307
+ return { outVar: single.varName, outPlist: single.plist };
1308
+ }
1309
+ if (check.status === "ALWAYS_FALSE") {
1310
+ return failScope({ kind: "single", ...single }, desiredOut || single.plist, stmts);
1311
+ }
1312
+ // Runtime partial filter via iterative `dpda_coerce`!
1313
+ const outVar = emitChan(stmts, check.plist, "flt");
1314
+ emitCoerceOrSplice(stmts, single.varName, single.plist, outVar, check.plist);
1315
+ return { outVar, outPlist: check.plist };
1316
+ }
1317
+
1318
+ case "ref": {
1319
+ const single = materializeSingle(scope, stmts);
1320
+ if (isIntrinsic(exp.ref)) {
1321
+ if (isIdentityIntrinsic(exp.ref)) {
1322
+ return { outVar: single.varName, outPlist: single.plist };
1323
+ }
1324
+ throw unsupportedIntrinsic("kTVM", exp.ref);
1325
+ }
1326
+ const targetHash = resolveRelHash(kir, exp.ref);
1327
+ if (!targetHash) {
1328
+ throw new KTVMSchemaError(`Unresolved relation ref '${exp.ref}'`);
1329
+ }
1330
+ const callDesiredOut = desiredOut || lpgClosedOut(exp);
1331
+ let childSpec;
1332
+ try {
1333
+ childSpec = specializeRel(targetHash, single.plist, false, callDesiredOut);
1334
+ } catch (err) {
1335
+ if (err instanceof KTVMSchemaError) {
1336
+ // Internal call whose concrete argument is disjoint from callee's
1337
+ // partial input contract cannot match at runtime -> always fails.
1338
+ return failScope({ kind: "single", ...single }, callDesiredOut || desiredOut, stmts);
1339
+ }
1340
+ throw err;
1341
+ }
1342
+ const outVar = emitChan(stmts, childSpec.outPlist, "call");
1343
+ const isSameScc = sccInfo.isBranching && sccInfo.scc.has(targetHash);
1344
+ const token = isSameScc ? freshVar("tok") : null;
1345
+ stmts.push({
1346
+ op: "spawn",
1347
+ target: childSpec.procName,
1348
+ schemaArgs: [],
1349
+ inputs: [single.varName],
1350
+ outputs: [outVar],
1351
+ after: isSameScc ? afterToken : null,
1352
+ token
1353
+ });
1354
+ return { outVar, outPlist: childSpec.outPlist, sccToken: token };
1355
+ }
1356
+
1357
+ case "comp": {
1358
+ if (exp.items.length === 0) {
1359
+ const single = materializeSingle(scope, stmts);
1360
+ return { outVar: single.varName, outPlist: single.plist };
1361
+ }
1362
+ let curScope = scope;
1363
+ let curAfter = afterToken;
1364
+ let lastSccTok = null;
1365
+ let lastRes = null;
1366
+ for (let i = 0; i < exp.items.length; i++) {
1367
+ const isLast = i === exp.items.length - 1;
1368
+ const stepDesired = isLast ? (desiredOut || lpgClosedOut(exp.items[i])) : lpgClosedOut(exp.items[i]);
1369
+ const res = lowerExp(exp.items[i], curScope, stepDesired, stmts, curAfter);
1370
+ if (res.sccToken) {
1371
+ lastSccTok = res.sccToken;
1372
+ curAfter = res.sccToken;
1373
+ }
1374
+ lastRes = res;
1375
+ if (!isLast) {
1376
+ curScope = { kind: "single", varName: res.outVar, plist: res.outPlist };
1377
+ }
1378
+ }
1379
+ return { ...lastRes, sccToken: lastSccTok };
1380
+ }
1381
+
1382
+ case "product": {
1383
+ // Empty product `{}` -> unit (draining input to enforce strict K partiality!)
1384
+ if (exp.fields.length === 0) {
1385
+ const bar = drainScope(scope, stmts);
1386
+ const u = emitChan(stmts, UNIT_PLIST, "u");
1387
+ stmts.push({ op: "const_unit", dst: u });
1388
+ if (!bar) return { outVar: u, outPlist: UNIT_PLIST };
1389
+ const gated = emitChan(stmts, UNIT_PLIST, "ug");
1390
+ stmts.push({ op: "gate", barrier: bar, src: u, dst: gated });
1391
+ return { outVar: gated, outPlist: UNIT_PLIST };
1392
+ }
1393
+
1394
+ // Canonical field order for `mux`
1395
+ let fields = [...exp.fields].sort((a, b) => compareLabels(a.label, b.label));
1396
+
1397
+ // Rule 1: Demux input product ONCE if all branches only project fields!
1398
+ const wholeUses = analyzeFieldUses({ op: "product", fields });
1399
+ let curScope = maybeDemuxScope(scope, wholeUses, stmts);
1400
+
1401
+ // Rule 2: Common leading `/tag` hoisting on any field used 2+ times with same tag!
1402
+ // (Transforms `_reverse`'s `.xs /cons .cdr` + `.xs /cons .car` into ZERO tees!)
1403
+ if (curScope.kind === "fields") {
1404
+ const fieldUseCounts = new Map();
1405
+ for (const f of fields) {
1406
+ const u = analyzeFieldUses(f.expr);
1407
+ if (u instanceof Set) {
1408
+ for (const l of u) fieldUseCounts.set(l, (fieldUseCounts.get(l) || 0) + 1);
1409
+ }
1410
+ }
1411
+ for (const [label, count] of fieldUseCounts.entries()) {
1412
+ if (count < 2) continue;
1413
+ const chInfo = curScope.fields.get(label);
1414
+ if (!chInfo || chInfo.plist[0][0] !== "closed-union") continue;
1415
+ const commonTag = findCommonLeadingTagOnField({ op: "product", fields }, label);
1416
+ if (!commonTag) continue;
1417
+ const tInfo = unionTagInfo(chInfo.plist, 0, commonTag);
1418
+ if (!tInfo) {
1419
+ return failScope(curScope, desiredOut, stmts);
1420
+ }
1421
+ const payloadPl = subPlist(chInfo.plist, tInfo.targetId);
1422
+ const payloadVar = emitChan(stmts, payloadPl, `${label}_${commonTag}`);
1423
+ stmts.push({ op: "match", tag: commonTag, src: chInfo.varName, dst: payloadVar });
1424
+ curScope = {
1425
+ kind: "fields",
1426
+ plist: curScope.plist,
1427
+ fields: new Map(curScope.fields)
1428
+ };
1429
+ curScope.fields.set(label, { varName: payloadVar, plist: payloadPl });
1430
+ fields = fields.map((f) => ({
1431
+ ...f,
1432
+ expr: peelLeadingTagOnField(f.expr, label, commonTag)
1433
+ }));
1434
+
1435
+ // And if payload is a product accessed only by nested `.sub`, demux it right here too!
1436
+ // Wait: nested `.label .sub` patterns: check if every branch reading `label` immediately does `.sub`!
1437
+ if (payloadPl[0][0] === "closed-product") {
1438
+ const subPf = productFields(payloadPl, 0);
1439
+ if (subPf && subPf.length >= 2) {
1440
+ const subProjectionOk = checkAllUsesAreFieldDot({ op: "product", fields }, label);
1441
+ if (subProjectionOk) {
1442
+ const subDemuxFields = [];
1443
+ const subNames = new Map();
1444
+ for (const sf of subPf) {
1445
+ const sfPl = subPlist(payloadPl, sf.targetId);
1446
+ const sv = emitChan(stmts, sfPl, sf.label);
1447
+ const synthLabel = `__${label}__${sf.label}`;
1448
+ subDemuxFields.push({ label: sf.label, name: sv });
1449
+ subNames.set(sf.label, synthLabel);
1450
+ curScope.fields.set(synthLabel, { varName: sv, plist: sfPl });
1451
+ }
1452
+ stmts.push({
1453
+ op: "demux",
1454
+ src: payloadVar,
1455
+ schema: internSchema(payloadPl, "dm").expr,
1456
+ fields: subDemuxFields
1457
+ });
1458
+ curScope.fields.delete(label);
1459
+ fields = fields.map((f) => ({
1460
+ ...f,
1461
+ expr: rewriteFieldSubDot(f.expr, label, subNames)
1462
+ }));
1463
+ }
1464
+ }
1465
+ }
1466
+ }
1467
+ }
1468
+
1469
+ // Compute exact per-branch input scopes & allocate minimal `tee`s / `drain`s
1470
+ const branchScopes = fields.map(() => null);
1471
+ let unusedBarrier = null;
1472
+
1473
+ if (curScope.kind === "none") {
1474
+ for (let i = 0; i < fields.length; i++) branchScopes[i] = { kind: "none" };
1475
+ } else if (curScope.kind === "single") {
1476
+ const readers = [];
1477
+ for (let i = 0; i < fields.length; i++) {
1478
+ if (ignoresInput(fields[i].expr)) {
1479
+ branchScopes[i] = { kind: "none" };
1480
+ } else {
1481
+ readers.push(i);
1482
+ }
1483
+ }
1484
+ if (readers.length === 0) {
1485
+ unusedBarrier = drainScope(curScope, stmts);
1486
+ } else if (readers.length === 1) {
1487
+ branchScopes[readers[0]] = curScope;
1488
+ } else {
1489
+ const copies = readers.map((idx) => emitChan(stmts, curScope.plist, `t${idx}`));
1490
+ stmts.push({ op: "tee", src: curScope.varName, dsts: copies });
1491
+ readers.forEach((bIdx, k) => {
1492
+ branchScopes[bIdx] = { kind: "single", varName: copies[k], plist: curScope.plist };
1493
+ });
1494
+ }
1495
+ } else {
1496
+ // curScope.kind === "fields": per-field minimal fan-out!
1497
+ const branchFieldMaps = fields.map(() => new Map());
1498
+ const perFieldUses = fields.map((f) => analyzeFieldUses(f.expr));
1499
+ const unusedFields = [];
1500
+
1501
+ for (const [label, chInfo] of curScope.fields.entries()) {
1502
+ const users = [];
1503
+ for (let i = 0; i < fields.length; i++) {
1504
+ const u = perFieldUses[i];
1505
+ if (u === "ALL" || (u instanceof Set && u.has(label))) {
1506
+ users.push(i);
1507
+ }
1508
+ }
1509
+ if (users.length === 0) {
1510
+ unusedFields.push(chInfo);
1511
+ } else if (users.length === 1) {
1512
+ branchFieldMaps[users[0]].set(label, chInfo);
1513
+ } else {
1514
+ const copies = users.map((idx) => emitChan(stmts, chInfo.plist, `${label}_${idx}`));
1515
+ stmts.push({ op: "tee", src: chInfo.varName, dsts: copies });
1516
+ users.forEach((bIdx, k) => {
1517
+ branchFieldMaps[bIdx].set(label, { varName: copies[k], plist: chInfo.plist });
1518
+ });
1519
+ }
1520
+ }
1521
+
1522
+ if (unusedFields.length > 0) {
1523
+ unusedBarrier = emitBarrier(stmts);
1524
+ for (const chInfo of unusedFields) {
1525
+ stmts.push({
1526
+ op: "drain",
1527
+ src: chInfo.varName,
1528
+ schema: internSchema(chInfo.plist, "dr").expr,
1529
+ barrier: unusedBarrier
1530
+ });
1531
+ }
1532
+ }
1533
+
1534
+ for (let i = 0; i < fields.length; i++) {
1535
+ const fm = branchFieldMaps[i];
1536
+ if (fm.size === 0) branchScopes[i] = { kind: "none" };
1537
+ else branchScopes[i] = { kind: "fields", plist: curScope.plist, fields: fm };
1538
+ }
1539
+ }
1540
+
1541
+ // Determine desired per-field output schemas from `desiredOut` or `lpg`
1542
+ const prodDesired = desiredOut || lpgClosedOut(exp);
1543
+ const desiredFieldMap = new Map();
1544
+ if (prodDesired && prodDesired[0][0] === "closed-product") {
1545
+ for (const f of productFields(prodDesired, 0) || []) {
1546
+ desiredFieldMap.set(f.label, subPlist(prodDesired, f.targetId));
1547
+ }
1548
+ }
1549
+
1550
+ // Lower every field (chaining `after %tok` across branching recursive sibling calls!)
1551
+ let curAfter = afterToken;
1552
+ let lastSccTok = null;
1553
+ const loweredFields = [];
1554
+ for (let i = 0; i < fields.length; i++) {
1555
+ const f = fields[i];
1556
+ const fDesired = desiredFieldMap.get(f.label) || lpgClosedOut(f.expr);
1557
+ const res = lowerExp(
1558
+ f.expr,
1559
+ branchScopes[i],
1560
+ fDesired,
1561
+ stmts,
1562
+ curAfter
1563
+ );
1564
+ if (res.sccToken) {
1565
+ curAfter = res.sccToken;
1566
+ lastSccTok = res.sccToken;
1567
+ }
1568
+ loweredFields.push({ label: f.label, varName: res.outVar, plist: res.outPlist });
1569
+ }
1570
+
1571
+ const prodPl = composeClosedProductPlist(loweredFields.map((f) => ({ label: f.label, plist: f.plist })));
1572
+ const muxOut = emitChan(stmts, prodPl, "prod");
1573
+ stmts.push({
1574
+ op: "mux",
1575
+ fields: loweredFields.map((f) => ({ label: f.label, name: f.varName })),
1576
+ dst: muxOut,
1577
+ schema: internSchema(prodPl, "prod").expr
1578
+ });
1579
+
1580
+ if (!unusedBarrier) {
1581
+ return { outVar: muxOut, outPlist: prodPl, sccToken: lastSccTok };
1582
+ }
1583
+ const gated = emitChan(stmts, prodPl, "pg");
1584
+ stmts.push({ op: "gate", barrier: unusedBarrier, src: muxOut, dst: gated });
1585
+ return { outVar: gated, outPlist: prodPl, sccToken: lastSccTok };
1586
+ }
1587
+
1588
+ case "union": {
1589
+ if (exp.items.length === 0) {
1590
+ return failScope(scope, desiredOut, stmts);
1591
+ }
1592
+
1593
+ // Demux product input once upfront if all branches only project fields!
1594
+ const wholeUses = analyzeFieldUses(exp);
1595
+ const curScope = maybeDemuxScope(scope, wholeUses, stmts);
1596
+
1597
+ // Map key -> { varName, plist } for all inspectable channels in `curScope`
1598
+ const scopeMap = new Map();
1599
+ if (curScope.kind === "single") {
1600
+ scopeMap.set("", { varName: curScope.varName, plist: curScope.plist });
1601
+ } else if (curScope.kind === "fields") {
1602
+ for (const [label, chInfo] of curScope.fields.entries()) {
1603
+ scopeMap.set(label, chInfo);
1604
+ }
1605
+ }
1606
+
1607
+ // Analyze leading guards & prune statically dead branches!
1608
+ const liveBranches = [];
1609
+ for (const br of exp.items) {
1610
+ const g = computeLeadingGuards(br);
1611
+ if (g === "DEAD") continue;
1612
+ let dead = false;
1613
+ const filteredGuards = new Map();
1614
+ for (const [k, tags] of g.entries()) {
1615
+ const ch = scopeMap.get(k);
1616
+ if (!ch) continue;
1617
+ if (ch.plist[0][0] !== "closed-union") {
1618
+ dead = true;
1619
+ break;
1620
+ }
1621
+ const avail = new Set(ch.plist[0][1].map(([t]) => t));
1622
+ const inter = new Set([...tags].filter((t) => avail.has(t)));
1623
+ if (inter.size === 0) {
1624
+ dead = true;
1625
+ break;
1626
+ }
1627
+ filteredGuards.set(k, inter);
1628
+ }
1629
+ if (!dead) {
1630
+ liveBranches.push({ exp: br, guards: filteredGuards });
1631
+ }
1632
+ }
1633
+
1634
+ if (liveBranches.length === 0) {
1635
+ return failScope(curScope, desiredOut, stmts);
1636
+ }
1637
+ if (liveBranches.length === 1) {
1638
+ return lowerExp(liveBranches[0].exp, curScope, desiredOut, stmts, afterToken);
1639
+ }
1640
+
1641
+ // Check whether prefix-disjoint `switch` is sound!
1642
+ const switchPlan = tryBuildDisjointSwitchPlan(liveBranches, scopeMap);
1643
+
1644
+ // Lower each live branch in a fresh statement list to discover exact branch output schemas!
1645
+ const loweredBranches = [];
1646
+ for (let i = 0; i < liveBranches.length; i++) {
1647
+ const bStmts = [];
1648
+ const bScope = curScope.kind === "fields"
1649
+ ? { kind: "fields", plist: curScope.plist, fields: new Map(curScope.fields) }
1650
+ : { ...curScope };
1651
+ const bRes = lowerExp(liveBranches[i].exp, bScope, desiredOut, bStmts, null);
1652
+ loweredBranches.push({ stmts: bStmts, res: bRes });
1653
+ }
1654
+
1655
+ // Compute unified output schema across all non-failing live branches
1656
+ const validPlists = loweredBranches
1657
+ .filter((b) => !b.res.alwaysFails)
1658
+ .map((b) => b.res.outPlist);
1659
+ const unionOutPl = desiredOut
1660
+ ? desiredOut
1661
+ : (validPlists.length > 0 ? joinClosedPlists(validPlists) : UNIT_PLIST);
1662
+
1663
+ const outVar = emitChan(stmts, unionOutPl, "uout");
1664
+
1665
+ // Finalize every branch body to write into `outVar`
1666
+ const finalBodies = loweredBranches.map(({ stmts: bStmts, res }) => {
1667
+ emitCoerceOrSplice(bStmts, res.outVar, res.outPlist, outVar, unionOutPl);
1668
+ return bStmts;
1669
+ });
1670
+
1671
+ if (switchPlan) {
1672
+ // Emit zero-buffering prefix-disjoint `switch`!
1673
+ const arms = switchPlan.arms.map(({ patterns, branchIdx }) => ({
1674
+ patterns,
1675
+ // Clone AST body if a branch appears in multiple tag arms
1676
+ body: structuredClone(finalBodies[branchIdx])
1677
+ }));
1678
+ stmts.push({
1679
+ op: "switch",
1680
+ inputs: switchPlan.inspectVars,
1681
+ arms,
1682
+ defaultBody: null
1683
+ });
1684
+ return { outVar, outPlist: unionOutPl };
1685
+ }
1686
+
1687
+ // Emit ordered speculative `spec`!
1688
+ const specIns = liveChansOf(curScope).map((x) => x.varName);
1689
+ stmts.push({
1690
+ op: "spec",
1691
+ inputs: specIns,
1692
+ outputs: [outVar],
1693
+ branches: finalBodies.map((body, idx) => ({ index: idx, body }))
1694
+ });
1695
+ return { outVar, outPlist: unionOutPl };
1696
+ }
1697
+
1698
+ default:
1699
+ throw new Error(`Unsupported KIR-P expression op: '${exp.op}'`);
1700
+ }
1701
+ }
1702
+
1703
+ // Lower top-level relation body
1704
+ const bodyStmts = [];
1705
+ const inVar = "%in";
1706
+ const outVar = "%out";
1707
+ const rootRes = lowerExp(
1708
+ rel.body,
1709
+ { kind: "single", varName: inVar, plist: inMin.plist },
1710
+ predictedOut,
1711
+ bodyStmts,
1712
+ null
1713
+ );
1714
+
1715
+ const finalOutPlist = predictedOut || rootRes.outPlist;
1716
+ specRec.outPlist = finalOutPlist;
1717
+ specMemo.set(memoKey, specRec);
1718
+
1719
+ emitCoerceOrSplice(bodyStmts, rootRes.outVar, rootRes.outPlist, outVar, finalOutPlist);
1720
+
1721
+ const inSchemaRec = internSchema(inMin.plist, "in");
1722
+ const outSchemaRec = internSchema(finalOutPlist, "out");
1723
+ const attrs = [];
1724
+ if (sccInfo.isBranching) attrs.push("branching");
1725
+
1726
+ emittedProcs.push({
1727
+ name: procName,
1728
+ params: [],
1729
+ inputs: [{ name: inVar, schema: inSchemaRec.expr }],
1730
+ outputs: [{ name: outVar, schema: outSchemaRec.expr }],
1731
+ attrs,
1732
+ body: bodyStmts
1733
+ });
1734
+
1735
+ return specRec;
1736
+ }
1737
+
1738
+ const rootSpec = specializeRel(entryHash, entryInPlist, true);
1739
+
1740
+ const monoModule = createModule({
1741
+ version: "0.1",
1742
+ layer: "mono",
1743
+ entry: rootSpec.procName,
1744
+ schemas: emittedSchemas,
1745
+ procs: emittedProcs,
1746
+ kernels: [],
1747
+ tables: []
1748
+ });
1749
+
1750
+ if (validate) {
1751
+ validateModule(monoModule, { verifyTables });
1752
+ }
1753
+
1754
+ return {
1755
+ module: monoModule,
1756
+ entry: rootSpec.procName,
1757
+ inputPlist: rootSpec.inPlist,
1758
+ outputPlist: rootSpec.outPlist
1759
+ };
1760
+ }
1761
+
1762
+ // --- Helper: Nested Field-Projection Rewriting for Rule 2 ---
1763
+
1764
+ function checkAllUsesAreFieldDot(exp, fieldLabel) {
1765
+ let ok = true;
1766
+ function visit(e) {
1767
+ if (!ok || !e) return;
1768
+ switch (e.op) {
1769
+ case "dot":
1770
+ if (e.label === fieldLabel) ok = false;
1771
+ return;
1772
+ case "comp": {
1773
+ if (e.items.length === 0) return;
1774
+ const [first, ...rest] = e.items;
1775
+ if (first.op === "identity") {
1776
+ visit({ op: "comp", items: rest });
1777
+ return;
1778
+ }
1779
+ if (first.op === "dot" && first.label === fieldLabel) {
1780
+ let idx = 0;
1781
+ while (idx < rest.length && rest[idx].op === "identity") idx++;
1782
+ const next = rest[idx];
1783
+ if (!next || next.op !== "dot") ok = false;
1784
+ return;
1785
+ }
1786
+ visit(first);
1787
+ return;
1788
+ }
1789
+ case "product":
1790
+ for (const f of e.fields) visit(f.expr);
1791
+ return;
1792
+ case "union":
1793
+ for (const b of e.items) visit(b);
1794
+ return;
1795
+ default:
1796
+ return;
1797
+ }
1798
+ }
1799
+ visit(exp);
1800
+ return ok;
1801
+ }
1802
+
1803
+ function rewriteFieldSubDot(exp, fieldLabel, subNames) {
1804
+ if (!exp) return exp;
1805
+ switch (exp.op) {
1806
+ case "comp": {
1807
+ if (exp.items.length === 0) return exp;
1808
+ const [first, ...rest] = exp.items;
1809
+ if (first.op === "identity") {
1810
+ return { ...exp, items: [first, ...rewriteFieldSubDot({ op: "comp", items: rest }, fieldLabel, subNames).items] };
1811
+ }
1812
+ if (first.op === "dot" && first.label === fieldLabel) {
1813
+ let idx = 0;
1814
+ while (idx < rest.length && rest[idx].op === "identity") idx++;
1815
+ const next = rest[idx];
1816
+ if (next && next.op === "dot" && subNames.has(next.label)) {
1817
+ const synthDot = { op: "dot", label: subNames.get(next.label) };
1818
+ const tail = rest.slice(idx + 1);
1819
+ return tail.length === 0 ? synthDot : { ...exp, items: [synthDot, ...tail] };
1820
+ }
1821
+ }
1822
+ return { ...exp, items: [rewriteFieldSubDot(first, fieldLabel, subNames), ...rest] };
1823
+ }
1824
+ case "product":
1825
+ return {
1826
+ ...exp,
1827
+ fields: exp.fields.map((f) => ({ ...f, expr: rewriteFieldSubDot(f.expr, fieldLabel, subNames) }))
1828
+ };
1829
+ case "union":
1830
+ return {
1831
+ ...exp,
1832
+ items: exp.items.map((b) => rewriteFieldSubDot(b, fieldLabel, subNames))
1833
+ };
1834
+ default:
1835
+ return exp;
1836
+ }
1837
+ }
1838
+
1839
+ // --- Helper: Sound Prefix-Disjoint `switch` Planner ---
1840
+
1841
+ function tryBuildDisjointSwitchPlan(liveBranches, scopeMap) {
1842
+ const keySet = new Set();
1843
+ for (const b of liveBranches) {
1844
+ for (const k of b.guards.keys()) {
1845
+ const ch = scopeMap.get(k);
1846
+ if (ch && ch.plist[0][0] === "closed-union") keySet.add(k);
1847
+ }
1848
+ }
1849
+ if (keySet.size === 0 || keySet.size > 3) return null;
1850
+
1851
+ const inspectKeys = [...keySet].sort(compareLabels);
1852
+ const inspectVars = inspectKeys.map((k) => scopeMap.get(k).varName);
1853
+ const domainTags = inspectKeys.map((k) => scopeMap.get(k).plist[0][1].map(([t]) => t));
1854
+
1855
+ // Fast path: single inspected union channel (scales cleanly even to 128-tag ascii[]!)
1856
+ if (inspectKeys.length === 1) {
1857
+ const k0 = inspectKeys[0];
1858
+ const seenTags = new Set();
1859
+ const arms = [];
1860
+ let totalArms = 0;
1861
+ for (let i = 0; i < liveBranches.length; i++) {
1862
+ const g = liveBranches[i].guards.get(k0);
1863
+ if (!g || g.size === 0) return null; // wildcard overlaps earlier branches -> use `spec`!
1864
+ // Avoid code duplication if a single branch expands to many tags
1865
+ if (g.size > 1 && totalArms + g.size > 16) return null;
1866
+ for (const t of g) {
1867
+ if (seenTags.has(t)) return null; // overlapping tag -> must use `spec`!
1868
+ seenTags.add(t);
1869
+ arms.push({ patterns: [{ kind: "tag", tag: t }], branchIdx: i });
1870
+ totalArms++;
1871
+ }
1872
+ }
1873
+ return { inspectVars, arms };
1874
+ }
1875
+
1876
+ // Multi-channel case (2..3 ports): check Cartesian size & pairwise disjointness
1877
+ const cartSize = domainTags.reduce((a, ts) => a * ts.length, 1);
1878
+ if (cartSize > 64) return null;
1879
+
1880
+ // Verify every concrete tuple matches AT MOST ONE branch
1881
+ const arms = [];
1882
+ const tuple = new Array(inspectKeys.length);
1883
+
1884
+ function enumerate(dim) {
1885
+ if (dim === inspectKeys.length) {
1886
+ let matched = -1;
1887
+ for (let i = 0; i < liveBranches.length; i++) {
1888
+ let ok = true;
1889
+ for (let d = 0; d < inspectKeys.length; d++) {
1890
+ const g = liveBranches[i].guards.get(inspectKeys[d]);
1891
+ if (g && !g.has(tuple[d])) {
1892
+ ok = false;
1893
+ break;
1894
+ }
1895
+ }
1896
+ if (ok) {
1897
+ if (matched !== -1) return false; // Overlap! Must use `spec`
1898
+ matched = i;
1899
+ }
1900
+ }
1901
+ if (matched !== -1) {
1902
+ arms.push({
1903
+ patterns: tuple.map((t) => ({ kind: "tag", tag: t })),
1904
+ branchIdx: matched
1905
+ });
1906
+ }
1907
+ return true;
1908
+ }
1909
+ for (const t of domainTags[dim]) {
1910
+ tuple[dim] = t;
1911
+ if (!enumerate(dim + 1)) return false;
1912
+ }
1913
+ return true;
1914
+ }
1915
+
1916
+ if (!enumerate(0) || arms.length === 0) return null;
1917
+ // Avoid excessive body duplication if a single branch spans many tuples
1918
+ const counts = new Map();
1919
+ for (const a of arms) counts.set(a.branchIdx, (counts.get(a.branchIdx) || 0) + 1);
1920
+ for (const c of counts.values()) {
1921
+ if (c > 8) return null;
1922
+ }
1923
+ return { inspectVars, arms };
1924
+ }
1925
+
1926
+ // --- Polymorphic AOT Lowering: KIR-P -> `kTVM-P` (`layer: "poly"`) ---
1927
+
1928
+ /**
1929
+ * Lower a `KIR-P` (or `k-object`) into an inspectable polymorphic `kTVM-P`
1930
+ * module (`layer: "poly"`) without requiring a concrete input envelope yet.
1931
+ */
1932
+ export function lowerKIRToKTVMP(kirOrObject, { entry = null, validate = true } = {}) {
1933
+ const { kir } = normalizeKIR(kirOrObject);
1934
+ const findCode = makeCodeLookup(kir);
1935
+ const displayNames = buildDisplayNameMap(kir);
1936
+
1937
+ const entryHash = resolveRelHash(kir, entry || kir.main) || Object.keys(kir.rels || {})[0] || null;
1938
+ const relNameByHash = new Map();
1939
+ let procSeq = 0;
1940
+ for (const h of Object.keys(kir.rels || {})) {
1941
+ const nice = sanitizeIdent(displayNames.get(h) || h, "rel");
1942
+ relNameByHash.set(h, `@${nice}_${procSeq++}`);
1943
+ }
1944
+
1945
+ const emittedSchemas = [];
1946
+ const emittedProcs = [];
1947
+ let schemaSeq = 0;
1948
+
1949
+ for (const [relHash, rel] of Object.entries(kir.rels || {})) {
1950
+ const procName = relNameByHash.get(relHash);
1951
+ const lpg = new LocalPatternGraph(rel.patternGraph, findCode);
1952
+ const sccInfo = getSccInfoStatic(kir, relHash);
1953
+
1954
+ // Build schema expressions for nodes in `lpg`
1955
+ const nodeSchemaNames = new Map();
1956
+ const inDegree = new Map();
1957
+ const cycleTargets = new Set();
1958
+ const visitState = new Map();
1959
+
1960
+ const mark = (id) => {
1961
+ const r = lpg.find(id);
1962
+ visitState.set(r, 1);
1963
+ for (const [, t] of lpg.nodes[r].edges.entries()) {
1964
+ const rt = lpg.find(t);
1965
+ inDegree.set(rt, (inDegree.get(rt) || 0) + 1);
1966
+ if (visitState.get(rt) === 1) cycleTargets.add(rt);
1967
+ else if (!visitState.has(rt)) mark(rt);
1968
+ }
1969
+ visitState.set(r, 2);
1970
+ };
1971
+ for (const id of lpg.kirIdToLocal.values()) {
1972
+ if (!visitState.has(lpg.find(id))) mark(id);
1973
+ }
1974
+
1975
+ for (const id of new Set([...lpg.kirIdToLocal.values()].map((x) => lpg.find(x)))) {
1976
+ const node = lpg.nodes[id];
1977
+ if (node.kind === "any") continue;
1978
+ if (node.kind === "closed-product" && node.edges.size === 0) continue;
1979
+ if (cycleTargets.has(id)) {
1980
+ nodeSchemaNames.set(id, `$P_${schemaSeq++}`);
1981
+ }
1982
+ }
1983
+
1984
+ const toSchemaExpr = (localId, inlineSelf = false) => {
1985
+ const r = lpg.find(localId);
1986
+ const node = lpg.nodes[r];
1987
+ if (node.kind === "any") return S.any();
1988
+ if (node.kind === "closed-product" && node.edges.size === 0) return S.unit();
1989
+ if (!inlineSelf && nodeSchemaNames.has(r)) return S.ref(nodeSchemaNames.get(r));
1990
+ const fields = [...node.edges.entries()]
1991
+ .sort(([a], [b]) => compareLabels(a, b))
1992
+ .map(([label, t]) => ({ label, schema: toSchemaExpr(t, false) }));
1993
+ if (node.kind === "closed-product") return S.product(fields);
1994
+ if (node.kind === "open-product") return S.openProduct(fields);
1995
+ if (node.kind === "closed-union") return S.union(fields);
1996
+ if (node.kind === "open-union") return S.openUnion(fields);
1997
+ return S.any();
1998
+ };
1999
+
2000
+ for (const [id, sName] of nodeSchemaNames.entries()) {
2001
+ emittedSchemas.push({ name: sName, params: [], expr: toSchemaExpr(id, true) });
2002
+ }
2003
+
2004
+ const patSchema = (kirPatId) => {
2005
+ if (kirPatId == null || !lpg.kirIdToLocal.has(kirPatId)) return S.any();
2006
+ return toSchemaExpr(lpg.kirIdToLocal.get(kirPatId), false);
2007
+ };
2008
+
2009
+ let vSeq = 0;
2010
+ const fVar = (p = "v") => `%${p}_${vSeq++}`;
2011
+
2012
+ const lowerPolyExp = (exp, inVar, stmts) => {
2013
+ const inS = patSchema(exp.patterns?.[0]);
2014
+ const outS = patSchema(exp.patterns?.[1]);
2015
+ switch (exp.op) {
2016
+ case "identity":
2017
+ return inVar;
2018
+ case "empty": {
2019
+ const out = fVar("fail");
2020
+ stmts.push({ op: "chan", name: out, schema: outS });
2021
+ stmts.push({ op: "spec", inputs: [inVar], outputs: [out], branches: [] });
2022
+ return out;
2023
+ }
2024
+ case "dot": {
2025
+ const out = fVar("dot");
2026
+ stmts.push({ op: "chan", name: out, schema: outS });
2027
+ stmts.push({ op: "project", field: exp.label, src: inVar, srcSchema: inS, dst: out, dstSchema: outS });
2028
+ return out;
2029
+ }
2030
+ case "div": {
2031
+ const out = fVar("div");
2032
+ stmts.push({ op: "chan", name: out, schema: outS });
2033
+ stmts.push({ op: "match", tag: exp.tag, src: inVar, dst: out });
2034
+ return out;
2035
+ }
2036
+ case "vid": {
2037
+ const out = fVar("vid");
2038
+ stmts.push({ op: "chan", name: out, schema: outS });
2039
+ stmts.push({ op: "wrap", tag: exp.tag, src: inVar, dst: out });
2040
+ return out;
2041
+ }
2042
+ case "filter":
2043
+ case "code": {
2044
+ const out = fVar("flt");
2045
+ stmts.push({ op: "chan", name: out, schema: outS });
2046
+ stmts.push({ op: "guard", schema: inS, src: inVar, dst: out });
2047
+ return out;
2048
+ }
2049
+ case "ref": {
2050
+ if (isIntrinsic(exp.ref)) {
2051
+ if (isIdentityIntrinsic(exp.ref)) return inVar;
2052
+ throw unsupportedIntrinsic("kTVM-P", exp.ref);
2053
+ }
2054
+ const tHash = resolveRelHash(kir, exp.ref);
2055
+ const out = fVar("call");
2056
+ stmts.push({ op: "chan", name: out, schema: outS });
2057
+ stmts.push({
2058
+ op: "spawn",
2059
+ target: relNameByHash.get(tHash),
2060
+ schemaArgs: [],
2061
+ inputs: [inVar],
2062
+ outputs: [out],
2063
+ after: null,
2064
+ token: null
2065
+ });
2066
+ return out;
2067
+ }
2068
+ case "comp": {
2069
+ let cur = inVar;
2070
+ for (const item of exp.items) cur = lowerPolyExp(item, cur, stmts);
2071
+ return cur;
2072
+ }
2073
+ case "product": {
2074
+ if (exp.fields.length === 0) {
2075
+ const bar = fVar("bar");
2076
+ const u = fVar("u");
2077
+ const out = fVar("ug");
2078
+ stmts.push({ op: "barrier", name: bar });
2079
+ stmts.push({ op: "drain", src: inVar, schema: inS, barrier: bar });
2080
+ stmts.push({ op: "chan", name: u, schema: S.unit() });
2081
+ stmts.push({ op: "const_unit", dst: u });
2082
+ stmts.push({ op: "chan", name: out, schema: S.unit() });
2083
+ stmts.push({ op: "gate", barrier: bar, src: u, dst: out });
2084
+ return out;
2085
+ }
2086
+ const sorted = [...exp.fields].sort((a, b) => compareLabels(a.label, b.label));
2087
+ let branchIns;
2088
+ if (sorted.length === 1) {
2089
+ branchIns = [inVar];
2090
+ } else {
2091
+ branchIns = sorted.map((_, idx) => {
2092
+ const c = fVar(`t${idx}`);
2093
+ stmts.push({ op: "chan", name: c, schema: inS });
2094
+ return c;
2095
+ });
2096
+ stmts.push({ op: "tee", src: inVar, dsts: branchIns });
2097
+ }
2098
+ const muxFields = sorted.map((f, idx) => ({
2099
+ label: f.label,
2100
+ name: lowerPolyExp(f.expr, branchIns[idx], stmts)
2101
+ }));
2102
+ const out = fVar("prod");
2103
+ stmts.push({ op: "chan", name: out, schema: outS });
2104
+ stmts.push({ op: "mux", fields: muxFields, dst: out, schema: outS });
2105
+ return out;
2106
+ }
2107
+ case "union": {
2108
+ const out = fVar("uout");
2109
+ stmts.push({ op: "chan", name: out, schema: outS });
2110
+ const branches = exp.items.map((br, idx) => {
2111
+ const bStmts = [];
2112
+ const resVar = lowerPolyExp(br, inVar, bStmts);
2113
+ bStmts.push({ op: "splice", src: resVar, dst: out });
2114
+ return { index: idx, body: bStmts };
2115
+ });
2116
+ stmts.push({ op: "spec", inputs: [inVar], outputs: [out], branches });
2117
+ return out;
2118
+ }
2119
+ default:
2120
+ throw new Error(`Unsupported KIR-P op '${exp.op}'`);
2121
+ }
2122
+ };
2123
+
2124
+ const body = [];
2125
+ const resVar = lowerPolyExp(rel.body, "%in", body);
2126
+ body.push({ op: "splice", src: resVar, dst: "%out" });
2127
+
2128
+ emittedProcs.push({
2129
+ name: procName,
2130
+ params: [],
2131
+ inputs: [{ name: "%in", schema: patSchema(rel.inputPattern) }],
2132
+ outputs: [{ name: "%out", schema: patSchema(rel.outputPattern) }],
2133
+ attrs: sccInfo.isBranching ? ["branching"] : [],
2134
+ body
2135
+ });
2136
+ }
2137
+
2138
+ const polyMod = createModule({
2139
+ version: "0.1",
2140
+ layer: "poly",
2141
+ entry: entryHash ? relNameByHash.get(entryHash) : null,
2142
+ schemas: emittedSchemas,
2143
+ procs: emittedProcs,
2144
+ kernels: [],
2145
+ tables: []
2146
+ });
2147
+
2148
+ if (validate) {
2149
+ validateModule(polyMod, { verifyTables: false });
2150
+ }
2151
+ return polyMod;
2152
+ }
2153
+
2154
+ function getSccInfoStatic(kir, h) {
2155
+ return analyzeBranchingSCC(kir, h);
2156
+ }
2157
+
2158
+ // --- High-Level Object Artifact & Execution API (Mirroring `kvm.mjs`) ---
2159
+
2160
+ export function compileObjectToKTVM(object, relationName = null, inputPlist = null, options = {}) {
2161
+ if (!inputPlist) {
2162
+ return {
2163
+ module: lowerKIRToKTVMP(object, { entry: relationName || object.main, validate: options.validate !== false }),
2164
+ layer: "poly",
2165
+ isPolymorphic: true
2166
+ };
2167
+ }
2168
+ return compileKIRToKTVM(object, relationName || object.main, inputPlist, options);
2169
+ }
2170
+
2171
+ /**
2172
+ * Execute a K `k-object` relation via `kTVM` on either:
2173
+ * - an enveloped `k-wire` `Buffer` / `Uint8Array`, OR
2174
+ * - a K `Value` (with `opts.inputPlist` or inferred pattern from the relation/value).
2175
+ */
2176
+ export function executeObjectWithKTVM(object, relationName, inputValOrWire, opts = {}) {
2177
+ const relName = relationName || object.main;
2178
+
2179
+ if (inputValOrWire instanceof Uint8Array) {
2180
+ const { plist: inPlist, payloadDeque } = splitEnvelopedWire(inputValOrWire, { quota: opts.quota });
2181
+ const compiled = compileKIRToKTVM(object, relName, inPlist, {
2182
+ validate: opts.validate !== false,
2183
+ verifyTables: opts.verifyTables !== false,
2184
+ useCache: opts.useCache !== false
2185
+ });
2186
+ payloadDeque.release();
2187
+ return executeKTVMWire(compiled.module, inputValOrWire, {
2188
+ entry: compiled.entry,
2189
+ validate: false, // already validated during compileKIRToKTVM
2190
+ quota: opts.quota,
2191
+ decodeValue: opts.decodeValue
2192
+ });
2193
+ }
2194
+
2195
+ // In-memory K Value path
2196
+ let inPlist = opts.inputPlist || inputValOrWire?.pattern || null;
2197
+ if (!inPlist) {
2198
+ const relHash = resolveRelHash(object, relName);
2199
+ const rel = object.rels?.[relHash];
2200
+ if (rel) {
2201
+ inPlist = relationPatternPropertyList(rel, 0);
2202
+ }
2203
+ }
2204
+ if (!inPlist || !isClosedPlist(inPlist)) {
2205
+ throw new KTVMSchemaError(
2206
+ `executeObjectWithKTVM requires a closed input pattern (pass an enveloped k-wire Buffer or opts.inputPlist)`
2207
+ );
2208
+ }
2209
+
2210
+ const compiled = compileKIRToKTVM(object, relName, inPlist, {
2211
+ validate: opts.validate !== false,
2212
+ verifyTables: opts.verifyTables !== false,
2213
+ useCache: opts.useCache !== false
2214
+ });
2215
+ return executeKTVM(compiled.module, [inputValOrWire], {
2216
+ entry: compiled.entry,
2217
+ validate: false,
2218
+ quota: opts.quota,
2219
+ decodeValues: opts.decodeValues
2220
+ });
2221
+ }