Skip to main content

causa_runtime/
event.rs

1//! `ContextEvent` projection — a turn's facts projected into a sequence for
2//! UI, observability, and audit consumers.
3//!
4//! Events are a **projection** of a turn's facts (`TurnContext` +
5//! `TurnResult` + `TurnTrace`) into a sequence that consumers (UI,
6//! observability, audit) can subscribe to. They are not facts themselves:
7//! they are derived, not persisted, and never written back into a
8//! `TurnContext`.
9//!
10//! ## Layering
11//!
12//! ```text
13//! causa-kernel
14//!   └─ TurnContext / facts vocabulary                          ← facts + contracts
15//!             ^
16//!             │ project_turn(...)
17//!             |
18//! causa-runtime
19//!   └─ driver (TurnResult / TurnTrace / ModelRoundTrace)       ← outcome vocabulary
20//!   └─ ContextEvent / project_turn                             ← projection
21//!             ^
22//!             |
23//! app-host / external consumer   ← observers (UI, audit, metrics)
24//! ```
25//!
26//! ## Boundaries
27//!
28//! - **Not facts**: `ContextEvent` instances are constructed on demand
29//!   by `project_turn`; they never appear in a kernel snapshot.
30//! - **Not persistent**: nothing in this module touches the workspace
31//!   store. Consumers persist what they need.
32//! - **No harness dependency**: this module is `Send + Sync`-pure and
33//!   depends on no harness crate.
34//! - **No `AgentEvent` reuse**: `AgentEvent` is out of scope; a host that
35//!   needs to bridge to it does so with a one-off
36//!   `From<ContextEvent> for AgentEvent` adapter in the host crate, not
37//!   here.
38//!
39//! ## Serialization
40//!
41//! `ContextEvent` is serde-derived for IPC delivery to host UIs and audit
42//! pipelines. The embedded driver outcome types (`TurnResult`, `TurnTrace`)
43//! carry their own serde derives; their serde **shapes** are a load-bearing
44//! wire contract for this module — see the wire-contract note on
45//! `crate::driver::TurnOutcome`.
46
47use std::collections::HashMap;
48
49use serde::{Deserialize, Serialize};
50
51use crate::driver::{ModelRoundTrace, TurnResult, TurnTrace};
52use crate::interaction::TurnInteraction;
53use causa_kernel::{
54    BlockContent, ConversationId, RoundId, StreamDelta, ToolCallPayload, TurnContext, TurnId,
55};
56
57/// Framework-side event projected from a turn's facts.
58///
59/// Every variant shares the routing envelope (`conversation_id`,
60/// `turn_id`); the variant-specific payload lives in `kind`.
61///
62/// `conversation_id` is `Option<ConversationId>` because the bare
63/// `TurnRunner::run` entry does not carry a `ConversationState`; the
64/// `run_in_conversation` entry does. The host constructs the event with
65/// `Some(id)` when projecting from a `ConversationOutcome`, and `None` for
66/// the bare `TurnOutcome` path. Subscribers that care about
67/// cross-conversation routing key on `Some`.
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct ContextEvent {
70    /// Routing key for conversation-scoped consumers; skipped on the
71    /// wire when `None` (the bare `run` entry).
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub conversation_id: Option<ConversationId>,
74    /// The turn every event of the sequence belongs to.
75    pub turn_id: TurnId,
76    /// The variant-specific payload; the wire discriminator is `type`.
77    pub kind: ContextEventKind,
78}
79
80/// The event payload proper. `type` is the snake_case discriminator on
81/// the wire (`"turn_started"` / `"tool_batch_dispatched"` /
82/// `"turn_outcome"`).
83#[derive(Debug, Clone, Serialize, Deserialize)]
84#[serde(tag = "type", rename_all = "snake_case")]
85pub enum ContextEventKind {
86    /// The turn has begun. Emitted exactly once, first in the sequence.
87    TurnStarted,
88    /// A batch of tool calls was dispatched for `round_id`. `calls`
89    /// carries the **pre-execution** payloads — the model-emitted tool
90    /// calls as committed facts, in draft order. Emitted once per round
91    /// that has a `tool_batch` in the trace; rounds without one
92    /// (EndTurn, MaxTokens, Refusal, compaction failure, …) produce no
93    /// dispatch event.
94    ToolBatchDispatched {
95        /// The round whose batch was dispatched.
96        round_id: RoundId,
97        /// The pre-execution committed tool calls, in draft order.
98        calls: Vec<ToolCallPayload>,
99    },
100    /// The turn finished. `result` is the canonical `TurnResult`
101    /// (`Completed | Interrupted { cause }`) and `trace` is the full
102    /// `TurnTrace` (rounds, totals). Consumers can re-walk `trace`
103    /// for finer-grained data. Emitted exactly once, last in the
104    /// sequence.
105    TurnOutcome {
106        /// The canonical `TurnResult` (`Completed` or `Interrupted`).
107        result: TurnResult,
108        /// The full `TurnTrace` (rounds, totals).
109        trace: TurnTrace,
110    },
111    // Streaming-delta variants (the `project_streaming_turn` path; mutually
112    // exclusive with the batch `project_turn` sequence for the same turn).
113    // `conversation_id` / `turn_id` ride the envelope.
114    /// One model text increment in round `round_id`.
115    TextDelta {
116        /// The round the increment belongs to.
117        round_id: RoundId,
118        /// The text increment.
119        delta: String,
120    },
121    /// One reasoning increment in round `round_id`.
122    ReasoningDelta {
123        /// The round the increment belongs to.
124        round_id: RoundId,
125        /// The reasoning increment.
126        delta: String,
127    },
128    /// One tool-call increment in round `round_id`: the provider is
129    /// appending the name and/or the JSON arguments of the call at
130    /// `call_index` in draft order.
131    ToolCallDelta {
132        /// The round the increment belongs to.
133        round_id: RoundId,
134        /// Index of the call being streamed, in draft order.
135        call_index: usize,
136        /// The tool-name increment, when the provider streams one.
137        name_delta: Option<String>,
138        /// The JSON-arguments increment, when the provider streams one.
139        arguments_delta: Option<String>,
140    },
141}
142
143/// Project a turn into its canonical sequence of `ContextEvent`s.
144///
145/// ## Inputs
146///
147/// - `context` — the turn's fact state. `ToolBatchDispatched.calls` is
148///   derived from the committed `tool.call` blocks addressed by each
149///   round's `applied_block_ids`, so the projector needs no side-channel
150///   capture: the committed facts are the pre-execution batch (the
151///   kernel commits every model-emitted call before any dispatch).
152/// - `result` / `trace` — straight from `TurnOutcome` (or the
153///   `ConversationOutcome` fields).
154/// - `conversation_id` — `Some(id)` for the `run_in_conversation` entry,
155///   `None` for the bare `run` entry.
156///
157/// For the conversation path, project **before** `commit`/`abort_turn`
158/// (the turn is then still `state.active_turn()`); the projection reads
159/// the blocks and copies what it needs.
160///
161/// ## Output order
162///
163/// 1. `TurnStarted` — exactly once.
164/// 2. One `ToolBatchDispatched` per trace round that has a `tool_batch`,
165///    in `round_id` order, carrying that round's committed tool calls.
166/// 3. `TurnOutcome` — exactly once, with the full trace.
167///
168/// ## What this function never does
169///
170/// - It never reads or mutates kernel state beyond the arguments.
171/// - It never constructs `ToolExecutionOutcome` — execution results
172///   live in `trace`, not in events.
173/// - It never holds kernel locks; it is a pure projection over
174///   borrowed data.
175pub fn project_turn(
176    context: &TurnContext,
177    result: &TurnResult,
178    trace: &TurnTrace,
179    conversation_id: Option<ConversationId>,
180) -> Vec<ContextEvent> {
181    let turn_id = context.turn_id();
182    let mut events = Vec::with_capacity(2 + trace.rounds.len());
183    events.push(ContextEvent {
184        conversation_id: conversation_id.clone(),
185        turn_id: turn_id.clone(),
186        kind: ContextEventKind::TurnStarted,
187    });
188    // tool.call blocks indexed by block id — one pass over the facts,
189    // then O(1) resolution per round.
190    let calls_by_block = call_index(context);
191    for round in &trace.rounds {
192        if round.tool_batch.is_none() {
193            continue;
194        }
195        let calls = committed_calls(&calls_by_block, round);
196        events.push(ContextEvent {
197            conversation_id: conversation_id.clone(),
198            turn_id: turn_id.clone(),
199            kind: ContextEventKind::ToolBatchDispatched {
200                round_id: round.round_id,
201                calls,
202            },
203        });
204    }
205    events.push(ContextEvent {
206        conversation_id,
207        turn_id,
208        kind: ContextEventKind::TurnOutcome {
209            result: result.clone(),
210            trace: trace.clone(),
211        },
212    });
213    events
214}
215
216/// The model-emitted tool calls of one round, in draft (commit) order.
217/// `applied_block_ids` addresses every block the model door committed for
218/// the round (optional text first, then one tool call per draft); only the
219/// tool-call blocks resolve here.
220fn committed_calls(
221    call_index: &HashMap<causa_kernel::BlockId, ToolCallPayload>,
222    round: &ModelRoundTrace,
223) -> Vec<ToolCallPayload> {
224    round
225        .applied_block_ids
226        .iter()
227        .filter_map(|id| call_index.get(id).cloned())
228        .collect()
229}
230
231// --- streaming projection ----------------------------------------------------
232
233/// A collecting [`TurnInteraction`] — the bridge between a live streaming
234/// turn and the `ContextEvent` sequence. Wire it through
235/// `TurnRunOptions.interaction`; when the turn finishes, feed
236/// [`StreamEventCollector::into_events`] into
237/// [`project_streaming_turn`] to produce the canonical full sequence.
238///
239/// `Usage` / `Done` / `Error` deltas collect nothing: usage and the
240/// terminal state ride the final `TurnOutcome` event's `trace`/`result`.
241pub struct StreamEventCollector {
242    turn_id: TurnId,
243    conversation_id: Option<ConversationId>,
244    events: std::sync::Mutex<Vec<ContextEvent>>,
245}
246
247impl StreamEventCollector {
248    /// A collector for the given turn (and optional conversation); wire
249    /// it as `TurnRunOptions.interaction` for a streaming run.
250    pub fn new(turn_id: TurnId, conversation_id: Option<ConversationId>) -> Self {
251        Self {
252            turn_id,
253            conversation_id,
254            events: std::sync::Mutex::new(Vec::new()),
255        }
256    }
257
258    /// The delta events collected while the turn ran, in arrival order.
259    /// Borrowed form — convenient behind an `Arc` wiring.
260    pub fn events(&self) -> Vec<ContextEvent> {
261        self.events.lock().unwrap().clone()
262    }
263
264    /// The delta events collected while the turn ran, in arrival order.
265    pub fn into_events(self) -> Vec<ContextEvent> {
266        self.events.into_inner().unwrap()
267    }
268}
269
270#[async_trait::async_trait]
271impl TurnInteraction for StreamEventCollector {
272    async fn on_delta(&self, round_id: RoundId, delta: &StreamDelta) {
273        let kind = match delta {
274            StreamDelta::TextDelta { delta } => ContextEventKind::TextDelta {
275                round_id,
276                delta: delta.clone(),
277            },
278            StreamDelta::ReasoningDelta { delta } => ContextEventKind::ReasoningDelta {
279                round_id,
280                delta: delta.clone(),
281            },
282            StreamDelta::ToolCallDelta {
283                call_index,
284                name_delta,
285                arguments_delta,
286                ..
287            } => ContextEventKind::ToolCallDelta {
288                round_id,
289                call_index: *call_index,
290                name_delta: name_delta.clone(),
291                arguments_delta: arguments_delta.clone(),
292            },
293            // Usage / Done / Error ride the terminal TurnOutcome event.
294            StreamDelta::Usage(_) | StreamDelta::Done { .. } | StreamDelta::Error { .. } => {
295                return;
296            }
297        };
298        self.events.lock().unwrap().push(ContextEvent {
299            conversation_id: self.conversation_id.clone(),
300            turn_id: self.turn_id.clone(),
301            kind,
302        });
303    }
304}
305
306/// Project a **streaming** turn into its canonical `ContextEvent` sequence
307/// — the streaming counterpart of [`project_turn`]. The two are mutually
308/// exclusive for the same turn: a turn driven through
309/// `run_streaming` / `run_in_conversation_streaming` projects here, a
310/// batch-driven one through `project_turn`.
311///
312/// ## Inputs
313///
314/// - `context` / `result` / `trace` / `conversation_id` — exactly as in
315///   [`project_turn`].
316/// - `deltas` — the output of the [`StreamEventCollector`] wired into
317///   `TurnRunOptions.interaction` while the turn ran.
318///
319/// ## Output order
320///
321/// 1. `TurnStarted` — exactly once.
322/// 2. Per round, ascending by `round_id` (the union of trace rounds and
323///    delta rounds): that round's delta events in arrival order, then its
324///    `ToolBatchDispatched` if the trace carries a `tool_batch`.
325/// 3. `TurnOutcome` — exactly once, with the full trace.
326///
327/// Events are re-enveloped with this turn's ids, so the projector — not
328/// the collector — owns canonical identity.
329pub fn project_streaming_turn(
330    context: &TurnContext,
331    result: &TurnResult,
332    trace: &TurnTrace,
333    conversation_id: Option<ConversationId>,
334    deltas: Vec<ContextEvent>,
335) -> Vec<ContextEvent> {
336    let turn_id = context.turn_id();
337    let envelope = |kind: ContextEventKind| ContextEvent {
338        conversation_id: conversation_id.clone(),
339        turn_id: turn_id.clone(),
340        kind,
341    };
342    let mut delta_by_round: HashMap<u32, Vec<ContextEvent>> = HashMap::new();
343    for event in deltas {
344        let round = match &event.kind {
345            ContextEventKind::TextDelta { round_id, .. }
346            | ContextEventKind::ReasoningDelta { round_id, .. }
347            | ContextEventKind::ToolCallDelta { round_id, .. } => round_id.0,
348            _ => continue,
349        };
350        delta_by_round.entry(round).or_default().push(event);
351    }
352    let mut rounds: Vec<u32> = trace
353        .rounds
354        .iter()
355        .map(|r| r.round_id.0)
356        .chain(delta_by_round.keys().copied())
357        .collect();
358    rounds.sort_unstable();
359    rounds.dedup();
360
361    let mut events = Vec::with_capacity(2 + rounds.len());
362    events.push(envelope(ContextEventKind::TurnStarted));
363    for round in rounds {
364        if let Some(round_deltas) = delta_by_round.remove(&round) {
365            events.extend(round_deltas);
366        }
367        if let Some(trace_round) = trace
368            .rounds
369            .iter()
370            .find(|r| r.round_id.0 == round)
371            .filter(|r| r.tool_batch.is_some())
372        {
373            let calls = committed_calls(&call_index(context), trace_round);
374            events.push(envelope(ContextEventKind::ToolBatchDispatched {
375                round_id: RoundId(round),
376                calls,
377            }));
378        }
379    }
380    events.push(envelope(ContextEventKind::TurnOutcome {
381        result: result.clone(),
382        trace: trace.clone(),
383    }));
384    events
385}
386
387/// One pass over the facts: committed tool-call blocks indexed by block id.
388fn call_index(context: &TurnContext) -> HashMap<causa_kernel::BlockId, ToolCallPayload> {
389    context
390        .blocks()
391        .iter()
392        .filter_map(|b| match &b.content {
393            BlockContent::ToolCall(call) => Some((b.id.clone(), call.clone())),
394            _ => None,
395        })
396        .collect()
397}
398
399// --- tests ----------------------------------------------------------------
400//
401// Pure-projection tests. They build the kernel data types directly and
402// assert the emitted event sequence and serde shape. No driver, no
403// harness, no async — the projection is sync over borrowed data.
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408    use crate::driver::{OutputSummary, ToolBatchTrace, TurnInterruption};
409    use causa_kernel::{
410        BlockId, BlockSequence, ContextVersion, InvocationId, ModelResponse, ModelStopReason,
411        TextPayload, ToolCallId, TurnContext,
412    };
413    use serde_json::json;
414
415    fn turn_id(byte: u8) -> TurnId {
416        TurnId::new(format!("turn-{byte}"))
417    }
418
419    fn empty_trace() -> TurnTrace {
420        TurnTrace {
421            rounds: Vec::new(),
422            tool_calls_total: 0,
423            total_duration_ms: 0,
424        }
425    }
426
427    /// A turn whose facts contain one text block and one committed tool
428    /// call (sequence 1) — the shape the model door leaves behind.
429    fn turn_with_tool_call(tool: &str) -> TurnContext {
430        let mut ctx = TurnContext::new(turn_id(1));
431        ctx.append_input(TextPayload::new("hi"), "user")
432            .expect("append_input");
433        let response = ModelResponse {
434            text: TextPayload::new(String::new()),
435            tool_calls: vec![causa_kernel::ToolCallDraft {
436                tool_name: tool.to_string(),
437                arguments: json!({"k": "v"}),
438                provider_call_id: None,
439            }],
440        };
441        ctx.append_model_output(
442            InvocationId {
443                turn_id: turn_id(1),
444                round_id: RoundId(0),
445            },
446            &response,
447            ModelStopReason::ToolUse,
448        )
449        .expect("append_model_output");
450        ctx
451    }
452
453    /// Round trace with a tool batch whose `applied_block_ids` point at
454    /// the committed tool-call block (block sequence 1 in
455    /// `turn_with_tool_call`).
456    fn round_with_tool_batch(round_id: RoundId, call_block_seq: u64) -> ModelRoundTrace {
457        ModelRoundTrace {
458            round_id,
459            invocation_id: InvocationId {
460                turn_id: turn_id(1),
461                round_id,
462            },
463            frame_version: ContextVersion(0),
464            attempts: Vec::new(),
465            output_summary: Some(OutputSummary {
466                stop_reason: ModelStopReason::ToolUse,
467                usage: None,
468                tool_call_count: 1,
469                response_text_bytes: 0,
470            }),
471            applied_block_ids: vec![BlockId {
472                turn_id: turn_id(1),
473                sequence: BlockSequence(call_block_seq),
474            }],
475            tool_batch: Some(ToolBatchTrace {
476                calls: vec![],
477                completion_order: Vec::new(),
478            }),
479        }
480    }
481
482    fn round_endturn(round_id: RoundId) -> ModelRoundTrace {
483        ModelRoundTrace {
484            round_id,
485            invocation_id: InvocationId {
486                turn_id: turn_id(2),
487                round_id,
488            },
489            frame_version: ContextVersion(0),
490            attempts: Vec::new(),
491            output_summary: Some(OutputSummary {
492                stop_reason: ModelStopReason::EndTurn,
493                usage: None,
494                tool_call_count: 0,
495                response_text_bytes: 0,
496            }),
497            applied_block_ids: vec![],
498            tool_batch: None,
499        }
500    }
501
502    fn completed() -> TurnResult {
503        TurnResult::Completed {
504            final_output: causa_kernel::ModelOutput {
505                stop_reason: ModelStopReason::EndTurn,
506                usage: None,
507                reasoning: None,
508                response: ModelResponse {
509                    text: TextPayload::new(String::new()),
510                    tool_calls: Vec::new(),
511                },
512            },
513        }
514    }
515
516    #[test]
517    fn empty_trace_emits_only_started_and_outcome() {
518        let ctx = TurnContext::new(turn_id(1));
519        let events = project_turn(&ctx, &completed(), &empty_trace(), None);
520        assert_eq!(events.len(), 2);
521        assert!(matches!(events[0].kind, ContextEventKind::TurnStarted));
522        assert!(matches!(
523            events[1].kind,
524            ContextEventKind::TurnOutcome { .. }
525        ));
526    }
527
528    #[test]
529    fn dispatched_calls_derive_from_committed_tool_call_blocks() {
530        let ctx = turn_with_tool_call("echo");
531        let mut trace = empty_trace();
532        trace.rounds.push(round_with_tool_batch(RoundId(0), 1));
533
534        let events = project_turn(&ctx, &completed(), &trace, None);
535        assert_eq!(events.len(), 3);
536        match &events[1].kind {
537            ContextEventKind::ToolBatchDispatched { round_id, calls } => {
538                assert_eq!(*round_id, RoundId(0));
539                assert_eq!(calls.len(), 1);
540                assert_eq!(calls[0].tool_name, "echo");
541                assert_eq!(calls[0].arguments, json!({"k": "v"}));
542            }
543            other => panic!("expected ToolBatchDispatched, got {other:?}"),
544        }
545    }
546
547    #[test]
548    fn endturn_round_produces_no_dispatch_event() {
549        let ctx = TurnContext::new(turn_id(1));
550        let mut trace = empty_trace();
551        trace.rounds.push(round_endturn(RoundId(7)));
552
553        let events = project_turn(&ctx, &completed(), &trace, None);
554        assert_eq!(
555            events.len(),
556            2,
557            "EndTurn must not produce ToolBatchDispatched"
558        );
559        assert!(matches!(events[0].kind, ContextEventKind::TurnStarted));
560        assert!(matches!(
561            events[1].kind,
562            ContextEventKind::TurnOutcome { .. }
563        ));
564    }
565
566    #[test]
567    fn multiple_rounds_emit_dispatches_in_round_id_order() {
568        // Three rounds: tool_use, endturn, tool_use → two dispatch
569        // events in round order (0, 2), EndTurn round skipped.
570        let ctx = turn_with_tool_call("echo");
571        let mut trace = empty_trace();
572        trace.rounds.push(round_with_tool_batch(RoundId(0), 1));
573        trace.rounds.push(round_endturn(RoundId(1)));
574        trace.rounds.push(round_with_tool_batch(RoundId(2), 1));
575
576        let events = project_turn(&ctx, &completed(), &trace, None);
577        assert_eq!(events.len(), 4);
578        let dispatched_round_ids: Vec<RoundId> = events
579            .iter()
580            .filter_map(|e| match e.kind {
581                ContextEventKind::ToolBatchDispatched { round_id, .. } => Some(round_id),
582                _ => None,
583            })
584            .collect();
585        assert_eq!(dispatched_round_ids, vec![RoundId(0), RoundId(2)]);
586    }
587
588    #[test]
589    fn envelope_routes_conversation_and_turn_ids() {
590        let conv = ConversationId("conv-42".to_string());
591        let ctx = turn_with_tool_call("echo");
592        let mut trace = empty_trace();
593        trace.rounds.push(round_with_tool_batch(RoundId(0), 1));
594
595        let events = project_turn(&ctx, &completed(), &trace, Some(conv.clone()));
596        for e in &events {
597            assert_eq!(e.conversation_id, Some(conv.clone()));
598            assert_eq!(e.turn_id, turn_id(1));
599        }
600        // The bare-run path omits the key on the wire entirely.
601        let bare = project_turn(&ctx, &completed(), &trace, None);
602        let json = serde_json::to_string(&bare[0]).expect("serialize");
603        assert!(!json.contains("conversation_id"));
604    }
605
606    #[test]
607    fn interrupted_turn_carries_cause_in_outcome() {
608        let ctx = TurnContext::new(turn_id(1));
609        let mut trace = empty_trace();
610        trace.rounds.push(round_endturn(RoundId(0)));
611        let cause = TurnInterruption::MaxModelRounds { limit: 8 };
612        let events = project_turn(
613            &ctx,
614            &TurnResult::Interrupted {
615                cause: cause.clone(),
616            },
617            &trace,
618            None,
619        );
620        assert_eq!(events.len(), 2);
621        match &events[1].kind {
622            ContextEventKind::TurnOutcome { result, .. } => match result {
623                TurnResult::Interrupted { cause: c } => assert_eq!(*c, cause),
624                other => panic!("expected Interrupted, got {other:?}"),
625            },
626            other => panic!("expected TurnOutcome, got {other:?}"),
627        }
628    }
629
630    // -- ContextEvent JSON round-trip -------------------------------------
631
632    #[test]
633    fn round_trip_turn_started_no_conversation() {
634        let original = ContextEvent {
635            conversation_id: None,
636            turn_id: turn_id(7),
637            kind: ContextEventKind::TurnStarted,
638        };
639        let json = serde_json::to_string(&original).expect("serialize");
640        // conversation_id is skipped on None — compact wire format; the
641        // discriminator is snake_case under `type`.
642        assert!(!json.contains("conversation_id"));
643        assert!(json.contains("\"type\":\"turn_started\""));
644        let restored: ContextEvent = serde_json::from_str(&json).expect("deserialize");
645        assert_eq!(restored.turn_id, turn_id(7));
646        assert_eq!(restored.conversation_id, None);
647    }
648
649    #[test]
650    fn round_trip_tool_batch_dispatched() {
651        let original = ContextEvent {
652            conversation_id: Some(ConversationId("conv-batch".into())),
653            turn_id: turn_id(11),
654            kind: ContextEventKind::ToolBatchDispatched {
655                round_id: RoundId(3),
656                calls: vec![ToolCallPayload {
657                    call_id: ToolCallId("call-a".into()),
658                    tool_name: "echo".into(),
659                    arguments: json!({"k": "v"}),
660                }],
661            },
662        };
663        let json = serde_json::to_string(&original).expect("serialize");
664        let restored: ContextEvent = serde_json::from_str(&json).expect("deserialize");
665        match restored.kind {
666            ContextEventKind::ToolBatchDispatched { round_id, calls } => {
667                assert_eq!(round_id, RoundId(3));
668                assert_eq!(calls.len(), 1);
669                assert_eq!(calls[0].call_id.0, "call-a");
670            }
671            other => panic!("expected ToolBatchDispatched, got {other:?}"),
672        }
673        assert_eq!(
674            restored.conversation_id,
675            Some(ConversationId("conv-batch".into()))
676        );
677        assert_eq!(restored.turn_id, turn_id(11));
678    }
679
680    #[test]
681    fn round_trip_turn_outcome_completed_and_interrupted() {
682        let completed_event = ContextEvent {
683            conversation_id: Some(ConversationId("conv-out".into())),
684            turn_id: turn_id(99),
685            kind: ContextEventKind::TurnOutcome {
686                result: completed(),
687                trace: empty_trace(),
688            },
689        };
690        let json = serde_json::to_string(&completed_event).expect("serialize");
691        let restored: ContextEvent = serde_json::from_str(&json).expect("deserialize");
692        assert!(matches!(
693            restored.kind,
694            ContextEventKind::TurnOutcome {
695                result: TurnResult::Completed { .. },
696                ..
697            }
698        ));
699
700        let interrupted_event = ContextEvent {
701            conversation_id: None,
702            turn_id: turn_id(13),
703            kind: ContextEventKind::TurnOutcome {
704                result: TurnResult::Interrupted {
705                    cause: TurnInterruption::CompactionFailed {
706                        reason: "budget exceeded".into(),
707                    },
708                },
709                trace: empty_trace(),
710            },
711        };
712        let json = serde_json::to_string(&interrupted_event).expect("serialize");
713        let restored: ContextEvent = serde_json::from_str(&json).expect("deserialize");
714        match restored.kind {
715            ContextEventKind::TurnOutcome {
716                result: TurnResult::Interrupted { cause },
717                ..
718            } => assert_eq!(
719                cause,
720                TurnInterruption::CompactionFailed {
721                    reason: "budget exceeded".into()
722                }
723            ),
724            other => panic!("expected TurnOutcome Interrupted, got {other:?}"),
725        }
726    }
727
728    #[test]
729    fn project_turn_output_survives_serialization_round_trip() {
730        let ctx = turn_with_tool_call("echo");
731        let mut trace = empty_trace();
732        trace.rounds.push(round_with_tool_batch(RoundId(0), 1));
733
734        let events = project_turn(
735            &ctx,
736            &completed(),
737            &trace,
738            Some(ConversationId("conv-e2e".into())),
739        );
740        let json = serde_json::to_string(&events).expect("serialize");
741        let restored: Vec<ContextEvent> = serde_json::from_str(&json).expect("deserialize");
742        assert_eq!(restored.len(), events.len());
743        // All events carry the same conversation id and turn id.
744        for e in &restored {
745            assert_eq!(e.conversation_id, Some(ConversationId("conv-e2e".into())));
746            assert_eq!(e.turn_id, turn_id(1));
747        }
748        // The middle event is a ToolBatchDispatched with the one call.
749        match &restored[1].kind {
750            ContextEventKind::ToolBatchDispatched { calls, .. } => {
751                assert_eq!(calls.len(), 1);
752            }
753            other => panic!("expected ToolBatchDispatched, got {other:?}"),
754        }
755    }
756
757    // -- streaming-variant serialization pins ------------------------------
758
759    #[test]
760    fn round_trip_streaming_delta_variants() {
761        let variants = vec![
762            ContextEvent {
763                conversation_id: Some(ConversationId("conv-s".into())),
764                turn_id: turn_id(21),
765                kind: ContextEventKind::TextDelta {
766                    round_id: RoundId(1),
767                    delta: "he".into(),
768                },
769            },
770            ContextEvent {
771                conversation_id: None,
772                turn_id: turn_id(22),
773                kind: ContextEventKind::ReasoningDelta {
774                    round_id: RoundId(0),
775                    delta: "pondering".into(),
776                },
777            },
778            ContextEvent {
779                conversation_id: None,
780                turn_id: turn_id(23),
781                kind: ContextEventKind::ToolCallDelta {
782                    round_id: RoundId(2),
783                    call_index: 1,
784                    name_delta: Some("echo".into()),
785                    arguments_delta: Some("{\"a\":1}".into()),
786                },
787            },
788        ];
789        for original in variants {
790            let json = serde_json::to_string(&original).expect("serialize");
791            let restored: ContextEvent = serde_json::from_str(&json).expect("deserialize");
792            assert_eq!(
793                serde_json::to_string(&restored).expect("re-serialize"),
794                json,
795                "round-trip must be stable"
796            );
797        }
798    }
799
800    #[test]
801    fn streaming_delta_wire_discriminators_are_pinned() {
802        let event = ContextEvent {
803            conversation_id: None,
804            turn_id: turn_id(1),
805            kind: ContextEventKind::TextDelta {
806                round_id: RoundId(0),
807                delta: "x".into(),
808            },
809        };
810        let json = serde_json::to_string(&event).expect("serialize");
811        assert!(json.contains("\"type\":\"text_delta\""), "{json}");
812        assert!(json.contains("\"round_id\":0"), "{json}");
813
814        let call = ContextEvent {
815            conversation_id: None,
816            turn_id: turn_id(1),
817            kind: ContextEventKind::ToolCallDelta {
818                round_id: RoundId(0),
819                call_index: 0,
820                name_delta: Some("echo".into()),
821                arguments_delta: None,
822            },
823        };
824        let json = serde_json::to_string(&call).expect("serialize");
825        assert!(json.contains("\"type\":\"tool_call_delta\""), "{json}");
826        // A None delta field is skipped on the wire (Option serialization
827        // without skip flags keeps nulls — pin whatever the derive does).
828        let reasoning = ContextEvent {
829            conversation_id: None,
830            turn_id: turn_id(1),
831            kind: ContextEventKind::ReasoningDelta {
832                round_id: RoundId(0),
833                delta: "r".into(),
834            },
835        };
836        let json = serde_json::to_string(&reasoning).expect("serialize");
837        assert!(json.contains("\"type\":\"reasoning_delta\""), "{json}");
838    }
839
840    #[test]
841    fn collector_maps_deltas_and_skips_terminal_ones() {
842        let collector = StreamEventCollector::new(turn_id(9), None);
843        let deltas = vec![
844            StreamDelta::TextDelta { delta: "he".into() },
845            StreamDelta::ReasoningDelta { delta: "th".into() },
846            StreamDelta::ToolCallDelta {
847                call_index: 0,
848                provider_call_id: Some("p1".into()),
849                name_delta: Some("echo".into()),
850                arguments_delta: None,
851            },
852            StreamDelta::Usage(causa_kernel::ModelUsage {
853                input_tokens: 1,
854                output_tokens: 2,
855                cache_read_tokens: None,
856                cache_write_tokens: None,
857                reasoning_tokens: None,
858            }),
859            StreamDelta::Done {
860                stop_reason: ModelStopReason::EndTurn,
861                final_output: causa_kernel::ModelOutput {
862                    response: ModelResponse {
863                        text: TextPayload::new("he"),
864                        tool_calls: vec![],
865                    },
866                    usage: None,
867                    stop_reason: ModelStopReason::EndTurn,
868                    reasoning: None,
869                },
870            },
871            StreamDelta::Error {
872                kind: causa_kernel::ModelInvokeErrorKind::Transient,
873                message: "x".into(),
874            },
875        ];
876        let rt = tokio::runtime::Runtime::new().unwrap();
877        for d in &deltas {
878            rt.block_on(collector.on_delta(RoundId(4), d));
879        }
880        let events = collector.into_events();
881        // Usage / Done / Error ride the terminal TurnOutcome event only.
882        assert_eq!(events.len(), 3);
883        assert!(matches!(
884            events[0].kind,
885            ContextEventKind::TextDelta {
886                round_id: RoundId(4),
887                ..
888            }
889        ));
890        assert!(matches!(
891            events[1].kind,
892            ContextEventKind::ReasoningDelta { .. }
893        ));
894        match &events[2].kind {
895            ContextEventKind::ToolCallDelta {
896                call_index,
897                name_delta,
898                ..
899            } => {
900                assert_eq!(*call_index, 0);
901                assert_eq!(name_delta.as_deref(), Some("echo"));
902            }
903            other => panic!("expected ToolCallDelta, got {other:?}"),
904        }
905    }
906}