clm-kernel 0.0.0__py3-none-any.whl

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 (333) hide show
  1. clm/__init__.py +230 -0
  2. clm/__main__.py +25 -0
  3. clm/cross_cutting/__init__.py +50 -0
  4. clm/cross_cutting/_test_runner.py +36 -0
  5. clm/cross_cutting/async_utils.py +25 -0
  6. clm/cross_cutting/cel_builder.py +123 -0
  7. clm/cross_cutting/cel_converter.py +697 -0
  8. clm/cross_cutting/cel_engine.py +252 -0
  9. clm/cross_cutting/cel_ops.py +72 -0
  10. clm/cross_cutting/cel_ops_db.py +157 -0
  11. clm/cross_cutting/cel_ops_files.py +99 -0
  12. clm/cross_cutting/cel_ops_state.py +71 -0
  13. clm/cross_cutting/cel_ops_strings.py +64 -0
  14. clm/cross_cutting/cel_resolver.py +63 -0
  15. clm/cross_cutting/cel_slices.py +56 -0
  16. clm/cross_cutting/cel_store.py +330 -0
  17. clm/cross_cutting/clm_logger.py +140 -0
  18. clm/cross_cutting/config/__init__.py +155 -0
  19. clm/cross_cutting/config/config_constants.py +392 -0
  20. clm/cross_cutting/config/env_parameters.py +90 -0
  21. clm/cross_cutting/config/logging.py +378 -0
  22. clm/cross_cutting/config/settings.py +504 -0
  23. clm/cross_cutting/context.py +5 -0
  24. clm/cross_cutting/domain_models.py +55 -0
  25. clm/cross_cutting/domain_types.py +61 -0
  26. clm/cross_cutting/effects.py +67 -0
  27. clm/cross_cutting/errors.py +153 -0
  28. clm/cross_cutting/governance.py +331 -0
  29. clm/cross_cutting/guards.py +41 -0
  30. clm/cross_cutting/mcard.py +321 -0
  31. clm/cross_cutting/native.py +185 -0
  32. clm/cross_cutting/observability.py +289 -0
  33. clm/cross_cutting/pcard.py +434 -0
  34. clm/cross_cutting/registry.py +71 -0
  35. clm/cross_cutting/resources.py +84 -0
  36. clm/cross_cutting/secrets.py +44 -0
  37. clm/cross_cutting/subprocess_utils.py +118 -0
  38. clm/cross_cutting/telemetry.py +164 -0
  39. clm/cross_cutting/testing/__init__.py +8 -0
  40. clm/cross_cutting/testing/comparator.py +187 -0
  41. clm/cross_cutting/testing/datasets.py +87 -0
  42. clm/cross_cutting/timeutil.py +20 -0
  43. clm/cross_cutting/types/new_type_check.py +0 -0
  44. clm/cross_cutting/utils/__init__.py +1 -0
  45. clm/cross_cutting/utils/url_safety.py +50 -0
  46. clm/cross_cutting/vcard.py +560 -0
  47. clm/cross_cutting/writer.py +118 -0
  48. clm/layer0/README.md +50 -0
  49. clm/layer0/__init__.py +223 -0
  50. clm/layer0/algebra.py +60 -0
  51. clm/layer0/algebra_baldwin.py +133 -0
  52. clm/layer0/algebra_baldwin_generators.py +36 -0
  53. clm/layer0/algebra_equivalence.py +262 -0
  54. clm/layer0/algebra_ingest.py +306 -0
  55. clm/layer0/algebra_manifest_io.py +156 -0
  56. clm/layer0/assembler.py +481 -0
  57. clm/layer0/cel/__init__.py +23 -0
  58. clm/layer0/cel_eval.py +491 -0
  59. clm/layer0/codec.py +106 -0
  60. clm/layer0/context.py +122 -0
  61. clm/layer0/db.py +160 -0
  62. clm/layer0/exceptions.py +73 -0
  63. clm/layer0/fibration.py +106 -0
  64. clm/layer0/gates.py +50 -0
  65. clm/layer0/hash.py +80 -0
  66. clm/layer0/loader.py +826 -0
  67. clm/layer0/math_utils.py +163 -0
  68. clm/layer0/mcard.py +96 -0
  69. clm/layer0/model/__init__.py +0 -0
  70. clm/layer0/model/action.py +223 -0
  71. clm/layer0/model/card.py +280 -0
  72. clm/layer0/model/card_triad.py +427 -0
  73. clm/layer0/model/compatibility.py +60 -0
  74. clm/layer0/model/dictionary.py +46 -0
  75. clm/layer0/model/dots.py +331 -0
  76. clm/layer0/model/event_producer.py +88 -0
  77. clm/layer0/model/g_time.py +89 -0
  78. clm/layer0/model/handle.py +163 -0
  79. clm/layer0/model/hash/__init__.py +6 -0
  80. clm/layer0/model/hash/algorithms/__init__.py +3 -0
  81. clm/layer0/model/hash/algorithms/custom_hash.py +7 -0
  82. clm/layer0/model/hash/algorithms/local_sha256.py +178 -0
  83. clm/layer0/model/hash/constants.py +53 -0
  84. clm/layer0/model/hash/enums.py +60 -0
  85. clm/layer0/model/hash/validator.py +307 -0
  86. clm/layer0/model/interpreter.py +275 -0
  87. clm/layer0/model/pagination.py +45 -0
  88. clm/layer0/model/pcard.py +716 -0
  89. clm/layer0/model/schema.py +44 -0
  90. clm/layer0/model/utils/__init__.py +1 -0
  91. clm/layer0/model/utils/content_analyzer.py +152 -0
  92. clm/layer0/model/validators/__init__.py +1 -0
  93. clm/layer0/model/validators/base_validator.py +44 -0
  94. clm/layer0/model/validators/binary_validator.py +66 -0
  95. clm/layer0/model/validators/text_validator.py +82 -0
  96. clm/layer0/model/validators/validation_registry.py +49 -0
  97. clm/layer0/model/vcard.py +823 -0
  98. clm/layer0/model/vcard_ext/__init__.py +39 -0
  99. clm/layer0/model/vcard_ext/core.py +60 -0
  100. clm/layer0/model/vcard_ext/network.py +23 -0
  101. clm/layer0/model/vcard_ext/observability.py +63 -0
  102. clm/layer0/model/vcard_ext/storage.py +60 -0
  103. clm/layer0/model/vcard_ext/vendors.py +211 -0
  104. clm/layer0/model/vcard_sandwich.py +119 -0
  105. clm/layer0/model/vcard_vocabulary.py +463 -0
  106. clm/layer0/model/workflow.py +274 -0
  107. clm/layer0/narrative.py +431 -0
  108. clm/layer0/ontology/collection.py +125 -0
  109. clm/layer0/parser.py +429 -0
  110. clm/layer0/relations.py +73 -0
  111. clm/layer0/rule_evaluator.py +251 -0
  112. clm/layer0/schema/__init__.py +38 -0
  113. clm/layer0/schema/ddl.py +97 -0
  114. clm/layer0/templates/abstract.yaml +99 -0
  115. clm/layer0/templates/balanced.yaml +253 -0
  116. clm/layer0/templates/concrete.yaml +172 -0
  117. clm/layer0/type_registry.py +223 -0
  118. clm/layer0/types.py +204 -0
  119. clm/layer0/utils.py +886 -0
  120. clm/layer0/verifier_core.py +262 -0
  121. clm/layer1/__init__.py +31 -0
  122. clm/layer1/action_dispatcher.py +275 -0
  123. clm/layer1/adapter_registry.py +233 -0
  124. clm/layer1/algebra_baldwin_generators.py +192 -0
  125. clm/layer1/arrow_compiler.py +525 -0
  126. clm/layer1/batch_processor.py +152 -0
  127. clm/layer1/cel/__init__.py +27 -0
  128. clm/layer1/cel/builder.py +173 -0
  129. clm/layer1/engine.py +759 -0
  130. clm/layer1/engine_async.py +89 -0
  131. clm/layer1/eval_callback.py +49 -0
  132. clm/layer1/gate_composer.py +229 -0
  133. clm/layer1/hoare_sandwich.py +298 -0
  134. clm/layer1/identity_guard.py +348 -0
  135. clm/layer1/matrix.py +138 -0
  136. clm/layer1/neural_runtime.py +221 -0
  137. clm/layer1/operations/__init__.py +123 -0
  138. clm/layer1/operations/augment.py +156 -0
  139. clm/layer1/operations/base.py +109 -0
  140. clm/layer1/operations/builtins.py +338 -0
  141. clm/layer1/operations/dispatch.py +144 -0
  142. clm/layer1/operations/exclude.py +107 -0
  143. clm/layer1/operations/handle.py +197 -0
  144. clm/layer1/operations/identity.py +139 -0
  145. clm/layer1/operations/invert.py +66 -0
  146. clm/layer1/operations/loader.py +116 -0
  147. clm/layer1/operations/manipulators/__init__.py +23 -0
  148. clm/layer1/operations/manipulators/document.py +211 -0
  149. clm/layer1/operations/manipulators/media.py +134 -0
  150. clm/layer1/operations/manipulators/structured.py +159 -0
  151. clm/layer1/operations/manipulators/tabular.py +334 -0
  152. clm/layer1/operations/port.py +65 -0
  153. clm/layer1/operations/services.py +529 -0
  154. clm/layer1/operations/split.py +117 -0
  155. clm/layer1/operations/substitute.py +75 -0
  156. clm/layer1/petri.py +1052 -0
  157. clm/layer1/pocketflow_orchestrator.py +408 -0
  158. clm/layer1/pocketflow_scheduler.py +519 -0
  159. clm/layer1/protocols.py +197 -0
  160. clm/layer1/runtime_adapter.py +718 -0
  161. clm/layer1/runtimes/__init__.py +71 -0
  162. clm/layer1/runtimes/_generated_assertions.py +125 -0
  163. clm/layer1/runtimes/_generated_types.py +42 -0
  164. clm/layer1/runtimes/base.py +265 -0
  165. clm/layer1/runtimes/binary.py +101 -0
  166. clm/layer1/runtimes/factory.py +203 -0
  167. clm/layer1/runtimes/javascript.py +321 -0
  168. clm/layer1/runtimes/javascript_runtime.js +33 -0
  169. clm/layer1/runtimes/js_scripts/isomorphism.mjs +22 -0
  170. clm/layer1/runtimes/js_scripts/loader.mjs +52 -0
  171. clm/layer1/runtimes/lambda_calc.py +126 -0
  172. clm/layer1/runtimes/python.py +288 -0
  173. clm/layer1/runtimes/python_runtime.py +41 -0
  174. clm/layer1/runtimes/script.py +114 -0
  175. clm/layer1/sandbox.py +334 -0
  176. clm/layer1/savepoint_guard.py +136 -0
  177. clm/layer1/sparse_net.py +122 -0
  178. clm/layer1/spec_tester.py +165 -0
  179. clm/layer1/store.py +295 -0
  180. clm/layer1/test_runner.py +498 -0
  181. clm/layer1/type_inspector.py +166 -0
  182. clm/layer1/verifier.py +772 -0
  183. clm/layer1/vm.py +91 -0
  184. clm/layer2/__init__.py +78 -0
  185. clm/layer2/card_collection.py +678 -0
  186. clm/layer2/classifier.py +479 -0
  187. clm/layer2/engine/__init__.py +1 -0
  188. clm/layer2/engine/abstract_sql_engine.py +320 -0
  189. clm/layer2/engine/base.py +193 -0
  190. clm/layer2/engine/duckdb_engine.py +576 -0
  191. clm/layer2/engine/sqlite_engine.py +518 -0
  192. clm/layer2/fiber/__init__.py +31 -0
  193. clm/layer2/fiber/context.py +89 -0
  194. clm/layer2/fiber/disposable.py +163 -0
  195. clm/layer2/fiber/fiber.py +125 -0
  196. clm/layer2/fiber/hoare.py +191 -0
  197. clm/layer2/file_io.py +376 -0
  198. clm/layer2/file_registrar.py +77 -0
  199. clm/layer2/ingest.py +202 -0
  200. clm/layer2/lineage.py +322 -0
  201. clm/layer2/mcard_fs.py +262 -0
  202. clm/layer2/merkle.py +11 -0
  203. clm/layer2/mime.py +244 -0
  204. clm/layer2/mime_detector.py +245 -0
  205. clm/layer2/private_collection.py +118 -0
  206. clm/layer2/shared_store.py +11 -0
  207. clm/layer2/storage/__init__.py +190 -0
  208. clm/layer2/storage/db_bitemporal.py +141 -0
  209. clm/layer2/storage/db_driver.py +331 -0
  210. clm/layer2/storage/db_hyperlinks.py +214 -0
  211. clm/layer2/storage/db_pool.py +139 -0
  212. clm/layer2/storage/db_repository.py +229 -0
  213. clm/layer2/storage/savepoint.py +78 -0
  214. clm/layer2/storage/sqlite_wal.py +74 -0
  215. clm/layer2/tridb.py +245 -0
  216. clm/layer2/vcard_receipt.py +71 -0
  217. clm/layer2/vfs.py +17 -0
  218. clm/layer3/__init__.py +141 -0
  219. clm/layer3/agency/__init__.py +19 -0
  220. clm/layer3/agency/config.py +220 -0
  221. clm/layer3/agency/providers/__init__.py +15 -0
  222. clm/layer3/agency/providers/base.py +91 -0
  223. clm/layer3/agency/providers/mlc_llm.py +169 -0
  224. clm/layer3/agency/providers/ollama.py +203 -0
  225. clm/layer3/agency/router.py +71 -0
  226. clm/layer3/agency/runtime.py +524 -0
  227. clm/layer3/gateway.py +353 -0
  228. clm/layer3/open_interpreter_adapter.py +159 -0
  229. clm/layer3/rag/__init__.py +70 -0
  230. clm/layer3/rag/cli.py +228 -0
  231. clm/layer3/rag/config.py +153 -0
  232. clm/layer3/rag/embeddings/__init__.py +16 -0
  233. clm/layer3/rag/embeddings/base.py +79 -0
  234. clm/layer3/rag/embeddings/ollama.py +211 -0
  235. clm/layer3/rag/embeddings/vision.py +290 -0
  236. clm/layer3/rag/engine.py +276 -0
  237. clm/layer3/rag/graph/__init__.py +22 -0
  238. clm/layer3/rag/graph/community.py +198 -0
  239. clm/layer3/rag/graph/engine.py +433 -0
  240. clm/layer3/rag/graph/extractor.py +255 -0
  241. clm/layer3/rag/graph/schema.py +115 -0
  242. clm/layer3/rag/graph/store.py +641 -0
  243. clm/layer3/rag/indexer.py +333 -0
  244. clm/layer3/rag/llm_providers.json +52 -0
  245. clm/layer3/rag/semantic_versioning.py +313 -0
  246. clm/layer3/rag/vector/__init__.py +28 -0
  247. clm/layer3/rag/vector/handle_vector_store.py +749 -0
  248. clm/layer3/rag/vector/schema.py +151 -0
  249. clm/layer3/rag/vector/store.py +632 -0
  250. clm/layer3/reticulum/__init__.py +55 -0
  251. clm/layer3/reticulum/bridge.py +74 -0
  252. clm/layer3/reticulum/daemon.py +88 -0
  253. clm/layer3/reticulum/discovery.py +164 -0
  254. clm/layer3/reticulum/identity.py +107 -0
  255. clm/layer3/reticulum/media.py +148 -0
  256. clm/layer3/reticulum/transport.py +133 -0
  257. clm/layer3/satori/__init__.py +209 -0
  258. clm/layer3/satori/alpha_conversion.py +168 -0
  259. clm/layer3/satori/beta_reduction.py +359 -0
  260. clm/layer3/satori/continuation.py +38 -0
  261. clm/layer3/satori/eta_conversion.py +205 -0
  262. clm/layer3/satori/free_variables.py +163 -0
  263. clm/layer3/satori/io_effects.py +370 -0
  264. clm/layer3/satori/lambda_runtime.py +726 -0
  265. clm/layer3/satori/lambda_term.py +230 -0
  266. clm/layer3/satori/sheaf_audit.py +261 -0
  267. clm/layer3/satori/speech_act.py +279 -0
  268. clm/layer4/README.md +9 -0
  269. clm/layer4/__init__.py +67 -0
  270. clm/layer4/_sovereign_executor.py +580 -0
  271. clm/layer4/action_commands.py +719 -0
  272. clm/layer4/api.py +236 -0
  273. clm/layer4/bootstrap/__init__.py +13 -0
  274. clm/layer4/bootstrap/bootstrapper.py +118 -0
  275. clm/layer4/bootstrap/cleanup.py +44 -0
  276. clm/layer4/bootstrap/clm_hooks.py +49 -0
  277. clm/layer4/bootstrap/genesis.py +77 -0
  278. clm/layer4/bootstrap/injection.py +125 -0
  279. clm/layer4/cli.py +549 -0
  280. clm/layer4/collection_manager.py +553 -0
  281. clm/layer4/commands/__init__.py +81 -0
  282. clm/layer4/commands/action_cmd.py +42 -0
  283. clm/layer4/commands/check_cmd.py +82 -0
  284. clm/layer4/commands/envelope.py +73 -0
  285. clm/layer4/commands/evaluate_cmd.py +224 -0
  286. clm/layer4/commands/mcard_cmd.py +24 -0
  287. clm/layer4/commands/petri_cmd.py +92 -0
  288. clm/layer4/commands/tridb_cmd.py +319 -0
  289. clm/layer4/commands/version_cmd.py +27 -0
  290. clm/layer4/diff_commands.py +167 -0
  291. clm/layer4/eoa_sponsor.py +232 -0
  292. clm/layer4/events.py +69 -0
  293. clm/layer4/flux_gateway.py +133 -0
  294. clm/layer4/gateway.py +91 -0
  295. clm/layer4/loader.py +307 -0
  296. clm/layer4/mcard_commands.py +166 -0
  297. clm/layer4/membrane.py +273 -0
  298. clm/layer4/navigation.py +50 -0
  299. clm/layer4/protocol/protocol_entry_python.py +108 -0
  300. clm/layer4/protocol/python_sync.py +126 -0
  301. clm/layer4/runner.py +150 -0
  302. clm/layer4/satori.py +262 -0
  303. clm/layer4/server/python_sync_client.py +150 -0
  304. clm/layer4/server/python_sync_server.py +139 -0
  305. clm/layer4/server/service_api.py +315 -0
  306. clm/layer4/server/start_servers.py +107 -0
  307. clm/layer4/server/stop_servers.py +24 -0
  308. clm/layer4/simulated_optimization_fix.py +0 -0
  309. clm/layer4/storage.py +463 -0
  310. clm/layer4/tridb_admin.py +268 -0
  311. clm/layer4/websocket/test_ws_client.py +104 -0
  312. clm/layer4/websocket/test_ws_server.py +138 -0
  313. clm/layer4/websocket/ws_server_local.py +160 -0
  314. clm/layer5/__init__.py +51 -0
  315. clm/layer5/async_batch_writer.py +133 -0
  316. clm/layer5/learning.py +276 -0
  317. clm/layer5/telemetry_hook.py +107 -0
  318. clm/layer5/type_lattice.py +238 -0
  319. clm/py.typed +0 -0
  320. clm/schemas/__init__.py +652 -0
  321. clm/schemas/abstract_face_schema.yaml +77 -0
  322. clm/schemas/cel_schema.yaml +416 -0
  323. clm/schemas/lifecycle/__init__.py +45 -0
  324. clm/schemas/lifecycle/models.py +123 -0
  325. clm/schemas/lifecycle/service.py +364 -0
  326. clm/schemas/mcard_schema.sql +192 -0
  327. clm/schemas/mcard_vector_schema.sql +283 -0
  328. clm/schemas/mlp-context-v1.json +91 -0
  329. clm_kernel-0.0.0.dist-info/METADATA +121 -0
  330. clm_kernel-0.0.0.dist-info/RECORD +333 -0
  331. clm_kernel-0.0.0.dist-info/WHEEL +4 -0
  332. clm_kernel-0.0.0.dist-info/entry_points.txt +3 -0
  333. clm_kernel-0.0.0.dist-info/licenses/LICENSE +21 -0
clm/layer4/runner.py ADDED
@@ -0,0 +1,150 @@
1
+ """CLM Runner - The standard entrypoint for executing YAML CLM definitions.
2
+
3
+ This module provides the `CLMRunner` class which ingests YAML chapters
4
+ and processes them via the formal PTREngine.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import os
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import yaml
15
+
16
+ from clm.layer0.loader import CLMChapterLoader
17
+ from clm.layer0.model.card import MCard
18
+ from clm.layer0.model.pcard import PCard
19
+ from clm.layer0.model.vcard_sandwich import VCardSandwich
20
+ from clm.layer1.engine import PTREngine
21
+
22
+
23
+ class CLMRunner:
24
+ """Unified Runner for CLM execution.
25
+
26
+ Ingests .yaml configurations, orchestrates the PTR Sandwiches, and issues reports.
27
+ """
28
+
29
+ def __init__(self, collection: Any = None, private_collection: Any = None) -> None:
30
+ self.logger = logging.getLogger(__name__)
31
+ self._engine = PTREngine(
32
+ storage_collection=collection,
33
+ execution_log_collection=private_collection,
34
+ )
35
+ self.collection = self._engine.collection
36
+ self.private_collection = private_collection
37
+
38
+ def run_file(
39
+ self, file_path: str, context: dict[str, Any] | None = None
40
+ ) -> dict[str, Any]:
41
+ """Execute a CLM specification from a YAML file."""
42
+ if not os.path.exists(file_path):
43
+ raise FileNotFoundError(f"File not found: {file_path}")
44
+
45
+ with open(file_path) as f:
46
+ content_str = f.read()
47
+ try:
48
+ data = yaml.safe_load(content_str)
49
+ except yaml.YAMLError as e:
50
+ raise ValueError(f"Invalid YAML file: {e}") from e
51
+
52
+ context = context or {}
53
+ context.setdefault("pcard_dir", str(Path(file_path).parent.absolute()))
54
+
55
+ if (
56
+ "chapter" in data
57
+ or "clm" in data
58
+ or ("abstract" in data and "concrete" in data)
59
+ ):
60
+ return self.run_chapter(file_path, data, content_str, context)
61
+ else:
62
+ raise ValueError(
63
+ "Unknown file format. Expected 'chapter', 'clm', or 'abstract'/'concrete' keys."
64
+ )
65
+
66
+ def run_chapter(
67
+ self,
68
+ file_path: str,
69
+ data: dict[str, Any],
70
+ content_str: str,
71
+ context: dict[str, Any],
72
+ ) -> dict[str, Any]:
73
+ """Execute a CLM Chapter through the formal PTR lifecycle."""
74
+ self.logger.info(f"Executing Chapter from: {file_path}")
75
+
76
+ pcard = PCard(content_str)
77
+ vcard_manifest = context.get("vcard_manifest", {})
78
+ gatekeeper_status = pcard.can_fire(vcard_manifest)
79
+
80
+ if not gatekeeper_status["can_fire"]:
81
+ missing = gatekeeper_status["missing"]
82
+ error_msg = f"SecurityError: Gatekeeper Rejection. Missing required VCards: {missing}"
83
+ self.logger.error(error_msg)
84
+ if context.get("enforce_gatekeeper", False):
85
+ raise PermissionError(error_msg)
86
+ else:
87
+ self.logger.warning(
88
+ "Gatekeeper check failed but enforcement is optional. Proceeding."
89
+ )
90
+
91
+ chapter = CLMChapterLoader.load_from_yaml(file_path)
92
+
93
+ clm_section = data.get("clm")
94
+ if clm_section:
95
+ concrete_config = clm_section.get("concrete", {})
96
+ balanced_config = clm_section.get("balanced", {})
97
+ else:
98
+ concrete_config = data.get("concrete", {})
99
+ balanced_config = data.get("balanced", {})
100
+
101
+ run_ctx: dict[str, Any] = {
102
+ "runtimes_config": concrete_config.get("runtimes_config", []),
103
+ "balanced": balanced_config,
104
+ "examples": data.get("examples", []),
105
+ }
106
+ run_ctx.update(context)
107
+ for k, v in concrete_config.items():
108
+ if k not in run_ctx:
109
+ run_ctx[k] = v
110
+
111
+ input_content = context.get("__input_content__", content_str)
112
+ input_mcard = MCard(input_content)
113
+ v_pre = VCardSandwich.witness_precondition(input_mcard)
114
+
115
+ result, new_state, logs = chapter.run(run_ctx, {"collection": self.collection})
116
+
117
+ if isinstance(result, dict):
118
+ if "consensus" in result:
119
+ is_success = bool(result["consensus"])
120
+ elif "success" in result:
121
+ is_success = bool(result["success"])
122
+ else:
123
+ is_success = "error" not in result
124
+ else:
125
+ is_success = result is not None
126
+
127
+ v_post = VCardSandwich.witness_postcondition(result, pcard_hash=pcard.hash)
128
+ sandwich = VCardSandwich.sandwich(v_pre, v_post, pcard_hash=pcard.hash)
129
+
130
+ event_record_hash = None
131
+ try:
132
+ self._engine.execution_log.add(sandwich)
133
+ event_record_hash = sandwich.hash
134
+ self.logger.info(
135
+ f"Generated VCard Sandwich proof: {event_record_hash[:16]}"
136
+ )
137
+ except (ValueError, TypeError, KeyError) as e:
138
+ self.logger.warning(f"Failed to store VCard Sandwich: {e}")
139
+
140
+ return {
141
+ "status": "success" if is_success else "failure",
142
+ "result": result,
143
+ "logs": logs,
144
+ "chapter_id": chapter.id,
145
+ "chapter_title": chapter.title,
146
+ "event_record_hash": event_record_hash,
147
+ "v_pre_hash": v_pre.hash,
148
+ "v_post_hash": v_post.hash,
149
+ "sandwich_hash": sandwich.hash if sandwich else None,
150
+ }
clm/layer4/satori.py ADDED
@@ -0,0 +1,262 @@
1
+ """Satori Message AST, Speech Act Calculus & Conversational Substrate.
2
+ Canonical Path: kernel/scripts/clm/layer4/satori.py
3
+ Deliverable: DEL-254-03
4
+
5
+ Parity with Rust `satori::element::SatoriMessage` and `satori::mcard_codec`
6
+ for Layer 4 Generative Hypermedia Surface.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from typing import Any, Literal
13
+
14
+ from pydantic import BaseModel, ConfigDict, Field
15
+
16
+ from clm.cross_cutting.domain_models import MCard
17
+ from clm.layer0.utils import clm_hash_string
18
+
19
+ SpeechActType = Literal[
20
+ "assertive",
21
+ "directive",
22
+ "commissive",
23
+ "expressive",
24
+ "declarative",
25
+ ]
26
+
27
+
28
+ class SatoriElement(BaseModel):
29
+ """Canonical Satori message element representation."""
30
+
31
+ model_config = ConfigDict(frozen=True, extra="ignore")
32
+
33
+ element_type: str = Field(alias="type")
34
+ text: str | None = None
35
+ id: str | None = None
36
+ src: str | None = None
37
+ label: str | None = None
38
+
39
+ @classmethod
40
+ def text_elem(cls, text: str) -> SatoriElement:
41
+ return cls(type="text", text=text)
42
+
43
+ @classmethod
44
+ def at_elem(cls, user_id: str) -> SatoriElement:
45
+ return cls(type="at", id=user_id)
46
+
47
+ @classmethod
48
+ def quote_elem(cls, message_id: str) -> SatoriElement:
49
+ return cls(type="quote", id=message_id)
50
+
51
+ @classmethod
52
+ def image_elem(cls, src: str) -> SatoriElement:
53
+ return cls(type="image", src=src)
54
+
55
+ @classmethod
56
+ def audio_elem(cls, src: str) -> SatoriElement:
57
+ return cls(type="audio", src=src)
58
+
59
+ @classmethod
60
+ def button_elem(cls, button_id: str, label: str) -> SatoriElement:
61
+ return cls(type="button", id=button_id, label=label)
62
+
63
+ @classmethod
64
+ def action_elem(cls, action_id: str) -> SatoriElement:
65
+ return cls(type="action", id=action_id)
66
+
67
+ def to_xml(self) -> str:
68
+ """Serializes an element into canonical XML string."""
69
+ if self.element_type == "text":
70
+ return f"<text>{_escape_xml(self.text or '')}</text>"
71
+ elif self.element_type == "at":
72
+ return f'<at id="{_escape_xml(self.id or "")}"/>'
73
+ elif self.element_type == "quote":
74
+ return f'<quote id="{_escape_xml(self.id or "")}"/>'
75
+ elif self.element_type == "image":
76
+ return f'<image src="{_escape_xml(self.src or "")}"/>'
77
+ elif self.element_type == "audio":
78
+ return f'<audio src="{_escape_xml(self.src or "")}"/>'
79
+ elif self.element_type == "button":
80
+ return f'<button id="{_escape_xml(self.id or "")}" label="{_escape_xml(self.label or "")}"/>'
81
+ elif self.element_type == "action":
82
+ return f'<action id="{_escape_xml(self.id or "")}"/>'
83
+ return ""
84
+
85
+
86
+ class SatoriMessage(BaseModel):
87
+ """Normalized Satori message speech act."""
88
+
89
+ model_config = ConfigDict(frozen=True, extra="ignore")
90
+
91
+ id: str
92
+ channel_id: str
93
+ user_did: str
94
+ elements: list[SatoriElement] = Field(default_factory=list)
95
+ timestamp: int
96
+
97
+ def content_hash(self) -> str:
98
+ """Computes BLAKE3 content-address digest of canonical JSON."""
99
+ raw = json.dumps(self.model_dump(by_alias=True), sort_keys=True, separators=(",", ":"))
100
+ return clm_hash_string(raw)
101
+
102
+ def to_xml(self) -> str:
103
+ """Serializes message elements to Satori XML fragment."""
104
+ return "".join(e.to_xml() for e in self.elements)
105
+
106
+ def to_mcard(self) -> dict[str, Any]:
107
+ """Converts message to canonical MCard dictionary (legacy dict format)."""
108
+ return {
109
+ "mcard_uri": f"mcard:chat/message/{self.id}",
110
+ "type": "clm:types:chat:satori_message",
111
+ "header": {
112
+ "id": self.id,
113
+ "channel_id": self.channel_id,
114
+ "user_did": self.user_did,
115
+ "timestamp": self.timestamp,
116
+ },
117
+ "elements": [e.model_dump(by_alias=True, exclude_none=True) for e in self.elements],
118
+ "content_hash": self.content_hash(),
119
+ }
120
+
121
+ @classmethod
122
+ def from_mcard(cls, value: dict[str, Any]) -> SatoriMessage:
123
+ header = value.get("header", {})
124
+ elements_data = value.get("elements", [])
125
+ elements = [SatoriElement(**ed) for ed in elements_data]
126
+ return cls(
127
+ id=header.get("id", ""),
128
+ channel_id=header.get("channel_id", ""),
129
+ user_did=header.get("user_did", ""),
130
+ elements=elements,
131
+ timestamp=int(header.get("timestamp", 0)),
132
+ )
133
+
134
+
135
+ class BaseSpeechAct(BaseModel):
136
+ """Base class for Searle-Austin speech act taxonomy."""
137
+
138
+ model_config = ConfigDict(frozen=True)
139
+
140
+ speech_act_type: SpeechActType
141
+ message: SatoriMessage
142
+
143
+
144
+ class AssertiveSpeechAct(BaseSpeechAct):
145
+ speech_act_type: SpeechActType = "assertive"
146
+
147
+
148
+ class DirectiveSpeechAct(BaseSpeechAct):
149
+ speech_act_type: SpeechActType = "directive"
150
+
151
+
152
+ class CommissiveSpeechAct(BaseSpeechAct):
153
+ speech_act_type: SpeechActType = "commissive"
154
+
155
+
156
+ class ExpressiveSpeechAct(BaseSpeechAct):
157
+ speech_act_type: SpeechActType = "expressive"
158
+
159
+
160
+ class DeclarativeSpeechAct(BaseSpeechAct):
161
+ speech_act_type: SpeechActType = "declarative"
162
+
163
+
164
+ def classify_speech_act(msg_or_card: SatoriMessage | MCard) -> SpeechActType:
165
+ """Classifies a SatoriMessage or MCard into one of 5 Searle-Austin speech act classes."""
166
+ if isinstance(msg_or_card, MCard):
167
+ act_type = msg_or_card.metadata.get("speech_act_type")
168
+ if act_type in ("assertive", "directive", "commissive", "expressive", "declarative"):
169
+ return act_type # type: ignore
170
+ if isinstance(msg_or_card.payload, dict) and "speech_act_type" in msg_or_card.payload:
171
+ return msg_or_card.payload["speech_act_type"] # type: ignore
172
+ return "assertive"
173
+
174
+ # Inspect Satori elements
175
+ for elem in msg_or_card.elements:
176
+ if elem.element_type in ("action", "button", "execute"):
177
+ return "directive"
178
+
179
+ # Inspect textual keywords
180
+ text_content = " ".join(e.text for e in msg_or_card.elements if e.text).lower()
181
+ if "?" in text_content or text_content.startswith("please ") or text_content.startswith("can you "):
182
+ return "directive"
183
+ if "promise" in text_content or "i will " in text_content or "committed" in text_content:
184
+ return "commissive"
185
+ if any(w in text_content for w in ("thank", "congrat", "great", "sorry")):
186
+ return "expressive"
187
+ if any(w in text_content for w in ("declared", "witnessed:", "receipt:")):
188
+ return "declarative"
189
+
190
+ return "assertive"
191
+
192
+
193
+ def satori_to_mcard(
194
+ msg: SatoriMessage,
195
+ speech_act_type: SpeechActType | None = None,
196
+ ) -> MCard:
197
+ """Converts a SatoriMessage into an immutable content-addressed MCard."""
198
+ act_type = speech_act_type or classify_speech_act(msg)
199
+ uri = f"mcard:chat/message/{msg.id}"
200
+ metadata = {
201
+ "speech_act_type": act_type,
202
+ "satori_id": msg.id,
203
+ "channel_id": msg.channel_id,
204
+ "user_did": msg.user_did,
205
+ "timestamp": msg.timestamp,
206
+ }
207
+ payload = {
208
+ "header": {
209
+ "id": msg.id,
210
+ "channel_id": msg.channel_id,
211
+ "user_did": msg.user_did,
212
+ "timestamp": msg.timestamp,
213
+ },
214
+ "elements": [e.model_dump(by_alias=True, exclude_none=True) for e in msg.elements],
215
+ "speech_act_type": act_type,
216
+ }
217
+ return MCard.create(
218
+ uri=uri,
219
+ payload=payload,
220
+ metadata=metadata,
221
+ author=msg.user_did,
222
+ sequence=msg.timestamp,
223
+ )
224
+
225
+
226
+ def mcard_to_satori(card: MCard) -> SatoriMessage:
227
+ """Reconstructs a SatoriMessage from an MCard."""
228
+ if isinstance(card.payload, dict):
229
+ header = card.payload.get("header") or {
230
+ "id": card.metadata.get("satori_id") or card.uri.replace("mcard:chat/message/", ""),
231
+ "channel_id": card.metadata.get("channel_id", ""),
232
+ "user_did": card.metadata.get("user_did") or str(card.author),
233
+ "timestamp": card.metadata.get("timestamp") or card.sequence,
234
+ }
235
+ elements_raw = card.payload.get("elements") or []
236
+ elements = [SatoriElement(**ed) for ed in elements_raw]
237
+ return SatoriMessage(
238
+ id=header.get("id", ""),
239
+ channel_id=header.get("channel_id", ""),
240
+ user_did=header.get("user_did", ""),
241
+ elements=elements,
242
+ timestamp=int(header.get("timestamp", 0)),
243
+ )
244
+
245
+ # Fallback to text element
246
+ return SatoriMessage(
247
+ id=card.metadata.get("satori_id") or card.uri.replace("mcard:chat/message/", ""),
248
+ channel_id=card.metadata.get("channel_id", ""),
249
+ user_did=card.metadata.get("user_did") or str(card.author),
250
+ elements=[SatoriElement.text_elem(str(card.payload))],
251
+ timestamp=card.sequence,
252
+ )
253
+
254
+
255
+ def _escape_xml(s: str) -> str:
256
+ return (
257
+ s.replace("&", "&amp;")
258
+ .replace("<", "&lt;")
259
+ .replace(">", "&gt;")
260
+ .replace('"', "&quot;")
261
+ .replace("'", "&apos;")
262
+ )
@@ -0,0 +1,150 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Cross-Runtime Communication Demo: Python Sync Client
4
+
5
+ This connects to a JavaScript sync server and demonstrates:
6
+ 1. Pulling MCards created by JavaScript
7
+ 2. Pushing new MCards created by Python
8
+ 3. Cross-language MCard synchronization
9
+ """
10
+
11
+ import json
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ # Add the project root to path
16
+ sys.path.insert(0, str(Path(__file__).parent.parent))
17
+
18
+ import os
19
+
20
+ from clm.layer0.model.card import MCard
21
+ from clm.layer2.card_collection import CardCollection
22
+
23
+ try:
24
+ from clm.layer3.satori.network_runtime import NetworkRuntime
25
+ except ImportError:
26
+ NetworkRuntime = None
27
+
28
+ SYNC_URL = os.environ.get("MCARD_SYNC_URL", "http://localhost:3001/sync")
29
+ MANIFEST_URL = (
30
+ SYNC_URL + "/manifest" if not SYNC_URL.endswith("/") else SYNC_URL + "manifest"
31
+ )
32
+
33
+
34
+ def main():
35
+ print("\n" + "=" * 60)
36
+ print(" Python Sync Client - Cross-Runtime Demo")
37
+ print("=" * 60 + "\n")
38
+
39
+ # Create a collection with seed data
40
+ collection = CardCollection(db_path=":memory:")
41
+ runtime = NetworkRuntime(collection)
42
+
43
+ # Add Python MCards as seed data
44
+ seed_cards = [
45
+ MCard("Hello from Python Client! 🐍"),
46
+ MCard("Python PTR Client is ready"),
47
+ MCard(
48
+ json.dumps(
49
+ {"origin": "python-client", "timestamp": __import__("time").time()}
50
+ )
51
+ ),
52
+ ]
53
+
54
+ for card in seed_cards:
55
+ collection.add(card)
56
+
57
+ print(f"[Python Client] Created collection with {len(seed_cards)} seed MCards:")
58
+ for card in seed_cards:
59
+ content = card.get_content()
60
+ if isinstance(content, bytes):
61
+ content = content.decode("utf-8")
62
+ print(f" • {card.hash[:16]}... = '{content[:50]}'")
63
+ print()
64
+
65
+ # Test connection to JavaScript server
66
+ print("[Python Client] Testing connection to JavaScript server...")
67
+ try:
68
+ health_result = runtime.execute(
69
+ {"builtin": "http_get", "config": {"url": MANIFEST_URL}}, MCard("dummy"), {}
70
+ )
71
+
72
+ if isinstance(health_result, dict) and health_result.get("success"):
73
+ body = health_result.get("body", [])
74
+ print(
75
+ f"[Python Client] ✅ Connected to JavaScript server! Found {len(body) if isinstance(body, list) else 0} remote cards.\n"
76
+ )
77
+ else:
78
+ print(f"[Python Client] ✅ Connection response: {health_result}\n")
79
+ except Exception as e:
80
+ print(f"[Python Client] ❌ Connection failed: {e}")
81
+ print(
82
+ "Make sure the JavaScript server is running: npx tsx examples/js-sync-server.ts"
83
+ )
84
+ sys.exit(1)
85
+
86
+ # Step 1: Pull MCards from JavaScript
87
+ print("[Python Client] Step 1: Pulling MCards from JavaScript server...")
88
+
89
+ pull_result = runtime.execute(
90
+ {"builtin": "mcard_sync", "config": {"url": SYNC_URL, "mode": "pull"}},
91
+ MCard("dummy"),
92
+ {},
93
+ )
94
+
95
+ print(
96
+ f"[Python Client] Pull result: {'SUCCESS' if pull_result.get('success') else 'FAILED'}"
97
+ )
98
+ if "stats" in pull_result:
99
+ stats = pull_result["stats"]
100
+ print(f" • Mode: {stats.get('mode')}")
101
+ print(f" • Remote cards: {stats.get('remote_total')}")
102
+ print(f" • Synced (pulled): {stats.get('synced')}")
103
+ print()
104
+
105
+ # Step 2: Push Python MCards to JavaScript
106
+ print("[Python Client] Step 2: Pushing Python MCards to JavaScript server...")
107
+
108
+ push_result = runtime.execute(
109
+ {"builtin": "mcard_sync", "config": {"url": SYNC_URL, "mode": "push"}},
110
+ MCard("dummy"),
111
+ {},
112
+ )
113
+
114
+ print(
115
+ f"[Python Client] Push result: {'SUCCESS' if push_result.get('success') else 'FAILED'}"
116
+ )
117
+ if "stats" in push_result:
118
+ stats = push_result["stats"]
119
+ print(f" • Mode: {stats.get('mode')}")
120
+ print(f" • Local cards: {stats.get('local_total')}")
121
+ print(f" • Synced (pushed): {stats.get('synced')}")
122
+ print()
123
+
124
+ # Step 3: Show final collection state
125
+ print("[Python Client] Final collection state after sync:")
126
+ all_cards = list(collection.get_all_mcards_raw())
127
+ print(f" Total cards in Python collection: {len(all_cards)}")
128
+
129
+ for card in all_cards:
130
+ content = card.get_content()
131
+ if isinstance(content, bytes):
132
+ content = content.decode("utf-8")
133
+
134
+ if "JavaScript" in content:
135
+ origin = "🟨 JavaScript"
136
+ elif "Python" in content:
137
+ origin = "🐍 Python"
138
+ else:
139
+ origin = "❓ Unknown"
140
+
141
+ print(f" • [{origin}] {card.hash[:16]}... = '{content[:40]}...'")
142
+
143
+ print("\n" + "=" * 60)
144
+ print(" ✅ Cross-Runtime Communication Successful!")
145
+ print(" JavaScript → Python MCard synchronization complete.")
146
+ print("=" * 60 + "\n")
147
+
148
+
149
+ if __name__ == "__main__":
150
+ main()