Skip to main content

kian_loop/
evidence.rs

1//! Evidence gate v1 (SPEC P4/A6): a declarative, bounded,
2//! **no-model-call** gate over the worker's own event stream.
3//!
4//! The gate is a pure predicate evaluation: it never calls the provider,
5//! never mutates context (verdicts are non-context-bearing ), and
6//! only *reports* — recovery disposition stays owned by the engine
7//! (a failed gate surfaces as a soft failure; the engine settles it).
8//!
9//! Semantics (wired into the built-in loop's stop path by
10//! [`crate::react::ReActLoop::with_evidence_gate`]):
11//!
12//! - On the loop's terminal stop — `Settled` (final answer, empty inbox:
13//!   the loop's "done" claim) or `Stopped` (intentional stop, e.g. The
14//!   iteration budget) — the gate evaluates every check as a pure
15//!   predicate over the session's event stream.
16//! - **Pass**: append `evidence/verdict{passed:true}` and let the stop
17//!   proceed — the verdict is the last event before the end write.
18//! - **Fail**: append `evidence/verdict{passed:false, attempt}` and send
19//!   the loop back for another provider turn while `attempt <
20//!   max_retries`; past the budget the loop reports a soft failure, which
21//!   the engine settles as `failed` — never `completed` with a failed
22//!   gate (constraint 7).
23//! - `attempt` is derived from the stream (the number of prior failed
24//!   verdicts of the same gate), so the retry budget survives episodes,
25//!   crashes and takeover (constraint 1 in spirit).
26//! - Retry turns reuse the identical context prefix: verdict events are
27//!   non-context-bearing, so a gate retry never invalidates the provider
28//!   prefix cache (constraint 3).
29//!
30//! Default-off: [`EvidenceGateConfig::default`] is disabled; built-in
31//! behavior is unchanged until a caller explicitly mounts a gate.
32
33use std::sync::Arc;
34use std::sync::atomic::{AtomicU64, Ordering};
35
36use kian_core::events::{Event, EventKind};
37use serde::{Deserialize, Serialize};
38use serde_json::{Value, json};
39
40/// Gate name the built-in loop stamps on its verdicts. Custom wrappers
41/// ('s worker driver) pass their own name so multiple gates can coexist
42/// on one stream.
43pub const BUILTIN_GATE_NAME: &str = "builtin";
44
45// ---------------------------------------------------------------------------
46// Check vocabulary (closed v1 — additions require a plan amendment)
47// ---------------------------------------------------------------------------
48
49/// One declarative evidence check. Each variant is a **pure predicate over
50/// `&[Event]`** — no provider call, no context mutation, no clock.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(tag = "type", rename_all = "snake_case")]
53pub enum CheckSpec {
54    /// The last assistant message after the last user input is a final
55    /// answer: non-empty text, no tool calls.
56    FinalMessagePresent,
57    /// At least one `tool/result` exists after the last user input (the
58    /// loop actually acted on the task, not just talked).
59    ToolResultSinceLastUserInput,
60    /// The trailing window of (up to) `k` tool results contains no error.
61    /// Vacuously true when the stream has fewer (or zero) tool results —
62    /// pair with [`CheckSpec::MinToolResults`] when presence is required.
63    NoErrorToolResultTail { k: u64 },
64    /// The stream holds at least `n` tool results in total.
65    MinToolResults { n: u64 },
66}
67
68impl CheckSpec {
69    /// The check's name as it appears in the verdict payload.
70    #[must_use]
71    pub fn name(&self) -> &'static str {
72        match self {
73            Self::FinalMessagePresent => "final_message_present",
74            Self::ToolResultSinceLastUserInput => "tool_result_since_last_user_input",
75            Self::NoErrorToolResultTail { .. } => "no_error_tool_result_tail",
76            Self::MinToolResults { .. } => "min_tool_results",
77        }
78    }
79
80    fn evaluate(&self, events: &[Event]) -> CheckOutcome {
81        let (passed, detail) = match *self {
82            Self::FinalMessagePresent => {
83                let after_input = slice_after_last_input(events);
84                let found = after_input.iter().any(|ev| {
85                    matches!(ev.kind, EventKind::AssistantMessage) && is_final_message(ev)
86                });
87                (
88                    found,
89                    Some("no assistant final message after the last user input".to_string()),
90                )
91            }
92            Self::ToolResultSinceLastUserInput => {
93                let after_input = slice_after_last_input(events);
94                let found = after_input
95                    .iter()
96                    .any(|ev| matches!(ev.kind, EventKind::ToolResult));
97                (
98                    found,
99                    Some("no tool/result after the last user input".to_string()),
100                )
101            }
102            Self::NoErrorToolResultTail { k } => {
103                let results = tool_results(events);
104                let window = (k as usize).min(results.len());
105                let errors = results[results.len() - window..]
106                    .iter()
107                    .filter(|ev| ev.bytes.pointer("/content/is_error") == Some(&json!(true)))
108                    .count();
109                let passed = errors == 0;
110                let detail = if passed {
111                    None
112                } else {
113                    Some(format!(
114                        "the trailing {window} tool result(s) include {errors} error(s)"
115                    ))
116                };
117                (passed, detail)
118            }
119            Self::MinToolResults { n } => {
120                let count = tool_results(events).len();
121                let passed = count >= n as usize;
122                let detail = if passed {
123                    None
124                } else {
125                    Some(format!("expected >= {n} tool results, found {count}"))
126                };
127                (passed, detail)
128            }
129        };
130        CheckOutcome {
131            name: self.name().to_string(),
132            passed,
133            detail: if passed { None } else { detail },
134        }
135    }
136}
137
138/// One evaluated check inside a verdict. `detail` is present exactly when
139/// the check failed (observable why, no noise on passes).
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct CheckOutcome {
142    pub name: String,
143    pub passed: bool,
144    pub detail: Option<String>,
145}
146
147/// The gate's verdict over one stream.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct GateVerdict {
150    pub passed: bool,
151    pub checks: Vec<CheckOutcome>,
152    /// 0-based retry counter, derived from prior *failed* verdicts of the
153    /// same gate in the stream.
154    pub attempt: u64,
155}
156
157/// Evaluates `checks` against `events`. Pure: same inputs, same verdict.
158///
159/// Public and reusable — 's worker-loop wrapper consumes this directly
160/// instead of reimplementing gate semantics.
161#[must_use]
162pub fn evaluate_evidence_gate(gate: &str, checks: &[CheckSpec], events: &[Event]) -> GateVerdict {
163    let attempt = events
164        .iter()
165        .filter(|ev| {
166            matches!(ev.kind, EventKind::EvidenceVerdict)
167                && ev.bytes.get("gate") == Some(&json!(gate))
168                && ev.bytes.get("passed") == Some(&json!(false))
169        })
170        .count() as u64;
171    let checks: Vec<CheckOutcome> = checks.iter().map(|c| c.evaluate(events)).collect();
172    let passed = checks.iter().all(|c| c.passed);
173    GateVerdict {
174        passed,
175        checks,
176        attempt,
177    }
178}
179
180/// Renders a verdict into the frozen `evidence/verdict` payload:
181/// `{"gate": str, "passed": bool, "checks": [{"name": str, "passed": bool,
182/// "detail"?: str}], "attempt": u64}`. Field order in serialized form is
183/// lexicographic (frozen serialization discipline, constraint 3).
184#[must_use]
185pub fn verdict_payload(gate: &str, verdict: &GateVerdict) -> Value {
186    let checks: Vec<Value> = verdict
187        .checks
188        .iter()
189        .map(|c| {
190            let mut v = json!({"name": c.name, "passed": c.passed});
191            if let Some(detail) = &c.detail {
192                v["detail"] = Value::String(detail.clone());
193            }
194            v
195        })
196        .collect();
197    json!({
198        "gate": gate,
199        "passed": verdict.passed,
200        "checks": checks,
201        "attempt": verdict.attempt,
202    })
203}
204
205// ---------------------------------------------------------------------------
206// Predicate support (pure stream slices)
207// ---------------------------------------------------------------------------
208
209/// The events after the last `input/admitted`; empty when no user input
210/// exists (nothing has been asked — presence checks fail).
211fn slice_after_last_input(events: &[Event]) -> &[Event] {
212    match events
213        .iter()
214        .rposition(|ev| matches!(ev.kind, EventKind::InputAdmitted))
215    {
216        Some(i) => &events[i + 1..],
217        None => &[],
218    }
219}
220
221fn tool_results(events: &[Event]) -> Vec<&Event> {
222    events
223        .iter()
224        .filter(|ev| matches!(ev.kind, EventKind::ToolResult))
225        .collect()
226}
227
228/// A context-bearing assistant/message is a *final* message when its text
229/// is non-empty and it carries no tool calls (payload convention).
230fn is_final_message(ev: &Event) -> bool {
231    let Some(content) = ev.bytes.get("content") else {
232        return false;
233    };
234    let text_present = content
235        .get("text")
236        .and_then(Value::as_str)
237        .is_some_and(|t| !t.is_empty());
238    let no_tool_calls = content
239        .get("tool_calls")
240        .and_then(Value::as_array)
241        .is_none_or(|calls| calls.is_empty());
242    text_present && no_tool_calls
243}
244
245// ---------------------------------------------------------------------------
246// Configuration + metrics counters
247// ---------------------------------------------------------------------------
248
249/// Verdict counters for the metrics surface (SPEC §3.1: evidence-gate
250/// verdicts). Mounted into `GET /metrics` by the assembly; cheap to
251/// read at any time.
252#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
253pub struct VerdictCounters {
254    pub passed: u64,
255    pub failed: u64,
256}
257
258/// Shared, lock-free verdict counters. Cloning the containing
259/// [`EvidenceGateConfig`] shares the same counters (an `Arc`).
260#[derive(Debug, Default)]
261pub struct EvidenceGateCounters {
262    passed: AtomicU64,
263    failed: AtomicU64,
264}
265
266impl EvidenceGateCounters {
267    pub fn record_passed(&self) {
268        self.passed.fetch_add(1, Ordering::Relaxed);
269    }
270
271    pub fn record_failed(&self) {
272        self.failed.fetch_add(1, Ordering::Relaxed);
273    }
274
275    #[must_use]
276    pub fn snapshot(&self) -> VerdictCounters {
277        VerdictCounters {
278            passed: self.passed.load(Ordering::Relaxed),
279            failed: self.failed.load(Ordering::Relaxed),
280        }
281    }
282}
283
284/// Evidence-gate tuning. Default is **disabled** — built-in behavior is
285/// unchanged until a caller mounts a gate explicitly.
286#[derive(Debug, Clone, Serialize, Deserialize)]
287#[serde(deny_unknown_fields)]
288pub struct EvidenceGateConfig {
289    /// Default `false`: no gate runs, no verdict events are appended.
290    #[serde(default)]
291    pub enabled: bool,
292    /// The closed v1 check vocabulary; an empty list is a vacuous pass.
293    #[serde(default)]
294    pub checks: Vec<CheckSpec>,
295    /// How many extra loop iterations a failed gate may buy (bounded
296    /// recovery, constraint 8). `0` = one failure settles immediately.
297    #[serde(default)]
298    pub max_retries: u64,
299    /// Shared verdict counters for the metrics surface; not configuration.
300    #[serde(skip)]
301    pub counters: Arc<EvidenceGateCounters>,
302}
303
304impl Default for EvidenceGateConfig {
305    fn default() -> Self {
306        Self {
307            enabled: false,
308            checks: Vec::new(),
309            max_retries: 0,
310            counters: Arc::new(EvidenceGateCounters::default()),
311        }
312    }
313}
314
315/// Config identity ignores the shared counters handle (runtime state, not
316/// configuration).
317impl PartialEq for EvidenceGateConfig {
318    fn eq(&self, other: &Self) -> bool {
319        self.enabled == other.enabled
320            && self.checks == other.checks
321            && self.max_retries == other.max_retries
322    }
323}