alethic-kernel 0.1.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 (55) hide show
  1. alethic_kernel/__init__.py +9 -0
  2. alethic_kernel/agents/__init__.py +0 -0
  3. alethic_kernel/agents/alethic_agent.py +109 -0
  4. alethic_kernel/agents/json_glue.py +35 -0
  5. alethic_kernel/agents/llm_agent.py +186 -0
  6. alethic_kernel/agents/string_glue.py +33 -0
  7. alethic_kernel/alethic/__init__.py +13 -0
  8. alethic_kernel/alethic/adaptive_worker.py +134 -0
  9. alethic_kernel/alethic/api/__init__.py +0 -0
  10. alethic_kernel/alethic/api/app.py +65 -0
  11. alethic_kernel/alethic/api/dependencies.py +59 -0
  12. alethic_kernel/alethic/api/models.py +104 -0
  13. alethic_kernel/alethic/api/routes.py +142 -0
  14. alethic_kernel/alethic/api/tracing.py +25 -0
  15. alethic_kernel/alethic/client.py +280 -0
  16. alethic_kernel/alethic/kernel.py +261 -0
  17. alethic_kernel/alethic/migrations.py +76 -0
  18. alethic_kernel/alethic/orchestrator.py +99 -0
  19. alethic_kernel/alethic/permissions.py +16 -0
  20. alethic_kernel/alethic/py.typed +0 -0
  21. alethic_kernel/alethic/schema.py +37 -0
  22. alethic_kernel/alethic/session.py +23 -0
  23. alethic_kernel/alethic/sim_worker.py +162 -0
  24. alethic_kernel/alethic/sqlite_store.py +188 -0
  25. alethic_kernel/alethic/store.py +101 -0
  26. alethic_kernel/alethic/store_protocol.py +33 -0
  27. alethic_kernel/alethic/validators.py +46 -0
  28. alethic_kernel/alethic/worker.py +42 -0
  29. alethic_kernel/eval/__init__.py +0 -0
  30. alethic_kernel/eval/harness.py +53 -0
  31. alethic_kernel/eval/metrics.py +70 -0
  32. alethic_kernel/eval/report.py +41 -0
  33. alethic_kernel/eval/task_loader.py +38 -0
  34. alethic_kernel/examples/demo.py +472 -0
  35. alethic_kernel/examples/multi_episode.py +263 -0
  36. alethic_kernel/llm/__init__.py +0 -0
  37. alethic_kernel/llm/planner.py +178 -0
  38. alethic_kernel/py.typed +0 -0
  39. alethic_kernel/run.py +172 -0
  40. alethic_kernel/tasks/stripe_refund_clean.yaml +18 -0
  41. alethic_kernel/tasks/stripe_refund_combined.yaml +18 -0
  42. alethic_kernel/tasks/stripe_refund_conflict.yaml +18 -0
  43. alethic_kernel/tasks/stripe_refund_duplicate.yaml +19 -0
  44. alethic_kernel/tasks/stripe_refund_stale.yaml +18 -0
  45. alethic_kernel/tasks/stripe_refund_tool_failure.yaml +18 -0
  46. alethic_kernel/tools/__init__.py +0 -0
  47. alethic_kernel/tools/payment_tool.py +30 -0
  48. alethic_kernel/tools/perturb.py +17 -0
  49. alethic_kernel/tools/refund_tool.py +16 -0
  50. alethic_kernel-0.1.0.dist-info/METADATA +163 -0
  51. alethic_kernel-0.1.0.dist-info/RECORD +55 -0
  52. alethic_kernel-0.1.0.dist-info/WHEEL +5 -0
  53. alethic_kernel-0.1.0.dist-info/entry_points.txt +2 -0
  54. alethic_kernel-0.1.0.dist-info/licenses/LICENSE +21 -0
  55. alethic_kernel-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,9 @@
1
+ """Alethic — a governed cognition framework for AI systems."""
2
+ from importlib.metadata import PackageNotFoundError, version as _version
3
+
4
+ try:
5
+ __version__ = _version("alethic-kernel")
6
+ except PackageNotFoundError: # running from a source tree, not installed
7
+ __version__ = "0.0.0.dev0"
8
+
9
+ __all__ = ["__version__"]
File without changes
@@ -0,0 +1,109 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass
3
+ from typing import Any, Dict
4
+ import uuid
5
+
6
+ from ..alethic.kernel import Kernel
7
+ from ..tools.payment_tool import PaymentTool
8
+ from ..tools.refund_tool import RefundTool
9
+
10
+ @dataclass
11
+ class AlethicAgent:
12
+ kernel: Kernel
13
+ payment_tool: PaymentTool
14
+ refund_tool: RefundTool
15
+ id: str = "alethic"
16
+
17
+ def run(self, seed: int, task_id: str, task_inputs: Dict[str, Any],
18
+ constraints: Dict[str, Any]) -> Dict[str, Any]:
19
+ trace_id = f"{task_id}-{seed}-{uuid.uuid4().hex[:8]}"
20
+
21
+ # t0 Commit constraints
22
+ for cname, cdef in constraints.items():
23
+ payload = {"enabled": True}
24
+ if isinstance(cdef, dict):
25
+ payload.update(cdef)
26
+ self.kernel.write("symbolic_validator", "constraints", "COMMIT",
27
+ cname, payload, trace_id)
28
+
29
+ # t0 Tools commit percepts
30
+ charge = self.payment_tool.get_charge(
31
+ seed, task_inputs["chargeId"], task_inputs["customerId"],
32
+ task_inputs["amount"])
33
+ if charge is None:
34
+ charge = {"charge_id": task_inputs["chargeId"],
35
+ "amount": task_inputs["amount"], "currency": "usd",
36
+ "status": "disputed", "stale": True, "conflict": False,
37
+ "customer_id": task_inputs["customerId"]}
38
+ confidence = charge.pop("_confidence", None)
39
+ self.kernel.write("tool", "percepts", "COMMIT", "charge", charge,
40
+ trace_id, confidence=confidence)
41
+
42
+ # t2 Planner proposes belief
43
+ belief_prop = self.kernel.write(
44
+ "planner", "beliefs", "PROPOSE", "refund_due",
45
+ {"value": True, "depends_on": ["charge"]},
46
+ trace_id, input_refs=["charge"])
47
+
48
+ # t3-t4 Kernel validates evidence, confidence, conflicts
49
+ ok_belief, belief_code = self.kernel.commit_belief_from_proposal(
50
+ belief_prop.id, trace_id)
51
+
52
+ # t5 Planner proposes plan
53
+ is_duplicate = task_inputs.get("is_duplicate", False)
54
+ refund = self.refund_tool.render_refund(
55
+ task_inputs["chargeId"], task_inputs["amount"],
56
+ task_inputs["customerId"],
57
+ reason=task_inputs.get("disputeReason", "customer_request"),
58
+ is_duplicate=is_duplicate)
59
+ plan_step = {
60
+ "action": "issue_refund",
61
+ "requires_beliefs": ["refund_due"],
62
+ "is_duplicate": refund.get("is_duplicate", False),
63
+ }
64
+ plan_prop = self.kernel.write(
65
+ "planner", "plans", "PROPOSE", "action_plan",
66
+ {"steps": [plan_step]}, trace_id)
67
+
68
+ # t6 Validators check plan feasibility
69
+ ok_plan, plan_code = self.kernel.validate_plan(plan_prop.id, trace_id)
70
+
71
+ ok_action, action_code = False, ""
72
+ ok_safe, safe_code = False, ""
73
+
74
+ if ok_plan:
75
+ # t7 Propose action from plan
76
+ action_payload = {
77
+ "type": "issue_refund",
78
+ "charge_id": refund["charge_id"],
79
+ "amount": refund["amount"],
80
+ "reason": refund["reason"],
81
+ "is_duplicate": refund["is_duplicate"],
82
+ "requires_beliefs": ["refund_due"],
83
+ }
84
+ action_prop = self.kernel.write(
85
+ "planner", "actions", "PROPOSE", "issue_refund",
86
+ action_payload, trace_id, input_refs=[belief_prop.id])
87
+ # t8-t9 Kernel gates action
88
+ ok_action, action_code = self.kernel.commit_action_from_proposal(
89
+ action_prop.id, trace_id)
90
+
91
+ if not ok_action:
92
+ reason = action_code or plan_code
93
+ safe_prop = self.kernel.write(
94
+ "planner", "actions", "PROPOSE", "queue_for_review",
95
+ {"type": "queue_for_review", "reason": reason},
96
+ trace_id, input_refs=[plan_prop.id])
97
+ ok_safe, safe_code = self.kernel.commit_action_from_proposal(
98
+ safe_prop.id, trace_id)
99
+
100
+ return {
101
+ "trace_id": trace_id,
102
+ "final": {
103
+ "belief_committed": ok_belief, "belief_code": belief_code,
104
+ "plan_feasible": ok_plan, "plan_code": plan_code,
105
+ "action_committed": ok_action, "action_code": action_code,
106
+ "safe_action_committed": ok_safe, "safe_action_code": safe_code,
107
+ },
108
+ "view": self.kernel.current_view(trace_id),
109
+ }
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass
3
+ from typing import Any, Dict
4
+ from ..tools.payment_tool import PaymentTool
5
+ from ..tools.refund_tool import RefundTool
6
+
7
+ @dataclass
8
+ class JsonGlueAgent:
9
+ payment_tool: PaymentTool
10
+ refund_tool: RefundTool
11
+ id: str = "json_glue"
12
+
13
+ def run(self, seed: int, task_inputs: Dict[str, Any]) -> Dict[str, Any]:
14
+ charge = self.payment_tool.get_charge(
15
+ seed, task_inputs["chargeId"], task_inputs["customerId"],
16
+ task_inputs["amount"])
17
+ if charge is None:
18
+ charge = {"charge_id": task_inputs["chargeId"],
19
+ "amount": task_inputs["amount"], "currency": "usd",
20
+ "status": "disputed", "stale": True, "conflict": False,
21
+ "customer_id": task_inputs["customerId"]}
22
+ charge.pop("_confidence", None)
23
+ refund_due = True
24
+ confidence = 0.6 if charge.get("stale") else 0.9
25
+ is_duplicate = task_inputs.get("is_duplicate", False)
26
+ refund = self.refund_tool.render_refund(
27
+ task_inputs["chargeId"], task_inputs["amount"],
28
+ task_inputs["customerId"],
29
+ reason=task_inputs.get("disputeReason", "customer_request"),
30
+ is_duplicate=is_duplicate)
31
+ action = {"type": "issue_refund", "amount": refund["amount"],
32
+ "charge_id": refund["charge_id"], "is_duplicate": refund["is_duplicate"],
33
+ "confidence": confidence}
34
+ return {"beliefs": {"refund_due": refund_due, "confidence": confidence},
35
+ "action": action, "tool_obs": {"charge": charge, "refund": refund}}
@@ -0,0 +1,186 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass, field
3
+ from typing import Any, Dict, Optional
4
+ import sys
5
+ import uuid
6
+
7
+ from ..alethic.kernel import Kernel
8
+ from ..tools.payment_tool import PaymentTool
9
+ from ..tools.refund_tool import RefundTool
10
+ from ..llm.planner import propose_belief, propose_plan, propose_action
11
+
12
+
13
+ @dataclass
14
+ class LLMAgent:
15
+ kernel: Kernel
16
+ payment_tool: PaymentTool
17
+ refund_tool: RefundTool
18
+ id: str = "llm_bk"
19
+ llm_kw: Dict[str, Any] = field(default_factory=dict)
20
+
21
+ def run(self, seed: int, task_id: str, task_inputs: Dict[str, Any],
22
+ constraints: Dict[str, Any]) -> Dict[str, Any]:
23
+ trace_id = f"{task_id}-{seed}-{uuid.uuid4().hex[:8]}"
24
+ task_desc = (f"Process a refund for customer {task_inputs['customerName']} "
25
+ f"on charge {task_inputs['chargeId']} "
26
+ f"(${task_inputs['amount']:.2f}, reason: {task_inputs.get('disputeReason', 'unknown')})")
27
+ belief_name = "refund_due"
28
+
29
+ # t0 Commit constraints
30
+ for cname, cdef in constraints.items():
31
+ payload = {"enabled": True}
32
+ if isinstance(cdef, dict):
33
+ payload.update(cdef)
34
+ self.kernel.write("symbolic_validator", "constraints", "COMMIT",
35
+ cname, payload, trace_id)
36
+
37
+ # t0 Tools commit percepts
38
+ charge = self.payment_tool.get_charge(
39
+ seed, task_inputs["chargeId"], task_inputs["customerId"],
40
+ task_inputs["amount"])
41
+ if charge is None:
42
+ charge = {"charge_id": task_inputs["chargeId"],
43
+ "amount": task_inputs["amount"], "currency": "usd",
44
+ "status": "disputed", "stale": True, "conflict": False,
45
+ "customer_id": task_inputs["customerId"]}
46
+ confidence = charge.pop("_confidence", None)
47
+ self.kernel.write("tool", "percepts", "COMMIT", "charge", charge,
48
+ trace_id, confidence=confidence)
49
+
50
+ percept_keys = ["charge"]
51
+
52
+ # ── LLM proposes belief ──────────────────────────────────────
53
+ view = self.kernel.current_view(trace_id)
54
+ llm_belief = self._llm_propose_belief(
55
+ view["percepts"], view["constraints"], task_desc,
56
+ belief_name, percept_keys)
57
+
58
+ ok_belief, belief_code = False, "LLM_NO_BELIEF"
59
+ should_propose = True
60
+ if llm_belief is not None:
61
+ should_propose = llm_belief.get("propose", True)
62
+
63
+ if should_propose:
64
+ belief_prop = self.kernel.write(
65
+ "planner", "beliefs", "PROPOSE", belief_name,
66
+ {"value": True, "depends_on": percept_keys},
67
+ trace_id, input_refs=percept_keys)
68
+ ok_belief, belief_code = self.kernel.commit_belief_from_proposal(
69
+ belief_prop.id, trace_id)
70
+
71
+ # ── LLM proposes plan ────────────────────────────────────────
72
+ is_duplicate = task_inputs.get("is_duplicate", False)
73
+ refund = self.refund_tool.render_refund(
74
+ task_inputs["chargeId"], task_inputs["amount"],
75
+ task_inputs["customerId"],
76
+ reason=task_inputs.get("disputeReason", "customer_request"),
77
+ is_duplicate=is_duplicate)
78
+
79
+ view = self.kernel.current_view(trace_id)
80
+ action_context = {
81
+ "charge_id": refund["charge_id"],
82
+ "amount": refund["amount"],
83
+ "reason": refund["reason"],
84
+ "is_duplicate": refund["is_duplicate"],
85
+ }
86
+ required_beliefs = [belief_name]
87
+ llm_plan = self._llm_propose_plan(
88
+ view["beliefs"], view["constraints"], task_desc,
89
+ action_context, required_beliefs)
90
+
91
+ ok_plan, plan_code = False, "LLM_NO_PLAN"
92
+ plan_steps: list[Dict[str, Any]] = []
93
+
94
+ if llm_plan and llm_plan.get("steps"):
95
+ plan_steps = []
96
+ for step in llm_plan["steps"]:
97
+ normalized = dict(step)
98
+ normalized["requires_beliefs"] = required_beliefs
99
+ normalized.setdefault("is_duplicate", refund.get("is_duplicate", False))
100
+ plan_steps.append(normalized)
101
+
102
+ plan_prop = self.kernel.write(
103
+ "planner", "plans", "PROPOSE", "action_plan",
104
+ {"steps": plan_steps}, trace_id)
105
+ ok_plan, plan_code = self.kernel.validate_plan(plan_prop.id, trace_id)
106
+
107
+ # ── LLM proposes action ──────────────────────────────────────
108
+ ok_action, action_code = False, ""
109
+
110
+ if ok_plan and plan_steps:
111
+ step = plan_steps[0]
112
+ llm_action = self._llm_propose_action(
113
+ step, f"Refund ${refund['amount']:.2f} to {task_inputs['customerName']}",
114
+ refund.get("is_duplicate", False), {})
115
+
116
+ if llm_action:
117
+ action_payload = {
118
+ "type": "issue_refund",
119
+ "charge_id": refund["charge_id"],
120
+ "amount": refund["amount"],
121
+ "reason": refund["reason"],
122
+ "is_duplicate": refund["is_duplicate"],
123
+ "requires_beliefs": required_beliefs,
124
+ }
125
+ action_prop = self.kernel.write(
126
+ "planner", "actions", "PROPOSE", "issue_refund",
127
+ action_payload, trace_id,
128
+ input_refs=[f"beliefs:{trace_id}:1"] if ok_belief else [])
129
+ ok_action, action_code = self.kernel.commit_action_from_proposal(
130
+ action_prop.id, trace_id)
131
+
132
+ # ── Fallback: queue for review ───────────────────────────────
133
+ ok_safe, safe_code = False, ""
134
+ if not ok_action:
135
+ reason = action_code or plan_code or belief_code
136
+ safe_prop = self.kernel.write(
137
+ "planner", "actions", "PROPOSE", "queue_for_review",
138
+ {"type": "queue_for_review", "reason": reason},
139
+ trace_id)
140
+ ok_safe, safe_code = self.kernel.commit_action_from_proposal(
141
+ safe_prop.id, trace_id)
142
+
143
+ return {
144
+ "trace_id": trace_id,
145
+ "final": {
146
+ "belief_committed": ok_belief, "belief_code": belief_code,
147
+ "plan_feasible": ok_plan, "plan_code": plan_code,
148
+ "action_committed": ok_action, "action_code": action_code,
149
+ "safe_action_committed": ok_safe, "safe_action_code": safe_code,
150
+ },
151
+ "view": self.kernel.current_view(trace_id),
152
+ }
153
+
154
+ def _llm_propose_belief(self, percepts: Dict[str, Any], constraints: Dict[str, Any],
155
+ task_desc: str, belief_name: str,
156
+ percept_keys: list[str]) -> Optional[Dict[str, Any]]:
157
+ try:
158
+ return propose_belief(percepts, constraints, task_desc,
159
+ belief_name=belief_name,
160
+ percept_keys=percept_keys,
161
+ **self.llm_kw)
162
+ except Exception as e:
163
+ print(f"[llm_bk] propose_belief error: {e}", file=sys.stderr)
164
+ return None
165
+
166
+ def _llm_propose_plan(self, beliefs: Dict[str, Any], constraints: Dict[str, Any],
167
+ task_desc: str, action_context: Dict[str, Any],
168
+ required_beliefs: list[str]) -> Optional[Dict[str, Any]]:
169
+ try:
170
+ return propose_plan(beliefs, constraints, task_desc,
171
+ action_context,
172
+ required_beliefs=required_beliefs,
173
+ **self.llm_kw)
174
+ except Exception as e:
175
+ print(f"[llm_bk] propose_plan error: {e}", file=sys.stderr)
176
+ return None
177
+
178
+ def _llm_propose_action(self, plan_step: Dict[str, Any], message_text: str,
179
+ is_duplicate: bool,
180
+ action_metadata: Dict[str, Any]) -> Optional[Dict[str, Any]]:
181
+ try:
182
+ return propose_action(plan_step, message_text, is_duplicate,
183
+ action_metadata, **self.llm_kw)
184
+ except Exception as e:
185
+ print(f"[llm_bk] propose_action error: {e}", file=sys.stderr)
186
+ return None
@@ -0,0 +1,33 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass
3
+ from typing import Any, Dict
4
+ from ..tools.payment_tool import PaymentTool
5
+ from ..tools.refund_tool import RefundTool
6
+
7
+ @dataclass
8
+ class StringGlueAgent:
9
+ payment_tool: PaymentTool
10
+ refund_tool: RefundTool
11
+ id: str = "string_glue"
12
+
13
+ def run(self, seed: int, task_inputs: Dict[str, Any]) -> Dict[str, Any]:
14
+ charge = self.payment_tool.get_charge(
15
+ seed, task_inputs["chargeId"], task_inputs["customerId"],
16
+ task_inputs["amount"])
17
+ if charge is None:
18
+ charge = {"charge_id": task_inputs["chargeId"],
19
+ "amount": task_inputs["amount"], "currency": "usd",
20
+ "status": "disputed", "stale": False, "conflict": False,
21
+ "customer_id": task_inputs["customerId"]}
22
+ charge.pop("_confidence", None)
23
+ refund_due = True
24
+ is_duplicate = task_inputs.get("is_duplicate", False)
25
+ refund = self.refund_tool.render_refund(
26
+ task_inputs["chargeId"], task_inputs["amount"],
27
+ task_inputs["customerId"],
28
+ reason=task_inputs.get("disputeReason", "customer_request"),
29
+ is_duplicate=is_duplicate)
30
+ action = {"type": "issue_refund", "amount": refund["amount"],
31
+ "charge_id": refund["charge_id"], "is_duplicate": refund["is_duplicate"]}
32
+ return {"beliefs": {"refund_due": refund_due}, "action": action,
33
+ "tool_obs": {"charge": charge, "refund": refund}}
@@ -0,0 +1,13 @@
1
+ from .kernel import Kernel
2
+ from .schema import Record, Provenance, Slot, WriteMode
3
+ from .store import MemoryStore
4
+ from .store_protocol import StoreProtocol
5
+ from .sqlite_store import SqliteStore
6
+ from .permissions import PERMISSIONS, Role
7
+ from .validators import EvidenceValidator, SymbolicValidator
8
+ from .worker import Worker, BaseWorker
9
+ from .orchestrator import Orchestrator, OrchestratorResult
10
+ from .session import Session
11
+ from .sim_worker import SimulatorWorker, SimRule, evaluate_rule
12
+ from .adaptive_worker import AdaptiveWorker
13
+ from .client import AlethicClient, EpisodeResult
@@ -0,0 +1,134 @@
1
+ """Outcome-driven adaptive constraint learner.
2
+
3
+ Inspects the kernel's store for invalidated records, counts failure
4
+ patterns by reason code, and proposes persistent constraints when
5
+ a pattern exceeds a configurable threshold. This is real learning
6
+ from observed data — the constraints are derived, not scripted.
7
+ """
8
+ from __future__ import annotations
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Dict, FrozenSet, List, Set
11
+
12
+ from .permissions import Role
13
+ from .schema import Slot, Record
14
+ from .worker import BaseWorker
15
+
16
+ # Mapping from invalidation reason codes to constraint definitions.
17
+ # Each entry says: "if we see this reason N times, create this constraint."
18
+ _DEFAULT_REASON_TO_CONSTRAINT = {
19
+ "STALE_EVIDENCE": {
20
+ "name": "block_stale_actions",
21
+ "definition": {"enabled": True, "blocks_field": "uses_stale_data",
22
+ "source": "adaptive", "trigger": "STALE_EVIDENCE"},
23
+ },
24
+ "UNRESOLVED_CONFLICT": {
25
+ "name": "block_conflicted_actions",
26
+ "definition": {"enabled": True, "blocks_field": "uses_conflicted_data",
27
+ "source": "adaptive", "trigger": "UNRESOLVED_CONFLICT"},
28
+ },
29
+ "LOW_CONFIDENCE": {
30
+ "name": "block_low_confidence_actions",
31
+ "definition": {"enabled": True, "blocks_field": "uses_low_confidence_data",
32
+ "source": "adaptive", "trigger": "LOW_CONFIDENCE"},
33
+ },
34
+ "NEGATIVE_PREDICTION": {
35
+ "name": "block_negative_predictions",
36
+ "definition": {"enabled": True, "blocks_field": "has_negative_prediction",
37
+ "source": "adaptive", "trigger": "NEGATIVE_PREDICTION"},
38
+ },
39
+ }
40
+
41
+
42
+ @dataclass
43
+ class AdaptiveWorker(BaseWorker):
44
+ """Learns persistent constraints from failure patterns in the store.
45
+
46
+ After each episode, call `analyze(store)` to scan invalidated records
47
+ and queue constraints. On the next orchestrator run the worker will
48
+ commit any queued constraints as persistent records.
49
+
50
+ Attributes:
51
+ failure_threshold: how many occurrences of a reason code before
52
+ a constraint is proposed (default 2 — learn fast)
53
+ reason_to_constraint: mapping from reason codes to constraint
54
+ definitions. Override to customize what gets learned.
55
+ emitted: set of constraint names already committed (prevents dupes)
56
+ """
57
+ worker_id: str = "adaptive"
58
+ role: Role = "symbolic_validator"
59
+ reads: FrozenSet[Slot] = field(
60
+ default_factory=lambda: frozenset(["constraints"]))
61
+ writes: FrozenSet[Slot] = field(
62
+ default_factory=lambda: frozenset(["constraints"]))
63
+ failure_threshold: int = 2
64
+ reason_to_constraint: Dict[str, Dict[str, Any]] = field(
65
+ default_factory=lambda: dict(_DEFAULT_REASON_TO_CONSTRAINT))
66
+ emitted: Set[str] = field(default_factory=set)
67
+ _queued: Dict[str, Dict[str, Any]] = field(
68
+ default_factory=dict, repr=False)
69
+
70
+ def analyze(self, store: Any) -> List[str]:
71
+ """Scan the store for failure patterns and queue constraints.
72
+
73
+ Works with any store. Iterates invalidated records across
74
+ mutable slots and normalizes reason strings to base codes
75
+ (STALE_EVIDENCE, LOW_CONFIDENCE, etc.) before counting.
76
+
77
+ Returns a list of constraint names that were queued.
78
+ """
79
+ counts: Dict[str, int] = {}
80
+ for slot_name in ["beliefs", "actions", "plans", "predictions"]:
81
+ for rec in store.list_slot(slot_name):
82
+ if rec.status == "INVALIDATED" and rec.reason:
83
+ base = self._base_reason(rec.reason)
84
+ counts[base] = counts.get(base, 0) + 1
85
+
86
+ queued_names: List[str] = []
87
+ for reason, count in counts.items():
88
+ if count < self.failure_threshold:
89
+ continue
90
+ mapping = self.reason_to_constraint.get(reason)
91
+ if mapping is None:
92
+ continue
93
+ cname = mapping["name"]
94
+ if cname in self.emitted:
95
+ continue
96
+ defn = dict(mapping["definition"])
97
+ defn["learned_from_count"] = count
98
+ self._queued[cname] = defn
99
+ queued_names.append(cname)
100
+
101
+ return queued_names
102
+
103
+ def should_activate(self, view: Dict[str, Dict[str, Any]]) -> bool:
104
+ return bool(self._queued)
105
+
106
+ def step(self, kernel: Any, trace_id: str,
107
+ view: Dict[str, Dict[str, Any]]) -> bool:
108
+ if not self._queued:
109
+ return False
110
+ for cname, cdef in self._queued.items():
111
+ kernel.write("symbolic_validator", "constraints", "COMMIT",
112
+ cname, cdef, trace_id, scope="persistent")
113
+ self.emitted.add(cname)
114
+ self._queued.clear()
115
+ return True
116
+
117
+ @staticmethod
118
+ def _base_reason(reason: str) -> str:
119
+ """Extract the base reason code from a detailed reason string.
120
+
121
+ e.g. 'Belief depends on stale percept: invoice' -> 'STALE_EVIDENCE'
122
+ 'Low confidence on percept: temperature' -> 'LOW_CONFIDENCE'
123
+ """
124
+ r = reason.upper()
125
+ if "STALE" in r:
126
+ return "STALE_EVIDENCE"
127
+ if "CONFLICT" in r:
128
+ return "UNRESOLVED_CONFLICT"
129
+ if "LOW CONFIDENCE" in r or "LOW_CONFIDENCE" in r:
130
+ return "LOW_CONFIDENCE"
131
+ if "NEGATIVE" in r:
132
+ return "NEGATIVE_PREDICTION"
133
+ # return the raw reason if no mapping found
134
+ return reason
File without changes
@@ -0,0 +1,65 @@
1
+ """FastAPI application factory."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from contextlib import asynccontextmanager
6
+ from importlib.metadata import PackageNotFoundError, version as _dist_version
7
+ from typing import Any, AsyncGenerator
8
+
9
+ from fastapi import FastAPI, Request
10
+ from fastapi.exceptions import RequestValidationError
11
+ from fastapi.responses import JSONResponse
12
+
13
+ from .routes import router
14
+ from .dependencies import reset_shared_state
15
+
16
+
17
+ def _pkg_version() -> str:
18
+ try:
19
+ return _dist_version("alethic-kernel")
20
+ except PackageNotFoundError: # running from a source tree, not installed
21
+ return "0.0.0.dev0"
22
+
23
+
24
+ def _json_safe(value: Any) -> Any:
25
+ """Replace non-finite floats with their repr so the value can be encoded.
26
+
27
+ Validation errors echo the offending input back to the client, and a
28
+ rejected NaN or infinity is not JSON-encodable — without this the 422 fails
29
+ to serialize and the client gets a 500 instead of the reason it was refused.
30
+ """
31
+ if isinstance(value, float) and not math.isfinite(value):
32
+ return repr(value)
33
+ if isinstance(value, dict):
34
+ return {k: _json_safe(v) for k, v in value.items()}
35
+ if isinstance(value, (list, tuple)):
36
+ return [_json_safe(v) for v in value]
37
+ return value
38
+
39
+
40
+ async def _validation_error_handler(
41
+ request: Request, exc: RequestValidationError
42
+ ) -> JSONResponse:
43
+ return JSONResponse(status_code=422, content={"detail": _json_safe(exc.errors())})
44
+
45
+
46
+ @asynccontextmanager
47
+ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
48
+ yield
49
+ reset_shared_state()
50
+
51
+
52
+ def create_app() -> FastAPI:
53
+ """Create and configure the FastAPI application."""
54
+ app = FastAPI(
55
+ title="Alethic Kernel API",
56
+ description="Domain-agnostic AI governance kernel",
57
+ # Read from the installed package rather than repeated here: a hardcoded
58
+ # copy means /openapi.json keeps reporting the old version after a bump,
59
+ # and a version that lies is worse than one that is merely absent.
60
+ version=_pkg_version(),
61
+ lifespan=lifespan,
62
+ )
63
+ app.add_exception_handler(RequestValidationError, _validation_error_handler) # type: ignore[arg-type]
64
+ app.include_router(router)
65
+ return app
@@ -0,0 +1,59 @@
1
+ """Kernel lifecycle management for the API layer."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import threading
6
+
7
+ from ..kernel import Kernel
8
+ from ..store import MemoryStore
9
+ from ..sqlite_store import SqliteStore
10
+ from ..store_protocol import StoreProtocol
11
+
12
+
13
+ def _get_store_type() -> str:
14
+ return os.environ.get("ALETHIC_STORE", "memory")
15
+
16
+
17
+ def _create_store() -> StoreProtocol:
18
+ store_type = _get_store_type()
19
+ if store_type == "sqlite":
20
+ db_path = os.environ.get("ALETHIC_DB_PATH", "blackboard.db")
21
+ return SqliteStore(db_path)
22
+ return MemoryStore()
23
+
24
+
25
+ # Shared state — both modes use a shared kernel for low-level endpoints.
26
+ # The difference: memory mode loses data on restart; sqlite mode persists.
27
+ _shared_store: StoreProtocol | None = None
28
+ _shared_kernel: Kernel | None = None
29
+ _init_lock = threading.Lock()
30
+
31
+
32
+ def get_shared_kernel() -> Kernel:
33
+ """Return the shared kernel for low-level endpoints.
34
+
35
+ In memory mode: shared MemoryStore (data lost on restart).
36
+ In sqlite mode: shared SqliteStore (data persists across restarts).
37
+ """
38
+ global _shared_store, _shared_kernel
39
+ if _shared_kernel is not None:
40
+ return _shared_kernel
41
+ with _init_lock:
42
+ if _shared_kernel is None:
43
+ _shared_store = _create_store()
44
+ _shared_kernel = Kernel(store=_shared_store)
45
+ return _shared_kernel
46
+
47
+
48
+ def get_ephemeral_kernel() -> Kernel:
49
+ """Always return a fresh kernel (for /v1/episode)."""
50
+ return Kernel()
51
+
52
+
53
+ def reset_shared_state() -> None:
54
+ """Reset shared state (for testing)."""
55
+ global _shared_store, _shared_kernel
56
+ if _shared_store is not None:
57
+ _shared_store.close()
58
+ _shared_store = None
59
+ _shared_kernel = None