acuto 0.1.1__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.
acuto/__init__.py ADDED
@@ -0,0 +1,171 @@
1
+ """Acuto (Agentic Contract-based Runtime Orchestration): a symbolic control
2
+ layer for LLM agents.
3
+
4
+ A neuro-symbolic agent harness: procedural contracts are compiled into
5
+ runtime control. The agent chooses when there is freedom; Acuto executes
6
+ when there isn't.
7
+
8
+ Three orthogonal declarations:
9
+
10
+ * **tools** — what the agent CAN do (`ToolRegistry` / `@agent.tool`)
11
+ * **flow** — how the application WANTS to organize the task
12
+ (`FreeFlow` default, `GraphFlow` for staged tasks)
13
+ * **contracts** — what is ALLOWED and REQUIRED
14
+ (`ContractLibrary`, attached explicitly; never encoded into the flow)
15
+
16
+ import acuto
17
+
18
+ agent = acuto.Agent(model=acuto.models.resolve("anthropic:claude-sonnet-5"),
19
+ instructions="You are a bank service agent.")
20
+
21
+ @agent.tool
22
+ def verify_identity(customer_id: str) -> dict:
23
+ "Verify the customer's identity."
24
+ ...
25
+
26
+ library = acuto.ContractLibrary("refund-desk-v1", [
27
+ acuto.action("issue_refund").requires("identity_verified"),
28
+ acuto.after("verify_identity").asserts("identity_verified",
29
+ when=lambda r: r.output["verified"]),
30
+ acuto.when("fraud_detected").obligates("freeze_account", args={...}),
31
+ ])
32
+ library.verify() # symbolic certificates (LTLf-SAT)
33
+ agent.attach(library)
34
+
35
+ result = agent.run("Refund order #123")
36
+ for frame in agent.stream("Replace card for C-1024"):
37
+ print(frame.kind, frame.masked)
38
+
39
+ To drive Acuto from your own loop instead, build one ``acuto.Controller``
40
+ per task and call ``route()`` / ``verify()`` / ``commit()`` (or
41
+ ``execute()``) around your model and tool calls; ``acuto.Agent`` runs on
42
+ the same object.
43
+ """
44
+
45
+ from acuto import console, models
46
+ from acuto.agent import Agent
47
+ from acuto.backend import ContractBackend, LTLfBackend
48
+ from acuto.cache import ResidualPolicyCache
49
+ from acuto.checkpoint import Checkpoint, InFlightError
50
+ from acuto.contracts import (
51
+ ActionRule,
52
+ AfterRule,
53
+ CompiledContracts,
54
+ Contract,
55
+ CustomRule,
56
+ WhenRule,
57
+ action,
58
+ after,
59
+ ag,
60
+ compile_contracts,
61
+ when,
62
+ )
63
+ from acuto.control import SymbolicController
64
+ from acuto.controller import CallOutcome, Controller, as_action
65
+ from acuto.decisions import (
66
+ Decision,
67
+ DecisionKind,
68
+ ProposedAction,
69
+ ReturnVerdict,
70
+ StepDecision,
71
+ StepKind,
72
+ )
73
+ from acuto.facts import (
74
+ Fact,
75
+ FactStore,
76
+ LocalPredicateEvaluator,
77
+ PredicateContext,
78
+ PredicateEvaluator,
79
+ )
80
+ from acuto.flow import Flow, FlowContext, FreeFlow, GraphFlow
81
+ from acuto.library import ContractConflictError, ContractLibrary, VerifyReport
82
+ from acuto.loop import (
83
+ Compactor,
84
+ ContextArchive,
85
+ Frame,
86
+ MaskCompactor,
87
+ RunResult,
88
+ SummaryCompactor,
89
+ TruncateCompactor,
90
+ iterate,
91
+ run,
92
+ )
93
+ from acuto.obligations import ActiveObligation, ObligationEngine, ObligationSpec
94
+ from acuto.tools import Tool, ToolExecutor, ToolRegistry, ToolResult
95
+ from acuto.tracing import Tracer
96
+
97
+ # Back-compat alias from v0.0.1 (FreeAgent was renamed to FreeFlow).
98
+ FreeAgent = FreeFlow
99
+
100
+ __version__ = "0.1.1"
101
+
102
+ # The SDK surface, in three tiers. Everything below stays importable from
103
+ # ``acuto`` (nothing was removed); the tiers say what a user needs first.
104
+ # docs/SDK.md walks through them.
105
+ __all__ = [
106
+ # Tier 1 — write an agent with Acuto: model, tools, contracts, flow, run.
107
+ "Agent",
108
+ "models",
109
+ "console",
110
+ "Tool",
111
+ "ToolRegistry",
112
+ "ContractLibrary",
113
+ "action",
114
+ "after",
115
+ "when",
116
+ "ag",
117
+ "GraphFlow",
118
+ "FreeFlow",
119
+ "Frame",
120
+ "RunResult",
121
+ # Tier 2 — embed Acuto in your own loop: one session of control, driven
122
+ # step by step, plus the types its methods return.
123
+ "Controller",
124
+ "CallOutcome",
125
+ "as_action",
126
+ "ProposedAction",
127
+ "StepDecision",
128
+ "StepKind",
129
+ "Decision",
130
+ "DecisionKind",
131
+ "ReturnVerdict",
132
+ "ToolResult",
133
+ "run",
134
+ "iterate",
135
+ # Long runs: history compaction, checkpoint and resume.
136
+ "Compactor",
137
+ "ContextArchive",
138
+ "MaskCompactor",
139
+ "SummaryCompactor",
140
+ "TruncateCompactor",
141
+ "Checkpoint",
142
+ "InFlightError",
143
+ # Tier 3 — extension points and internals: custom predicates, raw
144
+ # formulas, the residual policy cache, the underlying controller.
145
+ "PredicateEvaluator",
146
+ "PredicateContext",
147
+ "LocalPredicateEvaluator",
148
+ "Fact",
149
+ "FactStore",
150
+ "Flow",
151
+ "FlowContext",
152
+ "CustomRule",
153
+ "Contract",
154
+ "ActionRule",
155
+ "AfterRule",
156
+ "WhenRule",
157
+ "CompiledContracts",
158
+ "compile_contracts",
159
+ "ContractConflictError",
160
+ "VerifyReport",
161
+ "SymbolicController",
162
+ "ContractBackend",
163
+ "LTLfBackend",
164
+ "ResidualPolicyCache",
165
+ "ActiveObligation",
166
+ "ObligationEngine",
167
+ "ObligationSpec",
168
+ "ToolExecutor",
169
+ "Tracer",
170
+ "FreeAgent",
171
+ ]
acuto/agent.py ADDED
@@ -0,0 +1,191 @@
1
+ """The user-facing Agent: model + tools + contract library + instructions.
2
+
3
+ Three orthogonal declarations meet here:
4
+
5
+ * **tools** say what the agent *can* do (ToolRegistry),
6
+ * **flow** says how the application *wants* to organize the task
7
+ (FreeFlow by default; GraphFlow for staged tasks),
8
+ * **contracts** say what is *allowed and required*
9
+ (ContractLibrary — attached explicitly, never encoded into the flow).
10
+
11
+ Usage::
12
+
13
+ agent = acuto.Agent(model=acuto.models.resolve("anthropic:claude-sonnet-5"),
14
+ instructions="You are a bank service agent.")
15
+
16
+ @agent.tool
17
+ def verify_identity(customer_id: str) -> dict: ...
18
+
19
+ agent.attach(acuto.ContractLibrary("refund-desk-v1", [...]))
20
+ result = agent.run("Refund order #123")
21
+ for frame in agent.stream("Replace card"):
22
+ ...
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from typing import Any, Callable, Generator, Iterable
28
+
29
+ from acuto.flow import Flow
30
+ from acuto.checkpoint import Checkpoint
31
+ from acuto.library import ContractLibrary
32
+ from acuto.loop import Compactor, Frame, RunResult, iterate
33
+ from acuto.models.base import Model
34
+ from acuto.tools import Tool, ToolRegistry
35
+
36
+
37
+ class Agent:
38
+ def __init__(
39
+ self,
40
+ model: Model,
41
+ *,
42
+ tools: ToolRegistry | Iterable[Tool] | None = None,
43
+ instructions: str | None = None,
44
+ flow: Flow | None = None,
45
+ contracts: ContractLibrary | list | None = None,
46
+ max_steps: int = 24,
47
+ predicate_evaluator: Any = None,
48
+ control_mode: str = "full",
49
+ cache: bool = False,
50
+ mask_granularity: str = "step",
51
+ compactor: Compactor | None = None,
52
+ ) -> None:
53
+ self.model = model
54
+ if isinstance(tools, ToolRegistry):
55
+ self.registry = tools
56
+ else:
57
+ self.registry = ToolRegistry()
58
+ for t in tools or []:
59
+ self.registry.register(t)
60
+ self.instructions = instructions
61
+ self.flow = flow
62
+ self.max_steps = max_steps
63
+ self.predicate_evaluator = predicate_evaluator
64
+ self.control_mode = control_mode
65
+ self.mask_granularity = mask_granularity
66
+ self.compactor = compactor
67
+ # Residual policy cache (opt-in): shared across this Agent's runs
68
+ # so repeated procedural states across tasks reuse compiled probes.
69
+ from acuto.cache import ResidualPolicyCache
70
+
71
+ self.probe_cache = ResidualPolicyCache() if cache else None
72
+ self.library: ContractLibrary | None = None
73
+ self.last_result: RunResult | None = None
74
+ if contracts is not None:
75
+ self.attach(contracts)
76
+
77
+ # ------------------------------------------------------------------
78
+ def tool(self, fn: Callable | None = None, **kwargs: Any):
79
+ """Register a tool on this agent (same options as ToolRegistry.tool)."""
80
+ return self.registry.tool(fn, **kwargs)
81
+
82
+ def attach(self, contracts: ContractLibrary | list) -> "Agent":
83
+ """Attach the contract library. Explicit and separate by design:
84
+ contracts are independent of the flow, never encoded into it."""
85
+ if isinstance(contracts, ContractLibrary):
86
+ self.library = contracts
87
+ else:
88
+ self.library = ContractLibrary("attached", list(contracts))
89
+ return self
90
+
91
+ # ------------------------------------------------------------------
92
+ def stream(
93
+ self,
94
+ task: str,
95
+ *,
96
+ facts: dict | None = None,
97
+ max_steps: int | None = None,
98
+ trace_path: str | None = None,
99
+ auditor: Any = None,
100
+ verbose: bool = False,
101
+ resume: Checkpoint | None = None,
102
+ checkpoint_path: str | None = None,
103
+ on_in_flight: str = "raise",
104
+ ) -> Generator[Frame, None, RunResult]:
105
+ """Yield one decision Frame per step; the generator's return value
106
+ is the RunResult (also stored as ``self.last_result``). With
107
+ ``verbose=True`` every step is also printed as it happens
108
+ (:mod:`acuto.console`). ``checkpoint_path`` writes the run's
109
+ checkpoint there before every step, so a run that died can be
110
+ resumed with ``resume=Checkpoint.load(path)``; ``on_in_flight``
111
+ says what to do with a call that was sent when it died
112
+ (:func:`acuto.loop.iterate`)."""
113
+ console = None
114
+ if verbose:
115
+ from acuto.console import Console
116
+
117
+ console = Console()
118
+ console.banner(
119
+ library=self.library,
120
+ tools=len(self.registry.names()),
121
+ flow=type(self.flow).__name__ if self.flow is not None else "FreeFlow",
122
+ model=type(self.model).__name__ if self.model is not None else None,
123
+ control_mode=self.control_mode,
124
+ )
125
+ gen = iterate(
126
+ task,
127
+ model=self.model,
128
+ tools=self.registry,
129
+ contracts=self.library,
130
+ flow=self.flow,
131
+ system=self.instructions,
132
+ max_steps=max_steps or self.max_steps,
133
+ trace_path=trace_path,
134
+ facts=facts,
135
+ predicate_evaluator=self.predicate_evaluator,
136
+ auditor=auditor,
137
+ control_mode=self.control_mode,
138
+ probe_cache=self.probe_cache,
139
+ mask_granularity=self.mask_granularity,
140
+ compactor=self.compactor,
141
+ resume=resume,
142
+ checkpoint_path=checkpoint_path,
143
+ on_in_flight=on_in_flight,
144
+ )
145
+ if console is None:
146
+ result = yield from gen
147
+ else:
148
+ while True:
149
+ try:
150
+ frame = next(gen)
151
+ except StopIteration as stop:
152
+ result = stop.value
153
+ break
154
+ console.step(frame)
155
+ yield frame
156
+ console.summary(result)
157
+ self.last_result = result
158
+ return result
159
+
160
+ def run(
161
+ self,
162
+ task: str,
163
+ *,
164
+ facts: dict | None = None,
165
+ max_steps: int | None = None,
166
+ trace_path: str | None = None,
167
+ auditor: Any = None,
168
+ verbose: bool = False,
169
+ resume: Checkpoint | None = None,
170
+ checkpoint_path: str | None = None,
171
+ on_in_flight: str = "raise",
172
+ ) -> RunResult:
173
+ """Run to completion. ``verbose=True`` prints every step;
174
+ ``resume`` continues from ``RunResult.checkpoint`` or from a
175
+ checkpoint loaded from ``checkpoint_path`` (see :meth:`stream`)."""
176
+ gen = self.stream(
177
+ task,
178
+ facts=facts,
179
+ max_steps=max_steps,
180
+ trace_path=trace_path,
181
+ auditor=auditor,
182
+ verbose=verbose,
183
+ resume=resume,
184
+ checkpoint_path=checkpoint_path,
185
+ on_in_flight=on_in_flight,
186
+ )
187
+ while True:
188
+ try:
189
+ next(gen)
190
+ except StopIteration as stop:
191
+ return stop.value
acuto/backend.py ADDED
@@ -0,0 +1,274 @@
1
+ """Contract backend: assume-guarantee monitoring via LTLf residuals.
2
+
3
+ Each contract gets a guarantee monitor and, when it carries an assumption,
4
+ an assumption monitor. Runtime semantics, following ContrAgent's
5
+ three-valued contract valuation (IDLE / ACTIVE / FAIL):
6
+
7
+ * the guarantee is in force from the start of the session — the agent is
8
+ bound by it while the environment keeps its side of the contract;
9
+ * an assumption is what the environment is required to keep. The contract
10
+ falls IDLE the moment an environment event falsifies it (residual ⊥),
11
+ and an IDLE contract constrains the agent no further;
12
+ * Acuto does not wait for that to happen. Like ContrAgent it maintains an
13
+ assumption by *suppressing* the environment event that would falsify it
14
+ (:meth:`acuto.control.SymbolicController.assert_fact`), so under
15
+ enforcement every loaded contract stays ACTIVE and IDLE is a diagnostic
16
+ of an environment Acuto could not hold to its side.
17
+
18
+ The split form is what makes that possible: folding the pair into the
19
+ single formula ``A → G`` would let a broken assumption silently discharge
20
+ the guarantee instead of surfacing as an environment violation. It also
21
+ exposes per-side diagnostics, drives A/G-aware feedback, and matches
22
+ ContrAgent's ``Contract`` model when importing its libraries. The rest of
23
+ Acuto depends only on the :class:`ContractBackend` protocol — probe /
24
+ step / finalize over valuation dicts.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from typing import Protocol, runtime_checkable
30
+
31
+ from contragent.kernel import DFAEvaluator, make_evaluator
32
+
33
+ from acuto.contracts import Contract
34
+
35
+ Valuation = dict[str, object]
36
+
37
+
38
+ @runtime_checkable
39
+ class ContractBackend(Protocol):
40
+ def probe(
41
+ self,
42
+ valuation: Valuation,
43
+ *,
44
+ include_args_dependent: bool = True,
45
+ masking_only: bool = False,
46
+ ) -> list[Contract]: ...
47
+
48
+ def step(self, valuation: Valuation) -> list[Contract]: ...
49
+
50
+ def finalize(self) -> list[Contract]: ...
51
+
52
+
53
+ class _Monitor:
54
+ __slots__ = ("contract", "g", "a", "a_broken")
55
+
56
+ def __init__(self, contract: Contract) -> None:
57
+ self.contract = contract
58
+ self.g = make_evaluator(contract.formula)
59
+ self.a = DFAEvaluator(contract.assumption) if contract.assumption is not None else None
60
+ self.a_broken = False # the environment has falsified its side
61
+
62
+ def _advance_assumption(self, valuation: Valuation) -> None:
63
+ if self.a is None or self.a_broken:
64
+ return
65
+ if self.a.step(valuation) == "⊥":
66
+ self.a_broken = True
67
+
68
+ def step(self, valuation: Valuation) -> bool:
69
+ """Advance one event; True iff the contract is (now) violated.
70
+
71
+ The guarantee monitor advances either way, so a contract that goes
72
+ IDLE keeps a well-defined residual for the control-state
73
+ signature; only the verdict is withheld."""
74
+ self._advance_assumption(valuation)
75
+ g_verdict = self.g.step(valuation)
76
+ return not self.a_broken and g_verdict == "⊥"
77
+
78
+ def assumption_broken_by(self, valuation: Valuation) -> bool:
79
+ """What-if on the environment side: would this event falsify the
80
+ assumption? Leaves the monitor untouched. ``False`` for an
81
+ unconditional contract and for one already IDLE."""
82
+ if self.a is None or self.a_broken:
83
+ return False
84
+ snap = self.a.snapshot()
85
+ verdict = self.a.step(valuation)
86
+ self.a.restore(snap)
87
+ return verdict == "⊥"
88
+
89
+ def snapshot(self) -> tuple:
90
+ """Restorable copy of this monitor's state (both DFAs + the flag)."""
91
+ return (
92
+ self.g.snapshot(),
93
+ self.a.snapshot() if self.a is not None else None,
94
+ self.a_broken,
95
+ )
96
+
97
+ def restore(self, snap: tuple) -> None:
98
+ g_snap, a_snap, broken = snap
99
+ self.g.restore(g_snap)
100
+ if a_snap is not None:
101
+ self.a.restore(a_snap)
102
+ self.a_broken = broken
103
+
104
+ def probe(self, valuation: Valuation) -> bool:
105
+ snap = self.snapshot()
106
+ violated = self.step(valuation)
107
+ self.restore(snap)
108
+ return violated
109
+
110
+ def final_violated(self) -> bool:
111
+ if self.a_broken:
112
+ return False
113
+ return self.g.finalize() == "⊥"
114
+
115
+ @property
116
+ def assumption_status(self) -> str:
117
+ if self.contract.assumption is None:
118
+ return "unconditional"
119
+ return "broken" if self.a_broken else "held"
120
+
121
+
122
+ class LTLfBackend:
123
+ """One monitor pair per contract; violations are contracts whose guarantee is ⊥
124
+ while their assumption still holds.
125
+
126
+ Because Acuto blocks violating actions *before* they commit, the live
127
+ monitors only ever consume compliant events in enforce flow, so
128
+ probing needs no staleness bookkeeping.
129
+ """
130
+
131
+ def __init__(self, contracts: list[Contract]) -> None:
132
+ self._monitors = [_Monitor(contract) for contract in contracts]
133
+
134
+ def probe(
135
+ self,
136
+ valuation: Valuation,
137
+ *,
138
+ include_args_dependent: bool = True,
139
+ masking_only: bool = False,
140
+ include_advisory: bool = False,
141
+ ) -> list[Contract]:
142
+ """What-if: would this event violate any contract? Leaves state untouched.
143
+
144
+ ``masking_only`` restricts the probe to contracts that participate in
145
+ tool masking (``Contract.masking``); soft-tier contracts still fire
146
+ at validate, where the violation reaches the model as feedback.
147
+ Unconfirmed (advisory) rules are left out unless ``include_advisory``:
148
+ only validate asks for them, to warn."""
149
+ return [
150
+ m.contract
151
+ for m in self._monitors
152
+ if (include_args_dependent or not m.contract.args_dependent)
153
+ and (not masking_only or m.contract.masking)
154
+ and (include_advisory or not m.contract.advisory)
155
+ and m.probe(valuation)
156
+ ]
157
+
158
+ def step(self, valuation: Valuation) -> list[Contract]:
159
+ """Commit one event into every monitor; returns contracts now violated."""
160
+ return [m.contract for m in self._monitors if m.step(valuation)]
161
+
162
+ def finalize(self) -> list[Contract]:
163
+ """Session-end verdicts (weak finite-trace collapse)."""
164
+ return [m.contract for m in self._monitors if m.final_violated()]
165
+
166
+ def snapshot(self) -> list:
167
+ """Restorable copy of every monitor's state; pairs with :meth:`restore`
168
+ so a caller can step the monitors speculatively (a batch of calls the
169
+ model emitted together) and put them back."""
170
+ return [m.snapshot() for m in self._monitors]
171
+
172
+ def restore(self, snaps: list) -> None:
173
+ for m, snap in zip(self._monitors, snaps):
174
+ m.restore(snap)
175
+
176
+ def residuals_after(
177
+ self,
178
+ valuation: Valuation,
179
+ *,
180
+ include_args_dependent: bool = False,
181
+ masking_only: bool = True,
182
+ ) -> list:
183
+ """Guarantee residuals the monitors would hold after ``valuation``.
184
+
185
+ Speculative like :meth:`probe`: the monitors are stepped, read, and
186
+ restored. The residuals are what a co-accessibility query needs --
187
+ what each contract still demands of the continuation. Contracts
188
+ whose environment side has already broken are dropped, since their
189
+ guarantee no longer binds.
190
+ """
191
+ snaps = self.snapshot()
192
+ try:
193
+ out = []
194
+ for m in self._monitors:
195
+ if m.a_broken:
196
+ continue
197
+ if not include_args_dependent and m.contract.args_dependent:
198
+ continue
199
+ if masking_only and not m.contract.masking:
200
+ continue
201
+ if m.contract.advisory: # an unconfirmed rule constrains nothing
202
+ continue
203
+ m.step(valuation)
204
+ out.append(m.g.residual)
205
+ return out
206
+ finally:
207
+ self.restore(snaps)
208
+
209
+ def state_signature(self) -> tuple:
210
+ """Hashable snapshot of the symbolic control state (per-contract
211
+ residuals + the environment-side flag). Together with the fact snapshot and
212
+ counters this keys the future residual-policy cache (partial
213
+ evaluation of contracts per control state — the symbolic-layer
214
+ analogue of prefix/KV reuse); tonight it instruments how often
215
+ control states REPEAT across tasks (the potential hit rate)."""
216
+ return tuple((m.contract.name, m.g.residual, m.a_broken) for m in self._monitors)
217
+
218
+ def assumption_breakers(self, valuation: Valuation) -> list[Contract]:
219
+ """Contracts whose assumption this environment event would falsify.
220
+
221
+ The environment-side counterpart of :meth:`probe`: the controller
222
+ suppresses such an event rather than let it discharge a guarantee
223
+ (ContrAgent's bidirectional enforcement)."""
224
+ return [
225
+ m.contract
226
+ for m in self._monitors
227
+ if not m.contract.advisory and m.assumption_broken_by(valuation)
228
+ ]
229
+
230
+ def assumption_statuses(self) -> dict[str, str]:
231
+ """contract name -> unconditional | held | broken."""
232
+ return {m.contract.name: m.assumption_status for m in self._monitors}
233
+
234
+ def contracts(self) -> list[Contract]:
235
+ return [m.contract for m in self._monitors]
236
+
237
+ def attach(self, contract: Contract) -> None:
238
+ """Monitor one more contract, from the current event on."""
239
+ if any(m.contract.name == contract.name for m in self._monitors):
240
+ raise ValueError(f"a contract named {contract.name!r} is already monitored")
241
+ self._monitors.append(_Monitor(contract))
242
+
243
+ def detach(self, name: str) -> Contract:
244
+ """Stop monitoring a contract; returns it."""
245
+ for i, m in enumerate(self._monitors):
246
+ if m.contract.name == name:
247
+ return self._monitors.pop(i).contract
248
+ raise KeyError(name)
249
+
250
+ def replace(self, name: str, contract: Contract, *, restart: bool = False) -> None:
251
+ """Swap a monitored contract's record (say, advisory to enforced),
252
+ keeping its monitor state, or starting it afresh with ``restart``."""
253
+ for i, m in enumerate(self._monitors):
254
+ if m.contract.name == name:
255
+ if restart:
256
+ self._monitors[i] = _Monitor(contract)
257
+ else:
258
+ m.contract = contract
259
+ return
260
+ raise KeyError(name)
261
+
262
+ def violated_now(self, name: str) -> bool:
263
+ """Has this contract's guarantee already reached ⊥?"""
264
+ for m in self._monitors:
265
+ if m.contract.name == name:
266
+ return m.g.peek() == "⊥" and not m.a_broken
267
+ raise KeyError(name)
268
+
269
+ def owes(self, name: str) -> bool:
270
+ """Would this contract fail if the session ended now?"""
271
+ for m in self._monitors:
272
+ if m.contract.name == name:
273
+ return m.final_violated()
274
+ raise KeyError(name)
acuto/cache.py ADDED
@@ -0,0 +1,62 @@
1
+ """Residual policy cache — symbolic-layer analogue of prefix/KV reuse.
2
+
3
+ Design (as specified): do NOT cache a concrete ``allowed_tools`` result;
4
+ key on the *residual control state* and evaluate session facts at lookup
5
+ time. The cache key for one candidate probe is:
6
+
7
+ (per-contract residuals + environment flags, # structural state
8
+ call counters + last tool, # trace registers
9
+ candidate tool,
10
+ fingerprint of the CONTRACT-REFERENCED fact valuation)
11
+
12
+ Session-specific values that contracts never mention (ticket ids, raw
13
+ strings) never enter the key — they are collapsed by the predicate
14
+ valuation itself. A hit skips the whole per-candidate probe (grounding
15
+ clone + ground_event + N residual steps); the stored value is the list
16
+ of violated contract names, so tracing stays byte-identical.
17
+
18
+ The cache is shared across runs of the same ContractLibrary (that is
19
+ where cross-task reuse lives: a 274-task benchmark visits only a few
20
+ dozen structural states). ``validate()`` is never cached — the hard
21
+ pre-execution boundary always computes.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from dataclasses import dataclass, field
27
+
28
+
29
+ @dataclass
30
+ class ResidualPolicyCache:
31
+ max_entries: int = 100_000
32
+ hits: int = 0
33
+ misses: int = 0
34
+ _store: dict = field(default_factory=dict)
35
+
36
+ def lookup(self, key):
37
+ entry = self._store.get(key, _MISS)
38
+ if entry is _MISS:
39
+ self.misses += 1
40
+ return None
41
+ self.hits += 1
42
+ return entry
43
+
44
+ def store(self, key, violated_names: tuple) -> None:
45
+ if len(self._store) < self.max_entries:
46
+ self._store[key] = violated_names
47
+
48
+ @property
49
+ def hit_rate(self) -> float:
50
+ total = self.hits + self.misses
51
+ return self.hits / total if total else 0.0
52
+
53
+ def stats(self) -> dict:
54
+ return {
55
+ "hits": self.hits,
56
+ "misses": self.misses,
57
+ "hit_rate": round(self.hit_rate, 4),
58
+ "entries": len(self._store),
59
+ }
60
+
61
+
62
+ _MISS = object()