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