cortex-runtime 0.2.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 (76) hide show
  1. cortex/__init__.py +51 -0
  2. cortex/__main__.py +13 -0
  3. cortex/client.py +263 -0
  4. cortex/compat.py +20 -0
  5. cortex/exceptions.py +57 -0
  6. cortex/plugin.py +50 -0
  7. cortex/py.typed +1 -0
  8. cortex/schema/__init__.py +29 -0
  9. cortex/schema/events.py +127 -0
  10. cortex/tools/__init__.py +3 -0
  11. cortex/tools/cli/__init__.py +3 -0
  12. cortex/tools/cli/main.py +139 -0
  13. cortex/tools/cli/runner.py +94 -0
  14. cortex/tools/cli/scaffolder.py +109 -0
  15. cortex/tools/gen_test_bin.py +35 -0
  16. cortex/tools/kernel/__init__.py +3 -0
  17. cortex/tools/kernel/actors/__init__.py +3 -0
  18. cortex/tools/kernel/actors/executor.py +44 -0
  19. cortex/tools/kernel/actors/planner.py +38 -0
  20. cortex/tools/kernel/context.py +22 -0
  21. cortex/tools/kernel/drivers/__init__.py +3 -0
  22. cortex/tools/kernel/drivers/mock_robot.py +84 -0
  23. cortex/tools/kernel/drivers/rtl_verilator.py +49 -0
  24. cortex/tools/kernel/graph/__init__.py +3 -0
  25. cortex/tools/kernel/graph/analyzer.py +52 -0
  26. cortex/tools/kernel/graph/execution_graph.py +44 -0
  27. cortex/tools/kernel/mailbox.py +35 -0
  28. cortex/tools/kernel/plugin/__init__.py +3 -0
  29. cortex/tools/kernel/plugin/loader.py +87 -0
  30. cortex/tools/kernel/plugin/manifest.py +53 -0
  31. cortex/tools/kernel/registry.py +36 -0
  32. cortex/tools/kernel/schema/__init__.py +3 -0
  33. cortex/tools/kernel/schema/contract.py +16 -0
  34. cortex/tools/kernel/schema/event.py +54 -0
  35. cortex/tools/kernel/schema/message.py +105 -0
  36. cortex/tools/kernel/schema/workflow.py +38 -0
  37. cortex/tools/kernel/services/__init__.py +3 -0
  38. cortex/tools/kernel/services/event_store.py +25 -0
  39. cortex/tools/kernel/services/execution_intelligence.py +49 -0
  40. cortex/tools/kernel/services/graph_builder.py +81 -0
  41. cortex/tools/kernel/services/replay.py +50 -0
  42. cortex/tools/kernel/services/verification.py +85 -0
  43. cortex/tools/kernel/transport.py +50 -0
  44. cortex/tools/run_phase2_verification.sh +20 -0
  45. cortex/tools/verification/__init__.py +5 -0
  46. cortex/tools/verification/adapters/__init__.py +3 -0
  47. cortex/tools/verification/adapters/base.py +14 -0
  48. cortex/tools/verification/adapters/coq.py +73 -0
  49. cortex/tools/verification/adapters/rtl.py +77 -0
  50. cortex/tools/verification/adapters/rust.py +72 -0
  51. cortex/tools/verification/archive.py +58 -0
  52. cortex/tools/verification/bus.py +28 -0
  53. cortex/tools/verification/contract.py +70 -0
  54. cortex/tools/verification/engine.py +121 -0
  55. cortex/tools/verification/generator/__init__.py +3 -0
  56. cortex/tools/verification/generator/composer.py +36 -0
  57. cortex/tools/verification/generator/program.py +46 -0
  58. cortex/tools/verification/generator/state.py +54 -0
  59. cortex/tools/verification/invariants/__init__.py +3 -0
  60. cortex/tools/verification/invariants/capability.py +62 -0
  61. cortex/tools/verification/metrics/__init__.py +3 -0
  62. cortex/tools/verification/metrics/base.py +18 -0
  63. cortex/tools/verification/metrics/opcode.py +25 -0
  64. cortex/tools/verification/metrics/state_space.py +26 -0
  65. cortex/tools/verification/metrics/trap.py +26 -0
  66. cortex/tools/verification/mutation.py +48 -0
  67. cortex/tools/verification/oracle.py +164 -0
  68. cortex/tools/verification/schema/__init__.py +44 -0
  69. cortex/tools/verification/schema/event.py +44 -0
  70. cortex/tools/verification/shrink.py +26 -0
  71. cortex/tools/verify.py +64 -0
  72. cortex_runtime-0.2.0.dist-info/METADATA +220 -0
  73. cortex_runtime-0.2.0.dist-info/RECORD +76 -0
  74. cortex_runtime-0.2.0.dist-info/WHEEL +4 -0
  75. cortex_runtime-0.2.0.dist-info/entry_points.txt +2 -0
  76. cortex_runtime-0.2.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,52 @@
1
+ """
2
+ Execution Graph Query, Root-Cause Analysis & Divergence Detection Engine
3
+ """
4
+
5
+ from cortex.tools.kernel.graph.execution_graph import ExecutionGraph, GraphNode
6
+
7
+
8
+ class ExecutionGraphAnalyzer:
9
+ """Provides analytical, root-cause, and graph-differencing capabilities."""
10
+ graph: ExecutionGraph
11
+
12
+ def __init__(self, graph: ExecutionGraph):
13
+ self.graph = graph
14
+
15
+ def find_root_cause(self, node_id: str) -> list[GraphNode]:
16
+ """Traverses upstream parent pointers to trace lineage back to the root Intent."""
17
+ path: list[GraphNode] = []
18
+ current_id: str | None = node_id
19
+
20
+ while current_id and current_id in self.graph.nodes:
21
+ node = self.graph.nodes[current_id]
22
+ path.append(node)
23
+ current_id = node.parent_id
24
+
25
+ return path
26
+
27
+ def filter_by_type(self, node_type: str) -> list[GraphNode]:
28
+ """Returns all nodes matching the specified type."""
29
+ return [node for node in self.graph.nodes.values() if node.node_type == node_type]
30
+
31
+ def find_failed_nodes(self) -> list[GraphNode]:
32
+ """Finds any Verification node where passed == False."""
33
+ failed: list[GraphNode] = []
34
+ for node in self.graph.nodes.values():
35
+ if node.node_type == "Verification" and not node.payload.get("passed", True):
36
+ failed.append(node)
37
+ return failed
38
+
39
+ @staticmethod
40
+ def diff_graphs(golden: ExecutionGraph, candidate: ExecutionGraph) -> dict[str, object]:
41
+ """Compares a golden reference graph against a candidate execution graph."""
42
+ golden_node_types = [n.node_type for n in golden.nodes.values()]
43
+ candidate_node_types = [n.node_type for n in candidate.nodes.values()]
44
+
45
+ node_count_diff = len(candidate.nodes) - len(golden.nodes)
46
+ missing_types = [t for t in golden_node_types if t not in candidate_node_types]
47
+
48
+ return {
49
+ "identical_structure": len(golden.nodes) == len(candidate.nodes) and not missing_types,
50
+ "node_count_diff": node_count_diff,
51
+ "missing_node_types": missing_types
52
+ }
@@ -0,0 +1,44 @@
1
+ """
2
+ Real-Time Causal Execution Graph Representation & Tree Renderer
3
+ """
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass
9
+ class GraphNode:
10
+ node_id: str
11
+ node_type: str
12
+ payload: dict[str, object]
13
+ parent_id: str | None = None
14
+ children: list[str] = field(default_factory=list)
15
+
16
+ class ExecutionGraph:
17
+ """First-class Causal Execution Graph representation."""
18
+ root_id: str
19
+ nodes: dict[str, GraphNode]
20
+
21
+ def __init__(self, root_id: str):
22
+ self.root_id = root_id
23
+ self.nodes = {}
24
+
25
+ def add_node(self, node_id: str, node_type: str, payload: dict[str, object], parent_id: str | None = None) -> None:
26
+ node = GraphNode(node_id=node_id, node_type=node_type, payload=payload, parent_id=parent_id)
27
+ self.nodes[node_id] = node
28
+ if parent_id and parent_id in self.nodes:
29
+ self.nodes[parent_id].children.append(node_id)
30
+
31
+ def render_tree(self, current_id: str | None = None, depth: int = 0) -> str:
32
+ """Renders an ASCII tree representation of the execution lineage."""
33
+ if current_id is None:
34
+ current_id = self.root_id
35
+ if current_id not in self.nodes:
36
+ return ""
37
+
38
+ node = self.nodes[current_id]
39
+ indent = " " * depth
40
+ prefix = "└── " if depth > 0 else ""
41
+ result = f"{indent}{prefix}[{node.node_type}] ID: {node.node_id[:8]}.. | Details: {node.payload}\n"
42
+ for child_id in node.children:
43
+ result += self.render_tree(child_id, depth + 1)
44
+ return result
@@ -0,0 +1,35 @@
1
+ """
2
+ Bounded, Priority-Aware Mailbox for Kernel Actors
3
+ """
4
+
5
+ import heapq
6
+
7
+
8
+ class Mailbox:
9
+ capacity: int
10
+ _queue: list[tuple[int, int, object]]
11
+ _counter: int
12
+
13
+ def __init__(self, capacity: int = 1000):
14
+ self.capacity = capacity
15
+ self._queue = []
16
+ self._counter = 0
17
+
18
+ def push(self, message: object, priority: int = 10) -> bool:
19
+ if len(self._queue) >= self.capacity:
20
+ return False
21
+ self._counter += 1
22
+ heapq.heappush(self._queue, (priority, self._counter, message))
23
+ return True
24
+
25
+ def pop(self) -> object | None:
26
+ if not self._queue:
27
+ return None
28
+ _, _, message = heapq.heappop(self._queue)
29
+ return message
30
+
31
+ def is_empty(self) -> bool:
32
+ return len(self._queue) == 0
33
+
34
+ def size(self) -> int:
35
+ return len(self._queue)
@@ -0,0 +1,3 @@
1
+ """
2
+ Kernel Plugin Runtime & Capability Negotiation
3
+ """
@@ -0,0 +1,87 @@
1
+ """
2
+ Plugin Loader & Capability Negotiation Engine
3
+
4
+ Enforces the security boundary between plugins and the Kernel Core.
5
+ Plugins receive only the Resource Handles and Runtime Context scoped
6
+ to their declared capabilities — never raw kernel internals.
7
+ """
8
+
9
+ import enum
10
+ from dataclasses import dataclass, field
11
+
12
+ from cortex.tools.kernel.plugin.manifest import PluginManifest
13
+
14
+
15
+ class PluginState(str, enum.Enum):
16
+ REGISTERED = "REGISTERED"
17
+ NEGOTIATING = "NEGOTIATING"
18
+ ACTIVE = "ACTIVE"
19
+ REJECTED = "REJECTED"
20
+ SUSPENDED = "SUSPENDED"
21
+
22
+
23
+ @dataclass
24
+ class PluginRegistration:
25
+ """Runtime representation of a loaded plugin."""
26
+ manifest: PluginManifest
27
+ state: PluginState = PluginState.REGISTERED
28
+ granted_capabilities: set[str] = field(default_factory=set)
29
+ denied_capabilities: list[str] = field(default_factory=list)
30
+
31
+
32
+ class CapabilityNegotiator:
33
+ """Evaluates plugin capability requests against the platform's
34
+ available capability set and security policy."""
35
+ platform_capabilities: set[str]
36
+
37
+ def __init__(self, platform_capabilities: set[str]):
38
+ self.platform_capabilities = platform_capabilities
39
+
40
+ def negotiate(self, manifest: PluginManifest) -> PluginRegistration:
41
+ """Evaluates a plugin manifest and returns a PluginRegistration
42
+ with granted/denied capability sets."""
43
+ registration = PluginRegistration(manifest=manifest, state=PluginState.NEGOTIATING)
44
+
45
+ granted: set[str] = set()
46
+ denied: list[str] = []
47
+
48
+ for cap in manifest.required_capabilities:
49
+ if cap in self.platform_capabilities:
50
+ granted.add(cap)
51
+ else:
52
+ denied.append(cap)
53
+
54
+ registration.granted_capabilities = granted
55
+ registration.denied_capabilities = denied
56
+
57
+ if denied:
58
+ registration.state = PluginState.REJECTED
59
+ else:
60
+ registration.state = PluginState.ACTIVE
61
+
62
+ return registration
63
+
64
+
65
+ class PluginRegistry:
66
+ """Manages the lifecycle of all registered plugins."""
67
+ negotiator: CapabilityNegotiator
68
+ _plugins: dict[str, PluginRegistration]
69
+
70
+ def __init__(self, platform_capabilities: set[str]):
71
+ self.negotiator = CapabilityNegotiator(platform_capabilities)
72
+ self._plugins = {}
73
+
74
+ def register(self, manifest: PluginManifest) -> PluginRegistration:
75
+ """Register a plugin via manifest. Returns the negotiation result."""
76
+ registration = self.negotiator.negotiate(manifest)
77
+ self._plugins[manifest.name] = registration
78
+ return registration
79
+
80
+ def get_plugin(self, name: str) -> PluginRegistration | None:
81
+ return self._plugins.get(name)
82
+
83
+ def get_active_plugins(self) -> list[PluginRegistration]:
84
+ return [p for p in self._plugins.values() if p.state == PluginState.ACTIVE]
85
+
86
+ def get_rejected_plugins(self) -> list[PluginRegistration]:
87
+ return [p for p in self._plugins.values() if p.state == PluginState.REJECTED]
@@ -0,0 +1,53 @@
1
+ """
2
+ Declarative Plugin Manifest Schema
3
+
4
+ Every plugin declares its event consumption/production contract and the
5
+ kernel capabilities it requires. The Kernel enforces capability negotiation
6
+ at registration time — no raw access to internals is ever granted.
7
+ """
8
+
9
+ from dataclasses import dataclass, field
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class PluginManifest:
14
+ """Immutable declaration of a plugin's identity, event contract,
15
+ and required kernel capabilities."""
16
+ name: str
17
+ version: str
18
+ description: str
19
+ consumes_events: list[str] = field(default_factory=list)
20
+ produces_events: list[str] = field(default_factory=list)
21
+ required_capabilities: list[str] = field(default_factory=list)
22
+
23
+
24
+ # -----------------------------------------------------------------------
25
+ # Reference Manifests — canonical examples of domain plugin declarations
26
+ # -----------------------------------------------------------------------
27
+
28
+ ROBOT_ARM_MANIFEST = PluginManifest(
29
+ name="robot-arm-driver",
30
+ version="0.1.0",
31
+ description="Interface for 6-DOF industrial robot arm",
32
+ consumes_events=["CommandIssuedEvent"],
33
+ produces_events=["DriverTelemetryEvent"],
34
+ required_capabilities=["hardware.actuators.execute", "hardware.telemetry.read"],
35
+ )
36
+
37
+ AGENT_PLANNER_MANIFEST = PluginManifest(
38
+ name="llm-task-planner",
39
+ version="0.1.0",
40
+ description="Decomposes goal intents into step-wise plans",
41
+ consumes_events=["IntentEvent"],
42
+ produces_events=["PlanGeneratedEvent"],
43
+ required_capabilities=["workflow.plan.create"],
44
+ )
45
+
46
+ VERIFICATION_SERVICE_MANIFEST = PluginManifest(
47
+ name="verification-service",
48
+ version="0.1.0",
49
+ description="Formal verification oracle for CommitContractV1",
50
+ consumes_events=["DriverTelemetryEvent", "CommitEventV1"],
51
+ produces_events=["VerificationResultEvent"],
52
+ required_capabilities=["verification.oracle.execute", "verification.invariant.check"],
53
+ )
@@ -0,0 +1,36 @@
1
+ """
2
+ Object Registry & Resource Handle Management
3
+ """
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class Capability:
10
+ name: str
11
+
12
+ @dataclass(frozen=True)
13
+ class ResourceHandle:
14
+ handle_id: str
15
+ resource_type: str
16
+ capabilities: set[Capability]
17
+
18
+ class ObjectRegistry:
19
+ _actors: dict[str, object]
20
+ _handles: dict[str, ResourceHandle]
21
+
22
+ def __init__(self):
23
+ self._actors = {}
24
+ self._handles = {}
25
+
26
+ def register_actor(self, actor_id: str, actor_instance: object) -> None:
27
+ self._actors[actor_id] = actor_instance
28
+
29
+ def get_actor(self, actor_id: str) -> object | None:
30
+ return self._actors.get(actor_id)
31
+
32
+ def register_handle(self, handle: ResourceHandle) -> None:
33
+ self._handles[handle.handle_id] = handle
34
+
35
+ def get_handle(self, handle_id: str) -> ResourceHandle | None:
36
+ return self._handles.get(handle_id)
@@ -0,0 +1,3 @@
1
+ """
2
+ Kernel Schema & Domain Event Hierarchy
3
+ """
@@ -0,0 +1,16 @@
1
+ """
2
+ Kernel Service Declarative Contracts
3
+ """
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from cortex.tools.kernel.schema.event import Event
8
+ from cortex.tools.kernel.schema.message import BaseEvent
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class ServiceContract:
13
+ """Contract advertising event types consumed and produced by a Kernel Service."""
14
+ service_name: str
15
+ consumes: list[type[Event | BaseEvent]]
16
+ produces: list[type[Event | BaseEvent]]
@@ -0,0 +1,54 @@
1
+ """
2
+ Domain Event Hierarchy for Cortex Kernel Runtime
3
+ """
4
+
5
+ import time
6
+ import uuid
7
+ from dataclasses import dataclass, field
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Event:
12
+ """Universal Base Envelope for Kernel Runtime IPC Events."""
13
+ event_id: str = field(default_factory=lambda: str(uuid.uuid4()))
14
+ parent_event_id: str | None = None
15
+ root_event_id: str | None = None
16
+ causation_id: str | None = None
17
+ correlation_id: str = field(default_factory=lambda: str(uuid.uuid4()))
18
+ session_id: str = ""
19
+ sequence_number: int = 0
20
+ timestamp_ns: int = field(default_factory=lambda: time.time_ns())
21
+
22
+ @dataclass(frozen=True)
23
+ class VerificationEvent(Event):
24
+ """Event category for hardware, formal, and simulation correctness."""
25
+
26
+ @dataclass(frozen=True)
27
+ class RawRTLTraceEvent(VerificationEvent):
28
+ """Raw telemetry frame emitted by hardware drivers or Verilator simulators."""
29
+ pc: int = 0
30
+ raw_instruction: str = ""
31
+ eff_trap: bool = False
32
+ trap_cause: int = 0
33
+ stcr_registers: dict[int, str] = field(default_factory=dict)
34
+
35
+ @dataclass(frozen=True)
36
+ class CommitVerifiedEvent(VerificationEvent):
37
+ """Domain decision event emitted after formal oracle state verification."""
38
+ step: int = 0
39
+ verified: bool = True
40
+ failing_field: str | None = None
41
+
42
+ @dataclass(frozen=True)
43
+ class MotorFeedbackEvent(Event):
44
+ """Driver raw telemetry event for physical or mock actuators."""
45
+ actuator_id: str = ""
46
+ position: float = 0.0
47
+ velocity: float = 0.0
48
+
49
+ @dataclass(frozen=True)
50
+ class InferenceCompletedEvent(Event):
51
+ """LLM agent or inference engine response event."""
52
+ agent_id: str = ""
53
+ prompt_tokens: int = 0
54
+ completion: str = ""
@@ -0,0 +1,105 @@
1
+ """
2
+ Unified Control & Execution Message Hierarchy for Cortex Kernel Runtime
3
+
4
+ Domain-Agnostic Event Taxonomy:
5
+ BaseEvent (universal envelope with workflow_id tracing)
6
+ ├── IntentEvent (User/System goal request)
7
+ ├── PlanGeneratedEvent (Agent planner output)
8
+ ├── CommandIssuedEvent (Executor dispatch)
9
+ ├── DriverTelemetryEvent (Hardware/Simulator feedback)
10
+ ├── VerificationResultEvent (Contract assertion result)
11
+ └── CommitEventV1 (Verification Substrate only — domain-isolated)
12
+ """
13
+
14
+ import time
15
+ import uuid
16
+ from dataclasses import dataclass, field
17
+
18
+ # ---------------------------------------------------------------------------
19
+ # Base Envelope
20
+ # ---------------------------------------------------------------------------
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class BaseEvent:
25
+ """Universal event envelope carrying identity, workflow correlation,
26
+ and causal lineage metadata."""
27
+
28
+ event_id: str = field(default_factory=lambda: str(uuid.uuid4()))
29
+ workflow_id: str | None = None
30
+ causation_id: str | None = None
31
+ correlation_id: str = ""
32
+ root_id: str = ""
33
+ timestamp_ns: int = field(default_factory=lambda: time.time_ns())
34
+ metadata: dict[str, object] = field(default_factory=dict)
35
+
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Universal Kernel & Domain Events
39
+ # ---------------------------------------------------------------------------
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class IntentEvent(BaseEvent):
44
+ """Represents WHAT is desired (Goal / Action Request)."""
45
+
46
+ intent_id: str = field(default_factory=lambda: str(uuid.uuid4()))
47
+ session_id: str = ""
48
+ goal: str = ""
49
+ parameters: dict[str, object] = field(default_factory=dict)
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class PlanGeneratedEvent(BaseEvent):
54
+ """Represents HOW the Intent is decomposed into structured steps."""
55
+
56
+ plan_id: str = field(default_factory=lambda: str(uuid.uuid4()))
57
+ intent_id: str = ""
58
+ steps: list[dict[str, object]] = field(default_factory=list)
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class CommandIssuedEvent(BaseEvent):
63
+ """Represents EXECUTE THIS SINGLE OPERATION."""
64
+
65
+ command_id: str = field(default_factory=lambda: str(uuid.uuid4()))
66
+ plan_id: str = ""
67
+ action: str = ""
68
+ parameters: dict[str, object] = field(default_factory=dict)
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class DriverTelemetryEvent(BaseEvent):
73
+ """Raw execution feedback from hardware, tools, or RTL models."""
74
+
75
+ driver_id: str = ""
76
+ status: str = "ok"
77
+ payload: dict[str, object] = field(default_factory=dict)
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class VerificationResultEvent(BaseEvent):
82
+ """Verification/Invariant evaluation result derived from Telemetry."""
83
+
84
+ passed: bool = True
85
+ rule_id: str = ""
86
+ details: dict[str, object] = field(default_factory=dict)
87
+ metrics: dict[str, object] = field(default_factory=dict)
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # Domain-Specific: Verification Substrate (Isolated to Verification Domain)
92
+ # ---------------------------------------------------------------------------
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class CommitEventV1(BaseEvent):
97
+ """Immutable architectural commit event scoped exclusively to the
98
+ formal verification service pipeline (Coq / Rust / RTL oracles)."""
99
+
100
+ cycle: int = 0
101
+ pc: int = 0
102
+ instruction: int = 0
103
+ register_writes: dict[str, int] = field(default_factory=dict)
104
+ memory_writes: dict[str, object] = field(default_factory=dict)
105
+ exception_code: int | None = None
@@ -0,0 +1,38 @@
1
+ """
2
+ First-Class Workflow Primitive & Policy Schema
3
+ """
4
+
5
+ import enum
6
+ import time
7
+ import uuid
8
+ from dataclasses import dataclass, field
9
+
10
+
11
+ class WorkflowState(str, enum.Enum):
12
+ PENDING = "PENDING"
13
+ RUNNING = "RUNNING"
14
+ COMPLETED = "COMPLETED"
15
+ FAILED = "FAILED"
16
+ ABORTED = "ABORTED"
17
+
18
+
19
+ @dataclass
20
+ class WorkflowPolicy:
21
+ timeout_seconds: float = 300.0
22
+ max_retries: int = 3
23
+ abort_on_verification_failure: bool = True
24
+
25
+
26
+ @dataclass
27
+ class Workflow:
28
+ """First-class runtime unit of execution encapsulating autonomous lifecycles."""
29
+
30
+ workflow_id: str = field(default_factory=lambda: str(uuid.uuid4()))
31
+ name: str = "default_workflow"
32
+ goal: str = ""
33
+ state: WorkflowState = WorkflowState.PENDING
34
+ policy: WorkflowPolicy = field(default_factory=WorkflowPolicy)
35
+ root_intent_id: str | None = None
36
+ execution_graph_id: str | None = None
37
+ created_at_ns: int = field(default_factory=lambda: time.time_ns())
38
+ metadata: dict[str, object] = field(default_factory=dict)
@@ -0,0 +1,3 @@
1
+ """
2
+ Kernel Services Layer
3
+ """
@@ -0,0 +1,25 @@
1
+ """
2
+ Event Store & Audit Journal Kernel Service
3
+ """
4
+
5
+ from cortex.tools.kernel.schema.contract import ServiceContract
6
+ from cortex.tools.kernel.transport import AnyEvent
7
+
8
+
9
+ class EventStoreService:
10
+ _log: list[AnyEvent]
11
+
12
+ contract: ServiceContract = ServiceContract(
13
+ service_name="EventStoreService",
14
+ consumes=[],
15
+ produces=[],
16
+ )
17
+
18
+ def __init__(self) -> None:
19
+ self._log = []
20
+
21
+ def record_event(self, event: AnyEvent) -> None:
22
+ self._log.append(event)
23
+
24
+ def get_log(self) -> list[AnyEvent]:
25
+ return list(self._log)
@@ -0,0 +1,49 @@
1
+ """
2
+ Execution Intelligence & Causal Explainer Kernel Service
3
+ """
4
+
5
+ from cortex.tools.kernel.graph.execution_graph import ExecutionGraph, GraphNode
6
+
7
+
8
+ class CausalExplainer:
9
+ """Analyzes an ExecutionGraph to provide root-cause diagnostics and lineage traces."""
10
+ graph: ExecutionGraph
11
+
12
+ def __init__(self, graph: ExecutionGraph):
13
+ self.graph = graph
14
+
15
+ def explain_failure(self, failed_node_id: str) -> dict[str, object]:
16
+ """Traverses backwards up the causal chain to locate the root cause of a failure."""
17
+ if failed_node_id not in self.graph.nodes:
18
+ return {"error": "Node not found"}
19
+
20
+ chain: list[GraphNode] = []
21
+ curr: str | None = failed_node_id
22
+
23
+ while curr and curr in self.graph.nodes:
24
+ node = self.graph.nodes[curr]
25
+ chain.append(node)
26
+ curr = node.parent_id
27
+
28
+ chain.reverse()
29
+
30
+ return {
31
+ "target_node": failed_node_id,
32
+ "root_intent": chain[0].payload if chain else None,
33
+ "causal_path": [
34
+ {
35
+ "node_id": n.node_id,
36
+ "type": n.node_type,
37
+ "summary": n.payload
38
+ } for n in chain
39
+ ],
40
+ "diagnosis": self._derive_diagnosis(chain)
41
+ }
42
+
43
+ def _derive_diagnosis(self, chain: list[GraphNode]) -> str:
44
+ for node in reversed(chain):
45
+ if node.node_type == "Verification" and not node.payload.get("passed", True):
46
+ return f"Verification assertion failed at rule '{node.payload.get('rule')}'."
47
+ if node.node_type == "Telemetry" and node.payload.get("status") != "ok":
48
+ return f"Driver reported error status '{node.payload.get('status')}' during command execution."
49
+ return "Unknown failure cause."