amiril 0.0.0.dev0__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 (64) hide show
  1. amiril/__init__.py +51 -0
  2. amiril/_adapters.py +399 -0
  3. amiril/_engine/__init__.py +1 -0
  4. amiril/_engine/engine.py +113 -0
  5. amiril/_engine/expr.py +653 -0
  6. amiril/_engine/numbers.py +111 -0
  7. amiril/_engine/regex.py +262 -0
  8. amiril/_engine/rules.py +192 -0
  9. amiril/_engine/sentence.py +251 -0
  10. amiril/_engine/timeparse.py +72 -0
  11. amiril/_engine/validate.py +863 -0
  12. amiril/_engine/values.py +273 -0
  13. amiril/_kernel/__init__.py +1 -0
  14. amiril/_kernel/bundle.py +245 -0
  15. amiril/_kernel/coerce.py +103 -0
  16. amiril/_kernel/events.py +87 -0
  17. amiril/_kernel/guard.py +1196 -0
  18. amiril/_kernel/ids.py +66 -0
  19. amiril/_kernel/messages.py +30 -0
  20. amiril/_kernel/normalise.py +165 -0
  21. amiril/_kernel/records.py +131 -0
  22. amiril/_kernel/store.py +661 -0
  23. amiril/_runtime.py +617 -0
  24. amiril/adk.py +577 -0
  25. amiril/control/__init__.py +25 -0
  26. amiril/control/_delivery.py +567 -0
  27. amiril/control/_disk.py +418 -0
  28. amiril/control/_holds.py +252 -0
  29. amiril/control/_jsonschema.py +265 -0
  30. amiril/control/_pathc.py +85 -0
  31. amiril/control/_records.py +293 -0
  32. amiril/control/_redact.py +79 -0
  33. amiril/control/_transport.py +184 -0
  34. amiril/control/_wire.py +73 -0
  35. amiril/control/client.py +1313 -0
  36. amiril/control/config.py +204 -0
  37. amiril/control/schemas/bundle.response.schema.json +22 -0
  38. amiril/control/schemas/common.schema.json +593 -0
  39. amiril/control/schemas/decisions.request.schema.json +558 -0
  40. amiril/control/schemas/decisions.response.schema.json +23 -0
  41. amiril/control/schemas/error.response.schema.json +54 -0
  42. amiril/control/schemas/heartbeat.request.schema.json +305 -0
  43. amiril/control/schemas/heartbeat.response.schema.json +34 -0
  44. amiril/control/schemas/hold-create.request.schema.json +138 -0
  45. amiril/control/schemas/hold.response.schema.json +226 -0
  46. amiril/control/schemas/installation-register.request.schema.json +492 -0
  47. amiril/control/schemas/installation-register.response.schema.json +85 -0
  48. amiril/core.py +89 -0
  49. amiril/docs/README.md +14 -0
  50. amiril/docs/durability/langgraph.md +292 -0
  51. amiril/docs/frameworks/adk.md +141 -0
  52. amiril/docs/frameworks/langgraph.md +154 -0
  53. amiril/docs/frameworks/no-framework.md +238 -0
  54. amiril/docs/frameworks/write-an-adapter.md +203 -0
  55. amiril/durable.py +342 -0
  56. amiril/langgraph.py +746 -0
  57. amiril/plain.py +454 -0
  58. amiril/py.typed +0 -0
  59. amiril/seams.py +357 -0
  60. amiril/testing.py +21 -0
  61. amiril-0.0.0.dev0.dist-info/METADATA +114 -0
  62. amiril-0.0.0.dev0.dist-info/RECORD +64 -0
  63. amiril-0.0.0.dev0.dist-info/WHEEL +4 -0
  64. amiril-0.0.0.dev0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,1196 @@
1
+ """The kernel surface every adapter calls (spec/kernel.md).
2
+
3
+ `Guard.before_call` runs the steps of kernel.md 6.1 in order: re-execution or
4
+ retry, identity, record and evaluation, modes and aggregate, hold, block,
5
+ finish. A failure of the kernel itself on that path is a fault that fails
6
+ open when no decision exists yet and keeps the decision otherwise (section
7
+ 10), written as a fault line and never raised into the framework.
8
+ Cancellation and other control-flow exceptions (`BaseException`s that are
9
+ not `Exception`) are not faults: the kernel settles the call, releases what
10
+ it holds for it and re-raises. `after_call` is 6.2, `end_run` 8.2,
11
+ `end_session` 8.3, `swap` 8.4.
12
+
13
+ With a durable store (kernel.md 4.1a) the history store mirrors its writes,
14
+ the guard persists each `before_call` outcome before returning it, and the
15
+ first `before_call` of a root run or session not in memory loads that unit
16
+ back, settling what the dead process left unfinished (a `pending` record as
17
+ `error`, a `held` one as blocked with resolution `timeout`), so a re-fire of
18
+ either is a retry. A durable store that fails writes a fault line and the
19
+ in-memory store carries on: the decision is never lost to its storage.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import asyncio
25
+ import dataclasses
26
+ import os
27
+ import queue
28
+ import threading
29
+ import time
30
+ import weakref
31
+ from collections import OrderedDict
32
+ from collections.abc import Callable, Iterable, Mapping
33
+ from dataclasses import dataclass, field
34
+ from typing import Any
35
+
36
+ from .._engine.engine import Engine, LoadedDocument
37
+ from .._engine.rules import DEFAULT_HOLD_TIMEOUT_MS, CompiledRule
38
+ from . import messages
39
+ from .bundle import is_bundle, prepare_bundle
40
+ from .events import DecisionEvent
41
+ from .normalise import normalise_result, to_json
42
+ from .records import REEXECUTE_STATUSES, CallRecord, Decision, Outcome, RunContext, most_severe
43
+ from .store import (
44
+ DEFAULT_MAX_RECORDS,
45
+ DEFAULT_MAX_RESULT_BYTES,
46
+ DEFAULT_RUN_IDLE_MS,
47
+ DEFAULT_SESSION_IDLE_MS,
48
+ HistoryStore,
49
+ )
50
+
51
+ UNKNOWN_TOOL_RULE = "amiril.unknown-tool"
52
+ KERNEL_MODES = ("off", "shadow", "enforce")
53
+ HOLD_OUTCOMES = ("approved", "denied", "expired", "unreachable")
54
+ _DEFAULT_OUTCOME = {"allow": "approved", "block": "denied", "timeout": "unreachable"}
55
+ SWEEP_INTERVAL_MS = 1000 # kernel.md 6.1: the sweep of all units runs at most once per second of kernel clock
56
+ DURABLE_SWEEP_INTERVAL_MS = 60000 # kernel.md 4.1a: the durable store's retention sweep, at most once a minute
57
+
58
+ Sink = Callable[[DecisionEvent], None]
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class LoadedState:
63
+ """The live document and the bundle metadata it came with, assigned as one
64
+ object so a call is decided entirely against one of them (kernel.md 15)."""
65
+
66
+ loaded: LoadedDocument
67
+ bundle_version: str | None = None
68
+ bundle_warnings: tuple[dict, ...] = ()
69
+ skipped_environment: int = 0
70
+
71
+
72
+ class _Wait:
73
+ __slots__ = ("event",)
74
+
75
+ def __init__(self, event: threading.Event) -> None:
76
+ self.event = event
77
+
78
+
79
+ @dataclass
80
+ class _Progress:
81
+ """How far one `before_call` got; the fault and cancellation paths read it."""
82
+
83
+ ctx: RunContext
84
+ call_id: str
85
+ tool_name: str
86
+ args: Any
87
+ batch_id: str
88
+ tool_id: str | None
89
+ parent_call_id: str | None
90
+ meta: dict | None
91
+ minted: bool
92
+ state: LoadedState
93
+ attempt: int = 1
94
+ registered: bool = False
95
+ rec: CallRecord | None = None
96
+ evaluated: bool = False
97
+ decisions: list[Decision] = field(default_factory=list)
98
+ aggregate: str = "allow"
99
+ refused: Decision | None = None
100
+ hold_fault: str | None = None
101
+ holding: Decision | None = None
102
+ resolutions: list[dict] = field(default_factory=list)
103
+ resolution_by_rule: dict[str, dict] = field(default_factory=dict)
104
+ lines_written: bool = False
105
+
106
+
107
+ class _HoldWorker:
108
+ """One daemon thread that runs synchronous resolver calls for the kernel's
109
+ own timer (kernel.md 7): the caller waits with a timeout, and a resolver
110
+ that outlives it keeps only this one thread busy, so nothing leaks."""
111
+
112
+ def __init__(self) -> None:
113
+ self._queue: queue.Queue = queue.Queue()
114
+ self._lock = threading.Lock()
115
+ self._thread: threading.Thread | None = None
116
+
117
+ def _run(self) -> None:
118
+ while True:
119
+ fn, box, done = self._queue.get()
120
+ try:
121
+ box["value"] = fn()
122
+ except BaseException as exc: # noqa: BLE001 - handed to the waiting caller
123
+ box["error"] = exc
124
+ done.set()
125
+
126
+ def call(self, fn: Callable[[], Any], timeout_s: float) -> Any:
127
+ """Run `fn` on the worker and wait at most `timeout_s`; `_TIMEOUT` when it did not finish."""
128
+ with self._lock:
129
+ if self._thread is None or not self._thread.is_alive():
130
+ self._thread = threading.Thread(target=self._run, name="amiril-hold", daemon=True)
131
+ self._thread.start()
132
+ box: dict[str, Any] = {}
133
+ done = threading.Event()
134
+ self._queue.put((fn, box, done))
135
+ if not done.wait(timeout_s):
136
+ return _TIMEOUT
137
+ if "error" in box:
138
+ raise box["error"]
139
+ return box["value"]
140
+
141
+
142
+ _TIMEOUT = object()
143
+
144
+
145
+ class Guard:
146
+ """The kernel. One per process serves every adapter in it.
147
+
148
+ Arguments: `mode` is the kernel mode (`enforce`, `shadow`, `off`);
149
+ `document` a rule document or bundle body to load; `predicates` the host
150
+ functions documents may name; `resolver` what holds wait on (kernel.md 7;
151
+ none means holds fail closed); `tools` the tool registry for the
152
+ unknown-tool check (6.3; None disables it); `sink` receives every
153
+ `DecisionEvent`; `environment` is the installation's environment for
154
+ bundle `applies_to.environments`; the `history_*` limits are kernel.md 4.3;
155
+ `clock` is injectable for tests."""
156
+
157
+ def __init__(
158
+ self,
159
+ *,
160
+ mode: str = "enforce",
161
+ document: dict | None = None,
162
+ predicates: Mapping[str, Callable[..., Any]] | None = None,
163
+ resolver: Any = None,
164
+ tools: Iterable[str] | None = None,
165
+ unknown_tool_action: str = "flag",
166
+ sink: Sink | Any = None,
167
+ environment: str | None = None,
168
+ history_max_records: int = DEFAULT_MAX_RECORDS,
169
+ history_run_idle_ms: int = DEFAULT_RUN_IDLE_MS,
170
+ history_session_idle_ms: int = DEFAULT_SESSION_IDLE_MS,
171
+ history_max_result_bytes: int = DEFAULT_MAX_RESULT_BYTES,
172
+ idle_sweep_interval_ms: int = SWEEP_INTERVAL_MS,
173
+ clock: Callable[[], float] = time.time,
174
+ durable: Any = None,
175
+ ) -> None:
176
+ if mode not in KERNEL_MODES:
177
+ raise ValueError(f"kernel mode must be one of {KERNEL_MODES}, got {mode!r}")
178
+ self.mode = mode
179
+ self.clock = clock
180
+ self.engine = Engine(predicates)
181
+ self._state = LoadedState(self.engine.loaded)
182
+ self._swap_lock = threading.Lock()
183
+ self.resolver = resolver
184
+ self.tools: frozenset[str] | None = frozenset(tools) if tools is not None else None
185
+ if unknown_tool_action not in ("allow", "flag", "hold", "block"):
186
+ raise ValueError(f"unknown_tool_action must be an action, got {unknown_tool_action!r}")
187
+ self.unknown_tool_action = unknown_tool_action
188
+ self.environment = environment
189
+ self._sink: Sink | None = _as_sink(sink)
190
+ self.store = HistoryStore(max_records=history_max_records, run_idle_ms=history_run_idle_ms,
191
+ session_idle_ms=history_session_idle_ms, clock=clock,
192
+ durable=durable, on_durable_error=self._durable_fault, # (exc, record or None)
193
+ max_result_bytes=history_max_result_bytes)
194
+ self.durable = durable
195
+ self._last_durable_sweep = float("-inf")
196
+ if durable is not None:
197
+ self._last_durable_sweep = clock()
198
+ self.store.durable_sweep(self._last_durable_sweep) # 4.1a: the file's retention, on open
199
+ # 4.1a Integrity: units whose load failed, as ("run", root) or ("session", agent, session).
200
+ # Retried on every call; nothing of theirs is appended or written through until a load succeeds.
201
+ self._untrusted: OrderedDict[tuple, None] = OrderedDict()
202
+ self.idle_sweep_interval_ms = idle_sweep_interval_ms
203
+ self._last_sweep = float("-inf") # the first before_call sweeps (kernel.md 6.1)
204
+ self._hold_worker = _HoldWorker()
205
+ self._lock = threading.RLock()
206
+ # Keyed by (root run id, call id): call identity is scoped to the root run (kernel.md 5).
207
+ self._outcomes: dict[tuple, Outcome] = {}
208
+ self._inflight: dict[tuple, threading.Event] = {}
209
+ self._counts: dict[tuple[str, str], dict[str, int]] = {}
210
+ _GUARDS.add(self)
211
+ _install_fork_hook()
212
+ if document is not None:
213
+ self.swap(document)
214
+
215
+ def _reset_after_fork(self) -> None:
216
+ """Make this kernel usable in a forked child. A lock a parent thread held
217
+ at fork() would never be released here (the thread does not exist), so
218
+ every lock is new; the hold worker is new too, with an empty queue, so a
219
+ hold the parent was resolving is not run in the child; in-flight calls
220
+ belong to the parent. The durable store reopens its file, or is disabled
221
+ with a fault line when it cannot: SQLite forbids using a connection
222
+ across fork()."""
223
+ self._lock = threading.RLock()
224
+ self._swap_lock = threading.Lock()
225
+ self._inflight = {}
226
+ self._hold_worker = _HoldWorker()
227
+ self.store.reset_after_fork()
228
+ durable = self.store.durable
229
+ if durable is None:
230
+ return
231
+ try:
232
+ after_fork = getattr(durable, "after_fork", None)
233
+ if after_fork is None:
234
+ raise RuntimeError("the durable store cannot be carried across fork()")
235
+ after_fork()
236
+ except Exception as exc: # noqa: BLE001 - the child runs on memory alone, and says so
237
+ self.durable = None
238
+ self.store.durable = None
239
+ self._durable_fault(RuntimeError(f"disabled in the forked child: {_err(exc)}"))
240
+
241
+ # ------------------------------------------------------------ exposed state (kernel.md 14)
242
+
243
+ @property
244
+ def state(self) -> LoadedState:
245
+ return self._state
246
+
247
+ @property
248
+ def loaded(self) -> LoadedDocument:
249
+ return self._state.loaded
250
+
251
+ @property
252
+ def ruleset_version(self) -> str:
253
+ return self._state.loaded.ruleset_version
254
+
255
+ @property
256
+ def document(self) -> dict:
257
+ return self._state.loaded.doc
258
+
259
+ @property
260
+ def bundle_version(self) -> str | None:
261
+ return self._state.bundle_version
262
+
263
+ @property
264
+ def bundle_warnings(self) -> list[dict]:
265
+ return list(self._state.bundle_warnings)
266
+
267
+ @property
268
+ def skipped_environment(self) -> int:
269
+ return self._state.skipped_environment
270
+
271
+ def history_report(self) -> dict[str, int]:
272
+ return self.store.history_report()
273
+
274
+ def drain_counts(self) -> list[dict]:
275
+ """Per-rule outcome counts since the last drain, in the heartbeat's shape
276
+ (protocol.md 6.1 `counts[]`), and reset the window."""
277
+ with self._lock:
278
+ out = [{"rule_id": rid, "rule_version": ver, **c} for (rid, ver), c in self._counts.items()]
279
+ self._counts.clear()
280
+ return out
281
+
282
+ def tool_id_for(self, tool_name: str, declared: str | None = None, state: LoadedState | None = None) -> str:
283
+ """kernel.md 2.1: the declared id, else the alias map, else the raw name."""
284
+ if declared:
285
+ return declared
286
+ loaded = (state or self._state).loaded
287
+ return loaded.tool_aliases.get(tool_name, tool_name)
288
+
289
+ # ------------------------------------------------------------ lifecycle
290
+
291
+ def swap(self, document_or_bundle: dict) -> None:
292
+ """kernel.md 8.4: load atomically; a refused document raises and leaves the old one live."""
293
+ with self._swap_lock:
294
+ if is_bundle(document_or_bundle):
295
+ prepared = prepare_bundle(document_or_bundle, self.environment, set(self.engine.predicates))
296
+ loaded = self.engine.load(prepared.document, prepared.stand_ins)
297
+ self._state = LoadedState(loaded, prepared.bundle_version, tuple(prepared.warnings),
298
+ prepared.skipped_environment)
299
+ else:
300
+ self._state = LoadedState(self.engine.load(document_or_bundle))
301
+
302
+ def start_run(self, ctx: RunContext) -> None:
303
+ """kernel.md 8.1. Optional: a run exists from its first record, so this
304
+ keeps nothing (bookkeeping is bounded with the records, 4.3)."""
305
+ return None
306
+
307
+ def end_session(self, agent_id: str, session_id: str) -> None:
308
+ """kernel.md 8.3."""
309
+ self._forget(self.store.end_session(agent_id, session_id))
310
+
311
+ def record_fault(self, ctx: RunContext, error: BaseException | str, *, call_id: str | None = None,
312
+ tool_name: str | None = None, phase: str = "pre") -> None:
313
+ """kernel.md 10: an adapter fault outside the kernel, written as a fault line."""
314
+ rec = None
315
+ if tool_name is not None:
316
+ rec = CallRecord(call_id=call_id or "", run_id=ctx.run_id, root_run_id=ctx.root_run_id or ctx.run_id,
317
+ session_id=ctx.session_id, agent_id=ctx.agent_id, tool_id=tool_name,
318
+ tool_name_raw=tool_name, args={}, correlation={}, status="pending",
319
+ parent_call_id=ctx.parent_call_id)
320
+ if self.mode == "off":
321
+ return
322
+ state = self._state
323
+ self._emit(DecisionEvent("fault", phase, ctx, call_id, "allow", self.mode, self.clock(), record=rec,
324
+ fault_error=_err(error), fault_action="allow", fault_kind="adapter",
325
+ bundle_version=state.bundle_version))
326
+
327
+ # ------------------------------------------------------------ before_call
328
+
329
+ def before_call(self, ctx: RunContext, call_id: str, tool_name: str, args: Any, batch_id: str, *,
330
+ tool_id: str | None = None, parent_call_id: str | None = None,
331
+ correlation: Mapping[str, Any] | None = None, meta: dict | None = None,
332
+ call_id_minted: bool = False) -> Outcome:
333
+ """kernel.md 6.1. `call_id_minted` says the id is the kernel's minted
334
+ one, not the framework's tool call id (kernel.md 3.1)."""
335
+ prog = _Progress(ctx, call_id, tool_name, args, batch_id, tool_id, parent_call_id, meta, call_id_minted,
336
+ self._state)
337
+ try:
338
+ try:
339
+ step = self._begin(prog, correlation)
340
+ if isinstance(step, Outcome):
341
+ return step
342
+ if isinstance(step, _Wait):
343
+ step.event.wait()
344
+ return self._replay(prog)
345
+ if prog.aggregate == "hold":
346
+ self._hold(prog)
347
+ return self._finish(prog)
348
+ except Exception as exc: # noqa: BLE001 - kernel.md 10: never raise into the framework
349
+ return self._fault(prog, exc)
350
+ except BaseException:
351
+ self._interrupted(prog)
352
+ raise
353
+ finally:
354
+ self._release_inflight(prog)
355
+
356
+ async def abefore_call(self, ctx: RunContext, call_id: str, tool_name: str, args: Any, batch_id: str, *,
357
+ tool_id: str | None = None, parent_call_id: str | None = None,
358
+ correlation: Mapping[str, Any] | None = None, meta: dict | None = None,
359
+ call_id_minted: bool = False) -> Outcome:
360
+ """`before_call` for asynchronous runtimes: holds await the resolver."""
361
+ prog = _Progress(ctx, call_id, tool_name, args, batch_id, tool_id, parent_call_id, meta, call_id_minted,
362
+ self._state)
363
+ try:
364
+ try:
365
+ step = self._begin(prog, correlation)
366
+ if isinstance(step, Outcome):
367
+ return step
368
+ if isinstance(step, _Wait):
369
+ await asyncio.to_thread(step.event.wait)
370
+ return self._replay(prog)
371
+ if prog.aggregate == "hold":
372
+ await self._ahold(prog)
373
+ return self._finish(prog)
374
+ except Exception as exc: # noqa: BLE001
375
+ return self._fault(prog, exc)
376
+ except BaseException:
377
+ self._interrupted(prog)
378
+ raise
379
+ finally:
380
+ self._release_inflight(prog)
381
+
382
+ def _begin(self, prog: _Progress, correlation: Mapping[str, Any] | None) -> Outcome | _Wait | None:
383
+ ctx, call_id = prog.ctx, prog.call_id
384
+ if self.durable is not None:
385
+ try:
386
+ self._restore(ctx, call_id) # kernel.md 4.1a: load on resume, before the idle check and step 1
387
+ except _UntrustedHistory as exc:
388
+ return self._untrusted_call(prog, exc)
389
+ self._maybe_sweep()
390
+ # kernel.md 6.1, idle check timing: the call's own run and session first.
391
+ self._forget(self.store.evict_idle_units(ctx.root_run_id, ctx.agent_id, ctx.session_id, self.clock()))
392
+ # Step 1: re-execution, retry, or in flight (kernel.md 5).
393
+ key = _key(prog)
394
+ with self._lock:
395
+ inflight = self._inflight.get(key)
396
+ if inflight is not None:
397
+ return _Wait(inflight)
398
+ existing = self.store.latest(call_id, ctx.root_run_id)
399
+ if existing is not None and existing.status in REEXECUTE_STATUSES:
400
+ stored = self._outcomes.get(key)
401
+ if stored is not None:
402
+ return stored
403
+ return Outcome("allow", [], "", existing)
404
+ prog.attempt = self.store.next_attempt(call_id, ctx.root_run_id)
405
+ self._inflight[key] = threading.Event()
406
+ prog.registered = True
407
+
408
+ # Step 2: identity.
409
+ loaded = prog.state.loaded
410
+ tool_id = self.tool_id_for(prog.tool_name, prog.tool_id, prog.state)
411
+ norm_meta: dict = {}
412
+ plain_args = to_json(dict(prog.args or {}), norm_meta)
413
+ corr = self._correlation(loaded, plain_args, correlation)
414
+ unknown = self.tools is not None and tool_id not in self.tools
415
+
416
+ # Step 3: record, append, snapshot, evaluate.
417
+ rec = self._new_record(prog, tool_id, plain_args, corr)
418
+ if norm_meta.get("normalise_fallback"):
419
+ rec.meta["normalise_fallback"] = True
420
+ if unknown:
421
+ rec.meta["unknown_tool"] = True
422
+ self._append(rec)
423
+ prog.rec = rec
424
+ if self.mode == "off":
425
+ prog.evaluated = True
426
+ return None
427
+ history = self.store.snapshot(rec)
428
+ decisions = loaded.evaluate(rec, history, self._context(ctx), "pre", self.store.run_floor(rec.root_run_id))
429
+ if unknown:
430
+ decisions.append(self._unknown_decision(rec, loaded))
431
+ prog.evaluated = True
432
+
433
+ # Step 4: modes and aggregate (kernel.md 9).
434
+ prog.decisions = self._cap(decisions)
435
+ prog.aggregate = self._aggregate(prog.decisions)
436
+ return None
437
+
438
+ # ------------------------------------------------------------ holds (kernel.md 7)
439
+
440
+ def _hold_decisions(self, prog: _Progress) -> list[Decision]:
441
+ return [d for d in prog.decisions if d.mode == "enforce" and d.action == "hold"]
442
+
443
+ def _start_hold(self, prog: _Progress) -> list[Decision] | None:
444
+ self._publish(prog, status="held")
445
+ if self.resolver is None:
446
+ prog.hold_fault = "no resolver is configured; the hold cannot be approved"
447
+ prog.refused = self._hold_decisions(prog)[0]
448
+ return None
449
+ return self._hold_decisions(prog)
450
+
451
+ def _hold(self, prog: _Progress) -> None:
452
+ holds = self._start_hold(prog)
453
+ if holds is not None:
454
+ for d in holds:
455
+ prog.holding = d
456
+ answer = self._resolve_sync(d, prog.rec, self._hold_timeout(prog, d))
457
+ prog.holding = None
458
+ if self._apply_answer(prog, d, answer):
459
+ break
460
+ self._settle_hold(prog)
461
+
462
+ async def _ahold(self, prog: _Progress) -> None:
463
+ holds = self._start_hold(prog)
464
+ if holds is not None:
465
+ for d in holds:
466
+ prog.holding = d
467
+ answer = await self._resolve_async(d, prog.rec, self._hold_timeout(prog, d))
468
+ prog.holding = None
469
+ if self._apply_answer(prog, d, answer):
470
+ break
471
+ self._settle_hold(prog)
472
+
473
+ def _hold_timeout(self, prog: _Progress, d: Decision) -> int:
474
+ rule = prog.state.loaded.rules_by_id.get(d.rule_id)
475
+ return rule.hold_timeout_ms if rule is not None else DEFAULT_HOLD_TIMEOUT_MS
476
+
477
+ def _resolve_sync(self, d: Decision, rec: CallRecord, timeout_ms: int) -> dict:
478
+ """Ask the resolver; a resolver that fails, answers garbage or outlives
479
+ the kernel's timer is `timeout`. Control-flow exceptions propagate."""
480
+ resolver = self.resolver
481
+ resolve = getattr(resolver, "resolve", None)
482
+ if resolve is None:
483
+ aresolve = getattr(resolver, "aresolve", None)
484
+ if aresolve is None:
485
+ return _timeout_answer()
486
+
487
+ def resolve(d: Decision, rec: CallRecord, t: int) -> Any: # noqa: F811 - the sync shape of an async resolver
488
+ return asyncio.run(aresolve(d, rec, t))
489
+
490
+ try:
491
+ if getattr(resolver, "owns_deadline", False):
492
+ return _answer(resolve(d, rec, timeout_ms))
493
+ result = self._hold_worker.call(lambda: resolve(d, rec, timeout_ms), timeout_ms / 1000.0)
494
+ if result is _TIMEOUT:
495
+ return _timeout_answer()
496
+ return _answer(result)
497
+ except Exception: # noqa: BLE001 - a resolver that throws is a timeout (kernel.md 7)
498
+ return _timeout_answer()
499
+
500
+ async def _resolve_async(self, d: Decision, rec: CallRecord, timeout_ms: int) -> dict:
501
+ resolver = self.resolver
502
+ try:
503
+ aresolve = getattr(resolver, "aresolve", None)
504
+ if aresolve is not None:
505
+ coro = aresolve(d, rec, timeout_ms)
506
+ elif getattr(resolver, "resolve", None) is not None:
507
+ coro = asyncio.to_thread(resolver.resolve, d, rec, timeout_ms)
508
+ else:
509
+ return _timeout_answer()
510
+ if getattr(resolver, "owns_deadline", False):
511
+ return _answer(await coro)
512
+ try:
513
+ return _answer(await asyncio.wait_for(coro, timeout_ms / 1000.0))
514
+ except asyncio.TimeoutError:
515
+ return _timeout_answer()
516
+ except Exception: # noqa: BLE001
517
+ return _timeout_answer()
518
+
519
+ def _apply_answer(self, prog: _Progress, d: Decision, answer: dict) -> bool:
520
+ entry = {"rule_id": d.rule_id, **answer}
521
+ prog.resolutions.append(entry)
522
+ prog.resolution_by_rule[d.rule_id] = entry
523
+ if answer["answer"] == "block":
524
+ prog.refused = d
525
+ return True
526
+ if answer["answer"] == "timeout":
527
+ prog.refused = d
528
+ prog.hold_fault = f"hold by rule {d.rule_id} got no answer: the resolver timed out or failed"
529
+ return True
530
+ return False
531
+
532
+ def _settle_hold(self, prog: _Progress) -> None:
533
+ meta = dict(prog.rec.meta)
534
+ meta["resolutions"] = list(prog.resolutions)
535
+ if prog.hold_fault is not None:
536
+ meta["fault"] = prog.hold_fault
537
+ status = "blocked" if prog.refused is not None else "pending"
538
+ self._publish(prog, status=status, meta=meta)
539
+
540
+ # ------------------------------------------------------------ finish, fault, interruption
541
+
542
+ def _message(self, prog: _Progress) -> str:
543
+ rec = prog.rec
544
+ if prog.aggregate == "block":
545
+ blocker = next(d for d in prog.decisions if d.mode == "enforce" and d.action == "block")
546
+ return messages.blocked(rec.tool_id, blocker.rule_id, blocker.sentence)
547
+ if prog.hold_fault is not None:
548
+ return messages.held_no_approval(rec.tool_id, prog.refused.rule_id, prog.refused.sentence)
549
+ if prog.refused is not None:
550
+ return messages.held_and_refused(rec.tool_id, prog.refused.rule_id, prog.refused.sentence)
551
+ return ""
552
+
553
+ def _write_pre(self, prog: _Progress, fault: tuple[str, str, str] | None) -> None:
554
+ """The pre phase's lines: decisions, a fault line when given (hold or
555
+ kernel fault, after the decisions), then the summary (decision-line.md 1).
556
+ Written once per attempt, whatever interrupts the writing."""
557
+ if prog.lines_written:
558
+ return
559
+ prog.lines_written = True
560
+ rec = prog.rec
561
+ state = prog.state
562
+ ts = self.clock()
563
+ for d in prog.decisions:
564
+ self._count(d)
565
+ self._emit(DecisionEvent("decision", "pre", prog.ctx, rec.call_id, prog.aggregate, self.mode, ts,
566
+ record=rec, decision=d, resolution=prog.resolution_by_rule.get(d.rule_id),
567
+ bundle_version=state.bundle_version))
568
+ if fault is not None:
569
+ # kernel.md 13: a failed hold's fault line carries the resulting action as its aggregate.
570
+ error, action, kind = fault
571
+ aggregate = action if kind == "hold" else prog.aggregate
572
+ self._emit(DecisionEvent("fault", "pre", prog.ctx, rec.call_id, aggregate, self.mode, ts, record=rec,
573
+ fault_error=error, fault_action=action, fault_kind=kind,
574
+ bundle_version=state.bundle_version))
575
+ self._emit(DecisionEvent("summary", "pre", prog.ctx, rec.call_id, prog.aggregate, self.mode, ts, record=rec,
576
+ resolutions=list(prog.resolutions), bundle_version=state.bundle_version))
577
+
578
+ def _finish(self, prog: _Progress) -> Outcome:
579
+ if prog.aggregate == "block":
580
+ self._publish(prog, status="blocked")
581
+ message = self._message(prog)
582
+ rec = prog.rec
583
+ self._observe(rec)
584
+ if self.mode != "off":
585
+ fault = (prog.hold_fault, "block", "hold") if prog.hold_fault is not None else None
586
+ self._write_pre(prog, fault)
587
+ outcome = Outcome(prog.aggregate, list(prog.decisions), message, rec)
588
+ self._remember(prog, outcome)
589
+ return outcome
590
+
591
+ def _fault(self, prog: _Progress, exc: BaseException) -> Outcome:
592
+ """kernel.md 10: record the call, write the fault line, never raise. With
593
+ no decision yet the call fails open, or closed under a fail-closed
594
+ rule; a decision that exists is kept."""
595
+ error = _err(exc)
596
+ try:
597
+ rec = prog.rec
598
+ if rec is None:
599
+ args, dropped = _safe_args(prog.args)
600
+ rec = self._new_record(prog, self.tool_id_for(prog.tool_name, prog.tool_id, prog.state), args, {})
601
+ if dropped:
602
+ rec.meta["fault_dropped_keys"] = dropped
603
+ try:
604
+ self._append(rec)
605
+ except Exception: # noqa: BLE001 - the store itself may be what failed
606
+ pass
607
+ prog.rec = rec
608
+ if prog.evaluated:
609
+ # The decision stands: a fault never turns a block into an allow.
610
+ if prog.holding is not None and prog.refused is None:
611
+ self._apply_answer(prog, prog.holding, _timeout_answer())
612
+ prog.hold_fault = f"hold by rule {prog.holding.rule_id} got no answer: {error}"
613
+ prog.holding = None
614
+ blocked = prog.aggregate == "block" or prog.refused is not None
615
+ action = prog.aggregate
616
+ status = "blocked" if blocked else "pending"
617
+ message = self._message(prog) if blocked else ""
618
+ self._settle_record(prog, status, error)
619
+ if self.mode != "off":
620
+ self._write_pre(prog, (error, "block" if blocked else "allow", "kernel"))
621
+ outcome = Outcome(action, list(prog.decisions), message, prog.rec)
622
+ else:
623
+ closing = self._fail_closed_rule(prog, rec)
624
+ action, status, message = "allow", "pending", ""
625
+ if closing is not None:
626
+ action, status = "block", "blocked"
627
+ message = messages.could_not_be_checked(rec.tool_id, closing.id)
628
+ self._settle_record(prog, status, error)
629
+ if self.mode != "off":
630
+ self._emit(DecisionEvent("fault", "pre", prog.ctx, prog.call_id, action, self.mode, self.clock(),
631
+ record=prog.rec, fault_error=error, fault_action=action,
632
+ fault_kind="kernel", bundle_version=prog.state.bundle_version))
633
+ outcome = Outcome(action, [], message, prog.rec)
634
+ self._remember(prog, outcome)
635
+ return outcome
636
+ except Exception: # noqa: BLE001 - the fault path itself must not raise
637
+ ctx = prog.ctx
638
+ bare = prog.rec or CallRecord(
639
+ call_id=prog.call_id, run_id=getattr(ctx, "run_id", ""), root_run_id=getattr(ctx, "root_run_id", ""),
640
+ session_id=getattr(ctx, "session_id", None), agent_id=getattr(ctx, "agent_id", ""),
641
+ tool_id=prog.tool_name, tool_name_raw=prog.tool_name, args={}, correlation={},
642
+ batch_id=prog.batch_id, parent_call_id=getattr(ctx, "parent_call_id", None), attempt=prog.attempt)
643
+ outcome = Outcome("allow", [], "", bare)
644
+ self._remember(prog, outcome)
645
+ return outcome
646
+
647
+ def _settle_record(self, prog: _Progress, status: str, error: str) -> None:
648
+ meta = dict(prog.rec.meta)
649
+ meta["fault"] = error
650
+ if prog.resolutions:
651
+ meta["resolutions"] = list(prog.resolutions)
652
+ try:
653
+ self._publish(prog, status=status, meta=meta)
654
+ except Exception: # noqa: BLE001
655
+ pass
656
+
657
+ def _interrupted(self, prog: _Progress) -> None:
658
+ """kernel.md 10: cancellation is not a fault. A call cancelled while it
659
+ waits on a hold is settled blocked with resolution `timeout` and its
660
+ outcome remembered; a call decided but not finished keeps its decision;
661
+ a call interrupted before any decision is forgotten, so a re-fire of its
662
+ id is evaluated afresh. The host's exception then propagates unchanged."""
663
+ try:
664
+ if prog.rec is None:
665
+ return
666
+ if not prog.evaluated or (not prog.decisions and self.mode != "off"):
667
+ self.store.discard(prog.rec)
668
+ return
669
+ if prog.holding is not None and prog.refused is None:
670
+ self._apply_answer(prog, prog.holding, _timeout_answer())
671
+ prog.hold_fault = f"hold by rule {prog.holding.rule_id} got no answer: the call was cancelled"
672
+ prog.holding = None
673
+ blocked = prog.refused is not None or prog.aggregate == "block"
674
+ meta = dict(prog.rec.meta)
675
+ if prog.resolutions:
676
+ meta["resolutions"] = list(prog.resolutions)
677
+ if prog.hold_fault is not None:
678
+ meta["fault"] = prog.hold_fault
679
+ self._publish(prog, status="blocked" if blocked else "pending", meta=meta)
680
+ outcome = Outcome(prog.aggregate, list(prog.decisions), self._message(prog) if blocked else "", prog.rec)
681
+ self._remember(prog, outcome)
682
+ if self.mode != "off":
683
+ self._write_pre(prog, (prog.hold_fault, "block", "hold") if prog.hold_fault else None)
684
+ except BaseException: # noqa: BLE001 - never mask the host's exception with one of our own
685
+ pass
686
+
687
+ def _fail_closed_rule(self, prog: _Progress, rec: CallRecord) -> CompiledRule | None:
688
+ """kernel.md 10: the first enforce, fail-closed rule targeting the call in phase pre."""
689
+ if self.mode != "enforce":
690
+ return None
691
+ for rule in prog.state.loaded.targeting("pre", rec.agent_id, rec.tool_id):
692
+ if rule.mode == "enforce" and rule.fail_mode == "closed":
693
+ return rule
694
+ return None
695
+
696
+ # ------------------------------------------------------------ after_call (kernel.md 6.2)
697
+
698
+ def after_call(self, ctx: RunContext, call_id: str, raw_result: Any = None, error: Any = None) -> list[Decision]:
699
+ rec: CallRecord | None = None
700
+ state = self._state
701
+ try:
702
+ stored = self.store.latest_surviving(call_id, getattr(ctx, "root_run_id", None))
703
+ if stored is None:
704
+ raise LookupError(f"after_call for unknown call {call_id!r}")
705
+ if stored.status in ("blocked", "ok", "error"):
706
+ return []
707
+ rec = stored
708
+ changes: dict[str, Any] = {"ended_at": self.clock()}
709
+ if error is not None:
710
+ changes["status"] = "error"
711
+ changes["error"] = _err(error) if isinstance(error, BaseException) else str(error)
712
+ else:
713
+ changes["status"] = "ok"
714
+ result, fallback = normalise_result(raw_result)
715
+ changes["result"] = result
716
+ if fallback:
717
+ meta = dict(rec.meta)
718
+ meta["normalise_fallback"] = True
719
+ changes["meta"] = meta
720
+ done = dataclasses.replace(stored, **changes)
721
+ # 4.3 max_result_bytes: history keeps a marker for a large result; this post phase sees it whole.
722
+ if not self.store.complete(stored, self.store.capped(done)):
723
+ return [] # a concurrent duplicate completed it first (kernel.md 15)
724
+ rec = done
725
+ if self.mode == "off":
726
+ return []
727
+ loaded = state.loaded
728
+ history = self.store.snapshot(rec, fresh=True) # 4.2: post sees current state
729
+ raw = loaded.evaluate(rec, history, self._context(ctx), "post", self.store.run_floor(rec.root_run_id))
730
+ decisions = [_cap_to_flag(d) for d in self._cap(raw)]
731
+ aggregate = self._aggregate(decisions)
732
+ self._observe(rec)
733
+ ts = self.clock()
734
+ for d in decisions:
735
+ self._count(d)
736
+ self._emit(DecisionEvent("decision", "post", ctx, call_id, aggregate, self.mode, ts, record=rec,
737
+ decision=d, bundle_version=state.bundle_version))
738
+ self._emit(DecisionEvent("summary", "post", ctx, call_id, aggregate, self.mode, ts, record=rec,
739
+ bundle_version=state.bundle_version))
740
+ return decisions
741
+ except Exception as exc: # noqa: BLE001 - kernel.md 10
742
+ text = _err(exc)
743
+ if rec is not None and rec.status in ("pending", "held"):
744
+ try:
745
+ meta = dict(rec.meta)
746
+ meta["fault"] = text
747
+ done = dataclasses.replace(rec, status="ok", result=None, ended_at=self.clock(), meta=meta)
748
+ if self.store.complete(rec, done):
749
+ rec = done
750
+ except Exception: # noqa: BLE001
751
+ pass
752
+ if self.mode != "off":
753
+ self._emit(DecisionEvent("fault", "post", ctx, call_id, "allow", self.mode, self.clock(), record=rec,
754
+ fault_error=text, fault_action="allow", fault_kind="kernel",
755
+ bundle_version=state.bundle_version))
756
+ return []
757
+
758
+ # ------------------------------------------------------------ end_run (kernel.md 8.2)
759
+
760
+ def end_run(self, ctx: RunContext) -> list[Decision]:
761
+ if ctx is None:
762
+ return [] # an adapter bug; there is no run to end
763
+ if ctx.nested:
764
+ return []
765
+ root = ctx.root_run_id
766
+ call_id = f"run_end:{root}"
767
+ decisions: list[Decision] = []
768
+ state = self._state
769
+ try:
770
+ if self.mode != "off":
771
+ loaded = state.loaded
772
+ rec = CallRecord(call_id=call_id, run_id=ctx.run_id, root_run_id=root, session_id=ctx.session_id,
773
+ agent_id=ctx.agent_id, tool_id="", tool_name_raw="", args={}, correlation={},
774
+ status="pending", seq=self.store.last_seq(root) + 1, batch_id=call_id,
775
+ started_at=self.clock())
776
+ history = self.store.run_end_history(root, ctx.agent_id, ctx.session_id)
777
+ decisions = self._cap(loaded.evaluate(rec, history, self._context(ctx), "run_end",
778
+ self.store.run_floor(root)))
779
+ aggregate = self._aggregate(decisions)
780
+ ts = self.clock()
781
+ for d in decisions:
782
+ self._count(d)
783
+ self._emit(DecisionEvent("decision", "run_end", ctx, call_id, aggregate, self.mode, ts,
784
+ decision=d, bundle_version=state.bundle_version))
785
+ self._emit(DecisionEvent("summary", "run_end", ctx, call_id, aggregate, self.mode, ts,
786
+ bundle_version=state.bundle_version))
787
+ except Exception as exc: # noqa: BLE001 - kernel.md 10: logged, and the run is still evicted
788
+ self._emit(DecisionEvent("fault", "run_end", ctx, call_id, "allow", self.mode, self.clock(),
789
+ fault_error=_err(exc), fault_action="allow", fault_kind="kernel",
790
+ bundle_version=state.bundle_version))
791
+ decisions = []
792
+ finally:
793
+ # 4.1a Integrity: an untrusted root's rows are never written, the file's end_run included.
794
+ self._forget(self.store.end_run(root, mirror=("run", root) not in self._untrusted))
795
+ return decisions
796
+
797
+ # ------------------------------------------------------------ helpers
798
+
799
+ def _context(self, ctx: RunContext) -> dict:
800
+ return {
801
+ "agent_id": ctx.agent_id,
802
+ "agent_version": ctx.agent_version,
803
+ "env": ctx.env,
804
+ "now": ctx.now if ctx.now is not None else self.clock(),
805
+ "run_id": ctx.run_id,
806
+ "session_id": ctx.session_id,
807
+ }
808
+
809
+ def _new_record(self, p: _Progress, tool_id: str, args: dict, corr: dict) -> CallRecord:
810
+ ctx = p.ctx
811
+ return CallRecord(
812
+ call_id=p.call_id, run_id=ctx.run_id, root_run_id=ctx.root_run_id, session_id=ctx.session_id,
813
+ agent_id=ctx.agent_id, tool_id=tool_id, tool_name_raw=p.tool_name, args=args, correlation=corr,
814
+ status="pending", batch_id=p.batch_id,
815
+ parent_call_id=p.parent_call_id if p.parent_call_id is not None else ctx.parent_call_id,
816
+ attempt=p.attempt, started_at=self.clock(), meta=dict(p.meta or {}), tool_declared_id=p.tool_id or None,
817
+ call_id_minted=p.minted, root_agent_id=getattr(ctx, "root_agent_id", None),
818
+ )
819
+
820
+ def _append(self, rec: CallRecord) -> None:
821
+ self._forget(self.store.append(rec))
822
+
823
+ def _publish(self, prog: _Progress, **changes: Any) -> None:
824
+ """Replace the stored record. A record evicted while its call was in
825
+ flight is carried on in the call's own state only."""
826
+ rec = dataclasses.replace(prog.rec, **changes)
827
+ prog.rec = rec # the call's own state first: a store that fails loses nothing here
828
+ self.store.update(rec)
829
+
830
+ @staticmethod
831
+ def _correlation(loaded: LoadedDocument, args: dict, explicit: Mapping[str, Any] | None) -> dict:
832
+ """kernel.md 3.3: canonical names win over raw aliases; explicit values win over derived."""
833
+ out: dict[str, Any] = {}
834
+ names = loaded.correlation_names
835
+ for key, value in args.items():
836
+ if key in names:
837
+ out[key] = value
838
+ # Raw names in the alias map's document order, so of two raw names for one
839
+ # canonical name the first alias entry wins, as `arg` reads do.
840
+ for raw, canon in loaded.arg_aliases.items():
841
+ if canon not in out and raw in args:
842
+ out[canon] = args[raw]
843
+ if explicit:
844
+ out.update(to_json(dict(explicit)))
845
+ return out
846
+
847
+ def _cap(self, decisions: list[Decision]) -> list[Decision]:
848
+ if self.mode == "shadow":
849
+ return [d if d.mode == "shadow" else dataclasses.replace(d, mode="shadow") for d in decisions]
850
+ return decisions
851
+
852
+ @staticmethod
853
+ def _aggregate(decisions: list[Decision]) -> str:
854
+ return most_severe([d.action for d in decisions if d.mode == "enforce"])
855
+
856
+ def _unknown_decision(self, rec: CallRecord, loaded: LoadedDocument) -> Decision:
857
+ return Decision(
858
+ rule_id=UNKNOWN_TOOL_RULE, rule_version="1", ruleset_version=loaded.ruleset_version,
859
+ action=self.unknown_tool_action, outcome="violate", rule_mode="enforce", mode="enforce",
860
+ evidence=[{"path": "call.tool_id", "value": rec.tool_id}],
861
+ sentence=f'The tool "{rec.tool_name_raw}" is not in the registered tool list.', error=None,
862
+ )
863
+
864
+ def _observe(self, rec: CallRecord) -> None:
865
+ observe = getattr(self.engine, "observe", None)
866
+ if callable(observe):
867
+ observe(rec)
868
+
869
+ def _replay(self, prog: _Progress) -> Outcome:
870
+ with self._lock:
871
+ stored = self._outcomes.get(_key(prog))
872
+ if stored is not None:
873
+ return stored
874
+ existing = self.store.latest(prog.call_id, _key(prog)[0])
875
+ return Outcome("allow", [], "", existing) if existing is not None else Outcome("allow", [], "", None)
876
+
877
+ def _remember(self, prog: _Progress, outcome: Outcome) -> None:
878
+ try:
879
+ with self._lock:
880
+ self._outcomes[_key(prog)] = outcome
881
+ except TypeError: # an unhashable call id from a broken adapter: nothing to remember it under
882
+ pass
883
+ if self.durable is not None and outcome.record is not None:
884
+ # 4.1a write-through: the record with its decisions and message is on
885
+ # disk before the adapter learns the outcome, unless its unit ended
886
+ # while the call was in flight (then no orphan row). Never raises.
887
+ self.store.persist_if_stored(outcome.record, _outcome_json(outcome))
888
+
889
+ # ------------------------------------------------------------ durable store (kernel.md 4.1a)
890
+
891
+ def _durable_fault(self, exc: BaseException, record: CallRecord | None = None, *,
892
+ ctx: RunContext | None = None, call_id: str | None = None, phase: str = "pre") -> None:
893
+ """A durable store write or read failed: the decision stands in memory
894
+ and a fault line, against the call where one is known, says the history
895
+ may not survive a restart."""
896
+ if self.mode == "off":
897
+ return
898
+ if record is not None:
899
+ ctx = ctx or RunContext(run_id=record.run_id, agent_id=record.agent_id, session_id=record.session_id,
900
+ root_run_id=record.root_run_id, parent_call_id=record.parent_call_id,
901
+ root_agent_id=record.root_agent_id)
902
+ call_id = call_id or record.call_id
903
+ if ctx is None:
904
+ ctx = RunContext(run_id="durable", agent_id="unknown")
905
+ self._emit(DecisionEvent("fault", phase, ctx, call_id, "allow", self.mode, self.clock(), record=record,
906
+ fault_error=f"durable store: {_err(exc)}", fault_action="allow",
907
+ fault_kind="kernel", bundle_version=self._state.bundle_version))
908
+
909
+ def _restore(self, ctx: RunContext, call_id: str) -> None:
910
+ """4.1a load on resume: the first call of a root run or (agent, session)
911
+ that is not in memory loads that unit from the durable store, settles
912
+ the records a dead process left unfinished, and remembers the stored
913
+ outcomes so a re-fire of a completed call is a re-execution. A row that
914
+ cannot be decoded is skipped with a fault line; a unit that cannot be
915
+ loaded at all raises `_UntrustedHistory`, which `before_call` handles
916
+ as a fault: the per-rule fail-closed check of kernel.md 10, never an
917
+ evaluation on an empty history."""
918
+ root, agent, session = ctx.root_run_id, ctx.agent_id, ctx.session_id
919
+ run_key, session_key = ("run", root), ("session", agent, session)
920
+ with self._lock:
921
+ need_run = run_key in self._untrusted or not self.store.has_open_run(root)
922
+ need_session = session is not None and (session_key in self._untrusted
923
+ or not self.store.has_session(agent, session))
924
+ if not need_run and not need_session:
925
+ return
926
+ keys = [k for k, needed in ((run_key, need_run), (session_key, need_session)) if needed]
927
+ try:
928
+ items, open_runs, skipped = self.durable.load(root if need_run else None, agent,
929
+ session if need_session else None)
930
+ except Exception as exc: # noqa: BLE001
931
+ for k in keys: # 4.1a Integrity: untrusted until a load succeeds; retried on every call
932
+ self._untrusted[k] = None
933
+ self._untrusted.move_to_end(k)
934
+ while len(self._untrusted) > 10_000:
935
+ self._untrusted.popitem(last=False)
936
+ raise _UntrustedHistory(f"the durable store could not load the history of this call: {_err(exc)}"
937
+ ) from exc
938
+ for k in keys:
939
+ self._untrusted.pop(k, None)
940
+ # Settle before anything enters memory: a sibling re-fired concurrently
941
+ # must never find a restored record still `pending` and take it as a
942
+ # re-execution (an allow with no evaluation).
943
+ settled = [(self._settled(rec, out), out) for rec, out in items]
944
+ restored = self.store.restore([(rec, out) for (rec, _), out in settled], open_runs)
945
+ placed = {id(rec) for rec in restored}
946
+ lines: list[tuple[CallRecord, tuple]] = []
947
+ for (rec, fault), out in settled:
948
+ if id(rec) not in placed:
949
+ continue
950
+ if fault is not None:
951
+ self.store.persist(rec)
952
+ lines.append((rec, fault))
953
+ elif out is not None:
954
+ try:
955
+ self._outcomes[(rec.root_run_id, rec.call_id)] = Outcome(
956
+ out["action"], _decisions_from_json(out), out.get("message", ""), rec)
957
+ except Exception: # noqa: BLE001 - an unreadable outcome: a re-fire is evaluated afresh
958
+ pass
959
+ if self.mode != "off":
960
+ for rec, (text, phase, action, kind, aggregate) in lines:
961
+ rctx = RunContext(run_id=rec.run_id, agent_id=rec.agent_id, session_id=rec.session_id,
962
+ root_run_id=rec.root_run_id, parent_call_id=rec.parent_call_id,
963
+ root_agent_id=rec.root_agent_id)
964
+ self._emit(DecisionEvent("fault", phase, rctx, rec.call_id, aggregate, self.mode, self.clock(),
965
+ record=rec, fault_error=text, fault_action=action, fault_kind=kind,
966
+ bundle_version=self._state.bundle_version))
967
+ for s_root, s_call, s_attempt, s_agent, s_session, text in skipped:
968
+ sctx = RunContext(run_id=s_root, agent_id=s_agent, session_id=s_session, root_run_id=s_root)
969
+ self._durable_fault(RuntimeError(f"row for call {s_call!r} attempt {s_attempt} skipped: {text}"),
970
+ ctx=sctx, call_id=s_call)
971
+
972
+ def _untrusted_call(self, prog: _Progress, exc: _UntrustedHistory) -> Outcome:
973
+ """4.1a Integrity: a call of a unit whose history could not be loaded.
974
+ Nothing is appended or written through (the unit's rows must not be
975
+ overwritten and attempts come from the loaded history only); the call is
976
+ a fault before any decision, so the per-rule fail-closed check of
977
+ kernel.md 10 decides it, and a fault line names the call."""
978
+ error = _err(exc)
979
+ args, dropped = _safe_args(prog.args)
980
+ rec = self._new_record(prog, self.tool_id_for(prog.tool_name, prog.tool_id, prog.state), args, {})
981
+ if dropped:
982
+ rec.meta["fault_dropped_keys"] = dropped
983
+ rec.meta["fault"] = error
984
+ prog.rec = rec
985
+ closing = self._fail_closed_rule(prog, rec)
986
+ action, message = "allow", ""
987
+ if closing is not None:
988
+ action, rec.status = "block", "blocked"
989
+ message = messages.could_not_be_checked(rec.tool_id, closing.id)
990
+ if self.mode != "off":
991
+ self._emit(DecisionEvent("fault", "pre", prog.ctx, prog.call_id, action, self.mode, self.clock(),
992
+ record=rec, fault_error=error, fault_action=action, fault_kind="kernel",
993
+ bundle_version=prog.state.bundle_version))
994
+ return Outcome(action, [], message, rec)
995
+
996
+ def _settled(self, rec: CallRecord, out: dict | None) -> tuple[CallRecord, tuple | None]:
997
+ """4.1a: a record still `pending` after a restart has an unknown outcome
998
+ and becomes `error`; one still `held` had no answer and becomes `blocked`
999
+ with resolution `timeout`. Either way its re-fire is a retry. Returns the
1000
+ record to place in memory and, when it was settled, the fault line's
1001
+ (text, phase, action, kind, aggregate)."""
1002
+ if rec.status not in ("pending", "held"):
1003
+ return rec, None
1004
+ meta = dict(rec.meta)
1005
+ if rec.status == "pending":
1006
+ text = UNKNOWN_OUTCOME
1007
+ meta["fault"] = text
1008
+ done = dataclasses.replace(rec, status="error", error=text, ended_at=self.clock(), meta=meta)
1009
+ return done, (text, "post", "allow", "kernel", "allow")
1010
+ text = "the process ended during the hold; the hold got no answer"
1011
+ meta["fault"] = text
1012
+ held_by = next((d.get("rule_id") for d in (out or {}).get("decisions") or []
1013
+ if d.get("mode") == "enforce" and d.get("action") == "hold"), None)
1014
+ meta["resolutions"] = [*(meta.get("resolutions") or []),
1015
+ {"rule_id": held_by, "answer": "timeout", "token": None, "outcome": "unreachable"}]
1016
+ done = dataclasses.replace(rec, status="blocked", ended_at=self.clock(), meta=meta)
1017
+ return done, (text, "pre", "block", "hold", "block")
1018
+
1019
+ def _release_inflight(self, prog: _Progress) -> None:
1020
+ if not prog.registered:
1021
+ return
1022
+ with self._lock:
1023
+ event = self._inflight.pop(_key(prog), None)
1024
+ if event is not None:
1025
+ event.set()
1026
+
1027
+ def _forget(self, removed: list[CallRecord]) -> None:
1028
+ if not removed:
1029
+ return
1030
+ with self._lock:
1031
+ for r in removed:
1032
+ if self.store.latest(r.call_id, r.root_run_id) is None:
1033
+ self._outcomes.pop((r.root_run_id, r.call_id), None)
1034
+
1035
+ def _maybe_sweep(self) -> None:
1036
+ now = self.clock()
1037
+ if (now - self._last_sweep) * 1000.0 >= self.idle_sweep_interval_ms:
1038
+ self._last_sweep = now
1039
+ self._forget(self.store.evict_idle(now))
1040
+ if (now - self._last_durable_sweep) * 1000.0 >= DURABLE_SWEEP_INTERVAL_MS:
1041
+ self._last_durable_sweep = now
1042
+ self.store.durable_sweep(now) # 4.1a: the file's retention, at most once a minute
1043
+
1044
+ def evict_idle(self) -> None:
1045
+ """Run the idle-age eviction now (kernel.md 4.3); `before_call` runs it periodically."""
1046
+ self._last_sweep = self._last_durable_sweep = self.clock()
1047
+ self._forget(self.store.evict_idle(self._last_sweep))
1048
+ self.store.durable_sweep(self._last_sweep)
1049
+
1050
+ def _count(self, d: Decision) -> None:
1051
+ key = (d.rule_id, d.rule_version)
1052
+ with self._lock:
1053
+ c = self._counts.get(key)
1054
+ if c is None:
1055
+ c = self._counts[key] = {"allow": 0, "flag": 0, "hold": 0, "block": 0, "error": 0,
1056
+ "would_fire": 0, "shadow_error": 0}
1057
+ if d.mode == "enforce":
1058
+ c["error" if d.outcome == "error" else d.action] += 1
1059
+ elif d.outcome == "error":
1060
+ c["shadow_error"] += 1
1061
+ elif d.action in ("hold", "block"):
1062
+ c["would_fire"] += 1
1063
+ else:
1064
+ c[d.action] += 1
1065
+
1066
+ def _emit(self, ev: DecisionEvent) -> None:
1067
+ if self._sink is None:
1068
+ return
1069
+ try:
1070
+ self._sink(ev)
1071
+ except Exception: # noqa: BLE001 - a broken sink must not break the agent
1072
+ pass
1073
+
1074
+
1075
+ _GUARDS: weakref.WeakSet = weakref.WeakSet() # every live kernel, for the fork hook
1076
+ _fork_hook_lock = threading.Lock()
1077
+ _fork_hook_installed = False
1078
+
1079
+
1080
+ def _install_fork_hook() -> None:
1081
+ """One process-wide `after_in_child` hook, installed by the first kernel,
1082
+ that resets every live kernel (`_reset_after_fork`). Registered once over a
1083
+ weak set, so the registration pins no kernel."""
1084
+ global _fork_hook_installed
1085
+ if _fork_hook_installed or not hasattr(os, "register_at_fork"):
1086
+ return
1087
+ with _fork_hook_lock:
1088
+ if not _fork_hook_installed:
1089
+ os.register_at_fork(after_in_child=_after_fork_in_child)
1090
+ _fork_hook_installed = True
1091
+
1092
+
1093
+ def _after_fork_in_child() -> None:
1094
+ for guard in list(_GUARDS):
1095
+ try:
1096
+ guard._reset_after_fork()
1097
+ except Exception: # noqa: BLE001 - one kernel's trouble must not stop the others resetting
1098
+ pass
1099
+
1100
+
1101
+ def _as_sink(sink: Any) -> Sink | None:
1102
+ if sink is None:
1103
+ return None
1104
+ on_event = getattr(sink, "on_event", None)
1105
+ if callable(on_event):
1106
+ return on_event
1107
+ if callable(sink):
1108
+ return sink
1109
+ raise TypeError("sink must be callable or have an on_event method")
1110
+
1111
+
1112
+ def _key(prog: _Progress) -> tuple:
1113
+ """Call identity: (root run id, call id) (kernel.md 5)."""
1114
+ return (getattr(prog.ctx, "root_run_id", None), prog.call_id)
1115
+
1116
+
1117
+ UNKNOWN_OUTCOME = "the process ended before the result was recorded"
1118
+
1119
+
1120
+ class _UntrustedHistory(RuntimeError):
1121
+ """4.1a: a unit the durable store could not load. Handled by `before_call`
1122
+ as a fault before any decision, so the per-rule fail-closed check of
1123
+ kernel.md 10 decides the call, never an evaluation on an empty history."""
1124
+
1125
+
1126
+ def _outcome_json(outcome: Outcome) -> dict:
1127
+ """The outcome as the durable store keeps it (kernel.md 4.1a)."""
1128
+ return {"action": outcome.action, "decisions": [dataclasses.asdict(d) for d in outcome.decisions],
1129
+ "message": outcome.message}
1130
+
1131
+
1132
+ def _decisions_from_json(outcome: dict) -> list[Decision]:
1133
+ return [Decision(**d) for d in outcome.get("decisions") or []]
1134
+
1135
+
1136
+ def _timeout_answer() -> dict:
1137
+ return {"answer": "timeout", "token": None, "outcome": "unreachable"}
1138
+
1139
+
1140
+ def _answer(resolution: Any) -> dict:
1141
+ """Normalise a resolver's return (a mapping, an object or a bare answer
1142
+ string) to `{"answer", "token", "outcome"}`; `outcome` is the hold outcome
1143
+ detail (protocol.md 7.4), defaulted from the answer when the resolver gives none."""
1144
+ if isinstance(resolution, str):
1145
+ answer, token, outcome = resolution, None, None
1146
+ elif isinstance(resolution, Mapping):
1147
+ answer, token, outcome = resolution.get("answer"), resolution.get("token"), resolution.get("outcome")
1148
+ else:
1149
+ answer = getattr(resolution, "answer", None)
1150
+ token = getattr(resolution, "token", None)
1151
+ outcome = getattr(resolution, "outcome", None)
1152
+ if answer not in ("allow", "block", "timeout"):
1153
+ raise ValueError(f"resolver answer must be allow, block or timeout, got {answer!r}")
1154
+ if outcome == "unknown":
1155
+ outcome = "denied" # protocol.md 7.4: a hold the control plane does not know is denied
1156
+ if outcome not in HOLD_OUTCOMES:
1157
+ outcome = _DEFAULT_OUTCOME[answer]
1158
+ return {"answer": answer, "token": str(token) if token is not None else None, "outcome": outcome}
1159
+
1160
+
1161
+ def _cap_to_flag(d: Decision) -> Decision:
1162
+ if d.action in ("hold", "block"):
1163
+ return dataclasses.replace(d, action="flag")
1164
+ return d
1165
+
1166
+
1167
+ def _safe_args(args: Any) -> tuple[dict, list[str]]:
1168
+ """Normalise what can be normalised; name the keys that could not (kernel.md 10)."""
1169
+ out: dict = {}
1170
+ dropped: list[str] = []
1171
+ try:
1172
+ items = list(dict(args or {}).items())
1173
+ except Exception: # noqa: BLE001
1174
+ return {}, ["*"]
1175
+ for key, value in items:
1176
+ try:
1177
+ out[str(key)] = to_json(value)
1178
+ except Exception: # noqa: BLE001
1179
+ dropped.append(str(key))
1180
+ return out, dropped
1181
+
1182
+
1183
+ def _err(exc: BaseException | Any) -> str:
1184
+ if isinstance(exc, BaseException):
1185
+ try:
1186
+ text = str(exc)
1187
+ except Exception: # noqa: BLE001 - an exception whose text itself fails
1188
+ text = ""
1189
+ return f"{type(exc).__name__}: {text}" if text else type(exc).__name__
1190
+ try:
1191
+ return str(exc)
1192
+ except Exception: # noqa: BLE001
1193
+ return type(exc).__name__
1194
+
1195
+
1196
+ __all__ = ["Guard", "LoadedState", "UNKNOWN_TOOL_RULE", "KERNEL_MODES", "HOLD_OUTCOMES"]