@fraczak/k 9.0.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.
@@ -41,14 +41,28 @@ import {
41
41
  compileSchemaExprToPlist,
42
42
  mooreKey,
43
43
  schemasEquivalent,
44
+ normalizeNodeList,
45
+ nodeListComplete,
46
+ stepNodeListTag,
47
+ stepNodeListLabel,
48
+ wireLanguageKey,
49
+ wireLanguagesEqual,
50
+ productFields,
44
51
  validateModule,
45
52
  specializeKTVM,
46
53
  clearSpecializationCache,
47
54
  executeKTVM,
48
55
  executeKTVMWire,
56
+ splitWireHeaderOnly,
49
57
  splitEnvelopedWire,
50
58
  encodePayloadToDeque,
51
- decodeDequeToValue
59
+ decodeDequeToValue,
60
+ encodeValueToEnvelopedWire,
61
+ DPDA_RESULT,
62
+ createSchemaCursor,
63
+ cursorNodeList,
64
+ stepSchemaCursor,
65
+ scanBufferAlignedOffset
52
66
  } from "./index.mjs";
53
67
 
54
68
  // --- Helpers to build K Values cleanly ---
@@ -1371,6 +1385,421 @@ test("packed_base64 chunk_table + fsm_table_step + kernel handoff work end-to-en
1371
1385
  assert.ok(rPack.telemetry.tableLookups >= 10);
1372
1386
  });
1373
1387
 
1388
+ // ============================================================================
1389
+ // 7. s-Language Node-List Derivatives, Wire Equivalence & Aligned Scanner
1390
+ // ============================================================================
1391
+
1392
+ function compileSchemaSnippet(src, refName) {
1393
+ const mod = parseModule(`ktvm 0.1 mono;\n${src}`);
1394
+ return compileSchemaExprToPlist({ kind: "ref", name: refName, args: [] }, mod.schemas);
1395
+ }
1396
+
1397
+ test("Node-list prefix derivatives: unit/product normalization, tag/label steps, and cycle checks", () => {
1398
+ const listPlist = compileSchemaSnippet(
1399
+ `
1400
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1401
+ schema $int = union { +: $bits, -: $bits };
1402
+ schema $list = union { cons: product { car: $int, cdr: $list }, nil: unit };
1403
+ `,
1404
+ "$list"
1405
+ );
1406
+
1407
+ // Initial list root is already a union (`closed-union` at node 0)
1408
+ assert.deepEqual(normalizeNodeList(listPlist, [0]), [0]);
1409
+ assert.equal(nodeListComplete(listPlist, [0]), false);
1410
+
1411
+ // Step /cons -> expands product { car: $int, cdr: $list } into [intId, listId]
1412
+ const sCons = stepNodeListLabel(listPlist, [0], "cons");
1413
+ assert.equal(sCons.ok, true);
1414
+ assert.equal(sCons.label, "cons");
1415
+ assert.equal(sCons.ordinal, 0);
1416
+ assert.equal(sCons.width, 1);
1417
+ assert.equal(sCons.nextNodes.length, 2);
1418
+ const [intId, listId] = sCons.nextNodes;
1419
+ assert.equal(listId, 0);
1420
+
1421
+ // Step sign `+` on [intId, listId] -> [bitsId, listId]
1422
+ const sPlus = stepNodeListLabel(listPlist, sCons.nextNodes, "+");
1423
+ assert.equal(sPlus.ok, true);
1424
+ assert.equal(sPlus.width, 1);
1425
+ const [bitsId, tailListId] = sPlus.nextNodes;
1426
+ assert.equal(tailListId, 0);
1427
+
1428
+ // Step bit `1` then `_` (unit!) on [bitsId, listId] -> collapses unit, leaving [listId]
1429
+ const sOne = stepNodeListTag(listPlist, sPlus.nextNodes, 1);
1430
+ assert.equal(sOne.ok, true);
1431
+ assert.equal(sOne.label, "1");
1432
+ assert.equal(sOne.width, 2);
1433
+ assert.deepEqual(sOne.nextNodes, [bitsId, 0]);
1434
+
1435
+ const sTerm = stepNodeListLabel(listPlist, sOne.nextNodes, "_");
1436
+ assert.equal(sTerm.ok, true);
1437
+ assert.deepEqual(sTerm.nextNodes, [0]);
1438
+
1439
+ // Step /nil -> unit eliminates completely to []
1440
+ const sNil = stepNodeListLabel(listPlist, sTerm.nextNodes, "nil");
1441
+ assert.equal(sNil.ok, true);
1442
+ assert.deepEqual(sNil.nextNodes, []);
1443
+ assert.equal(nodeListComplete(listPlist, sNil.nextNodes), true);
1444
+
1445
+ // Error cases: stepping complete list, bad ordinal, unknown label
1446
+ assert.equal(stepNodeListTag(listPlist, [], 0).ok, false);
1447
+ assert.equal(stepNodeListTag(listPlist, [bitsId], 3).ok, false);
1448
+ assert.equal(stepNodeListLabel(listPlist, [0], "missing").ok, false);
1449
+
1450
+ // Shared unit-product diamond must normalize cleanly in linear time (not a cycle!)
1451
+ const unitDiamond = [
1452
+ ["closed-product", [["a", 1], ["b", 1]]],
1453
+ ["closed-product", [["c", 2], ["d", 2]]],
1454
+ ["closed-product", []]
1455
+ ];
1456
+ assert.deepEqual(normalizeNodeList(unitDiamond, [0]), []);
1457
+ assert.equal(nodeListComplete(unitDiamond, [0]), true);
1458
+
1459
+ // True unguarded product cycle must throw KTVMSchemaError
1460
+ const cyclicProd = [
1461
+ ["closed-product", [["a", 1]]],
1462
+ ["closed-product", [["b", 0]]]
1463
+ ];
1464
+ assert.throws(() => normalizeNodeList(cyclicProd, [0]), KTVMSchemaError);
1465
+ });
1466
+
1467
+ test("Bit-level s-language equivalence (wireLanguagesEqual) vs structural schemasEquivalent", () => {
1468
+ const bitsInt1 = compileSchemaSnippet(
1469
+ `
1470
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1471
+ schema $int = union { +: $bits, -: $bits };
1472
+ schema $pair = product { a: $int, b: $bits };
1473
+ `,
1474
+ "$pair"
1475
+ );
1476
+ const bitsInt2 = compileSchemaSnippet(
1477
+ `
1478
+ schema $b = union { x0: $b, x1: $b, z: unit };
1479
+ schema $i = union { neg: $b, pos: $b };
1480
+ schema $p = product { first: $i, second: $b };
1481
+ `,
1482
+ "$p"
1483
+ );
1484
+ // Renamed labels: same bit language, distinct structural Moore schemas!
1485
+ assert.equal(wireLanguagesEqual(bitsInt1, [0], bitsInt2, [0]), true);
1486
+ assert.equal(schemasEquivalent(bitsInt1, 0, bitsInt2, 0), false);
1487
+
1488
+ // Product associativity: {{A, B}, C} vs {A, {B, C}} and node-list [A, B, C]
1489
+ const leftAssoc = compileSchemaSnippet(
1490
+ `
1491
+ schema $u2 = union { a: unit, b: unit };
1492
+ schema $u3 = union { a: unit, b: unit, c: unit };
1493
+ schema $s = product { ab: product { a: $u2, b: $u3 }, c: $u2 };
1494
+ `,
1495
+ "$s"
1496
+ );
1497
+ const rightAssoc = compileSchemaSnippet(
1498
+ `
1499
+ schema $u2 = union { x: unit, y: unit };
1500
+ schema $u3 = union { x: unit, y: unit, z: unit };
1501
+ schema $s = product { a: $u2, bc: product { b: $u3, c: $u2 } };
1502
+ `,
1503
+ "$s"
1504
+ );
1505
+ assert.equal(wireLanguagesEqual(leftAssoc, [0], rightAssoc, [0]), true);
1506
+ assert.equal(schemasEquivalent(leftAssoc, 0, rightAssoc, 0), false);
1507
+ const flatNodes = normalizeNodeList(leftAssoc, [0]);
1508
+ assert.equal(flatNodes.length, 3);
1509
+ assert.equal(wireLanguagesEqual(leftAssoc, flatNodes, rightAssoc, [0]), true);
1510
+
1511
+ // Unit elimination and 1-tag union elimination
1512
+ const plainInt = compileSchemaSnippet(
1513
+ `
1514
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1515
+ schema $int = union { +: $bits, -: $bits };
1516
+ `,
1517
+ "$int"
1518
+ );
1519
+ const wrappedInt = compileSchemaSnippet(
1520
+ `
1521
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1522
+ schema $int = union { +: $bits, -: $bits };
1523
+ schema $wrap = product { a: unit, b: union { only: $int }, c: product { u: unit } };
1524
+ `,
1525
+ "$wrap"
1526
+ );
1527
+ assert.equal(wireLanguagesEqual(plainInt, 0, wrappedInt, 0), true);
1528
+
1529
+ // Dead union branch elimination (`<a:{}, b:{}, c:{}, d:<>>` == `<a:{}, b:{}, c:{}>`)
1530
+ const threeTag = [
1531
+ ["closed-union", [["a", 1], ["b", 1], ["c", 1]]],
1532
+ ["closed-product", []]
1533
+ ];
1534
+ const fourWithDead = [
1535
+ ["closed-union", [["a", 1], ["b", 1], ["c", 1], ["d", 2]]],
1536
+ ["closed-product", []],
1537
+ ["closed-union", []]
1538
+ ];
1539
+ assert.equal(wireLanguagesEqual(threeTag, 0, fourWithDead, 0), true);
1540
+
1541
+ // Prime suffix factoring (R2 & R3):
1542
+ // 1) 4-tag union == product of two 2-tag unions == nested 2-tag unions (all = {00,01,10,11})
1543
+ const fourTag = compileSchemaSnippet(`schema $s = union { a: unit, b: unit, c: unit, d: unit };`, "$s");
1544
+ const twoByTwo = compileSchemaSnippet(
1545
+ `
1546
+ schema $bit = union { 0: unit, 1: unit };
1547
+ schema $s = product { a: $bit, b: $bit };
1548
+ `,
1549
+ "$s"
1550
+ );
1551
+ const nestedTwo = compileSchemaSnippet(
1552
+ `
1553
+ schema $bit = union { 0: unit, 1: unit };
1554
+ schema $s = union { a: $bit, b: $bit };
1555
+ `,
1556
+ "$s"
1557
+ );
1558
+ assert.equal(wireLanguagesEqual(fourTag, 0, twoByTwo, 0), true);
1559
+ assert.equal(wireLanguagesEqual(fourTag, 0, nestedTwo, 0), true);
1560
+
1561
+ // 2) `int[] = < +: bits[], -: bits[] >` == `{ a_sign: < +: unit, -: unit >, b_mag: bits[] }`
1562
+ const splitInt = compileSchemaSnippet(
1563
+ `
1564
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1565
+ schema $sign = union { +: unit, -: unit };
1566
+ schema $s = product { a_sign: $sign, b_mag: $bits };
1567
+ `,
1568
+ "$s"
1569
+ );
1570
+ assert.equal(wireLanguagesEqual(plainInt, 0, splitInt, 0), true);
1571
+
1572
+ // 3) Recursive unrolling (`< 0: S, 1: {} >` == `< 0: < 0: S, 1: {} >, 1: {} >`)
1573
+ const rec1 = compileSchemaSnippet(`schema $s = union { 0: $s, 1: unit };`, "$s");
1574
+ const rec2 = compileSchemaSnippet(`schema $s = union { 0: union { 0: $s, 1: unit }, 1: unit };`, "$s");
1575
+ assert.equal(wireLanguagesEqual(rec1, 0, rec2, 0), true);
1576
+
1577
+ // Negative cases: MUST return false when bit languages differ!
1578
+ const twoTag = compileSchemaSnippet(`schema $s = union { a: unit, b: unit };`, "$s");
1579
+ assert.equal(wireLanguagesEqual(twoTag, 0, threeTag, 0), false);
1580
+
1581
+ const ordAB = compileSchemaSnippet(
1582
+ `
1583
+ schema $u2 = union { a: unit, b: unit };
1584
+ schema $u3 = union { a: unit, b: unit, c: unit };
1585
+ schema $s = product { a: $u2, b: $u3 };
1586
+ `,
1587
+ "$s"
1588
+ );
1589
+ const ordBA = compileSchemaSnippet(
1590
+ `
1591
+ schema $u2 = union { a: unit, b: unit };
1592
+ schema $u3 = union { a: unit, b: unit, c: unit };
1593
+ schema $s = product { a: $u3, b: $u2 };
1594
+ `,
1595
+ "$s"
1596
+ );
1597
+ assert.equal(wireLanguagesEqual(ordAB, 0, ordBA, 0), false);
1598
+
1599
+ const rev1 = compileSchemaSnippet(
1600
+ `
1601
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1602
+ schema $s = union { a: $bits, b: unit };
1603
+ `,
1604
+ "$s"
1605
+ );
1606
+ const rev2 = compileSchemaSnippet(
1607
+ `
1608
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1609
+ schema $s = union { a: unit, b: $bits };
1610
+ `,
1611
+ "$s"
1612
+ );
1613
+ assert.equal(wireLanguagesEqual(rev1, 0, rev2, 0), false);
1614
+
1615
+ // Empty language vs unit language
1616
+ const emptyPlist = [["closed-union", []]];
1617
+ const unitPlist = [["closed-product", []]];
1618
+ const unprodCycle = [["closed-union", [["a", 0], ["b", 0]]]];
1619
+ assert.equal(wireLanguageKey(emptyPlist, 0), "EMPTY");
1620
+ assert.equal(wireLanguageKey(unprodCycle, 0), "EMPTY");
1621
+ assert.equal(wireLanguageKey(unitPlist, 0), "EPS");
1622
+ assert.equal(wireLanguagesEqual(emptyPlist, 0, unitPlist, 0), false);
1623
+ assert.equal(wireLanguagesEqual(emptyPlist, 0, unprodCycle, 0), true);
1624
+ });
1625
+
1626
+ test("Unified SchemaCursor, BitDeque node-list getters, and scanBufferAlignedOffset", () => {
1627
+ const listPlist = compileSchemaSnippet(
1628
+ `
1629
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1630
+ schema $int = union { +: $bits, -: $bits };
1631
+ schema $list = union { cons: product { car: $int, cdr: $list }, nil: unit };
1632
+ `,
1633
+ "$list"
1634
+ );
1635
+
1636
+ // BitDeque prodNodeList / consNodeList getters
1637
+ const emptyChan = new BitDeque(700);
1638
+ assert.deepEqual(emptyChan.prodNodeList, []);
1639
+ assert.deepEqual(emptyChan.consNodeList, []);
1640
+ emptyChan.release();
1641
+
1642
+ const typedChan = new BitDeque(701, {
1643
+ prodSchema: listPlist,
1644
+ prodNodeId: 0,
1645
+ consSchema: listPlist,
1646
+ consNodeId: 0
1647
+ });
1648
+ assert.deepEqual(typedChan.prodNodeList, [0]);
1649
+ assert.deepEqual(typedChan.consNodeList, [0]);
1650
+ typedChan.release();
1651
+
1652
+ // Build list `[+5, -13, +0]` and encode to enveloped k-wire bytes
1653
+ const elems = [
1654
+ Value.variant("+", bitsFromBigIntLSB(5n)),
1655
+ Value.variant("-", bitsFromBigIntLSB(13n)),
1656
+ Value.variant("+", bitsFromBigIntLSB(0n))
1657
+ ];
1658
+ let listVal = Value.variant("nil", UNIT);
1659
+ for (let i = elems.length - 1; i >= 0; i--) {
1660
+ listVal = Value.variant("cons", Value.product({ car: elems[i], cdr: listVal }));
1661
+ }
1662
+ const wire = encodeValueToEnvelopedWire(listVal, listPlist);
1663
+ const { plist: hdrPlist, headerBitLen } = splitWireHeaderOnly(wire);
1664
+
1665
+ // Walk the raw enveloped buffer strictly via node-list aligned offsets!
1666
+ let offset = headerBitLen;
1667
+ let nodes = [0];
1668
+ const decodedElems = [];
1669
+
1670
+ while (true) {
1671
+ const tagStep = scanBufferAlignedOffset(wire, offset, hdrPlist, nodes, { mode: "tag" });
1672
+ assert.equal(tagStep.ok, true);
1673
+ offset = tagStep.bitOffset;
1674
+ nodes = tagStep.nodes;
1675
+ if (tagStep.label === "nil") {
1676
+ assert.equal(tagStep.complete, true);
1677
+ assert.deepEqual(nodes, []);
1678
+ break;
1679
+ }
1680
+ assert.equal(tagStep.label, "cons");
1681
+ assert.equal(nodes.length, 2);
1682
+ const elemStart = offset;
1683
+ const elemNodeId = nodes[0];
1684
+
1685
+ // Skip the complete head `int[]` sub-value to reach the aligned `cdr` offset
1686
+ const valStep = scanBufferAlignedOffset(wire, offset, hdrPlist, nodes, { mode: "value" });
1687
+ assert.equal(valStep.ok, true);
1688
+ assert.equal(valStep.headNodeId, elemNodeId);
1689
+ const elemEnd = valStep.bitOffset;
1690
+
1691
+ // Independently slice [elemStart..elemEnd) into a fresh BitDeque and decode under elemNodeId
1692
+ const sliceDq = new BitDeque(702);
1693
+ for (let b = elemStart; b < elemEnd; b++) {
1694
+ const bit = (wire[b >>> 3] >>> (7 - (b & 7))) & 1;
1695
+ sliceDq.pushBits(bit, 1);
1696
+ }
1697
+ sliceDq.close();
1698
+ const elemVal = decodeDequeToValue(sliceDq, hdrPlist, elemNodeId, { exact: true });
1699
+ sliceDq.release();
1700
+ decodedElems.push({ sign: elemVal.tag, mag: bitsToBigIntLSB(elemVal.value) });
1701
+
1702
+ offset = elemEnd;
1703
+ nodes = valStep.nodes;
1704
+ assert.deepEqual(nodes, [0]); // back at aligned `[listNodeId]`!
1705
+ }
1706
+
1707
+ assert.deepEqual(decodedElems, [
1708
+ { sign: "+", mag: 5n },
1709
+ { sign: "-", mag: 13n },
1710
+ { sign: "+", mag: 0n }
1711
+ ]);
1712
+ const trailingPadBits = wire.length * 8 - offset;
1713
+ assert.ok(trailingPadBits >= 0 && trailingPadBits < 8);
1714
+
1715
+ // Resumable SchemaCursor fed 1 bit at a time across a multi-node list [intId, listId]
1716
+ const intNodeId = stepNodeListLabel(listPlist, [0], "cons").nextNodes[0];
1717
+ const srcFull = new BitDeque(703);
1718
+ encodePayloadToDeque(elems[0], listPlist, srcFull, intNodeId);
1719
+ encodePayloadToDeque(listVal, listPlist, srcFull, 0);
1720
+ const fullBits = srcFull.toBitString();
1721
+ srcFull.release();
1722
+
1723
+ const streamIn = new BitDeque(704);
1724
+ const streamOut = new BitDeque(705);
1725
+ const cursor = createSchemaCursor(listPlist, [intNodeId, 0]);
1726
+ assert.deepEqual(cursorNodeList(cursor), [intNodeId, 0]);
1727
+
1728
+ let res = DPDA_RESULT.NEED_BITS;
1729
+ for (let i = 0; i < fullBits.length; i++) {
1730
+ streamIn.pushBits(fullBits[i] === "1" ? 1 : 0, 1);
1731
+ res = stepSchemaCursor(streamIn, cursor, streamOut);
1732
+ if (i < fullBits.length - 1) {
1733
+ assert.equal(res, DPDA_RESULT.NEED_BITS);
1734
+ assert.ok(cursorNodeList(cursor).length >= 1);
1735
+ }
1736
+ }
1737
+ assert.equal(res, DPDA_RESULT.DONE);
1738
+ assert.deepEqual(cursorNodeList(cursor), []);
1739
+ assert.equal(streamOut.toBitString(), fullBits);
1740
+ streamIn.release();
1741
+ streamOut.release();
1742
+
1743
+ // Nested product: whole-field skip vs flattened leaf skip
1744
+ const nestedProd = compileSchemaSnippet(
1745
+ `
1746
+ schema $bits = union { 0: $bits, 1: $bits, _: unit };
1747
+ schema $int = union { +: $bits, -: $bits };
1748
+ schema $inner = product { p: $int, q: $bits };
1749
+ schema $outer = product { first: $inner, second: $int };
1750
+ `,
1751
+ "$outer"
1752
+ );
1753
+ const outerVal = Value.product({
1754
+ first: Value.product({
1755
+ p: Value.variant("+", bitsFromBigIntLSB(3n)),
1756
+ q: bitsFromBigIntLSB(6n)
1757
+ }),
1758
+ second: Value.variant("-", bitsFromBigIntLSB(9n))
1759
+ });
1760
+ const outerWire = encodeValueToEnvelopedWire(outerVal, nestedProd);
1761
+ const outerHdr = splitWireHeaderOnly(outerWire);
1762
+ const topFields = productFields(outerHdr.plist, 0);
1763
+ const fieldIds = topFields.map((f) => f.targetId);
1764
+
1765
+ // Skip whole `first` (`$inner`) in one step -> leaves `[second]`
1766
+ const afterFirst = scanBufferAlignedOffset(outerWire, outerHdr.headerBitLen, outerHdr.plist, fieldIds, {
1767
+ mode: "value"
1768
+ });
1769
+ assert.equal(afterFirst.ok, true);
1770
+ assert.deepEqual(afterFirst.nodes, [fieldIds[1]]);
1771
+ assert.equal(afterFirst.complete, false);
1772
+
1773
+ // Decode `second` directly from `afterFirst.bitOffset`
1774
+ const afterSecond = scanBufferAlignedOffset(outerWire, afterFirst.bitOffset, outerHdr.plist, afterFirst.nodes, {
1775
+ mode: "value"
1776
+ });
1777
+ assert.equal(afterSecond.ok, true);
1778
+ assert.deepEqual(afterSecond.nodes, []);
1779
+ assert.equal(afterSecond.complete, true);
1780
+
1781
+ // Error checks in scanBufferAlignedOffset: truncated `cons` (bit 0 = cons, missing car/cdr),
1782
+ // invalid ordinal 0b11, out-of-bounds bit offset, and 0-bit union cycle.
1783
+ assert.equal(
1784
+ scanBufferAlignedOffset(new Uint8Array([0b00000000]), 0, listPlist, [0], { mode: "value", totalBits: 1 }).ok,
1785
+ false
1786
+ );
1787
+ const bitsOnly = compileSchemaSnippet(`schema $bits = union { 0: $bits, 1: $bits, _: unit };`, "$bits");
1788
+ assert.equal(
1789
+ scanBufferAlignedOffset(new Uint8Array([0b11000000]), 0, bitsOnly, [0], { mode: "tag", totalBits: 2 }).ok,
1790
+ false
1791
+ );
1792
+ assert.equal(
1793
+ scanBufferAlignedOffset(new Uint8Array([0]), 9, bitsOnly, [0], { mode: "value" }).ok,
1794
+ false
1795
+ );
1796
+ const zeroUnionCycle = [["closed-union", [["loop", 0]]]];
1797
+ assert.equal(
1798
+ scanBufferAlignedOffset(new Uint8Array([0]), 0, zeroUnionCycle, [0], { mode: "value" }).ok,
1799
+ false
1800
+ );
1801
+ });
1802
+
1374
1803
  // --- Summary ---
1375
1804
  console.log(`\nResults: ${passed} passed, ${failed} failed.`);
1376
1805
  if (failed > 0) process.exit(1);
@@ -4340,7 +4340,6 @@
4340
4340
  (param $outPtr i32) (param $outCap i32) (param $frameHeader i32)
4341
4341
  (result i32)
4342
4342
  (local $rootSc i32)
4343
- (local $rawCh i32)
4344
4343
  (local $rootIn i32)
4345
4344
  (local $rootOut i32)
4346
4345
  (local $dpda i32)
@@ -4354,29 +4353,21 @@
4354
4353
  (local.set $rootIn (call $chan_alloc (local.get $rootSc) (global.get $DATA_IN_SCHEMA_ID)))
4355
4354
  (if (i32.ne (global.get $g_error_code) (i32.const 0)) (then (return (global.get $g_error_code))))
4356
4355
 
4356
+ ;; Validate through the input channel cursor, then rewind over the same buffer.
4357
+ (call $bd_load_bytes_at (local.get $rootIn) (local.get $inPtr) (local.get $inBitOff) (local.get $inBitLen))
4358
+ (if (i32.ne (global.get $g_error_code) (i32.const 0)) (then (return (global.get $g_error_code))))
4357
4359
  (if (local.get $validatePad)
4358
4360
  (then
4359
- ;; Load raw bits + DPDA-copy exact payload + check trailing <8 zero pad bits!
4360
- (local.set $rawCh (call $chan_alloc (i32.const 0) (global.get $DATA_IN_SCHEMA_ID)))
4361
- (call $bd_load_bytes_at (local.get $rawCh) (local.get $inPtr) (local.get $inBitOff) (local.get $inBitLen))
4362
- (if (i32.ne (global.get $g_error_code) (i32.const 0)) (then (return (global.get $g_error_code))))
4363
- (local.set $dpda (call $dpda_alloc (i32.const 1) (global.get $DATA_IN_SCHEMA_ID) (i32.const 0)))
4364
- (local.set $res (call $dpda_step_skip_copy (local.get $rawCh) (local.get $rootIn) (local.get $dpda)))
4361
+ (local.set $dpda (call $dpda_alloc (i32.const 0) (global.get $DATA_IN_SCHEMA_ID) (i32.const 0)))
4362
+ (local.set $res (call $dpda_step_skip_copy (local.get $rootIn) (i32.const 0) (local.get $dpda)))
4365
4363
  (call $dpda_free (local.get $dpda))
4366
4364
  (if (i32.ne (local.get $res) (i32.const 0)) (then (return (i32.const -6))))
4367
- (local.set $rem (i32.load (i32.add (local.get $rawCh) (i32.const 44))))
4365
+ (local.set $rem (i32.load (i32.add (local.get $rootIn) (i32.const 44))))
4368
4366
  (if (i32.ge_s (local.get $rem) (i32.const 8)) (then (return (i32.const -6))))
4369
- (if (i32.gt_s (local.get $rem) (i32.const 0))
4370
- (then
4371
- (if (i32.ne (call $bd_shift_bits (local.get $rawCh) (local.get $rem)) (i32.const 0))
4372
- (then (return (i32.const -6))))))
4373
- (call $bd_release (local.get $rawCh))
4374
- )
4375
- (else
4376
- (call $bd_load_bytes_at (local.get $rootIn) (local.get $inPtr) (local.get $inBitOff) (local.get $inBitLen))
4377
- (if (i32.ne (global.get $g_error_code) (i32.const 0)) (then (return (global.get $g_error_code))))
4378
- )
4379
- )
4367
+ (if (i32.ne (call $bd_shift_bits (local.get $rootIn) (local.get $rem)) (i32.const 0))
4368
+ (then (return (i32.const -6))))
4369
+ (i32.store (i32.add (local.get $rootIn) (i32.const 40)) (i32.const 0))
4370
+ (i32.store (i32.add (local.get $rootIn) (i32.const 44)) (i32.sub (local.get $inBitLen) (local.get $rem)))))
4380
4371
  (call $bd_close (local.get $rootIn))
4381
4372
 
4382
4373
  (local.set $rootOut (call $chan_alloc (i32.const 0) (global.get $DATA_OUT_SCHEMA_ID)))
@@ -294,6 +294,9 @@ await test("Wasm enforces maxSteps & maxBitDequeBytes quotas and rejects malform
294
294
  // Truncated payload rejected cleanly
295
295
  const truncated = bigWire.subarray(0, bigWire.length - 4);
296
296
  assert.throws(() => runner.executeWire(truncated), /Malformed k-wire/);
297
+ assert.throws(() => runner.executeWire(Buffer.concat([bigWire, Buffer.alloc(1)])), /Malformed k-wire/);
298
+ const expected = executeKTVMWire(artifact.ktvmModule, bigWire, { entry: artifact.entry, validate: false });
299
+ assert.deepEqual(Buffer.from(runner.executeWire(bigWire).wire), Buffer.from(expected.wire));
297
300
  });
298
301
 
299
302
  await test("Wasm spec: local mismatch rollback + upstream failure abort + after %tok sequential settlement", async () => {