Skip to main content

kian_core/
seams.rs

1//! Seam trait definitions (DESIGN §6.2 "Seam three roles").
2//!
3//! The built-in seam traits — `ModelProvider`, `LoopDriver`, `ToolProvider`,
4//! `ExecBackend`, `RecoveryPolicySource` — plus the bundle additions
5//! `ChannelAdapter` and `WatchdogSource` — are *definitions only*:
6//! no impls here; implementation crates (kian-llm, kian-loop,
7//! kian-superagent, kian-exec, …) implement and re-export them. Living in
8//! `kian-core` keeps the orchestrator dependency tree clean (constraint
9//! 10).
10
11use std::collections::BTreeMap;
12
13use futures::future::BoxFuture;
14use futures::stream::BoxStream;
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17
18use crate::model::SlotName;
19use crate::secrets::Redaction;
20
21// ---------------------------------------------------------------------------
22// ModelProvider
23// ---------------------------------------------------------------------------
24
25/// A model request: slot + opaque provider-shaped body. The body is built
26/// and serialized by the provider implementation (its serialization format
27/// is frozen stable content); the core stays provider-agnostic.
28///
29/// Persist-what-you-send (A2): the *caller* persists the request bytes as a
30/// `step/request` event before invoking [`ModelProvider::complete`] — the
31/// ordering obligation lives at the call site, not inside the provider.
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33pub struct ModelRequest {
34    pub slot: SlotName,
35    pub body: Value,
36}
37
38/// One streamed response chunk; the delta shape is provider-defined and
39/// opaque to the core.
40///
41/// a chunk may instead (or additionally) carry the provider's
42/// `usage` object **verbatim** — a usage-only frame has `delta: null`
43/// and `usage: Some(…)`; consumers must skip null deltas when
44/// assembling content. The field is additive (serde default, omitted
45/// when `None`).
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
47pub struct ModelChunk {
48    pub delta: Value,
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub usage: Option<Value>,
51}
52
53impl ModelChunk {
54    /// A delta-bearing chunk with no usage report.
55    #[must_use]
56    pub fn new(delta: Value) -> Self {
57        Self { delta, usage: None }
58    }
59
60    /// A chunk carrying a (possibly null) delta plus the provider's
61    /// usage object verbatim.
62    #[must_use]
63    pub fn with_usage(delta: Value, usage: Value) -> Self {
64        Self {
65            delta,
66            usage: Some(usage),
67        }
68    }
69}
70
71/// Provider-side failures. Variants pre-align with the pure error
72/// classifier so classification never needs to parse error strings.
73#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
74pub enum ProviderError {
75    #[error("rate limited")]
76    RateLimited,
77    #[error("context overflow")]
78    ContextOverflow,
79    #[error("provider unavailable: {0}")]
80    Unavailable(String),
81    #[error("transport error: {0}")]
82    Transport(String),
83    /// A soft failure (constraint 7): never mappable onto `completed`.
84    #[error("empty response")]
85    EmptyResponse,
86    /// The request itself is too large (ADR-068): an operator
87    /// `max_request_bytes` bound refused it before sending, or the
88    /// provider answered HTTP 413. Re-sending the same bytes cannot
89    /// succeed, so this is its own class — never `provider_down`.
90    #[error("request too large: {detail}")]
91    RequestTooLarge {
92        /// Serialized body size, in bytes.
93        size: usize,
94        /// The configured outbound bound; `None` when no local bound is
95        /// configured and the verdict came from the provider's 413.
96        limit: Option<u64>,
97        /// Operator-facing detail: bound or status, snippet, and whether
98        /// any request byte left this process.
99        detail: String,
100    },
101    #[error("invalid response: {0}")]
102    InvalidResponse(String),
103    #[error("{0}")]
104    Other(String),
105}
106
107/// Seam (DESIGN §6.2): model completion as a stream of chunks. Built-in
108/// provider: openai-compat (kian-llm); any third-party may replace it.
109pub trait ModelProvider: Send + Sync {
110    fn complete(&self, req: ModelRequest) -> BoxStream<'static, Result<ModelChunk, ProviderError>>;
111}
112
113// ---------------------------------------------------------------------------
114// ToolProvider
115// ---------------------------------------------------------------------------
116
117/// A model-visible tool schema. Serialized into the request prefix; the
118/// serialization format is frozen stable content (constraint 3).
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
120pub struct ToolSchema {
121    pub name: String,
122    pub description: String,
123    /// JSON-Schema-shaped parameter description (opaque to the core).
124    pub parameters: Value,
125}
126
127/// A tool invocation requested by the model.
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
129pub struct ToolCall {
130    pub id: String,
131    pub name: String,
132    pub arguments: Value,
133}
134
135/// A tool invocation result.
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137pub struct ToolResult {
138    pub call_id: String,
139    pub output: Value,
140    /// Distinguishes tool-level errors from successful outputs honestly
141    /// (constraint 7).
142    pub is_error: bool,
143    /// redaction provenance: what the exec redactor scrubbed from
144    /// this result (aggregate counts, never secret values). Additive
145    /// seam field — legacy JSON parses with an empty vec, an empty vec
146    /// serializes without the key, and the report never enters the
147    /// model-visible `output`.
148    #[serde(default, skip_serializing_if = "Vec::is_empty")]
149    pub redactions: Vec<Redaction>,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
153pub enum ToolError {
154    #[error("invalid tool call: {0}")]
155    InvalidCall(String),
156    #[error("tool execution failed: {0}")]
157    Execution(String),
158    #[error("tool timed out")]
159    Timeout,
160}
161
162/// Seam (DESIGN §6.2): model-visible tools. Built-ins: fs/exec/kiand
163/// (kian-loop). Side-effecting invocations must be *logged before
164/// execution* (invariant 1) — the caller appends the `tool/call` event
165/// before `invoke` runs.
166pub trait ToolProvider: Send + Sync {
167    fn schemas(&self) -> Vec<ToolSchema>;
168    fn invoke(&self, call: ToolCall) -> BoxFuture<'static, Result<ToolResult, ToolError>>;
169}
170
171// ---------------------------------------------------------------------------
172// ExecBackend
173// ---------------------------------------------------------------------------
174
175/// A command execution request (argv vector, never a shell string).
176#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
177pub struct ExecCommand {
178    pub argv: Vec<String>,
179    pub env: BTreeMap<String, String>,
180    pub cwd: Option<String>,
181    pub timeout_ms: Option<u64>,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
185pub struct ExecResult {
186    /// `None` when the process was killed / did not exit normally.
187    pub exit_code: Option<i32>,
188    pub stdout: String,
189    pub stderr: String,
190    pub timed_out: bool,
191    /// redaction provenance, produced by the redaction pass that
192    /// scrubbed `stdout`/`stderr` (the report travels with the result so
193    /// tool layers can attach it to the `tool/result` event payload).
194    /// Additive: legacy JSON parses with an empty vec; empty serializes
195    /// without the key.
196    #[serde(default, skip_serializing_if = "Vec::is_empty")]
197    pub redactions: Vec<Redaction>,
198}
199
200#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
201pub enum ExecError {
202    #[error("failed to spawn: {0}")]
203    Spawn(String),
204    #[error("execution timed out")]
205    Timeout,
206    #[error("io error: {0}")]
207    Io(String),
208}
209
210/// Seam (DESIGN §6.2): environment command execution. Built-ins: local
211/// (built-) and remote endpoint via KiandProto (bundle).
212pub trait ExecBackend: Send + Sync {
213    fn exec(&self, cmd: ExecCommand) -> BoxFuture<'static, Result<ExecResult, ExecError>>;
214}
215
216// ---------------------------------------------------------------------------
217// LoopDriver
218// ---------------------------------------------------------------------------
219
220/// What a loop iteration reports back to the drain. A soft failure is
221/// routed to the recovery policy and is *never* settled as `completed`
222/// (constraint 7).
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224pub enum LoopOutcome {
225    /// One provider turn finished (events were appended during it).
226    TurnDone,
227    /// No eligible input remains; the drain may settle and release.
228    Settled,
229    /// A stop condition ended the loop intentionally.
230    Stopped { reason: String },
231    /// Soft failure (e.g. empty model response) — consult the recovery
232    /// policy table.
233    SoftFailed { reason: String },
234    /// The session-lifetime token budget refused the next provider
235    /// request (ADR-055): the drain ends `awaiting_budget` (resumable,
236    /// running -> idle) instead of spending past the limit. `budget` is
237    /// the projection the gate evaluated (`limit`, `raised`, `spent`,
238    /// `estimate`), carried for the end-of-drain audit line.
239    AwaitingBudget { budget: Value },
240}
241
242/// Stop reason prefix a resident loop (the Router, the watchdog) emits
243/// when its **per-episode** iteration budget is exhausted. The
244/// `RouterDriver` recognizes it and parks the resident instead of ending
245/// the session (ADR-024); it is an in-process contract, not an event or a
246/// wire value.
247pub const EPISODE_BUDGET_STOP_REASON_PREFIX: &str = "episode iteration budget exhausted";
248/// Stop reason a resident loop (the Router) emits when its rotation
249/// threshold is met at a park boundary: the engine ends the session
250/// `rotated` (ADR-040 phase 2). The **hold owner** ends its own session
251/// — a parked resident holds the drain, so an outside closer cannot
252/// claim an idle session. In-process contract only, not an event or wire
253/// value.
254pub const ROTATION_STOP_REASON: &str = "resident rotation requested";
255
256/// Seam (DESIGN §6.2): the agent loop as control flow inside a drain.
257/// Built-in: the async ReAct loop (kian-loop). The context type is
258/// left abstract on purpose — it is the drain handle surface (inbox take,
259/// event append, …) that the orchestrator provides; the core does not model
260/// execution internals (layered iron rule).
261pub trait LoopDriver: Send + Sync {
262    type Ctx: Send;
263    fn drive(&self, ctx: Self::Ctx) -> BoxStream<'static, LoopOutcome>;
264}
265
266// ---------------------------------------------------------------------------
267// RecoveryPolicySource
268// ---------------------------------------------------------------------------
269
270/// One declarative policy rule (A4): a classifier class name → action.
271/// `class` strings follow the pure classifier's names (
272/// `provider_down`, `rate_limited`, `context_overflow`, …).
273#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
274pub struct PolicyRule {
275    pub class: String,
276    pub action: RecoveryAction,
277}
278
279/// Recovery actions (DESIGN §2.4). Every action is one-shot-guarded and
280/// budgeted with refund semantics; none may loop unboundedly (constraint 8).
281#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
282pub enum RecoveryAction {
283    BackoffRetry { delay_ms: u64 },
284    CompressThenRetry,
285    Failover,
286    InterruptAsk,
287    Fail,
288}
289
290/// Seam (DESIGN §6.2): supplies the declarative recovery table. Built-in:
291/// config file (`kian.yaml`). Disposition stays owned by the
292/// caller — this source is pure data.
293pub trait RecoveryPolicySource: Send + Sync {
294    fn table(&self) -> Vec<PolicyRule>;
295}
296
297// ---------------------------------------------------------------------------
298// ChannelAdapter (bundle — definition only; impls live in the
299// super-agent bundle, never in core)
300// ---------------------------------------------------------------------------
301
302/// One inbound channel event, surfaced by a [`ChannelAdapter`]. The
303/// payload is verbatim channel JSON (it rides inside the admitted input's
304/// `content`, so the frozen message-payload contract is untouched).
305#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
306pub struct ChannelEvent {
307    /// Channel name (e.g. `mock-im`, `lark`, `github`).
308    pub channel: String,
309    /// Adapter-side unique id — the idempotency key for admission
310    /// (one inbox row per event, never two).
311    pub event_id: String,
312    /// Optional routing topic (subscription rules may match on it).
313    pub topic: Option<String>,
314    /// Optional sender provenance (adapter-defined identity — the id,
315    /// name, or object the channel reports). Opaque to the core; the
316    /// bundle's admission-class vocabulary keys on it.
317    /// `#[serde(default)]`: old JSON parses unchanged with `None`.
318    #[serde(default)]
319    pub sender: Option<Value>,
320    /// Optional group/chat provenance (adapter-defined — the chat or
321    /// group the event arrived in, when distinct from the routing
322    /// topic). Opaque to the core.
323    /// `#[serde(default)]`: old JSON parses unchanged with `None`.
324    #[serde(default)]
325    pub group: Option<String>,
326    /// Verbatim event payload, opaque to the core.
327    pub payload: Value,
328    /// Observed at, unix epoch milliseconds.
329    pub ts_ms: u64,
330}
331
332/// One outbound channel delivery, handed to a [`ChannelAdapter`]. Output
333/// policies (word limits, structured sections) are applied by the caller
334/// *before* the send; the adapter delivers what it is given and returns
335/// an honest [`SendReceipt`] or error.
336#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
337pub struct ChannelDelivery {
338    pub channel: String,
339    /// Channel-defined delivery target (chat id, issue ref, …) — opaque
340    /// to everything upstream of the adapter.
341    pub target: Value,
342    /// The message content to deliver, already policy-shaped.
343    pub content: Value,
344}
345
346/// Proof that a delivery landed: the adapter's own id for the sent
347/// message plus the delivery timestamp. Recorded in the audit stream via
348/// the caller's `channel/delivered` event.
349#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
350pub struct SendReceipt {
351    pub message_id: String,
352    pub ts_ms: u64,
353}
354
355/// Adapter-side failures, pre-aligned with the pure error classifier's
356/// vocabulary so classification never parses error strings.
357#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
358pub enum ChannelError {
359    #[error("channel unavailable: {0}")]
360    Unavailable(String),
361    #[error("delivery failed: {0}")]
362    DeliveryFailed(String),
363    #[error("delivery timed out")]
364    Timeout,
365}
366
367/// Seam (DESIGN §6.2, bundle): an inbound/outbound channel (IM, issue
368/// tracker, …). Definition only in core — the first impl is the
369/// production-quality in-memory mock channel (kian-superagent); real
370/// lark/GitHub adapters are ecosystem. Subscribe streams must be
371/// independently cloneable consumers of the adapter's own choosing.
372pub trait ChannelAdapter: Send + Sync {
373    /// Inbound events. Each event must be surfaced exactly once per
374    /// subscriber; admission dedupes on `event_id` as the durable guard.
375    fn subscribe(&self) -> BoxStream<'static, ChannelEvent>;
376    /// Outbound delivery. Resolves only after the channel accepted the
377    /// message — an honest error never masquerades as a receipt.
378    fn send(&self, out: ChannelDelivery) -> BoxFuture<'static, Result<SendReceipt, ChannelError>>;
379}
380
381// ---------------------------------------------------------------------------
382// WatchdogSource (bundle — definition only)
383// ---------------------------------------------------------------------------
384
385/// Endpoint health as the watchdog observes it. Edge-triggered: a source
386/// reports *changes*, not heartbeats.
387#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
388#[serde(rename_all = "lowercase")]
389pub enum EndpointHealth {
390    Online,
391    Offline,
392}
393
394/// One edge-triggered health transition for a registered endpoint. A
395/// dead daemon cannot report its own death — the authoritative v1 view
396/// is the server's heartbeat-absence observation (DESIGN §4.3).
397#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
398pub struct HealthEvent {
399    pub endpoint_id: String,
400    pub status: EndpointHealth,
401    pub ts_ms: u64,
402    pub detail: Option<String>,
403}
404
405/// Seam (DESIGN §6.2, bundle): an edge-triggered health monitor.
406/// Definition only in core — the v1 impl is the server-side heartbeat
407/// watchdog over the endpoint registry (kian-exec). The stream
408/// carries state changes only (no flapping, no periodic noise); health
409/// events reach sessions exclusively via Admit — the watchdog never
410/// writes session streams itself (layered iron rule).
411pub trait WatchdogSource: Send + Sync {
412    fn health(&self) -> BoxStream<'static, HealthEvent>;
413}
414
415#[cfg(test)]
416mod tests {
417    use serde_json::json;
418
419    use super::{
420        ExecCommand, ExecResult, LoopOutcome, ModelChunk, ModelRequest, PolicyRule, RecoveryAction,
421        ToolCall, ToolResult, ToolSchema,
422    };
423    use crate::model::SlotName;
424
425    /// All built-in seams are object-safe so the orchestrator can hold
426    /// plugin-registered `Arc<dyn _>` impls (DESIGN §6.2, §7).
427    #[test]
428    fn seam_traits_are_object_safe() {
429        fn assert_object_safe(
430            _: &dyn super::ModelProvider,
431            _: &dyn super::ToolProvider,
432            _: &dyn super::ExecBackend,
433            _: &dyn super::RecoveryPolicySource,
434            _: &dyn super::LoopDriver<Ctx = ()>,
435        ) {
436        }
437        let _ = assert_object_safe;
438    }
439
440    /// The bundle seams are object-safe for the same reason the
441    /// built-in seams are: assembly holds `Arc<dyn ChannelAdapter>` /
442    /// `Arc<dyn WatchdogSource>` registered by plugins.
443    #[test]
444    fn bundle_seam_traits_are_object_safe() {
445        fn assert_object_safe(_: &dyn super::ChannelAdapter, _: &dyn super::WatchdogSource) {}
446        let _ = assert_object_safe;
447    }
448
449    /// The bundle seam support types round-trip through JSON; the
450    /// health status serializes as the lowercase tabled form.
451    #[test]
452    fn bundle_seam_support_types_round_trip() {
453        use super::{
454            ChannelDelivery, ChannelError, ChannelEvent, EndpointHealth, HealthEvent, SendReceipt,
455        };
456
457        let event = ChannelEvent {
458            channel: "mock-im".into(),
459            event_id: "evt-7".into(),
460            topic: Some("worker-1".into()),
461            sender: Some(json!({"id": "u-42", "name": "yifei"})),
462            group: Some("chat-9".into()),
463            payload: json!({"text": "@kian deploy"}),
464            ts_ms: 1_762_000_000_000,
465        };
466        let delivery = ChannelDelivery {
467            channel: "mock-im".into(),
468            target: json!({"chat_id": 42}),
469            content: json!({"text": "done"}),
470        };
471        let receipt = SendReceipt {
472            message_id: "msg-9".into(),
473            ts_ms: 1_762_000_000_001,
474        };
475        let health = HealthEvent {
476            endpoint_id: "ep-laptop".into(),
477            status: EndpointHealth::Offline,
478            ts_ms: 1_762_000_000_002,
479            detail: Some("heartbeat stale".into()),
480        };
481
482        fn rt<T>(val: &T)
483        where
484            T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
485        {
486            let ser = serde_json::to_value(val).unwrap();
487            let back: T = serde_json::from_value(ser).unwrap();
488            assert_eq!(&back, val);
489        }
490        rt(&event);
491        rt(&delivery);
492        rt(&receipt);
493        rt(&health);
494
495        // Tabled serde forms: lowercase status words.
496        assert_eq!(
497            serde_json::to_value(EndpointHealth::Online).unwrap(),
498            json!("online")
499        );
500        assert_eq!(
501            serde_json::to_value(EndpointHealth::Offline).unwrap(),
502            json!("offline")
503        );
504        // Errors stay display-stable (classification reads kinds, not
505        // strings, but the messages are human-facing).
506        assert_eq!(ChannelError::Timeout.to_string(), "delivery timed out");
507    }
508
509    /// Old `ChannelEvent` JSON (legacy, no `sender`/`group`) parses
510    /// unchanged with `None` defaults for the new fields, and the new
511    /// fields serialize as explicit nulls — additive, never breaking.
512    #[test]
513    fn old_channel_event_json_parses_with_default_provenance() {
514        use super::ChannelEvent;
515
516        let old = json!({
517            "channel": "mock-im",
518            "event_id": "evt-legacy",
519            "topic": null,
520            "payload": {"text": "hi"},
521            "ts_ms": 1_762_000_000_000u64,
522        });
523        let event: ChannelEvent = serde_json::from_value(old).unwrap();
524        assert_eq!(event.channel, "mock-im");
525        assert_eq!(event.event_id, "evt-legacy");
526        assert_eq!(event.topic, None);
527        assert_eq!(event.sender, None);
528        assert_eq!(event.group, None);
529
530        // The new fields serialize as nulls (serde default visibility):
531        // a round trip preserves equality either way.
532        let ser = serde_json::to_value(&event).unwrap();
533        assert_eq!(ser["sender"], serde_json::Value::Null);
534        assert_eq!(ser["group"], serde_json::Value::Null);
535        let back: ChannelEvent = serde_json::from_value(ser).unwrap();
536        assert_eq!(back, event);
537    }
538
539    /// `ModelChunk.usage` is additive — legacy JSON (no `usage`
540    /// key) parses with `None`, `None` serializes without the key, and
541    /// a usage-carrying chunk round-trips with `delta: null`.
542    #[test]
543    fn model_chunk_usage_is_additive() {
544        let plain = ModelChunk::new(json!({"content": "hi"}));
545        let ser = serde_json::to_value(&plain).unwrap();
546        assert_eq!(ser, json!({"delta": {"content": "hi"}}));
547        let legacy: ModelChunk =
548            serde_json::from_value(json!({"delta": {"content": "hi"}})).unwrap();
549        assert_eq!(legacy, plain);
550        assert_eq!(legacy.usage, None);
551
552        let with = ModelChunk::with_usage(serde_json::Value::Null, json!({"prompt_tokens": 3}));
553        let ser = serde_json::to_value(&with).unwrap();
554        assert_eq!(ser, json!({"delta": null, "usage": {"prompt_tokens": 3}}));
555        let back: ModelChunk = serde_json::from_value(ser).unwrap();
556        assert_eq!(back, with);
557    }
558
559    /// The seam support types round-trip through JSON; policy rules come
560    /// from declarative config and must be serde-shaped.
561    #[test]
562    fn seam_support_types_round_trip() {
563        let req = ModelRequest {
564            slot: SlotName("main".into()),
565            body: json!({"messages": []}),
566        };
567        let chunk = ModelChunk::new(json!({"text": "hi"}));
568        let schema = ToolSchema {
569            name: "fs.read".into(),
570            description: "read a file".into(),
571            parameters: json!({"type": "object"}),
572        };
573        let call = ToolCall {
574            id: "call-1".into(),
575            name: "fs.read".into(),
576            arguments: json!({"path": "/tmp/x"}),
577        };
578        let result = ToolResult {
579            call_id: "call-1".into(),
580            output: json!({"content": "…"}),
581            is_error: false,
582            redactions: Vec::new(),
583        };
584        let cmd = ExecCommand {
585            argv: vec!["rg".into(), "-n".into(), "pat".into()],
586            env: [("HOME".to_string(), "/tmp".to_string())]
587                .into_iter()
588                .collect(),
589            cwd: Some("/tmp".into()),
590            timeout_ms: Some(5_000),
591        };
592        let exec = ExecResult {
593            exit_code: Some(0),
594            stdout: "match".into(),
595            stderr: String::new(),
596            timed_out: false,
597            redactions: Vec::new(),
598        };
599        let rule = PolicyRule {
600            class: "rate_limited".into(),
601            action: RecoveryAction::BackoffRetry { delay_ms: 500 },
602        };
603
604        fn rt<T>(val: &T)
605        where
606            T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
607        {
608            let ser = serde_json::to_value(val).unwrap();
609            let back: T = serde_json::from_value(ser).unwrap();
610            assert_eq!(&back, val);
611        }
612        rt(&req);
613        rt(&chunk);
614        rt(&schema);
615        rt(&call);
616        rt(&result);
617        rt(&cmd);
618        rt(&exec);
619        rt(&rule);
620
621        let outcome = LoopOutcome::SoftFailed {
622            reason: "empty model response".into(),
623        };
624        // LoopOutcome uses default serde variant naming (it is a seam type,
625        // not part of the frozen event schema).
626        assert_eq!(
627            serde_json::to_value(&outcome).unwrap(),
628            json!({"SoftFailed": {"reason": "empty model response"}})
629        );
630    }
631}