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,261 @@
1
+ from __future__ import annotations
2
+ import math
3
+ import threading
4
+ from typing import Any, Dict, List, Literal, Optional, Tuple
5
+ import time
6
+
7
+ from .schema import Record, Provenance, RecordIdConflict, Slot, WriteMode
8
+ from .store import MemoryStore
9
+ from .store_protocol import StoreProtocol
10
+ from .permissions import PERMISSIONS, Role
11
+ from .validators import EvidenceValidator, SymbolicValidator
12
+
13
+ def _rid(slot: str, n: int, trace_id: str) -> str:
14
+ return f"{slot}:{trace_id}:{n}"
15
+
16
+
17
+ # A backstop against spinning forever if a store reports every id as taken.
18
+ # Reached only by a store that is misbehaving, never by a busy trace.
19
+ _MAX_ID_PROBES = 10_000
20
+
21
+ class Kernel:
22
+ def __init__(self, min_confidence: float = 0.5,
23
+ conflict_confidence_threshold: float = 0.7,
24
+ store: Optional[StoreProtocol] = None) -> None:
25
+ self.store: StoreProtocol = store if store is not None else MemoryStore()
26
+ self._counters: Dict[str, int] = {}
27
+ self._counter_lock = threading.Lock()
28
+ self._commit_lock = threading.Lock()
29
+ self.evidence_validator = EvidenceValidator()
30
+ self.symbolic_validator = SymbolicValidator()
31
+ self.min_confidence = min_confidence
32
+ self.conflict_confidence_threshold = conflict_confidence_threshold
33
+
34
+ def _next_id(self, slot: str, trace_id: str) -> str:
35
+ key = f"{slot}:{trace_id}"
36
+ with self._counter_lock:
37
+ self._counters[key] = self._counters.get(key, 0) + 1
38
+ return _rid(slot, self._counters[key], trace_id)
39
+
40
+
41
+ def write(self, role: Role, slot: Slot, mode: WriteMode, kind: str, payload: Dict[str, Any],
42
+ trace_id: str, input_refs: Optional[List[str]] = None, confidence: Optional[float] = None,
43
+ ttl_ms: Optional[int] = None, evidence_refs: Optional[List[str]] = None,
44
+ scope: Literal["episode", "persistent"] = "episode") -> Record:
45
+ perms = PERMISSIONS.get(role)
46
+ allowed = perms.get(slot, frozenset()) if perms is not None else frozenset()
47
+ if mode not in allowed:
48
+ raise PermissionError(f"Role {role} cannot {mode} to {slot}")
49
+ # Rejects NaN and the infinities as well as out-of-range values: every
50
+ # comparison against NaN is False, so a NaN that reached the confidence
51
+ # gate would pass straight through it.
52
+ if confidence is not None and not (0.0 <= confidence <= 1.0):
53
+ raise ValueError(f"confidence must be in [0.0, 1.0], got {confidence!r}")
54
+ # Counters live in this process while the store may outlive it, so the
55
+ # store can already hold `beliefs:order-123:1` — written by an earlier
56
+ # run against the same database, or by another kernel sharing it. Walk
57
+ # forward until an id is free rather than colliding on the primary key.
58
+ # Each pass takes the next counter value, so this converges on the
59
+ # records already under this trace.
60
+ for _ in range(_MAX_ID_PROBES):
61
+ rec = Record(
62
+ id=self._next_id(slot, trace_id),
63
+ slot=slot, mode=mode, kind=kind, payload=payload,
64
+ prov=Provenance(
65
+ writer_id=role, trace_id=trace_id,
66
+ ts_ms=int(time.time() * 1000),
67
+ input_refs=input_refs or [],
68
+ confidence=confidence, ttl_ms=ttl_ms,
69
+ ),
70
+ evidence_refs=evidence_refs or [],
71
+ scope=scope,
72
+ )
73
+ try:
74
+ self.store.append(rec)
75
+ return rec
76
+ except RecordIdConflict:
77
+ continue
78
+ raise RuntimeError(
79
+ f"could not allocate a record id for {slot}:{trace_id} after "
80
+ f"{_MAX_ID_PROBES} attempts"
81
+ )
82
+
83
+ def current_view(self, trace_id: str,
84
+ include_persistent: bool = False) -> Dict[str, Dict[str, Any]]:
85
+ slots: List[Slot] = ["percepts", "beliefs", "constraints", "plans",
86
+ "evidence", "predictions", "actions"]
87
+ view: Dict[str, Dict[str, Any]] = {s: {} for s in slots}
88
+ for slot in slots:
89
+ for r in self.store.list_slot(slot):
90
+ if r.status != "ACTIVE":
91
+ continue
92
+ # include record if it matches the trace_id, or if it's
93
+ # persistent and the caller opted in
94
+ if r.prov.trace_id != trace_id:
95
+ if not (include_persistent and r.scope == "persistent"):
96
+ continue
97
+ if r.mode == "COMMIT":
98
+ view[slot][r.kind] = r.payload
99
+ else:
100
+ view[slot].setdefault("_proposals", []).append(
101
+ {"id": r.id, "kind": r.kind, "payload": r.payload})
102
+ return view
103
+
104
+ # ── belief commitment with evidence validation ──────────────────────
105
+
106
+ def commit_belief_from_proposal(self, proposal_id: str, trace_id: str) -> Tuple[bool, str]:
107
+ with self._commit_lock:
108
+ prop = self.store.get(proposal_id)
109
+ if not prop or prop.status != "ACTIVE" or prop.slot != "beliefs" or prop.mode != "PROPOSE":
110
+ return False, "INVALID_PROPOSAL"
111
+
112
+ view = self.current_view(trace_id)
113
+ res = self.evidence_validator.validate_belief_commit(prop.payload, view["percepts"])
114
+
115
+ if not res.ok:
116
+ # conflict arbitration: high-confidence source overrides conflict
117
+ if res.code == "CONFLICTING_EVIDENCE":
118
+ dep_key = res.context.get("percept_key")
119
+ dep_rec = self.store.find_active_by_kind("percepts", dep_key, trace_id) if dep_key else None
120
+ if (dep_rec and dep_rec.prov.confidence is not None
121
+ and dep_rec.prov.confidence >= self.conflict_confidence_threshold):
122
+ pass # arbitrated — proceed
123
+ else:
124
+ self.store.invalidate(proposal_id, res.detail)
125
+ return False, "UNRESOLVED_CONFLICT"
126
+ else:
127
+ self.store.invalidate(proposal_id, res.detail)
128
+ return False, res.code
129
+
130
+ # confidence gate on dependent percepts
131
+ for dep_kind in prop.payload.get("depends_on", []):
132
+ dep_rec = self.store.find_active_by_kind("percepts", dep_kind, trace_id)
133
+ if dep_rec and dep_rec.prov.confidence is not None:
134
+ conf = dep_rec.prov.confidence
135
+ # An unknown confidence is exactly what this gate is for, so
136
+ # NaN must fail it rather than slip through `conf < min`.
137
+ if math.isnan(conf) or conf < self.min_confidence:
138
+ self.store.invalidate(proposal_id, f"Low confidence on percept: {dep_kind}")
139
+ return False, "LOW_CONFIDENCE"
140
+
141
+ # record evidence artifact
142
+ checks = ["existence", "staleness", "conflict"]
143
+ for dep_kind in prop.payload.get("depends_on", []):
144
+ dep_rec = self.store.find_active_by_kind("percepts", dep_kind, trace_id)
145
+ if dep_rec and dep_rec.prov.confidence is not None:
146
+ checks.append("confidence")
147
+ break
148
+ # One unit: evidence saying validation passed must not outlive the
149
+ # belief it vouches for, and the proposal must stay retryable unless
150
+ # the belief actually lands.
151
+ with self.store.transaction():
152
+ ev_rec = self.write(
153
+ "evidence_validator", "evidence", "COMMIT",
154
+ f"validation_{prop.kind}",
155
+ {"belief": prop.kind, "result": "pass", "checks": checks},
156
+ trace_id,
157
+ )
158
+ self.store.invalidate(proposal_id, "SUPERSEDED_BY_COMMIT")
159
+ self.write(
160
+ "kernel", "beliefs", "COMMIT", prop.kind, prop.payload, trace_id,
161
+ input_refs=prop.prov.input_refs, confidence=prop.prov.confidence,
162
+ evidence_refs=[ev_rec.id],
163
+ )
164
+ return True, "COMMITTED"
165
+
166
+ # ── plan feasibility check ──────────────────────────────────────────
167
+
168
+ def validate_plan(self, proposal_id: str, trace_id: str) -> Tuple[bool, str]:
169
+ with self._commit_lock:
170
+ prop = self.store.get(proposal_id)
171
+ if not prop or prop.status != "ACTIVE" or prop.slot != "plans" or prop.mode != "PROPOSE":
172
+ return False, "INVALID_PLAN_PROPOSAL"
173
+
174
+ view = self.current_view(trace_id)
175
+ committed_beliefs = view["beliefs"]
176
+ constraints = view["constraints"]
177
+
178
+ for step in prop.payload.get("steps", []):
179
+ # required beliefs must be committed and truthy
180
+ for belief_name in step.get("requires_beliefs", []):
181
+ belief = committed_beliefs.get(belief_name)
182
+ if belief is None:
183
+ self.store.invalidate(proposal_id, f"Plan requires missing belief: {belief_name}")
184
+ return False, "PLAN_MISSING_BELIEF"
185
+ value = belief.get("value") if isinstance(belief, dict) else belief
186
+ if not value:
187
+ self.store.invalidate(proposal_id, f"Plan requires unsatisfied belief: {belief_name}")
188
+ return False, "PLAN_BELIEF_NOT_SATISFIED"
189
+ # constraint pre-check
190
+ for cname, cval in constraints.items():
191
+ if not isinstance(cval, dict) or not cval.get("enabled"):
192
+ continue
193
+ blocked_field = cval.get("blocks_field")
194
+ if blocked_field and step.get(blocked_field) is True:
195
+ self.store.invalidate(proposal_id, f"Plan blocked by constraint: {cname}")
196
+ return False, f"PLAN_{cname.upper()}_BLOCKED"
197
+
198
+ return True, "PLAN_FEASIBLE"
199
+
200
+ # ── prediction commitment ───────────────────────────────────────────
201
+
202
+ def commit_prediction(self, proposal_id: str, trace_id: str) -> Tuple[bool, str]:
203
+ with self._commit_lock:
204
+ prop = self.store.get(proposal_id)
205
+ if (not prop or prop.status != "ACTIVE"
206
+ or prop.slot != "predictions" or prop.mode != "PROPOSE"):
207
+ return False, "INVALID_PREDICTION_PROPOSAL"
208
+ # validate that required beliefs exist
209
+ for dep in prop.payload.get("requires_beliefs", []):
210
+ if not self.store.find_active_by_kind("beliefs", dep, trace_id):
211
+ self.store.invalidate(proposal_id,
212
+ f"Prediction requires missing belief: {dep}")
213
+ return False, "PREDICTION_MISSING_BELIEF"
214
+ with self.store.transaction():
215
+ self.store.invalidate(proposal_id, "SUPERSEDED_BY_COMMIT")
216
+ self.write(
217
+ "kernel", "predictions", "COMMIT", prop.kind, prop.payload,
218
+ trace_id, input_refs=prop.prov.input_refs,
219
+ confidence=prop.prov.confidence,
220
+ )
221
+ return True, "COMMITTED"
222
+
223
+ # ── action commitment with symbolic validation ──────────────────────
224
+
225
+ def commit_action_from_proposal(self, proposal_id: str, trace_id: str,
226
+ require_prediction: bool = False) -> Tuple[bool, str]:
227
+ with self._commit_lock:
228
+ prop = self.store.get(proposal_id)
229
+ if not prop or prop.status != "ACTIVE" or prop.slot != "actions" or prop.mode != "PROPOSE":
230
+ return False, "INVALID_ACTION_PROPOSAL"
231
+ view = self.current_view(trace_id)
232
+
233
+ # optional prediction gate
234
+ if require_prediction:
235
+ action_type = prop.payload.get("type", prop.kind)
236
+ predictions = view.get("predictions", {})
237
+ matched = None
238
+ for _pk, pval in predictions.items():
239
+ if isinstance(pval, dict) and pval.get("action_type") == action_type:
240
+ matched = pval
241
+ break
242
+ if matched is None:
243
+ self.store.invalidate(proposal_id,
244
+ f"No prediction for action type: {action_type}")
245
+ return False, "NO_PREDICTION"
246
+ if matched.get("expected_outcome", 0) < 0:
247
+ self.store.invalidate(proposal_id,
248
+ f"Prediction negative for: {action_type}")
249
+ return False, "NEGATIVE_PREDICTION"
250
+
251
+ res = self.symbolic_validator.validate_action(prop.payload, view["beliefs"], view["constraints"])
252
+ if not res.ok:
253
+ self.store.invalidate(proposal_id, res.detail)
254
+ return False, res.code
255
+ with self.store.transaction():
256
+ self.store.invalidate(proposal_id, "SUPERSEDED_BY_COMMIT")
257
+ self.write(
258
+ "kernel", "actions", "COMMIT", prop.kind, prop.payload, trace_id,
259
+ input_refs=prop.prov.input_refs, confidence=prop.prov.confidence,
260
+ )
261
+ return True, "COMMITTED"
@@ -0,0 +1,76 @@
1
+ """Zero-dependency schema migration system for SqliteStore.
2
+
3
+ Tracks schema version in a `schema_version` table. Each migration is a SQL
4
+ string keyed by version number. `migrate()` applies all pending migrations
5
+ in order. Fresh databases get all migrations. Existing databases upgrade
6
+ incrementally. Running `migrate()` twice is safe (idempotent).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import sqlite3
11
+ from typing import Dict
12
+
13
+
14
+ # ── Migration registry ───────────────────────────────────────────────
15
+ # Each key is a version number (1-indexed). Value is the SQL to apply.
16
+ # New migrations MUST be appended — never modify or reorder existing ones.
17
+
18
+ MIGRATIONS: Dict[int, str] = {
19
+ 1: """
20
+ CREATE TABLE IF NOT EXISTS records (
21
+ id TEXT PRIMARY KEY,
22
+ slot TEXT NOT NULL,
23
+ mode TEXT NOT NULL,
24
+ kind TEXT NOT NULL,
25
+ payload TEXT NOT NULL,
26
+ writer_id TEXT NOT NULL,
27
+ trace_id TEXT NOT NULL,
28
+ ts_ms INTEGER NOT NULL,
29
+ input_refs TEXT NOT NULL,
30
+ confidence REAL,
31
+ ttl_ms INTEGER,
32
+ evidence_refs TEXT NOT NULL,
33
+ status TEXT NOT NULL DEFAULT 'ACTIVE',
34
+ reason TEXT,
35
+ scope TEXT NOT NULL DEFAULT 'episode'
36
+ );
37
+ CREATE INDEX IF NOT EXISTS idx_slot ON records(slot);
38
+ CREATE INDEX IF NOT EXISTS idx_trace ON records(trace_id);
39
+ CREATE INDEX IF NOT EXISTS idx_status ON records(status);
40
+ CREATE INDEX IF NOT EXISTS idx_slot_kind_trace ON records(slot, kind, trace_id, status);
41
+ """,
42
+ }
43
+
44
+
45
+ def _ensure_version_table(conn: sqlite3.Connection) -> None:
46
+ """Create the schema_version table if it doesn't exist."""
47
+ conn.execute("""
48
+ CREATE TABLE IF NOT EXISTS schema_version (
49
+ version INTEGER PRIMARY KEY
50
+ )
51
+ """)
52
+ conn.commit()
53
+
54
+
55
+ def _current_version(conn: sqlite3.Connection) -> int:
56
+ """Return the current schema version (0 if no migrations applied)."""
57
+ cur = conn.execute("SELECT MAX(version) FROM schema_version")
58
+ row = cur.fetchone()
59
+ if row is None or row[0] is None:
60
+ return 0
61
+ return int(row[0])
62
+
63
+
64
+ def migrate(conn: sqlite3.Connection) -> int:
65
+ """Apply all pending migrations. Returns the final schema version."""
66
+ _ensure_version_table(conn)
67
+ current = _current_version(conn)
68
+
69
+ for version in sorted(MIGRATIONS.keys()):
70
+ if version <= current:
71
+ continue
72
+ conn.executescript(MIGRATIONS[version])
73
+ conn.execute("INSERT INTO schema_version (version) VALUES (?)", (version,))
74
+ conn.commit()
75
+
76
+ return _current_version(conn)
@@ -0,0 +1,99 @@
1
+ from __future__ import annotations
2
+ import sys
3
+
4
+ from dataclasses import dataclass, field
5
+ from typing import Any, Callable, Dict, List, Optional
6
+
7
+ from .kernel import Kernel
8
+ from .worker import Worker
9
+
10
+
11
+ @dataclass
12
+ class OrchestratorResult:
13
+ trace_id: str
14
+ view: Dict[str, Dict[str, Any]]
15
+ rounds: int
16
+ worker_log: List[Dict[str, Any]] = field(default_factory=list)
17
+ errors: List[Dict[str, Any]] = field(default_factory=list)
18
+
19
+
20
+ def _dependency_key(w: Worker) -> int:
21
+ """Sort workers so those that write to early slots run first."""
22
+ order = {"percepts": 0, "beliefs": 1, "constraints": 2,
23
+ "plans": 3, "evidence": 4, "predictions": 5, "actions": 6}
24
+ if not w.writes:
25
+ return 0
26
+ return min(order.get(s, 99) for s in w.writes)
27
+
28
+
29
+ class Orchestrator:
30
+ """Generic round-robin loop over Worker instances on a Kernel.
31
+
32
+ Workers are sorted by dependency (writers of early slots run first).
33
+ Each round, every worker that wants to activate gets a `step()` call.
34
+ The loop stops at quiescence (no worker produced) or max_rounds.
35
+
36
+ Worker exceptions are caught, logged, and the loop continues with
37
+ the remaining workers. Errors are collected in the result.
38
+ """
39
+
40
+ def __init__(self, kernel: Kernel, workers: List[Worker],
41
+ max_rounds: int = 20,
42
+ on_error: Optional[Callable[[str, Exception], None]] = None,
43
+ ) -> None:
44
+ self.kernel = kernel
45
+ self.workers = sorted(workers, key=_dependency_key)
46
+ self.max_rounds = max_rounds
47
+ self._on_error = on_error
48
+
49
+ def run(self, trace_id: str,
50
+ include_persistent: bool = False) -> OrchestratorResult:
51
+ log: List[Dict[str, Any]] = []
52
+ errors: List[Dict[str, Any]] = []
53
+ rounds = 0
54
+
55
+ for _ in range(self.max_rounds):
56
+ rounds += 1
57
+ any_produced = False
58
+ view = self.kernel.current_view(trace_id,
59
+ include_persistent=include_persistent)
60
+
61
+ for w in self.workers:
62
+ try:
63
+ if not w.should_activate(view):
64
+ continue
65
+ except Exception as exc:
66
+ self._handle_error(w.worker_id, "should_activate", exc, errors)
67
+ continue
68
+
69
+ try:
70
+ produced = w.step(self.kernel, trace_id, view)
71
+ except Exception as exc:
72
+ self._handle_error(w.worker_id, "step", exc, errors)
73
+ produced = False
74
+
75
+ log.append({"round": rounds, "worker": w.worker_id,
76
+ "produced": produced})
77
+ if produced:
78
+ any_produced = True
79
+ view = self.kernel.current_view(
80
+ trace_id, include_persistent=include_persistent)
81
+
82
+ if not any_produced:
83
+ break # quiescence
84
+
85
+ final_view = self.kernel.current_view(trace_id,
86
+ include_persistent=include_persistent)
87
+ return OrchestratorResult(trace_id=trace_id, view=final_view,
88
+ rounds=rounds, worker_log=log, errors=errors)
89
+
90
+ def _handle_error(self, worker_id: str, phase: str, exc: Exception,
91
+ errors: List[Dict[str, Any]]) -> None:
92
+ entry = {"worker": worker_id, "phase": phase,
93
+ "error": str(exc), "type": type(exc).__name__}
94
+ errors.append(entry)
95
+ if self._on_error:
96
+ self._on_error(worker_id, exc)
97
+ else:
98
+ print(f"[orchestrator] {worker_id}.{phase}() failed: {exc}",
99
+ file=sys.stderr)
@@ -0,0 +1,16 @@
1
+ from __future__ import annotations
2
+ from types import MappingProxyType
3
+ from typing import Dict, FrozenSet, Literal, Mapping, Set
4
+
5
+ Role = Literal["kernel","tool","planner","symbolic_validator","evidence_validator","sim_validator"]
6
+
7
+ PERMISSIONS: Mapping[str, Mapping[str, FrozenSet[str]]] = MappingProxyType({
8
+ "tool": MappingProxyType({"percepts": frozenset({"COMMIT"})}),
9
+ "planner": MappingProxyType({"beliefs": frozenset({"PROPOSE"}), "plans": frozenset({"PROPOSE"}),
10
+ "actions": frozenset({"PROPOSE"}), "predictions": frozenset({"PROPOSE"})}),
11
+ "symbolic_validator": MappingProxyType({"constraints": frozenset({"COMMIT"})}),
12
+ "evidence_validator": MappingProxyType({"evidence": frozenset({"COMMIT"})}),
13
+ "sim_validator": MappingProxyType({"evidence": frozenset({"COMMIT"}), "predictions": frozenset({"COMMIT"})}),
14
+ "kernel": MappingProxyType({"beliefs": frozenset({"COMMIT"}), "actions": frozenset({"COMMIT"}),
15
+ "predictions": frozenset({"COMMIT"})}),
16
+ })
File without changes
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass, field
3
+ from typing import Any, Dict, List, Optional, Literal
4
+
5
+ Slot = Literal["percepts","beliefs","constraints","plans","evidence","predictions","actions"]
6
+ WriteMode = Literal["PROPOSE","COMMIT"]
7
+
8
+
9
+ class RecordIdConflict(Exception):
10
+ """A record with this id already exists.
11
+
12
+ Records are an append-only audit trail, so a store must refuse to replace
13
+ one rather than silently overwrite it. Raised by every store so callers can
14
+ react without knowing which backend they hold.
15
+ """
16
+
17
+ @dataclass
18
+ class Provenance:
19
+ writer_id: str
20
+ trace_id: str
21
+ ts_ms: int
22
+ input_refs: List[str] = field(default_factory=list)
23
+ confidence: Optional[float] = None
24
+ ttl_ms: Optional[int] = None
25
+
26
+ @dataclass
27
+ class Record:
28
+ id: str
29
+ slot: Slot
30
+ mode: WriteMode
31
+ kind: str
32
+ payload: Dict[str, Any]
33
+ prov: Provenance
34
+ evidence_refs: List[str] = field(default_factory=list)
35
+ status: Literal["ACTIVE","INVALIDATED","EXPIRED"] = "ACTIVE"
36
+ reason: Optional[str] = None
37
+ scope: Literal["episode", "persistent"] = "episode"
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+ import threading
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Dict
5
+ import uuid
6
+
7
+
8
+ @dataclass
9
+ class Session:
10
+ """Groups multiple episodes under a single persistent context."""
11
+
12
+ session_id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
13
+ metadata: Dict[str, Any] = field(default_factory=dict)
14
+ _episode_counter: int = field(default=0, repr=False)
15
+ _lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
16
+
17
+ def episode_trace_id(self) -> str:
18
+ """Generate a unique trace_id for a new episode within this session."""
19
+ with self._lock:
20
+ self._episode_counter += 1
21
+ counter = self._episode_counter
22
+ short = uuid.uuid4().hex[:8]
23
+ return f"{self.session_id}-ep{counter}-{short}"
@@ -0,0 +1,162 @@
1
+ """Rule-based forward simulator.
2
+
3
+ SimRules are declarative: they specify conditions on beliefs and percepts,
4
+ an action_type, and an expected_outcome. The SimulatorWorker evaluates
5
+ all rules against the current view and proposes predictions for matching
6
+ rules via the kernel's commit_prediction() pipeline.
7
+
8
+ Conditions are dicts of {field: value} for equality, or {field__op: value}
9
+ for comparisons (gt, lt, gte, lte, ne).
10
+ """
11
+ from __future__ import annotations
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Dict, FrozenSet, List, Optional
14
+
15
+ from .permissions import Role
16
+ from .schema import Slot
17
+ from .worker import BaseWorker
18
+
19
+
20
+ @dataclass
21
+ class SimRule:
22
+ """One declarative prediction rule.
23
+
24
+ Attributes:
25
+ action_type: the action this prediction is about
26
+ expected_outcome: positive = favorable, negative = unfavorable, 0 = neutral
27
+ requires_beliefs: belief kinds that must be committed
28
+ percept_conditions: {percept_kind: {field_op: value, ...}}
29
+ field_op is either "field" (equality) or "field__gt", "field__lt",
30
+ "field__gte", "field__lte", "field__ne"
31
+ belief_conditions: {belief_kind: {field_op: value, ...}}
32
+ confidence: confidence to attach to the prediction
33
+ """
34
+ action_type: str
35
+ expected_outcome: float
36
+ requires_beliefs: List[str] = field(default_factory=list)
37
+ percept_conditions: Dict[str, Dict[str, Any]] = field(default_factory=dict)
38
+ belief_conditions: Dict[str, Dict[str, Any]] = field(default_factory=dict)
39
+ confidence: float = 0.8
40
+
41
+
42
+ _OPS = {
43
+ "gt": lambda a, b: a > b,
44
+ "lt": lambda a, b: a < b,
45
+ "gte": lambda a, b: a >= b,
46
+ "lte": lambda a, b: a <= b,
47
+ "ne": lambda a, b: a != b,
48
+ }
49
+
50
+
51
+ def _check_conditions(payload: Dict[str, Any],
52
+ conditions: Dict[str, Any]) -> bool:
53
+ """Evaluate declarative conditions against a payload dict."""
54
+ for key, expected in conditions.items():
55
+ if "__" in key:
56
+ field_name, op = key.rsplit("__", 1)
57
+ actual = payload.get(field_name)
58
+ if actual is None:
59
+ return False
60
+ op_fn = _OPS.get(op)
61
+ if op_fn is None:
62
+ return False
63
+ if not op_fn(actual, expected):
64
+ return False
65
+ else:
66
+ if payload.get(key) != expected:
67
+ return False
68
+ return True
69
+
70
+
71
+ def evaluate_rule(rule: SimRule,
72
+ view: Dict[str, Dict[str, Any]]) -> Optional[float]:
73
+ """Evaluate a single rule against a view.
74
+
75
+ Returns the expected_outcome if all conditions pass, None otherwise.
76
+ """
77
+ beliefs = view.get("beliefs", {})
78
+ percepts = view.get("percepts", {})
79
+
80
+ # required beliefs must exist
81
+ for bname in rule.requires_beliefs:
82
+ if bname not in beliefs:
83
+ return None
84
+
85
+ # belief conditions
86
+ for bname, conds in rule.belief_conditions.items():
87
+ belief = beliefs.get(bname)
88
+ if belief is None or not isinstance(belief, dict):
89
+ return None
90
+ if not _check_conditions(belief, conds):
91
+ return None
92
+
93
+ # percept conditions
94
+ for pname, conds in rule.percept_conditions.items():
95
+ percept = percepts.get(pname)
96
+ if percept is None or not isinstance(percept, dict):
97
+ return None
98
+ if not _check_conditions(percept, conds):
99
+ return None
100
+
101
+ return rule.expected_outcome
102
+
103
+
104
+ @dataclass
105
+ class SimulatorWorker(BaseWorker):
106
+ """Evaluates SimRules and proposes predictions through the kernel.
107
+
108
+ For each rule whose conditions match the current view, proposes a
109
+ prediction with the rule's expected_outcome. The kernel's
110
+ commit_prediction() validates that required beliefs exist before
111
+ committing.
112
+ """
113
+ worker_id: str = "simulator"
114
+ role: Role = "planner"
115
+ reads: FrozenSet[Slot] = field(
116
+ default_factory=lambda: frozenset(["beliefs", "percepts", "predictions"]))
117
+ writes: FrozenSet[Slot] = field(
118
+ default_factory=lambda: frozenset(["predictions"]))
119
+ rules: List[SimRule] = field(default_factory=list)
120
+ _done: bool = field(default=False, repr=False)
121
+
122
+ def reset(self) -> None:
123
+ self._done = False
124
+
125
+ def should_activate(self, view: Dict[str, Dict[str, Any]]) -> bool:
126
+ if self._done:
127
+ return False
128
+ # activate once beliefs exist and we haven't run yet
129
+ return bool(view.get("beliefs"))
130
+
131
+ def step(self, kernel: Any, trace_id: str,
132
+ view: Dict[str, Dict[str, Any]]) -> bool:
133
+ self._done = True
134
+ produced = False
135
+ predictions = view.get("predictions", {})
136
+
137
+ for rule in self.rules:
138
+ # skip if prediction for this action_type already committed
139
+ pred_kind = f"pred_{rule.action_type}"
140
+ if pred_kind in predictions:
141
+ continue
142
+
143
+ outcome = evaluate_rule(rule, view)
144
+ if outcome is None:
145
+ continue
146
+
147
+ prop = kernel.write(
148
+ "planner", "predictions", "PROPOSE", pred_kind,
149
+ {"action_type": rule.action_type,
150
+ "expected_outcome": outcome,
151
+ "requires_beliefs": rule.requires_beliefs,
152
+ "rule_conditions": {
153
+ "percept_conditions": rule.percept_conditions,
154
+ "belief_conditions": rule.belief_conditions,
155
+ }},
156
+ trace_id, confidence=rule.confidence,
157
+ )
158
+ ok, code = kernel.commit_prediction(prop.id, trace_id)
159
+ if ok:
160
+ produced = True
161
+
162
+ return produced