Skip to main content

agent_base/types/
events.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4use agent_types::NoticeKind;
5
6use super::approval::ApprovalRequest;
7use super::checkpoint::CheckpointData;
8use super::plan_update::PlanItem;
9use super::session::SessionId;
10
11// ---------------------------------------------------------------------------
12// UserEvent — user-space events produced by tools
13// ---------------------------------------------------------------------------
14
15/// User-space events produced by tools during execution.
16///
17/// Tools send these through `ToolContext::emit_user_event()`. The framework
18/// wraps them in [`RuntimeEvent::UserEvent`] before delivering to external
19/// consumers.
20#[derive(Clone, Debug, Serialize, Deserialize)]
21#[serde(tag = "userEventType", rename_all = "camelCase")]
22pub enum UserEvent {
23    /// Tool progress notification.
24    Progress { text: String },
25    /// User-defined structured event for custom business semantics.
26    Structured { event_type: String, data: Value },
27    /// Tool partial result — emitted during long-running tool execution.
28    /// `is_partial: true` means more output is coming; `false` means this is the final chunk.
29    ToolPartialResult {
30        tool_call_id: String,
31        content: String,
32        is_partial: bool,
33    },
34    /// Display-only notice from an engine mechanism (guard degradation,
35    /// reaper, ...). `text` is a mechanism-level English fact; product layers
36    /// may rewrite it per `source`. `source` is a `String` (not `&'static str`)
37    /// because `UserEvent` must deserialize across process boundaries.
38    Notice {
39        kind: NoticeKind,
40        source: String,
41        text: String,
42    },
43}
44
45// ---------------------------------------------------------------------------
46// RuntimeEvent — unified event stream for all consumers
47// ---------------------------------------------------------------------------
48
49/// Unified runtime event — the single event type for both internal and external
50/// consumers (frontends, CLIs, tests).
51#[derive(Clone, Debug, Serialize, Deserialize)]
52#[serde(tag = "runtimeEventType", rename_all = "camelCase")]
53pub enum RuntimeEvent {
54    // --- Framework system events ---
55    TextDelta {
56        session_id: SessionId,
57        text: String,
58        /// Identifies the agent that produced this event (root / sub-agent path).
59        #[serde(default, skip_serializing_if = "Option::is_none")]
60        agent_id: Option<String>,
61        /// Distributed tracing context carried across systems (e.g. MCP caller → phi-agent).
62        #[serde(default, skip_serializing_if = "Option::is_none")]
63        trace_id: Option<String>,
64    },
65    ThoughtDelta {
66        session_id: SessionId,
67        text: String,
68        #[serde(default, skip_serializing_if = "Option::is_none")]
69        agent_id: Option<String>,
70        #[serde(default, skip_serializing_if = "Option::is_none")]
71        trace_id: Option<String>,
72    },
73    /// A tool call that is still being streamed into existence.
74    ///
75    /// Tool-call arguments arrive as fragments and are only materialized into
76    /// a [`RuntimeEvent::ActionStarted`] once the whole turn's stream is
77    /// drained — multi-KB arguments (a `spawn_agent` task brief) are invisible
78    /// to every consumer until then. This event makes that window observable:
79    /// coarse progress on the call being drafted (`index`), enough for a UI to
80    /// say "writing tool calls" instead of looking hung. It carries no
81    /// argument text, only a size, and is throttled at the source.
82    #[serde(alias = "toolCallDraft")]
83    ActionDraft {
84        session_id: SessionId,
85        /// The call's stream index within this turn (its eventual tool-call
86        /// id is not known yet).
87        index: usize,
88        /// Function name, empty until the fragment carrying it arrives.
89        name: String,
90        /// Argument characters accumulated for this call so far.
91        args_len: usize,
92        /// How many calls this turn has produced so far (drafts included).
93        count: usize,
94        #[serde(default, skip_serializing_if = "Option::is_none")]
95        agent_id: Option<String>,
96        #[serde(default, skip_serializing_if = "Option::is_none")]
97        trace_id: Option<String>,
98    },
99    #[serde(alias = "toolCallStarted")]
100    ActionStarted {
101        session_id: SessionId,
102        tool_name: String,
103        args_json: String,
104        #[serde(default, skip_serializing_if = "Option::is_none")]
105        agent_id: Option<String>,
106        #[serde(default, skip_serializing_if = "Option::is_none")]
107        trace_id: Option<String>,
108    },
109    /// A corrupt tool-call batch was discarded whole and the LLM re-asked
110    /// (turn-as-transaction). Carries the discarded response so the session's
111    /// event log keeps the evidence: the raw tool calls (arguments still
112    /// broken — that IS the evidence), the structural facts, and the text the
113    /// round carried.
114    #[serde(alias = "integrityDiscard")]
115    IntegrityDiscard {
116        session_id: SessionId,
117        /// Turn the discard happened in.
118        turn: u32,
119        /// Silent retries already spent on this logical round.
120        retries_in_round: u32,
121        /// Named tool calls whose arguments did not parse.
122        invalid_args: usize,
123        /// Bytes of args fragments that landed on name-less buckets (the
124        /// provider leaked the tail past its owning block).
125        orphan_args_bytes: usize,
126        /// The discarded calls, verbatim (arguments as the provider sent them).
127        tool_calls: Vec<serde_json::Value>,
128        /// The text the discarded round carried (empty on silent rounds).
129        text: String,
130    },
131    #[serde(alias = "toolCallFinished")]
132    ActionFinished {
133        session_id: SessionId,
134        tool_name: String,
135        summary: String,
136        #[serde(default, skip_serializing_if = "Option::is_none")]
137        agent_id: Option<String>,
138        #[serde(default, skip_serializing_if = "Option::is_none")]
139        trace_id: Option<String>,
140        /// `true` when this finish is the result of an approval denial (not a
141        /// normal tool result or execution error).
142        #[serde(default)]
143        denied: bool,
144        /// Structured metadata from the tool result (e.g. edit line numbers).
145        /// Carried through to UI consumers; never sent to the LLM.
146        #[serde(default, skip_serializing_if = "Option::is_none")]
147        details: Option<Value>,
148    },
149    AwaitingApproval {
150        session_id: SessionId,
151        request: ApprovalRequest,
152        #[serde(default, skip_serializing_if = "Option::is_none")]
153        agent_id: Option<String>,
154        #[serde(default, skip_serializing_if = "Option::is_none")]
155        trace_id: Option<String>,
156    },
157    Checkpoint {
158        session_id: SessionId,
159        /// Boxed so the announcement event stays small on the hot path (every
160        /// RuntimeEvent copy is as big as its largest variant).
161        checkpoint: Box<CheckpointData>,
162        #[serde(default, skip_serializing_if = "Option::is_none")]
163        agent_id: Option<String>,
164        #[serde(default, skip_serializing_if = "Option::is_none")]
165        trace_id: Option<String>,
166    },
167    RunFinished {
168        session_id: SessionId,
169        #[serde(default, skip_serializing_if = "Option::is_none")]
170        agent_id: Option<String>,
171        #[serde(default, skip_serializing_if = "Option::is_none")]
172        trace_id: Option<String>,
173    },
174    RunCancelled {
175        session_id: SessionId,
176        #[serde(default, skip_serializing_if = "Option::is_none")]
177        agent_id: Option<String>,
178        #[serde(default, skip_serializing_if = "Option::is_none")]
179        trace_id: Option<String>,
180    },
181    // --- Lightweight plan update (display-only, no execution semantics) ---
182    PlanUpdated {
183        session_id: SessionId,
184        objective: String,
185        explanation: Option<String>,
186        plan: Vec<PlanItem>,
187        #[serde(default, skip_serializing_if = "Option::is_none")]
188        agent_id: Option<String>,
189        #[serde(default, skip_serializing_if = "Option::is_none")]
190        trace_id: Option<String>,
191    },
192    // --- User-space events ---
193    /// A user-space event produced by a tool.
194    UserEvent {
195        session_id: SessionId,
196        event: UserEvent,
197        #[serde(default, skip_serializing_if = "Option::is_none")]
198        agent_id: Option<String>,
199        #[serde(default, skip_serializing_if = "Option::is_none")]
200        trace_id: Option<String>,
201    },
202}
203
204impl RuntimeEvent {
205    /// Get the session ID associated with this event.
206    pub fn session_id(&self) -> &SessionId {
207        match self {
208            RuntimeEvent::TextDelta { session_id, .. } => session_id,
209            RuntimeEvent::ThoughtDelta { session_id, .. } => session_id,
210            RuntimeEvent::ActionDraft { session_id, .. } => session_id,
211            RuntimeEvent::ActionStarted { session_id, .. } => session_id,
212            RuntimeEvent::IntegrityDiscard { session_id, .. } => session_id,
213            RuntimeEvent::ActionFinished { session_id, .. } => session_id,
214            RuntimeEvent::AwaitingApproval { session_id, .. } => session_id,
215            RuntimeEvent::Checkpoint { session_id, .. } => session_id,
216            RuntimeEvent::RunFinished { session_id, .. } => session_id,
217            RuntimeEvent::RunCancelled { session_id, .. } => session_id,
218            RuntimeEvent::PlanUpdated { session_id, .. } => session_id,
219            RuntimeEvent::UserEvent { session_id, .. } => session_id,
220        }
221    }
222
223    /// Get the agent ID associated with this event, if any.
224    pub fn agent_id(&self) -> Option<&str> {
225        match self {
226            RuntimeEvent::TextDelta { agent_id, .. } => agent_id.as_deref(),
227            RuntimeEvent::ThoughtDelta { agent_id, .. } => agent_id.as_deref(),
228            RuntimeEvent::ActionDraft { agent_id, .. } => agent_id.as_deref(),
229            RuntimeEvent::ActionStarted { agent_id, .. } => agent_id.as_deref(),
230            RuntimeEvent::ActionFinished { agent_id, .. } => agent_id.as_deref(),
231            RuntimeEvent::AwaitingApproval { agent_id, .. } => agent_id.as_deref(),
232            RuntimeEvent::Checkpoint { agent_id, .. } => agent_id.as_deref(),
233            RuntimeEvent::RunFinished { agent_id, .. } => agent_id.as_deref(),
234            RuntimeEvent::RunCancelled { agent_id, .. } => agent_id.as_deref(),
235            RuntimeEvent::PlanUpdated { agent_id, .. } => agent_id.as_deref(),
236            RuntimeEvent::UserEvent { agent_id, .. } => agent_id.as_deref(),
237            RuntimeEvent::IntegrityDiscard { .. } => None,
238        }
239    }
240
241    /// Get the trace ID associated with this event, if any.
242    pub fn trace_id(&self) -> Option<&str> {
243        match self {
244            RuntimeEvent::TextDelta { trace_id, .. } => trace_id.as_deref(),
245            RuntimeEvent::ThoughtDelta { trace_id, .. } => trace_id.as_deref(),
246            RuntimeEvent::ActionDraft { trace_id, .. } => trace_id.as_deref(),
247            RuntimeEvent::ActionStarted { trace_id, .. } => trace_id.as_deref(),
248            RuntimeEvent::ActionFinished { trace_id, .. } => trace_id.as_deref(),
249            RuntimeEvent::AwaitingApproval { trace_id, .. } => trace_id.as_deref(),
250            RuntimeEvent::Checkpoint { trace_id, .. } => trace_id.as_deref(),
251            RuntimeEvent::RunFinished { trace_id, .. } => trace_id.as_deref(),
252            RuntimeEvent::RunCancelled { trace_id, .. } => trace_id.as_deref(),
253            RuntimeEvent::PlanUpdated { trace_id, .. } => trace_id.as_deref(),
254            RuntimeEvent::UserEvent { trace_id, .. } => trace_id.as_deref(),
255            RuntimeEvent::IntegrityDiscard { .. } => None,
256        }
257    }
258
259    /// Set the agent ID (sub-agent path) on this event.
260    pub fn with_agent_id(mut self, id: impl Into<String>) -> Self {
261        let id = id.into();
262        match &mut self {
263            RuntimeEvent::TextDelta { agent_id, .. }
264            | RuntimeEvent::ThoughtDelta { agent_id, .. }
265            | RuntimeEvent::ActionDraft { agent_id, .. }
266            | RuntimeEvent::ActionStarted { agent_id, .. }
267            | RuntimeEvent::ActionFinished { agent_id, .. }
268            | RuntimeEvent::AwaitingApproval { agent_id, .. }
269            | RuntimeEvent::Checkpoint { agent_id, .. }
270            | RuntimeEvent::RunFinished { agent_id, .. }
271            | RuntimeEvent::RunCancelled { agent_id, .. }
272            | RuntimeEvent::PlanUpdated { agent_id, .. }
273            | RuntimeEvent::UserEvent { agent_id, .. } => *agent_id = Some(id),
274            // Session-scoped event: no agent path to stamp.
275            RuntimeEvent::IntegrityDiscard { .. } => {}
276        }
277        self
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use crate::types::{
285        ActionFormat, CheckpointStep, MigrationKind, PlanStepStatus, RiskLevel, RunState,
286    };
287
288    fn sid(id: u64) -> SessionId {
289        SessionId::new(id)
290    }
291
292    fn approval_request() -> ApprovalRequest {
293        ApprovalRequest {
294            title: "title".to_string(),
295            message: "message".to_string(),
296            action_key: None,
297            risk_level: RiskLevel::Safe,
298            raw: None,
299            source: None,
300        }
301    }
302
303    fn checkpoint() -> CheckpointData {
304        CheckpointData::new(
305            sid(42),
306            "input",
307            CheckpointStep::AfterUserInput,
308            0,
309            ActionFormat::ToolCall,
310            RunState::default(),
311        )
312    }
313
314    #[test]
315    fn checkpoint_event_reads_pre_m3_jsonl_fixture() {
316        // A journal line written by a pre-M3 binary: tool-call triples, no
317        // version/backend fields. Must decode with its migration mark intact
318        // (旧 checkpoint/JSONL fixture → 新二进制可读).
319        let line = r#"{"runtimeEventType":"checkpoint","session_id":{"id":7,"external_id":"s7"},"checkpoint":{"session_id":{"id":7,"external_id":"s7"},"user_input":"resume me","step":{"BeforeToolCalls":{"tool_calls":[["call_1","echo","{\"text\":\"hi\"}"]]}},"turn_count":2}}"#;
320        let event: RuntimeEvent = serde_json::from_str(line).unwrap();
321        match event {
322            RuntimeEvent::Checkpoint { checkpoint, .. } => {
323                assert_eq!(checkpoint.version, 0);
324                assert_eq!(checkpoint.backend, ActionFormat::ToolCall);
325                let mark = checkpoint
326                    .migrated_from
327                    .as_ref()
328                    .expect("legacy payload must carry its source mark");
329                assert_eq!(mark.kind, MigrationKind::ToolCallTriplesV0);
330                match &checkpoint.step {
331                    CheckpointStep::BeforeActions { actions } => {
332                        assert_eq!(actions.len(), 1);
333                        assert_eq!(actions[0].id, "call_1");
334                        assert_eq!(actions[0].name, "echo");
335                        assert_eq!(actions[0].raw_args(), r#"{"text":"hi"}"#);
336                    }
337                    other => panic!("expected BeforeActions, got {other:?}"),
338                }
339            }
340            other => panic!("expected Checkpoint event, got {other:?}"),
341        }
342    }
343
344    #[test]
345    fn accessors_return_embedded_ids_for_all_variants() {
346        let events: Vec<RuntimeEvent> = vec![
347            RuntimeEvent::TextDelta {
348                session_id: sid(1),
349                text: "hi".into(),
350                agent_id: Some("a".into()),
351                trace_id: Some("t".into()),
352            },
353            RuntimeEvent::ThoughtDelta {
354                session_id: sid(2),
355                text: "hmm".into(),
356                agent_id: Some("a".into()),
357                trace_id: Some("t".into()),
358            },
359            RuntimeEvent::ActionStarted {
360                session_id: sid(3),
361                tool_name: "read".into(),
362                args_json: "{}".into(),
363                agent_id: Some("a".into()),
364                trace_id: Some("t".into()),
365            },
366            RuntimeEvent::ActionFinished {
367                session_id: sid(4),
368                tool_name: "read".into(),
369                summary: "ok".into(),
370                agent_id: Some("a".into()),
371                trace_id: Some("t".into()),
372                denied: false,
373                details: None,
374            },
375            RuntimeEvent::AwaitingApproval {
376                session_id: sid(5),
377                request: approval_request(),
378                agent_id: Some("a".into()),
379                trace_id: Some("t".into()),
380            },
381            RuntimeEvent::Checkpoint {
382                session_id: sid(6),
383                checkpoint: Box::new(checkpoint()),
384                agent_id: Some("a".into()),
385                trace_id: Some("t".into()),
386            },
387            RuntimeEvent::RunFinished {
388                session_id: sid(7),
389                agent_id: Some("a".into()),
390                trace_id: Some("t".into()),
391            },
392            RuntimeEvent::RunCancelled {
393                session_id: sid(8),
394                agent_id: Some("a".into()),
395                trace_id: Some("t".into()),
396            },
397            RuntimeEvent::PlanUpdated {
398                session_id: sid(9),
399                objective: "goal".into(),
400                explanation: None,
401                plan: vec![PlanItem {
402                    step: "s".into(),
403                    status: PlanStepStatus::Pending,
404                }],
405                agent_id: Some("a".into()),
406                trace_id: Some("t".into()),
407            },
408            RuntimeEvent::UserEvent {
409                session_id: sid(10),
410                event: UserEvent::Progress { text: "p".into() },
411                agent_id: Some("a".into()),
412                trace_id: Some("t".into()),
413            },
414            RuntimeEvent::ActionDraft {
415                session_id: sid(11),
416                index: 0,
417                name: "spawn_agent".into(),
418                args_len: 512,
419                count: 1,
420                agent_id: Some("a".into()),
421                trace_id: Some("t".into()),
422            },
423        ];
424
425        for (i, ev) in events.iter().enumerate() {
426            let expected = i as u64 + 1;
427            assert_eq!(ev.session_id(), &sid(expected), "variant {i}");
428            assert_eq!(ev.agent_id(), Some("a"), "variant {i}");
429            assert_eq!(ev.trace_id(), Some("t"), "variant {i}");
430        }
431    }
432
433    #[test]
434    fn with_agent_id_sets_id_on_all_variants() {
435        let events: Vec<RuntimeEvent> = vec![
436            RuntimeEvent::TextDelta {
437                session_id: sid(1),
438                text: "hi".into(),
439                agent_id: None,
440                trace_id: None,
441            },
442            RuntimeEvent::ThoughtDelta {
443                session_id: sid(2),
444                text: "hmm".into(),
445                agent_id: None,
446                trace_id: None,
447            },
448            RuntimeEvent::ActionStarted {
449                session_id: sid(3),
450                tool_name: "read".into(),
451                args_json: "{}".into(),
452                agent_id: None,
453                trace_id: None,
454            },
455            RuntimeEvent::ActionFinished {
456                session_id: sid(4),
457                tool_name: "read".into(),
458                summary: "ok".into(),
459                agent_id: None,
460                trace_id: None,
461                denied: false,
462                details: None,
463            },
464            RuntimeEvent::AwaitingApproval {
465                session_id: sid(5),
466                request: approval_request(),
467                agent_id: None,
468                trace_id: None,
469            },
470            RuntimeEvent::Checkpoint {
471                session_id: sid(6),
472                checkpoint: Box::new(checkpoint()),
473                agent_id: None,
474                trace_id: None,
475            },
476            RuntimeEvent::RunFinished {
477                session_id: sid(7),
478                agent_id: None,
479                trace_id: None,
480            },
481            RuntimeEvent::RunCancelled {
482                session_id: sid(8),
483                agent_id: None,
484                trace_id: None,
485            },
486            RuntimeEvent::PlanUpdated {
487                session_id: sid(9),
488                objective: "goal".into(),
489                explanation: None,
490                plan: vec![PlanItem {
491                    step: "s".into(),
492                    status: PlanStepStatus::Pending,
493                }],
494                agent_id: None,
495                trace_id: None,
496            },
497            RuntimeEvent::UserEvent {
498                session_id: sid(10),
499                event: UserEvent::Progress { text: "p".into() },
500                agent_id: None,
501                trace_id: None,
502            },
503            RuntimeEvent::ActionDraft {
504                session_id: sid(11),
505                index: 0,
506                name: "spawn_agent".into(),
507                args_len: 512,
508                count: 1,
509                agent_id: None,
510                trace_id: None,
511            },
512        ];
513
514        for (i, ev) in events.into_iter().enumerate() {
515            let tagged = ev.with_agent_id("sub/1");
516            assert_eq!(tagged.agent_id(), Some("sub/1"), "variant {i}");
517            assert_eq!(tagged.session_id(), &sid(i as u64 + 1), "variant {i}");
518        }
519    }
520
521    #[test]
522    fn accessors_return_none_when_ids_absent() {
523        let ev = RuntimeEvent::RunFinished {
524            session_id: sid(1),
525            agent_id: None,
526            trace_id: None,
527        };
528        assert_eq!(ev.session_id(), &sid(1));
529        assert_eq!(ev.agent_id(), None);
530        assert_eq!(ev.trace_id(), None);
531    }
532
533    #[test]
534    fn runtime_event_serde_uses_camel_case_tag() {
535        let ev = RuntimeEvent::ActionStarted {
536            session_id: SessionId::with_external_id(7, "ext"),
537            tool_name: "read".into(),
538            args_json: "{}".into(),
539            agent_id: Some("a".into()),
540            trace_id: None,
541        };
542        let v = serde_json::to_value(&ev).unwrap();
543        assert_eq!(v["runtimeEventType"], "actionStarted");
544        assert_eq!(v["session_id"]["id"], serde_json::json!(7));
545        assert_eq!(v["session_id"]["external_id"], "ext");
546        // trace_id is None → field skipped
547        assert!(v.get("trace_id").is_none());
548
549        let back: RuntimeEvent = serde_json::from_value(v).unwrap();
550        assert_eq!(back.session_id(), &SessionId::with_external_id(7, "ext"));
551        assert_eq!(back.agent_id(), Some("a"));
552        assert_eq!(back.trace_id(), None);
553    }
554
555    #[test]
556    fn tool_call_draft_serde_round_trip() {
557        let ev = RuntimeEvent::ActionDraft {
558            session_id: sid(3),
559            index: 2,
560            name: "spawn_agent".into(),
561            args_len: 640,
562            count: 4,
563            agent_id: None,
564            trace_id: None,
565        };
566        let v = serde_json::to_value(&ev).unwrap();
567        assert_eq!(v["runtimeEventType"], "actionDraft");
568        assert_eq!(v["args_len"], 640);
569        assert!(v.get("agent_id").is_none(), "None ids stay skipped");
570
571        // Old wire names (pre-M3 rename) still deserialize via serde alias.
572        let mut old = v.clone();
573        old["runtimeEventType"] = serde_json::json!("toolCallDraft");
574        let legacy: RuntimeEvent = serde_json::from_value(old).unwrap();
575        assert!(matches!(legacy, RuntimeEvent::ActionDraft { .. }));
576
577        let back: RuntimeEvent = serde_json::from_value(v).unwrap();
578        match back {
579            RuntimeEvent::ActionDraft {
580                index,
581                name,
582                args_len,
583                count,
584                ..
585            } => {
586                assert_eq!(index, 2);
587                assert_eq!(name, "spawn_agent");
588                assert_eq!(args_len, 640);
589                assert_eq!(count, 4);
590            }
591            other => panic!("expected ActionDraft, got {other:?}"),
592        }
593    }
594
595    #[test]
596    fn user_event_serde_tag() {
597        let v = serde_json::to_value(UserEvent::Progress {
598            text: "working".into(),
599        })
600        .unwrap();
601        assert_eq!(v["userEventType"], "progress");
602        assert_eq!(v["text"], "working");
603
604        let v = serde_json::to_value(UserEvent::Structured {
605            event_type: "custom".into(),
606            data: serde_json::json!({"k": 1}),
607        })
608        .unwrap();
609        assert_eq!(v["userEventType"], "structured");
610        assert_eq!(v["data"]["k"], serde_json::json!(1));
611    }
612
613    // Design doc §9: UserEvent::Notice serialization tag + serde round-trip
614    // (source must be String — &'static str cannot deserialize).
615    #[test]
616    fn user_event_notice_serde_round_trip() {
617        let ev = UserEvent::Notice {
618            kind: NoticeKind::Warning,
619            source: "guard".into(),
620            text: "guard judge unparsed — treating as complete".into(),
621        };
622        let v = serde_json::to_value(&ev).unwrap();
623        assert_eq!(v["userEventType"], "notice");
624        assert_eq!(v["kind"], serde_json::json!("warning"));
625        assert_eq!(v["source"], serde_json::json!("guard"));
626        assert_eq!(
627            v["text"],
628            serde_json::json!("guard judge unparsed — treating as complete")
629        );
630
631        let back: UserEvent = serde_json::from_value(v).unwrap();
632        match back {
633            UserEvent::Notice { kind, source, text } => {
634                assert_eq!(kind, NoticeKind::Warning);
635                assert_eq!(source, "guard");
636                assert_eq!(text, "guard judge unparsed — treating as complete");
637            }
638            other => panic!("expected Notice, got {other:?}"),
639        }
640    }
641
642    // Design doc §11: old JSONL replay — a Notice serialized elsewhere must
643    // deserialize cleanly alongside existing variants (serde is add-only).
644    #[test]
645    fn notice_coexists_with_legacy_variants_on_replay() {
646        let json = r#"{"userEventType":"progress","text":"legacy line"}"#;
647        let back: UserEvent = serde_json::from_str(json).unwrap();
648        assert!(matches!(back, UserEvent::Progress { .. }));
649    }
650}