Skip to main content

kian_plugin/hooks/
views.rs

1//! The §3.2 payload catalog (closed) — plain serde structs, one per hook
2//! id, with field names, order and nesting exactly per the §3.2 field
3//! tables. Serialization is byte-checked against the spec examples (K2):
4//! a field-order drift is a silent ABI break for the sidecar tier.
5//!
6//! Each view carries an in-process `frame: Option<FrameInfo>` that is
7//! `#[serde(skip)]`d: it is the dispatch identity (§1 "Dispatch", §7.3
8//! frame metadata — `session`, `worker`, `seq`, and `epoch` for
9//! drain-phase hooks only) the bus needs for scope filtering and audit,
10//! and that the sidecar frame adds on the wire, so it must never ride the
11//! payload itself.
12
13use serde::Serialize;
14
15use kian_core::model::SessionId;
16
17/// In-process dispatch identity (§1 "Dispatch", §7.3). On the wire these
18/// are frame keys, not payload keys, which is why the view field is
19/// `#[serde(skip)]`.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct FrameInfo {
22    /// The **target** session of this dispatch (§7.2): the one drain's
23    /// session for a drain-phase hook, the one target session for an
24    /// `admit/pre` frame.
25    pub session: SessionId,
26    /// That target's durable `exec_worker` id; the empty string when the
27    /// session has no binding (§7.3).
28    pub worker: String,
29    /// That target's last observed seq at consultation; `0` when the
30    /// session has no event yet (§7.3).
31    pub seq: u64,
32    /// The fencing epoch of the drain that consulted — present for
33    /// drain-phase hooks only (§7.2); `None` for `admit/*`.
34    pub epoch: Option<u64>,
35}
36
37impl FrameInfo {
38    /// A frame for `session` with no worker binding and no events yet
39    /// (§7.3's floor values).
40    pub fn new(session: SessionId) -> Self {
41        Self {
42            session,
43            worker: String::new(),
44            seq: 0,
45            epoch: None,
46        }
47    }
48}
49
50/// The durable execution-worker binding key — **one spelling on every
51/// surface** (the delegation wrapper, the `thread/started` payload, the
52/// `spawn_worker` argument, the spawn result echo; §7.3/§8.2). The
53/// binding grammar and the routing-layer refusal rules live in
54/// `kian-superagent` (ADR-020 D1/D2); this crate owns only what frame
55/// identity needs — the key, and the stream-derived reader below.
56/// `kian-superagent` re-exports this constant, so the two cannot drift.
57pub const EXEC_WORKER_KEY: &str = "exec_worker";
58
59fn binding_of_value(value: Option<&serde_json::Value>) -> Option<&str> {
60    match value {
61        Some(serde_json::Value::String(id)) if !id.is_empty() => Some(id.as_str()),
62        _ => None,
63    }
64}
65
66/// The session's durable `exec_worker` binding, derived from its own
67/// stream alone (§7.3's `worker` field, §8.2's resolve input): the
68/// `thread/started` payload naming this session as the worker and the
69/// **first** `input/admitted` delegation wrapper must agree on the id.
70/// `Some(id)` when the two readable ids agree, or when exactly one
71/// side names one; `None` when neither names one or the two readable
72/// ids disagree. A present-but-unreadable value (non-string, empty)
73/// reads as unnamed — so a malformed payload key plus a valid wrapper
74/// resolves to the wrapper's id (the §7.3 floor picks rather than
75/// refuses), where the stricter routing-layer reading
76/// (`kian_superagent::worker_binding_of`) returns `Malformed` and
77/// refuses. The two agree on every Bound and Unbound stream; the
78/// relationship — including the malformed-input divergence — is
79/// pinned cross-crate in `kian-superagent`'s tests (n1).
80pub fn durable_worker_binding(
81    events: &[kian_core::events::Event],
82    session: &SessionId,
83) -> Option<String> {
84    let started = events.iter().find(|ev| {
85        ev.kind == kian_core::events::EventKind::ThreadStarted
86            && ev.bytes.get("worker").and_then(serde_json::Value::as_str)
87                == Some(session.0.to_string().as_str())
88    });
89    let payload = started.and_then(|ev| binding_of_value(ev.bytes.get(EXEC_WORKER_KEY)));
90    let wrapper = events
91        .iter()
92        .find(|ev| ev.kind == kian_core::events::EventKind::InputAdmitted)
93        .and_then(|ev| ev.bytes.get("content"))
94        .and_then(|content| binding_of_value(content.get(EXEC_WORKER_KEY)));
95    match (payload, wrapper) {
96        (Some(a), Some(b)) if a == b => Some(a.to_string()),
97        (Some(a), None) | (None, Some(a)) => Some(a.to_string()),
98        _ => None,
99    }
100}
101
102/// Which ingress produced an admission (§3.2.1 `origin`); decides veto
103/// availability (§3.4.3 — only the channel-borne port is veto-capable in
104/// v1).
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum Origin {
107    Channel,
108    Api,
109}
110
111impl Origin {
112    pub fn as_str(self) -> &'static str {
113        match self {
114            Origin::Channel => "channel",
115            Origin::Api => "api",
116        }
117    }
118
119    pub fn parse(s: &str) -> Option<Self> {
120        match s {
121            "channel" => Some(Origin::Channel),
122            "api" => Some(Origin::Api),
123            _ => None,
124        }
125    }
126}
127
128impl Serialize for Origin {
129    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
130        serializer.serialize_str(self.as_str())
131    }
132}
133
134/// One fan-out target of an admission evaluation (§3.2.1 `targets`).
135#[derive(Debug, Clone, Serialize)]
136pub struct AdmitTarget {
137    pub session: SessionId,
138    /// Whether this target is the fan-out's Router session.
139    pub router: bool,
140}
141
142/// The shaped input an admission would carry (§3.2.1 `input`).
143#[derive(Debug, Clone, Serialize)]
144pub struct AdmitInput {
145    pub role: String,
146    /// True for steer-injected content (strippable, EVENT-MODEL A6).
147    pub synthetic: bool,
148    /// Redacted, possibly truncated head of the content, ≤4096 bytes.
149    pub content_preview: String,
150    /// Exact serialized content length.
151    pub content_bytes: u64,
152    /// Digest of the **unredacted** serialized content (correlation only).
153    pub content_sha256: String,
154    /// True when the preview is shorter than the content.
155    pub content_truncated: bool,
156    /// True when the row will carry only an Inline view (over-cap spill).
157    pub inline_view: bool,
158}
159
160/// Channel provenance for `origin:"channel"`; `null` for `"api"`
161/// (§3.2.1 `channel`).
162#[derive(Debug, Clone, Serialize)]
163pub struct ChannelProvenance {
164    pub name: String,
165    pub event_id: String,
166    pub topic: Option<String>,
167}
168
169/// The shaping that will be applied (§3.2.1 `admission`).
170#[derive(Debug, Clone, Serialize)]
171pub struct AdmissionInfo {
172    pub policy: String,
173    pub spilled: bool,
174}
175
176/// `admit/pre` payload (§3.2.1). One view per inbound event — the complete
177/// fan-out set rides in `targets`; the evaluation is one, the frames are
178/// per target (§4.1).
179#[derive(Debug, Clone, Serialize)]
180pub struct AdmitDraft {
181    pub origin: Origin,
182    /// The complete fan-out set this one evaluation covers, sorted by
183    /// session id (§3.2.1).
184    pub targets: Vec<AdmitTarget>,
185    pub input: AdmitInput,
186    /// Channel provenance for `origin:"channel"`, `null` for `"api"`.
187    pub channel: Option<ChannelProvenance>,
188    pub admission: AdmissionInfo,
189    /// Per-target frame identity, aligned with `targets` (skip: the wire
190    /// frame carries it, §7.2). When shorter than `targets`, the bus
191    /// derives floor frames (`worker` empty, `seq` 0).
192    #[serde(skip)]
193    pub frames: Vec<FrameInfo>,
194}
195
196/// `admit/post` payload (§3.2.2); `event_id`/`seq` name the durable row
197/// that now exists.
198#[derive(Debug, Clone, Serialize)]
199pub struct AdmitReceiptView {
200    pub session: SessionId,
201    pub event_id: String,
202    pub seq: u64,
203    pub origin: Origin,
204    pub deduplicated: bool,
205    pub input: AdmitPostInput,
206    #[serde(skip)]
207    pub frame: Option<FrameInfo>,
208}
209
210/// The input summary of an `admit/post` receipt (§3.2.2).
211#[derive(Debug, Clone, Serialize)]
212pub struct AdmitPostInput {
213    pub role: String,
214    pub content_bytes: u64,
215    pub spilled: bool,
216}
217
218/// `turn/request` payload (§3.2.3). Fires once per provider turn, on the
219/// persisted primary body — never per fallback attempt (§4.2).
220#[derive(Debug, Clone, Serialize)]
221pub struct RequestMeta {
222    pub slot: String,
223    pub provider: String,
224    pub model: String,
225    pub iteration: u64,
226    pub request_bytes: u64,
227    pub request_sha256: String,
228    pub message_count: u64,
229    /// Sorted tool names in the body's `tools` array.
230    pub tool_names: Vec<String>,
231    pub tool_schema_sha256: String,
232    /// The only value ever dispatched in v1: `"pre_send"` (§3.2.3).
233    pub timing: String,
234    pub step_request_seq: u64,
235    #[serde(skip)]
236    pub frame: Option<FrameInfo>,
237}
238
239/// The `turn/end`-vocabulary error audit object of a `turn/response`
240/// payload (§3.2.4 `error`).
241#[derive(Debug, Clone, Serialize)]
242pub struct TurnErrorAudit {
243    pub class: String,
244    pub action: String,
245}
246
247/// `turn/response` payload (§3.2.4); `usage` is the provider's verbatim
248/// object (audit-only).
249#[derive(Debug, Clone, Serialize)]
250pub struct ResponseView {
251    pub iteration: u64,
252    /// `turn/end` vocabulary: `final_answer | tool_calls | soft_failure |
253    /// error`.
254    pub outcome: String,
255    pub tool_calls: u64,
256    pub text_bytes: u64,
257    pub reasoning_bytes: u64,
258    pub usage: serde_json::Value,
259    pub error: Option<TurnErrorAudit>,
260    /// The only value in v1: `"settled"` (§3.2.4).
261    pub timing: String,
262    #[serde(skip)]
263    pub frame: Option<FrameInfo>,
264}
265
266/// The declarative gate's decision for a tool call, which has already run
267/// (§4.4 ordering). Field shape matches the `tool/call.permission`
268/// provenance object (ADR-015; `reason` rides only a deny).
269#[derive(Debug, Clone, Serialize)]
270pub struct PermissionView {
271    pub evaluated: String,
272    pub policy: String,
273    pub matched: String,
274    #[serde(skip_serializing_if = "Option::is_none")]
275    pub reason: Option<String>,
276}
277
278/// `tool/pre` payload (§3.2.5). `arguments` is the parsed value
279/// (redacted) when its serialization fits the frame bound, else a string
280/// prefix with `arguments_truncated: true` — the two forms are exhaustive
281/// and unambiguous.
282#[derive(Debug, Clone, Serialize)]
283pub struct ToolCallView {
284    pub call_id: String,
285    pub name: String,
286    pub iteration: u64,
287    pub arguments: serde_json::Value,
288    pub arguments_bytes: u64,
289    pub arguments_sha256: String,
290    pub arguments_truncated: bool,
291    pub permission: PermissionView,
292    /// The only value in v1: `"react"` (§3.5).
293    pub surface: String,
294    #[serde(skip)]
295    pub frame: Option<FrameInfo>,
296}
297
298/// One aggregate redaction report entry (§3.2.6) — counts only, never
299/// values.
300#[derive(Debug, Clone, Serialize)]
301pub struct RedactionReport {
302    pub kind: String,
303    pub name: String,
304    pub count: u64,
305}
306
307/// `tool/post` payload (§3.2.6). No tool output content is shipped in v1
308/// (§16.7).
309#[derive(Debug, Clone, Serialize)]
310pub struct ToolPostView {
311    pub call_id: String,
312    pub name: String,
313    pub is_error: bool,
314    pub output_bytes: u64,
315    pub output_sha256: String,
316    pub redactions: Vec<RedactionReport>,
317    #[serde(skip)]
318    pub frame: Option<FrameInfo>,
319}
320
321/// `recover/decided` payload (§3.2.7). A hook may not veto or alter
322/// recovery (constraint 8): this point exists so a plugin can observe
323/// which class fired.
324#[derive(Debug, Clone, Serialize)]
325pub struct RecoveryView {
326    pub error_class: String,
327    /// A disposition name from the declarative table, or `"none"`.
328    pub action: String,
329    pub iteration: u64,
330    #[serde(skip)]
331    pub frame: Option<FrameInfo>,
332}
333
334/// `settle/pre` payload (§3.2.8). `reason` is `"completed"` — the only
335/// value ever dispatched (§3.4.2).
336#[derive(Debug, Clone, Serialize)]
337pub struct SettleView {
338    pub reason: String,
339    pub turns: u64,
340    pub tool_calls: u64,
341    /// `"none" | "passed" | "failed"` — the evidence gate's state, if it
342    /// ran.
343    pub evidence: String,
344    /// **This plugin's** completion-veto budget in this session (§3.2.8).
345    pub vetoes_used: u64,
346    pub vetoes_remaining: u64,
347    pub episodes: u64,
348    #[serde(skip)]
349    pub frame: Option<FrameInfo>,
350}
351
352/// The verdict of an `admit/pre` evaluation (§3.3: `Allow` is the default
353/// when no handler denies). One evaluation → one verdict for the whole
354/// fan-out (§4.1).
355#[derive(Debug, Clone, PartialEq, Eq)]
356pub enum AdmitVerdict {
357    /// No valid `stop` anywhere in the grid: the write loop proceeds.
358    Next,
359    /// A `stop` (or a fail-closed default of a `veto:admit` holder at
360    /// channel origin) refused the event for **every** target.
361    Stop { plugin: String, reason: String },
362}
363
364/// The verdict of a `tool/pre` dispatch (§3.3).
365#[derive(Debug, Clone, PartialEq, Eq)]
366pub enum ToolVerdict {
367    /// No valid denial: the declarative permission gate's decision stands.
368    Allow,
369    /// A valid `deny` from a `veto:tool` holder, or the fail-closed class
370    /// default (§11.1) — for the default the reason is the honest-error
371    /// tail `hook unavailable (<cause>)`.
372    Deny { plugin: String, reason: String },
373}
374
375/// The verdict of a `settle/pre` consultation (§4.6 steps 3–5).
376#[derive(Debug, Clone, PartialEq, Eq)]
377pub enum SettleVerdict {
378    /// No handler denied: settlement proceeds.
379    Allow,
380    /// A `veto:settle` holder denied with budget remaining and the marker
381    /// row was admitted: the caller propagates the outcome unchanged and
382    /// the engine re-arms (§4.6 step 3).
383    Deny { plugin: String, reason: String },
384    /// Budget exhausted (§4.6 step 4): the veto is recorded but settlement
385    /// proceeds — one audit line records the override.
386    Override {
387        plugin: String,
388        reason: String,
389        vetoes_used: u64,
390    },
391    /// The marker append failed (§4.6, the three-step failure path): the
392    /// gate does **not** settle — the caller propagates the append error
393    /// through the existing append-failure route, and the budget was
394    /// consumed anyway via the in-process counter.
395    AdmitFailed {
396        plugin: String,
397        reason: String,
398        error: String,
399        vetoes_used: u64,
400    },
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406
407    fn sid(s: &str) -> SessionId {
408        // SessionId is Deserialize over its uuid string form, so tests pin
409        // exact uuids without a direct uuid dependency edge (only sha2 may
410        // be added this round, K10).
411        serde_json::from_str(&format!("\"{s}\"")).expect("valid uuid literal")
412    }
413
414    fn frame(session: &str) -> Option<FrameInfo> {
415        Some(FrameInfo {
416            session: sid(session),
417            worker: "node-zulu".to_string(),
418            seq: 41,
419            epoch: Some(7),
420        })
421    }
422
423    const SESSION_A: &str = "0f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b";
424    const SESSION_B: &str = "1f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b";
425
426    fn compact<T: Serialize>(v: &T) -> String {
427        serde_json::to_string(v).expect("view serializes")
428    }
429
430    #[test]
431    fn payload_goldens_match_spec_3_2() {
432        // §3.2.1 `admit/pre` — compact form of the spec example, keys in
433        // spec order (the spec block is pretty-printed; K2 pins keys,
434        // order and nesting, so the golden is the compact rendering).
435        let draft = AdmitDraft {
436            origin: Origin::Channel,
437            targets: vec![
438                AdmitTarget {
439                    session: sid(SESSION_A),
440                    router: false,
441                },
442                AdmitTarget {
443                    session: sid(SESSION_B),
444                    router: true,
445                },
446            ],
447            input: AdmitInput {
448                role: "user".to_string(),
449                synthetic: false,
450                content_preview: "please run the cleanup".to_string(),
451                content_bytes: 91234,
452                content_sha256: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
453                    .to_string(),
454                content_truncated: true,
455                inline_view: false,
456            },
457            channel: Some(ChannelProvenance {
458                name: "lark".to_string(),
459                event_id: "evt_42".to_string(),
460                topic: None,
461            }),
462            admission: AdmissionInfo {
463                policy: "inline_cap_bytes=8192".to_string(),
464                spilled: true,
465            },
466            frames: vec![frame(SESSION_A).unwrap(), frame(SESSION_B).unwrap()],
467        };
468        assert_eq!(
469            compact(&draft),
470            concat!(
471                r#"{"origin":"channel","targets":[{"session":"0f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b","router":false},"#,
472                r#"{"session":"1f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b","router":true}],"#,
473                r#""input":{"role":"user","synthetic":false,"content_preview":"please run the cleanup","content_bytes":91234,"#,
474                r#""content_sha256":"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","#,
475                r#""content_truncated":true,"inline_view":false},"#,
476                r#""channel":{"name":"lark","event_id":"evt_42","topic":null},"#,
477                r#""admission":{"policy":"inline_cap_bytes=8192","spilled":true}}"#
478            ),
479            "the in-process frame identity must not ride the wire (K2)"
480        );
481
482        // §3.2.2 `admit/post`.
483        let receipt = AdmitReceiptView {
484            session: sid(SESSION_A),
485            event_id: format!("{SESSION_A}:41"),
486            seq: 41,
487            origin: Origin::Channel,
488            deduplicated: false,
489            input: AdmitPostInput {
490                role: "user".to_string(),
491                content_bytes: 91234,
492                spilled: true,
493            },
494            frame: frame(SESSION_A),
495        };
496        assert_eq!(
497            compact(&receipt),
498            concat!(
499                r#"{"session":"0f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b","event_id":"0f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b:41","#,
500                r#""seq":41,"origin":"channel","deduplicated":false,"#,
501                r#""input":{"role":"user","content_bytes":91234,"spilled":true}}"#
502            )
503        );
504
505        // §3.2.3 `turn/request`.
506        let request = RequestMeta {
507            slot: "main".to_string(),
508            provider: "openai-compat".to_string(),
509            model: "gpt-5".to_string(),
510            iteration: 2,
511            request_bytes: 48211,
512            request_sha256: "11b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
513                .to_string(),
514            message_count: 11,
515            tool_names: vec!["fs_read".to_string(), "fs_write".to_string()],
516            tool_schema_sha256: "22b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
517                .to_string(),
518            timing: "pre_send".to_string(),
519            step_request_seq: 57,
520            frame: frame(SESSION_A),
521        };
522        assert_eq!(
523            compact(&request),
524            concat!(
525                r#"{"slot":"main","provider":"openai-compat","model":"gpt-5","iteration":2,"#,
526                r#""request_bytes":48211,"request_sha256":"11b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","#,
527                r#""message_count":11,"tool_names":["fs_read","fs_write"],"#,
528                r#""tool_schema_sha256":"22b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","#,
529                r#""timing":"pre_send","step_request_seq":57}"#
530            )
531        );
532
533        // §3.2.4 `turn/response`.
534        let response = ResponseView {
535            iteration: 2,
536            outcome: "final_answer".to_string(),
537            tool_calls: 0,
538            text_bytes: 1422,
539            reasoning_bytes: 0,
540            usage: serde_json::json!({"input_tokens": 120, "output_tokens": 30}),
541            error: None,
542            timing: "settled".to_string(),
543            frame: frame(SESSION_A),
544        };
545        assert_eq!(
546            compact(&response),
547            concat!(
548                r#"{"iteration":2,"outcome":"final_answer","tool_calls":0,"text_bytes":1422,"#,
549                r#""reasoning_bytes":0,"usage":{"input_tokens":120,"output_tokens":30},"error":null,"#,
550                r#""timing":"settled"}"#
551            )
552        );
553
554        // §3.2.5 `tool/pre`.
555        let call = ToolCallView {
556            call_id: "call_abc".to_string(),
557            name: "exec".to_string(),
558            iteration: 2,
559            arguments: serde_json::json!({"cmd": ["rm", "-rf", "/tmp/x"]}),
560            arguments_bytes: 38,
561            arguments_sha256: "33b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
562                .to_string(),
563            arguments_truncated: false,
564            permission: PermissionView {
565                evaluated: "allow".to_string(),
566                policy: "configured".to_string(),
567                matched: "rule[3]".to_string(),
568                reason: None,
569            },
570            surface: "react".to_string(),
571            frame: frame(SESSION_A),
572        };
573        assert_eq!(
574            compact(&call),
575            concat!(
576                r#"{"call_id":"call_abc","name":"exec","iteration":2,"arguments":{"cmd":["rm","-rf","/tmp/x"]},"#,
577                r#""arguments_bytes":38,"arguments_sha256":"33b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","#,
578                r#""arguments_truncated":false,"#,
579                r#""permission":{"evaluated":"allow","policy":"configured","matched":"rule[3]"},"#,
580                r#""surface":"react"}"#
581            )
582        );
583
584        // §3.2.6 `tool/post`.
585        let post = ToolPostView {
586            call_id: "call_abc".to_string(),
587            name: "exec".to_string(),
588            is_error: false,
589            output_bytes: 812,
590            output_sha256: "44b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
591                .to_string(),
592            redactions: vec![RedactionReport {
593                kind: "env_line".to_string(),
594                name: "OPENAI_API_KEY".to_string(),
595                count: 1,
596            }],
597            frame: frame(SESSION_A),
598        };
599        assert_eq!(
600            compact(&post),
601            concat!(
602                r#"{"call_id":"call_abc","name":"exec","is_error":false,"output_bytes":812,"#,
603                r#""output_sha256":"44b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","#,
604                r#""redactions":[{"kind":"env_line","name":"OPENAI_API_KEY","count":1}]}"#
605            )
606        );
607
608        // §3.2.7 `recover/decided`.
609        let recovery = RecoveryView {
610            error_class: "rate_limited".to_string(),
611            action: "backoff_retry".to_string(),
612            iteration: 3,
613            frame: frame(SESSION_A),
614        };
615        assert_eq!(
616            compact(&recovery),
617            r#"{"error_class":"rate_limited","action":"backoff_retry","iteration":3}"#
618        );
619
620        // §3.2.8 `settle/pre`.
621        let settle = SettleView {
622            reason: "completed".to_string(),
623            turns: 4,
624            tool_calls: 7,
625            evidence: "passed".to_string(),
626            vetoes_used: 0,
627            vetoes_remaining: 3,
628            episodes: 2,
629            frame: frame(SESSION_A),
630        };
631        assert_eq!(
632            compact(&settle),
633            concat!(
634                r#"{"reason":"completed","turns":4,"tool_calls":7,"evidence":"passed","#,
635                r#""vetoes_used":0,"vetoes_remaining":3,"episodes":2}"#
636            )
637        );
638    }
639}