Skip to main content

kian_loop/
react.rs

1//! Built-in ReAct loop.
2//!
3//! Per iteration: assemble context via `derive_model_context`, call the
4//! resolved model slot, persist request/response events before they fly,
5//! dispatch tool calls (side effects logged before execution), respect
6//! promote boundaries and the steer allowance, and terminate honestly.
7//! Local process execution runs via `spawn_blocking` so a sleeping tool
8//! cannot stall concurrent drains.
9//!
10//! The loop is a **passenger inside the drain** (layered iron rule): it
11//! only ever appends events through [`DrainCtx`] and reads projections;
12//! admission, claims, interrupts, the end write and episode supervision
13//! belong to the engine.
14//!
15//! ## Event payload conventions (frozen, additions-only discipline)
16//!
17//! - `turn/start` / `turn/end`: `{"iteration": <n>,...}` — the iteration
18//!   counter, derived from the stream (number of prior `turn/start`s),
19//!   never from resident state.
20//! - `step/request`: `{"slot", "provider", "model", "iteration", "body"}`
21//!   — the A2 audit copy of the request, appended **before** the provider
22//!   is called (the provider-level `PersistSink`, additionally covers
23//!   fallback-request bytes at the HTTP edge).
24//! - `assistant/message`: content `{"text": str, "tool_calls"?: [...]}`.
25//! - `tool/call` (logged before execution): content
26//!   `{"id", "name", "arguments"}` with role `assistant` (fixture
27//!   convention).
28//! - `tool/result`: content `{"call_id", "output", "is_error"}` with role
29//!   `tool`.
30//!
31//! ## Honest termination (constraint 7)
32//!
33//! An empty model response is a soft failure: the loop consults the
34//! declarative [`RecoveryPolicySource`] table for the class
35//! [`CLASS_EMPTY_RESPONSE`] and reports [`LoopOutcome::SoftFailed`] — the
36//! engine settles it as `failed`, never `completed`. The loop itself never
37//! retries (constraint 8: recovery disposition is one-shot-guarded and
38//! owned by the caller).
39//!
40//! ## Evidence gate on the stop path
41//!
42//! When mounted via [`ReActLoop::with_evidence_gate`], every terminal stop
43//! flow (`Settled` — the final-answer "done" claim — and `Stopped`) passes
44//! through [`crate::evidence`] before it is reported: pass appends
45//! `evidence/verdict{passed:true}` and lets the stop proceed; fail appends
46//! the failed verdict, buys at most `max_retries` extra provider turns,
47//! then reports a soft failure the engine settles as `failed` — never
48//! `completed` with a failed gate. The gate makes no provider call and
49//! never mutates context. Default-off (built-in behavior unchanged).
50
51use std::collections::BTreeMap;
52use std::sync::Arc;
53
54use futures::stream::{BoxStream, StreamExt};
55use kian_core::confirmation::{PendingCall, confirmable, confirmations, pending_calls};
56use kian_core::context::{Message, derive_model_context};
57use kian_core::control::{ConfirmDecision, ConfirmIntent};
58use kian_core::events::{Event, EventKind};
59use kian_core::model::{AgentDef, Permission, SlotName};
60use kian_core::seams::{
61    LoopDriver, LoopOutcome, ModelRequest, ProviderError, RecoveryAction, RecoveryPolicySource,
62    ToolCall, ToolProvider, ToolResult,
63};
64use kian_llm::provider::{ChatMessage, WireFunctionCall, WireToolCall, build_chat_body};
65use kian_llm::slots::{SessionSlots, SlotBinding, SlotError, SlotResolver};
66use kian_llm::turn::{ProviderRegistry, SlotEventSink, complete_turn};
67use kian_orchestrator::{DrainCtx, EngineError};
68use serde_json::{Value, json};
69
70use crate::evidence::{
71    BUILTIN_GATE_NAME, EvidenceGateConfig, evaluate_evidence_gate, verdict_payload,
72};
73
74/// Recovery-policy class for an empty model response (constraint 7).
75pub const CLASS_EMPTY_RESPONSE: &str = "empty_response";
76
77/// Iteration budget default: stops honest loops that never converge.
78pub const DEFAULT_MAX_ITERATIONS: usize = 32;
79
80/// How a loop's iteration budget is scoped (ADR-024).
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
82pub enum BudgetScope {
83    /// The budget counts every `turn/start` ever committed on the session
84    /// (the legacy behavior; correct for short-lived worker/plain
85    /// sessions).
86    #[default]
87    Lifetime,
88    /// The budget counts the current episode's turns only (resident loops:
89    /// the Router and the watchdog). Exhaustion parks the resident; it
90    /// never ends the session.
91    PerEpisode,
92}
93
94impl BudgetScope {
95    /// The budget counter this scope compares against the limit.
96    #[must_use]
97    fn used(self, lifetime_iteration: usize, episode_iterations: usize) -> usize {
98        match self {
99            Self::Lifetime => lifetime_iteration,
100            Self::PerEpisode => episode_iterations,
101        }
102    }
103}
104
105// ---------------------------------------------------------------------------
106// Configuration
107// ---------------------------------------------------------------------------
108
109/// Tuning for the built-in ReAct loop.
110#[derive(Debug, Clone)]
111pub struct ReActConfig {
112    /// The model slot the loop drives (resolved via the session's slot
113    /// bindings, ADR-006).
114    pub slot: SlotName,
115    /// Maximum provider turns per session (counted from the event stream,
116    /// so the budget survives episodes and restarts — the legacy scope).
117    /// With [`BudgetScope::PerEpisode`] (resident loops, ADR-024) the same
118    /// value bounds one episode instead.
119    pub max_iterations: usize,
120    /// Whether the budget is lifetime-scoped (default) or per episode.
121    pub budget_scope: BudgetScope,
122    /// Per-call tool permission table (ADR-015): tool name →
123    /// `allow`/`deny`. **Absent = empty = allow-all**, and with an empty
124    /// table the `tool/call` payload stays byte-identical to the legacy
125    /// shape (no provenance key at all). A non-empty table decides every
126    /// call — provenance rides the payload on allow, not only on deny.
127    pub permissions: BTreeMap<String, Permission>,
128}
129
130impl Default for ReActConfig {
131    fn default() -> Self {
132        Self {
133            slot: SlotName("main".into()),
134            max_iterations: DEFAULT_MAX_ITERATIONS,
135            budget_scope: BudgetScope::Lifetime,
136            permissions: BTreeMap::new(),
137        }
138    }
139}
140
141struct Inner {
142    registry: Arc<ProviderRegistry>,
143    tools: Arc<dyn ToolProvider>,
144    policy: Arc<dyn RecoveryPolicySource>,
145    agent: AgentDef,
146    config: ReActConfig,
147    /// evidence gate on the stop path; default (disabled) leaves
148    /// built-in behavior untouched.
149    gate: EvidenceGateConfig,
150    /// The injected hook ports (PLUGIN-SPEC §4 rows (b)–(f)); `None`
151    /// mounts no consultation and is byte-identical to the pre-plugin
152    /// loop. The loop never builds a bus — assembly injects it.
153    hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
154    /// The §9.2 session-consistency guard, called once per drive (one
155    /// drain begin = one claim boundary): record the set digest at
156    /// first sight, recompute and compare after. `None` (every legacy
157    /// constructor) is a no-op — byte-identical (§13.3). This is not
158    /// an eighth interception port (§4's seven are frozen); it is the
159    /// guard's own seam.
160    set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
161}
162
163/// The built-in async ReAct [`LoopDriver`] (DESIGN §6.2). Cheap to clone.
164#[derive(Clone)]
165pub struct ReActLoop(Arc<Inner>);
166
167impl ReActLoop {
168    /// Assembles the loop from an agent definition, a provider registry
169    /// (slot targets resolve against it), the tool provider, and the
170    /// declarative recovery-policy source consulted on soft failures.
171    pub fn new(
172        agent: AgentDef,
173        registry: Arc<ProviderRegistry>,
174        tools: Arc<dyn ToolProvider>,
175        policy: Arc<dyn RecoveryPolicySource>,
176    ) -> Self {
177        Self::with_config(agent, registry, tools, policy, ReActConfig::default())
178    }
179
180    /// [`ReActLoop::new`] with explicit loop tuning. The evidence gate is
181    /// disabled (built-in behavior).
182    pub fn with_config(
183        agent: AgentDef,
184        registry: Arc<ProviderRegistry>,
185        tools: Arc<dyn ToolProvider>,
186        policy: Arc<dyn RecoveryPolicySource>,
187        config: ReActConfig,
188    ) -> Self {
189        Self::with_evidence_gate(
190            agent,
191            registry,
192            tools,
193            policy,
194            config,
195            EvidenceGateConfig::default(),
196        )
197    }
198
199    /// [`ReActLoop::with_config`] with an evidence gate mounted on
200    /// the stop path. A disabled [`EvidenceGateConfig`] behaves exactly
201    /// like [`ReActLoop::with_config`].
202    pub fn with_evidence_gate(
203        agent: AgentDef,
204        registry: Arc<ProviderRegistry>,
205        tools: Arc<dyn ToolProvider>,
206        policy: Arc<dyn RecoveryPolicySource>,
207        config: ReActConfig,
208        gate: EvidenceGateConfig,
209    ) -> Self {
210        Self::with_hooks(agent, registry, tools, policy, config, gate, None)
211    }
212
213    /// [`ReActLoop::with_evidence_gate`] plus the injected hook ports
214    /// (PLUGIN-SPEC §4): the bus instance assembly owns, consulted at
215    /// this loop's five ReAct sites — `turn/request`, `turn/response`,
216    /// `tool/pre`, `tool/post`, `recover/decided`. `None` (every
217    /// legacy constructor) mounts no consultation at all.
218    pub fn with_hooks(
219        agent: AgentDef,
220        registry: Arc<ProviderRegistry>,
221        tools: Arc<dyn ToolProvider>,
222        policy: Arc<dyn RecoveryPolicySource>,
223        config: ReActConfig,
224        gate: EvidenceGateConfig,
225        hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
226    ) -> Self {
227        Self::with_hooks_and_guard(agent, registry, tools, policy, config, gate, hooks, None)
228    }
229
230    /// [`ReActLoop::with_hooks`] plus the §9.2 session-set guard — the
231    /// assembly mounts both from the same bus instance. The guard runs
232    /// once per drive (the drain/claim boundary), before the first
233    /// iteration; the frame carries this drain's session and epoch with
234    /// the honest floor binding (the loop holds no worker binding,
235    /// §7.3 — an unbound session resolves the server scope, §8.2).
236    /// Eight named arguments, same shape as the sibling constructors —
237    /// a bundle struct would only rename the same list.
238    #[allow(clippy::too_many_arguments)]
239    pub fn with_hooks_and_guard(
240        agent: AgentDef,
241        registry: Arc<ProviderRegistry>,
242        tools: Arc<dyn ToolProvider>,
243        policy: Arc<dyn RecoveryPolicySource>,
244        config: ReActConfig,
245        gate: EvidenceGateConfig,
246        hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
247        set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
248    ) -> Self {
249        Self(Arc::new(Inner {
250            registry,
251            tools,
252            policy,
253            agent,
254            config,
255            gate,
256            hooks,
257            set_guard,
258        }))
259    }
260
261    #[must_use]
262    pub fn config(&self) -> &ReActConfig {
263        &self.0.config
264    }
265
266    /// The mounted evidence-gate config. The shared verdict counters
267    /// inside are the metrics surface for `GET /metrics` (wired by the
268    /// assembly).
269    #[must_use]
270    pub fn evidence_gate(&self) -> &EvidenceGateConfig {
271        &self.0.gate
272    }
273}
274
275// ---------------------------------------------------------------------------
276// LoopDriver
277// ---------------------------------------------------------------------------
278
279/// unfold state: one step == one full provider turn (with its tool
280/// dispatches). `done` ends the stream after the terminal outcome was
281/// yielded; `begun` fires the drain-boundary §9.2 guard once, on the
282/// first poll.
283struct LoopState {
284    ctx: DrainCtx,
285    done: bool,
286    begun: bool,
287    /// Per-episode turn count for [`BudgetScope::PerEpisode`]; reset per
288    /// drive stream (ADR-024).
289    drain_iterations: usize,
290}
291
292impl LoopDriver for ReActLoop {
293    type Ctx = DrainCtx;
294
295    fn drive(&self, ctx: DrainCtx) -> BoxStream<'static, LoopOutcome> {
296        let inner = Arc::clone(&self.0);
297        futures::stream::unfold(
298            LoopState {
299                ctx,
300                done: false,
301                begun: false,
302                drain_iterations: 0,
303            },
304            move |mut st| {
305                let inner = Arc::clone(&inner);
306                async move {
307                    if st.done {
308                        return None;
309                    }
310                    // §9.2 steps 1–4 at the drain/claim boundary: the
311                    // guard records the set digest at first sight and
312                    // re-checks it on every claim this process serves.
313                    // A no-op without a mounted guard. The frame's
314                    // `worker` is the session's durable `exec_worker`
315                    // binding (§7.3/§8.2) derived from its own stream —
316                    // a bound worker session records its narrowed set's
317                    // digest, never the server scope's. Fired on the
318                    // first poll (the drain's first step) because the
319                    // stream read is async.
320                    if !st.begun {
321                        st.begun = true;
322                        if let Some(guard) = inner.set_guard.as_ref() {
323                            let worker = match st.ctx.events().await {
324                                Ok(events) => kian_plugin::hooks::durable_worker_binding(
325                                    &events,
326                                    &st.ctx.session(),
327                                )
328                                .unwrap_or_default(),
329                                // An unreadable stream cannot prove a
330                                // binding; the honest floor is §7.3's
331                                // empty string, never a guess.
332                                Err(_) => String::new(),
333                            };
334                            guard.session_begin(kian_plugin::hooks::FrameInfo {
335                                session: st.ctx.session(),
336                                worker,
337                                seq: 0,
338                                epoch: Some(st.ctx.epoch().0),
339                            });
340                        }
341                    }
342                    let outcome = match inner.iteration(&st.ctx, &mut st.drain_iterations).await {
343                        Flow::TurnDone => LoopOutcome::TurnDone,
344                        Flow::Settled | Flow::Deferred => LoopOutcome::Settled,
345                        Flow::Stopped(reason) => LoopOutcome::Stopped { reason },
346                        Flow::Soft(reason) => LoopOutcome::SoftFailed { reason },
347                    };
348                    if !matches!(outcome, LoopOutcome::TurnDone) {
349                        st.done = true;
350                    }
351                    Some((outcome, st))
352                }
353            },
354        )
355        .boxed()
356    }
357}
358
359/// What one iteration concluded.
360enum Flow {
361    /// A provider turn ran (with or without tool calls); keep looping.
362    TurnDone,
363    /// No eligible input remains and the model gave a final answer.
364    Settled,
365    /// The turn stopped on a pending confirmation (CONFIRMATION-MODEL
366    /// §7): no provider request is allowed while a call is unanswered.
367    /// Reported as `LoopOutcome::Settled`; the engine derives the
368    /// `awaiting_input` end reason from the stream.
369    Deferred,
370    /// An intentional stop condition fired.
371    Stopped(String),
372    /// Soft failure — routed to the recovery policy; never `completed`.
373    Soft(String),
374}
375
376enum TurnOutcome {
377    FinalAnswer,
378    ToolCalls(usize),
379}
380
381/// One provider turn's terminal state plus the audit facts the
382/// `turn/end` payload needs: the last non-null provider usage
383/// observed across the whole turn — including an attempt that emitted
384/// usage before failing — travels with every outcome variant.
385struct TurnResult {
386    result: Result<TurnOutcome, TurnError>,
387    usage: Option<Value>,
388}
389
390enum TurnError {
391    /// Soft failure — reported to the engine as `LoopOutcome::SoftFailed`.
392    /// Carries the structured recovery audit for `turn/end`
393    /// (`{"class", "action"}`).
394    Soft { reason: String, audit: Value },
395    /// Hard error (store/append failure): honest `failed`, never retried
396    /// by the loop. Also carries the recovery audit.
397    Fatal { error: LoopError, audit: Value },
398}
399
400/// Loop-level failures. Every one degrades honestly to a soft report —
401/// the loop has no code path that could masquerade an error as
402/// completion.
403#[derive(Debug, thiserror::Error)]
404pub enum LoopError {
405    #[error("engine: {0}")]
406    Engine(#[from] EngineError),
407    #[error("context projection: {0}")]
408    Context(#[from] kian_core::context::ContextError),
409    #[error("slots: {0}")]
410    Slot(#[from] SlotError),
411}
412
413impl Inner {
414    /// One ReAct iteration.
415    async fn iteration(&self, ctx: &DrainCtx, drain_iterations: &mut usize) -> Flow {
416        let flow = match self.run_iteration(ctx, drain_iterations).await {
417            Ok(flow) => flow,
418            Err(e) => return Flow::Soft(format!("loop error: {e}")),
419        };
420        // terminal stop flows pass through the evidence gate before
421        // they are reported (a disabled gate is a no-op pass-through).
422        match flow {
423            Flow::Settled | Flow::Stopped(_) => self.apply_evidence_gate(ctx, flow).await,
424            other => other,
425        }
426    }
427
428    /// The evidence gate on the loop's stop path. Evaluates the
429    /// configured checks as pure predicates over the session's own event
430    /// stream — never a provider call, never a context mutation — and
431    /// appends one `evidence/verdict` event:
432    ///
433    /// - pass → the stop proceeds; the verdict is the last event before
434    ///   the engine's end write;
435    /// - fail → the loop continues (`Flow::TurnDone`) while
436    ///   `attempt < max_retries`, else reports a soft failure — the
437    ///   engine settles it `failed`, never `completed` (constraint 7).
438    ///
439    /// The gate only reports; disposition stays with the engine.
440    async fn apply_evidence_gate(&self, ctx: &DrainCtx, flow: Flow) -> Flow {
441        if !self.gate.enabled {
442            return flow;
443        }
444        let events = match ctx.events().await {
445            Ok(events) => events,
446            Err(e) => {
447                return Flow::Soft(format!("evidence gate: stream read failed: {e}"));
448            }
449        };
450        let verdict = evaluate_evidence_gate(BUILTIN_GATE_NAME, &self.gate.checks, &events);
451        let payload = verdict_payload(BUILTIN_GATE_NAME, &verdict);
452        if let Err(e) = ctx.append(EventKind::EvidenceVerdict, payload).await {
453            return Flow::Soft(format!("evidence gate: verdict append failed: {e}"));
454        }
455        if verdict.passed {
456            self.gate.counters.record_passed();
457            flow
458        } else {
459            self.gate.counters.record_failed();
460            if verdict.attempt < self.gate.max_retries {
461                Flow::TurnDone
462            } else {
463                Flow::Soft(format!(
464                    "evidence gate `{BUILTIN_GATE_NAME}` failed after {} attempt(s)",
465                    verdict.attempt + 1
466                ))
467            }
468        }
469    }
470
471    // -- hook-port dispatch (PLUGIN-SPEC §4 rows (b)–(f)) ------------------
472    //
473    // Every helper is a no-op without an injected bus, and every view
474    // is built from the exact facts the site already holds — no extra
475    // store reads, no re-serialization of model-visible bytes (the
476    // digest fields describe the persisted bytes; nothing is rebuilt).
477
478    /// The frame identity of a drain-phase dispatch (§7.3): this
479    /// drain's session and fencing epoch, `seq` is the last append
480    /// this drain observed, and `worker` is the session's durable
481    /// `exec_worker` binding derived from its own stream — the loop
482    /// holds no resident binding, so a bound worker session narrows
483    /// its plugin set (§8.2) while an unbound session keeps the honest
484    /// floor (§7.3's empty string). The events read is the engine's
485    /// cached one, and the model-visible request bytes are untouched —
486    /// frame identity is `#[serde(skip)]`d metadata (§12.1).
487    async fn hook_frame(ctx: &DrainCtx, seq: u64) -> Option<kian_plugin::hooks::FrameInfo> {
488        let worker = match ctx.events().await {
489            Ok(events) => kian_plugin::hooks::durable_worker_binding(&events, &ctx.session())
490                .unwrap_or_default(),
491            // An unreadable stream cannot prove a binding; the honest
492            // floor is §7.3's empty string, never a guess.
493            Err(_) => String::new(),
494        };
495        Some(kian_plugin::hooks::FrameInfo {
496            session: ctx.session(),
497            worker,
498            seq,
499            epoch: Some(ctx.epoch().0),
500        })
501    }
502
503    /// Row (b) — `turn/request` (§4.2): observe-only, exactly once per
504    /// provider turn, on the persisted primary body, immediately after
505    /// the `step/request` append returns `Ok`.
506    // The view's normative fields arrive as separate borrowed parts of
507    // the turn's state; a tuple struct would only rename the same list.
508    #[allow(clippy::too_many_arguments)]
509    async fn observe_request(
510        &self,
511        ctx: &DrainCtx,
512        binding: &SlotBinding,
513        chat_len: usize,
514        schemas: &[kian_core::seams::ToolSchema],
515        iteration: usize,
516        body: &Value,
517        step_request_seq: u64,
518    ) {
519        use kian_plugin::hooks::{RequestMeta, serialized, sha256_hex};
520        let Some(hooks) = self.hooks.as_ref() else {
521            return;
522        };
523        let bytes = serialized(body);
524        let meta = RequestMeta {
525            slot: self.config.slot.0.clone(),
526            provider: binding.target.provider.clone(),
527            model: binding.target.model.clone(),
528            iteration: iteration as u64,
529            request_bytes: bytes.len() as u64,
530            request_sha256: sha256_hex(&bytes),
531            message_count: chat_len as u64,
532            tool_names: schemas.iter().map(|s| s.name.clone()).collect(),
533            tool_schema_sha256: sha256_hex(&serialized(&Value::Array(
534                schemas
535                    .iter()
536                    .map(|s| serde_json::to_value(s).unwrap_or(Value::Null))
537                    .collect(),
538            ))),
539            timing: "pre_send".to_string(),
540            step_request_seq,
541            frame: Self::hook_frame(ctx, step_request_seq).await,
542        };
543        hooks.request(&meta).await;
544    }
545
546    /// Row (c) — `turn/response` (§4.3): observe-only, once per settled
547    /// provider turn, never per chunk. `error_audit` is the
548    /// `turn/end`-vocabulary `{class, action}` object the same path
549    /// already builds, when the outcome is a failure.
550    #[allow(clippy::too_many_arguments)] // settled-turn state, borrowed in parts
551    async fn observe_response(
552        &self,
553        ctx: &DrainCtx,
554        iteration: usize,
555        seq: u64,
556        outcome: &str,
557        tool_calls: u64,
558        text_bytes: u64,
559        reasoning_bytes: u64,
560        usage: Option<&Value>,
561        error_audit: Option<&Value>,
562    ) {
563        use kian_plugin::hooks::{ResponseView, TurnErrorAudit};
564        let Some(hooks) = self.hooks.as_ref() else {
565            return;
566        };
567        let error = error_audit.and_then(|audit| {
568            Some(TurnErrorAudit {
569                class: audit.get("class")?.as_str()?.to_string(),
570                action: audit.get("action")?.as_str()?.to_string(),
571            })
572        });
573        let view = ResponseView {
574            iteration: iteration as u64,
575            outcome: outcome.to_string(),
576            tool_calls,
577            text_bytes,
578            reasoning_bytes,
579            usage: usage.cloned().unwrap_or(Value::Null),
580            error,
581            timing: "settled".to_string(),
582            frame: Self::hook_frame(ctx, seq).await,
583        };
584        hooks.response(&view).await;
585    }
586
587    /// Row (d) — `tool/pre` (§4.4 step 2): consulted after the
588    /// declarative gate has decided and before the `tool/call` append /
589    /// `invoke`. Only a verdict from a `veto:tool` holder (or its
590    /// fail-closed default) denies; otherwise the declarative gate's
591    /// decision stands.
592    async fn consult_tool_pre(
593        &self,
594        ctx: &DrainCtx,
595        call: &ToolCall,
596        iteration: usize,
597        seq: u64,
598        decision: Option<PermissionDecision>,
599    ) -> kian_plugin::hooks::ToolVerdict {
600        use kian_plugin::hooks::{ToolCallView, bounded_value, serialized, sha256_hex};
601        let Some(hooks) = self.hooks.as_ref() else {
602            return kian_plugin::hooks::ToolVerdict::Allow;
603        };
604        let bytes = serialized(&call.arguments);
605        let (arguments, arguments_truncated) = bounded_value(&call.arguments);
606        let view = ToolCallView {
607            call_id: call.id.clone(),
608            name: call.name.clone(),
609            iteration: iteration as u64,
610            arguments,
611            arguments_bytes: bytes.len() as u64,
612            arguments_sha256: sha256_hex(&bytes),
613            arguments_truncated,
614            permission: permission_view(call, decision),
615            surface: "react".to_string(),
616            frame: Self::hook_frame(ctx, seq).await,
617        };
618        hooks.tool_pre(&view).await
619    }
620
621    /// Row (d′) — `tool/post` (§4.4 step 5): observe-only after the
622    /// `tool/result` append, on the executed, declared-denied and
623    /// hook-denied arms alike (the uniform surface).
624    async fn observe_tool_post(&self, ctx: &DrainCtx, result: &ToolResult, name: &str, seq: u64) {
625        use kian_plugin::hooks::{RedactionReport, ToolPostView, serialized, sha256_hex};
626        let Some(hooks) = self.hooks.as_ref() else {
627            return;
628        };
629        let bytes = serialized(&result.output);
630        let view = ToolPostView {
631            call_id: result.call_id.clone(),
632            name: name.to_string(),
633            is_error: result.is_error,
634            output_bytes: bytes.len() as u64,
635            output_sha256: sha256_hex(&bytes),
636            redactions: result
637                .redactions
638                .iter()
639                .map(|r| RedactionReport {
640                    kind: serde_json::to_value(r.kind)
641                        .ok()
642                        .and_then(|v| v.as_str().map(str::to_string))
643                        .unwrap_or_default(),
644                    name: r.name.clone(),
645                    count: r.count,
646                })
647                .collect(),
648            frame: Self::hook_frame(ctx, seq).await,
649        };
650        hooks.tool_post(&view).await;
651    }
652
653    /// Row (f) — `recover/decided` (§4.5): observe-only at each
654    /// class → action resolution this loop performs; the audit object
655    /// is the one the `turn/end` payload already carries.
656    async fn observe_recover(&self, ctx: &DrainCtx, iteration: usize, seq: u64, audit: &Value) {
657        let Some(hooks) = self.hooks.as_ref() else {
658            return;
659        };
660        let view = kian_plugin::hooks::RecoveryView {
661            error_class: audit
662                .get("class")
663                .and_then(Value::as_str)
664                .unwrap_or_default()
665                .to_string(),
666            action: audit
667                .get("action")
668                .and_then(Value::as_str)
669                .unwrap_or("none")
670                .to_string(),
671            iteration: iteration as u64,
672            frame: Self::hook_frame(ctx, seq).await,
673        };
674        hooks.recover(&view).await;
675    }
676
677    /// The fatal-turn observation pair (rows (c) + (f)): an
678    /// append-failure turn settles as `error` and its recovery audit
679    /// observes like any other resolution.
680    #[allow(clippy::too_many_arguments)] // fatal-turn state, borrowed in parts
681    async fn observe_fatal(
682        &self,
683        ctx: &DrainCtx,
684        iteration: usize,
685        seq: u64,
686        audit: &Value,
687        text_bytes: u64,
688        reasoning_bytes: u64,
689        usage: Option<&Value>,
690    ) {
691        self.observe_recover(ctx, iteration, seq, audit).await;
692        self.observe_response(
693            ctx,
694            iteration,
695            seq,
696            "error",
697            0,
698            text_bytes,
699            reasoning_bytes,
700            usage,
701            Some(audit),
702        )
703        .await;
704    }
705
706    async fn run_iteration(
707        &self,
708        ctx: &DrainCtx,
709        drain_iterations: &mut usize,
710    ) -> Result<Flow, LoopError> {
711        // 1. Promote newly eligible inputs at this safe boundary (we are
712        //    between provider turns here; DrainCtx refuses otherwise —
713        //    steer never interleaves an in-flight turn).
714        let taken = ctx.take_eligible_inputs().await?;
715
716        // 2. Rebuild the truth and derive the model context (A2/A3).
717        let mut events = ctx.events().await?;
718
719        // (CONFIRMATION-MODEL §7) Durable answers are applied here — in
720        // call order — before any provider request. A pending ask with no
721        // decision ends the turn without a model call: the engine derives
722        // `awaiting_input` from the stream and the session waits.
723        let mut pending = pending_calls(&events);
724        if !pending.is_empty() {
725            let decisions = confirmations(&events);
726            for (call, decision) in confirmable(&pending, &decisions) {
727                self.apply_confirmation(ctx, &call, &decision).await?;
728            }
729            events = ctx.events().await?;
730            pending = pending_calls(&events);
731            if !pending.is_empty() {
732                tracing::debug!(
733                    session = %ctx.session().0,
734                    pending = pending.len(),
735                    "awaiting confirmation: settling without a provider call"
736                );
737                return Ok(Flow::Deferred);
738            }
739        }
740
741        let binding = self.binding_for(ctx, &mut events).await?;
742        let messages = derive_model_context(&events)?;
743
744        // (ADR-025) A resident episode with no eligible input and a context
745        // that ends on an assistant message has nothing to judge: settle
746        // (the RouterDriver parks) without spending a provider call. A
747        // tool-result continuation ends on `tool` and still proceeds; a new
748        // input is `taken` and still proceeds. Non-resident loops are
749        // untouched.
750        if resident_empty_batch(
751            self.config.budget_scope,
752            taken.is_empty(),
753            messages.last().map(|m| m.role.as_str()),
754        ) {
755            tracing::debug!(
756                session = %ctx.session().0,
757                "resident empty batch: settling without a provider call (ADR-025)"
758            );
759            return Ok(Flow::Settled);
760        }
761
762        // 3. Iteration counter — derived from the stream, so the budget
763        //    survives episodes and restarts (constraint 1 in spirit).
764        let iteration = events
765            .iter()
766            .filter(|ev| matches!(ev.kind, EventKind::TurnStart))
767            .count();
768        let used = self.config.budget_scope.used(iteration, *drain_iterations);
769        if used >= self.config.max_iterations {
770            let reason = match self.config.budget_scope {
771                BudgetScope::Lifetime => {
772                    format!("iteration budget exhausted after {iteration} turns")
773                }
774                BudgetScope::PerEpisode => format!(
775                    "{} after {used} turns",
776                    kian_core::seams::EPISODE_BUDGET_STOP_REASON_PREFIX
777                ),
778            };
779            return Ok(Flow::Stopped(reason));
780        }
781        if self.config.budget_scope == BudgetScope::PerEpisode {
782            *drain_iterations += 1;
783        }
784
785        // 4. The provider turn. begin/end bracket every outcome (including
786        //    soft failures) so turn events stay balanced in the stream.
787        ctx.begin_turn_with(json!({"iteration": iteration})).await?;
788        let turn = self
789            .provider_turn(ctx, &binding, &messages, iteration)
790            .await;
791        let usage = turn.usage.as_ref();
792        let flow = match turn.result {
793            Ok(TurnOutcome::ToolCalls(n)) => {
794                let mut payload = json!({"iteration": iteration, "tool_calls": n});
795                if let Some(u) = usage {
796                    payload["usage"] = u.clone();
797                }
798                ctx.end_turn_with(payload).await?;
799                return Ok(Flow::TurnDone);
800            }
801            // Final answer + empty inbox = honest settle. New inputs
802            // (a folded steer) keep the loop going instead.
803            Ok(TurnOutcome::FinalAnswer) => {
804                if ctx.has_eligible_inputs().await? {
805                    Flow::TurnDone
806                } else {
807                    Flow::Settled
808                }
809            }
810            Err(TurnError::Soft { reason, audit }) => {
811                let mut payload = json!({
812                    "iteration": iteration,
813                    "outcome": "soft_failure",
814                    "error": audit,
815                });
816                if let Some(u) = usage {
817                    payload["usage"] = u.clone();
818                }
819                let _ = ctx.end_turn_with(payload).await;
820                return Ok(Flow::Soft(reason));
821            }
822            Err(TurnError::Fatal { error, audit }) => {
823                let mut payload = json!({
824                    "iteration": iteration,
825                    "outcome": "error",
826                    "error": audit,
827                });
828                if let Some(u) = usage {
829                    payload["usage"] = u.clone();
830                }
831                let _ = ctx.end_turn_with(payload).await;
832                return Err(error);
833            }
834        };
835        let mut payload = json!({"iteration": iteration, "outcome": "final_answer"});
836        if let Some(u) = usage {
837            payload["usage"] = u.clone();
838        }
839        ctx.end_turn_with(payload).await?;
840        Ok(flow)
841    }
842
843    /// Applies one durable answer (CONFIRMATION-MODEL §5, ADR-033):
844    /// approve invokes the frozen call and appends its real result;
845    /// reject (or an expired answer, already transformed to a reject by
846    /// the server) appends the honest-error result. Both carry the
847    /// additive `confirmation` provenance **outside `content`** — the
848    /// model-visible wire shape is unchanged.
849    async fn apply_confirmation(
850        &self,
851        ctx: &DrainCtx,
852        call: &PendingCall,
853        decision: &ConfirmIntent,
854    ) -> Result<(), LoopError> {
855        let result = match decision.decision {
856            ConfirmDecision::Approve => {
857                let tool_call = ToolCall {
858                    id: call.call_id.clone(),
859                    name: call.tool.clone(),
860                    arguments: call.arguments.clone(),
861                };
862                match self.tools.invoke(tool_call).await {
863                    Ok(r) => r,
864                    // Tool-level failure is an honest error result, never
865                    // a loop abort (the deny arm's discipline).
866                    Err(e) => ToolResult {
867                        call_id: call.call_id.clone(),
868                        output: json!({"error": e.to_string()}),
869                        is_error: true,
870                        redactions: Vec::new(),
871                    },
872                }
873            }
874            ConfirmDecision::Reject => ToolResult {
875                call_id: call.call_id.clone(),
876                output: if decision.expired {
877                    json!({
878                        "error": "confirmation expired",
879                        "policy": "ask",
880                        "expired": true
881                    })
882                } else {
883                    match &decision.reason {
884                        Some(reason) => json!({
885                            "error": "permission denied by user",
886                            "policy": "ask",
887                            "reason": reason
888                        }),
889                        None => json!({
890                            "error": "permission denied by user",
891                            "policy": "ask"
892                        }),
893                    }
894                },
895                is_error: true,
896                redactions: Vec::new(),
897            },
898        };
899        let payload = tool_result_payload_confirmed(&result, decision);
900        ctx.append(EventKind::ToolResult, payload).await?;
901        Ok(())
902    }
903
904    /// Resolves the session's slot binding, appending `slot/binding`
905    /// events at first use (the binding is then fixed for the session's
906    /// lifetime and rebuildable by replay, ADR-006).
907    async fn binding_for(
908        &self,
909        ctx: &DrainCtx,
910        events: &mut Vec<Event>,
911    ) -> Result<SlotBinding, LoopError> {
912        let session = ctx.session();
913        if let Ok(slots) = SessionSlots::replay(session, events)
914            && slots.binding(&self.config.slot).is_ok()
915        {
916            return Ok(slots.binding(&self.config.slot)?.clone());
917        }
918        let fresh = SlotResolver::from_agent_def(&self.agent).bind_session(session);
919        for payload in fresh.binding_payloads() {
920            ctx.append(EventKind::SlotBinding, payload).await?;
921        }
922        // Refresh the projection source so the appended bindings are part
923        // of the truth this drain derives from.
924        *events = ctx.events().await?;
925        Ok(fresh.binding(&self.config.slot)?.clone())
926    }
927
928    /// Runs one provider turn: persist the A2 audit copy, call the slot
929    /// (with fallback traversal), assemble the streamed response, then
930    /// either dispatch tool calls (log-before-execute) or return a final
931    /// answer. The returned [`TurnResult`] carries the last non-null
932    /// provider usage observed across the turn, on every path.
933    async fn provider_turn(
934        &self,
935        ctx: &DrainCtx,
936        binding: &SlotBinding,
937        messages: &[Message],
938        iteration: usize,
939    ) -> TurnResult {
940        let target = binding.target.clone();
941
942        // Deterministic tool order (the request body freezes the tools
943        // array order — serialization contract).
944        let mut schemas = self.tools.schemas();
945        schemas.sort_by(|a, b| a.name.cmp(&b.name));
946        let chat: Vec<ChatMessage> = messages.iter().filter_map(to_chat_message).collect();
947
948        // A2: the audit copy of the exact request is durable BEFORE the
949        // provider is called.
950        let body = build_chat_body(&target.model, &chat, &schemas);
951        let step_request = ctx
952            .append(
953                EventKind::StepRequest,
954                json!({
955                    "slot": self.config.slot.0,
956                    "provider": target.provider,
957                    "model": target.model,
958                    "iteration": iteration,
959                    "body": body,
960                }),
961            )
962            .await;
963        let step_request_seq = match step_request {
964            Ok(ev) => ev.seq,
965            Err(e) => {
966                let fatal = TurnError::fatal(e, self.policy.as_ref());
967                // Rows (c)+(f): the turn settles `error` with its audit.
968                if let TurnError::Fatal { audit, .. } = &fatal {
969                    self.observe_fatal(ctx, iteration, 0, audit, 0, 0, None)
970                        .await;
971                }
972                return TurnResult {
973                    result: Err(fatal),
974                    usage: None,
975                };
976            }
977        };
978        // Port (b) — `turn/request` (§4.2): fires immediately after the
979        // persisted primary body exists, exactly once per provider turn
980        // (never per fallback attempt — `complete_turn`'s rebuilt bodies
981        // are provider-layer internals, not second `step/request`s).
982        self.observe_request(
983            ctx,
984            binding,
985            chat.len(),
986            &schemas,
987            iteration,
988            &body,
989            step_request_seq,
990        )
991        .await;
992
993        // complete_turn rebuilds the body per (fallback) target so the
994        // model name always matches the provider actually called.
995        let slot = self.config.slot.clone();
996        let build_chat = chat.clone();
997        let build_schemas = schemas.clone();
998        let build = Arc::new(move |t: &kian_core::model::SlotTarget| ModelRequest {
999            slot: slot.clone(),
1000            body: build_chat_body(&t.model, &build_chat, &build_schemas),
1001        });
1002        let mut stream = complete_turn(
1003            Arc::clone(&self.registry),
1004            self.config.slot.clone(),
1005            binding.clone(),
1006            build,
1007            Arc::new(CtxSlotSink { ctx: ctx.clone() }),
1008        );
1009
1010        // Assemble the streamed deltas. Usage-only chunks carry a
1011        // Null delta — they never assemble content, but the last
1012        // non-null usage is captured across the whole turn, including an
1013        // attempt that emitted usage before failing.
1014        let mut text = String::new();
1015        let mut reasoning = String::new();
1016        let mut calls: BTreeMap<u64, CallAcc> = BTreeMap::new();
1017        let mut usage: Option<Value> = None;
1018        let mut stream_error: Option<ProviderError> = None;
1019        while let Some(item) = stream.next().await {
1020            match item {
1021                Ok(chunk) => {
1022                    if let Some(u) = chunk.usage.as_ref().filter(|u| !u.is_null()) {
1023                        usage = Some(u.clone()); // last wins
1024                    }
1025                    if !chunk.delta.is_null() {
1026                        assemble_delta(&chunk.delta, &mut text, &mut reasoning, &mut calls);
1027                    }
1028                }
1029                Err(e) => {
1030                    stream_error = Some(e);
1031                    break;
1032                }
1033            }
1034        }
1035        // Byte counts for the §3.2.4 view fields — captured before the
1036        // content assembly moves the strings.
1037        let text_bytes = text.len() as u64;
1038        let reasoning_bytes = reasoning.len() as u64;
1039        if let Some(e) = stream_error {
1040            let class = error_class(&e);
1041            let action = consult_policy(self.policy.as_ref(), class);
1042            let note = action_note(action);
1043            let audit = recovery_audit(self.policy.as_ref(), provider_error_class(&e));
1044            // Rows (f)+(c): the resolution observes, the settled turn
1045            // reports `soft_failure` with the same audit object.
1046            self.observe_recover(ctx, iteration, step_request_seq, &audit)
1047                .await;
1048            self.observe_response(
1049                ctx,
1050                iteration,
1051                step_request_seq,
1052                "soft_failure",
1053                0,
1054                text_bytes,
1055                reasoning_bytes,
1056                usage.as_ref(),
1057                Some(&audit),
1058            )
1059            .await;
1060            return TurnResult {
1061                result: Err(TurnError::Soft {
1062                    reason: format!("provider error ({class}): {e}{note}"),
1063                    audit,
1064                }),
1065                usage,
1066            };
1067        }
1068        if text.is_empty() && calls.is_empty() {
1069            // Constraint 7: an empty model response is a soft failure
1070            // routed to the recovery policy — never a completion.
1071            let action = consult_policy(self.policy.as_ref(), CLASS_EMPTY_RESPONSE);
1072            let note = action_note(action);
1073            let audit = recovery_audit(
1074                self.policy.as_ref(),
1075                kian_orchestrator::recovery::ErrorClass::EmptyResponse,
1076            );
1077            self.observe_recover(ctx, iteration, step_request_seq, &audit)
1078                .await;
1079            self.observe_response(
1080                ctx,
1081                iteration,
1082                step_request_seq,
1083                "soft_failure",
1084                0,
1085                0,
1086                0,
1087                usage.as_ref(),
1088                Some(&audit),
1089            )
1090            .await;
1091            return TurnResult {
1092                result: Err(TurnError::Soft {
1093                    reason: format!("empty model response{note}"),
1094                    audit,
1095                }),
1096                usage,
1097            };
1098        }
1099
1100        let tool_calls: Vec<ToolCall> = calls.into_values().map(CallAcc::finish).collect();
1101        let mut content = json!({"text": text});
1102        if !tool_calls.is_empty() {
1103            content["tool_calls"] = Value::Array(
1104                tool_calls
1105                    .iter()
1106                    .map(|c| json!({"id": c.id, "name": c.name, "arguments": c.arguments}))
1107                    .collect(),
1108            );
1109        }
1110        if !reasoning.is_empty() {
1111            // ADR-022: thinking-mode reasoning is context — persisted
1112            // verbatim and replayed by `assistant_message` below.
1113            content["reasoning_content"] = Value::String(reasoning);
1114        }
1115        if let Err(e) = ctx
1116            .append(
1117                EventKind::AssistantMessage,
1118                json!({"role": "assistant", "content": content}),
1119            )
1120            .await
1121        {
1122            let fatal = TurnError::fatal(e, self.policy.as_ref());
1123            if let TurnError::Fatal { audit, .. } = &fatal {
1124                self.observe_fatal(
1125                    ctx,
1126                    iteration,
1127                    step_request_seq,
1128                    audit,
1129                    text_bytes,
1130                    reasoning_bytes,
1131                    usage.as_ref(),
1132                )
1133                .await;
1134            }
1135            return TurnResult {
1136                result: Err(fatal),
1137                usage,
1138            };
1139        }
1140
1141        if tool_calls.is_empty() {
1142            // Row (c) — the settled final-answer turn (§4.3).
1143            self.observe_response(
1144                ctx,
1145                iteration,
1146                step_request_seq,
1147                "final_answer",
1148                0,
1149                text_bytes,
1150                reasoning_bytes,
1151                usage.as_ref(),
1152                None,
1153            )
1154            .await;
1155            return TurnResult {
1156                result: Ok(TurnOutcome::FinalAnswer),
1157                usage,
1158            };
1159        }
1160
1161        let n = tool_calls.len();
1162        // Log-before-execute (invariant 1): each `tool/call` event is
1163        // durable before `invoke` runs — for BOTH arms. The deny arm
1164        // logs the call (with its deny provenance) and then never
1165        // invokes; the honest audit record of the attempted call exists
1166        // either way.
1167        for call in tool_calls {
1168            // (ADR-015): evaluate the per-call permission once,
1169            // before the `tool/call` append. `None` = no table
1170            // configured → the legacy byte-identical payload, invoke
1171            // as today.
1172            let decision = evaluate_permission(&self.config.permissions, &call.name);
1173            // Port (d) — `tool/pre` (§4.4 step 2): consulted
1174            // **unconditionally**, after the declarative table is
1175            // evaluated and before the `tool/call` append / `invoke` —
1176            // a policy-denied call is still a call the port is defined
1177            // over, and the payload already carries the declarative
1178            // verdict (`permission.evaluated/policy`). A hook denial
1179            // wins over the declarative one by the existing
1180            // first-deny order — end-to-end: the hook-denied log AND
1181            // the honest-error result both name the plugin (§4.4
1182            // steps 3–4); an abstaining hook leaves the declarative
1183            // decision standing.
1184            let hook_verdict = self
1185                .consult_tool_pre(ctx, &call, iteration, step_request_seq, decision)
1186                .await;
1187            let appended = match hook_verdict {
1188                kian_plugin::hooks::ToolVerdict::Deny {
1189                    ref plugin,
1190                    ref reason,
1191                } => {
1192                    // §4.4 step 3: the hook denial is logged before any
1193                    // effect, with `policy:"hook"` provenance naming the
1194                    // denying plugin (§16.1's payload value — P4 owns
1195                    // the EVENT-MODEL row).
1196                    ctx.append(
1197                        EventKind::ToolCall,
1198                        tool_call_payload_hook_denied(&call, plugin, reason),
1199                    )
1200                    .await
1201                }
1202                _ => {
1203                    ctx.append(EventKind::ToolCall, tool_call_payload(&call, decision))
1204                        .await
1205                }
1206            };
1207            let call_seq = match appended {
1208                Ok(ev) => ev.seq,
1209                Err(e) => {
1210                    let fatal = TurnError::fatal(e, self.policy.as_ref());
1211                    if let TurnError::Fatal { audit, .. } = &fatal {
1212                        self.observe_fatal(
1213                            ctx,
1214                            iteration,
1215                            step_request_seq,
1216                            audit,
1217                            text_bytes,
1218                            reasoning_bytes,
1219                            usage.as_ref(),
1220                        )
1221                        .await;
1222                    }
1223                    return TurnResult {
1224                        result: Err(fatal),
1225                        usage,
1226                    };
1227                }
1228            };
1229            // §4.4 step 4: a hook-denied call never reaches
1230            // `self.tools.invoke`; the model receives the honest-error
1231            // `tool/result` naming the plugin and its reason. The hook
1232            // denial also wins the RESULT on the coincident arm (a
1233            // call the declarative table denies AND a `veto:tool`
1234            // plugin denies): first-deny order means the plugin's
1235            // denial is the one the pair records end-to-end — the
1236            // `tool/call` above (`policy:"hook"`, the plugin's
1237            // reason) and this `tool/result` name the same denier,
1238            // never one each.
1239            if let kian_plugin::hooks::ToolVerdict::Deny {
1240                ref plugin,
1241                ref reason,
1242            } = hook_verdict
1243            {
1244                let denied = ToolResult {
1245                    call_id: call.id.clone(),
1246                    output: json!({
1247                        "error": format!("denied by plugin {plugin}: {reason}"),
1248                        "policy": "hook"
1249                    }),
1250                    is_error: true,
1251                    redactions: Vec::new(),
1252                };
1253                if let Err(e) = ctx
1254                    .append(EventKind::ToolResult, tool_result_payload(&denied))
1255                    .await
1256                {
1257                    let fatal = TurnError::fatal(e, self.policy.as_ref());
1258                    if let TurnError::Fatal { audit, .. } = &fatal {
1259                        self.observe_fatal(
1260                            ctx,
1261                            iteration,
1262                            call_seq,
1263                            audit,
1264                            text_bytes,
1265                            reasoning_bytes,
1266                            usage.as_ref(),
1267                        )
1268                        .await;
1269                    }
1270                    return TurnResult {
1271                        result: Err(fatal),
1272                        usage,
1273                    };
1274                }
1275                self.observe_tool_post(ctx, &denied, &call.name, call_seq)
1276                    .await;
1277                continue;
1278            }
1279            // Ask (ADR-033): never invoked here. The call stays pending
1280            // until a control row answers it; the drain ends
1281            // `awaiting_input` and the answer path applies it.
1282            if matches!(decision, Some(PermissionDecision::Ask)) {
1283                continue;
1284            }
1285            // Declarative deny (the table alone denied the call): no
1286            // tool side effect either. The model sees an honest error
1287            // result next turn and reacts — a denied call is a tool
1288            // failure, never a loop abort.
1289            if let Some(denied) = declared_denial(&call, decision) {
1290                if let Err(e) = ctx
1291                    .append(EventKind::ToolResult, tool_result_payload(&denied))
1292                    .await
1293                {
1294                    let fatal = TurnError::fatal(e, self.policy.as_ref());
1295                    if let TurnError::Fatal { audit, .. } = &fatal {
1296                        self.observe_fatal(
1297                            ctx,
1298                            iteration,
1299                            call_seq,
1300                            audit,
1301                            text_bytes,
1302                            reasoning_bytes,
1303                            usage.as_ref(),
1304                        )
1305                        .await;
1306                    }
1307                    return TurnResult {
1308                        result: Err(fatal),
1309                        usage,
1310                    };
1311                }
1312                // Port (d′) — `tool/post` fires on the declared-denial
1313                // arm too (§4.4 step 5: the uniform surface).
1314                self.observe_tool_post(ctx, &denied, &call.name, call_seq)
1315                    .await;
1316                continue;
1317            }
1318            let result = match self.tools.invoke(call.clone()).await {
1319                Ok(r) => r,
1320                Err(e) => {
1321                    // Tool-level failure is an honest error result, not a
1322                    // loop abort: the model sees the failure and reacts.
1323                    ToolResult {
1324                        call_id: call.id.clone(),
1325                        output: json!({"error": e.to_string()}),
1326                        is_error: true,
1327                        redactions: Vec::new(),
1328                    }
1329                }
1330            };
1331            // redaction provenance rides the payload OUTSIDE
1332            // `content` — the model-visible wire shape (and therefore
1333            // request bytes and prefix cache) never sees it; the key is
1334            // omitted entirely when nothing was redacted.
1335            let result_seq = match ctx
1336                .append(EventKind::ToolResult, tool_result_payload(&result))
1337                .await
1338            {
1339                Ok(ev) => ev.seq,
1340                Err(e) => {
1341                    let fatal = TurnError::fatal(e, self.policy.as_ref());
1342                    if let TurnError::Fatal { audit, .. } = &fatal {
1343                        self.observe_fatal(
1344                            ctx,
1345                            iteration,
1346                            call_seq,
1347                            audit,
1348                            text_bytes,
1349                            reasoning_bytes,
1350                            usage.as_ref(),
1351                        )
1352                        .await;
1353                    }
1354                    return TurnResult {
1355                        result: Err(fatal),
1356                        usage,
1357                    };
1358                }
1359            };
1360            // Port (d′) — `tool/post` after the executed call's
1361            // `tool/result` append (§4.4 step 5).
1362            self.observe_tool_post(ctx, &result, &call.name, result_seq)
1363                .await;
1364        }
1365        // Row (c) — the settled tool-calls turn (§4.3): dispatched once
1366        // per settled provider turn, after its tool dispatches.
1367        self.observe_response(
1368            ctx,
1369            iteration,
1370            step_request_seq,
1371            "tool_calls",
1372            n as u64,
1373            text_bytes,
1374            reasoning_bytes,
1375            usage.as_ref(),
1376            None,
1377        )
1378        .await;
1379        TurnResult {
1380            result: Ok(TurnOutcome::ToolCalls(n)),
1381            usage,
1382        }
1383    }
1384}
1385
1386// ---------------------------------------------------------------------------
1387// Support types
1388// ---------------------------------------------------------------------------
1389
1390impl TurnError {
1391    /// A hard (store/append) failure with its recovery audit. The
1392    /// class follows the existing pure classifier's vocabulary
1393    /// (`Engine` → `store_failure`; context/slot errors are outside it
1394    /// and classify as `unknown`), the action comes from the table.
1395    fn fatal(e: EngineError, policy: &dyn RecoveryPolicySource) -> Self {
1396        let error = LoopError::Engine(e);
1397        let audit = recovery_audit(policy, loop_error_class(&error));
1398        Self::Fatal { error, audit }
1399    }
1400}
1401
1402/// The class of a loop-level hard error, aligned with the existing pure
1403/// classifier (`recovery::classify`): engine failures are store
1404/// failures; context-projection and slot-resolution errors sit outside
1405/// its vocabulary and classify as `unknown` — the same result
1406/// `classify(RecoveryError::Unknown(_))` yields.
1407fn loop_error_class(e: &LoopError) -> kian_orchestrator::recovery::ErrorClass {
1408    match e {
1409        LoopError::Engine(_) => kian_orchestrator::recovery::ErrorClass::StoreFailure,
1410        LoopError::Context(_) | LoopError::Slot(_) => {
1411            kian_orchestrator::recovery::ErrorClass::Unknown
1412        }
1413    }
1414}
1415
1416/// The class of a provider error via the existing pure classifier
1417/// `classify(RecoveryError::Provider(e))`.
1418fn provider_error_class(e: &ProviderError) -> kian_orchestrator::recovery::ErrorClass {
1419    kian_orchestrator::recovery::classify(
1420        &kian_orchestrator::recovery::RecoveryError::Provider(e.clone()),
1421        &kian_orchestrator::recovery::ClassifyCtx { attempt: 0 },
1422    )
1423}
1424
1425/// The `turn/end` `error` audit object: the pure classifier's class
1426/// name plus the declarative policy's disposition name — `"none"` when
1427/// no rule covers the class (the honest no-rule spelling).
1428fn recovery_audit(
1429    policy: &dyn RecoveryPolicySource,
1430    class: kian_orchestrator::recovery::ErrorClass,
1431) -> Value {
1432    let action = consult_policy(policy, class.name());
1433    json!({
1434        "class": class.name(),
1435        "action": action_name(action.as_ref()),
1436    })
1437}
1438
1439/// The disposition-name spelling of a policy action (the `ActionDef`
1440/// names of `kian.yaml`), or `"none"` when no rule matched.
1441fn action_name(action: Option<&RecoveryAction>) -> &'static str {
1442    match action {
1443        None => "none",
1444        Some(RecoveryAction::BackoffRetry { .. }) => "backoff_retry",
1445        Some(RecoveryAction::CompressThenRetry) => "compress_then_retry",
1446        Some(RecoveryAction::Failover) => "failover",
1447        Some(RecoveryAction::InterruptAsk) => "interrupt_ask",
1448        Some(RecoveryAction::Fail) => "fail",
1449    }
1450}
1451
1452/// Persists `slot/fallback` payloads through the drain ctx (one durable
1453/// event per fallback switch, before the fallback provider is called —
1454/// ordering).
1455struct CtxSlotSink {
1456    ctx: DrainCtx,
1457}
1458
1459impl SlotEventSink for CtxSlotSink {
1460    fn persist_fallback(
1461        &self,
1462        payload: Value,
1463    ) -> futures::future::BoxFuture<'static, Result<(), String>> {
1464        let ctx = self.ctx.clone();
1465        Box::pin(async move {
1466            ctx.append(EventKind::SlotFallback, payload)
1467                .await
1468                .map(|_| ())
1469                .map_err(|e| e.to_string())
1470        })
1471    }
1472}
1473
1474/// Accumulates one streamed tool call (openai streaming shape).
1475struct CallAcc {
1476    id: String,
1477    name: String,
1478    arguments: String,
1479}
1480
1481impl CallAcc {
1482    fn finish(self) -> ToolCall {
1483        let arguments = serde_json::from_str::<Value>(&self.arguments)
1484            .unwrap_or_else(|_| Value::String(self.arguments.clone()));
1485        ToolCall {
1486            id: self.id,
1487            name: self.name,
1488            arguments,
1489        }
1490    }
1491}
1492
1493/// Folds one streamed delta into the assembled turn. Content fragments
1494/// concatenate; tool-call fragments accumulate by stream index.
1495fn assemble_delta(
1496    delta: &Value,
1497    text: &mut String,
1498    reasoning: &mut String,
1499    calls: &mut BTreeMap<u64, CallAcc>,
1500) {
1501    if let Some(fragment) = delta.get("content").and_then(Value::as_str) {
1502        text.push_str(fragment);
1503    }
1504    if let Some(fragment) = delta.get("reasoning_content").and_then(Value::as_str) {
1505        reasoning.push_str(fragment);
1506    }
1507    if let Some(list) = delta.get("tool_calls").and_then(Value::as_array) {
1508        for entry in list {
1509            let index = entry.get("index").and_then(Value::as_u64).unwrap_or(0);
1510            let slot = calls.entry(index).or_insert_with(|| CallAcc {
1511                id: String::new(),
1512                name: String::new(),
1513                arguments: String::new(),
1514            });
1515            if let Some(id) = entry.get("id").and_then(Value::as_str) {
1516                slot.id = id.to_string();
1517            }
1518            if let Some(name) = entry.pointer("/function/name").and_then(Value::as_str) {
1519                slot.name.push_str(name);
1520            }
1521            if let Some(args) = entry.pointer("/function/arguments").and_then(Value::as_str) {
1522                slot.arguments.push_str(args);
1523            }
1524        }
1525    }
1526}
1527
1528/// Converts a projected [`Message`] into the request-body chat shape
1529/// (dialect v2). Plain string content passes through unchanged
1530/// (byte-identical to dialect v1); structured content is translated to
1531/// the strict openai wire shape — anything else is serialized compactly,
1532/// deterministic under the frozen serialization (lexicographic keys).
1533///
1534/// - `role:"tool"` `{call_id, output, is_error}` → `{role:"tool",
1535///   tool_call_id, content: <output as a JSON string>}` (the `is_error`
1536///   flag stays in the event stream; the wire carries the output only,
1537///   the shape verified live against the real DeepSeek API).
1538/// - assistant `{"text", "tool_calls": [...]}` → `{role:"assistant",
1539///   content: <text or null>, tool_calls: [{id, type:"function",
1540///   function:{name, arguments: <JSON string>}}]}`.
1541/// - assistant `{"id", "name", "arguments"}` (the per-call `tool/call`
1542///   transcript duplicate) → **dropped**: the enclosing assistant turn's
1543///   `tool_calls` already carries the same call id, and strict endpoints
1544///   reject the duplicate. Returns `None`.
1545///
1546/// Public: `kian session replay` re-derives the model context
1547/// from the event stream and must rebuild the *exact* chat shape the
1548/// loop sent, so the A2 byte-identity check compares like with like.
1549/// This conversion is part of the frozen request-serialization contract
1550/// (constraint 3) — changing it invalidates every replay comparison and
1551/// every provider prefix cache.
1552pub fn to_chat_message(m: &Message) -> Option<ChatMessage> {
1553    match m.role.as_str() {
1554        "tool" => Some(tool_result_message(&m.content)),
1555        "assistant" => assistant_message(&m.content),
1556        _ => Some(string_or_compact(&m.role, &m.content)),
1557    }
1558}
1559
1560/// The permission decision for one tool call (ADR-015). Evaluated
1561/// once per call, before the `tool/call` append.
1562#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1563pub(crate) enum PermissionDecision {
1564    /// Explicitly allowed by the configured table.
1565    AllowConfigured,
1566    /// Not named by the (non-empty) table — the default allow.
1567    AllowDefault,
1568    /// Explicitly denied by the configured table: no invocation.
1569    Deny,
1570    /// Deferred to a person (ADR-033): logged, never invoked; the drain
1571    /// ends `awaiting_input` and the answer arrives as a control row.
1572    Ask,
1573}
1574
1575/// The deny `reason` string on the provenance object (closed).
1576const PERMISSION_DENY_REASON: &str = "tool_denied_by_policy";
1577
1578/// Evaluates the per-call permission table (ADR-015):
1579///
1580/// - empty table → `None`: no table is configured, the `tool/call`
1581///   payload stays byte-identical to the legacy shape (constraint 3 —
1582///   cache-byte stability) and the call invokes as today;
1583/// - non-empty table → every call gets a decision: an explicit entry is
1584///   `configured` (allow or deny), an unnamed tool falls through to the
1585///   **default allow** — provenance is recorded on the action either way
1586///   (provenance-on-the-action), not only on deny.
1587fn evaluate_permission(
1588    permissions: &BTreeMap<String, Permission>,
1589    tool: &str,
1590) -> Option<PermissionDecision> {
1591    if permissions.is_empty() {
1592        return None;
1593    }
1594    match permissions.get(tool) {
1595        Some(Permission::Allow) => Some(PermissionDecision::AllowConfigured),
1596        Some(Permission::Deny) => Some(PermissionDecision::Deny),
1597        Some(Permission::Ask) => Some(PermissionDecision::Ask),
1598        None => Some(PermissionDecision::AllowDefault),
1599    }
1600}
1601
1602/// The declared-permission deny arm's honest-error result (ADR-015):
1603/// `Some` only when the declarative table denied this call — the
1604/// payload shape the model reacts to, unchanged from the pre-plugin
1605/// loop.
1606fn declared_denial(call: &ToolCall, decision: Option<PermissionDecision>) -> Option<ToolResult> {
1607    matches!(decision, Some(PermissionDecision::Deny)).then(|| ToolResult {
1608        call_id: call.id.clone(),
1609        output: json!({
1610            "error": format!("permission denied by policy: {}", call.name),
1611            "policy": "deny"
1612        }),
1613        is_error: true,
1614        redactions: Vec::new(),
1615    })
1616}
1617
1618/// The `tool/call` event payload: the frozen `{role, content}` shape
1619/// plus, only when a permission table is configured, the additive
1620/// top-level `permission` provenance key **outside `content`** — the
1621/// projection reads `role`/`content` only, so request bytes are
1622/// identical with and without it.
1623fn tool_call_payload(call: &ToolCall, decision: Option<PermissionDecision>) -> Value {
1624    let mut payload = json!({
1625        "role": "assistant",
1626        "content": {"id": call.id, "name": call.name, "arguments": call.arguments}
1627    });
1628    if let Some(decision) = decision {
1629        payload["permission"] = match decision {
1630            PermissionDecision::AllowConfigured => json!({
1631                "evaluated": "allow", "policy": "configured", "matched": call.name
1632            }),
1633            PermissionDecision::AllowDefault => json!({
1634                "evaluated": "allow", "policy": "default", "matched": call.name
1635            }),
1636            PermissionDecision::Deny => json!({
1637                "evaluated": "deny",
1638                "policy": "configured",
1639                "matched": call.name,
1640                "reason": PERMISSION_DENY_REASON
1641            }),
1642            PermissionDecision::Ask => json!({
1643                "evaluated": "ask",
1644                "policy": "configured",
1645                "matched": call.name
1646            }),
1647        };
1648    }
1649    payload
1650}
1651
1652/// The `tool/call` payload of a **hook-denied** call (§4.4 step 3 +
1653/// §16.1): log-before-execute holds for hook denials too — the call is
1654/// logged, with `permission.policy = "hook"` and `matched` naming the
1655/// denying `<plugin>:<hook>`, before the honest-error result is
1656/// appended and **before any effect** (the invoke never runs). The
1657/// `policy: "hook"` payload value is the one EVENT-MODEL amendment of
1658/// this round (P4's card owns the doc + goldens).
1659fn tool_call_payload_hook_denied(call: &ToolCall, plugin: &str, reason: &str) -> Value {
1660    let mut payload = json!({
1661        "role": "assistant",
1662        "content": {"id": call.id, "name": call.name, "arguments": call.arguments}
1663    });
1664    payload["permission"] = json!({
1665        "evaluated": "deny",
1666        "policy": "hook",
1667        "matched": format!("{plugin}:tool/pre"),
1668        "reason": reason,
1669    });
1670    payload
1671}
1672
1673/// The declarative gate's decision rendered as the §3.2.5
1674/// `permission` view object (ADR-015 provenance shape; `reason` rides
1675/// only a deny). `None` (no table configured) renders the default-allow
1676/// row — the decision the call actually runs under.
1677fn permission_view(
1678    call: &ToolCall,
1679    decision: Option<PermissionDecision>,
1680) -> kian_plugin::hooks::PermissionView {
1681    match decision {
1682        Some(PermissionDecision::AllowConfigured) => kian_plugin::hooks::PermissionView {
1683            evaluated: "allow".to_string(),
1684            policy: "configured".to_string(),
1685            matched: call.name.clone(),
1686            reason: None,
1687        },
1688        Some(PermissionDecision::Deny) => kian_plugin::hooks::PermissionView {
1689            evaluated: "deny".to_string(),
1690            policy: "configured".to_string(),
1691            matched: call.name.clone(),
1692            reason: Some(PERMISSION_DENY_REASON.to_string()),
1693        },
1694        Some(PermissionDecision::Ask) => kian_plugin::hooks::PermissionView {
1695            evaluated: "ask".to_string(),
1696            policy: "configured".to_string(),
1697            matched: call.name.clone(),
1698            reason: None,
1699        },
1700        Some(PermissionDecision::AllowDefault) | None => kian_plugin::hooks::PermissionView {
1701            evaluated: "allow".to_string(),
1702            policy: "default".to_string(),
1703            matched: call.name.clone(),
1704            reason: None,
1705        },
1706    }
1707}
1708
1709/// The `tool/result` event payload: `{role, content}` plus, only when
1710/// the exec redactor scrubbed something, the provenance report as
1711/// an additive top-level `redactions` key **outside `content`** — the
1712/// model-visible wire shape (`to_chat_message` reads `content` only) is
1713/// byte-identical either way, so request bytes and the provider prefix
1714/// cache never see the report.
1715fn tool_result_payload(result: &ToolResult) -> Value {
1716    let mut payload = json!({
1717        "role": "tool",
1718        "content": {
1719            "call_id": result.call_id,
1720            "output": result.output,
1721            "is_error": result.is_error
1722        }
1723    });
1724    if !result.redactions.is_empty() {
1725        // A failed serialization degrades to omitting the key (the
1726        // report is provenance, never correctness-critical).
1727        if let Ok(report) = serde_json::to_value(&result.redactions) {
1728            payload["redactions"] = report;
1729        }
1730    }
1731    payload
1732}
1733
1734/// [`tool_result_payload`] plus the additive `confirmation` provenance
1735/// (CONFIRMATION-MODEL A5) recording which decision produced this result
1736/// — outside `content`, audit-only.
1737fn tool_result_payload_confirmed(result: &ToolResult, decision: &ConfirmIntent) -> Value {
1738    let mut payload = tool_result_payload(result);
1739    let mut provenance = json!({
1740        "call_id": result.call_id,
1741        "decision": decision.decision.as_str(),
1742        "requested_by": decision.requested_by,
1743        "answered_at_ms": decision.answered_at_ms,
1744    });
1745    if decision.expired {
1746        provenance["expired"] = json!(true);
1747    }
1748    payload["confirmation"] = provenance;
1749    payload
1750}
1751
1752/// `{role, content}` from a plain string, or the compact serialization
1753/// of any other JSON shape (the v1 fallback, unchanged).
1754fn string_or_compact(role: &str, content: &Value) -> ChatMessage {
1755    let text = match content {
1756        Value::String(s) => s.clone(),
1757        other => serde_json::to_string(other).unwrap_or_default(),
1758    };
1759    ChatMessage {
1760        role: role.to_owned(),
1761        content: Some(text),
1762        tool_call_id: None,
1763        tool_calls: None,
1764        reasoning_content: None,
1765    }
1766}
1767
1768/// A `tool/result` payload `{call_id, output, is_error}` → the strict
1769/// wire shape. A foreign shape still maps to a `role:"tool"` message
1770/// (with an empty `tool_call_id`) so nothing is silently swallowed.
1771fn tool_result_message(content: &Value) -> ChatMessage {
1772    if let Some(obj) = content.as_object()
1773        && let Some(call_id) = obj.get("call_id").and_then(Value::as_str)
1774    {
1775        let output = obj.get("output").cloned().unwrap_or(Value::Null);
1776        return ChatMessage {
1777            role: "tool".into(),
1778            content: Some(serde_json::to_string(&output).unwrap_or_default()),
1779            tool_call_id: Some(call_id.to_owned()),
1780            tool_calls: None,
1781            reasoning_content: None,
1782        };
1783    }
1784    ChatMessage {
1785        role: "tool".into(),
1786        content: Some(serde_json::to_string(content).unwrap_or_default()),
1787        tool_call_id: Some(String::new()),
1788        tool_calls: None,
1789        reasoning_content: None,
1790    }
1791}
1792
1793/// The replayed reasoning of an assistant payload, if present
1794/// (ADR-022). Absent/blank/non-string ⇒ `None` (legacy bytes unchanged).
1795fn reasoning_field(obj: &serde_json::Map<String, Value>) -> Option<String> {
1796    obj.get("reasoning_content")
1797        .and_then(Value::as_str)
1798        .filter(|r| !r.is_empty())
1799        .map(str::to_owned)
1800}
1801
1802/// An assistant payload: a tool-call turn, its per-call transcript
1803/// duplicate (`None` — dropped from the wire), a bare `{"text": …}`, or
1804/// the compact fallback.
1805fn assistant_message(content: &Value) -> Option<ChatMessage> {
1806    let Some(obj) = content.as_object() else {
1807        return Some(string_or_compact("assistant", content));
1808    };
1809    if obj.contains_key("tool_calls") {
1810        let calls: Option<Vec<WireToolCall>> =
1811            obj.get("tool_calls").and_then(Value::as_array).map(|list| {
1812                list.iter()
1813                    .filter_map(|tc| {
1814                        let id = tc.get("id").and_then(Value::as_str)?;
1815                        let name = tc.get("name").and_then(Value::as_str)?;
1816                        let arguments = tc.get("arguments").cloned().unwrap_or(Value::Null);
1817                        Some(WireToolCall {
1818                            id: id.to_owned(),
1819                            r#type: "function".into(),
1820                            function: WireFunctionCall {
1821                                name: name.to_owned(),
1822                                arguments: serde_json::to_string(&arguments).unwrap_or_default(),
1823                            },
1824                        })
1825                    })
1826                    .collect()
1827            });
1828        return Some(ChatMessage {
1829            role: "assistant".into(),
1830            // Empty text serializes as `content: null` (the strict shape
1831            // verified live: a purely tool-calling assistant turn).
1832            content: obj
1833                .get("text")
1834                .and_then(Value::as_str)
1835                .filter(|t| !t.is_empty())
1836                .map(str::to_owned),
1837            tool_call_id: None,
1838            tool_calls: calls,
1839            reasoning_content: reasoning_field(obj),
1840        });
1841    }
1842    // The per-call `tool/call` transcript duplicate: the enclosing
1843    // assistant turn's tool_calls already carries this call id.
1844    if obj.contains_key("id") && obj.contains_key("name") && obj.contains_key("arguments") {
1845        return None;
1846    }
1847    if let Some(text) = obj.get("text").and_then(Value::as_str) {
1848        return Some(ChatMessage {
1849            role: "assistant".into(),
1850            content: Some(text.to_owned()),
1851            tool_call_id: None,
1852            tool_calls: None,
1853            reasoning_content: reasoning_field(obj),
1854        });
1855    }
1856    Some(string_or_compact("assistant", content))
1857}
1858
1859/// (ADR-025) Whether a resident iteration has no work to judge: the loop is
1860/// episode-scoped, `take_eligible_inputs` returned nothing, and the context
1861/// ends on an assistant message (the empty-batch shape). A tool-result
1862/// continuation (last role `tool`) or any newly taken input is real work.
1863fn resident_empty_batch(scope: BudgetScope, taken_empty: bool, last_role: Option<&str>) -> bool {
1864    scope == BudgetScope::PerEpisode && taken_empty && last_role == Some("assistant")
1865}
1866
1867/// Maps a provider error onto the classifier's class names (
1868/// vocabulary) for the policy lookup.
1869fn error_class(e: &ProviderError) -> &'static str {
1870    match e {
1871        ProviderError::RateLimited => "rate_limited",
1872        ProviderError::ContextOverflow => "context_overflow",
1873        ProviderError::Unavailable(_) | ProviderError::Transport(_) => "provider_down",
1874        ProviderError::EmptyResponse => CLASS_EMPTY_RESPONSE,
1875        ProviderError::InvalidResponse(_) => "validation_failed",
1876        ProviderError::Other(_) => "internal",
1877    }
1878}
1879
1880/// Consults the declarative policy table for `class`. The loop never
1881/// *execs* the action (disposition is owned by the caller, A4); the match
1882/// is reported in the soft-failure reason for observability.
1883fn consult_policy(policy: &dyn RecoveryPolicySource, class: &str) -> Option<RecoveryAction> {
1884    policy
1885        .table()
1886        .into_iter()
1887        .find(|rule| rule.class == class)
1888        .map(|rule| rule.action)
1889}
1890
1891fn action_note(action: Option<RecoveryAction>) -> String {
1892    match action {
1893        Some(a) => format!("; recovery policy action: {a:?}"),
1894        None => "; no matching recovery policy rule".into(),
1895    }
1896}
1897
1898#[cfg(test)]
1899mod tests {
1900    use crate::react::{
1901        BudgetScope, CLASS_EMPTY_RESPONSE, ReActConfig, ReActLoop, assemble_delta, consult_policy,
1902        to_chat_message, tool_result_payload,
1903    };
1904    use crate::test_support::{NoopPolicy, NoopTools, agent_def};
1905    use kian_core::context::{Message, derive_model_context};
1906    use kian_core::events::{Event, EventKind};
1907    use kian_core::model::SessionId;
1908    use kian_core::seams::{ToolCall, ToolResult};
1909    use kian_core::secrets::{Redaction, RedactionKind};
1910    use kian_llm::provider::build_chat_body;
1911    use serde_json::json;
1912    use std::collections::BTreeMap;
1913
1914    fn msg(role: &str, content: serde_json::Value) -> Message {
1915        Message {
1916            role: role.into(),
1917            content,
1918            synthetic: false,
1919        }
1920    }
1921
1922    /// the `tool/result` payload carries the redaction report as
1923    /// an additive top-level key OUTSIDE `content`, and omits it when
1924    /// nothing was redacted — the un-redacted payload is byte-identical
1925    /// to the legacy literal.
1926    #[test]
1927    fn tool_result_payload_carries_redactions_outside_content() {
1928        let plain = ToolResult {
1929            call_id: "call-1".into(),
1930            output: json!({"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false}),
1931            is_error: false,
1932            redactions: Vec::new(),
1933        };
1934        let payload = tool_result_payload(&plain);
1935        assert_eq!(
1936            payload,
1937            json!({
1938                "role": "tool",
1939                "content": {
1940                    "call_id": "call-1",
1941                    "output": {"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false},
1942                    "is_error": false
1943                }
1944            }),
1945            "no redactions → no key, bytes unchanged"
1946        );
1947
1948        let redacted = ToolResult {
1949            call_id: "call-2".into(),
1950            output: json!({"exit_code": 0, "stdout": "[REDACTED:token]", "stderr": "", "timed_out": false}),
1951            is_error: false,
1952            redactions: vec![Redaction {
1953                kind: RedactionKind::TokenPattern,
1954                name: "ghp_".into(),
1955                count: 1,
1956            }],
1957        };
1958        let payload = tool_result_payload(&redacted);
1959        assert_eq!(
1960            payload["redactions"],
1961            json!([{"kind": "token_pattern", "name": "ghp_", "count": 1}])
1962        );
1963        // The report sits outside `content`; content itself is exactly
1964        // the four legacy fields.
1965        assert!(payload["content"].get("redactions").is_none());
1966        assert_eq!(payload["content"]["call_id"], json!("call-2"));
1967    }
1968
1969    /// (constraint 3): the additive `redactions` payload key never
1970    /// reaches the model context — the projection reads `role`/`content`
1971    /// only, so request bytes are identical with and without the key.
1972    #[test]
1973    fn redactions_payload_key_never_enters_the_model_context() {
1974        let session = SessionId::new();
1975        let bytes = tool_result_payload(&ToolResult {
1976            call_id: "call-9".into(),
1977            output: json!({"content": "scrubbed"}),
1978            is_error: false,
1979            redactions: vec![Redaction {
1980                kind: RedactionKind::EnvLine,
1981                name: "MY_SERVICE_TOKEN".into(),
1982                count: 2,
1983            }],
1984        });
1985        let with = Event {
1986            seq: 2,
1987            session,
1988            epoch: kian_core::model::Epoch(1),
1989            ts: 1,
1990            kind: EventKind::ToolResult,
1991            bytes: bytes.clone(),
1992            version: 0,
1993        };
1994        let mut without_bytes = bytes.clone();
1995        without_bytes.as_object_mut().unwrap().remove("redactions");
1996        let without = Event {
1997            bytes: without_bytes,
1998            ..with.clone()
1999        };
2000        let base = Event {
2001            seq: 1,
2002            session,
2003            epoch: kian_core::model::Epoch(0),
2004            ts: 0,
2005            kind: EventKind::SessionCreated,
2006            bytes: json!({}),
2007            version: 0,
2008        };
2009        let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
2010        let ctx_without = derive_model_context(&[base, without]).unwrap();
2011        assert_eq!(ctx_with, ctx_without);
2012        assert_eq!(ctx_with.len(), 1);
2013        // And the projected message is the frozen wire shape.
2014        let chat = to_chat_message(&ctx_with[0]).unwrap();
2015        assert_eq!(chat.role, "tool");
2016        assert_eq!(chat.tool_call_id.as_deref(), Some("call-9"));
2017        assert_eq!(chat.content.as_deref(), Some("{\"content\":\"scrubbed\"}"));
2018    }
2019
2020    /// Dialect v2: a projected tool round trip maps to the
2021    /// strict openai wire shape, and the per-call `tool/call` transcript
2022    /// duplicate is dropped (the assistant turn's tool_calls already
2023    /// carries the id).
2024    #[test]
2025    fn tool_round_trip_projects_to_the_strict_wire_shape() {
2026        let assistant = msg(
2027            "assistant",
2028            json!({
2029                "text": "",
2030                "tool_calls": [
2031                    {"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}
2032                ]
2033            }),
2034        );
2035        let chat = to_chat_message(&assistant).unwrap();
2036        assert_eq!(chat.role, "assistant");
2037        assert_eq!(chat.content, None, "empty text serializes as null");
2038        let tc = &chat.tool_calls.as_ref().unwrap()[0];
2039        assert_eq!(tc.id, "call-1");
2040        assert_eq!(tc.r#type, "function");
2041        assert_eq!(tc.function.name, "fs_read");
2042        assert_eq!(tc.function.arguments, "{\"path\":\"a.txt\"}");
2043
2044        // Non-empty text rides along as string content.
2045        let with_text = msg(
2046            "assistant",
2047            json!({"text": "checking", "tool_calls": [
2048                {"id": "call-2", "name": "exec", "arguments": {"argv": ["true"]}}
2049            ]}),
2050        );
2051        let chat = to_chat_message(&with_text).unwrap();
2052        assert_eq!(chat.content.as_deref(), Some("checking"));
2053
2054        // The tool/call transcript duplicate: dropped.
2055        let dup = msg(
2056            "assistant",
2057            json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}),
2058        );
2059        assert!(to_chat_message(&dup).is_none());
2060
2061        // The tool result: role tool + tool_call_id + serialized output.
2062        let result = msg(
2063            "tool",
2064            json!({"call_id": "call-1", "output": {"content": "x"}, "is_error": false}),
2065        );
2066        let chat = to_chat_message(&result).unwrap();
2067        assert_eq!(chat.role, "tool");
2068        assert_eq!(chat.tool_call_id.as_deref(), Some("call-1"));
2069        assert_eq!(chat.content.as_deref(), Some("{\"content\":\"x\"}"));
2070        assert!(chat.tool_calls.is_none());
2071    }
2072
2073    /// Dialect v2: plain messages keep the exact v1 `{content, role}`
2074    /// shape (no new keys), and bare `{"text": …}` assistant content
2075    /// unwraps to the string.
2076    #[test]
2077    fn plain_messages_keep_the_v1_shape() {
2078        let user = msg("user", json!("hello"));
2079        let chat = to_chat_message(&user).unwrap();
2080        assert_eq!(chat.role, "user");
2081        assert_eq!(chat.content.as_deref(), Some("hello"));
2082        assert!(chat.tool_call_id.is_none() && chat.tool_calls.is_none());
2083
2084        let bare = msg("assistant", json!({"text": "hi"}));
2085        assert_eq!(
2086            to_chat_message(&bare).unwrap().content.as_deref(),
2087            Some("hi")
2088        );
2089
2090        // A foreign tool shape still maps (empty tool_call_id) — nothing
2091        // is silently swallowed.
2092        let foreign = msg("tool", json!({"odd": true}));
2093        let chat = to_chat_message(&foreign).unwrap();
2094        assert_eq!(chat.tool_call_id.as_deref(), Some(""));
2095    }
2096
2097    // -- pure-unit sections ---------------------------------------------------
2098
2099    /// (ADR-015): with no permissions table configured, evaluation
2100    /// returns `None` — the `tool/call` payload stays byte-identical to
2101    /// the legacy shape (cache-byte stability). A non-empty table
2102    /// decides every call: an explicit entry is `configured`, an absent
2103    /// entry falls through to the default allow.
2104    #[test]
2105    fn permission_evaluation_covers_absent_default_and_configured() {
2106        use crate::react::{PermissionDecision, evaluate_permission};
2107        use kian_core::model::Permission;
2108
2109        let empty: BTreeMap<String, Permission> = BTreeMap::new();
2110        assert_eq!(evaluate_permission(&empty, "fs_write"), None);
2111
2112        let table: BTreeMap<String, Permission> = BTreeMap::from([
2113            ("fs_read".to_string(), Permission::Allow),
2114            ("fs_write".to_string(), Permission::Deny),
2115        ]);
2116        assert_eq!(
2117            evaluate_permission(&table, "fs_read"),
2118            Some(PermissionDecision::AllowConfigured)
2119        );
2120        assert_eq!(
2121            evaluate_permission(&table, "fs_write"),
2122            Some(PermissionDecision::Deny)
2123        );
2124        // A tool the table does not name: the default allow, provenance
2125        // still recorded (provenance-on-the-action).
2126        assert_eq!(
2127            evaluate_permission(&table, "exec"),
2128            Some(PermissionDecision::AllowDefault)
2129        );
2130    }
2131
2132    /// the allow/deny provenance shapes on `tool/call` — additive
2133    /// top-level `permission` key outside `content`, `content` exactly
2134    /// the legacy `{id, name, arguments}` triple.
2135    #[test]
2136    fn tool_call_payload_carries_permission_provenance_outside_content() {
2137        use crate::react::{evaluate_permission, tool_call_payload};
2138        use kian_core::model::Permission;
2139
2140        let call = ToolCall {
2141            id: "call-7".into(),
2142            name: "fs_write".into(),
2143            arguments: json!({"path": "a.txt"}),
2144        };
2145
2146        // No table → byte-identical legacy payload (no key at all).
2147        let empty: BTreeMap<String, Permission> = BTreeMap::new();
2148        let legacy = tool_call_payload(&call, evaluate_permission(&empty, &call.name));
2149        assert_eq!(
2150            legacy,
2151            json!({
2152                "role": "assistant",
2153                "content": {"id": "call-7", "name": "fs_write", "arguments": {"path": "a.txt"}}
2154            })
2155        );
2156
2157        // Configured allow.
2158        let table: BTreeMap<String, Permission> =
2159            BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
2160        let allowed = tool_call_payload(&call, evaluate_permission(&table, &call.name)); // default arm
2161        assert_eq!(
2162            allowed["permission"],
2163            json!({"evaluated": "allow", "policy": "default", "matched": "fs_write"})
2164        );
2165        assert_eq!(allowed["content"], legacy["content"]);
2166
2167        // Configured deny.
2168        let table: BTreeMap<String, Permission> =
2169            BTreeMap::from([("fs_write".to_string(), Permission::Deny)]);
2170        let denied = tool_call_payload(&call, evaluate_permission(&table, &call.name));
2171        assert_eq!(
2172            denied["permission"],
2173            json!({
2174                "evaluated": "deny",
2175                "policy": "configured",
2176                "matched": "fs_write",
2177                "reason": "tool_denied_by_policy"
2178            })
2179        );
2180        assert_eq!(denied["content"], legacy["content"]);
2181    }
2182
2183    /// P4 (PLUGIN-SPEC §4.4 + §16.1): the one EVENT-MODEL amendment of
2184    /// the hook round — the additive payload VALUE `policy:"hook"` on
2185    /// the existing `permission` key (never a new key, never a new
2186    /// kind). This is the golden pair, frozen to the exact serialized
2187    /// bytes: (a) the hook-denied `tool/call` payload (log-before-
2188    /// execute provenance naming the denying `<plugin>:<hook>`) and
2189    /// (b) the honest-error `tool/result` the model reacts to. Object
2190    /// keys serialize in canonical (sorted) order — `serde_json`
2191    /// without `preserve_order` — so the strings below are the durable
2192    /// audit bytes, not just structural equality.
2193    #[test]
2194    fn hook_denied_permission_payload_goldens_are_frozen_bytes() {
2195        use crate::react::{evaluate_permission, tool_call_payload, tool_call_payload_hook_denied};
2196        use kian_core::model::Permission;
2197
2198        let call = ToolCall {
2199            id: "call-7".into(),
2200            name: "exec".into(),
2201            arguments: json!({"cmd": ["ls"]}),
2202        };
2203
2204        // (a) tool/call, hook-denied arm (§4.4 step 3).
2205        let hook_denied =
2206            tool_call_payload_hook_denied(&call, "approval-gate", "exec not on the allowlist");
2207        assert_eq!(
2208            serde_json::to_string(&hook_denied).unwrap(),
2209            "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2210             \"permission\":{\"evaluated\":\"deny\",\"matched\":\"approval-gate:tool/pre\",\
2211             \"policy\":\"hook\",\"reason\":\"exec not on the allowlist\"},\"role\":\"assistant\"}"
2212        );
2213
2214        // (b) tool/result, the honest error of the same denial
2215        // (§4.4 step 4) — exactly the bytes the loop appends on the
2216        // deny arm (no redactions key: the report is empty there).
2217        let denied_result = ToolResult {
2218            call_id: call.id.clone(),
2219            output: json!({
2220                "error": "denied by plugin approval-gate: exec not on the allowlist",
2221                "policy": "hook"
2222            }),
2223            is_error: true,
2224            redactions: Vec::new(),
2225        };
2226        assert_eq!(
2227            serde_json::to_string(&tool_result_payload(&denied_result)).unwrap(),
2228            "{\"content\":{\"call_id\":\"call-7\",\"is_error\":true,\
2229             \"output\":{\"error\":\"denied by plugin approval-gate: exec not on the allowlist\",\
2230             \"policy\":\"hook\"}},\"role\":\"tool\"}"
2231        );
2232
2233        // Frozen regression — the amendment touches no other payload
2234        // shape: every pre-existing `permission` arm (and the legacy
2235        // key-less arm) serializes to exactly its pre-amendment bytes.
2236        let empty: BTreeMap<String, Permission> = BTreeMap::new();
2237        assert_eq!(
2238            serde_json::to_string(&tool_call_payload(
2239                &call,
2240                evaluate_permission(&empty, &call.name)
2241            ))
2242            .unwrap(),
2243            "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2244             \"role\":\"assistant\"}"
2245        );
2246        let default_table = BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
2247        assert_eq!(
2248            serde_json::to_string(&tool_call_payload(
2249                &call,
2250                evaluate_permission(&default_table, &call.name)
2251            ))
2252            .unwrap(),
2253            "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2254             \"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"default\"},\
2255             \"role\":\"assistant\"}"
2256        );
2257        let allow_table = BTreeMap::from([("exec".to_string(), Permission::Allow)]);
2258        assert_eq!(
2259            serde_json::to_string(&tool_call_payload(
2260                &call,
2261                evaluate_permission(&allow_table, &call.name)
2262            ))
2263            .unwrap(),
2264            "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2265             \"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"configured\"},\
2266             \"role\":\"assistant\"}"
2267        );
2268        let deny_table = BTreeMap::from([("exec".to_string(), Permission::Deny)]);
2269        assert_eq!(
2270            serde_json::to_string(&tool_call_payload(
2271                &call,
2272                evaluate_permission(&deny_table, &call.name)
2273            ))
2274            .unwrap(),
2275            "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2276             \"permission\":{\"evaluated\":\"deny\",\"matched\":\"exec\",\"policy\":\"configured\",\
2277             \"reason\":\"tool_denied_by_policy\"},\"role\":\"assistant\"}"
2278        );
2279    }
2280
2281    /// (constraint 3): the additive `permission` payload key never
2282    /// reaches the model context — the projection reads `role`/`content`
2283    /// only, so the projected message (and therefore request bytes) is
2284    /// identical with and without the key.
2285    #[test]
2286    fn permission_payload_key_never_enters_the_model_context() {
2287        use crate::react::{PermissionDecision, tool_call_payload};
2288        use kian_core::seams::ToolCall;
2289
2290        let session = SessionId::new();
2291        let call = ToolCall {
2292            id: "call-1".into(),
2293            name: "fs_read".into(),
2294            arguments: json!({"path": "a.txt"}),
2295        };
2296        let with_bytes = tool_call_payload(&call, Some(PermissionDecision::Deny));
2297        let mut without_bytes = with_bytes.clone();
2298        without_bytes.as_object_mut().unwrap().remove("permission");
2299        let with = Event {
2300            seq: 2,
2301            session,
2302            epoch: kian_core::model::Epoch(1),
2303            ts: 1,
2304            kind: EventKind::ToolCall,
2305            bytes: with_bytes,
2306            version: 0,
2307        };
2308        let without = Event {
2309            bytes: without_bytes,
2310            ..with.clone()
2311        };
2312        let base = Event {
2313            seq: 1,
2314            session,
2315            epoch: kian_core::model::Epoch(0),
2316            ts: 0,
2317            kind: EventKind::SessionCreated,
2318            bytes: json!({}),
2319            version: 0,
2320        };
2321        let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
2322        let ctx_without = derive_model_context(&[base, without]).unwrap();
2323        assert_eq!(ctx_with, ctx_without);
2324        assert_eq!(ctx_with.len(), 1);
2325        // The projected message is the frozen wire shape (the per-call
2326        // transcript duplicate, dropped from the chat body downstream).
2327        assert_eq!(ctx_with[0].role, "assistant");
2328        assert_eq!(
2329            ctx_with[0].content,
2330            json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}})
2331        );
2332        assert!(!ctx_with[0].synthetic);
2333    }
2334
2335    /// ADR-024: the budget scope selects which counter the limit applies
2336    /// to — the lifetime `turn/start` count (worker/plain) or the current
2337    /// episode's count (resident loops).
2338    /// (ADR-025) Only a resident episode ending on an assistant message with
2339    /// nothing taken is skipped; tool-result continuations, new inputs and
2340    /// lifetime loops are real work.
2341    #[test]
2342    fn resident_empty_batch_is_skipped_only_for_resident_assistant_tails() {
2343        use super::resident_empty_batch;
2344        assert!(resident_empty_batch(
2345            BudgetScope::PerEpisode,
2346            true,
2347            Some("assistant")
2348        ));
2349        assert!(!resident_empty_batch(
2350            BudgetScope::PerEpisode,
2351            false,
2352            Some("assistant")
2353        ));
2354        assert!(!resident_empty_batch(
2355            BudgetScope::PerEpisode,
2356            true,
2357            Some("tool")
2358        ));
2359        assert!(!resident_empty_batch(
2360            BudgetScope::PerEpisode,
2361            true,
2362            Some("user")
2363        ));
2364        assert!(!resident_empty_batch(
2365            BudgetScope::Lifetime,
2366            true,
2367            Some("assistant")
2368        ));
2369    }
2370
2371    #[test]
2372    fn budget_scope_selects_lifetime_or_episode_counter() {
2373        assert_eq!(BudgetScope::Lifetime.used(9, 0), 9);
2374        assert_eq!(BudgetScope::Lifetime.used(0, 9), 0);
2375        assert_eq!(BudgetScope::PerEpisode.used(9, 2), 2);
2376        assert_eq!(BudgetScope::PerEpisode.used(0, 0), 0);
2377    }
2378
2379    #[test]
2380    fn delta_assembly_concatenates_content_fragments() {
2381        let mut text = String::new();
2382        let mut reasoning = String::new();
2383        let mut calls = Default::default();
2384        for fragment in ["Hello", ", ", "kian"] {
2385            assemble_delta(
2386                &serde_json::json!({"content": fragment}),
2387                &mut text,
2388                &mut reasoning,
2389                &mut calls,
2390            );
2391        }
2392        assert_eq!(text, "Hello, kian");
2393        assert!(calls.is_empty());
2394    }
2395
2396    /// ADR-022: reasoning fragments concatenate in arrival order, persist
2397    /// inside the assistant payload, and replay as the top-level wire
2398    /// field; a legacy payload without the key stays byte-identical.
2399    #[test]
2400    fn reasoning_fragments_are_persisted_and_replayed() {
2401        let mut text = String::new();
2402        let mut reasoning = String::new();
2403        let mut calls = Default::default();
2404        assemble_delta(
2405            &json!({"reasoning_content": "think "}),
2406            &mut text,
2407            &mut reasoning,
2408            &mut calls,
2409        );
2410        assemble_delta(
2411            &json!({"reasoning_content": "harder"}),
2412            &mut text,
2413            &mut reasoning,
2414            &mut calls,
2415        );
2416        assemble_delta(
2417            &json!({"content": "answer"}),
2418            &mut text,
2419            &mut reasoning,
2420            &mut calls,
2421        );
2422        assert_eq!(reasoning, "think harder");
2423        assert_eq!(text, "answer");
2424
2425        let with = to_chat_message(&msg(
2426            "assistant",
2427            json!({"text": text, "reasoning_content": reasoning}),
2428        ))
2429        .unwrap();
2430        assert_eq!(with.reasoning_content.as_deref(), Some("think harder"));
2431        let body = build_chat_body("m", &[with], &[]);
2432        assert_eq!(body["messages"][0]["reasoning_content"], "think harder");
2433
2434        let legacy = to_chat_message(&msg("assistant", json!({"text": "answer"}))).unwrap();
2435        assert!(legacy.reasoning_content.is_none());
2436        let body = build_chat_body("m", &[legacy], &[]);
2437        assert!(body["messages"][0].get("reasoning_content").is_none());
2438    }
2439
2440    #[test]
2441    fn delta_assembly_accumulates_tool_call_fragments_by_index() {
2442        let mut text = String::new();
2443        let mut reasoning = String::new();
2444        let mut calls = Default::default();
2445        assemble_delta(
2446            &serde_json::json!({"tool_calls": [
2447                {"index": 0, "id": "call-1", "function": {"name": "fs.read"}}
2448            ]}),
2449            &mut text,
2450            &mut reasoning,
2451            &mut calls,
2452        );
2453        assemble_delta(
2454            &serde_json::json!({"tool_calls": [
2455                {"index": 0, "function": {"arguments": "{\"pa"}}
2456            ]}),
2457            &mut text,
2458            &mut reasoning,
2459            &mut calls,
2460        );
2461        assemble_delta(
2462            &serde_json::json!({"tool_calls": [
2463                {"index": 0, "function": {"arguments": "th\": \"a.txt\"}"}}
2464            ]}),
2465            &mut text,
2466            &mut reasoning,
2467            &mut calls,
2468        );
2469        let finished: Vec<_> = calls.into_values().map(|c| c.finish()).collect();
2470        assert_eq!(finished.len(), 1);
2471        assert_eq!(finished[0].id, "call-1");
2472        assert_eq!(finished[0].name, "fs.read");
2473        assert_eq!(finished[0].arguments, serde_json::json!({"path": "a.txt"}));
2474    }
2475
2476    #[test]
2477    fn policy_consult_matches_rule_by_class() {
2478        use kian_core::seams::{PolicyRule, RecoveryAction, RecoveryPolicySource};
2479
2480        struct Table(Vec<PolicyRule>);
2481        impl RecoveryPolicySource for Table {
2482            fn table(&self) -> Vec<PolicyRule> {
2483                self.0.clone()
2484            }
2485        }
2486        let table = Table(vec![
2487            PolicyRule {
2488                class: "rate_limited".into(),
2489                action: RecoveryAction::BackoffRetry { delay_ms: 100 },
2490            },
2491            PolicyRule {
2492                class: CLASS_EMPTY_RESPONSE.into(),
2493                action: RecoveryAction::InterruptAsk,
2494            },
2495        ]);
2496        assert_eq!(
2497            consult_policy(&table, "rate_limited"),
2498            Some(RecoveryAction::BackoffRetry { delay_ms: 100 })
2499        );
2500        assert_eq!(
2501            consult_policy(&table, CLASS_EMPTY_RESPONSE),
2502            Some(RecoveryAction::InterruptAsk)
2503        );
2504        assert_eq!(consult_policy(&table, "no_such_class"), None);
2505    }
2506
2507    // -- engine integration sections live in integration_tests.rs -------------
2508
2509    /// the recovery audit carries the pure classifier's class name
2510    /// plus the policy disposition name, `"none"` when no rule covers
2511    /// the class; provider classes flow through the existing pure
2512    /// classifier and loop-level hard errors map onto its vocabulary.
2513    #[test]
2514    fn recovery_audit_carries_class_and_policy_action() {
2515        use kian_core::seams::{PolicyRule, RecoveryPolicySource};
2516        use kian_orchestrator::recovery::ErrorClass;
2517        use serde_json::json;
2518
2519        struct Table(Vec<PolicyRule>);
2520        impl RecoveryPolicySource for Table {
2521            fn table(&self) -> Vec<PolicyRule> {
2522                self.0.clone()
2523            }
2524        }
2525        let with_rule = Table(vec![PolicyRule {
2526            class: "store_failure".into(),
2527            action: kian_core::seams::RecoveryAction::Fail,
2528        }]);
2529        assert_eq!(
2530            super::recovery_audit(&with_rule, ErrorClass::StoreFailure),
2531            json!({"class": "store_failure", "action": "fail"})
2532        );
2533        assert_eq!(
2534            super::recovery_audit(&with_rule, ErrorClass::EmptyResponse),
2535            json!({"class": "empty_response", "action": "none"}),
2536            "no covering rule → the honest none spelling"
2537        );
2538
2539        // Provider classes route through the pure classifier.
2540        assert_eq!(
2541            super::provider_error_class(&kian_core::seams::ProviderError::RateLimited),
2542            ErrorClass::RateLimited
2543        );
2544        assert_eq!(
2545            super::provider_error_class(&kian_core::seams::ProviderError::Unavailable(
2546                "upstream 503".into()
2547            )),
2548            ErrorClass::ProviderDown
2549        );
2550
2551        // Loop-level hard errors stay inside the classifier vocabulary.
2552        assert_eq!(
2553            super::loop_error_class(&super::LoopError::Engine(
2554                kian_orchestrator::EngineError::NotAtSafeBoundary {
2555                    session: kian_core::model::SessionId::new(),
2556                }
2557            )),
2558            ErrorClass::StoreFailure
2559        );
2560        assert_eq!(
2561            super::loop_error_class(&super::LoopError::Slot(
2562                kian_llm::slots::SlotError::UnknownSlot("aux".into())
2563            )),
2564            ErrorClass::Unknown
2565        );
2566    }
2567
2568    #[test]
2569    fn react_config_defaults_are_sane() {
2570        let cfg = ReActConfig::default();
2571        assert_eq!(cfg.slot.0, "main");
2572        assert!(cfg.max_iterations >= 1);
2573        // constructor smoke: config accessor round-trips
2574        let react = ReActLoop::new(
2575            agent_def(),
2576            std::sync::Arc::new(kian_llm::ProviderRegistry::new()),
2577            std::sync::Arc::new(NoopTools),
2578            std::sync::Arc::new(NoopPolicy),
2579        );
2580        assert_eq!(react.config().slot.0, "main");
2581    }
2582}