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/layer3/gateway.py ADDED
@@ -0,0 +1,353 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import time
5
+ from typing import Any
6
+
7
+ import yaml
8
+
9
+ from clm.cross_cutting.clm_logger import get_logger
10
+ from clm.layer0.exceptions import GatewayError
11
+ from clm.layer0.utils import clm_hash_string, prefixed_hash_raw, strip_hash_prefix
12
+
13
+ _logger = get_logger("clm.layer3.gateway")
14
+
15
+
16
+ def route_handle(clm_root: str, handle_name: str, fallback: str = "error", cache: str = "true") -> tuple[str, int]:
17
+ """
18
+ Routes and resolves a handle dynamically across local and remote mediums.
19
+
20
+ Args:
21
+ clm_root (str): The workspace root directory.
22
+ handle_name (str): The handle pointer to resolve.
23
+ fallback (str): Fallback behavior on resolution failure.
24
+ cache (str): Cache setting (true/false) for storing fetched content.
25
+
26
+ Returns:
27
+ Tuple[str, int]: The resolved final content and the status code.
28
+
29
+ Raises:
30
+ GatewayError: If handle is not found or circular reference is detected.
31
+ """
32
+ from clm.layer2.storage import CLMDB, CLMRepository
33
+ db = CLMDB(clm_root)
34
+ repo = CLMRepository(db, clm_root)
35
+ current_handle = handle_name
36
+ visited_handles = {handle_name}
37
+ final_content = ""
38
+ status = 0
39
+
40
+ while True:
41
+ content_hash = repo.resolve_handle_hash(current_handle, "content_memory")
42
+ if not content_hash:
43
+ if current_handle == handle_name:
44
+ raise GatewayError(f"Handle not found: {current_handle}")
45
+ else:
46
+ break
47
+
48
+ route_handle_name = f"route:{content_hash}"
49
+ route_content = repo.resolve_handle_content(route_handle_name, "content_memory")
50
+
51
+ medium = "local"
52
+ route_data = {}
53
+ if route_content:
54
+ try:
55
+ route_data = yaml.safe_load(route_content)
56
+ if isinstance(route_data, dict):
57
+ medium = route_data.get("medium", "local")
58
+ except Exception as e:
59
+ _logger.error(f"[route_handle] Debug: route_content YAML load failed: {e}")
60
+
61
+ if medium == "file":
62
+ uri = route_data.get("uri", "")
63
+ path = uri.replace("file://", "", 1)
64
+ if not os.path.isabs(path) and not os.path.exists(path):
65
+ alt_path = os.path.join(clm_root, path)
66
+ if os.path.exists(alt_path):
67
+ path = alt_path
68
+ try:
69
+ with open(path, encoding="utf-8") as f:
70
+ final_content = f.read()
71
+ status = 0
72
+ except Exception as e:
73
+ _logger.warning(f"[route_handle] Warning: file medium resolution failed: {e}")
74
+ status = 2
75
+ elif medium in ("http", "ftp"):
76
+ uri = route_data.get("uri", "")
77
+ try:
78
+ import urllib.request
79
+ req = urllib.request.Request(
80
+ uri,
81
+ headers={'User-Agent': 'Mozilla/5.0'}
82
+ )
83
+ with urllib.request.urlopen(req, timeout=10) as response:
84
+ final_content = response.read().decode('utf-8')
85
+ status = 0
86
+ except Exception as e:
87
+ _logger.warning(f"[route_handle] Warning: URL medium resolution failed: {e}")
88
+ status = 2
89
+ elif medium == "ipfs":
90
+ uri = route_data.get("uri", "")
91
+ cid = uri.replace("ipfs://", "", 1)
92
+ try:
93
+ import subprocess
94
+ proc = subprocess.Popen(["ipfs", "cat", cid], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
95
+ try:
96
+ stdout_data, _ = proc.communicate(timeout=15)
97
+ except subprocess.TimeoutExpired:
98
+ proc.kill()
99
+ proc.communicate()
100
+ status = 2
101
+ else:
102
+ if proc.returncode == 0:
103
+ final_content = stdout_data
104
+ status = 0
105
+ else:
106
+ status = 2
107
+ except Exception as e:
108
+ _logger.warning(f"[route_handle] Warning: IPFS medium resolution failed: {e}")
109
+ status = 2
110
+ elif medium == "indexeddb":
111
+ status = 2
112
+ else:
113
+ try:
114
+ final_content = repo.get_card_content(content_hash, "content_memory") or ""
115
+ status = 0
116
+ except Exception as e:
117
+ _logger.error(f"[route_handle] Error: get_card_content failed: {e}")
118
+ status = 2
119
+
120
+ if status == 0 and medium != "local":
121
+ cached_hash = route_data.get("cached_hash", "")
122
+ if cached_hash and cached_hash != "null":
123
+ actual_hash = clm_hash_string(final_content)
124
+ clean_expected = strip_hash_prefix(cached_hash)
125
+ if actual_hash != clean_expected:
126
+ _logger.error(f"[route_handle] Error: Hash mismatch. Expected: {cached_hash}, Actual: {prefixed_hash_raw(actual_hash)}")
127
+ status = 2
128
+
129
+ if status == 0 and cache == "true" and medium != "local":
130
+ final_hash = route_data.get("cached_hash", "")
131
+ if not final_hash or final_hash == "null":
132
+ actual_hash = clm_hash_string(final_content)
133
+ final_hash = prefixed_hash_raw(actual_hash)
134
+
135
+ clean_hash = strip_hash_prefix(final_hash)
136
+ ts = time.strftime("%Y-%m-%dT%H:%M:%S%z")
137
+ try:
138
+ repo.save_card(clean_hash, final_content, "content_memory", timestamp=ts, replace=False)
139
+ except Exception as e:
140
+ _logger.warning(f"[route_handle] Warning: Caching failed: {e}")
141
+
142
+ if status != 0:
143
+ if fallback == "stale":
144
+ cached_hash = route_data.get("cached_hash", "")
145
+ if cached_hash and cached_hash != "null":
146
+ clean_hash = strip_hash_prefix(cached_hash)
147
+ try:
148
+ res = repo.get_card_content(clean_hash, "content_memory")
149
+ if res:
150
+ final_content = res
151
+ status = 3
152
+ _logger.warning(f"[route_handle] Warning: Stale fallback used for {current_handle}")
153
+ except Exception as e:
154
+ _logger.warning(f"[route_handle] Warning: Stale fallback fetch failed: {e}")
155
+
156
+ if status != 3:
157
+ try:
158
+ prev_hash = repo.get_latest_handle_history(current_handle, "content_memory")
159
+ if prev_hash:
160
+ res = repo.get_card_content(prev_hash, "content_memory")
161
+ if res:
162
+ final_content = res
163
+ status = 3
164
+ _logger.warning(f"[route_handle] Warning: Stale fallback (history) used for {current_handle}")
165
+ except Exception as e:
166
+ _logger.warning(f"[route_handle] Warning: Stale history fallback fetch failed: {e}")
167
+
168
+ if status != 3:
169
+ _logger.error(f"[route_handle] Error: Network error resolving medium {medium} for {current_handle}")
170
+ raise GatewayError(f"Network error resolving medium {medium}")
171
+
172
+ if len(final_content) <= 255 and re.match(r"^[a-zA-Z0-9_:-]+$", final_content):
173
+ check_hash = repo.resolve_handle_hash(final_content, "content_memory")
174
+ if check_hash:
175
+ if final_content in visited_handles:
176
+ _logger.error(f"[route_handle] Error: Circular reference detected: {visited_handles} -> {final_content}")
177
+ raise GatewayError("Circular reference detected")
178
+ visited_handles.add(final_content)
179
+ current_handle = final_content
180
+ continue
181
+
182
+ break
183
+
184
+ return final_content, status
185
+
186
+ def remote_handle_resolver(
187
+ clm_root: str,
188
+ action: str | None = None,
189
+ handle: str | None = None,
190
+ peer_url: str | None = None,
191
+ locale_trust: str | None = None,
192
+ allowed_sponsors: str | None = None,
193
+ active_agent: str | None = None
194
+ ) -> tuple[dict[str, Any], int]:
195
+ """
196
+ Resolves a handle query over remote gateways or serves incoming peer resolution queries.
197
+ """
198
+ from clm.layer2.storage import CLMDB, CLMRepository
199
+ db = CLMDB(clm_root)
200
+ repo = CLMRepository(db, clm_root)
201
+
202
+ if action in ("serve", "server", "resolve_inbound"):
203
+ active_agent = active_agent or os.environ.get("ACTIVE_AGENT_DID") or os.environ.get("CLM_AGENT_DID") or ""
204
+ allowed_sponsors = allowed_sponsors or os.environ.get("CLM_RESOLVE_ALLOWED_SPONSORS") or ""
205
+
206
+ if allowed_sponsors and active_agent != "did:clm:bootstrap":
207
+ allowed_list = [s.strip() for s in allowed_sponsors.split(",") if s.strip()]
208
+ if active_agent not in allowed_list:
209
+ return {"status": "ERROR", "error": "Unauthorized agent"}, 1
210
+
211
+ if not handle:
212
+ return {"status": "ERROR", "error": "Missing handle parameter"}, 1
213
+
214
+ current_hash = ""
215
+ try:
216
+ current_hash = repo.resolve_handle_hash(handle, "content_memory")
217
+ except Exception as e:
218
+ _logger.warning(f"[remote_handle_resolver] Warning: resolve_handle_hash failed for {handle}: {e}")
219
+
220
+ if not current_hash and not handle.startswith("clm:"):
221
+ try:
222
+ current_hash = repo.resolve_handle_hash(f"clm:{handle}", "content_memory")
223
+ except Exception as e:
224
+ _logger.warning(f"[remote_handle_resolver] Warning: resolve_handle_hash failed for clm:{handle}: {e}")
225
+
226
+ if not current_hash:
227
+ return {"status": "ERROR", "error": "Handle not found"}, 1
228
+
229
+ yaml_content = ""
230
+ try:
231
+ yaml_content = repo.get_card_content(current_hash, "content_memory") or ""
232
+ except Exception as e:
233
+ _logger.warning(f"[remote_handle_resolver] Warning: get_card_content failed for {current_hash}: {e}")
234
+
235
+ if not yaml_content:
236
+ return {"status": "ERROR", "error": "Content not found in CAS"}, 1
237
+
238
+ locale_hash = os.environ.get("CLM_EXECUTION_LOCALE_HASH", "")
239
+ signature = ""
240
+ try:
241
+ parsed = yaml.safe_load(yaml_content)
242
+ if isinstance(parsed, dict):
243
+ inner = parsed.get("clm", parsed)
244
+ if isinstance(inner, dict):
245
+ signature = inner.get("_meta", {}).get("signature", "")
246
+ except Exception as e:
247
+ _logger.error(f"[remote_handle_resolver] Debug: failed to parse signature from yaml_content: {e}")
248
+
249
+ return {
250
+ "status": "SUCCESS",
251
+ "hash": current_hash,
252
+ "content": yaml_content,
253
+ "locale_hash": locale_hash,
254
+ "signature": signature
255
+ }, 0
256
+
257
+ elif action in ("resolve", "client", "resolve_outbound"):
258
+ if not handle or not peer_url:
259
+ return {"status": "ERROR", "error": "Missing handle or peer_url parameters"}, 1
260
+
261
+ raw_response = None
262
+ if peer_url.startswith("http://") or peer_url.startswith("https://"):
263
+ try:
264
+ import urllib.error
265
+ import urllib.request
266
+ req = urllib.request.Request(
267
+ peer_url,
268
+ data=json.dumps({"action": "serve", "handle": handle}).encode("utf-8"),
269
+ headers={"Content-Type": "application/json"}
270
+ )
271
+ with urllib.request.urlopen(req, timeout=10) as response:
272
+ raw_response = response.read().decode("utf-8")
273
+ except Exception as e:
274
+ return {"status": "ERROR", "error": f"Transport connection failed: {e}"}, 1
275
+ elif peer_url == "mock" or peer_url == "mock_fail_hash":
276
+ mock_yaml = (
277
+ "clm:\n"
278
+ " _meta:\n"
279
+ " clm_root_hash: \"sha256:correct_hash\"\n"
280
+ " content_hash: \"sha256:correct_hash\"\n"
281
+ " g_time: \"2026-06-13T19:00:00Z\"\n"
282
+ )
283
+ correct_hash = clm_hash_string(mock_yaml)
284
+ mock_yaml = mock_yaml.replace("correct_hash", correct_hash)
285
+
286
+ h = correct_hash
287
+ if peer_url == "mock_fail_hash":
288
+ h = "sha256:bad_hash"
289
+
290
+ raw_response = json.dumps({
291
+ "status": "SUCCESS",
292
+ "hash": h,
293
+ "content": mock_yaml,
294
+ "locale_hash": "sha256:mock_locale",
295
+ "signature": "mock_sig"
296
+ })
297
+ else:
298
+ return {"status": "ERROR", "error": f"Unsupported peer URL: {peer_url}"}, 1
299
+
300
+ try:
301
+ resp_data = json.loads(raw_response)
302
+ except Exception:
303
+ return {"status": "ERROR", "error": "Invalid JSON response from peer"}, 1
304
+
305
+ status = resp_data.get("status", "ERROR")
306
+ if status != "SUCCESS":
307
+ error_msg = resp_data.get("error", "Unknown peer error")
308
+ return {"status": "ERROR", "error": f"Peer error: {error_msg}"}, 1
309
+
310
+ r_hash = resp_data.get("hash", "")
311
+ content = resp_data.get("content", "")
312
+ locale_hash = resp_data.get("locale_hash", "")
313
+ signature = resp_data.get("signature", "")
314
+
315
+ locale_trust = locale_trust or os.environ.get("CLM_LOCALE_TRUST") or ""
316
+ if locale_trust:
317
+ trusted_list = [t.strip() for t in locale_trust.split(",") if t.strip()]
318
+ if locale_hash not in trusted_list:
319
+ return {"status": "ERROR", "error": "Untrusted locale"}, 1
320
+
321
+ computed_root = ""
322
+ try:
323
+ parsed = yaml.safe_load(content)
324
+ if isinstance(parsed, dict):
325
+ inner = parsed.get("clm", parsed)
326
+ if isinstance(inner, dict):
327
+ computed_root = inner.get("_meta", {}).get("clm_root_hash", "")
328
+ except Exception as e:
329
+ _logger.error(f"[remote_handle_resolver] Debug: yaml load failed for integrity check: {e}")
330
+
331
+ clean_computed = strip_hash_prefix(computed_root)
332
+ clean_returned = strip_hash_prefix(r_hash)
333
+ if clean_computed and clean_computed != clean_returned:
334
+ return {"status": "ERROR", "error": "Integrity hash mismatch"}, 1
335
+
336
+ clm_name = handle
337
+ if handle.startswith("clm:"):
338
+ clm_name = handle[4:]
339
+ remote_handle = f"remote:clm:{clm_name}"
340
+
341
+ try:
342
+ ts = time.strftime("%Y-%m-%dT%H:%M:%S%z")
343
+ repo.save_card_and_handle(remote_handle, clean_returned, content, "content_memory", timestamp=ts, replace=True)
344
+ except Exception as e:
345
+ _logger.warning(f"[remote_handle_resolver] Warning: Caching remote handle failed: {e}")
346
+
347
+ return {
348
+ "status": "SUCCESS",
349
+ "hash": r_hash,
350
+ "remote_handle": remote_handle
351
+ }, 0
352
+ else:
353
+ return {"status": "ERROR", "error": "Unknown action"}, 1
@@ -0,0 +1,159 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import sys
5
+
6
+ from clm.cross_cutting.clm_logger import get_logger
7
+
8
+ _logger = get_logger("clm.layer3.open_interpreter_adapter")
9
+
10
+
11
+ def evaluate_open_interpreter(clm_root, clm_file, block, extra_args):
12
+ """
13
+ Executes open_interpreter process payload, supporting sandbox isolation
14
+ and mock/simulated modes for offline testing.
15
+ """
16
+ payload = extra_args[0] if extra_args else ""
17
+
18
+ # 1. Parse manifest parameters
19
+ model = block.get("model", "gpt-4o")
20
+ temp = float(block.get("temperature", 0.1))
21
+ prompt_template = block.get("script", block.get("prompt", ""))
22
+
23
+ # Check for script_handle
24
+ script_handle = block.get("script_handle", "")
25
+ if script_handle:
26
+ from clm.layer2.storage import resolve_handle_content
27
+ prompt_template = resolve_handle_content(clm_root, script_handle)
28
+
29
+ if not prompt_template:
30
+ _logger.error("[PAL:open_interpreter] ❌ No script or prompt found.")
31
+ return 2
32
+
33
+ # 2. Interpolate prompt
34
+ prompt = interpolate_prompt(prompt_template, clm_file, payload)
35
+
36
+ # Check mock behavior first
37
+ mock_behavior = os.environ.get("CLM_MOCK_OI_BEHAVIOR") or os.environ.get("CLM_MOCK_LLM_BEHAVIOR")
38
+ if mock_behavior:
39
+ return handle_mock_behavior(mock_behavior, prompt, clm_root, payload)
40
+
41
+ # 3. Check for library availability
42
+ try:
43
+ from interpreter import interpreter
44
+
45
+ # Enforce Zero-FS Hermetic Isolation
46
+ zero_fs = os.environ.get("CLM_ZERO_FS", "").lower() == "true"
47
+ if zero_fs:
48
+ import shutil
49
+ import tempfile
50
+ temp_dir = tempfile.mkdtemp()
51
+ orig_cwd = os.getcwd()
52
+ os.chdir(temp_dir)
53
+
54
+ try:
55
+ interpreter.llm.model = model
56
+ interpreter.llm.temperature = temp
57
+ interpreter.auto_run = True
58
+
59
+ # Run the prompt
60
+ response = interpreter.chat(prompt)
61
+ print(response)
62
+ return 0
63
+ finally:
64
+ if zero_fs:
65
+ os.chdir(orig_cwd)
66
+ shutil.rmtree(temp_dir, ignore_errors=True)
67
+
68
+ except ImportError:
69
+ # Fallback to simulated execution if interpreter is not installed
70
+ _logger.warning("[PAL:open_interpreter] ⚠️ Open Interpreter library not installed. Running simulated sandbox.")
71
+ return run_simulated_execution(prompt, clm_root, payload)
72
+
73
+ def interpolate_prompt(prompt_template, clm_file, payload):
74
+ context_str = os.environ.get("CLM_MLP_CONTEXT", "{}")
75
+ try:
76
+ context = json.loads(context_str)
77
+ except Exception:
78
+ context = {}
79
+
80
+ flat = {
81
+ "payload": context.get("context", {}).get("payload", "") or os.environ.get("CLM_PAYLOAD", "") or payload,
82
+ "clm_payload": context.get("context", {}).get("payload", "") or os.environ.get("CLM_PAYLOAD", "") or payload,
83
+ "operation": context.get("context", {}).get("operation", ""),
84
+ "clm_file": context.get("context", {}).get("clm_file", "") or clm_file,
85
+ "a_hash": context.get("context", {}).get("a_hash", ""),
86
+ "c_hash": context.get("context", {}).get("c_hash", ""),
87
+ }
88
+
89
+ interpolated = prompt_template
90
+ for k, v in flat.items():
91
+ interpolated = interpolated.replace("{{" + k + "}}", str(v))
92
+ return interpolated
93
+
94
+ def handle_mock_behavior(behavior, prompt, clm_root, payload):
95
+ _logger.info(f"[PAL:open_interpreter] Mocking behavior: {behavior}")
96
+ if behavior == "success" or behavior == "react_success":
97
+ # Simulates successful file creation/command execution
98
+ match = re.search(r"create a file named (\S+) containing ['\"](.*?)['\"]", prompt, re.IGNORECASE)
99
+ if match:
100
+ filename, content = match.groups()
101
+ filepath = os.path.join(clm_root, filename)
102
+ with open(filepath, "w", encoding="utf-8") as f:
103
+ f.write(content)
104
+ print(f"Created file {filename} with content: {content}")
105
+ else:
106
+ print(json.dumps({"result": "success", "detail": "simulated action completed"}))
107
+ return 0
108
+ elif behavior == "failure" or behavior == "react_unauthorized":
109
+ _logger.info("[PAL:open_interpreter] Mocking execution failure / unauthorized tool access")
110
+ return 1
111
+ elif behavior == "malformed" or behavior == "react_infinite":
112
+ _logger.info("[PAL:open_interpreter] Mocking malformed output / infinite loop bounding")
113
+ return 2
114
+ else:
115
+ _logger.info(f"[PAL:open_interpreter] Unknown mock behavior {behavior}")
116
+ return 1
117
+
118
+ def run_simulated_execution(prompt, clm_root, payload):
119
+ match = re.search(r"create a file named (\S+) containing ['\"](.*?)['\"]", prompt, re.IGNORECASE)
120
+ if match:
121
+ filename, content = match.groups()
122
+ filepath = os.path.join(clm_root, filename)
123
+ try:
124
+ with open(filepath, "w", encoding="utf-8") as f:
125
+ f.write(content)
126
+ print(f"Created file {filename} with content: {content}")
127
+ return 0
128
+ except Exception as e:
129
+ _logger.error(f"[PAL:open_interpreter] Simulation file write failed: {e}")
130
+ return 1
131
+
132
+ print(json.dumps({"result": "simulated_success", "payload": payload}))
133
+ return 0
134
+
135
+ def main_cli():
136
+ if len(sys.argv) < 2:
137
+ _logger.info("Usage: open_interpreter_adapter.py <clm_file> [entry_point] [payload]")
138
+ return 1
139
+
140
+ clm_file = sys.argv[1]
141
+ sys.argv[2] if len(sys.argv) > 2 else ""
142
+ payload = sys.argv[3] if len(sys.argv) > 3 else ""
143
+
144
+ clm_root = os.environ.get("CLM_ROOT") or os.getcwd()
145
+
146
+ from clm.layer0.algebra import load_normalized_manifest
147
+ try:
148
+ yaml_data = load_normalized_manifest(clm_root, clm_file)
149
+ except Exception as e:
150
+ _logger.info(f"Failed to load CLM YAML: {e}")
151
+ return 1
152
+
153
+ inner = yaml_data.get("clm", yaml_data)
154
+ concrete = inner.get("concrete_impl", {})
155
+ process = concrete.get("process", {})
156
+
157
+ block = (process[0] if process else {}) if isinstance(process, list) else process
158
+
159
+ return evaluate_open_interpreter(clm_root, clm_file, block, [payload] if payload else [])
@@ -0,0 +1,70 @@
1
+ """
2
+ MCard RAG (Retrieval-Augmented Generation) Package
3
+
4
+ Provides vector search, semantic retrieval, and knowledge graph capabilities
5
+ for MCard content using SQLite with sqlite-vec extension and Ollama embeddings.
6
+ """
7
+
8
+ from .config import DEFAULT_RAG_CONFIG, RAGConfig
9
+ from .engine import MCardRAGEngine, RAGResponse
10
+ from .graph import (
11
+ Entity,
12
+ GraphExtractor,
13
+ GraphRAGEngine,
14
+ GraphRAGResponse,
15
+ GraphStore,
16
+ Relationship,
17
+ )
18
+ from .indexer import PersistentIndexer, get_indexer, index_mcard, semantic_search
19
+ from .semantic_versioning import (
20
+ compare_versions_by_similarity,
21
+ find_most_similar_version,
22
+ get_handle_version_history,
23
+ get_semantic_evolution,
24
+ get_store,
25
+ get_store_info,
26
+ get_version_distances,
27
+ link_mcard_to_handle,
28
+ list_handles,
29
+ search_within_handle,
30
+ )
31
+ from .vector import (
32
+ HandleVectorStore,
33
+ HandleVersion,
34
+ VersionSimilarityResult,
35
+ )
36
+
37
+ __all__ = [
38
+ # Config
39
+ "RAGConfig",
40
+ "DEFAULT_RAG_CONFIG",
41
+ # Vector RAG
42
+ "MCardRAGEngine",
43
+ "RAGResponse",
44
+ # Persistent Indexer
45
+ "PersistentIndexer",
46
+ "get_indexer",
47
+ "semantic_search",
48
+ "index_mcard",
49
+ # GraphRAG
50
+ "GraphRAGEngine",
51
+ "GraphRAGResponse",
52
+ "GraphExtractor",
53
+ "GraphStore",
54
+ "Entity",
55
+ "Relationship",
56
+ # Semantic Versioning
57
+ "link_mcard_to_handle",
58
+ "get_handle_version_history",
59
+ "compare_versions_by_similarity",
60
+ "search_within_handle",
61
+ "get_version_distances",
62
+ "find_most_similar_version",
63
+ "get_semantic_evolution",
64
+ "list_handles",
65
+ "get_store_info",
66
+ "get_store",
67
+ "HandleVectorStore",
68
+ "HandleVersion",
69
+ "VersionSimilarityResult",
70
+ ]