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