@fraczak/k 8.9.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/DOCS/ARCHITECTURE.md +5 -4
  3. package/DOCS/DICTIONARY.md +2 -2
  4. package/DOCS/FILE_FORMATS.md +11 -9
  5. package/DOCS/KIR_V1.md +5 -1
  6. package/DOCS/KTVM_SPEC.md +907 -0
  7. package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
  8. package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
  9. package/DOCS/PROFILING_AND_TRACING.md +13 -4
  10. package/DOCS/README.md +3 -2
  11. package/DOCS/REPL.md +16 -12
  12. package/README.md +138 -2
  13. package/backend-api.mjs +31 -16
  14. package/backends/llvm/README.md +4 -5
  15. package/backends/llvm/bin/k-llvm-build.mjs +7 -19
  16. package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
  17. package/backends/llvm/bin/k-llvm.mjs +11 -33
  18. package/backends/llvm/src/cli.mjs +2 -12
  19. package/backends/llvm/src/executable.mjs +7 -95
  20. package/backends/llvm/src/kvm2llvm.mjs +1 -7
  21. package/backends/llvm/src/llvm.mjs +4 -113
  22. package/backends/llvm/tests/k-llvm-run.mjs +1 -6
  23. package/backends/llvm/tests/perf-support.mjs +3 -5
  24. package/backends/llvm/tests/test-llvm.mjs +2 -16
  25. package/backends/wasm/README.md +7 -3
  26. package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
  27. package/backends/wasm/bin/k-wasm.mjs +4 -6
  28. package/backends/wasm/src/cli.mjs +8 -24
  29. package/backends/wasm/src/wasm.mjs +60 -57
  30. package/backends/wasm/tests/test-wasm.mjs +41 -2
  31. package/browser/repl-browser.mjs +9 -8
  32. package/browser/shims/buffer.mjs +31 -2
  33. package/browser/shims/child_process.mjs +26 -0
  34. package/browser/shims/fs.mjs +3 -1
  35. package/codecs/runtime/prefix-codec.mjs +67 -1
  36. package/conformance/run.mjs +17 -2
  37. package/harness/adapters/ktvm-llvm.mjs +118 -0
  38. package/harness/adapters/ktvm-wasm.mjs +104 -0
  39. package/harness/adapters/ktvm.mjs +133 -0
  40. package/harness/registry.mjs +9 -0
  41. package/ktvm/ast.mjs +218 -0
  42. package/ktvm/bit-deque.mjs +497 -0
  43. package/ktvm/fixtures/integer-streaming.k +477 -0
  44. package/ktvm/index.mjs +130 -0
  45. package/ktvm/llvm/index.mjs +202 -0
  46. package/ktvm/llvm/lower-c.mjs +1258 -0
  47. package/ktvm/llvm/runtime.h +3542 -0
  48. package/ktvm/llvm/test-llvm.mjs +476 -0
  49. package/ktvm/lower-kir.mjs +2221 -0
  50. package/ktvm/optimize/fuse-kernel.mjs +2111 -0
  51. package/ktvm/optimize/index.mjs +116 -0
  52. package/ktvm/optimize/mwtr.mjs +283 -0
  53. package/ktvm/optimize/simplify-procs.mjs +5250 -0
  54. package/ktvm/optimize/synthesize-tables.mjs +1105 -0
  55. package/ktvm/parser.mjs +1101 -0
  56. package/ktvm/printer.mjs +281 -0
  57. package/ktvm/schema.mjs +1134 -0
  58. package/ktvm/specialize.mjs +538 -0
  59. package/ktvm/test-conformance.mjs +597 -0
  60. package/ktvm/test-ktvm.mjs +1805 -0
  61. package/ktvm/test-optimize.mjs +598 -0
  62. package/ktvm/validator.mjs +1280 -0
  63. package/ktvm/vm.mjs +2225 -0
  64. package/ktvm/wasm/index.mjs +331 -0
  65. package/ktvm/wasm/lower-wasm.mjs +1272 -0
  66. package/ktvm/wasm/runtime.wat +4404 -0
  67. package/ktvm/wasm/test-wasm.mjs +429 -0
  68. package/ktvm/wire.mjs +679 -0
  69. package/package.json +1 -9
  70. package/paper/Makefile +8 -5
  71. package/paper/k-transducer-compiler.pdf +0 -0
  72. package/paper/k-transducer-compiler.tex +658 -0
  73. package/paper/replay-diagnostic.mjs +63 -0
  74. package/repl.mjs +101 -20
  75. package/scripts/build-repl-html.mjs +40 -18
  76. package/scripts/perf-bigint-compare.mjs +12 -16
  77. package/scripts/perf-ieee.mjs +14 -232
  78. package/scripts/perf-int.mjs +16 -274
  79. package/scripts/perf-multiplication.mjs +116 -121
  80. package/scripts/perf-poly.mjs +9 -263
  81. package/scripts/run-tests.mjs +5 -2
  82. package/scripts/test-package.mjs +15 -3
  83. package/tests/README.md +3 -3
  84. package/tests/test-repl-html.mjs +72 -15
  85. package/tests/test-repl.mjs +24 -17
  86. package/DOCS/POLYMORPHIC_IR.md +0 -86
  87. package/access-table.mjs +0 -343
  88. package/pkir.mjs +0 -772
  89. package/tests/test-access-table.mjs +0 -213
  90. package/tests/test-pkir.mjs +0 -530
@@ -0,0 +1,1134 @@
1
+ /**
2
+ * kTVM Schema & Wire Type System.
3
+ *
4
+ * Compiles kTVM schema AST expressions to canonical k-wire property-list graphs
5
+ * (`plist`), computes Moore minimal bisimulation quotients for zero-copy splice
6
+ * equivalence (`S1 ≡ S2`), derives node-list prefix derivatives (`s`-language
7
+ * representation of aligned offsets), checks bit-level `s`-language wire
8
+ * equivalence, and unifies polymorphic `kTVM-P` contracts against concrete
9
+ * `k-wire` envelopes using K's `intersectPropertyListPatterns`.
10
+ */
11
+
12
+ import { intersectPropertyListPatterns } from "../codecs/runtime/codec.mjs";
13
+ import { choiceWidth } from "../codecs/runtime/prefix-codec.mjs";
14
+ import { KTVMSchemaError, S } from "./ast.mjs";
15
+
16
+ export function compareLabels(a, b) {
17
+ return a < b ? -1 : a > b ? 1 : 0;
18
+ }
19
+
20
+ export function isClosedSchemaKind(kind) {
21
+ return kind === "closed-product" || kind === "closed-union";
22
+ }
23
+
24
+ export function isClosedPlist(plist) {
25
+ if (!Array.isArray(plist) || plist.length === 0) return false;
26
+ for (const node of plist) {
27
+ if (!Array.isArray(node) || node.length !== 2) return false;
28
+ if (!isClosedSchemaKind(node[0])) return false;
29
+ }
30
+ return true;
31
+ }
32
+
33
+ /**
34
+ * Substitute schema parameters `$X -> schemaExpr` inside a schema AST expression.
35
+ */
36
+ export function substituteSchemaExpr(expr, env) {
37
+ if (!expr) return expr;
38
+ switch (expr.kind) {
39
+ case "unit":
40
+ case "any":
41
+ return expr;
42
+ case "ref": {
43
+ if ((!expr.args || expr.args.length === 0) && env.has(expr.name)) {
44
+ return env.get(expr.name);
45
+ }
46
+ return S.ref(expr.name, (expr.args || []).map((a) => substituteSchemaExpr(a, env)));
47
+ }
48
+ case "product":
49
+ return S.product(expr.fields.map((f) => ({ label: f.label, schema: substituteSchemaExpr(f.schema, env) })));
50
+ case "open_product":
51
+ return S.openProduct(expr.fields.map((f) => ({ label: f.label, schema: substituteSchemaExpr(f.schema, env) })));
52
+ case "union":
53
+ return S.union(expr.fields.map((f) => ({ label: f.label, schema: substituteSchemaExpr(f.schema, env) })));
54
+ case "open_union":
55
+ return S.openUnion(expr.fields.map((f) => ({ label: f.label, schema: substituteSchemaExpr(f.schema, env) })));
56
+ default:
57
+ throw new Error(`Unknown schema expr kind: ${expr.kind}`);
58
+ }
59
+ }
60
+
61
+ function exprStructuralKey(expr) {
62
+ switch (expr.kind) {
63
+ case "unit": return "U";
64
+ case "any": return "A";
65
+ case "ref":
66
+ return expr.args && expr.args.length > 0
67
+ ? `R(${expr.name}[${expr.args.map(exprStructuralKey).join(",")}])`
68
+ : `R(${expr.name})`;
69
+ case "product":
70
+ case "open_product":
71
+ case "union":
72
+ case "open_union": {
73
+ const sorted = [...expr.fields].sort((a, b) => compareLabels(a.label, b.label));
74
+ return `${expr.kind}(${sorted.map((f) => `${JSON.stringify(f.label)}:${exprStructuralKey(f.schema)}`).join(",")})`;
75
+ }
76
+ default:
77
+ throw new Error(`Unknown schema expr kind: ${expr.kind}`);
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Compile a closed (or open, if allowOpen=true) kTVM schema expression against
83
+ * a map of schema declarations into a canonical k-wire property-list graph.
84
+ */
85
+ export function compileSchemaExprToPlist(expr, schemaDecls, { paramBindings = new Map(), allowOpen = false } = {}) {
86
+ const declMap = schemaDecls instanceof Map
87
+ ? schemaDecls
88
+ : new Map((schemaDecls || []).map((d) => [d.name, d]));
89
+
90
+ const nodes = [];
91
+ const memo = new Map();
92
+
93
+ function visit(curExpr, env, expandingRefs = new Set()) {
94
+ const resolved = substituteSchemaExpr(curExpr, env);
95
+ if (resolved.kind === "ref") {
96
+ const decl = declMap.get(resolved.name);
97
+ if (!decl) {
98
+ if (allowOpen) {
99
+ const id = nodes.length;
100
+ nodes.push(["any", []]);
101
+ return id;
102
+ }
103
+ throw new KTVMSchemaError(`Unresolved schema reference '${resolved.name}'`);
104
+ }
105
+ const args = resolved.args || [];
106
+ if (args.length !== (decl.params || []).length) {
107
+ throw new KTVMSchemaError(
108
+ `Schema '${resolved.name}' expects ${(decl.params || []).length} args, got ${args.length}`
109
+ );
110
+ }
111
+ const key = `${resolved.name}[${args.map(exprStructuralKey).join(",")}]`;
112
+ if (memo.has(key)) return memo.get(key);
113
+ if (expandingRefs.has(key)) {
114
+ throw new KTVMSchemaError(`Unguarded direct schema cycle on '${resolved.name}'`);
115
+ }
116
+ const nextEnv = new Map();
117
+ for (let i = 0; i < args.length; i++) {
118
+ nextEnv.set(decl.params[i], args[i]);
119
+ }
120
+ const nextExpanding = new Set(expandingRefs);
121
+ nextExpanding.add(key);
122
+
123
+ // Peek body kind; reserve node slot BEFORE descending into edges to tie recursive knots.
124
+ const body = substituteSchemaExpr(decl.expr, nextEnv);
125
+ if (body.kind === "ref") {
126
+ const id = visit(body, nextEnv, nextExpanding);
127
+ memo.set(key, id);
128
+ return id;
129
+ }
130
+ const id = nodes.length;
131
+ memo.set(key, id);
132
+ nodes.push(null);
133
+ nodes[id] = buildComposite(body, nextEnv);
134
+ return id;
135
+ }
136
+
137
+ const id = nodes.length;
138
+ nodes.push(null);
139
+ nodes[id] = buildComposite(resolved, env);
140
+ return id;
141
+ }
142
+
143
+ function buildComposite(resolved, env) {
144
+ switch (resolved.kind) {
145
+ case "unit":
146
+ return ["closed-product", []];
147
+ case "any":
148
+ if (!allowOpen) throw new KTVMSchemaError("Schema 'any' is not allowed in concrete mono kTVM");
149
+ return ["any", []];
150
+ case "product":
151
+ case "union": {
152
+ const kind = resolved.kind === "product" ? "closed-product" : "closed-union";
153
+ const sorted = [...resolved.fields].sort((a, b) => compareLabels(a.label, b.label));
154
+ const edges = sorted.map((f) => [f.label, visit(f.schema, env)]);
155
+ return [kind, edges];
156
+ }
157
+ case "open_product":
158
+ case "open_union": {
159
+ if (!allowOpen) {
160
+ throw new KTVMSchemaError(`Open schema '${resolved.kind}' is not allowed in concrete mono kTVM`);
161
+ }
162
+ const kind = resolved.kind === "open_product" ? "open-product" : "open-union";
163
+ const sorted = [...resolved.fields].sort((a, b) => compareLabels(a.label, b.label));
164
+ const edges = sorted.map((f) => [f.label, visit(f.schema, env)]);
165
+ return [kind, edges];
166
+ }
167
+ default:
168
+ throw new KTVMSchemaError(`Unsupported schema kind '${resolved.kind}'`);
169
+ }
170
+ }
171
+
172
+ visit(expr, paramBindings);
173
+ return canonicalizePlistOrder(nodes, 0);
174
+ }
175
+
176
+ /**
177
+ * Re-index a property-list graph in canonical DFS discovery order from `rootId`
178
+ * with edges sorted in canonical label order.
179
+ */
180
+ export function canonicalizePlistOrder(plist, rootId = 0) {
181
+ const idMap = new Map();
182
+ const out = [];
183
+
184
+ function dfs(oldId) {
185
+ if (idMap.has(oldId)) return idMap.get(oldId);
186
+ const newId = out.length;
187
+ idMap.set(oldId, newId);
188
+ const [kind, edges] = plist[oldId];
189
+ const sortedEdges = [...edges].sort((a, b) => compareLabels(a[0], b[0]));
190
+ const slot = [kind, []];
191
+ out.push(slot);
192
+ slot[1] = sortedEdges.map(([label, target]) => [label, dfs(target)]);
193
+ return newId;
194
+ }
195
+
196
+ dfs(rootId);
197
+ return out;
198
+ }
199
+
200
+ /**
201
+ * Extract the reachable subgraph rooted at `rootId` as a standalone property-list.
202
+ */
203
+ export function subPlist(plist, rootId = 0) {
204
+ return canonicalizePlistOrder(plist, rootId);
205
+ }
206
+
207
+ /**
208
+ * Compute the Moore minimal bisimulation quotient of a property-list graph
209
+ * rooted at `rootId`, returning both the minimized plist and a unique canonical
210
+ * string key (`S1 ≡ S2 <=> mooreKey(S1) === mooreKey(S2)`).
211
+ */
212
+ export function mooreMinimize(plist, rootId = 0) {
213
+ const sub = canonicalizePlistOrder(plist, rootId);
214
+ const n = sub.length;
215
+
216
+ // Initial partition by (kind, ordered label list)
217
+ let cls = new Int32Array(n);
218
+ const initSigs = new Map();
219
+ let numClasses = 0;
220
+ for (let i = 0; i < n; i++) {
221
+ const [kind, edges] = sub[i];
222
+ const sig = `${kind}|${edges.map(([l]) => JSON.stringify(l)).join(",")}`;
223
+ let c = initSigs.get(sig);
224
+ if (c === undefined) {
225
+ c = numClasses++;
226
+ initSigs.set(sig, c);
227
+ }
228
+ cls[i] = c;
229
+ }
230
+
231
+ // Refine partition to fixed point
232
+ while (true) {
233
+ const nextCls = new Int32Array(n);
234
+ const sigMap = new Map();
235
+ let nextNum = 0;
236
+ for (let i = 0; i < n; i++) {
237
+ const edges = sub[i][1];
238
+ const sig = `${cls[i]}:${edges.map(([, t]) => cls[t]).join(",")}`;
239
+ let c = sigMap.get(sig);
240
+ if (c === undefined) {
241
+ c = nextNum++;
242
+ sigMap.set(sig, c);
243
+ }
244
+ nextCls[i] = c;
245
+ }
246
+ cls = nextCls;
247
+ if (nextNum === numClasses) break;
248
+ numClasses = nextNum;
249
+ }
250
+
251
+ // Build representative graph over classes and re-order canonically from root's class
252
+ const repOfClass = new Int32Array(numClasses).fill(-1);
253
+ for (let i = 0; i < n; i++) {
254
+ if (repOfClass[cls[i]] === -1) repOfClass[cls[i]] = i;
255
+ }
256
+ const quotient = [];
257
+ for (let c = 0; c < numClasses; c++) {
258
+ const [kind, edges] = sub[repOfClass[c]];
259
+ quotient.push([kind, edges.map(([l, t]) => [l, cls[t]])]);
260
+ }
261
+ const canonical = canonicalizePlistOrder(quotient, cls[0]);
262
+ return { plist: canonical, key: JSON.stringify(canonical) };
263
+ }
264
+
265
+ const MOORE_KEY_CACHE = new WeakMap();
266
+
267
+ export function mooreKey(plist, rootId = 0) {
268
+ let byRoot = MOORE_KEY_CACHE.get(plist);
269
+ if (!byRoot) {
270
+ byRoot = new Map();
271
+ MOORE_KEY_CACHE.set(plist, byRoot);
272
+ }
273
+ let key = byRoot.get(rootId);
274
+ if (key === undefined) {
275
+ key = mooreMinimize(plist, rootId).key;
276
+ byRoot.set(rootId, key);
277
+ }
278
+ return key;
279
+ }
280
+
281
+ export function schemasEquivalent(p1, r1, p2, r2) {
282
+ if (p1 === p2 && r1 === r2) return true;
283
+ return mooreKey(p1, r1) === mooreKey(p2, r2);
284
+ }
285
+
286
+ // --- Node-List Prefix Derivatives (s-Language Representation of Aligned Offsets) ---
287
+
288
+ function coerceNodeList(nodes) {
289
+ if (nodes === undefined || nodes === null) return [0];
290
+ if (typeof nodes === "number") return [nodes];
291
+ if (Array.isArray(nodes)) return [...nodes];
292
+ throw new KTVMSchemaError("Expected schema node ID or array of node IDs");
293
+ }
294
+
295
+ /**
296
+ * Normalize a front-to-back residual schema node list `[v_1, ..., v_k]` over a
297
+ * closed property-list graph by applying head-rewriting rules (unit elimination
298
+ * and product expansion) until the list is empty or its head is a `closed-union`.
299
+ *
300
+ * Detects unguarded product cycles in O(|V| + |E|) time and throws `KTVMSchemaError`.
301
+ */
302
+ export function normalizeNodeList(plist, nodes = [0]) {
303
+ if (!Array.isArray(plist) || plist.length === 0) {
304
+ throw new KTVMSchemaError("Schema property list must be a non-empty array");
305
+ }
306
+ const initial = coerceNodeList(nodes);
307
+ // Working stack in LIFO order (head at top) with negative sentinels `-(id + 1)`
308
+ // marking completion of an expanded product node.
309
+ const stack = [];
310
+ for (let i = initial.length - 1; i >= 0; i--) {
311
+ const id = initial[i];
312
+ if (!Number.isInteger(id) || id < 0 || id >= plist.length) {
313
+ throw new KTVMSchemaError(`Invalid schema node id ${id}`);
314
+ }
315
+ stack.push(id);
316
+ }
317
+
318
+ const active = new Set();
319
+ const knownUnit = new Set();
320
+
321
+ while (stack.length > 0) {
322
+ const top = stack[stack.length - 1];
323
+ if (top < 0) {
324
+ stack.pop();
325
+ const finishedId = -(top + 1);
326
+ active.delete(finishedId);
327
+ knownUnit.add(finishedId);
328
+ continue;
329
+ }
330
+ const node = plist[top];
331
+ if (!node || !Array.isArray(node)) {
332
+ throw new KTVMSchemaError(`Invalid schema node ${top}`);
333
+ }
334
+ const [kind, edges] = node;
335
+ if (kind === "closed-product") {
336
+ stack.pop();
337
+ if (knownUnit.has(top)) continue;
338
+ if (active.has(top)) {
339
+ throw new KTVMSchemaError(`Unguarded product cycle at schema node ${top}`);
340
+ }
341
+ active.add(top);
342
+ stack.push(-(top + 1));
343
+ for (let i = edges.length - 1; i >= 0; i--) {
344
+ const targetId = edges[i][1];
345
+ if (!Number.isInteger(targetId) || targetId < 0 || targetId >= plist.length) {
346
+ throw new KTVMSchemaError(`Invalid edge target ${targetId} from schema node ${top}`);
347
+ }
348
+ stack.push(targetId);
349
+ }
350
+ } else if (kind === "closed-union") {
351
+ break;
352
+ } else {
353
+ throw new KTVMSchemaError(
354
+ `normalizeNodeList requires closed schema nodes, got '${kind}' at node ${top}`
355
+ );
356
+ }
357
+ }
358
+
359
+ const out = [];
360
+ for (let i = stack.length - 1; i >= 0; i--) {
361
+ if (stack[i] >= 0) out.push(stack[i]);
362
+ }
363
+ return out;
364
+ }
365
+
366
+ /**
367
+ * Return `true` iff the residual node list denotes the completed empty-string
368
+ * language `{ε}` (every remaining sub-pattern reduces to empty products).
369
+ */
370
+ export function nodeListComplete(plist, nodes = [0]) {
371
+ return normalizeNodeList(plist, nodes).length === 0;
372
+ }
373
+
374
+ /**
375
+ * Advance a residual node list across one union tag ordinal `ordinal`.
376
+ * Normalizes leading products/units before checking the head `closed-union`,
377
+ * and normalizes the resulting suffix node list.
378
+ */
379
+ export function stepNodeListTag(plist, nodes, ordinal) {
380
+ const norm = normalizeNodeList(plist, nodes);
381
+ if (norm.length === 0) {
382
+ return { ok: false, reason: "node list is already complete (empty)" };
383
+ }
384
+ const headNodeId = norm[0];
385
+ const node = plist[headNodeId];
386
+ if (!node || node[0] !== "closed-union") {
387
+ return {
388
+ ok: false,
389
+ reason: `expected closed-union at node ${headNodeId}, got '${node ? node[0] : "missing"}'`
390
+ };
391
+ }
392
+ const edges = node[1];
393
+ if (edges.length === 0) {
394
+ return { ok: false, reason: `empty closed-union at node ${headNodeId}` };
395
+ }
396
+ if (!Number.isInteger(ordinal) || ordinal < 0 || ordinal >= edges.length) {
397
+ return {
398
+ ok: false,
399
+ reason: `invalid union ordinal ${ordinal} (expected 0..${edges.length - 1}) at node ${headNodeId}`
400
+ };
401
+ }
402
+ const [label, targetId] = edges[ordinal];
403
+ const nextNodes = normalizeNodeList(plist, [targetId, ...norm.slice(1)]);
404
+ return {
405
+ ok: true,
406
+ headNodeId,
407
+ label,
408
+ ordinal,
409
+ width: choiceWidth(edges.length),
410
+ tagCount: edges.length,
411
+ targetId,
412
+ nextNodes
413
+ };
414
+ }
415
+
416
+ /**
417
+ * Advance a residual node list across one union tag identified by its `label`.
418
+ */
419
+ export function stepNodeListLabel(plist, nodes, label) {
420
+ const norm = normalizeNodeList(plist, nodes);
421
+ if (norm.length === 0) {
422
+ return { ok: false, reason: "node list is already complete (empty)" };
423
+ }
424
+ const headNodeId = norm[0];
425
+ const node = plist[headNodeId];
426
+ if (!node || node[0] !== "closed-union") {
427
+ return {
428
+ ok: false,
429
+ reason: `expected closed-union at node ${headNodeId}, got '${node ? node[0] : "missing"}'`
430
+ };
431
+ }
432
+ const ordinal = node[1].findIndex(([l]) => l === label);
433
+ if (ordinal < 0) {
434
+ return { ok: false, reason: `unknown union tag '${label}' at node ${headNodeId}` };
435
+ }
436
+ return stepNodeListTag(plist, norm, ordinal);
437
+ }
438
+
439
+ // --- Bit-Level s-Language Wire Equivalence (Binary GNF + Prime Suffix Factoring) ---
440
+
441
+ const WIRE_LANG_KEY_CACHE = new WeakMap();
442
+ const MAX_GNF_FLAT_LEN = 65536;
443
+ const MAX_GNF_FACTOR_ITERS = 1024;
444
+
445
+ function substGnfSeq(seq, targetId, replacement) {
446
+ if (seq === null) return null;
447
+ let found = false;
448
+ for (let i = 0; i < seq.length; i++) {
449
+ if (seq[i] === targetId) {
450
+ found = true;
451
+ break;
452
+ }
453
+ }
454
+ if (!found) return seq;
455
+ const out = [];
456
+ for (let i = 0; i < seq.length; i++) {
457
+ if (seq[i] === targetId) {
458
+ for (let j = 0; j < replacement.length; j++) out.push(replacement[j]);
459
+ } else {
460
+ out.push(seq[i]);
461
+ }
462
+ }
463
+ return out;
464
+ }
465
+
466
+ function canonicalizeGnfDfs(rootSeq, nodes) {
467
+ const idMap = new Map();
468
+ const outNodes = [];
469
+
470
+ function visit(oldId) {
471
+ if (idMap.has(oldId)) return idMap.get(oldId);
472
+ const newId = outNodes.length;
473
+ idMap.set(oldId, newId);
474
+ const slot = { b0: null, b1: null };
475
+ outNodes.push(slot);
476
+ const cur = nodes[oldId];
477
+ slot.b0 = cur.b0 === null ? null : cur.b0.map(visit);
478
+ slot.b1 = cur.b1 === null ? null : cur.b1.map(visit);
479
+ return newId;
480
+ }
481
+
482
+ const outRoot = rootSeq.map(visit);
483
+ return { root: outRoot, nodes: outNodes };
484
+ }
485
+
486
+ function gcAndMinimizeGnf(rootSeq, nodes) {
487
+ const reach = canonicalizeGnfDfs(rootSeq, nodes);
488
+ const rNodes = reach.nodes;
489
+ const n = rNodes.length;
490
+ if (n === 0) return reach;
491
+
492
+ let cls = new Int32Array(n);
493
+ const initSigs = new Map();
494
+ let numClasses = 0;
495
+ for (let i = 0; i < n; i++) {
496
+ const { b0, b1 } = rNodes[i];
497
+ const sig = `${b0 === null ? "X" : b0.length}|${b1 === null ? "X" : b1.length}`;
498
+ let c = initSigs.get(sig);
499
+ if (c === undefined) {
500
+ c = numClasses++;
501
+ initSigs.set(sig, c);
502
+ }
503
+ cls[i] = c;
504
+ }
505
+
506
+ while (true) {
507
+ const nextCls = new Int32Array(n);
508
+ const sigMap = new Map();
509
+ let nextNum = 0;
510
+ for (let i = 0; i < n; i++) {
511
+ const { b0, b1 } = rNodes[i];
512
+ const s0 = b0 === null ? "X" : b0.map((t) => cls[t]).join(",");
513
+ const s1 = b1 === null ? "X" : b1.map((t) => cls[t]).join(",");
514
+ const sig = `${cls[i]}|${s0}|${s1}`;
515
+ let c = sigMap.get(sig);
516
+ if (c === undefined) {
517
+ c = nextNum++;
518
+ sigMap.set(sig, c);
519
+ }
520
+ nextCls[i] = c;
521
+ }
522
+ cls = nextCls;
523
+ if (nextNum === numClasses) break;
524
+ numClasses = nextNum;
525
+ }
526
+
527
+ const repOfClass = new Int32Array(numClasses).fill(-1);
528
+ for (let i = 0; i < n; i++) {
529
+ if (repOfClass[cls[i]] === -1) repOfClass[cls[i]] = i;
530
+ }
531
+ const quotient = [];
532
+ for (let c = 0; c < numClasses; c++) {
533
+ const { b0, b1 } = rNodes[repOfClass[c]];
534
+ quotient.push({
535
+ b0: b0 === null ? null : b0.map((t) => cls[t]),
536
+ b1: b1 === null ? null : b1.map((t) => cls[t])
537
+ });
538
+ }
539
+ const mappedRoot = reach.root.map((t) => cls[t]);
540
+ return canonicalizeGnfDfs(mappedRoot, quotient);
541
+ }
542
+
543
+ /**
544
+ * Compute a label-erased, bit-level canonical key for the `k-wire` `s`-language
545
+ * `L([v_1, ..., v_k]) ⊆ {0,1}*` of a closed schema node list.
546
+ *
547
+ * Unlike structural `mooreKey` (which preserves field/tag labels and product
548
+ * nesting for `coerce`, `mux`/`demux` fusion, and `kTVM-P` unification),
549
+ * `wireLanguageKey` erases labels, flattens associative products, eliminates
550
+ * units and 1-tag unions, prunes empty branches, expands multi-bit tags into
551
+ * binary `{0,1}` choice tries, applies sound prime right-suffix factoring
552
+ * (single-branch peel, common suffix, and self-recursive suffix factoring),
553
+ * and computes the Moore minimal quotient of the resulting GNF `s`-grammar.
554
+ */
555
+ export function wireLanguageKey(plist, nodes = [0]) {
556
+ if (!isClosedPlist(plist)) {
557
+ throw new KTVMSchemaError("wireLanguageKey requires a closed property-list schema");
558
+ }
559
+ const isSingleId = typeof nodes === "number";
560
+ if (isSingleId) {
561
+ let byRoot = WIRE_LANG_KEY_CACHE.get(plist);
562
+ if (byRoot && byRoot.has(nodes)) return byRoot.get(nodes);
563
+ }
564
+
565
+ const initList = coerceNodeList(nodes);
566
+ for (const id of initList) {
567
+ if (!Number.isInteger(id) || id < 0 || id >= plist.length) {
568
+ throw new KTVMSchemaError(`Invalid schema node id ${id}`);
569
+ }
570
+ }
571
+
572
+ const key = computeWireLanguageKey(plist, initList);
573
+ if (isSingleId) {
574
+ let byRoot = WIRE_LANG_KEY_CACHE.get(plist);
575
+ if (!byRoot) {
576
+ byRoot = new Map();
577
+ WIRE_LANG_KEY_CACHE.set(plist, byRoot);
578
+ }
579
+ byRoot.set(nodes, key);
580
+ }
581
+ return key;
582
+ }
583
+
584
+ function computeWireLanguageKey(plist, initList) {
585
+ if (initList.length === 0) return "EPS";
586
+
587
+ // 1. Expand closed property list into a binary-branching raw graph over
588
+ // { EMPTY, PROD(children[]), BIN(left, right) }, reserving 0..plist.length-1
589
+ // for the original plist vertices so cyclic edges tie directly.
590
+ const nOrig = plist.length;
591
+ const EMPTY_ID = nOrig;
592
+ const raw = new Array(nOrig + 1);
593
+ raw[EMPTY_ID] = { kind: "EMPTY" };
594
+
595
+ function buildUnionTrie(edges, depth, prefix, width, targetSlot) {
596
+ if (depth === width) {
597
+ return prefix < edges.length ? edges[prefix][1] : EMPTY_ID;
598
+ }
599
+ const left = buildUnionTrie(edges, depth + 1, prefix << 1, width, -1);
600
+ const right = buildUnionTrie(edges, depth + 1, (prefix << 1) | 1, width, -1);
601
+ const node = { kind: "BIN", left, right };
602
+ if (targetSlot >= 0) {
603
+ raw[targetSlot] = node;
604
+ return targetSlot;
605
+ }
606
+ const id = raw.length;
607
+ raw.push(node);
608
+ return id;
609
+ }
610
+
611
+ for (let i = 0; i < nOrig; i++) {
612
+ const [kind, edges] = plist[i];
613
+ if (kind === "closed-product") {
614
+ raw[i] = { kind: "PROD", children: edges.map(([, t]) => t) };
615
+ } else if (kind === "closed-union") {
616
+ if (edges.length === 0) {
617
+ raw[i] = { kind: "EMPTY" };
618
+ } else if (edges.length === 1) {
619
+ // 1-tag closed union has choiceWidth(1) === 0 bits.
620
+ raw[i] = { kind: "PROD", children: [edges[0][1]] };
621
+ } else {
622
+ buildUnionTrie(edges, 0, 0, choiceWidth(edges.length), i);
623
+ }
624
+ } else {
625
+ throw new KTVMSchemaError(`wireLanguageKey requires closed nodes, got '${kind}'`);
626
+ }
627
+ }
628
+
629
+ const totalRaw = raw.length;
630
+
631
+ // 2. Least fixed point for productive nodes (L(v) ≠ ∅).
632
+ const productive = new Uint8Array(totalRaw);
633
+ let changed = true;
634
+ while (changed) {
635
+ changed = false;
636
+ for (let i = 0; i < totalRaw; i++) {
637
+ if (productive[i]) continue;
638
+ const node = raw[i];
639
+ if (node.kind === "PROD") {
640
+ let allProd = true;
641
+ for (const c of node.children) {
642
+ if (!productive[c]) {
643
+ allProd = false;
644
+ break;
645
+ }
646
+ }
647
+ if (allProd) {
648
+ productive[i] = 1;
649
+ changed = true;
650
+ }
651
+ } else if (node.kind === "BIN") {
652
+ if (productive[node.left] || productive[node.right]) {
653
+ productive[i] = 1;
654
+ changed = true;
655
+ }
656
+ }
657
+ }
658
+ }
659
+
660
+ for (const id of initList) {
661
+ if (!productive[id]) return "EMPTY";
662
+ }
663
+
664
+ // 3. Least fixed point for unit-only nodes (L(v) = {ε}).
665
+ // Because closed k-wire languages are prefix-free, ε ∈ L(v) <=> L(v) = {ε}.
666
+ const isEps = new Uint8Array(totalRaw);
667
+ changed = true;
668
+ while (changed) {
669
+ changed = false;
670
+ for (let i = 0; i < totalRaw; i++) {
671
+ if (isEps[i]) continue;
672
+ const node = raw[i];
673
+ if (node.kind === "PROD") {
674
+ let allEps = true;
675
+ for (const c of node.children) {
676
+ if (!isEps[c]) {
677
+ allEps = false;
678
+ break;
679
+ }
680
+ }
681
+ if (allEps) {
682
+ isEps[i] = 1;
683
+ changed = true;
684
+ }
685
+ }
686
+ }
687
+ }
688
+
689
+ // 4. Flatten productive PROD nodes into Greibach Normal Form (GNF) lists of
690
+ // BIN nonterminals. Every productive PROD has strictly decreasing
691
+ // productivity rank to its children, so flattening is acyclic.
692
+ const rawToBin = new Map();
693
+ const binRawIds = [];
694
+ const flatMemo = new Map();
695
+
696
+ function getBinId(rawId) {
697
+ let bid = rawToBin.get(rawId);
698
+ if (bid === undefined) {
699
+ bid = binRawIds.length;
700
+ rawToBin.set(rawId, bid);
701
+ binRawIds.push(rawId);
702
+ }
703
+ return bid;
704
+ }
705
+
706
+ function flattenToBins(rawId) {
707
+ if (!productive[rawId]) return null;
708
+ if (isEps[rawId]) return [];
709
+ if (flatMemo.has(rawId)) return flatMemo.get(rawId);
710
+ const node = raw[rawId];
711
+ if (node.kind === "BIN") {
712
+ const res = [getBinId(rawId)];
713
+ flatMemo.set(rawId, res);
714
+ return res;
715
+ }
716
+ // Productive non-eps PROD
717
+ const out = [];
718
+ for (const c of node.children) {
719
+ const part = flattenToBins(c);
720
+ if (part === null) {
721
+ flatMemo.set(rawId, null);
722
+ return null;
723
+ }
724
+ if (out.length + part.length > MAX_GNF_FLAT_LEN) {
725
+ throw new KTVMSchemaError("Schema product expansion exceeded wireLanguageKey limit");
726
+ }
727
+ for (let i = 0; i < part.length; i++) out.push(part[i]);
728
+ }
729
+ flatMemo.set(rawId, out);
730
+ return out;
731
+ }
732
+
733
+ const rootSeq = [];
734
+ for (const id of initList) {
735
+ const part = flattenToBins(id);
736
+ if (part === null) return "EMPTY";
737
+ for (let i = 0; i < part.length; i++) rootSeq.push(part[i]);
738
+ }
739
+ if (rootSeq.length === 0) return "EPS";
740
+
741
+ const binNodes = [];
742
+ for (let bid = 0; bid < binRawIds.length; bid++) {
743
+ const node = raw[binRawIds[bid]];
744
+ const b0 = flattenToBins(node.left);
745
+ const b1 = flattenToBins(node.right);
746
+ binNodes.push({ b0, b1 });
747
+ }
748
+
749
+ // 5. Iterate Moore minimization + sound prime right-suffix factoring (R1/R2/R3).
750
+ // Each rewrite strictly decreases the norm multiset of active nonterminals.
751
+ let gnf = gcAndMinimizeGnf(rootSeq, binNodes);
752
+ for (let iter = 0; iter < MAX_GNF_FACTOR_ITERS; iter++) {
753
+ let rewrote = false;
754
+ const count = gnf.nodes.length;
755
+ for (let id = 0; id < count; id++) {
756
+ const { b0, b1 } = gnf.nodes[id];
757
+
758
+ // R1: Single-branch peel (0·α => P_0·α, 1·α => P_1·α)
759
+ if (b0 !== null && b0.length > 0 && b1 === null) {
760
+ const p0Id = gnf.nodes.length;
761
+ gnf.nodes.push({ b0: [], b1: null });
762
+ const rep = [p0Id, ...b0];
763
+ gnf.root = substGnfSeq(gnf.root, id, rep);
764
+ for (let j = 0; j < p0Id; j++) {
765
+ if (j === id) continue;
766
+ gnf.nodes[j].b0 = substGnfSeq(gnf.nodes[j].b0, id, rep);
767
+ gnf.nodes[j].b1 = substGnfSeq(gnf.nodes[j].b1, id, rep);
768
+ }
769
+ gnf = gcAndMinimizeGnf(gnf.root, gnf.nodes);
770
+ rewrote = true;
771
+ break;
772
+ }
773
+ if (b1 !== null && b1.length > 0 && b0 === null) {
774
+ const p1Id = gnf.nodes.length;
775
+ gnf.nodes.push({ b0: null, b1: [] });
776
+ const rep = [p1Id, ...b1];
777
+ gnf.root = substGnfSeq(gnf.root, id, rep);
778
+ for (let j = 0; j < p1Id; j++) {
779
+ if (j === id) continue;
780
+ gnf.nodes[j].b0 = substGnfSeq(gnf.nodes[j].b0, id, rep);
781
+ gnf.nodes[j].b1 = substGnfSeq(gnf.nodes[j].b1, id, rep);
782
+ }
783
+ gnf = gcAndMinimizeGnf(gnf.root, gnf.nodes);
784
+ rewrote = true;
785
+ break;
786
+ }
787
+
788
+ if (b0 !== null && b1 !== null && b0.length > 0 && b1.length > 0) {
789
+ const last0 = b0[b0.length - 1];
790
+ const last1 = b1[b1.length - 1];
791
+
792
+ // R2: Common right suffix (0·β0·S ∪ 1·β1·S => A'·S)
793
+ if (last0 === last1 && last0 !== id) {
794
+ const suffixId = last0;
795
+ const newId = gnf.nodes.length;
796
+ const rep = [newId, suffixId];
797
+ const newB0 = substGnfSeq(b0.slice(0, -1), id, rep);
798
+ const newB1 = substGnfSeq(b1.slice(0, -1), id, rep);
799
+ gnf.nodes.push({ b0: newB0, b1: newB1 });
800
+ gnf.root = substGnfSeq(gnf.root, id, rep);
801
+ for (let j = 0; j < newId; j++) {
802
+ if (j === id) continue;
803
+ gnf.nodes[j].b0 = substGnfSeq(gnf.nodes[j].b0, id, rep);
804
+ gnf.nodes[j].b1 = substGnfSeq(gnf.nodes[j].b1, id, rep);
805
+ }
806
+ gnf = gcAndMinimizeGnf(gnf.root, gnf.nodes);
807
+ rewrote = true;
808
+ break;
809
+ }
810
+
811
+ // R3: Self-recursive common right suffix (0·β0·A ∪ 1·β1·S => A'·S)
812
+ if (last0 === id && last1 !== id) {
813
+ const suffixId = last1;
814
+ const newId = gnf.nodes.length;
815
+ const rep = [newId, suffixId];
816
+ const newB0 = [...substGnfSeq(b0.slice(0, -1), id, rep), newId];
817
+ const newB1 = substGnfSeq(b1.slice(0, -1), id, rep);
818
+ gnf.nodes.push({ b0: newB0, b1: newB1 });
819
+ gnf.root = substGnfSeq(gnf.root, id, rep);
820
+ for (let j = 0; j < newId; j++) {
821
+ if (j === id) continue;
822
+ gnf.nodes[j].b0 = substGnfSeq(gnf.nodes[j].b0, id, rep);
823
+ gnf.nodes[j].b1 = substGnfSeq(gnf.nodes[j].b1, id, rep);
824
+ }
825
+ gnf = gcAndMinimizeGnf(gnf.root, gnf.nodes);
826
+ rewrote = true;
827
+ break;
828
+ }
829
+ if (last1 === id && last0 !== id) {
830
+ const suffixId = last0;
831
+ const newId = gnf.nodes.length;
832
+ const rep = [newId, suffixId];
833
+ const newB0 = substGnfSeq(b0.slice(0, -1), id, rep);
834
+ const newB1 = [...substGnfSeq(b1.slice(0, -1), id, rep), newId];
835
+ gnf.nodes.push({ b0: newB0, b1: newB1 });
836
+ gnf.root = substGnfSeq(gnf.root, id, rep);
837
+ for (let j = 0; j < newId; j++) {
838
+ if (j === id) continue;
839
+ gnf.nodes[j].b0 = substGnfSeq(gnf.nodes[j].b0, id, rep);
840
+ gnf.nodes[j].b1 = substGnfSeq(gnf.nodes[j].b1, id, rep);
841
+ }
842
+ gnf = gcAndMinimizeGnf(gnf.root, gnf.nodes);
843
+ rewrote = true;
844
+ break;
845
+ }
846
+ }
847
+ }
848
+ if (!rewrote) break;
849
+ }
850
+
851
+ return JSON.stringify({
852
+ root: gnf.root,
853
+ nodes: gnf.nodes.map((node) => [node.b0, node.b1])
854
+ });
855
+ }
856
+
857
+ /**
858
+ * Sound bit-level `s`-language equivalence predicate over closed schemas or
859
+ * residual node lists (`L(p1, nodes1) == L(p2, nodes2) ⊆ {0,1}*`).
860
+ */
861
+ export function wireLanguagesEqual(p1, nodes1 = [0], p2, nodes2 = [0]) {
862
+ if (p1 === p2) {
863
+ if (nodes1 === nodes2) return true;
864
+ if (
865
+ Array.isArray(nodes1) &&
866
+ Array.isArray(nodes2) &&
867
+ nodes1.length === nodes2.length &&
868
+ nodes1.every((v, idx) => v === nodes2[idx])
869
+ ) {
870
+ return true;
871
+ }
872
+ }
873
+ return wireLanguageKey(p1, nodes1) === wireLanguageKey(p2, nodes2);
874
+ }
875
+
876
+ // --- Wire Layout Helpers ---
877
+
878
+ export function isUnitSchema(plist, nodeId = 0) {
879
+ const node = plist[nodeId];
880
+ return node[0] === "closed-product" && node[1].length === 0;
881
+ }
882
+
883
+ export function unionTagInfo(plist, nodeId, label) {
884
+ const node = plist[nodeId];
885
+ if (!node || (node[0] !== "closed-union" && node[0] !== "open-union")) return null;
886
+ const edges = node[1];
887
+ const ordinal = edges.findIndex(([l]) => l === label);
888
+ if (ordinal < 0) return null;
889
+ return {
890
+ ordinal,
891
+ width: choiceWidth(edges.length),
892
+ targetId: edges[ordinal][1],
893
+ tagCount: edges.length
894
+ };
895
+ }
896
+
897
+ export function unionOrdinalInfo(plist, nodeId, ordinal) {
898
+ const node = plist[nodeId];
899
+ if (!node || (node[0] !== "closed-union" && node[0] !== "open-union")) return null;
900
+ const edges = node[1];
901
+ if (ordinal < 0 || ordinal >= edges.length) return null;
902
+ return {
903
+ label: edges[ordinal][0],
904
+ targetId: edges[ordinal][1],
905
+ width: choiceWidth(edges.length),
906
+ tagCount: edges.length
907
+ };
908
+ }
909
+
910
+ export function productFields(plist, nodeId = 0) {
911
+ const node = plist[nodeId];
912
+ if (!node || (node[0] !== "closed-product" && node[0] !== "open-product")) return null;
913
+ return node[1].map(([label, targetId]) => ({ label, targetId }));
914
+ }
915
+
916
+ export function productFieldInfo(plist, nodeId, label) {
917
+ const fields = productFields(plist, nodeId);
918
+ if (!fields) return null;
919
+ const idx = fields.findIndex((f) => f.label === label);
920
+ if (idx < 0) return null;
921
+ return { index: idx, label, targetId: fields[idx].targetId, fields };
922
+ }
923
+
924
+ /**
925
+ * Convert a concrete closed property-list graph back into clean kTVM schema
926
+ * declarations (`$prefix_0`, ...) plus a root schema expression.
927
+ */
928
+ export function plistToSchemaAst(plist, namePrefix = "$S") {
929
+ const min = mooreMinimize(plist, 0).plist;
930
+ // Detect which nodes are referenced recursively (or multiple times) so we emit clean named decls.
931
+ const inDegree = new Int32Array(min.length);
932
+ const isCycleTarget = new Uint8Array(min.length);
933
+ const state = new Int8Array(min.length);
934
+
935
+ function mark(u) {
936
+ state[u] = 1;
937
+ for (const [, v] of min[u][1]) {
938
+ inDegree[v]++;
939
+ if (state[v] === 1) isCycleTarget[v] = 1;
940
+ else if (state[v] === 0) mark(v);
941
+ }
942
+ state[u] = 2;
943
+ }
944
+ mark(0);
945
+
946
+ const decls = [];
947
+ const nameOf = new Map();
948
+ let seq = 0;
949
+ for (let i = 0; i < min.length; i++) {
950
+ const [kind, edges] = min[i];
951
+ if (kind === "closed-product" && edges.length === 0) continue; // inline `unit`
952
+ if (isCycleTarget[i] || inDegree[i] > 1 || i === 0) {
953
+ nameOf.set(i, seq === 0 ? namePrefix : `${namePrefix}_${seq}`);
954
+ seq++;
955
+ }
956
+ }
957
+
958
+ function buildExpr(i, inlineSelf) {
959
+ const [kind, edges] = min[i];
960
+ if (kind === "closed-product" && edges.length === 0) return S.unit();
961
+ if (!inlineSelf && nameOf.has(i)) return S.ref(nameOf.get(i));
962
+ const fields = edges.map(([label, t]) => ({ label, schema: buildExpr(t, false) }));
963
+ if (kind === "closed-product") return S.product(fields);
964
+ if (kind === "closed-union") return S.union(fields);
965
+ if (kind === "open-product") return S.openProduct(fields);
966
+ if (kind === "open-union") return S.openUnion(fields);
967
+ return S.any();
968
+ }
969
+
970
+ for (const [nodeId, name] of nameOf.entries()) {
971
+ decls.push({ name, params: [], expr: buildExpr(nodeId, true) });
972
+ }
973
+ const rootExpr = nameOf.has(0) ? S.ref(nameOf.get(0)) : buildExpr(0, true);
974
+ return { decls, rootExpr, plist: min };
975
+ }
976
+
977
+ /**
978
+ * Unify a polymorphic kTVM-P contract expression against a concrete closed
979
+ * k-wire property-list graph `concretePlist`.
980
+ *
981
+ * Returns `Map<paramName, concreteSubPlist>` binding every schema parameter
982
+ * `$X` in `paramSet`, or throws `KTVMSchemaError` on any structural contradiction.
983
+ */
984
+ export function unifyContractWithConcrete(contractExpr, schemaDecls, paramNames, concretePlist, concreteRootId = 0) {
985
+ if (!isClosedPlist(concretePlist)) {
986
+ throw new KTVMSchemaError("Input envelope schema must be a closed concrete k-wire pattern graph");
987
+ }
988
+ const declMap = schemaDecls instanceof Map
989
+ ? schemaDecls
990
+ : new Map((schemaDecls || []).map((d) => [d.name, d]));
991
+ const paramSet = new Set(paramNames || []);
992
+ const bindings = new Map(); // $X -> minimized concrete subPlist
993
+ const visited = new Set();
994
+
995
+ function unify(cExpr, localEnv, nodeId) {
996
+ const resolved = substituteSchemaExpr(cExpr, localEnv);
997
+ const cNode = concretePlist[nodeId];
998
+ if (!cNode) throw new KTVMSchemaError(`Invalid concrete schema node ${nodeId}`);
999
+ const [cKind, cEdges] = cNode;
1000
+
1001
+ // Schema parameter `$X`
1002
+ if (resolved.kind === "ref" && (!resolved.args || resolved.args.length === 0) && paramSet.has(resolved.name)) {
1003
+ const candidate = mooreMinimize(concretePlist, nodeId).plist;
1004
+ if (bindings.has(resolved.name)) {
1005
+ const prev = bindings.get(resolved.name);
1006
+ // Verify compatibility via K's pattern intersection and Moore equivalence
1007
+ try {
1008
+ const inter = intersectPropertyListPatterns(prev, candidate);
1009
+ const mPrev = mooreKey(prev, 0);
1010
+ const mCand = mooreKey(candidate, 0);
1011
+ const mInter = mooreKey(inter, 0);
1012
+ if (mPrev !== mCand || mInter !== mPrev) {
1013
+ throw new KTVMSchemaError(
1014
+ `Conflicting bindings for schema parameter '${resolved.name}'`
1015
+ );
1016
+ }
1017
+ } catch (err) {
1018
+ if (err instanceof KTVMSchemaError) throw err;
1019
+ throw new KTVMSchemaError(
1020
+ `Incompatible bindings for schema parameter '${resolved.name}': ${err.message}`
1021
+ );
1022
+ }
1023
+ } else {
1024
+ bindings.set(resolved.name, candidate);
1025
+ }
1026
+ return;
1027
+ }
1028
+
1029
+ if (resolved.kind === "any") {
1030
+ return;
1031
+ }
1032
+
1033
+ if (resolved.kind === "unit") {
1034
+ if (cKind !== "closed-product" || cEdges.length !== 0) {
1035
+ throw new KTVMSchemaError(`Expected 'unit', got '${cKind}' with ${cEdges.length} edges`);
1036
+ }
1037
+ return;
1038
+ }
1039
+
1040
+ // Named schema reference (possibly recursive & parameterized)
1041
+ if (resolved.kind === "ref") {
1042
+ const decl = declMap.get(resolved.name);
1043
+ if (!decl) {
1044
+ throw new KTVMSchemaError(`Unknown schema '${resolved.name}'`);
1045
+ }
1046
+ const args = resolved.args || [];
1047
+ if (args.length !== (decl.params || []).length) {
1048
+ throw new KTVMSchemaError(
1049
+ `Schema '${resolved.name}' expects ${(decl.params || []).length} args, got ${args.length}`
1050
+ );
1051
+ }
1052
+ const visitKey = `${exprStructuralKey(resolved)}@${nodeId}`;
1053
+ if (visited.has(visitKey)) return;
1054
+ visited.add(visitKey);
1055
+
1056
+ const nextEnv = new Map();
1057
+ for (let i = 0; i < args.length; i++) {
1058
+ nextEnv.set(decl.params[i], args[i]);
1059
+ }
1060
+ unify(decl.expr, nextEnv, nodeId);
1061
+ return;
1062
+ }
1063
+
1064
+ // Products
1065
+ if (resolved.kind === "product" || resolved.kind === "open_product") {
1066
+ if (cKind !== "closed-product") {
1067
+ throw new KTVMSchemaError(`Expected product schema, got '${cKind}'`);
1068
+ }
1069
+ const cMap = new Map(cEdges);
1070
+ const reqFields = resolved.fields || [];
1071
+ if (resolved.kind === "product" && reqFields.length !== cEdges.length) {
1072
+ throw new KTVMSchemaError(
1073
+ `Closed product arity mismatch: contract has ${reqFields.length} fields, input has ${cEdges.length}`
1074
+ );
1075
+ }
1076
+ for (const f of reqFields) {
1077
+ if (!cMap.has(f.label)) {
1078
+ throw new KTVMSchemaError(`Input product is missing required field '${f.label}'`);
1079
+ }
1080
+ unify(f.schema, localEnv, cMap.get(f.label));
1081
+ }
1082
+ return;
1083
+ }
1084
+
1085
+ // Unions
1086
+ if (resolved.kind === "union" || resolved.kind === "open_union") {
1087
+ if (cKind !== "closed-union") {
1088
+ throw new KTVMSchemaError(`Expected union schema, got '${cKind}'`);
1089
+ }
1090
+ const cMap = new Map(cEdges);
1091
+ const contractMap = new Map((resolved.fields || []).map((f) => [f.label, f.schema]));
1092
+ if (resolved.kind === "union") {
1093
+ // Every tag in input must be accepted by closed union contract; for exact closed-union
1094
+ // contract, check exact tag set match (consistent with k-wire closed union).
1095
+ for (const [label] of cEdges) {
1096
+ if (!contractMap.has(label)) {
1097
+ throw new KTVMSchemaError(`Input union carries unhandled tag '${label}'`);
1098
+ }
1099
+ }
1100
+ if (contractMap.size !== cEdges.length) {
1101
+ throw new KTVMSchemaError(
1102
+ `Closed union tag set mismatch: contract expects [${[...contractMap.keys()].join(", ")}], input has [${cEdges.map(([l]) => l).join(", ")}]`
1103
+ );
1104
+ }
1105
+ } else {
1106
+ // open_union: contract tags present in input must unify; intersection must be non-empty
1107
+ // if contract has tags, at least compatible kinds.
1108
+ }
1109
+ for (const [label, targetId] of cEdges) {
1110
+ if (contractMap.has(label)) {
1111
+ unify(contractMap.get(label), localEnv, targetId);
1112
+ }
1113
+ }
1114
+ return;
1115
+ }
1116
+
1117
+ throw new KTVMSchemaError(`Unsupported contract kind '${resolved.kind}'`);
1118
+ }
1119
+
1120
+ unify(contractExpr, new Map(), concreteRootId);
1121
+ return bindings;
1122
+ }
1123
+
1124
+ /**
1125
+ * Intersect two concrete or open property-list patterns using K's canonical
1126
+ * `intersectPropertyListPatterns`, converting errors into `KTVMSchemaError`.
1127
+ */
1128
+ export function intersectSchemas(leftPlist, rightPlist) {
1129
+ try {
1130
+ return canonicalizePlistOrder(intersectPropertyListPatterns(leftPlist, rightPlist), 0);
1131
+ } catch (err) {
1132
+ throw new KTVMSchemaError(err.message);
1133
+ }
1134
+ }