mcard-js 2.1.47 → 2.1.49

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 (52) hide show
  1. package/dist/AbstractSqlEngine-DKka6XjT.d.cts +451 -0
  2. package/dist/AbstractSqlEngine-DKka6XjT.d.ts +451 -0
  3. package/dist/CardCollection-TYC67XOH.js +10 -0
  4. package/dist/CardCollection-ZQ3G3Q3A.js +10 -0
  5. package/dist/EventProducer-VFDOM5W2.js +47 -0
  6. package/dist/IndexedDBEngine-5CEFZDOG.js +12 -0
  7. package/dist/IndexedDBEngine-BWXAB46W.js +12 -0
  8. package/dist/LLMRuntime-PH3MOQ2Y.js +17 -0
  9. package/dist/LambdaRuntime-DMEBYJIN.js +19 -0
  10. package/dist/LambdaRuntime-YH74FHIW.js +19 -0
  11. package/dist/Loader-OBPDJNFH.js +12 -0
  12. package/dist/Loader-WZXYG4GE.js +12 -0
  13. package/dist/MCard-RHTWJPHJ.js +8 -0
  14. package/dist/NetworkRuntime-KBQURQ6A.js +1598 -0
  15. package/dist/NetworkRuntime-S4DZCGVN.js +1598 -0
  16. package/dist/OllamaProvider-SPGO5Z5E.js +9 -0
  17. package/dist/chunk-3FFEA2XK.js +149 -0
  18. package/dist/chunk-7AXRV7NS.js +112 -0
  19. package/dist/chunk-AAO4GDBI.js +2360 -0
  20. package/dist/chunk-ASW6AOA7.js +140 -0
  21. package/dist/chunk-BJJZWPIF.js +112 -0
  22. package/dist/chunk-GGQCF7ZK.js +170 -0
  23. package/dist/chunk-HIVVDGE5.js +497 -0
  24. package/dist/chunk-HWBEGVEN.js +364 -0
  25. package/dist/chunk-ISY5LYLF.js +217 -0
  26. package/dist/chunk-KVZYFZJ5.js +427 -0
  27. package/dist/chunk-NGTY4P6A.js +275 -0
  28. package/dist/chunk-OAHWTOEB.js +275 -0
  29. package/dist/chunk-OUW2SUGM.js +368 -0
  30. package/dist/chunk-QKH3N62B.js +2360 -0
  31. package/dist/chunk-QPVEUPMU.js +299 -0
  32. package/dist/chunk-RZENJZGX.js +299 -0
  33. package/dist/chunk-VYDZR4ZD.js +364 -0
  34. package/dist/chunk-XJZOEM5F.js +903 -0
  35. package/dist/chunk-Z7EFXSTO.js +217 -0
  36. package/dist/index.browser.cjs +58 -20
  37. package/dist/index.browser.d.cts +34 -17
  38. package/dist/index.browser.d.ts +34 -17
  39. package/dist/index.browser.js +12 -8
  40. package/dist/index.cjs +644 -167
  41. package/dist/index.d.cts +725 -5
  42. package/dist/index.d.ts +725 -5
  43. package/dist/index.js +536 -95
  44. package/dist/storage/SqliteNodeEngine.cjs +28 -20
  45. package/dist/storage/SqliteNodeEngine.d.cts +1 -1
  46. package/dist/storage/SqliteNodeEngine.d.ts +1 -1
  47. package/dist/storage/SqliteNodeEngine.js +5 -5
  48. package/dist/storage/SqliteWasmEngine.cjs +28 -20
  49. package/dist/storage/SqliteWasmEngine.d.cts +1 -1
  50. package/dist/storage/SqliteWasmEngine.d.ts +1 -1
  51. package/dist/storage/SqliteWasmEngine.js +5 -5
  52. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  import {
2
2
  FileIO_exports,
3
3
  Loader_exports
4
- } from "./chunk-MECEQNTO.js";
4
+ } from "./chunk-VYDZR4ZD.js";
5
5
  import {
6
6
  LLMRuntime,
7
7
  chatMonad,
8
8
  promptMonad
9
- } from "./chunk-UEXPSC52.js";
9
+ } from "./chunk-KVZYFZJ5.js";
10
10
  import {
11
11
  LLMConfig
12
- } from "./chunk-4OAJAFFP.js";
12
+ } from "./chunk-OUW2SUGM.js";
13
13
  import {
14
14
  NETWORK_DEFAULT_HOST,
15
15
  PROCESS_TERMINATE_WAIT_MS,
@@ -61,12 +61,14 @@ import {
61
61
  storeTerm,
62
62
  termExists,
63
63
  termToMCard
64
- } from "./chunk-76T7FWZ6.js";
64
+ } from "./chunk-QKH3N62B.js";
65
65
  import {
66
66
  ErrorCodes,
67
67
  FaroSidecar,
68
68
  LensProtocol,
69
69
  MCardStore,
70
+ PostconditionViolation,
71
+ PreconditionViolation,
70
72
  Reader,
71
73
  ServiceWorkerPTR,
72
74
  State,
@@ -75,10 +77,10 @@ import {
75
77
  Writer,
76
78
  computeHash,
77
79
  validationRegistry
78
- } from "./chunk-SP4YPKPR.js";
80
+ } from "./chunk-XJZOEM5F.js";
79
81
  import {
80
82
  IndexedDBEngine
81
- } from "./chunk-GQZKMXGA.js";
83
+ } from "./chunk-NGTY4P6A.js";
82
84
  import {
83
85
  IO
84
86
  } from "./chunk-MPMRBT5R.js";
@@ -87,11 +89,11 @@ import {
87
89
  } from "./chunk-2KADE3SE.js";
88
90
  import {
89
91
  SqliteNodeEngine
90
- } from "./chunk-AOTXYFW2.js";
92
+ } from "./chunk-Z7EFXSTO.js";
91
93
  import {
92
94
  SqliteWasmEngine
93
- } from "./chunk-UFSXA5QB.js";
94
- import "./chunk-FPW33LMV.js";
95
+ } from "./chunk-7AXRV7NS.js";
96
+ import "./chunk-HIVVDGE5.js";
95
97
  import "./chunk-3EIBJPNF.js";
96
98
  import {
97
99
  ContentHandle,
@@ -106,21 +108,21 @@ import {
106
108
  import {
107
109
  CardCollection,
108
110
  Maybe
109
- } from "./chunk-Q7EHSN3K.js";
111
+ } from "./chunk-QPVEUPMU.js";
110
112
  import {
111
113
  DEFAULT_CLM_TIMEOUT_MS,
112
114
  DEFAULT_SANDBOX_TIMEOUT_MS
113
- } from "./chunk-J3IDWMDN.js";
115
+ } from "./chunk-3FFEA2XK.js";
114
116
  import {
115
117
  ContentTypeInterpreter,
116
118
  MCard,
117
119
  createPCardDOTSMetadata,
118
120
  createVCardDOTSMetadata
119
- } from "./chunk-2NFGZ6PA.js";
121
+ } from "./chunk-GGQCF7ZK.js";
120
122
  import {
121
123
  GTime,
122
124
  HashValidator
123
- } from "./chunk-7NKII2JA.js";
125
+ } from "./chunk-ASW6AOA7.js";
124
126
  import {
125
127
  __export
126
128
  } from "./chunk-PNKVD2UK.js";
@@ -161,7 +163,7 @@ var ENGINE_INFO = {
161
163
  async function createEngine(type, options = {}) {
162
164
  switch (type) {
163
165
  case "indexeddb" /* INDEXED_DB */: {
164
- const { IndexedDBEngine: IndexedDBEngine2 } = await import("./IndexedDBEngine-SYJHHDQM.js");
166
+ const { IndexedDBEngine: IndexedDBEngine2 } = await import("./IndexedDBEngine-BWXAB46W.js");
165
167
  const engine = new IndexedDBEngine2();
166
168
  await engine.init();
167
169
  return engine;
@@ -410,12 +412,12 @@ var SandboxWorker = class {
410
412
  * Send request and wait for response
411
413
  */
412
414
  sendRequest(request) {
413
- return new Promise((resolve4, reject) => {
415
+ return new Promise((resolve5, reject) => {
414
416
  const timeout = setTimeout(() => {
415
417
  this.pendingRequests.delete(request.id);
416
418
  reject(new Error(`Request ${request.id} timed out`));
417
419
  }, this.defaultTimeout);
418
- this.pendingRequests.set(request.id, { resolve: resolve4, reject, timeout });
420
+ this.pendingRequests.set(request.id, { resolve: resolve5, reject, timeout });
419
421
  this.worker.postMessage(request);
420
422
  });
421
423
  }
@@ -516,67 +518,9 @@ __export(lambda_exports, {
516
518
  termToMCard: () => termToMCard
517
519
  });
518
520
 
519
- // src/ptr/node/clm/utils.ts
520
- function resultsEqual(a, b, tolerance = 1e-9) {
521
- if (a === b) return true;
522
- if (a == null || b == null) return false;
523
- if (typeof a === "number" && typeof b === "number") {
524
- if (Number.isNaN(a) && Number.isNaN(b)) return true;
525
- if (!Number.isFinite(a) || !Number.isFinite(b)) return a === b;
526
- return Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b));
527
- }
528
- if (Array.isArray(a) && Array.isArray(b)) {
529
- if (a.length !== b.length) return false;
530
- return a.every((val, i) => resultsEqual(val, b[i], tolerance));
531
- }
532
- if (typeof a === "object" && typeof b === "object") {
533
- const keysA = Object.keys(a);
534
- const keysB = Object.keys(b);
535
- if (keysA.length !== keysB.length) return false;
536
- return keysA.every(
537
- (key) => keysB.includes(key) && resultsEqual(a[key], b[key], tolerance)
538
- );
539
- }
540
- return a === b;
541
- }
542
- function asObject(input) {
543
- return typeof input === "object" && input !== null ? input : {};
544
- }
545
- function buildBaseContext(clm, input) {
546
- const inputObj = asObject(input);
547
- return {
548
- balanced: clm.clm.balanced,
549
- input_arguments: clm.clm.concrete?.input_arguments,
550
- output_arguments: clm.clm.concrete?.output_arguments,
551
- params: inputObj,
552
- ...inputObj
553
- };
554
- }
555
- function buildExecutionResult(success, result, startTime, clm, error, boundary) {
556
- return {
557
- success,
558
- result,
559
- error,
560
- executionTime: Date.now() - startTime,
561
- clm: {
562
- chapter: clm.chapter?.title || "Unknown",
563
- concept: clm.clm.abstract?.concept || "Unknown",
564
- manifestation: clm.clm.concrete?.manifestation || "Unknown",
565
- boundary
566
- }
567
- };
568
- }
569
- function isRecursiveCLM(runtimeName) {
570
- return runtimeName.endsWith(".clm") || runtimeName.endsWith(".yaml") || runtimeName.endsWith(".yml");
571
- }
572
- function isMultiRuntime(clm) {
573
- const runtimesConfig = clm.clm?.concrete?.runtimes_config;
574
- return Array.isArray(runtimesConfig) && runtimesConfig.length > 0;
575
- }
576
-
577
- // src/ptr/node/clm/runner.ts
578
- import * as path5 from "path";
579
- import * as yaml2 from "yaml";
521
+ // src/ptr/node/PTREngine.ts
522
+ import * as path6 from "path";
523
+ import * as yaml3 from "yaml";
580
524
 
581
525
  // src/model/PCard.ts
582
526
  import { parse } from "yaml";
@@ -771,8 +715,8 @@ var PCard = class _PCard extends MCard {
771
715
  }
772
716
  }
773
717
  };
774
- const { stringify: stringify2 } = await import("yaml");
775
- return _PCard.create(stringify2(newClm), this.hashFunction);
718
+ const { stringify: stringify3 } = await import("yaml");
719
+ return _PCard.create(stringify3(newClm), this.hashFunction);
776
720
  }
777
721
  /**
778
722
  * Tensor Product ($A \otimes B$)
@@ -799,8 +743,8 @@ var PCard = class _PCard extends MCard {
799
743
  }
800
744
  }
801
745
  };
802
- const { stringify: stringify2 } = await import("yaml");
803
- return _PCard.create(stringify2(newClm), this.hashFunction);
746
+ const { stringify: stringify3 } = await import("yaml");
747
+ return _PCard.create(stringify3(newClm), this.hashFunction);
804
748
  }
805
749
  /**
806
750
  * Symmetry ($\sigma$)
@@ -826,8 +770,8 @@ var PCard = class _PCard extends MCard {
826
770
  }
827
771
  }
828
772
  };
829
- const { stringify: stringify2 } = await import("yaml");
830
- return _PCard.create(stringify2(newClm), this.hashFunction);
773
+ const { stringify: stringify3 } = await import("yaml");
774
+ return _PCard.create(stringify3(newClm), this.hashFunction);
831
775
  }
832
776
  // =========================================================================
833
777
  // Universal Tooling Interface
@@ -1031,6 +975,70 @@ var PCard = class _PCard extends MCard {
1031
975
  const runtimesConfig = config?.runtimes_config;
1032
976
  return Array.isArray(runtimesConfig) && runtimesConfig.length > 1;
1033
977
  }
978
+ // =========================================================================
979
+ // VCard Sandwich Boundary Spec Accessors
980
+ // =========================================================================
981
+ // Mirrors Python: PCard.get_pre_vcard_spec(), PCard.get_post_vcard_spec()
982
+ // =========================================================================
983
+ /**
984
+ * Get precondition specification for VCard Sandwich evaluation.
985
+ *
986
+ * Extracts the precondition spec from abstract.preconditions,
987
+ * classifying each condition by type.
988
+ *
989
+ * @returns Object with conditions array and classified conditions
990
+ */
991
+ getPreVCardSpec() {
992
+ const abstractSpec = this.abstract;
993
+ const preconditions = abstractSpec?.preconditions || [];
994
+ return {
995
+ conditions: preconditions,
996
+ classified: preconditions.map((c) => this.classifyCondition(c))
997
+ };
998
+ }
999
+ /**
1000
+ * Get postcondition specification for VCard Sandwich evaluation.
1001
+ *
1002
+ * Extracts the postcondition spec from abstract.postconditions,
1003
+ * classifying each condition by type.
1004
+ *
1005
+ * @returns Object with conditions array and classified conditions
1006
+ */
1007
+ getPostVCardSpec() {
1008
+ const abstractSpec = this.abstract;
1009
+ const postconditions = abstractSpec?.postconditions || [];
1010
+ return {
1011
+ conditions: postconditions,
1012
+ classified: postconditions.map((c) => this.classifyCondition(c))
1013
+ };
1014
+ }
1015
+ /**
1016
+ * Classify a condition by its type (function, schema, capability, declarative).
1017
+ *
1018
+ * @param condition - The condition to classify
1019
+ * @returns Object with type and the original condition
1020
+ */
1021
+ classifyCondition(condition) {
1022
+ if (typeof condition === "string") {
1023
+ return { type: "declarative", condition };
1024
+ }
1025
+ if (typeof condition === "object" && condition !== null) {
1026
+ const cond = condition;
1027
+ if (typeof cond.function === "string" || typeof cond.callable === "string") {
1028
+ return { type: "function", condition };
1029
+ }
1030
+ if (cond.schema || cond.json_schema) {
1031
+ return { type: "schema", condition };
1032
+ }
1033
+ if (typeof cond.capability === "string") {
1034
+ return { type: "capability", condition };
1035
+ }
1036
+ if (cond.description) {
1037
+ return { type: "declarative", condition };
1038
+ }
1039
+ }
1040
+ return { type: "unknown", condition };
1041
+ }
1034
1042
  };
1035
1043
 
1036
1044
  // src/model/VCard.ts
@@ -1421,6 +1429,127 @@ var VCard = class _VCard extends MCard {
1421
1429
  const myHandle = this.getTokenHandle();
1422
1430
  return myHandle === requiredHandle;
1423
1431
  }
1432
+ // =========================================================================
1433
+ // VCard Sandwich — Arrow Boundary Evaluation Pattern
1434
+ // =========================================================================
1435
+ //
1436
+ // These static methods implement the formal VCard Sandwich lifecycle:
1437
+ // V_pre → PCard(Evaluation Map) → V_post → Sandwich(V_pre, V_post)
1438
+ //
1439
+ // Mirrors Python: VCard.witness_precondition(), witness_postcondition(), sandwich()
1440
+ // =========================================================================
1441
+ /**
1442
+ * Witness Precondition (V_pre) — creates a VCard that witnesses
1443
+ * the input was accepted for evaluation.
1444
+ *
1445
+ * @param inputMCard - The input MCard being evaluated
1446
+ * @param hashAlgorithm - Hash algorithm to use
1447
+ * @returns VCard with type "precondition-witness"
1448
+ */
1449
+ static async witnessPrecondition(inputMCard, hashAlgorithm = "sha256") {
1450
+ const structure = {
1451
+ vcard: {
1452
+ type: "precondition-witness",
1453
+ identity: {
1454
+ subject_did: "did:ptr:system",
1455
+ controller_pubkeys: []
1456
+ },
1457
+ verification: {
1458
+ input_hash: inputMCard.hash,
1459
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1460
+ witness_type: "precondition"
1461
+ },
1462
+ gatekeeper: { capabilities: [] },
1463
+ external_refs: []
1464
+ }
1465
+ };
1466
+ const contentString = JSON.stringify(structure, null, 2);
1467
+ const bytes = new TextEncoder().encode(contentString);
1468
+ const hash = await HashValidator.computeHash(bytes, hashAlgorithm);
1469
+ const g_time = GTime.stampNow(hashAlgorithm);
1470
+ const contentType = ContentTypeInterpreter.detect(bytes);
1471
+ return new _VCard(bytes, hash, g_time, contentType, hashAlgorithm, structure);
1472
+ }
1473
+ /**
1474
+ * Witness Postcondition (V_post) — creates a VCard that witnesses
1475
+ * the output was produced by a PCard evaluation.
1476
+ *
1477
+ * @param output - The execution output
1478
+ * @param pcardHash - Hash of the PCard that produced the output
1479
+ * @param hashAlgorithm - Hash algorithm to use
1480
+ * @returns VCard with type "postcondition-witness"
1481
+ */
1482
+ static async witnessPostcondition(output, pcardHash, hashAlgorithm = "sha256") {
1483
+ let outputRepr;
1484
+ try {
1485
+ outputRepr = typeof output === "string" ? output : JSON.stringify(output);
1486
+ } catch {
1487
+ outputRepr = String(output);
1488
+ }
1489
+ const outputHash = await HashValidator.computeHash(
1490
+ new TextEncoder().encode(outputRepr),
1491
+ hashAlgorithm
1492
+ );
1493
+ const structure = {
1494
+ vcard: {
1495
+ type: "postcondition-witness",
1496
+ identity: {
1497
+ subject_did: "did:ptr:system",
1498
+ controller_pubkeys: []
1499
+ },
1500
+ verification: {
1501
+ output_hash: outputHash,
1502
+ pcard_hash: pcardHash || null,
1503
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1504
+ witness_type: "postcondition"
1505
+ },
1506
+ gatekeeper: { capabilities: [] },
1507
+ external_refs: []
1508
+ }
1509
+ };
1510
+ const contentString = JSON.stringify(structure, null, 2);
1511
+ const bytes = new TextEncoder().encode(contentString);
1512
+ const hash = await HashValidator.computeHash(bytes, hashAlgorithm);
1513
+ const g_time = GTime.stampNow(hashAlgorithm);
1514
+ const contentType = ContentTypeInterpreter.detect(bytes);
1515
+ return new _VCard(bytes, hash, g_time, contentType, hashAlgorithm, structure);
1516
+ }
1517
+ /**
1518
+ * Create a Sandwich Proof — combines V_pre and V_post into a
1519
+ * composite verification proof.
1520
+ *
1521
+ * @param vPre - Precondition witness VCard
1522
+ * @param vPost - Postcondition witness VCard
1523
+ * @param pcardHash - Hash of the PCard that was evaluated
1524
+ * @param hashAlgorithm - Hash algorithm to use
1525
+ * @returns VCard with type "verification-sandwich"
1526
+ */
1527
+ static async sandwich(vPre, vPost, pcardHash, hashAlgorithm = "sha256") {
1528
+ const structure = {
1529
+ vcard: {
1530
+ type: "verification-sandwich",
1531
+ identity: {
1532
+ subject_did: "did:ptr:system",
1533
+ controller_pubkeys: []
1534
+ },
1535
+ verification: {
1536
+ v_pre_hash: vPre.hash,
1537
+ v_post_hash: vPost.hash,
1538
+ pcard_hash: pcardHash || null,
1539
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1540
+ witness_type: "sandwich"
1541
+ },
1542
+ gatekeeper: { capabilities: [] },
1543
+ external_refs: []
1544
+ }
1545
+ };
1546
+ const contentString = JSON.stringify(structure, null, 2);
1547
+ const bytes = new TextEncoder().encode(contentString);
1548
+ const hash = await HashValidator.computeHash(bytes, hashAlgorithm);
1549
+ const g_time = GTime.stampNow(hashAlgorithm);
1550
+ const contentType = ContentTypeInterpreter.detect(bytes);
1551
+ return new _VCard(bytes, hash, g_time, contentType, hashAlgorithm, structure);
1552
+ }
1424
1553
  };
1425
1554
  var VCardSimulation = class {
1426
1555
  vcard;
@@ -1442,6 +1571,68 @@ var VCardSimulation = class {
1442
1571
  }
1443
1572
  };
1444
1573
 
1574
+ // src/ptr/node/clm/runner.ts
1575
+ import * as path5 from "path";
1576
+ import * as yaml2 from "yaml";
1577
+
1578
+ // src/ptr/node/clm/utils.ts
1579
+ function resultsEqual(a, b, tolerance = 1e-9) {
1580
+ if (a === b) return true;
1581
+ if (a == null || b == null) return false;
1582
+ if (typeof a === "number" && typeof b === "number") {
1583
+ if (Number.isNaN(a) && Number.isNaN(b)) return true;
1584
+ if (!Number.isFinite(a) || !Number.isFinite(b)) return a === b;
1585
+ return Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b));
1586
+ }
1587
+ if (Array.isArray(a) && Array.isArray(b)) {
1588
+ if (a.length !== b.length) return false;
1589
+ return a.every((val, i) => resultsEqual(val, b[i], tolerance));
1590
+ }
1591
+ if (typeof a === "object" && typeof b === "object") {
1592
+ const keysA = Object.keys(a);
1593
+ const keysB = Object.keys(b);
1594
+ if (keysA.length !== keysB.length) return false;
1595
+ return keysA.every(
1596
+ (key) => keysB.includes(key) && resultsEqual(a[key], b[key], tolerance)
1597
+ );
1598
+ }
1599
+ return a === b;
1600
+ }
1601
+ function asObject(input) {
1602
+ return typeof input === "object" && input !== null ? input : {};
1603
+ }
1604
+ function buildBaseContext(clm, input) {
1605
+ const inputObj = asObject(input);
1606
+ return {
1607
+ balanced: clm.clm.balanced,
1608
+ input_arguments: clm.clm.concrete?.input_arguments,
1609
+ output_arguments: clm.clm.concrete?.output_arguments,
1610
+ params: inputObj,
1611
+ ...inputObj
1612
+ };
1613
+ }
1614
+ function buildExecutionResult(success, result, startTime, clm, error, boundary) {
1615
+ return {
1616
+ success,
1617
+ result,
1618
+ error,
1619
+ executionTime: Date.now() - startTime,
1620
+ clm: {
1621
+ chapter: clm.chapter?.title || "Unknown",
1622
+ concept: clm.clm.abstract?.concept || "Unknown",
1623
+ manifestation: clm.clm.concrete?.manifestation || "Unknown",
1624
+ boundary
1625
+ }
1626
+ };
1627
+ }
1628
+ function isRecursiveCLM(runtimeName) {
1629
+ return runtimeName.endsWith(".clm") || runtimeName.endsWith(".yaml") || runtimeName.endsWith(".yml");
1630
+ }
1631
+ function isMultiRuntime(clm) {
1632
+ const runtimesConfig = clm.clm?.concrete?.runtimes_config;
1633
+ return Array.isArray(runtimesConfig) && runtimesConfig.length > 0;
1634
+ }
1635
+
1445
1636
  // src/ptr/node/core/operations/index.ts
1446
1637
  var NETWORK_BUILTINS = /* @__PURE__ */ new Set([
1447
1638
  "http_get",
@@ -1557,8 +1748,8 @@ async function runVersionExamples(examples) {
1557
1748
  }
1558
1749
  async function executeVersionSingle(handle, versions) {
1559
1750
  const { SqliteNodeEngine: SqliteNodeEngine2 } = await import("./storage/SqliteNodeEngine.js");
1560
- const { CardCollection: CardCollection2 } = await import("./CardCollection-QY5VDVEL.js");
1561
- const { MCard: MCard2 } = await import("./MCard-XHG3BZC7.js");
1751
+ const { CardCollection: CardCollection2 } = await import("./CardCollection-ZQ3G3Q3A.js");
1752
+ const { MCard: MCard2 } = await import("./MCard-RHTWJPHJ.js");
1562
1753
  const engine = await SqliteNodeEngine2.create(":memory:");
1563
1754
  const collection = new CardCollection2(engine);
1564
1755
  try {
@@ -1618,8 +1809,8 @@ async function runPruneExamples(examples) {
1618
1809
  }
1619
1810
  async function executePruneSingle(handle, versions, pruneType, olderThanSeconds) {
1620
1811
  const { SqliteNodeEngine: SqliteNodeEngine2 } = await import("./storage/SqliteNodeEngine.js");
1621
- const { CardCollection: CardCollection2 } = await import("./CardCollection-QY5VDVEL.js");
1622
- const { MCard: MCard2 } = await import("./MCard-XHG3BZC7.js");
1812
+ const { CardCollection: CardCollection2 } = await import("./CardCollection-ZQ3G3Q3A.js");
1813
+ const { MCard: MCard2 } = await import("./MCard-RHTWJPHJ.js");
1623
1814
  const engine = await SqliteNodeEngine2.create(":memory:");
1624
1815
  const collection = new CardCollection2(engine);
1625
1816
  try {
@@ -1788,7 +1979,7 @@ setInterval(() => {}, 1000);
1788
1979
  });
1789
1980
  child.unref();
1790
1981
  fs.writeFileSync(pidFile, String(child.pid));
1791
- await new Promise((resolve4) => setTimeout(resolve4, STATIC_SERVER_START_WAIT_MS));
1982
+ await new Promise((resolve5) => setTimeout(resolve5, STATIC_SERVER_START_WAIT_MS));
1792
1983
  if (isPortInUse(port)) {
1793
1984
  return {
1794
1985
  success: true,
@@ -1841,10 +2032,10 @@ setInterval(() => {}, 1000);
1841
2032
  }
1842
2033
  try {
1843
2034
  process.kill(pid, "SIGTERM");
1844
- await new Promise((resolve4) => setTimeout(resolve4, PROCESS_TERMINATE_WAIT_MS));
2035
+ await new Promise((resolve5) => setTimeout(resolve5, PROCESS_TERMINATE_WAIT_MS));
1845
2036
  if (isPortInUse(port)) {
1846
2037
  process.kill(pid, "SIGKILL");
1847
- await new Promise((resolve4) => setTimeout(resolve4, PROCESS_TERMINATE_WAIT_MS));
2038
+ await new Promise((resolve5) => setTimeout(resolve5, PROCESS_TERMINATE_WAIT_MS));
1848
2039
  }
1849
2040
  if (fs.existsSync(pidFile)) {
1850
2041
  fs.unlinkSync(pidFile);
@@ -1986,7 +2177,7 @@ Process exited with code ${code}
1986
2177
  } catch {
1987
2178
  }
1988
2179
  fs2.writeFileSync(pidFile, String(child.pid));
1989
- await new Promise((resolve4) => setTimeout(resolve4, WEBSOCKET_SERVER_START_WAIT_MS));
2180
+ await new Promise((resolve5) => setTimeout(resolve5, WEBSOCKET_SERVER_START_WAIT_MS));
1990
2181
  if (isPortInUse2(port)) {
1991
2182
  console.log(`[WebSocket Server] Successfully started on port ${port}`);
1992
2183
  return {
@@ -2050,10 +2241,10 @@ Process exited with code ${code}
2050
2241
  }
2051
2242
  try {
2052
2243
  process.kill(pid, "SIGTERM");
2053
- await new Promise((resolve4) => setTimeout(resolve4, PROCESS_TERMINATE_WAIT_MS));
2244
+ await new Promise((resolve5) => setTimeout(resolve5, PROCESS_TERMINATE_WAIT_MS));
2054
2245
  if (isPortInUse2(port)) {
2055
2246
  process.kill(pid, "SIGKILL");
2056
- await new Promise((resolve4) => setTimeout(resolve4, PROCESS_TERMINATE_WAIT_MS));
2247
+ await new Promise((resolve5) => setTimeout(resolve5, PROCESS_TERMINATE_WAIT_MS));
2057
2248
  }
2058
2249
  if (fs2.existsSync(pidFile)) {
2059
2250
  fs2.unlinkSync(pidFile);
@@ -2382,10 +2573,12 @@ var CLMRunner = class _CLMRunner {
2382
2573
  loader;
2383
2574
  timeout;
2384
2575
  collection;
2385
- constructor(basePath = process.cwd(), timeout = DEFAULT_CLM_TIMEOUT_MS, collection) {
2576
+ privateCollection;
2577
+ constructor(basePath = process.cwd(), timeout = DEFAULT_CLM_TIMEOUT_MS, collection, privateCollection) {
2386
2578
  this.loader = new CLMLoader(basePath);
2387
2579
  this.timeout = timeout;
2388
2580
  this.collection = collection;
2581
+ this.privateCollection = privateCollection;
2389
2582
  }
2390
2583
  /**
2391
2584
  * Run a CLM directly from a file path.
@@ -2496,7 +2689,8 @@ var CLMRunner = class _CLMRunner {
2496
2689
  previousVCard,
2497
2690
  result.success
2498
2691
  );
2499
- await this.collection.add(vcard);
2692
+ const storageTarget = this.privateCollection || this.collection;
2693
+ await storageTarget.add(vcard);
2500
2694
  result.petriNet = {
2501
2695
  pcardHash: pcard.hash,
2502
2696
  vcardHash: vcard.hash,
@@ -2771,6 +2965,250 @@ var CLMRunner = class _CLMRunner {
2771
2965
  };
2772
2966
  }
2773
2967
  };
2968
+
2969
+ // src/ptr/node/PTREngine.ts
2970
+ var PTREngine = class {
2971
+ collection;
2972
+ executionLog;
2973
+ runner;
2974
+ /**
2975
+ * Initialize PTREngine.
2976
+ *
2977
+ * @param storageCollection - MCard collection for long-term knowledge (mcard_collection.db)
2978
+ * @param executionLogCollection - MCard collection for execution traces (execution_log.db).
2979
+ * If not provided, traces are written to storageCollection.
2980
+ * @param options - Additional configuration
2981
+ */
2982
+ constructor(storageCollection, executionLogCollection, options) {
2983
+ this.collection = storageCollection;
2984
+ this.executionLog = executionLogCollection || this.collection;
2985
+ this.runner = new CLMRunner(
2986
+ options?.basePath || process.cwd(),
2987
+ options?.timeout,
2988
+ this.collection,
2989
+ this.executionLog
2990
+ );
2991
+ }
2992
+ // =========================================================================
2993
+ // ARROW INTERFACE — The canonical PTR execution primitives
2994
+ // =========================================================================
2995
+ /**
2996
+ * The Arrow execution primitive — the entire PTR in one method.
2997
+ *
2998
+ * Implements the VCard Sandwich lifecycle:
2999
+ * V_pre → PCard(Evaluation Map) → V_post
3000
+ *
3001
+ * @param pcardHash - Hash of the PCard to execute
3002
+ * @param inputHash - Hash of the input MCard
3003
+ * @param preCheck - Optional callable to validate preconditions on input
3004
+ * @param postCheck - Optional callable to validate postconditions on output
3005
+ * @returns Tuple of [execution_output, vcard_sandwich]
3006
+ * @throws PreconditionViolation if preCheck returns false
3007
+ * @throws PostconditionViolation if postCheck returns false
3008
+ */
3009
+ async runWithSandwich(pcardHash, inputHash, preCheck, postCheck) {
3010
+ const pcard = await this.collection.get(pcardHash);
3011
+ if (!pcard) throw new Error(`PCard not found: ${pcardHash}`);
3012
+ const inputMCard = await this.collection.get(inputHash);
3013
+ if (!inputMCard) throw new Error(`Input MCard not found: ${inputHash}`);
3014
+ if (preCheck && !preCheck(inputMCard)) {
3015
+ throw new PreconditionViolation(pcardHash, inputHash);
3016
+ }
3017
+ const vPre = await VCard.witnessPrecondition(inputMCard);
3018
+ const pcardObj = await PCard.create(
3019
+ new TextDecoder().decode(pcard.content)
3020
+ );
3021
+ const clmSpec = {
3022
+ chapter: { id: "runtime", title: "Runtime Execution" },
3023
+ clm: pcardObj.clm
3024
+ };
3025
+ const result = await this.runner.executeCLM(
3026
+ clmSpec,
3027
+ process.cwd(),
3028
+ inputMCard.getContentAsText()
3029
+ );
3030
+ const output = result.result;
3031
+ if (postCheck && !postCheck(output)) {
3032
+ throw new PostconditionViolation(
3033
+ pcardHash,
3034
+ typeof output === "string" ? output.substring(0, 64) : JSON.stringify(output).substring(0, 64)
3035
+ );
3036
+ }
3037
+ const vPost = await VCard.witnessPostcondition(output, pcardHash);
3038
+ const sandwich = await VCard.sandwich(vPre, vPost, pcardHash);
3039
+ await this.recordToExecutionLog(sandwich);
3040
+ return [output, sandwich];
3041
+ }
3042
+ /**
3043
+ * Execute a CLM specification from a YAML file.
3044
+ *
3045
+ * Absorbs CLMRunner.runFile(), routing all file-based execution
3046
+ * through the formal PTREngine lifecycle with VCard Sandwich generation.
3047
+ *
3048
+ * @param filePath - Path to the YAML file
3049
+ * @param context - Execution context (inputs)
3050
+ * @returns Execution report with VCard Sandwich proof hashes
3051
+ */
3052
+ async runFile(filePath, context) {
3053
+ const loader = new CLMLoader(path6.dirname(filePath));
3054
+ const clm = loader.load(filePath);
3055
+ const chapterDir = path6.dirname(path6.resolve(filePath));
3056
+ const clmContent = yaml3.stringify(clm);
3057
+ const pcard = await PCard.create(clmContent);
3058
+ if (this.collection) {
3059
+ await this.collection.add(pcard);
3060
+ }
3061
+ const inputMCard = await MCard.create(JSON.stringify(context || {}));
3062
+ const vPre = await VCard.witnessPrecondition(inputMCard);
3063
+ const result = await this.runner.executeCLM(clm, chapterDir, context || {});
3064
+ const vPost = await VCard.witnessPostcondition(result.result, pcard.hash);
3065
+ const sandwich = await VCard.sandwich(vPre, vPost, pcard.hash);
3066
+ let eventRecordHash = null;
3067
+ try {
3068
+ if (this.executionLog) {
3069
+ await this.executionLog.add(sandwich);
3070
+ eventRecordHash = sandwich.hash;
3071
+ }
3072
+ } catch (e) {
3073
+ console.warn(`[PTREngine] Failed to store VCard Sandwich: ${e}`);
3074
+ }
3075
+ return {
3076
+ status: result.success ? "success" : "failure",
3077
+ result: result.result,
3078
+ error: result.error,
3079
+ chapter_id: clm.chapter?.id,
3080
+ chapter_title: clm.chapter?.title,
3081
+ event_record_hash: eventRecordHash,
3082
+ v_pre_hash: vPre.hash,
3083
+ v_post_hash: vPost.hash,
3084
+ sandwich_hash: sandwich.hash
3085
+ };
3086
+ }
3087
+ /**
3088
+ * Arrow `arr` — lift a pure function into a PCard.
3089
+ *
3090
+ * Creates a PCard whose Concrete implementation is the given function.
3091
+ *
3092
+ * @param func - A pure function from string to string
3093
+ * @param name - Human-readable name for the PCard
3094
+ * @returns The created PCard (stored in collection)
3095
+ */
3096
+ async arr(func, name = "lifted") {
3097
+ const funcSource = func.toString();
3098
+ const clmYaml = yaml3.stringify({
3099
+ chapter: { id: `arr_${name}`, title: `Lifted: ${name}` },
3100
+ clm: {
3101
+ abstract: {
3102
+ purpose: `Lifted pure function: ${name}`,
3103
+ inputs: { input: "any" },
3104
+ outputs: { result: "any" },
3105
+ preconditions: [],
3106
+ postconditions: []
3107
+ },
3108
+ concrete: {
3109
+ runtime: "javascript",
3110
+ operation: `lifted_${name}`,
3111
+ code: funcSource
3112
+ },
3113
+ balanced: { test_cases: [], expectations: {} }
3114
+ }
3115
+ });
3116
+ const pcard = await PCard.create(clmYaml);
3117
+ if (this.collection) {
3118
+ await this.collection.add(pcard);
3119
+ }
3120
+ return pcard;
3121
+ }
3122
+ /**
3123
+ * Arrow `>>>` — sequential composition of two PCards.
3124
+ *
3125
+ * Creates a new PCard representing pcardA >>> pcardB,
3126
+ * where the output of A feeds into the input of B.
3127
+ *
3128
+ * @param pcardAHash - Hash of the first PCard (executed first)
3129
+ * @param pcardBHash - Hash of the second PCard (executed second)
3130
+ * @returns The composed PCard (stored in collection)
3131
+ */
3132
+ async compose(pcardAHash, pcardBHash) {
3133
+ const clmYaml = yaml3.stringify({
3134
+ chapter: {
3135
+ id: `compose_${pcardAHash.substring(0, 8)}_${pcardBHash.substring(0, 8)}`,
3136
+ title: "Sequential Composition (Arrow >>>)"
3137
+ },
3138
+ clm: {
3139
+ abstract: {
3140
+ type: "sequential_composition",
3141
+ purpose: `Compose ${pcardAHash.substring(0, 16)} >>> ${pcardBHash.substring(0, 16)}`,
3142
+ inputs: { input: "any" },
3143
+ outputs: { result: "any" },
3144
+ preconditions: [],
3145
+ postconditions: []
3146
+ },
3147
+ concrete: {
3148
+ runtime: "ptr",
3149
+ operation: "compose_sequential",
3150
+ steps: [pcardAHash, pcardBHash]
3151
+ },
3152
+ balanced: { test_cases: [], expectations: {} }
3153
+ }
3154
+ });
3155
+ const pcard = await PCard.create(clmYaml);
3156
+ if (this.collection) {
3157
+ await this.collection.add(pcard);
3158
+ }
3159
+ return pcard;
3160
+ }
3161
+ /**
3162
+ * Arrow `first` — operate on first element of a product.
3163
+ *
3164
+ * Creates a new PCard that applies the original PCard to the
3165
+ * first element of a (A, C) pair while preserving C.
3166
+ *
3167
+ * @param pcardHash - Hash of the PCard to lift
3168
+ * @returns The first-lifted PCard (stored in collection)
3169
+ */
3170
+ async first(pcardHash) {
3171
+ const clmYaml = yaml3.stringify({
3172
+ chapter: {
3173
+ id: `first_${pcardHash.substring(0, 8)}`,
3174
+ title: "Arrow First (Product Preservation)"
3175
+ },
3176
+ clm: {
3177
+ abstract: {
3178
+ type: "arrow_first",
3179
+ purpose: `Apply ${pcardHash.substring(0, 16)} to first element, preserve second`,
3180
+ inputs: { pair: "(A, C)" },
3181
+ outputs: { result: "(B, C)" },
3182
+ preconditions: [],
3183
+ postconditions: []
3184
+ },
3185
+ concrete: {
3186
+ runtime: "ptr",
3187
+ operation: "apply_first",
3188
+ target: pcardHash
3189
+ },
3190
+ balanced: { test_cases: [], expectations: {} }
3191
+ }
3192
+ });
3193
+ const pcard = await PCard.create(clmYaml);
3194
+ if (this.collection) {
3195
+ await this.collection.add(pcard);
3196
+ }
3197
+ return pcard;
3198
+ }
3199
+ // =========================================================================
3200
+ // Private Helpers
3201
+ // =========================================================================
3202
+ async recordToExecutionLog(sandwich) {
3203
+ try {
3204
+ if (this.executionLog) {
3205
+ await this.executionLog.add(sandwich);
3206
+ }
3207
+ } catch (e) {
3208
+ console.warn(`[PTREngine] Failed to record to execution log: ${e}`);
3209
+ }
3210
+ }
3211
+ };
2774
3212
  export {
2775
3213
  ALGORITHM_HIERARCHY,
2776
3214
  CLMRunner,
@@ -2798,6 +3236,9 @@ export {
2798
3236
  MCard,
2799
3237
  MCardStore,
2800
3238
  Maybe,
3239
+ PTREngine,
3240
+ PostconditionViolation,
3241
+ PreconditionViolation,
2801
3242
  Reader,
2802
3243
  SandboxWorker,
2803
3244
  ServiceWorkerPTR,