mcard-js 2.1.48 → 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 (37) hide show
  1. package/dist/AbstractSqlEngine-DKka6XjT.d.cts +451 -0
  2. package/dist/AbstractSqlEngine-DKka6XjT.d.ts +451 -0
  3. package/dist/CardCollection-ZQ3G3Q3A.js +10 -0
  4. package/dist/IndexedDBEngine-BWXAB46W.js +12 -0
  5. package/dist/LLMRuntime-PH3MOQ2Y.js +17 -0
  6. package/dist/LambdaRuntime-YH74FHIW.js +19 -0
  7. package/dist/Loader-WZXYG4GE.js +12 -0
  8. package/dist/NetworkRuntime-S4DZCGVN.js +1598 -0
  9. package/dist/OllamaProvider-SPGO5Z5E.js +9 -0
  10. package/dist/chunk-3FFEA2XK.js +149 -0
  11. package/dist/chunk-7AXRV7NS.js +112 -0
  12. package/dist/chunk-HIVVDGE5.js +497 -0
  13. package/dist/chunk-KVZYFZJ5.js +427 -0
  14. package/dist/chunk-NGTY4P6A.js +275 -0
  15. package/dist/chunk-OUW2SUGM.js +368 -0
  16. package/dist/chunk-QKH3N62B.js +2360 -0
  17. package/dist/chunk-QPVEUPMU.js +299 -0
  18. package/dist/chunk-VYDZR4ZD.js +364 -0
  19. package/dist/chunk-XJZOEM5F.js +903 -0
  20. package/dist/chunk-Z7EFXSTO.js +217 -0
  21. package/dist/index.browser.cjs +37 -1
  22. package/dist/index.browser.d.cts +20 -2
  23. package/dist/index.browser.d.ts +20 -2
  24. package/dist/index.browser.js +10 -6
  25. package/dist/index.cjs +618 -146
  26. package/dist/index.d.cts +723 -4
  27. package/dist/index.d.ts +723 -4
  28. package/dist/index.js +527 -89
  29. package/dist/storage/SqliteNodeEngine.cjs +7 -1
  30. package/dist/storage/SqliteNodeEngine.d.cts +1 -1
  31. package/dist/storage/SqliteNodeEngine.d.ts +1 -1
  32. package/dist/storage/SqliteNodeEngine.js +3 -3
  33. package/dist/storage/SqliteWasmEngine.cjs +7 -1
  34. package/dist/storage/SqliteWasmEngine.d.cts +1 -1
  35. package/dist/storage/SqliteWasmEngine.d.ts +1 -1
  36. package/dist/storage/SqliteWasmEngine.js +3 -3
  37. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -455,6 +455,8 @@ var init_app_config = __esm({
455
455
  default_ws_host: "127.0.0.1",
456
456
  default_ws_port: 5321,
457
457
  default_api_port: 5320,
458
+ default_python_api_port: 28302,
459
+ default_js_api_port: 28303,
458
460
  default_server_host: "0.0.0.0",
459
461
  cors_origins: [
460
462
  "http://localhost:3000",
@@ -484,7 +486,8 @@ var init_app_config = __esm({
484
486
  default_server_memory_db: "servermemory.db",
485
487
  default_mcard_db: "mcard.db",
486
488
  default_server_log_db: "server_log.db",
487
- default_push_subscriptions_file: "subscriptions.json"
489
+ default_push_subscriptions_file: "subscriptions.json",
490
+ default_vcard_db_path: "data/vcard.db"
488
491
  },
489
492
  services: {
490
493
  default_ollama_base_url: "http://localhost:11434",
@@ -524,7 +527,7 @@ var init_app_config = __esm({
524
527
  });
525
528
 
526
529
  // src/config/constants.ts
527
- var network, identity, services, web, DEFAULT_PAGE_SIZE, MAX_FILE_SIZE, READ_TIMEOUT_MS, KNOWN_TYPE_SIZE_LIMIT, BINARY_CHECK_SAMPLE_SIZE, CONTENT_DETECTION_SAMPLE_SIZE, DEFAULT_MAX_PROBLEM_BYTES, INDEXEDDB_DEFAULT_DB_NAME, INDEXEDDB_DEFAULT_DB_VERSION, SQLITE_BUSY_TIMEOUT_MS, DEFAULT_IDENTITY_PROVIDER, DEFAULT_IDENTITY_SPACE_PATH, DEFAULT_API_PORT, DEFAULT_WS_PORT, DEFAULT_WS_HOST, DEFAULT_SERVER_HOST, CORS_ORIGINS, getEnvUrl, API_KEY_HEADER_NAME, DEFAULT_OLLAMA_BASE_URL, DEFAULT_OTLP_ENDPOINT, DEFAULT_VLLM_BASE_URL, DEFAULT_LMSTUDIO_BASE_URL, DEFAULT_SQLJS_WASM_URL, DEFAULT_SANDBOX_TIMEOUT_MS, DEFAULT_CLM_TIMEOUT_MS, DEFAULT_VM_EXECUTION_TIMEOUT_MS, LLM_DEFAULT_TIMEOUT_SECS, LLM_DEFAULT_RETRY_COUNT, LLM_DEFAULT_RETRY_DELAY_SECS;
530
+ var network, identity, services, web, DEFAULT_PAGE_SIZE, MAX_FILE_SIZE, READ_TIMEOUT_MS, KNOWN_TYPE_SIZE_LIMIT, BINARY_CHECK_SAMPLE_SIZE, CONTENT_DETECTION_SAMPLE_SIZE, DEFAULT_MAX_PROBLEM_BYTES, INDEXEDDB_DEFAULT_DB_NAME, INDEXEDDB_DEFAULT_DB_VERSION, SQLITE_BUSY_TIMEOUT_MS, DEFAULT_IDENTITY_PROVIDER, DEFAULT_IDENTITY_SPACE_PATH, DEFAULT_API_PORT, DEFAULT_PYTHON_API_PORT, DEFAULT_JS_API_PORT, DEFAULT_VCARD_DB_PATH, DEFAULT_WS_PORT, DEFAULT_WS_HOST, DEFAULT_SERVER_HOST, CORS_ORIGINS, getEnvUrl, API_KEY_HEADER_NAME, DEFAULT_OLLAMA_BASE_URL, DEFAULT_OTLP_ENDPOINT, DEFAULT_VLLM_BASE_URL, DEFAULT_LMSTUDIO_BASE_URL, DEFAULT_SQLJS_WASM_URL, DEFAULT_SANDBOX_TIMEOUT_MS, DEFAULT_CLM_TIMEOUT_MS, DEFAULT_VM_EXECUTION_TIMEOUT_MS, LLM_DEFAULT_TIMEOUT_SECS, LLM_DEFAULT_RETRY_COUNT, LLM_DEFAULT_RETRY_DELAY_SECS;
528
531
  var init_constants = __esm({
529
532
  "src/config/constants.ts"() {
530
533
  "use strict";
@@ -546,6 +549,9 @@ var init_constants = __esm({
546
549
  DEFAULT_IDENTITY_PROVIDER = String(identity.provider ?? "sqlite");
547
550
  DEFAULT_IDENTITY_SPACE_PATH = String(identity.space_path ?? "./data/IDENTITY_SPACE.db");
548
551
  DEFAULT_API_PORT = Number(network.default_api_port ?? 5320);
552
+ DEFAULT_PYTHON_API_PORT = Number(network.default_python_api_port ?? 28302);
553
+ DEFAULT_JS_API_PORT = Number(network.default_js_api_port ?? 28303);
554
+ DEFAULT_VCARD_DB_PATH = String(app_config_default.storage?.default_vcard_db_path ?? "./data/vcard.db");
549
555
  DEFAULT_WS_PORT = Number(network.default_ws_port ?? 5321);
550
556
  DEFAULT_WS_HOST = String(network.default_ws_host ?? "127.0.0.1");
551
557
  DEFAULT_SERVER_HOST = String(network.default_server_host ?? "0.0.0.0");
@@ -2855,7 +2861,7 @@ var init_OllamaProvider = __esm({
2855
2861
  },
2856
2862
  timeout: this.timeout
2857
2863
  };
2858
- return new Promise((resolve10) => {
2864
+ return new Promise((resolve11) => {
2859
2865
  let payload;
2860
2866
  if (data) {
2861
2867
  payload = JSON.stringify(data);
@@ -2870,33 +2876,33 @@ var init_OllamaProvider = __esm({
2870
2876
  if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
2871
2877
  try {
2872
2878
  if (body.includes("\n") && !body.trim().startsWith("{")) {
2873
- resolve10(Either.right(JSON.parse(body)));
2879
+ resolve11(Either.right(JSON.parse(body)));
2874
2880
  } else {
2875
- resolve10(Either.right(JSON.parse(body)));
2881
+ resolve11(Either.right(JSON.parse(body)));
2876
2882
  }
2877
2883
  } catch (e) {
2878
2884
  const lines = body.trim().split("\n").filter((l) => l);
2879
2885
  if (lines.length > 0) {
2880
2886
  try {
2881
- resolve10(Either.right(JSON.parse(lines[lines.length - 1])));
2887
+ resolve11(Either.right(JSON.parse(lines[lines.length - 1])));
2882
2888
  } catch (parseErr) {
2883
- resolve10(Either.left(`Ollama response parse error: ${parseErr}`));
2889
+ resolve11(Either.left(`Ollama response parse error: ${parseErr}`));
2884
2890
  }
2885
2891
  } else {
2886
- resolve10(Either.left(`Ollama response parse error: ${e}`));
2892
+ resolve11(Either.left(`Ollama response parse error: ${e}`));
2887
2893
  }
2888
2894
  }
2889
2895
  } else {
2890
- resolve10(Either.left(`Ollama HTTP error ${res.statusCode}: ${body}`));
2896
+ resolve11(Either.left(`Ollama HTTP error ${res.statusCode}: ${body}`));
2891
2897
  }
2892
2898
  });
2893
2899
  });
2894
2900
  req.on("error", (e) => {
2895
- resolve10(Either.left(`Ollama connection error: ${e.message}`));
2901
+ resolve11(Either.left(`Ollama connection error: ${e.message}`));
2896
2902
  });
2897
2903
  req.on("timeout", () => {
2898
2904
  req.destroy();
2899
- resolve10(Either.left(`Ollama request timed out after ${this.timeout}ms`));
2905
+ resolve11(Either.left(`Ollama request timed out after ${this.timeout}ms`));
2900
2906
  });
2901
2907
  if (payload) {
2902
2908
  req.write(payload);
@@ -3168,26 +3174,26 @@ var init_MLCLLMProvider = __esm({
3168
3174
  headers: options.headers || {},
3169
3175
  timeout: this.timeout
3170
3176
  };
3171
- return new Promise((resolve10) => {
3177
+ return new Promise((resolve11) => {
3172
3178
  const req = client.request(url, reqOptions, (res) => {
3173
3179
  let body = "";
3174
3180
  res.on("data", (chunk) => body += chunk);
3175
3181
  res.on("end", () => {
3176
3182
  if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
3177
3183
  try {
3178
- resolve10(Either.right(JSON.parse(body)));
3184
+ resolve11(Either.right(JSON.parse(body)));
3179
3185
  } catch (e) {
3180
- resolve10(Either.left(`Parse error: ${e}`));
3186
+ resolve11(Either.left(`Parse error: ${e}`));
3181
3187
  }
3182
3188
  } else {
3183
- resolve10(Either.left(`HTTP Error ${res.statusCode}: ${body}`));
3189
+ resolve11(Either.left(`HTTP Error ${res.statusCode}: ${body}`));
3184
3190
  }
3185
3191
  });
3186
3192
  });
3187
- req.on("error", (e) => resolve10(Either.left(e.message)));
3193
+ req.on("error", (e) => resolve11(Either.left(e.message)));
3188
3194
  req.on("timeout", () => {
3189
3195
  req.destroy();
3190
- resolve10(Either.left("Request timed out"));
3196
+ resolve11(Either.left("Request timed out"));
3191
3197
  });
3192
3198
  if (options.body) {
3193
3199
  req.write(options.body);
@@ -4092,7 +4098,7 @@ function normalize(collection, termHash, strategy = "normal", maxSteps = 1e3, ma
4092
4098
  const startTime = Date.now();
4093
4099
  let current = termHash;
4094
4100
  let steps = 0;
4095
- const path15 = [termHash];
4101
+ const path16 = [termHash];
4096
4102
  while (steps < maxSteps) {
4097
4103
  if (maxTimeMs !== void 0 && Date.now() - startTime > maxTimeMs) {
4098
4104
  return Either.left(
@@ -4104,11 +4110,11 @@ function normalize(collection, termHash, strategy = "normal", maxSteps = 1e3, ma
4104
4110
  return Either.right({
4105
4111
  normalForm: current,
4106
4112
  steps,
4107
- reductionPath: path15
4113
+ reductionPath: path16
4108
4114
  });
4109
4115
  }
4110
4116
  current = stepResult.value;
4111
- path15.push(current);
4117
+ path16.push(current);
4112
4118
  steps++;
4113
4119
  if (onStep) {
4114
4120
  await onStep(steps, current);
@@ -4690,7 +4696,7 @@ var init_wasm = __esm({
4690
4696
  async execute(wasmPath, context, config, chapterDir) {
4691
4697
  const fullPath = path7.resolve(chapterDir, wasmPath);
4692
4698
  const contextStr = typeof context === "string" ? context : JSON.stringify(context ?? {});
4693
- return new Promise((resolve10, reject) => {
4699
+ return new Promise((resolve11, reject) => {
4694
4700
  const proc = child_process3.spawn("wasmtime", [fullPath, contextStr]);
4695
4701
  proc.stdin.end();
4696
4702
  let stdout = "";
@@ -4713,16 +4719,16 @@ var init_wasm = __esm({
4713
4719
  }
4714
4720
  const out = stdout.trim();
4715
4721
  if (!out) {
4716
- return resolve10(void 0);
4722
+ return resolve11(void 0);
4717
4723
  }
4718
4724
  const numeric = out.trim();
4719
4725
  if (numeric && !Number.isNaN(Number(numeric))) {
4720
- return resolve10(Number(numeric));
4726
+ return resolve11(Number(numeric));
4721
4727
  }
4722
4728
  try {
4723
- return resolve10(JSON.parse(out));
4729
+ return resolve11(JSON.parse(out));
4724
4730
  } catch {
4725
- return resolve10(out);
4731
+ return resolve11(out);
4726
4732
  }
4727
4733
  });
4728
4734
  });
@@ -5092,14 +5098,14 @@ var init_P2PChatSession = __esm({
5092
5098
 
5093
5099
  // src/ptr/node/SignalingServer.ts
5094
5100
  function killProcessOnPort(port) {
5095
- return new Promise((resolve10) => {
5101
+ return new Promise((resolve11) => {
5096
5102
  (0, import_child_process.exec)(`lsof -ti:${port} | xargs kill -9 2>/dev/null`, (error) => {
5097
5103
  if (error) {
5098
5104
  Logger2.info(`No existing process on port ${port} to kill`);
5099
5105
  } else {
5100
5106
  Logger2.info(`Killed existing process on port ${port}`);
5101
5107
  }
5102
- setTimeout(resolve10, NETWORK_SIGNALING_PORT_RELEASE_WAIT_MS);
5108
+ setTimeout(resolve11, NETWORK_SIGNALING_PORT_RELEASE_WAIT_MS);
5103
5109
  });
5104
5110
  });
5105
5111
  }
@@ -5119,8 +5125,8 @@ async function createSignalingServer(config = {}) {
5119
5125
  return;
5120
5126
  }
5121
5127
  const url = new URL(req.url || "/", `http://${req.headers.host}`);
5122
- const path15 = url.pathname;
5123
- if (req.method === "GET" && path15 === "/health") {
5128
+ const path16 = url.pathname;
5129
+ if (req.method === "GET" && path16 === "/health") {
5124
5130
  res.writeHead(200, { "Content-Type": "application/json" });
5125
5131
  res.end(JSON.stringify({
5126
5132
  status: "ok",
@@ -5129,7 +5135,7 @@ async function createSignalingServer(config = {}) {
5129
5135
  }));
5130
5136
  return;
5131
5137
  }
5132
- if (req.method === "GET" && path15 === "/signal") {
5138
+ if (req.method === "GET" && path16 === "/signal") {
5133
5139
  const peerId = url.searchParams.get("peer_id");
5134
5140
  if (!peerId) {
5135
5141
  res.writeHead(400);
@@ -5162,7 +5168,7 @@ async function createSignalingServer(config = {}) {
5162
5168
  });
5163
5169
  return;
5164
5170
  }
5165
- if (req.method === "POST" && path15 === "/signal") {
5171
+ if (req.method === "POST" && path16 === "/signal") {
5166
5172
  let body = "";
5167
5173
  req.on("data", (chunk) => body += chunk);
5168
5174
  req.on("end", () => {
@@ -5202,7 +5208,7 @@ async function createSignalingServer(config = {}) {
5202
5208
  for (let attempt = 0; attempt < maxTries; attempt++) {
5203
5209
  const port = startPort + attempt;
5204
5210
  try {
5205
- await new Promise((resolve10, reject) => {
5211
+ await new Promise((resolve11, reject) => {
5206
5212
  server.once("error", (err) => {
5207
5213
  if (err.code === "EADDRINUSE") {
5208
5214
  reject(err);
@@ -5212,7 +5218,7 @@ async function createSignalingServer(config = {}) {
5212
5218
  });
5213
5219
  server.listen(port, () => {
5214
5220
  server.removeAllListeners("error");
5215
- resolve10();
5221
+ resolve11();
5216
5222
  });
5217
5223
  });
5218
5224
  Logger2.info(`Server running on port ${port}`);
@@ -5228,11 +5234,11 @@ async function createSignalingServer(config = {}) {
5228
5234
  Logger2.info(`Port ${port} in use, trying to kill existing process...`);
5229
5235
  await killProcessOnPort(port);
5230
5236
  try {
5231
- await new Promise((resolve10, reject) => {
5237
+ await new Promise((resolve11, reject) => {
5232
5238
  server.once("error", reject);
5233
5239
  server.listen(port, () => {
5234
5240
  server.removeAllListeners("error");
5235
- resolve10();
5241
+ resolve11();
5236
5242
  });
5237
5243
  });
5238
5244
  Logger2.info(`Server running on port ${port} (after kill)`);
@@ -5493,7 +5499,7 @@ var init_NetworkInfrastructure = __esm({
5493
5499
  */
5494
5500
  async waitFor(domain) {
5495
5501
  while (!this.check(domain)) {
5496
- await new Promise((resolve10) => setTimeout(resolve10, RATE_LIMIT_WAIT_INTERVAL_MS));
5502
+ await new Promise((resolve11) => setTimeout(resolve11, RATE_LIMIT_WAIT_INTERVAL_MS));
5497
5503
  }
5498
5504
  }
5499
5505
  };
@@ -5639,7 +5645,7 @@ var init_HttpClient = __esm({
5639
5645
  retryConfig.max_delay
5640
5646
  );
5641
5647
  console.log(`[Network] Retry ${attempt}/${retryConfig.max_attempts} for ${url} (status: ${response.status}, delay: ${delay}ms)`);
5642
- await new Promise((resolve10) => setTimeout(resolve10, delay));
5648
+ await new Promise((resolve11) => setTimeout(resolve11, delay));
5643
5649
  continue;
5644
5650
  }
5645
5651
  }
@@ -5703,7 +5709,7 @@ var init_HttpClient = __esm({
5703
5709
  retryConfig.max_delay
5704
5710
  );
5705
5711
  console.log(`[Network] Retry ${attempt}/${retryConfig.max_attempts} for ${url} (error: ${lastError.message}, delay: ${delay}ms)`);
5706
- await new Promise((resolve10) => setTimeout(resolve10, delay));
5712
+ await new Promise((resolve11) => setTimeout(resolve11, delay));
5707
5713
  continue;
5708
5714
  }
5709
5715
  }
@@ -5873,10 +5879,10 @@ var init_NetworkRuntime = __esm({
5873
5879
  }
5874
5880
  async handleListenHttp(config, context) {
5875
5881
  const port = Number(this.interpolate(String(config.port || NETWORK_DEFAULT_LISTEN_PORT), context));
5876
- const path15 = this.interpolate(config.path || "/mcard", context);
5877
- return new Promise((resolve10, reject) => {
5882
+ const path16 = this.interpolate(config.path || "/mcard", context);
5883
+ return new Promise((resolve11, reject) => {
5878
5884
  const server = http3.createServer(async (req, res) => {
5879
- if (req.method === "POST" && req.url === path15) {
5885
+ if (req.method === "POST" && req.url === path16) {
5880
5886
  const bodyChunks = [];
5881
5887
  req.on("data", (chunk) => bodyChunks.push(chunk));
5882
5888
  req.on("end", async () => {
@@ -5903,8 +5909,8 @@ var init_NetworkRuntime = __esm({
5903
5909
  }
5904
5910
  });
5905
5911
  server.listen(port, () => {
5906
- console.log(`[Network] Listening on port ${port} at ${path15}`);
5907
- resolve10({
5912
+ console.info(`[Network] Listening on port ${port} at ${path16}`);
5913
+ resolve11({
5908
5914
  success: true,
5909
5915
  message: `Server started on port ${port}`
5910
5916
  });
@@ -6032,9 +6038,9 @@ var init_NetworkRuntime = __esm({
6032
6038
  const myPeerId = config.peer_id ? this.interpolate(config.peer_id, context) : `peer_${Date.now()}`;
6033
6039
  const channelLabel = config.channel_label || "mcard-sync";
6034
6040
  if (signalingUrl === "mock://p2p") {
6035
- return new Promise((resolve10) => {
6041
+ return new Promise((resolve11) => {
6036
6042
  setTimeout(() => {
6037
- resolve10({
6043
+ resolve11({
6038
6044
  success: true,
6039
6045
  peer_id: myPeerId,
6040
6046
  channel: channelLabel,
@@ -6044,12 +6050,12 @@ var init_NetworkRuntime = __esm({
6044
6050
  }, WEBRTC_DEFAULT_MOCK_DELAY_MS);
6045
6051
  });
6046
6052
  }
6047
- console.log(`[WebRTC] Connecting to ${targetPeerId} via ${signalingUrl} as ${myPeerId}`);
6053
+ console.info(`[WebRTC] Connecting to ${targetPeerId} via ${signalingUrl} as ${myPeerId}`);
6048
6054
  const pc = new PeerConnection({
6049
6055
  iceServers: config.ice_servers || [{ urls: "stun:stun.l.google.com:19302" }]
6050
6056
  });
6051
6057
  const dc = pc.createDataChannel(channelLabel);
6052
- const connectionPromise = new Promise((resolve10, reject) => {
6058
+ const connectionPromise = new Promise((resolve11, reject) => {
6053
6059
  const timeoutMs = config.timeout || WEBRTC_DEFAULT_TIMEOUT_MS;
6054
6060
  const timeoutId = setTimeout(() => {
6055
6061
  pc.close();
@@ -6057,12 +6063,12 @@ var init_NetworkRuntime = __esm({
6057
6063
  }, timeoutMs);
6058
6064
  dc.onopen = () => {
6059
6065
  clearTimeout(timeoutId);
6060
- console.log(`[WebRTC] Data channel '${channelLabel}' open`);
6066
+ console.info(`[WebRTC] Data channel '${channelLabel}' open`);
6061
6067
  if (config.message) {
6062
6068
  const msg = typeof config.message === "string" ? this.interpolate(config.message, context) : JSON.stringify(config.message);
6063
6069
  dc.send(msg);
6064
6070
  }
6065
- resolve10({
6071
+ resolve11({
6066
6072
  success: true,
6067
6073
  peer_id: myPeerId,
6068
6074
  channel: channelLabel,
@@ -6078,7 +6084,7 @@ var init_NetworkRuntime = __esm({
6078
6084
  });
6079
6085
  const offer = await pc.createOffer();
6080
6086
  await pc.setLocalDescription(offer);
6081
- console.log("[WebRTC] Local Offer created. SDP ready to send.");
6087
+ console.info("[WebRTC] Local Offer created. SDP ready to send.");
6082
6088
  if (config.await_response !== false) {
6083
6089
  return connectionPromise;
6084
6090
  }
@@ -6129,7 +6135,7 @@ var init_NetworkRuntime = __esm({
6129
6135
  await this.collection.add(card);
6130
6136
  added++;
6131
6137
  }
6132
- console.log(`[WebRTC] Synced ${added} cards from peer.`);
6138
+ console.info(`[WebRTC] Synced ${added} cards from peer.`);
6133
6139
  }
6134
6140
  } catch (e) {
6135
6141
  console.error("[WebRTC] Protocol error:", e);
@@ -6147,9 +6153,9 @@ var init_NetworkRuntime = __esm({
6147
6153
  const signalingUrl = this.interpolate(config.signaling_url ?? "", context);
6148
6154
  const myPeerId = config.peer_id ? this.interpolate(config.peer_id, context) : `listener_${Date.now()}`;
6149
6155
  if (signalingUrl === "mock://p2p") {
6150
- return new Promise((resolve10) => {
6156
+ return new Promise((resolve11) => {
6151
6157
  setTimeout(() => {
6152
- resolve10({
6158
+ resolve11({
6153
6159
  success: true,
6154
6160
  peer_id: myPeerId,
6155
6161
  status: "listening",
@@ -6172,7 +6178,7 @@ var init_NetworkRuntime = __esm({
6172
6178
  }
6173
6179
  const port = Number(this.interpolate(String(config.port || NETWORK_DEFAULT_LISTEN_PORT), context));
6174
6180
  const basePath = this.interpolate(config.base_path || "/sync", context);
6175
- return new Promise((resolve10, reject) => {
6181
+ return new Promise((resolve11, reject) => {
6176
6182
  const server = http3.createServer(async (req, res) => {
6177
6183
  const url = req.url || "";
6178
6184
  const readBody = async () => {
@@ -6234,7 +6240,7 @@ var init_NetworkRuntime = __esm({
6234
6240
  });
6235
6241
  server.listen(port, () => {
6236
6242
  console.log(`[Network] Sync listening on port ${port} at ${basePath}`);
6237
- resolve10({
6243
+ resolve11({
6238
6244
  success: true,
6239
6245
  message: `Sync Server started on port ${port}`,
6240
6246
  port,
@@ -6248,8 +6254,8 @@ var init_NetworkRuntime = __esm({
6248
6254
  }
6249
6255
  interpolate(text, context) {
6250
6256
  if (!text || typeof text !== "string") return text;
6251
- return text.replace(/\$\{([^}]+)\}/g, (_, path15) => {
6252
- const keys = path15.split(".");
6257
+ return text.replace(/\$\{([^}]+)\}/g, (_, path16) => {
6258
+ const keys = path16.split(".");
6253
6259
  let val = context;
6254
6260
  for (const key of keys) {
6255
6261
  if (val && typeof val === "object" && key in val) {
@@ -6551,11 +6557,11 @@ var init_NetworkRuntime = __esm({
6551
6557
  message: "Background process started"
6552
6558
  };
6553
6559
  }
6554
- return new Promise((resolve10, reject) => {
6560
+ return new Promise((resolve11, reject) => {
6555
6561
  exec3(command, (error, stdout, stderr) => {
6556
6562
  if (error) {
6557
6563
  console.error(`[NetworkRuntime] Command failed: ${error.message}`);
6558
- return resolve10({
6564
+ return resolve11({
6559
6565
  success: false,
6560
6566
  error: error.message,
6561
6567
  stderr
@@ -6563,7 +6569,7 @@ var init_NetworkRuntime = __esm({
6563
6569
  }
6564
6570
  console.log(`[NetworkRuntime] Command output:
6565
6571
  ${stdout}`);
6566
- resolve10({
6572
+ resolve11({
6567
6573
  success: true,
6568
6574
  stdout,
6569
6575
  stderr
@@ -7553,6 +7559,9 @@ __export(index_exports, {
7553
7559
  MCard: () => MCard,
7554
7560
  MCardStore: () => MCardStore,
7555
7561
  Maybe: () => Maybe,
7562
+ PTREngine: () => PTREngine,
7563
+ PostconditionViolation: () => PostconditionViolation,
7564
+ PreconditionViolation: () => PreconditionViolation,
7556
7565
  Reader: () => Reader,
7557
7566
  SandboxWorker: () => SandboxWorker,
7558
7567
  ServiceWorkerPTR: () => ServiceWorkerPTR,
@@ -8090,12 +8099,12 @@ var SandboxWorker = class {
8090
8099
  * Send request and wait for response
8091
8100
  */
8092
8101
  sendRequest(request) {
8093
- return new Promise((resolve10, reject) => {
8102
+ return new Promise((resolve11, reject) => {
8094
8103
  const timeout = setTimeout(() => {
8095
8104
  this.pendingRequests.delete(request.id);
8096
8105
  reject(new Error(`Request ${request.id} timed out`));
8097
8106
  }, this.defaultTimeout);
8098
- this.pendingRequests.set(request.id, { resolve: resolve10, reject, timeout });
8107
+ this.pendingRequests.set(request.id, { resolve: resolve11, reject, timeout });
8099
8108
  this.worker.postMessage(request);
8100
8109
  });
8101
8110
  }
@@ -8156,6 +8165,32 @@ var VerificationStatus = /* @__PURE__ */ ((VerificationStatus2) => {
8156
8165
  VerificationStatus2["SKIPPED"] = "skipped";
8157
8166
  return VerificationStatus2;
8158
8167
  })(VerificationStatus || {});
8168
+ var PreconditionViolation = class extends Error {
8169
+ pcardHash;
8170
+ inputHash;
8171
+ detail;
8172
+ constructor(pcardHash, inputHash, detail = "") {
8173
+ const msg = `PreconditionViolation: PCard ${pcardHash.substring(0, 16)} rejected input ${inputHash.substring(0, 16)}${detail ? ` \u2014 ${detail}` : ""}`;
8174
+ super(msg);
8175
+ this.name = "PreconditionViolation";
8176
+ this.pcardHash = pcardHash;
8177
+ this.inputHash = inputHash;
8178
+ this.detail = detail;
8179
+ }
8180
+ };
8181
+ var PostconditionViolation = class extends Error {
8182
+ pcardHash;
8183
+ outputRepr;
8184
+ detail;
8185
+ constructor(pcardHash, outputRepr, detail = "") {
8186
+ const msg = `PostconditionViolation: PCard ${pcardHash.substring(0, 16)} postcondition failed for output ${outputRepr.substring(0, 64)}${detail ? ` \u2014 ${detail}` : ""}`;
8187
+ super(msg);
8188
+ this.name = "PostconditionViolation";
8189
+ this.pcardHash = pcardHash;
8190
+ this.outputRepr = outputRepr;
8191
+ this.detail = detail;
8192
+ }
8193
+ };
8159
8194
 
8160
8195
  // src/ptr/browser/storage/MCardStore.ts
8161
8196
  var import_idb2 = require("idb");
@@ -8641,78 +8676,10 @@ init_LambdaRuntime();
8641
8676
  // src/index.ts
8642
8677
  init_LambdaRuntime();
8643
8678
 
8644
- // src/ptr/node/clm/utils.ts
8645
- function resultsEqual(a, b, tolerance = 1e-9) {
8646
- if (a === b) return true;
8647
- if (a == null || b == null) return false;
8648
- if (typeof a === "number" && typeof b === "number") {
8649
- if (Number.isNaN(a) && Number.isNaN(b)) return true;
8650
- if (!Number.isFinite(a) || !Number.isFinite(b)) return a === b;
8651
- return Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b));
8652
- }
8653
- if (Array.isArray(a) && Array.isArray(b)) {
8654
- if (a.length !== b.length) return false;
8655
- return a.every((val, i) => resultsEqual(val, b[i], tolerance));
8656
- }
8657
- if (typeof a === "object" && typeof b === "object") {
8658
- const keysA = Object.keys(a);
8659
- const keysB = Object.keys(b);
8660
- if (keysA.length !== keysB.length) return false;
8661
- return keysA.every(
8662
- (key) => keysB.includes(key) && resultsEqual(a[key], b[key], tolerance)
8663
- );
8664
- }
8665
- return a === b;
8666
- }
8667
- function asObject(input) {
8668
- return typeof input === "object" && input !== null ? input : {};
8669
- }
8670
- function buildBaseContext(clm, input) {
8671
- const inputObj = asObject(input);
8672
- return {
8673
- balanced: clm.clm.balanced,
8674
- input_arguments: clm.clm.concrete?.input_arguments,
8675
- output_arguments: clm.clm.concrete?.output_arguments,
8676
- params: inputObj,
8677
- ...inputObj
8678
- };
8679
- }
8680
- function buildExecutionResult(success, result, startTime, clm, error, boundary) {
8681
- return {
8682
- success,
8683
- result,
8684
- error,
8685
- executionTime: Date.now() - startTime,
8686
- clm: {
8687
- chapter: clm.chapter?.title || "Unknown",
8688
- concept: clm.clm.abstract?.concept || "Unknown",
8689
- manifestation: clm.clm.concrete?.manifestation || "Unknown",
8690
- boundary
8691
- }
8692
- };
8693
- }
8694
- function isRecursiveCLM(runtimeName) {
8695
- return runtimeName.endsWith(".clm") || runtimeName.endsWith(".yaml") || runtimeName.endsWith(".yml");
8696
- }
8697
- function isMultiRuntime(clm) {
8698
- const runtimesConfig = clm.clm?.concrete?.runtimes_config;
8699
- return Array.isArray(runtimesConfig) && runtimesConfig.length > 0;
8700
- }
8701
-
8702
- // src/ptr/node/clm/runner.ts
8703
- var path14 = __toESM(require("path"), 1);
8704
- var yaml2 = __toESM(require("yaml"), 1);
8705
- init_constants();
8706
-
8707
- // src/ptr/node/runtimes/index.ts
8708
- init_base();
8709
- init_javascript();
8710
- init_python();
8711
- init_binary();
8712
- init_wasm();
8713
- init_lean();
8714
- init_loader();
8715
- init_factory();
8679
+ // src/ptr/node/PTREngine.ts
8680
+ var path15 = __toESM(require("path"), 1);
8681
+ var yaml3 = __toESM(require("yaml"), 1);
8682
+ init_MCard();
8716
8683
 
8717
8684
  // src/model/PCard.ts
8718
8685
  var import_yaml = require("yaml");
@@ -8912,8 +8879,8 @@ var PCard = class _PCard extends MCard {
8912
8879
  }
8913
8880
  }
8914
8881
  };
8915
- const { stringify: stringify2 } = await import("yaml");
8916
- return _PCard.create(stringify2(newClm), this.hashFunction);
8882
+ const { stringify: stringify3 } = await import("yaml");
8883
+ return _PCard.create(stringify3(newClm), this.hashFunction);
8917
8884
  }
8918
8885
  /**
8919
8886
  * Tensor Product ($A \otimes B$)
@@ -8940,8 +8907,8 @@ var PCard = class _PCard extends MCard {
8940
8907
  }
8941
8908
  }
8942
8909
  };
8943
- const { stringify: stringify2 } = await import("yaml");
8944
- return _PCard.create(stringify2(newClm), this.hashFunction);
8910
+ const { stringify: stringify3 } = await import("yaml");
8911
+ return _PCard.create(stringify3(newClm), this.hashFunction);
8945
8912
  }
8946
8913
  /**
8947
8914
  * Symmetry ($\sigma$)
@@ -8967,8 +8934,8 @@ var PCard = class _PCard extends MCard {
8967
8934
  }
8968
8935
  }
8969
8936
  };
8970
- const { stringify: stringify2 } = await import("yaml");
8971
- return _PCard.create(stringify2(newClm), this.hashFunction);
8937
+ const { stringify: stringify3 } = await import("yaml");
8938
+ return _PCard.create(stringify3(newClm), this.hashFunction);
8972
8939
  }
8973
8940
  // =========================================================================
8974
8941
  // Universal Tooling Interface
@@ -9172,6 +9139,70 @@ var PCard = class _PCard extends MCard {
9172
9139
  const runtimesConfig = config?.runtimes_config;
9173
9140
  return Array.isArray(runtimesConfig) && runtimesConfig.length > 1;
9174
9141
  }
9142
+ // =========================================================================
9143
+ // VCard Sandwich Boundary Spec Accessors
9144
+ // =========================================================================
9145
+ // Mirrors Python: PCard.get_pre_vcard_spec(), PCard.get_post_vcard_spec()
9146
+ // =========================================================================
9147
+ /**
9148
+ * Get precondition specification for VCard Sandwich evaluation.
9149
+ *
9150
+ * Extracts the precondition spec from abstract.preconditions,
9151
+ * classifying each condition by type.
9152
+ *
9153
+ * @returns Object with conditions array and classified conditions
9154
+ */
9155
+ getPreVCardSpec() {
9156
+ const abstractSpec = this.abstract;
9157
+ const preconditions = abstractSpec?.preconditions || [];
9158
+ return {
9159
+ conditions: preconditions,
9160
+ classified: preconditions.map((c) => this.classifyCondition(c))
9161
+ };
9162
+ }
9163
+ /**
9164
+ * Get postcondition specification for VCard Sandwich evaluation.
9165
+ *
9166
+ * Extracts the postcondition spec from abstract.postconditions,
9167
+ * classifying each condition by type.
9168
+ *
9169
+ * @returns Object with conditions array and classified conditions
9170
+ */
9171
+ getPostVCardSpec() {
9172
+ const abstractSpec = this.abstract;
9173
+ const postconditions = abstractSpec?.postconditions || [];
9174
+ return {
9175
+ conditions: postconditions,
9176
+ classified: postconditions.map((c) => this.classifyCondition(c))
9177
+ };
9178
+ }
9179
+ /**
9180
+ * Classify a condition by its type (function, schema, capability, declarative).
9181
+ *
9182
+ * @param condition - The condition to classify
9183
+ * @returns Object with type and the original condition
9184
+ */
9185
+ classifyCondition(condition) {
9186
+ if (typeof condition === "string") {
9187
+ return { type: "declarative", condition };
9188
+ }
9189
+ if (typeof condition === "object" && condition !== null) {
9190
+ const cond = condition;
9191
+ if (typeof cond.function === "string" || typeof cond.callable === "string") {
9192
+ return { type: "function", condition };
9193
+ }
9194
+ if (cond.schema || cond.json_schema) {
9195
+ return { type: "schema", condition };
9196
+ }
9197
+ if (typeof cond.capability === "string") {
9198
+ return { type: "capability", condition };
9199
+ }
9200
+ if (cond.description) {
9201
+ return { type: "declarative", condition };
9202
+ }
9203
+ }
9204
+ return { type: "unknown", condition };
9205
+ }
9175
9206
  };
9176
9207
 
9177
9208
  // src/model/VCard.ts
@@ -9567,6 +9598,127 @@ var VCard = class _VCard extends MCard {
9567
9598
  const myHandle = this.getTokenHandle();
9568
9599
  return myHandle === requiredHandle;
9569
9600
  }
9601
+ // =========================================================================
9602
+ // VCard Sandwich — Arrow Boundary Evaluation Pattern
9603
+ // =========================================================================
9604
+ //
9605
+ // These static methods implement the formal VCard Sandwich lifecycle:
9606
+ // V_pre → PCard(Evaluation Map) → V_post → Sandwich(V_pre, V_post)
9607
+ //
9608
+ // Mirrors Python: VCard.witness_precondition(), witness_postcondition(), sandwich()
9609
+ // =========================================================================
9610
+ /**
9611
+ * Witness Precondition (V_pre) — creates a VCard that witnesses
9612
+ * the input was accepted for evaluation.
9613
+ *
9614
+ * @param inputMCard - The input MCard being evaluated
9615
+ * @param hashAlgorithm - Hash algorithm to use
9616
+ * @returns VCard with type "precondition-witness"
9617
+ */
9618
+ static async witnessPrecondition(inputMCard, hashAlgorithm = "sha256") {
9619
+ const structure = {
9620
+ vcard: {
9621
+ type: "precondition-witness",
9622
+ identity: {
9623
+ subject_did: "did:ptr:system",
9624
+ controller_pubkeys: []
9625
+ },
9626
+ verification: {
9627
+ input_hash: inputMCard.hash,
9628
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9629
+ witness_type: "precondition"
9630
+ },
9631
+ gatekeeper: { capabilities: [] },
9632
+ external_refs: []
9633
+ }
9634
+ };
9635
+ const contentString = JSON.stringify(structure, null, 2);
9636
+ const bytes = new TextEncoder().encode(contentString);
9637
+ const hash = await HashValidator.computeHash(bytes, hashAlgorithm);
9638
+ const g_time = GTime.stampNow(hashAlgorithm);
9639
+ const contentType = ContentTypeInterpreter.detect(bytes);
9640
+ return new _VCard(bytes, hash, g_time, contentType, hashAlgorithm, structure);
9641
+ }
9642
+ /**
9643
+ * Witness Postcondition (V_post) — creates a VCard that witnesses
9644
+ * the output was produced by a PCard evaluation.
9645
+ *
9646
+ * @param output - The execution output
9647
+ * @param pcardHash - Hash of the PCard that produced the output
9648
+ * @param hashAlgorithm - Hash algorithm to use
9649
+ * @returns VCard with type "postcondition-witness"
9650
+ */
9651
+ static async witnessPostcondition(output, pcardHash, hashAlgorithm = "sha256") {
9652
+ let outputRepr;
9653
+ try {
9654
+ outputRepr = typeof output === "string" ? output : JSON.stringify(output);
9655
+ } catch {
9656
+ outputRepr = String(output);
9657
+ }
9658
+ const outputHash = await HashValidator.computeHash(
9659
+ new TextEncoder().encode(outputRepr),
9660
+ hashAlgorithm
9661
+ );
9662
+ const structure = {
9663
+ vcard: {
9664
+ type: "postcondition-witness",
9665
+ identity: {
9666
+ subject_did: "did:ptr:system",
9667
+ controller_pubkeys: []
9668
+ },
9669
+ verification: {
9670
+ output_hash: outputHash,
9671
+ pcard_hash: pcardHash || null,
9672
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9673
+ witness_type: "postcondition"
9674
+ },
9675
+ gatekeeper: { capabilities: [] },
9676
+ external_refs: []
9677
+ }
9678
+ };
9679
+ const contentString = JSON.stringify(structure, null, 2);
9680
+ const bytes = new TextEncoder().encode(contentString);
9681
+ const hash = await HashValidator.computeHash(bytes, hashAlgorithm);
9682
+ const g_time = GTime.stampNow(hashAlgorithm);
9683
+ const contentType = ContentTypeInterpreter.detect(bytes);
9684
+ return new _VCard(bytes, hash, g_time, contentType, hashAlgorithm, structure);
9685
+ }
9686
+ /**
9687
+ * Create a Sandwich Proof — combines V_pre and V_post into a
9688
+ * composite verification proof.
9689
+ *
9690
+ * @param vPre - Precondition witness VCard
9691
+ * @param vPost - Postcondition witness VCard
9692
+ * @param pcardHash - Hash of the PCard that was evaluated
9693
+ * @param hashAlgorithm - Hash algorithm to use
9694
+ * @returns VCard with type "verification-sandwich"
9695
+ */
9696
+ static async sandwich(vPre, vPost, pcardHash, hashAlgorithm = "sha256") {
9697
+ const structure = {
9698
+ vcard: {
9699
+ type: "verification-sandwich",
9700
+ identity: {
9701
+ subject_did: "did:ptr:system",
9702
+ controller_pubkeys: []
9703
+ },
9704
+ verification: {
9705
+ v_pre_hash: vPre.hash,
9706
+ v_post_hash: vPost.hash,
9707
+ pcard_hash: pcardHash || null,
9708
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9709
+ witness_type: "sandwich"
9710
+ },
9711
+ gatekeeper: { capabilities: [] },
9712
+ external_refs: []
9713
+ }
9714
+ };
9715
+ const contentString = JSON.stringify(structure, null, 2);
9716
+ const bytes = new TextEncoder().encode(contentString);
9717
+ const hash = await HashValidator.computeHash(bytes, hashAlgorithm);
9718
+ const g_time = GTime.stampNow(hashAlgorithm);
9719
+ const contentType = ContentTypeInterpreter.detect(bytes);
9720
+ return new _VCard(bytes, hash, g_time, contentType, hashAlgorithm, structure);
9721
+ }
9570
9722
  };
9571
9723
  var VCardSimulation = class {
9572
9724
  vcard;
@@ -9588,6 +9740,79 @@ var VCardSimulation = class {
9588
9740
  }
9589
9741
  };
9590
9742
 
9743
+ // src/ptr/node/clm/runner.ts
9744
+ var path14 = __toESM(require("path"), 1);
9745
+ var yaml2 = __toESM(require("yaml"), 1);
9746
+ init_constants();
9747
+
9748
+ // src/ptr/node/runtimes/index.ts
9749
+ init_base();
9750
+ init_javascript();
9751
+ init_python();
9752
+ init_binary();
9753
+ init_wasm();
9754
+ init_lean();
9755
+ init_loader();
9756
+ init_factory();
9757
+
9758
+ // src/ptr/node/clm/utils.ts
9759
+ function resultsEqual(a, b, tolerance = 1e-9) {
9760
+ if (a === b) return true;
9761
+ if (a == null || b == null) return false;
9762
+ if (typeof a === "number" && typeof b === "number") {
9763
+ if (Number.isNaN(a) && Number.isNaN(b)) return true;
9764
+ if (!Number.isFinite(a) || !Number.isFinite(b)) return a === b;
9765
+ return Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b));
9766
+ }
9767
+ if (Array.isArray(a) && Array.isArray(b)) {
9768
+ if (a.length !== b.length) return false;
9769
+ return a.every((val, i) => resultsEqual(val, b[i], tolerance));
9770
+ }
9771
+ if (typeof a === "object" && typeof b === "object") {
9772
+ const keysA = Object.keys(a);
9773
+ const keysB = Object.keys(b);
9774
+ if (keysA.length !== keysB.length) return false;
9775
+ return keysA.every(
9776
+ (key) => keysB.includes(key) && resultsEqual(a[key], b[key], tolerance)
9777
+ );
9778
+ }
9779
+ return a === b;
9780
+ }
9781
+ function asObject(input) {
9782
+ return typeof input === "object" && input !== null ? input : {};
9783
+ }
9784
+ function buildBaseContext(clm, input) {
9785
+ const inputObj = asObject(input);
9786
+ return {
9787
+ balanced: clm.clm.balanced,
9788
+ input_arguments: clm.clm.concrete?.input_arguments,
9789
+ output_arguments: clm.clm.concrete?.output_arguments,
9790
+ params: inputObj,
9791
+ ...inputObj
9792
+ };
9793
+ }
9794
+ function buildExecutionResult(success, result, startTime, clm, error, boundary) {
9795
+ return {
9796
+ success,
9797
+ result,
9798
+ error,
9799
+ executionTime: Date.now() - startTime,
9800
+ clm: {
9801
+ chapter: clm.chapter?.title || "Unknown",
9802
+ concept: clm.clm.abstract?.concept || "Unknown",
9803
+ manifestation: clm.clm.concrete?.manifestation || "Unknown",
9804
+ boundary
9805
+ }
9806
+ };
9807
+ }
9808
+ function isRecursiveCLM(runtimeName) {
9809
+ return runtimeName.endsWith(".clm") || runtimeName.endsWith(".yaml") || runtimeName.endsWith(".yml");
9810
+ }
9811
+ function isMultiRuntime(clm) {
9812
+ const runtimesConfig = clm.clm?.concrete?.runtimes_config;
9813
+ return Array.isArray(runtimesConfig) && runtimesConfig.length > 0;
9814
+ }
9815
+
9591
9816
  // src/ptr/node/core/operations/index.ts
9592
9817
  var NETWORK_BUILTINS = /* @__PURE__ */ new Set([
9593
9818
  "http_get",
@@ -9935,7 +10160,7 @@ setInterval(() => {}, 1000);
9935
10160
  });
9936
10161
  child.unref();
9937
10162
  fs8.writeFileSync(pidFile, String(child.pid));
9938
- await new Promise((resolve10) => setTimeout(resolve10, STATIC_SERVER_START_WAIT_MS));
10163
+ await new Promise((resolve11) => setTimeout(resolve11, STATIC_SERVER_START_WAIT_MS));
9939
10164
  if (isPortInUse(port)) {
9940
10165
  return {
9941
10166
  success: true,
@@ -9988,10 +10213,10 @@ setInterval(() => {}, 1000);
9988
10213
  }
9989
10214
  try {
9990
10215
  process.kill(pid, "SIGTERM");
9991
- await new Promise((resolve10) => setTimeout(resolve10, PROCESS_TERMINATE_WAIT_MS));
10216
+ await new Promise((resolve11) => setTimeout(resolve11, PROCESS_TERMINATE_WAIT_MS));
9992
10217
  if (isPortInUse(port)) {
9993
10218
  process.kill(pid, "SIGKILL");
9994
- await new Promise((resolve10) => setTimeout(resolve10, PROCESS_TERMINATE_WAIT_MS));
10219
+ await new Promise((resolve11) => setTimeout(resolve11, PROCESS_TERMINATE_WAIT_MS));
9995
10220
  }
9996
10221
  if (fs8.existsSync(pidFile)) {
9997
10222
  fs8.unlinkSync(pidFile);
@@ -10134,7 +10359,7 @@ Process exited with code ${code}
10134
10359
  } catch {
10135
10360
  }
10136
10361
  fs9.writeFileSync(pidFile, String(child.pid));
10137
- await new Promise((resolve10) => setTimeout(resolve10, WEBSOCKET_SERVER_START_WAIT_MS));
10362
+ await new Promise((resolve11) => setTimeout(resolve11, WEBSOCKET_SERVER_START_WAIT_MS));
10138
10363
  if (isPortInUse2(port)) {
10139
10364
  console.log(`[WebSocket Server] Successfully started on port ${port}`);
10140
10365
  return {
@@ -10198,10 +10423,10 @@ Process exited with code ${code}
10198
10423
  }
10199
10424
  try {
10200
10425
  process.kill(pid, "SIGTERM");
10201
- await new Promise((resolve10) => setTimeout(resolve10, PROCESS_TERMINATE_WAIT_MS));
10426
+ await new Promise((resolve11) => setTimeout(resolve11, PROCESS_TERMINATE_WAIT_MS));
10202
10427
  if (isPortInUse2(port)) {
10203
10428
  process.kill(pid, "SIGKILL");
10204
- await new Promise((resolve10) => setTimeout(resolve10, PROCESS_TERMINATE_WAIT_MS));
10429
+ await new Promise((resolve11) => setTimeout(resolve11, PROCESS_TERMINATE_WAIT_MS));
10205
10430
  }
10206
10431
  if (fs9.existsSync(pidFile)) {
10207
10432
  fs9.unlinkSync(pidFile);
@@ -10923,6 +11148,250 @@ var CLMRunner = class _CLMRunner {
10923
11148
  }
10924
11149
  };
10925
11150
 
11151
+ // src/ptr/node/PTREngine.ts
11152
+ var PTREngine = class {
11153
+ collection;
11154
+ executionLog;
11155
+ runner;
11156
+ /**
11157
+ * Initialize PTREngine.
11158
+ *
11159
+ * @param storageCollection - MCard collection for long-term knowledge (mcard_collection.db)
11160
+ * @param executionLogCollection - MCard collection for execution traces (execution_log.db).
11161
+ * If not provided, traces are written to storageCollection.
11162
+ * @param options - Additional configuration
11163
+ */
11164
+ constructor(storageCollection, executionLogCollection, options) {
11165
+ this.collection = storageCollection;
11166
+ this.executionLog = executionLogCollection || this.collection;
11167
+ this.runner = new CLMRunner(
11168
+ options?.basePath || process.cwd(),
11169
+ options?.timeout,
11170
+ this.collection,
11171
+ this.executionLog
11172
+ );
11173
+ }
11174
+ // =========================================================================
11175
+ // ARROW INTERFACE — The canonical PTR execution primitives
11176
+ // =========================================================================
11177
+ /**
11178
+ * The Arrow execution primitive — the entire PTR in one method.
11179
+ *
11180
+ * Implements the VCard Sandwich lifecycle:
11181
+ * V_pre → PCard(Evaluation Map) → V_post
11182
+ *
11183
+ * @param pcardHash - Hash of the PCard to execute
11184
+ * @param inputHash - Hash of the input MCard
11185
+ * @param preCheck - Optional callable to validate preconditions on input
11186
+ * @param postCheck - Optional callable to validate postconditions on output
11187
+ * @returns Tuple of [execution_output, vcard_sandwich]
11188
+ * @throws PreconditionViolation if preCheck returns false
11189
+ * @throws PostconditionViolation if postCheck returns false
11190
+ */
11191
+ async runWithSandwich(pcardHash, inputHash, preCheck, postCheck) {
11192
+ const pcard = await this.collection.get(pcardHash);
11193
+ if (!pcard) throw new Error(`PCard not found: ${pcardHash}`);
11194
+ const inputMCard = await this.collection.get(inputHash);
11195
+ if (!inputMCard) throw new Error(`Input MCard not found: ${inputHash}`);
11196
+ if (preCheck && !preCheck(inputMCard)) {
11197
+ throw new PreconditionViolation(pcardHash, inputHash);
11198
+ }
11199
+ const vPre = await VCard.witnessPrecondition(inputMCard);
11200
+ const pcardObj = await PCard.create(
11201
+ new TextDecoder().decode(pcard.content)
11202
+ );
11203
+ const clmSpec = {
11204
+ chapter: { id: "runtime", title: "Runtime Execution" },
11205
+ clm: pcardObj.clm
11206
+ };
11207
+ const result = await this.runner.executeCLM(
11208
+ clmSpec,
11209
+ process.cwd(),
11210
+ inputMCard.getContentAsText()
11211
+ );
11212
+ const output = result.result;
11213
+ if (postCheck && !postCheck(output)) {
11214
+ throw new PostconditionViolation(
11215
+ pcardHash,
11216
+ typeof output === "string" ? output.substring(0, 64) : JSON.stringify(output).substring(0, 64)
11217
+ );
11218
+ }
11219
+ const vPost = await VCard.witnessPostcondition(output, pcardHash);
11220
+ const sandwich = await VCard.sandwich(vPre, vPost, pcardHash);
11221
+ await this.recordToExecutionLog(sandwich);
11222
+ return [output, sandwich];
11223
+ }
11224
+ /**
11225
+ * Execute a CLM specification from a YAML file.
11226
+ *
11227
+ * Absorbs CLMRunner.runFile(), routing all file-based execution
11228
+ * through the formal PTREngine lifecycle with VCard Sandwich generation.
11229
+ *
11230
+ * @param filePath - Path to the YAML file
11231
+ * @param context - Execution context (inputs)
11232
+ * @returns Execution report with VCard Sandwich proof hashes
11233
+ */
11234
+ async runFile(filePath, context) {
11235
+ const loader = new CLMLoader(path15.dirname(filePath));
11236
+ const clm = loader.load(filePath);
11237
+ const chapterDir = path15.dirname(path15.resolve(filePath));
11238
+ const clmContent = yaml3.stringify(clm);
11239
+ const pcard = await PCard.create(clmContent);
11240
+ if (this.collection) {
11241
+ await this.collection.add(pcard);
11242
+ }
11243
+ const inputMCard = await MCard.create(JSON.stringify(context || {}));
11244
+ const vPre = await VCard.witnessPrecondition(inputMCard);
11245
+ const result = await this.runner.executeCLM(clm, chapterDir, context || {});
11246
+ const vPost = await VCard.witnessPostcondition(result.result, pcard.hash);
11247
+ const sandwich = await VCard.sandwich(vPre, vPost, pcard.hash);
11248
+ let eventRecordHash = null;
11249
+ try {
11250
+ if (this.executionLog) {
11251
+ await this.executionLog.add(sandwich);
11252
+ eventRecordHash = sandwich.hash;
11253
+ }
11254
+ } catch (e) {
11255
+ console.warn(`[PTREngine] Failed to store VCard Sandwich: ${e}`);
11256
+ }
11257
+ return {
11258
+ status: result.success ? "success" : "failure",
11259
+ result: result.result,
11260
+ error: result.error,
11261
+ chapter_id: clm.chapter?.id,
11262
+ chapter_title: clm.chapter?.title,
11263
+ event_record_hash: eventRecordHash,
11264
+ v_pre_hash: vPre.hash,
11265
+ v_post_hash: vPost.hash,
11266
+ sandwich_hash: sandwich.hash
11267
+ };
11268
+ }
11269
+ /**
11270
+ * Arrow `arr` — lift a pure function into a PCard.
11271
+ *
11272
+ * Creates a PCard whose Concrete implementation is the given function.
11273
+ *
11274
+ * @param func - A pure function from string to string
11275
+ * @param name - Human-readable name for the PCard
11276
+ * @returns The created PCard (stored in collection)
11277
+ */
11278
+ async arr(func, name = "lifted") {
11279
+ const funcSource = func.toString();
11280
+ const clmYaml = yaml3.stringify({
11281
+ chapter: { id: `arr_${name}`, title: `Lifted: ${name}` },
11282
+ clm: {
11283
+ abstract: {
11284
+ purpose: `Lifted pure function: ${name}`,
11285
+ inputs: { input: "any" },
11286
+ outputs: { result: "any" },
11287
+ preconditions: [],
11288
+ postconditions: []
11289
+ },
11290
+ concrete: {
11291
+ runtime: "javascript",
11292
+ operation: `lifted_${name}`,
11293
+ code: funcSource
11294
+ },
11295
+ balanced: { test_cases: [], expectations: {} }
11296
+ }
11297
+ });
11298
+ const pcard = await PCard.create(clmYaml);
11299
+ if (this.collection) {
11300
+ await this.collection.add(pcard);
11301
+ }
11302
+ return pcard;
11303
+ }
11304
+ /**
11305
+ * Arrow `>>>` — sequential composition of two PCards.
11306
+ *
11307
+ * Creates a new PCard representing pcardA >>> pcardB,
11308
+ * where the output of A feeds into the input of B.
11309
+ *
11310
+ * @param pcardAHash - Hash of the first PCard (executed first)
11311
+ * @param pcardBHash - Hash of the second PCard (executed second)
11312
+ * @returns The composed PCard (stored in collection)
11313
+ */
11314
+ async compose(pcardAHash, pcardBHash) {
11315
+ const clmYaml = yaml3.stringify({
11316
+ chapter: {
11317
+ id: `compose_${pcardAHash.substring(0, 8)}_${pcardBHash.substring(0, 8)}`,
11318
+ title: "Sequential Composition (Arrow >>>)"
11319
+ },
11320
+ clm: {
11321
+ abstract: {
11322
+ type: "sequential_composition",
11323
+ purpose: `Compose ${pcardAHash.substring(0, 16)} >>> ${pcardBHash.substring(0, 16)}`,
11324
+ inputs: { input: "any" },
11325
+ outputs: { result: "any" },
11326
+ preconditions: [],
11327
+ postconditions: []
11328
+ },
11329
+ concrete: {
11330
+ runtime: "ptr",
11331
+ operation: "compose_sequential",
11332
+ steps: [pcardAHash, pcardBHash]
11333
+ },
11334
+ balanced: { test_cases: [], expectations: {} }
11335
+ }
11336
+ });
11337
+ const pcard = await PCard.create(clmYaml);
11338
+ if (this.collection) {
11339
+ await this.collection.add(pcard);
11340
+ }
11341
+ return pcard;
11342
+ }
11343
+ /**
11344
+ * Arrow `first` — operate on first element of a product.
11345
+ *
11346
+ * Creates a new PCard that applies the original PCard to the
11347
+ * first element of a (A, C) pair while preserving C.
11348
+ *
11349
+ * @param pcardHash - Hash of the PCard to lift
11350
+ * @returns The first-lifted PCard (stored in collection)
11351
+ */
11352
+ async first(pcardHash) {
11353
+ const clmYaml = yaml3.stringify({
11354
+ chapter: {
11355
+ id: `first_${pcardHash.substring(0, 8)}`,
11356
+ title: "Arrow First (Product Preservation)"
11357
+ },
11358
+ clm: {
11359
+ abstract: {
11360
+ type: "arrow_first",
11361
+ purpose: `Apply ${pcardHash.substring(0, 16)} to first element, preserve second`,
11362
+ inputs: { pair: "(A, C)" },
11363
+ outputs: { result: "(B, C)" },
11364
+ preconditions: [],
11365
+ postconditions: []
11366
+ },
11367
+ concrete: {
11368
+ runtime: "ptr",
11369
+ operation: "apply_first",
11370
+ target: pcardHash
11371
+ },
11372
+ balanced: { test_cases: [], expectations: {} }
11373
+ }
11374
+ });
11375
+ const pcard = await PCard.create(clmYaml);
11376
+ if (this.collection) {
11377
+ await this.collection.add(pcard);
11378
+ }
11379
+ return pcard;
11380
+ }
11381
+ // =========================================================================
11382
+ // Private Helpers
11383
+ // =========================================================================
11384
+ async recordToExecutionLog(sandwich) {
11385
+ try {
11386
+ if (this.executionLog) {
11387
+ await this.executionLog.add(sandwich);
11388
+ }
11389
+ } catch (e) {
11390
+ console.warn(`[PTREngine] Failed to record to execution log: ${e}`);
11391
+ }
11392
+ }
11393
+ };
11394
+
10926
11395
  // src/model/hash/algorithms/LocalSHA256.ts
10927
11396
  async function computeHash(content) {
10928
11397
  let contentStr;
@@ -11160,6 +11629,9 @@ var validationRegistry = new ValidationRegistry();
11160
11629
  MCard,
11161
11630
  MCardStore,
11162
11631
  Maybe,
11632
+ PTREngine,
11633
+ PostconditionViolation,
11634
+ PreconditionViolation,
11163
11635
  Reader,
11164
11636
  SandboxWorker,
11165
11637
  ServiceWorkerPTR,