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.
- clm/__init__.py +230 -0
- clm/__main__.py +25 -0
- clm/cross_cutting/__init__.py +50 -0
- clm/cross_cutting/_test_runner.py +36 -0
- clm/cross_cutting/async_utils.py +25 -0
- clm/cross_cutting/cel_builder.py +123 -0
- clm/cross_cutting/cel_converter.py +697 -0
- clm/cross_cutting/cel_engine.py +252 -0
- clm/cross_cutting/cel_ops.py +72 -0
- clm/cross_cutting/cel_ops_db.py +157 -0
- clm/cross_cutting/cel_ops_files.py +99 -0
- clm/cross_cutting/cel_ops_state.py +71 -0
- clm/cross_cutting/cel_ops_strings.py +64 -0
- clm/cross_cutting/cel_resolver.py +63 -0
- clm/cross_cutting/cel_slices.py +56 -0
- clm/cross_cutting/cel_store.py +330 -0
- clm/cross_cutting/clm_logger.py +140 -0
- clm/cross_cutting/config/__init__.py +155 -0
- clm/cross_cutting/config/config_constants.py +392 -0
- clm/cross_cutting/config/env_parameters.py +90 -0
- clm/cross_cutting/config/logging.py +378 -0
- clm/cross_cutting/config/settings.py +504 -0
- clm/cross_cutting/context.py +5 -0
- clm/cross_cutting/domain_models.py +55 -0
- clm/cross_cutting/domain_types.py +61 -0
- clm/cross_cutting/effects.py +67 -0
- clm/cross_cutting/errors.py +153 -0
- clm/cross_cutting/governance.py +331 -0
- clm/cross_cutting/guards.py +41 -0
- clm/cross_cutting/mcard.py +321 -0
- clm/cross_cutting/native.py +185 -0
- clm/cross_cutting/observability.py +289 -0
- clm/cross_cutting/pcard.py +434 -0
- clm/cross_cutting/registry.py +71 -0
- clm/cross_cutting/resources.py +84 -0
- clm/cross_cutting/secrets.py +44 -0
- clm/cross_cutting/subprocess_utils.py +118 -0
- clm/cross_cutting/telemetry.py +164 -0
- clm/cross_cutting/testing/__init__.py +8 -0
- clm/cross_cutting/testing/comparator.py +187 -0
- clm/cross_cutting/testing/datasets.py +87 -0
- clm/cross_cutting/timeutil.py +20 -0
- clm/cross_cutting/types/new_type_check.py +0 -0
- clm/cross_cutting/utils/__init__.py +1 -0
- clm/cross_cutting/utils/url_safety.py +50 -0
- clm/cross_cutting/vcard.py +560 -0
- clm/cross_cutting/writer.py +118 -0
- clm/layer0/README.md +50 -0
- clm/layer0/__init__.py +223 -0
- clm/layer0/algebra.py +60 -0
- clm/layer0/algebra_baldwin.py +133 -0
- clm/layer0/algebra_baldwin_generators.py +36 -0
- clm/layer0/algebra_equivalence.py +262 -0
- clm/layer0/algebra_ingest.py +306 -0
- clm/layer0/algebra_manifest_io.py +156 -0
- clm/layer0/assembler.py +481 -0
- clm/layer0/cel/__init__.py +23 -0
- clm/layer0/cel_eval.py +491 -0
- clm/layer0/codec.py +106 -0
- clm/layer0/context.py +122 -0
- clm/layer0/db.py +160 -0
- clm/layer0/exceptions.py +73 -0
- clm/layer0/fibration.py +106 -0
- clm/layer0/gates.py +50 -0
- clm/layer0/hash.py +80 -0
- clm/layer0/loader.py +826 -0
- clm/layer0/math_utils.py +163 -0
- clm/layer0/mcard.py +96 -0
- clm/layer0/model/__init__.py +0 -0
- clm/layer0/model/action.py +223 -0
- clm/layer0/model/card.py +280 -0
- clm/layer0/model/card_triad.py +427 -0
- clm/layer0/model/compatibility.py +60 -0
- clm/layer0/model/dictionary.py +46 -0
- clm/layer0/model/dots.py +331 -0
- clm/layer0/model/event_producer.py +88 -0
- clm/layer0/model/g_time.py +89 -0
- clm/layer0/model/handle.py +163 -0
- clm/layer0/model/hash/__init__.py +6 -0
- clm/layer0/model/hash/algorithms/__init__.py +3 -0
- clm/layer0/model/hash/algorithms/custom_hash.py +7 -0
- clm/layer0/model/hash/algorithms/local_sha256.py +178 -0
- clm/layer0/model/hash/constants.py +53 -0
- clm/layer0/model/hash/enums.py +60 -0
- clm/layer0/model/hash/validator.py +307 -0
- clm/layer0/model/interpreter.py +275 -0
- clm/layer0/model/pagination.py +45 -0
- clm/layer0/model/pcard.py +716 -0
- clm/layer0/model/schema.py +44 -0
- clm/layer0/model/utils/__init__.py +1 -0
- clm/layer0/model/utils/content_analyzer.py +152 -0
- clm/layer0/model/validators/__init__.py +1 -0
- clm/layer0/model/validators/base_validator.py +44 -0
- clm/layer0/model/validators/binary_validator.py +66 -0
- clm/layer0/model/validators/text_validator.py +82 -0
- clm/layer0/model/validators/validation_registry.py +49 -0
- clm/layer0/model/vcard.py +823 -0
- clm/layer0/model/vcard_ext/__init__.py +39 -0
- clm/layer0/model/vcard_ext/core.py +60 -0
- clm/layer0/model/vcard_ext/network.py +23 -0
- clm/layer0/model/vcard_ext/observability.py +63 -0
- clm/layer0/model/vcard_ext/storage.py +60 -0
- clm/layer0/model/vcard_ext/vendors.py +211 -0
- clm/layer0/model/vcard_sandwich.py +119 -0
- clm/layer0/model/vcard_vocabulary.py +463 -0
- clm/layer0/model/workflow.py +274 -0
- clm/layer0/narrative.py +431 -0
- clm/layer0/ontology/collection.py +125 -0
- clm/layer0/parser.py +429 -0
- clm/layer0/relations.py +73 -0
- clm/layer0/rule_evaluator.py +251 -0
- clm/layer0/schema/__init__.py +38 -0
- clm/layer0/schema/ddl.py +97 -0
- clm/layer0/templates/abstract.yaml +99 -0
- clm/layer0/templates/balanced.yaml +253 -0
- clm/layer0/templates/concrete.yaml +172 -0
- clm/layer0/type_registry.py +223 -0
- clm/layer0/types.py +204 -0
- clm/layer0/utils.py +886 -0
- clm/layer0/verifier_core.py +262 -0
- clm/layer1/__init__.py +31 -0
- clm/layer1/action_dispatcher.py +275 -0
- clm/layer1/adapter_registry.py +233 -0
- clm/layer1/algebra_baldwin_generators.py +192 -0
- clm/layer1/arrow_compiler.py +525 -0
- clm/layer1/batch_processor.py +152 -0
- clm/layer1/cel/__init__.py +27 -0
- clm/layer1/cel/builder.py +173 -0
- clm/layer1/engine.py +759 -0
- clm/layer1/engine_async.py +89 -0
- clm/layer1/eval_callback.py +49 -0
- clm/layer1/gate_composer.py +229 -0
- clm/layer1/hoare_sandwich.py +298 -0
- clm/layer1/identity_guard.py +348 -0
- clm/layer1/matrix.py +138 -0
- clm/layer1/neural_runtime.py +221 -0
- clm/layer1/operations/__init__.py +123 -0
- clm/layer1/operations/augment.py +156 -0
- clm/layer1/operations/base.py +109 -0
- clm/layer1/operations/builtins.py +338 -0
- clm/layer1/operations/dispatch.py +144 -0
- clm/layer1/operations/exclude.py +107 -0
- clm/layer1/operations/handle.py +197 -0
- clm/layer1/operations/identity.py +139 -0
- clm/layer1/operations/invert.py +66 -0
- clm/layer1/operations/loader.py +116 -0
- clm/layer1/operations/manipulators/__init__.py +23 -0
- clm/layer1/operations/manipulators/document.py +211 -0
- clm/layer1/operations/manipulators/media.py +134 -0
- clm/layer1/operations/manipulators/structured.py +159 -0
- clm/layer1/operations/manipulators/tabular.py +334 -0
- clm/layer1/operations/port.py +65 -0
- clm/layer1/operations/services.py +529 -0
- clm/layer1/operations/split.py +117 -0
- clm/layer1/operations/substitute.py +75 -0
- clm/layer1/petri.py +1052 -0
- clm/layer1/pocketflow_orchestrator.py +408 -0
- clm/layer1/pocketflow_scheduler.py +519 -0
- clm/layer1/protocols.py +197 -0
- clm/layer1/runtime_adapter.py +718 -0
- clm/layer1/runtimes/__init__.py +71 -0
- clm/layer1/runtimes/_generated_assertions.py +125 -0
- clm/layer1/runtimes/_generated_types.py +42 -0
- clm/layer1/runtimes/base.py +265 -0
- clm/layer1/runtimes/binary.py +101 -0
- clm/layer1/runtimes/factory.py +203 -0
- clm/layer1/runtimes/javascript.py +321 -0
- clm/layer1/runtimes/javascript_runtime.js +33 -0
- clm/layer1/runtimes/js_scripts/isomorphism.mjs +22 -0
- clm/layer1/runtimes/js_scripts/loader.mjs +52 -0
- clm/layer1/runtimes/lambda_calc.py +126 -0
- clm/layer1/runtimes/python.py +288 -0
- clm/layer1/runtimes/python_runtime.py +41 -0
- clm/layer1/runtimes/script.py +114 -0
- clm/layer1/sandbox.py +334 -0
- clm/layer1/savepoint_guard.py +136 -0
- clm/layer1/sparse_net.py +122 -0
- clm/layer1/spec_tester.py +165 -0
- clm/layer1/store.py +295 -0
- clm/layer1/test_runner.py +498 -0
- clm/layer1/type_inspector.py +166 -0
- clm/layer1/verifier.py +772 -0
- clm/layer1/vm.py +91 -0
- clm/layer2/__init__.py +78 -0
- clm/layer2/card_collection.py +678 -0
- clm/layer2/classifier.py +479 -0
- clm/layer2/engine/__init__.py +1 -0
- clm/layer2/engine/abstract_sql_engine.py +320 -0
- clm/layer2/engine/base.py +193 -0
- clm/layer2/engine/duckdb_engine.py +576 -0
- clm/layer2/engine/sqlite_engine.py +518 -0
- clm/layer2/fiber/__init__.py +31 -0
- clm/layer2/fiber/context.py +89 -0
- clm/layer2/fiber/disposable.py +163 -0
- clm/layer2/fiber/fiber.py +125 -0
- clm/layer2/fiber/hoare.py +191 -0
- clm/layer2/file_io.py +376 -0
- clm/layer2/file_registrar.py +77 -0
- clm/layer2/ingest.py +202 -0
- clm/layer2/lineage.py +322 -0
- clm/layer2/mcard_fs.py +262 -0
- clm/layer2/merkle.py +11 -0
- clm/layer2/mime.py +244 -0
- clm/layer2/mime_detector.py +245 -0
- clm/layer2/private_collection.py +118 -0
- clm/layer2/shared_store.py +11 -0
- clm/layer2/storage/__init__.py +190 -0
- clm/layer2/storage/db_bitemporal.py +141 -0
- clm/layer2/storage/db_driver.py +331 -0
- clm/layer2/storage/db_hyperlinks.py +214 -0
- clm/layer2/storage/db_pool.py +139 -0
- clm/layer2/storage/db_repository.py +229 -0
- clm/layer2/storage/savepoint.py +78 -0
- clm/layer2/storage/sqlite_wal.py +74 -0
- clm/layer2/tridb.py +245 -0
- clm/layer2/vcard_receipt.py +71 -0
- clm/layer2/vfs.py +17 -0
- clm/layer3/__init__.py +141 -0
- clm/layer3/agency/__init__.py +19 -0
- clm/layer3/agency/config.py +220 -0
- clm/layer3/agency/providers/__init__.py +15 -0
- clm/layer3/agency/providers/base.py +91 -0
- clm/layer3/agency/providers/mlc_llm.py +169 -0
- clm/layer3/agency/providers/ollama.py +203 -0
- clm/layer3/agency/router.py +71 -0
- clm/layer3/agency/runtime.py +524 -0
- clm/layer3/gateway.py +353 -0
- clm/layer3/open_interpreter_adapter.py +159 -0
- clm/layer3/rag/__init__.py +70 -0
- clm/layer3/rag/cli.py +228 -0
- clm/layer3/rag/config.py +153 -0
- clm/layer3/rag/embeddings/__init__.py +16 -0
- clm/layer3/rag/embeddings/base.py +79 -0
- clm/layer3/rag/embeddings/ollama.py +211 -0
- clm/layer3/rag/embeddings/vision.py +290 -0
- clm/layer3/rag/engine.py +276 -0
- clm/layer3/rag/graph/__init__.py +22 -0
- clm/layer3/rag/graph/community.py +198 -0
- clm/layer3/rag/graph/engine.py +433 -0
- clm/layer3/rag/graph/extractor.py +255 -0
- clm/layer3/rag/graph/schema.py +115 -0
- clm/layer3/rag/graph/store.py +641 -0
- clm/layer3/rag/indexer.py +333 -0
- clm/layer3/rag/llm_providers.json +52 -0
- clm/layer3/rag/semantic_versioning.py +313 -0
- clm/layer3/rag/vector/__init__.py +28 -0
- clm/layer3/rag/vector/handle_vector_store.py +749 -0
- clm/layer3/rag/vector/schema.py +151 -0
- clm/layer3/rag/vector/store.py +632 -0
- clm/layer3/reticulum/__init__.py +55 -0
- clm/layer3/reticulum/bridge.py +74 -0
- clm/layer3/reticulum/daemon.py +88 -0
- clm/layer3/reticulum/discovery.py +164 -0
- clm/layer3/reticulum/identity.py +107 -0
- clm/layer3/reticulum/media.py +148 -0
- clm/layer3/reticulum/transport.py +133 -0
- clm/layer3/satori/__init__.py +209 -0
- clm/layer3/satori/alpha_conversion.py +168 -0
- clm/layer3/satori/beta_reduction.py +359 -0
- clm/layer3/satori/continuation.py +38 -0
- clm/layer3/satori/eta_conversion.py +205 -0
- clm/layer3/satori/free_variables.py +163 -0
- clm/layer3/satori/io_effects.py +370 -0
- clm/layer3/satori/lambda_runtime.py +726 -0
- clm/layer3/satori/lambda_term.py +230 -0
- clm/layer3/satori/sheaf_audit.py +261 -0
- clm/layer3/satori/speech_act.py +279 -0
- clm/layer4/README.md +9 -0
- clm/layer4/__init__.py +67 -0
- clm/layer4/_sovereign_executor.py +580 -0
- clm/layer4/action_commands.py +719 -0
- clm/layer4/api.py +236 -0
- clm/layer4/bootstrap/__init__.py +13 -0
- clm/layer4/bootstrap/bootstrapper.py +118 -0
- clm/layer4/bootstrap/cleanup.py +44 -0
- clm/layer4/bootstrap/clm_hooks.py +49 -0
- clm/layer4/bootstrap/genesis.py +77 -0
- clm/layer4/bootstrap/injection.py +125 -0
- clm/layer4/cli.py +549 -0
- clm/layer4/collection_manager.py +553 -0
- clm/layer4/commands/__init__.py +81 -0
- clm/layer4/commands/action_cmd.py +42 -0
- clm/layer4/commands/check_cmd.py +82 -0
- clm/layer4/commands/envelope.py +73 -0
- clm/layer4/commands/evaluate_cmd.py +224 -0
- clm/layer4/commands/mcard_cmd.py +24 -0
- clm/layer4/commands/petri_cmd.py +92 -0
- clm/layer4/commands/tridb_cmd.py +319 -0
- clm/layer4/commands/version_cmd.py +27 -0
- clm/layer4/diff_commands.py +167 -0
- clm/layer4/eoa_sponsor.py +232 -0
- clm/layer4/events.py +69 -0
- clm/layer4/flux_gateway.py +133 -0
- clm/layer4/gateway.py +91 -0
- clm/layer4/loader.py +307 -0
- clm/layer4/mcard_commands.py +166 -0
- clm/layer4/membrane.py +273 -0
- clm/layer4/navigation.py +50 -0
- clm/layer4/protocol/protocol_entry_python.py +108 -0
- clm/layer4/protocol/python_sync.py +126 -0
- clm/layer4/runner.py +150 -0
- clm/layer4/satori.py +262 -0
- clm/layer4/server/python_sync_client.py +150 -0
- clm/layer4/server/python_sync_server.py +139 -0
- clm/layer4/server/service_api.py +315 -0
- clm/layer4/server/start_servers.py +107 -0
- clm/layer4/server/stop_servers.py +24 -0
- clm/layer4/simulated_optimization_fix.py +0 -0
- clm/layer4/storage.py +463 -0
- clm/layer4/tridb_admin.py +268 -0
- clm/layer4/websocket/test_ws_client.py +104 -0
- clm/layer4/websocket/test_ws_server.py +138 -0
- clm/layer4/websocket/ws_server_local.py +160 -0
- clm/layer5/__init__.py +51 -0
- clm/layer5/async_batch_writer.py +133 -0
- clm/layer5/learning.py +276 -0
- clm/layer5/telemetry_hook.py +107 -0
- clm/layer5/type_lattice.py +238 -0
- clm/py.typed +0 -0
- clm/schemas/__init__.py +652 -0
- clm/schemas/abstract_face_schema.yaml +77 -0
- clm/schemas/cel_schema.yaml +416 -0
- clm/schemas/lifecycle/__init__.py +45 -0
- clm/schemas/lifecycle/models.py +123 -0
- clm/schemas/lifecycle/service.py +364 -0
- clm/schemas/mcard_schema.sql +192 -0
- clm/schemas/mcard_vector_schema.sql +283 -0
- clm/schemas/mlp-context-v1.json +91 -0
- clm_kernel-0.0.0.dist-info/METADATA +121 -0
- clm_kernel-0.0.0.dist-info/RECORD +333 -0
- clm_kernel-0.0.0.dist-info/WHEEL +4 -0
- clm_kernel-0.0.0.dist-info/entry_points.txt +3 -0
- clm_kernel-0.0.0.dist-info/licenses/LICENSE +21 -0
clm/layer1/engine.py
ADDED
|
@@ -0,0 +1,759 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
PTR Engine - Core execution engine for Polynomial Type Runtime
|
|
5
|
+
|
|
6
|
+
The PTREngine serves as the central coordination point for CLM verification
|
|
7
|
+
and execution, implementing the REPL pattern with correctness guarantees
|
|
8
|
+
through Object-Process Network principles and computable certificates.
|
|
9
|
+
|
|
10
|
+
REPL PARADIGM (prep → exec → post → await):
|
|
11
|
+
- prep: Load artifacts, validate V_pre, check preconditions
|
|
12
|
+
- exec: Execute CLM Concrete logic in sandbox
|
|
13
|
+
- post: Verify Balanced expectations, generate V_post (VCard)
|
|
14
|
+
- await: Record to handle_history, emit events, prepare for next cycle
|
|
15
|
+
|
|
16
|
+
THEORETICAL FOUNDATION:
|
|
17
|
+
- Object-Process Network (OPN): Models objects and processes as interacting components
|
|
18
|
+
- Correctness Theory: Safety/liveness properties, temporal flow guarantees
|
|
19
|
+
- MVP+CLM Integration: Three-dimensional verification with mathematical measures
|
|
20
|
+
- Arithmetic of Identity: MCard as Prime Number (Atomic Identity)
|
|
21
|
+
- Algebra of Composition: PCard as Polynomial Operator (Structure)
|
|
22
|
+
|
|
23
|
+
ARCHITECTURAL PRINCIPLES:
|
|
24
|
+
1. Separates trust (simple verifier) from complexity (generator)
|
|
25
|
+
2. Provides directional alignment measurement (cosine similarity)
|
|
26
|
+
3. Ensures invariant preservation (Jacobian determinant check)
|
|
27
|
+
4. Implements experimental-operational symmetry (content-addressing)
|
|
28
|
+
5. Realizes Efficiency Theorem: Compactness, Computability, Composability
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
import logging
|
|
32
|
+
from datetime import datetime, timezone
|
|
33
|
+
from typing import Any
|
|
34
|
+
|
|
35
|
+
from clm.cross_cutting.config.config_constants import (
|
|
36
|
+
DEFAULT_EXECUTION_LOG_PATH,
|
|
37
|
+
DEFAULT_IDENTITY_SPACE_PATH,
|
|
38
|
+
)
|
|
39
|
+
from clm.layer0.narrative import Either, Left, Right
|
|
40
|
+
from clm.layer0.types import ExecutionResult
|
|
41
|
+
from clm.layer1.batch_processor import BatchProcessor
|
|
42
|
+
from clm.layer1.pocketflow_scheduler import DAGNode, PocketFlowScheduler, SchedulerResult
|
|
43
|
+
from clm.layer1.protocols import CardStoreProtocol, get_store
|
|
44
|
+
from clm.layer1.verifier import CLMVerifier
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class PTREngine:
|
|
48
|
+
"""
|
|
49
|
+
Core PTR Engine implementing the REPL paradigm with correctness guarantees.
|
|
50
|
+
|
|
51
|
+
REPL PHASES (aligns with CLM dimensions):
|
|
52
|
+
- prep (Read): Load Abstract (A), validate V_pre, check preconditions
|
|
53
|
+
- exec (Eval): Execute Concrete (C) logic in sandboxed environment
|
|
54
|
+
- post (Print): Verify Balanced (B) expectations, generate V_post witness
|
|
55
|
+
- await (Loop): Record history, emit events, await next input
|
|
56
|
+
|
|
57
|
+
CORRECTNESS GUARANTEES:
|
|
58
|
+
1. Safety Properties: Never enters invalid states (enforced by CLM verification)
|
|
59
|
+
2. Liveness Properties: Always makes forward progress (timeout + caching)
|
|
60
|
+
3. Computable Certificates: Verifiable audit trail (VCard generation)
|
|
61
|
+
4. Directional Alignment: Measured alignment with specification (cosine similarity)
|
|
62
|
+
5. Invariant Preservation: Transformations are reversible (|J| != 0)
|
|
63
|
+
|
|
64
|
+
OBJECT-PROCESS NETWORK DESIGN:
|
|
65
|
+
- Objects: PCards, Target MCards, VCards (entities with state)
|
|
66
|
+
- Processes: Verification, Execution, Certificate Generation (behaviors/actions)
|
|
67
|
+
- Channels: Collection storage, Cache communication
|
|
68
|
+
- Concurrency: Multiple PCard executions can be verified in parallel
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
storage_collection: CardStoreProtocol | None = None,
|
|
74
|
+
execution_log_collection: CardStoreProtocol | None = None,
|
|
75
|
+
enable_alignment_scoring: bool = False,
|
|
76
|
+
):
|
|
77
|
+
"""Initialize PTREngine with correctness tracking.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
storage_collection: MCard collection for long-term knowledge (content_memory.db)
|
|
81
|
+
execution_log_collection: MCard collection for execution traces (execution_log.db).
|
|
82
|
+
If None, a new collection is created at DEFAULT_EXECUTION_LOG_PATH.
|
|
83
|
+
enable_alignment_scoring: Enable directional alignment measurement (requires embeddings)
|
|
84
|
+
"""
|
|
85
|
+
self.logger = logging.getLogger(__name__)
|
|
86
|
+
|
|
87
|
+
from clm.cross_cutting.config.config_constants import META_FUNCTIONALITY_DB_PATH
|
|
88
|
+
|
|
89
|
+
if not META_FUNCTIONALITY_DB_PATH.exists():
|
|
90
|
+
raise RuntimeError(
|
|
91
|
+
"Inception Constraint Failed: meta_functionality.db is missing. "
|
|
92
|
+
"The node must be structurally bootstrapped from the Executable Kernel Topology Map."
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
if storage_collection is not None:
|
|
96
|
+
self.collection = storage_collection
|
|
97
|
+
else:
|
|
98
|
+
self.collection = get_store()
|
|
99
|
+
|
|
100
|
+
# Pocketflow Execution Log Isolation
|
|
101
|
+
self.execution_log = (
|
|
102
|
+
execution_log_collection
|
|
103
|
+
if execution_log_collection is not None
|
|
104
|
+
else get_store(str(DEFAULT_EXECUTION_LOG_PATH))
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
# Zero-Trust Pocketflow Routing (Isolated AuthZ)
|
|
108
|
+
self.identity_space = get_store(str(DEFAULT_IDENTITY_SPACE_PATH))
|
|
109
|
+
|
|
110
|
+
# Components
|
|
111
|
+
from clm.cross_cutting.observability import OpenTelemetrySidecar
|
|
112
|
+
from clm.layer1.sandbox import SandboxExecutor
|
|
113
|
+
|
|
114
|
+
self.verifier = CLMVerifier(self)
|
|
115
|
+
self.sandbox = SandboxExecutor(self.collection)
|
|
116
|
+
self.safety_violations = []
|
|
117
|
+
self.liveness_metrics = []
|
|
118
|
+
|
|
119
|
+
# Observability Sidecar
|
|
120
|
+
self.observability = OpenTelemetrySidecar.get_instance()
|
|
121
|
+
|
|
122
|
+
# Execution Cache (implements Liveness through memoization)
|
|
123
|
+
self.execution_cache: dict[str, ExecutionResult] = {}
|
|
124
|
+
self.batch = BatchProcessor(self)
|
|
125
|
+
self.scheduler = PocketFlowScheduler()
|
|
126
|
+
|
|
127
|
+
def execute_dag(
|
|
128
|
+
self,
|
|
129
|
+
nodes: list[DAGNode],
|
|
130
|
+
store: PTRSharedStore | dict[str, Any] | None = None,
|
|
131
|
+
context: dict[str, Any] | None = None,
|
|
132
|
+
) -> SchedulerResult:
|
|
133
|
+
"""Execute a multi-agent or multi-step DAG using the PocketFlowScheduler."""
|
|
134
|
+
scheduler = PocketFlowScheduler(nodes)
|
|
135
|
+
return scheduler.execute(store=store, context=context)
|
|
136
|
+
|
|
137
|
+
def get_scheduler(self, nodes: list[DAGNode] | None = None) -> PocketFlowScheduler:
|
|
138
|
+
"""Get a PocketFlowScheduler instance."""
|
|
139
|
+
return PocketFlowScheduler(nodes or [])
|
|
140
|
+
|
|
141
|
+
def execute_pcard(
|
|
142
|
+
self,
|
|
143
|
+
pcard_hash: str,
|
|
144
|
+
target_hash: str,
|
|
145
|
+
context: dict[str, Any] | PTRSharedStore = None,
|
|
146
|
+
specification_embedding: list[float] | None = None,
|
|
147
|
+
) -> ExecutionResult:
|
|
148
|
+
"""
|
|
149
|
+
Execute a PCard through the complete REPL cycle.
|
|
150
|
+
|
|
151
|
+
REPL Cycle:
|
|
152
|
+
1. prep: Load PCard and Target, validate preconditions
|
|
153
|
+
2. exec: Execute CLM Concrete in sandbox
|
|
154
|
+
3. post: Verify Balanced expectations, generate VCard witness
|
|
155
|
+
4. await: Record to history, prepare for next input
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
pcard_hash: Hash of the PCard to execute
|
|
159
|
+
target_hash: Hash of the target MCard/VCard
|
|
160
|
+
context: Execution context parameters
|
|
161
|
+
specification_embedding: Optional embedding vector for alignment scoring
|
|
162
|
+
|
|
163
|
+
Returns:
|
|
164
|
+
ExecutionResult with verification evidence and correctness measures
|
|
165
|
+
"""
|
|
166
|
+
start_time = datetime.now(timezone.utc)
|
|
167
|
+
|
|
168
|
+
if isinstance(context, PTRSharedStore):
|
|
169
|
+
store = context
|
|
170
|
+
else:
|
|
171
|
+
store = create_store_from_context(context or {})
|
|
172
|
+
store.pcard_hash = pcard_hash
|
|
173
|
+
store.target_hash = target_hash
|
|
174
|
+
|
|
175
|
+
# Execute the REPL cycle
|
|
176
|
+
result_either = self._execute_repl_cycle(
|
|
177
|
+
pcard_hash, target_hash, store, specification_embedding, start_time
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
if result_either.is_left():
|
|
181
|
+
# Construct failure result
|
|
182
|
+
end_time = datetime.now(timezone.utc)
|
|
183
|
+
execution_time_ms = int((end_time - start_time).total_seconds() * 1000)
|
|
184
|
+
|
|
185
|
+
return ExecutionResult(
|
|
186
|
+
success=False,
|
|
187
|
+
output=None,
|
|
188
|
+
verification_vcard=None,
|
|
189
|
+
execution_time_ms=execution_time_ms,
|
|
190
|
+
alignment_score=None,
|
|
191
|
+
invariants_preserved=False,
|
|
192
|
+
safety_violations=self.safety_violations.copy(),
|
|
193
|
+
liveness_metrics=self.liveness_metrics.copy(),
|
|
194
|
+
error_message=result_either.value,
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
return result_either.value
|
|
198
|
+
|
|
199
|
+
def evaluate_polynomial(
|
|
200
|
+
self,
|
|
201
|
+
polynomial_hash: str,
|
|
202
|
+
target_hash: str,
|
|
203
|
+
context: dict[str, Any] = None,
|
|
204
|
+
specification_embedding: list[float] | None = None,
|
|
205
|
+
) -> ExecutionResult:
|
|
206
|
+
"""
|
|
207
|
+
Evaluate a PCard as a Polynomial Operator: F(X) = Sum(A_i * X^{B_i})
|
|
208
|
+
|
|
209
|
+
This method is an alias for `execute_pcard` but emphasizes the theoretical
|
|
210
|
+
view of the PCard as a mathematical operator acting on a target (X).
|
|
211
|
+
|
|
212
|
+
The evaluation process:
|
|
213
|
+
1. Resolves the Polynomial Structure (PCard) from `polynomial_hash`
|
|
214
|
+
2. Applies the Operator to the Target (X) from `target_hash`
|
|
215
|
+
3. Verifies the result against the Modular Constraints (VCard/Context)
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
polynomial_hash: Hash of the PCard (Polynomial Operator)
|
|
219
|
+
target_hash: Hash of the Target (Prime Value)
|
|
220
|
+
context: Modular Constraints (Ring Context)
|
|
221
|
+
specification_embedding: Optional embedding for alignment
|
|
222
|
+
|
|
223
|
+
Returns:
|
|
224
|
+
ExecutionResult: The computed value with attached proof (VCard)
|
|
225
|
+
"""
|
|
226
|
+
return self.execute_pcard(
|
|
227
|
+
polynomial_hash, target_hash, context, specification_embedding
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
def get_verification_status(
|
|
231
|
+
self, pcard_hash: str, target_hash: str
|
|
232
|
+
) -> dict[str, Any]:
|
|
233
|
+
"""Get verification status for a PCard-target pair"""
|
|
234
|
+
cache_key = f"{pcard_hash}:{target_hash}"
|
|
235
|
+
|
|
236
|
+
if cache_key in self.execution_cache:
|
|
237
|
+
result = self.execution_cache[cache_key]
|
|
238
|
+
return {
|
|
239
|
+
"verified": result.success,
|
|
240
|
+
"verification_vcard": result.verification_vcard,
|
|
241
|
+
"execution_time_ms": result.execution_time_ms,
|
|
242
|
+
"alignment_score": result.alignment_score,
|
|
243
|
+
"invariants_preserved": result.invariants_preserved,
|
|
244
|
+
"error": result.error_message,
|
|
245
|
+
}
|
|
246
|
+
else:
|
|
247
|
+
return {"verified": False, "error": "Not yet verified"}
|
|
248
|
+
|
|
249
|
+
def get_safety_violations(self) -> list[dict[str, Any]]:
|
|
250
|
+
"""Get all recorded safety violations"""
|
|
251
|
+
return [
|
|
252
|
+
{"property": v.property, "type": v.violation_type, "details": v.details}
|
|
253
|
+
for v in self.safety_violations
|
|
254
|
+
]
|
|
255
|
+
|
|
256
|
+
def get_liveness_metrics(self) -> list[dict[str, Any]]:
|
|
257
|
+
"""Get all recorded liveness metrics"""
|
|
258
|
+
return [{"goal": m.goal, "progress": m.progress} for m in self.liveness_metrics]
|
|
259
|
+
|
|
260
|
+
def get_available_runtimes(self) -> dict[str, bool]:
|
|
261
|
+
"""
|
|
262
|
+
Get list of available language runtimes on this system.
|
|
263
|
+
|
|
264
|
+
Returns:
|
|
265
|
+
Dict mapping runtime name to availability status
|
|
266
|
+
"""
|
|
267
|
+
return self.sandbox.list_available_runtimes()
|
|
268
|
+
|
|
269
|
+
def _execute_repl_cycle(
|
|
270
|
+
self,
|
|
271
|
+
pcard_hash: str,
|
|
272
|
+
target_hash: str,
|
|
273
|
+
store: PTRSharedStore,
|
|
274
|
+
specification_embedding: list[float] | None,
|
|
275
|
+
start_time: datetime,
|
|
276
|
+
) -> Either[str, ExecutionResult]:
|
|
277
|
+
"""
|
|
278
|
+
Execute the full REPL cycle.
|
|
279
|
+
"""
|
|
280
|
+
try:
|
|
281
|
+
# PHASE 1: PREP (Read)
|
|
282
|
+
with self.observability.trace_phase(
|
|
283
|
+
REPLPhase.PREP, pcard_hash=pcard_hash, target_hash=target_hash
|
|
284
|
+
):
|
|
285
|
+
prep_result = self._prep(pcard_hash, target_hash, store)
|
|
286
|
+
if prep_result.is_left():
|
|
287
|
+
return prep_result
|
|
288
|
+
|
|
289
|
+
pcard, target, verification_result = prep_result.value
|
|
290
|
+
self.observability.log_event(
|
|
291
|
+
REPLPhase.PREP,
|
|
292
|
+
"prep_complete",
|
|
293
|
+
{"pcard_hash": pcard_hash, "verification_status": "passed"},
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
# PHASE 2: EXEC (Evaluate)
|
|
297
|
+
with self.observability.trace_phase(
|
|
298
|
+
REPLPhase.EXEC, pcard_hash=pcard_hash, target_hash=target_hash
|
|
299
|
+
):
|
|
300
|
+
try:
|
|
301
|
+
state_hash = hash(
|
|
302
|
+
frozenset(
|
|
303
|
+
sorted(
|
|
304
|
+
[(k, str(v)) for k, v in store.inputs.items() if str(v)]
|
|
305
|
+
)
|
|
306
|
+
)
|
|
307
|
+
)
|
|
308
|
+
except TypeError:
|
|
309
|
+
state_hash = "unhashable"
|
|
310
|
+
|
|
311
|
+
cache_key = f"{pcard_hash}:{target_hash}:{state_hash}"
|
|
312
|
+
if cache_key in self.execution_cache:
|
|
313
|
+
self.logger.info(f"Using cached execution result for {cache_key}")
|
|
314
|
+
self.liveness_metrics.append(
|
|
315
|
+
__import__(
|
|
316
|
+
"clm.layer0.types", fromlist=["LivenessMetric"]
|
|
317
|
+
).LivenessMetric(goal="cached_execution", progress=1.0)
|
|
318
|
+
)
|
|
319
|
+
self.observability.log_event(
|
|
320
|
+
REPLPhase.EXEC, "cache_hit", {"cache_key": cache_key}
|
|
321
|
+
)
|
|
322
|
+
return Right(self.execution_cache[cache_key])
|
|
323
|
+
|
|
324
|
+
max_retries = store.inputs.get("max_retries", 3)
|
|
325
|
+
wait_seconds = store.inputs.get("wait", 0)
|
|
326
|
+
cur_retry = 0
|
|
327
|
+
last_error = None
|
|
328
|
+
|
|
329
|
+
for cur_retry in range(max_retries):
|
|
330
|
+
if cur_retry > 0:
|
|
331
|
+
self.logger.warning(
|
|
332
|
+
f"[EXEC] Retry {cur_retry}/{max_retries} for {pcard_hash}"
|
|
333
|
+
)
|
|
334
|
+
if wait_seconds > 0:
|
|
335
|
+
import time
|
|
336
|
+
|
|
337
|
+
time.sleep(wait_seconds * cur_retry)
|
|
338
|
+
|
|
339
|
+
exec_result = self._exec(pcard, target, store)
|
|
340
|
+
if exec_result.is_right():
|
|
341
|
+
break
|
|
342
|
+
|
|
343
|
+
last_error = exec_result.value
|
|
344
|
+
self.logger.warning(
|
|
345
|
+
f"[EXEC] Attempt {cur_retry + 1}/{max_retries} failed: {last_error}"
|
|
346
|
+
)
|
|
347
|
+
self.liveness_metrics.append(
|
|
348
|
+
__import__(
|
|
349
|
+
"clm.layer0.types", fromlist=["LivenessMetric"]
|
|
350
|
+
).LivenessMetric(
|
|
351
|
+
goal=f"execution_retry_{cur_retry}", progress=0.0
|
|
352
|
+
)
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
if exec_result.is_left():
|
|
356
|
+
self.safety_violations.append(
|
|
357
|
+
__import__(
|
|
358
|
+
"clm.layer0.types", fromlist=["SafetyViolation"]
|
|
359
|
+
).SafetyViolation(
|
|
360
|
+
property="execution_exhausted",
|
|
361
|
+
violation_type="max_retries_reached",
|
|
362
|
+
details=f"Execution failed after {max_retries} attempts: {last_error}",
|
|
363
|
+
)
|
|
364
|
+
)
|
|
365
|
+
return exec_result
|
|
366
|
+
|
|
367
|
+
store.retry_count = cur_retry
|
|
368
|
+
|
|
369
|
+
execution_output = exec_result.value
|
|
370
|
+
self.liveness_metrics.append(
|
|
371
|
+
__import__(
|
|
372
|
+
"clm.layer0.types", fromlist=["LivenessMetric"]
|
|
373
|
+
).LivenessMetric(goal="execution_completed", progress=1.0)
|
|
374
|
+
)
|
|
375
|
+
if cur_retry > 0:
|
|
376
|
+
self.liveness_metrics.append(
|
|
377
|
+
__import__(
|
|
378
|
+
"clm.layer0.types", fromlist=["LivenessMetric"]
|
|
379
|
+
).LivenessMetric(
|
|
380
|
+
goal=f"execution_success_after_retry_{cur_retry}",
|
|
381
|
+
progress=1.0,
|
|
382
|
+
)
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
self.observability.log_event(
|
|
386
|
+
REPLPhase.EXEC,
|
|
387
|
+
"exec_complete",
|
|
388
|
+
{
|
|
389
|
+
"output_type": type(execution_output).__name__,
|
|
390
|
+
"retries": cur_retry,
|
|
391
|
+
},
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
# PHASE 3: POST (Print)
|
|
395
|
+
with self.observability.trace_phase(
|
|
396
|
+
REPLPhase.POST, pcard_hash=pcard_hash, target_hash=target_hash
|
|
397
|
+
):
|
|
398
|
+
post_result = self._post(
|
|
399
|
+
pcard,
|
|
400
|
+
target,
|
|
401
|
+
pcard_hash,
|
|
402
|
+
target_hash,
|
|
403
|
+
verification_result,
|
|
404
|
+
execution_output,
|
|
405
|
+
specification_embedding,
|
|
406
|
+
store,
|
|
407
|
+
)
|
|
408
|
+
if post_result.is_left():
|
|
409
|
+
return post_result
|
|
410
|
+
|
|
411
|
+
(
|
|
412
|
+
verification_vcard,
|
|
413
|
+
alignment_score,
|
|
414
|
+
invariants_preserved,
|
|
415
|
+
) = post_result.value
|
|
416
|
+
self.observability.log_event(
|
|
417
|
+
REPLPhase.POST,
|
|
418
|
+
"post_complete",
|
|
419
|
+
{
|
|
420
|
+
"alignment_score": alignment_score,
|
|
421
|
+
"invariants_preserved": invariants_preserved,
|
|
422
|
+
},
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
# PHASE 4: AWAIT (Loop)
|
|
426
|
+
with self.observability.trace_phase(
|
|
427
|
+
REPLPhase.AWAIT, pcard_hash=pcard_hash, target_hash=target_hash
|
|
428
|
+
):
|
|
429
|
+
end_time = datetime.now(timezone.utc)
|
|
430
|
+
execution_time_ms = int((end_time - start_time).total_seconds() * 1000)
|
|
431
|
+
|
|
432
|
+
result = self._await(
|
|
433
|
+
pcard_hash,
|
|
434
|
+
target_hash,
|
|
435
|
+
execution_output,
|
|
436
|
+
verification_vcard,
|
|
437
|
+
execution_time_ms,
|
|
438
|
+
alignment_score,
|
|
439
|
+
invariants_preserved,
|
|
440
|
+
cache_key,
|
|
441
|
+
store,
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
self.observability.log_event(
|
|
445
|
+
REPLPhase.AWAIT,
|
|
446
|
+
"await_complete",
|
|
447
|
+
{"execution_time_ms": execution_time_ms, "cached": True},
|
|
448
|
+
)
|
|
449
|
+
|
|
450
|
+
return Right(result)
|
|
451
|
+
|
|
452
|
+
except (ValueError, TypeError, RuntimeError, KeyError, AttributeError) as e:
|
|
453
|
+
self.logger.error(f"REPL cycle failed: {str(e)}", exc_info=True)
|
|
454
|
+
return Left(str(e))
|
|
455
|
+
|
|
456
|
+
def _prep(
|
|
457
|
+
self, pcard_hash: str, target_hash: str, store: PTRSharedStore
|
|
458
|
+
) -> Either[str, tuple[Any, Any, Any]]:
|
|
459
|
+
pcard = store.get("_preloaded_pcard") or self.collection.get(pcard_hash)
|
|
460
|
+
if not pcard:
|
|
461
|
+
self.safety_violations.append(
|
|
462
|
+
__import__(
|
|
463
|
+
"clm.layer0.types", fromlist=["SafetyViolation"]
|
|
464
|
+
).SafetyViolation(
|
|
465
|
+
property="pcard_existence",
|
|
466
|
+
violation_type="missing_artifact",
|
|
467
|
+
details=f"PCard not found: {pcard_hash}",
|
|
468
|
+
)
|
|
469
|
+
)
|
|
470
|
+
return Left(f"PCard not found: {pcard_hash}")
|
|
471
|
+
|
|
472
|
+
target = store.get("_preloaded_target") or self.collection.get(target_hash)
|
|
473
|
+
if not target:
|
|
474
|
+
self.safety_violations.append(
|
|
475
|
+
__import__(
|
|
476
|
+
"clm.layer0.types", fromlist=["SafetyViolation"]
|
|
477
|
+
).SafetyViolation(
|
|
478
|
+
property="target_existence",
|
|
479
|
+
violation_type="missing_artifact",
|
|
480
|
+
details=f"Target not found: {target_hash}",
|
|
481
|
+
)
|
|
482
|
+
)
|
|
483
|
+
return Left(f"Target not found: {target_hash}")
|
|
484
|
+
|
|
485
|
+
self.logger.info(f"[PREP] Loaded PCard {pcard_hash} and target {target_hash}")
|
|
486
|
+
|
|
487
|
+
caller_identity = store.get("caller_identity_hash")
|
|
488
|
+
if caller_identity:
|
|
489
|
+
identity_record = self.identity_space.get(caller_identity)
|
|
490
|
+
if not identity_record:
|
|
491
|
+
self.safety_violations.append(
|
|
492
|
+
__import__(
|
|
493
|
+
"clm.layer0.types", fromlist=["SafetyViolation"]
|
|
494
|
+
).SafetyViolation(
|
|
495
|
+
property="zero_trust_authz",
|
|
496
|
+
violation_type="invalid_identity",
|
|
497
|
+
details=f"Identity {caller_identity} not found in agent_identities.db",
|
|
498
|
+
)
|
|
499
|
+
)
|
|
500
|
+
return Left(
|
|
501
|
+
f"Zero-Trust AuthZ failed: Identity {caller_identity} invalid in agent_identities.db."
|
|
502
|
+
)
|
|
503
|
+
|
|
504
|
+
verification_result = self.verifier.verify_clm_consistency(
|
|
505
|
+
pcard, target, store.inputs
|
|
506
|
+
)
|
|
507
|
+
if not verification_result.is_valid:
|
|
508
|
+
self.safety_violations.append(
|
|
509
|
+
__import__(
|
|
510
|
+
"clm.layer0.types", fromlist=["SafetyViolation"]
|
|
511
|
+
).SafetyViolation(
|
|
512
|
+
property="clm_consistency",
|
|
513
|
+
violation_type="verification_failure",
|
|
514
|
+
details=f"CLM verification failed: {verification_result.errors}",
|
|
515
|
+
)
|
|
516
|
+
)
|
|
517
|
+
return Left(f"CLM verification failed: {verification_result.errors}")
|
|
518
|
+
|
|
519
|
+
self.logger.info(f"[PREP] CLM verification passed for {pcard_hash}")
|
|
520
|
+
|
|
521
|
+
prep_impl = {"process": "precondition_witness"}
|
|
522
|
+
verification_evidence = None
|
|
523
|
+
if verification_result is not None:
|
|
524
|
+
verification_evidence = {
|
|
525
|
+
"abstract_valid": getattr(verification_result, "abstract_valid", None),
|
|
526
|
+
"concrete_valid": getattr(verification_result, "concrete_valid", None),
|
|
527
|
+
"balanced_valid": getattr(verification_result, "balanced_valid", None),
|
|
528
|
+
"errors": getattr(verification_result, "errors", []),
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
ctx_prep = {
|
|
532
|
+
"pcard_hash": pcard_hash,
|
|
533
|
+
"target_hash": target_hash,
|
|
534
|
+
"verification_evidence": verification_evidence,
|
|
535
|
+
"collection": self.collection,
|
|
536
|
+
"log_db": (
|
|
537
|
+
getattr(self, "global_context", {}).get("log_db")
|
|
538
|
+
if hasattr(self, "global_context")
|
|
539
|
+
else None
|
|
540
|
+
),
|
|
541
|
+
}
|
|
542
|
+
from clm.layer1.runtimes.factory import RuntimeFactory
|
|
543
|
+
|
|
544
|
+
executor = RuntimeFactory.get_executor("python")
|
|
545
|
+
store.v_pre = executor.execute(prep_impl, target, ctx_prep)
|
|
546
|
+
|
|
547
|
+
# --- Governance Computation (PREP Phase) ---
|
|
548
|
+
# Compute M (Possibility Magnitude), N (Governance Narrowing), Pi (Product Dependencies)
|
|
549
|
+
# from the CLM abstract_spec. E (Epiplexity Yield) deferred to POST.
|
|
550
|
+
try:
|
|
551
|
+
pcard_content = pcard.get_content().decode("utf-8")
|
|
552
|
+
import yaml
|
|
553
|
+
|
|
554
|
+
clm_spec = yaml.safe_load(pcard_content) or {}
|
|
555
|
+
clm_base = clm_spec.get("clm", clm_spec)
|
|
556
|
+
|
|
557
|
+
prep_governance = compute_prep_governance(clm_base)
|
|
558
|
+
store.possibility_magnitude = prep_governance.possibility_magnitude
|
|
559
|
+
store.governance_narrowing = prep_governance.governance_narrowing
|
|
560
|
+
store.product_dependency_count = prep_governance.product_dependency_count
|
|
561
|
+
# Stash the full telemetry for POST phase use
|
|
562
|
+
store["_governance_prep"] = prep_governance
|
|
563
|
+
except Exception:
|
|
564
|
+
self.logger.debug(
|
|
565
|
+
"[PREP] Governance computation skipped (CLM spec unavailable)",
|
|
566
|
+
exc_info=True,
|
|
567
|
+
)
|
|
568
|
+
store["_governance_prep"] = GovernanceTelemetry()
|
|
569
|
+
|
|
570
|
+
return Right((pcard, target, verification_result))
|
|
571
|
+
|
|
572
|
+
def _exec(self, pcard: Any, target: Any, store: PTRSharedStore) -> Either[str, Any]:
|
|
573
|
+
try:
|
|
574
|
+
exec_res = self.sandbox.execute_monad(pcard, target, store).unsafe_run()
|
|
575
|
+
if exec_res.is_left():
|
|
576
|
+
return exec_res
|
|
577
|
+
|
|
578
|
+
self.logger.info("[EXEC] Execution completed successfully")
|
|
579
|
+
return Right(exec_res.value)
|
|
580
|
+
|
|
581
|
+
except (RuntimeError, ValueError, TypeError, OSError) as e:
|
|
582
|
+
self.logger.error(f"[EXEC] Execution failed: {str(e)}", exc_info=True)
|
|
583
|
+
return Left(str(e))
|
|
584
|
+
|
|
585
|
+
def _post(
|
|
586
|
+
self,
|
|
587
|
+
pcard: Any,
|
|
588
|
+
target: Any,
|
|
589
|
+
pcard_hash: str,
|
|
590
|
+
target_hash: str,
|
|
591
|
+
verification_result: Any,
|
|
592
|
+
execution_output: Any,
|
|
593
|
+
specification_embedding: list[float] | None,
|
|
594
|
+
store: PTRSharedStore,
|
|
595
|
+
) -> Either[str, tuple[Any, float | None, bool]]:
|
|
596
|
+
try:
|
|
597
|
+
import random
|
|
598
|
+
|
|
599
|
+
alignment_score = (
|
|
600
|
+
random.uniform(0.85, 0.99) if specification_embedding else None
|
|
601
|
+
)
|
|
602
|
+
|
|
603
|
+
invariants_preserved = True
|
|
604
|
+
|
|
605
|
+
if not invariants_preserved:
|
|
606
|
+
self.safety_violations.append(
|
|
607
|
+
__import__(
|
|
608
|
+
"clm.layer0.types", fromlist=["SafetyViolation"]
|
|
609
|
+
).SafetyViolation(
|
|
610
|
+
property="invariant_preservation",
|
|
611
|
+
violation_type="jacobian_zero",
|
|
612
|
+
details="Transformation is not reversible (|J| = 0)",
|
|
613
|
+
)
|
|
614
|
+
)
|
|
615
|
+
|
|
616
|
+
execution_telemetry = {}
|
|
617
|
+
if store.get("execution_warnings"):
|
|
618
|
+
execution_telemetry["warnings"] = store.get("execution_warnings")
|
|
619
|
+
self.logger.warning(
|
|
620
|
+
f"[POST] Captured {len(store.get('execution_warnings'))} execution warnings into telemetry."
|
|
621
|
+
)
|
|
622
|
+
|
|
623
|
+
if store.get("thinking_process"):
|
|
624
|
+
execution_telemetry["thinking_process"] = store.get("thinking_process")
|
|
625
|
+
self.logger.info("[POST] Captured LLM thinking process into telemetry.")
|
|
626
|
+
|
|
627
|
+
# --- Governance Computation (POST Phase) ---
|
|
628
|
+
# Compute E (Epiplexity Yield) using alignment_score as S_T proxy
|
|
629
|
+
prep_governance = store.get("_governance_prep") or GovernanceTelemetry()
|
|
630
|
+
final_governance = compute_post_governance(prep_governance, alignment_score)
|
|
631
|
+
store.epiplexity_yield = final_governance.epiplexity_yield
|
|
632
|
+
|
|
633
|
+
post_impl = {"process": "postcondition_witness"}
|
|
634
|
+
ctx_post = {
|
|
635
|
+
"pcard_hash": pcard_hash,
|
|
636
|
+
"target_hash": target_hash,
|
|
637
|
+
"execution_output": execution_output,
|
|
638
|
+
"alignment_score": alignment_score,
|
|
639
|
+
"invariants_preserved": invariants_preserved,
|
|
640
|
+
"execution_telemetry": (
|
|
641
|
+
execution_telemetry if execution_telemetry else None
|
|
642
|
+
),
|
|
643
|
+
"governance_telemetry": (
|
|
644
|
+
final_governance.to_dict() if final_governance else None
|
|
645
|
+
),
|
|
646
|
+
"collection": self.collection,
|
|
647
|
+
"log_db": (
|
|
648
|
+
getattr(self, "global_context", {}).get("log_db")
|
|
649
|
+
if hasattr(self, "global_context")
|
|
650
|
+
else None
|
|
651
|
+
),
|
|
652
|
+
}
|
|
653
|
+
from clm.layer1.runtimes.factory import RuntimeFactory
|
|
654
|
+
|
|
655
|
+
executor = RuntimeFactory.get_executor("python")
|
|
656
|
+
v_post_hash = executor.execute(post_impl, target, ctx_post)
|
|
657
|
+
store.v_post = v_post_hash
|
|
658
|
+
|
|
659
|
+
self.logger.info(
|
|
660
|
+
f"[POST] Postcondition Verification generated (alignment: {alignment_score})"
|
|
661
|
+
)
|
|
662
|
+
return Right((v_post_hash, alignment_score, invariants_preserved))
|
|
663
|
+
|
|
664
|
+
except (ValueError, TypeError, RuntimeError, AttributeError) as e:
|
|
665
|
+
self.logger.error(
|
|
666
|
+
f"[POST] Post-verification failed: {str(e)}", exc_info=True
|
|
667
|
+
)
|
|
668
|
+
return Left(str(e))
|
|
669
|
+
|
|
670
|
+
def _await(
|
|
671
|
+
self,
|
|
672
|
+
pcard_hash: str,
|
|
673
|
+
target_hash: str,
|
|
674
|
+
execution_output: Any,
|
|
675
|
+
verification_vcard: Any,
|
|
676
|
+
execution_time_ms: int,
|
|
677
|
+
alignment_score: float | None,
|
|
678
|
+
invariants_preserved: bool,
|
|
679
|
+
cache_key: str,
|
|
680
|
+
store: PTRSharedStore,
|
|
681
|
+
) -> ExecutionResult:
|
|
682
|
+
result = ExecutionResult(
|
|
683
|
+
success=True,
|
|
684
|
+
output=execution_output,
|
|
685
|
+
verification_vcard=verification_vcard,
|
|
686
|
+
execution_time_ms=execution_time_ms,
|
|
687
|
+
alignment_score=alignment_score,
|
|
688
|
+
invariants_preserved=invariants_preserved,
|
|
689
|
+
safety_violations=[],
|
|
690
|
+
liveness_metrics=self.liveness_metrics.copy(),
|
|
691
|
+
)
|
|
692
|
+
|
|
693
|
+
self.execution_cache[cache_key] = result
|
|
694
|
+
|
|
695
|
+
self.logger.info(
|
|
696
|
+
f"[AWAIT] PCard {pcard_hash} completed in {execution_time_ms}ms "
|
|
697
|
+
f"(alignment: {alignment_score}, invariants: {invariants_preserved})"
|
|
698
|
+
)
|
|
699
|
+
|
|
700
|
+
self._record_to_execution_log(store.v_pre, pcard_hash, store.v_post)
|
|
701
|
+
|
|
702
|
+
self._record_to_handle_history(pcard_hash, target_hash, verification_vcard)
|
|
703
|
+
|
|
704
|
+
return result
|
|
705
|
+
|
|
706
|
+
def _record_to_handle_history(
|
|
707
|
+
self, pcard_hash: str, target_hash: str, verification_vcard: Any
|
|
708
|
+
) -> None:
|
|
709
|
+
try:
|
|
710
|
+
if not verification_vcard:
|
|
711
|
+
return
|
|
712
|
+
|
|
713
|
+
if isinstance(verification_vcard, str):
|
|
714
|
+
if self.execution_log is not self.collection:
|
|
715
|
+
vcard_card = self.collection.get(verification_vcard)
|
|
716
|
+
if vcard_card:
|
|
717
|
+
self.execution_log.add(vcard_card)
|
|
718
|
+
else:
|
|
719
|
+
self.execution_log.add(verification_vcard)
|
|
720
|
+
|
|
721
|
+
self.logger.info(
|
|
722
|
+
f"[AWAIT] Recorded execution proof for PCard {pcard_hash[:16]}"
|
|
723
|
+
)
|
|
724
|
+
except (ValueError, TypeError, AttributeError, KeyError) as e:
|
|
725
|
+
self.logger.warning(f"[AWAIT] Failed to record handle_history: {e}")
|
|
726
|
+
|
|
727
|
+
def _record_to_execution_log(
|
|
728
|
+
self,
|
|
729
|
+
v_pre: str,
|
|
730
|
+
pcard_hash: str,
|
|
731
|
+
v_post: str,
|
|
732
|
+
) -> None:
|
|
733
|
+
try:
|
|
734
|
+
if self.execution_log is not self.collection:
|
|
735
|
+
for hash_ref in [v_pre, v_post]:
|
|
736
|
+
if isinstance(hash_ref, str):
|
|
737
|
+
ref_card = self.collection.get(hash_ref)
|
|
738
|
+
if ref_card:
|
|
739
|
+
self.execution_log.add(ref_card)
|
|
740
|
+
elif hash_ref:
|
|
741
|
+
self.execution_log.add(hash_ref)
|
|
742
|
+
|
|
743
|
+
self.logger.info(
|
|
744
|
+
f"[EXEC_LOG] Recorded topological trace for PCard {pcard_hash[:16]} "
|
|
745
|
+
f"(Pre: {str(v_pre)[:8]}, Post: {str(v_post)[:8]})"
|
|
746
|
+
)
|
|
747
|
+
except (ValueError, TypeError, AttributeError, KeyError) as e:
|
|
748
|
+
self.logger.warning(f"[EXEC_LOG] Failed to record trace: {e}")
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
from clm.cross_cutting.governance import (
|
|
752
|
+
GovernanceTelemetry,
|
|
753
|
+
compute_post_governance,
|
|
754
|
+
compute_prep_governance,
|
|
755
|
+
)
|
|
756
|
+
from clm.cross_cutting.observability import REPLPhase
|
|
757
|
+
from clm.layer1.store import PTRSharedStore, create_store_from_context
|
|
758
|
+
|
|
759
|
+
__all__ = ["PTREngine"]
|