Skip to main content

kian_loop/
react.rs

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