@fraczak/k 9.0.0 → 9.1.1

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.
package/ktvm/schema.mjs CHANGED
@@ -3,9 +3,10 @@
3
3
  *
4
4
  * Compiles kTVM schema AST expressions to canonical k-wire property-list graphs
5
5
  * (`plist`), computes Moore minimal bisimulation quotients for zero-copy splice
6
- * equivalence (`S1 ≡ S2`), derives prefix derivatives, and unifies polymorphic
7
- * `kTVM-P` contracts against concrete `k-wire` envelopes using K's
8
- * `intersectPropertyListPatterns`.
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`.
9
10
  */
10
11
 
11
12
  import { intersectPropertyListPatterns } from "../codecs/runtime/codec.mjs";
@@ -282,6 +283,596 @@ export function schemasEquivalent(p1, r1, p2, r2) {
282
283
  return mooreKey(p1, r1) === mooreKey(p2, r2);
283
284
  }
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
+
285
876
  // --- Wire Layout Helpers ---
286
877
 
287
878
  export function isUnitSchema(plist, nodeId = 0) {