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
@@ -0,0 +1,74 @@
1
+ """SQLite WAL Connection Pooling & Tri-Database Consolidation (DEL-389-02).
2
+
3
+ Provides high-concurrency WAL-mode connection pools for the three canonical
4
+ tri-database pillars:
5
+ 1. agent_identities.db (DIDs, keys, and ZTA credentials)
6
+ 2. content_memory.db (Immutable CAS MCards and content payloads)
7
+ 3. execution_log.db (Append-only audit traces, markings, and learning events)
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from pathlib import Path
13
+
14
+ from clm.layer2.storage.db_pool import ClmDbPool
15
+
16
+ # Class alias
17
+ SqliteWalPool = ClmDbPool
18
+
19
+
20
+ class TriDatabasePoolRegistry:
21
+ """Singleton registry of SQLite WAL connection pools for the Triad."""
22
+
23
+ _instance: TriDatabasePoolRegistry | None = None
24
+
25
+ def __init__(self, clm_root: str | None = None) -> None:
26
+ self.clm_root = clm_root or os.environ.get("CLM_ROOT", ".")
27
+ self._pools: dict[str, ClmDbPool] = {}
28
+
29
+ @classmethod
30
+ def get_instance(cls, clm_root: str | None = None) -> TriDatabasePoolRegistry:
31
+ if cls._instance is None:
32
+ cls._instance = cls(clm_root)
33
+ return cls._instance
34
+
35
+ def get_pool(self, pillar: str) -> ClmDbPool:
36
+ """Get or initialize connection pool for a specific pillar."""
37
+ if pillar in self._pools:
38
+ return self._pools[pillar]
39
+
40
+ root = Path(self.clm_root).resolve()
41
+ data_dir = root / "data"
42
+
43
+ pillar_paths = {
44
+ "agent_identities": data_dir / "agent_identities.db",
45
+ "content_memory": data_dir / "content_memory.db",
46
+ "execution_log": data_dir / "execution_log.db",
47
+ }
48
+
49
+ db_path = str(pillar_paths.get(pillar, data_dir / f"{pillar}.db"))
50
+ pool = ClmDbPool(db_path)
51
+ self._pools[pillar] = pool
52
+ return pool
53
+
54
+ def close_all(self) -> None:
55
+ for pool in self._pools.values():
56
+ pool.close()
57
+ self._pools.clear()
58
+
59
+
60
+ def get_tridb_pools(clm_root: str | None = None) -> dict[str, ClmDbPool]:
61
+ """Return initialized pools for the three canonical pillars."""
62
+ reg = TriDatabasePoolRegistry.get_instance(clm_root)
63
+ return {
64
+ "agent_identities": reg.get_pool("agent_identities"),
65
+ "content_memory": reg.get_pool("content_memory"),
66
+ "execution_log": reg.get_pool("execution_log"),
67
+ }
68
+
69
+
70
+ __all__ = [
71
+ "SqliteWalPool",
72
+ "TriDatabasePoolRegistry",
73
+ "get_tridb_pools",
74
+ ]
clm/layer2/tridb.py ADDED
@@ -0,0 +1,245 @@
1
+ """Layer 2: Content-Addressed Storage & Tri-Database Engine.
2
+
3
+ Canonical Path: kernel/scripts/clm/layer2/tridb.py
4
+ Parity: Rust `src/layer2/storage.rs`, TypeScript `src/layer2/triDb.ts`
5
+
6
+ Per 00_Architecture_Overview.md §Key Arch Principles #4:
7
+ The Tri-Database (agent_identities.db, content_memory.db, execution_log.db)
8
+ is the soul-bound memory of the agency — a central, non-transferable Single
9
+ Source of Truth. The three databases are cryptographically inseparable:
10
+ identity proofs, semantic knowledge, and episodic traces cannot be
11
+ meaningfully moved independently.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from clm.layer2.card_collection import CardCollection
22
+ from clm.layer2.storage import (
23
+ CLMDB,
24
+ CLMRepository,
25
+ init_tridb,
26
+ memorize_mcard,
27
+ register_handle,
28
+ resolve_handle_content,
29
+ resolve_handle_hash,
30
+ )
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ # Canonical handle URIs for Kenotic Root resolution
35
+ HANDLE_AGENT_IDENTITIES = "pkc://db/agent_identities"
36
+ HANDLE_CONTENT_MEMORY = "pkc://db/content_memory"
37
+ HANDLE_EXECUTION_LOG = "pkc://db/execution_log"
38
+
39
+ # Default database filenames (per Four-Database Topology)
40
+ DB_AGENT_IDENTITIES = "agent_identities.db"
41
+ DB_CONTENT_MEMORY = "content_memory.db"
42
+ DB_EXECUTION_LOG = "execution_log.db"
43
+
44
+
45
+ @dataclass
46
+ class TriDatabase:
47
+ """Soul-bound Tri-Database: the non-transferable SSOT for the agency.
48
+
49
+ Architectural Invariant (00_Architecture_Overview §1.1):
50
+ The three databases are cryptographically inseparable. Identity proofs,
51
+ semantic knowledge, and episodic traces cannot be meaningfully moved
52
+ independently. This soul-bound property is itself a Polynomial Type
53
+ manifestation: the identical frozen 3-table schema is interpreted
54
+ polymorphically across three distinct cognitive domains (Who, What, How/When).
55
+
56
+ Three-Plane Mapping:
57
+ - agent_identities → Application Plane (Zero-Trust AuthZ/AuthN)
58
+ - content_memory → Data Plane (bits-to-hash guarantees)
59
+ - execution_log → Control Plane (PTR lifecycle traces)
60
+
61
+ Args:
62
+ agent_identities: CardCollection for agent identity proofs (Who).
63
+ content_memory: CardCollection for semantic domain knowledge (What).
64
+ execution_log: CardCollection for episodic execution traces (How/When).
65
+ tri_db_dir: Root directory containing the three database files.
66
+ """
67
+
68
+ agent_identities: Any # CardCollection (Who am I? Application Plane)
69
+ content_memory: Any # CardCollection (What do I know? Data Plane)
70
+ execution_log: Any # CardCollection (How did I do it? Control Plane)
71
+ tri_db_dir: Path | None = None # Configurable root directory
72
+
73
+ @classmethod
74
+ def from_kenotic_root(cls, root: Any) -> TriDatabase:
75
+ """Resolve Tri-Database paths from the Kenotic Root (meta_functionality.db).
76
+
77
+ Implements the Handle↔Hash duality (§Key Arch Principles #5):
78
+ Each pkc://db/* handle in the Kenotic Root resolves to an MCard
79
+ whose content encodes the database path. This is a directed morphism
80
+ from semantic name to content hash to physical location.
81
+
82
+ Args:
83
+ root: The Kenotic Root CardCollection (meta_functionality.db)
84
+ containing handle→hash mappings for the three databases.
85
+
86
+ Returns:
87
+ TriDatabase with collections resolved from handle metadata.
88
+
89
+ Raises:
90
+ ValueError: If required handles are not found in the Kenotic Root.
91
+ """
92
+ import yaml
93
+
94
+
95
+ paths = {}
96
+ for handle_uri, db_key in [
97
+ (HANDLE_AGENT_IDENTITIES, "agent_identities"),
98
+ (HANDLE_CONTENT_MEMORY, "content_memory"),
99
+ (HANDLE_EXECUTION_LOG, "execution_log"),
100
+ ]:
101
+ resolved_hash = root.resolve_handle(handle_uri)
102
+ if not resolved_hash:
103
+ raise ValueError(
104
+ f"Kenotic Root missing handle: {handle_uri}. "
105
+ f"Run bootstrap to provision the Four-Database topology."
106
+ )
107
+ card = root.get(resolved_hash)
108
+ if not card:
109
+ raise ValueError(
110
+ f"Kenotic Root handle {handle_uri} points to missing card: {resolved_hash}"
111
+ )
112
+ # Parse the card content to extract the 'path' field
113
+ raw_content = card.get_content(as_text=True) if hasattr(card, "get_content") else getattr(card, "content", "")
114
+ content = yaml.safe_load(raw_content)
115
+ db_path = content.get("path")
116
+ if not db_path:
117
+ raise ValueError(
118
+ f"Card for {handle_uri} missing 'path' field in content"
119
+ )
120
+ paths[db_key] = Path(db_path)
121
+
122
+ # Derive tri_db_dir from the common parent of the three paths
123
+ parents = {p.parent for p in paths.values()}
124
+ tri_db_dir = parents.pop() if len(parents) == 1 else None
125
+
126
+ return cls(
127
+ agent_identities=CardCollection(db_path=str(paths["agent_identities"])),
128
+ content_memory=CardCollection(db_path=str(paths["content_memory"])),
129
+ execution_log=CardCollection(db_path=str(paths["execution_log"])),
130
+ tri_db_dir=tri_db_dir,
131
+ )
132
+
133
+ @classmethod
134
+ def from_paths(cls, tri_db_dir: Path | str) -> TriDatabase:
135
+ """Create TriDatabase with explicit directory path.
136
+
137
+ Instantiates three CardCollections in the given directory using
138
+ the canonical filenames defined by the Four-Database Topology.
139
+
140
+ Args:
141
+ tri_db_dir: Directory containing (or to create) the three databases.
142
+
143
+ Returns:
144
+ TriDatabase with collections at canonical paths.
145
+ """
146
+
147
+ tri_db_dir = Path(tri_db_dir)
148
+ tri_db_dir.mkdir(parents=True, exist_ok=True)
149
+
150
+ return cls(
151
+ agent_identities=CardCollection(
152
+ db_path=str(tri_db_dir / DB_AGENT_IDENTITIES)
153
+ ),
154
+ content_memory=CardCollection(db_path=str(tri_db_dir / DB_CONTENT_MEMORY)),
155
+ execution_log=CardCollection(db_path=str(tri_db_dir / DB_EXECUTION_LOG)),
156
+ tri_db_dir=tri_db_dir,
157
+ )
158
+
159
+ @classmethod
160
+ def in_memory(cls) -> TriDatabase:
161
+ """Create an in-memory TriDatabase for testing.
162
+
163
+ All three databases use in-memory SQLite, enabling fast,
164
+ isolated test execution without filesystem side effects.
165
+
166
+ Returns:
167
+ TriDatabase with ephemeral, in-memory collections.
168
+ """
169
+
170
+ return cls(
171
+ agent_identities=CardCollection(db_path=":memory:"),
172
+ content_memory=CardCollection(db_path=":memory:"),
173
+ execution_log=CardCollection(db_path=":memory:"),
174
+ tri_db_dir=None,
175
+ )
176
+
177
+ def monotonic_merge(self, other: TriDatabase) -> TriDatabase:
178
+ """CRDT lattice-join: merge two Tri-Databases via monotonic union.
179
+
180
+ Per §Key Arch Principles #10: all data merges are mathematically
181
+ defined by monotonic lattice joins, guaranteeing Strong Eventual
182
+ Consistency (SEC). This means:
183
+
184
+ - Commutativity: A.merge(B) == B.merge(A)
185
+ - Associativity: (A.merge(B)).merge(C) == A.merge(B.merge(C))
186
+ - Idempotency: A.merge(A) == A
187
+ - Monotonicity: A ⊑ A.merge(B) — merged state is always "more defined"
188
+
189
+ The merge operation unions the card tables (content-addressed
190
+ deduplication is automatic via hash identity) and takes the latest
191
+ handle_registry entries by timestamp ordering.
192
+
193
+ Args:
194
+ other: The TriDatabase to merge from.
195
+
196
+ Returns:
197
+ A new TriDatabase containing the lattice-join of both inputs.
198
+
199
+ Note:
200
+ This is a foundational operation for future distributed mesh
201
+ replication. Currently supports local backup/restore with
202
+ provable convergence guarantees.
203
+ """
204
+ merged = TriDatabase.in_memory()
205
+
206
+ for src_db_name in ("agent_identities", "content_memory", "execution_log"):
207
+ src_self = getattr(self, src_db_name)
208
+ src_other = getattr(other, src_db_name)
209
+ dst = getattr(merged, src_db_name)
210
+
211
+ # Union card tables — hash identity gives automatic deduplication
212
+ raw_self = src_self.get_all_mcards_raw() if hasattr(src_self, "get_all_mcards_raw") else []
213
+ for card in raw_self:
214
+ try:
215
+ dst.add(card)
216
+ except Exception:
217
+ pass # Already exists (idempotent by hash)
218
+
219
+ raw_other = src_other.get_all_mcards_raw() if hasattr(src_other, "get_all_mcards_raw") else []
220
+ for card in raw_other:
221
+ try:
222
+ dst.add(card)
223
+ except Exception:
224
+ pass # Already exists (idempotent by hash)
225
+
226
+ logger.info("TriDatabase monotonic merge completed (lattice-join)")
227
+ return merged
228
+
229
+
230
+ __all__ = [
231
+ "CLMDB",
232
+ "CLMRepository",
233
+ "init_tridb",
234
+ "memorize_mcard",
235
+ "register_handle",
236
+ "resolve_handle_content",
237
+ "resolve_handle_hash",
238
+ "HANDLE_AGENT_IDENTITIES",
239
+ "HANDLE_CONTENT_MEMORY",
240
+ "HANDLE_EXECUTION_LOG",
241
+ "DB_AGENT_IDENTITIES",
242
+ "DB_CONTENT_MEMORY",
243
+ "DB_EXECUTION_LOG",
244
+ "TriDatabase",
245
+ ]
@@ -0,0 +1,71 @@
1
+ """VCard Receipt & Proof Generator (Sprint 394 / DEL-394-03).
2
+
3
+ Generates cryptographic proof receipts (archetype VCardReceipt) verifying that an
4
+ Action executed successfully within the Hoare Sandwich ({V_pre} Action {V_post}).
5
+
6
+ Acceptance Criteria:
7
+ - AC-394-03-03: Produces signed VCardReceipt containing input/output hashes, timestamps, and witness.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import datetime
13
+ from typing import Any
14
+
15
+ from clm.cross_cutting.domain_models import MCard
16
+ from clm.layer0.model.card_triad import compute_canonical_hash
17
+ from clm.layer0.utils import clm_hash_string
18
+
19
+
20
+ def generate_vcard_receipt(
21
+ action_name: str,
22
+ action_hash: str,
23
+ input_hashes: dict[str, str],
24
+ output_hashes: dict[str, str],
25
+ precondition_verdicts: list[dict[str, Any]],
26
+ postcondition_verdicts: list[dict[str, Any]],
27
+ author: str = "did:clm:verifier",
28
+ metrics: dict[str, Any] | None = None,
29
+ ) -> MCard:
30
+ """Generate an immutable VCard proof receipt certifying valid execution."""
31
+ now = datetime.datetime.now(datetime.timezone.utc).isoformat()
32
+
33
+ # Compute triadic witness hash: H(V_pre || Action || V_post)
34
+ pre_digest = compute_canonical_hash(precondition_verdicts)
35
+ post_digest = compute_canonical_hash(postcondition_verdicts)
36
+ witness_preimage = f"{pre_digest}:{action_hash}:{post_digest}"
37
+ witness_hash = clm_hash_string(witness_preimage)
38
+
39
+ payload = {
40
+ "archetype": "VCardReceipt",
41
+ "action": {
42
+ "name": action_name,
43
+ "hash": action_hash,
44
+ },
45
+ "inputs": input_hashes,
46
+ "outputs": output_hashes,
47
+ "verification": {
48
+ "all_passed": True,
49
+ "postconditions": postcondition_verdicts,
50
+ "preconditions": precondition_verdicts,
51
+ },
52
+ "witness": witness_hash,
53
+ }
54
+
55
+ receipt_hash = compute_canonical_hash(payload)
56
+ uri = f"mcard://receipts/{receipt_hash[:16]}"
57
+
58
+ mcard = MCard.create(
59
+ uri=uri,
60
+ payload=payload,
61
+ author=author,
62
+ metadata={
63
+ "format": "json",
64
+ "archetype": "VCardReceipt",
65
+ "action_name": action_name,
66
+ "witness": witness_hash,
67
+ "metrics": metrics or {},
68
+ "timestamp": now,
69
+ },
70
+ )
71
+ return mcard
clm/layer2/vfs.py ADDED
@@ -0,0 +1,17 @@
1
+ """Layer 2: MCard Virtual Filesystem (VFS) & Shared State Store.
2
+
3
+ Canonical Path: kernel/scripts/clm/layer2/vfs.py
4
+ Parity: Rust `src/layer2/vfs.rs`, TypeScript `src/layer2/mcardFs/filesystem.ts`
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from clm.layer2.mcard_fs import MCardFileSystem, MCardStat
10
+ from clm.layer2.shared_store import PTRSharedStore, create_store_from_context
11
+
12
+ __all__ = [
13
+ "MCardFileSystem",
14
+ "MCardStat",
15
+ "PTRSharedStore",
16
+ "create_store_from_context",
17
+ ]
clm/layer3/__init__.py ADDED
@@ -0,0 +1,141 @@
1
+ """CLM layer3 package — Distributed Network Gateway, Reticulum Mesh & Satori Protocols (Sprint 390).
2
+
3
+ Stratified subpackages:
4
+ - clm.layer3.reticulum: Sovereign mesh transport, discovery, identity, media, daemon
5
+ - clm.layer3.satori: Speech-act protocol, delimited continuations, sheaf auditing, lambda calculus
6
+ - clm.layer3.agency: Autonomous roles and LLM runtime
7
+ - clm.layer3.rag: Retrieval-Augmented Generation engine
8
+ - clm.layer3.gateway: Handle routing across local and remote mediums
9
+ """
10
+ from __future__ import annotations
11
+
12
+ # Subpackages
13
+ from clm.layer3 import agency, rag, reticulum, satori
14
+ from clm.layer3.gateway import remote_handle_resolver, route_handle
15
+ from clm.layer3.reticulum.bridge import SatoriReticulumBridge
16
+ from clm.layer3.reticulum.daemon import ReticulumLocalDaemon
17
+
18
+ # Reticulum Primitives
19
+ from clm.layer3.reticulum.discovery import (
20
+ RETICULUM_AUTOINTERFACE_PORT,
21
+ ReticulumDiscoveryEngine,
22
+ ReticulumDiscoveryService,
23
+ )
24
+ from clm.layer3.reticulum.identity import (
25
+ create_rns_identity_from_seed,
26
+ derive_destination_hash,
27
+ derive_destination_hex,
28
+ extract_raw_pubkey_from_did,
29
+ )
30
+ from clm.layer3.reticulum.media import (
31
+ fetch_mcard_resource,
32
+ inject_mcard_to_peer,
33
+ reassemble_chunks,
34
+ slice_into_chunks,
35
+ )
36
+ from clm.layer3.reticulum.transport import (
37
+ ReticulumLinkSession,
38
+ ReticulumTransport,
39
+ establish_link_pair,
40
+ )
41
+ from clm.layer3.satori.continuation import ContinuationToken
42
+ from clm.layer3.satori.sheaf_audit import (
43
+ Marking,
44
+ OpenSet,
45
+ Place,
46
+ Section,
47
+ Sheaf,
48
+ SheafAuditor,
49
+ SheafAuditReport,
50
+ audit_maxwell_demon,
51
+ )
52
+
53
+ # Satori Speech Acts & Sheaf Consensus
54
+ from clm.layer3.satori.speech_act import (
55
+ OPCODES_TO_TYPE,
56
+ SATORI_OPCODES,
57
+ SpeechAct,
58
+ SpeechActType,
59
+ classify_speech_act,
60
+ create_assert,
61
+ create_commissive,
62
+ create_commit,
63
+ create_declarative,
64
+ create_declare,
65
+ create_directive,
66
+ create_expressive,
67
+ create_request,
68
+ decode_satori_binary,
69
+ encode_satori_binary,
70
+ )
71
+
72
+ # Sprint 383 (DEL-383-04): Register Layer 3 runtimes with Layer 1 runtime factory
73
+ try:
74
+ from clm.layer1.runtimes.factory import register_external_executor
75
+ from clm.layer3.satori.lambda_runtime import LambdaRuntime
76
+
77
+ register_external_executor("lambda", LambdaRuntime)
78
+ except Exception:
79
+ pass
80
+
81
+ try:
82
+ from clm.layer1.runtimes.factory import register_external_executor
83
+ from clm.layer3.agency.runtime import LLMRuntime
84
+
85
+ register_external_executor("llm", LLMRuntime)
86
+ except Exception:
87
+ pass
88
+
89
+ __all__ = [
90
+ # Subpackages
91
+ "agency",
92
+ "rag",
93
+ "reticulum",
94
+ "satori",
95
+ # Gateway
96
+ "route_handle",
97
+ "remote_handle_resolver",
98
+ # Reticulum
99
+ "RETICULUM_AUTOINTERFACE_PORT",
100
+ "ReticulumDiscoveryService",
101
+ "ReticulumDiscoveryEngine",
102
+ "ReticulumLinkSession",
103
+ "ReticulumTransport",
104
+ "establish_link_pair",
105
+ "create_rns_identity_from_seed",
106
+ "derive_destination_hash",
107
+ "derive_destination_hex",
108
+ "extract_raw_pubkey_from_did",
109
+ "fetch_mcard_resource",
110
+ "inject_mcard_to_peer",
111
+ "reassemble_chunks",
112
+ "slice_into_chunks",
113
+ "ReticulumLocalDaemon",
114
+ "SatoriReticulumBridge",
115
+ # Satori Speech Acts
116
+ "SATORI_OPCODES",
117
+ "OPCODES_TO_TYPE",
118
+ "SpeechActType",
119
+ "SpeechAct",
120
+ "encode_satori_binary",
121
+ "decode_satori_binary",
122
+ "classify_speech_act",
123
+ "create_assert",
124
+ "create_directive",
125
+ "create_request",
126
+ "create_commissive",
127
+ "create_commit",
128
+ "create_expressive",
129
+ "create_declarative",
130
+ "create_declare",
131
+ # Sheaf
132
+ "Place",
133
+ "Marking",
134
+ "OpenSet",
135
+ "Section",
136
+ "Sheaf",
137
+ "SheafAuditReport",
138
+ "SheafAuditor",
139
+ "audit_maxwell_demon",
140
+ "ContinuationToken",
141
+ ]
@@ -0,0 +1,19 @@
1
+ """
2
+ LLM Runtime Package
3
+
4
+ Provides LLM execution capabilities integrated with the PTR engine.
5
+ """
6
+
7
+ from .config import DEFAULT_LLM_CONFIG, LLM_PROVIDERS, LLMConfig
8
+ from .router import IntelligenceRouter
9
+ from .runtime import LLMRuntime, chat_monad, prompt_monad
10
+
11
+ __all__ = [
12
+ "LLMConfig",
13
+ "LLM_PROVIDERS",
14
+ "DEFAULT_LLM_CONFIG",
15
+ "LLMRuntime",
16
+ "prompt_monad",
17
+ "chat_monad",
18
+ "IntelligenceRouter",
19
+ ]