Skip to main content

arabica_protocol/
lib.rs

1//! Canonical wire contract for Structure.
2//!
3//! Every UI sends [`CommandEnvelope`] values and observes [`EventEnvelope`]
4//! values. Runtime, session, and runner modules must not invent parallel wire
5//! types.
6
7mod trace;
8pub use trace::*;
9
10mod context;
11pub use context::*;
12
13pub mod lrp;
14
15use arabica_model::{
16    FinishReason, ProviderResponseState, ProviderState, RuntimeItem, RuntimeRequest, RuntimeUsage,
17};
18use schemars::{JsonSchema, Schema, schema_for};
19use serde::{Deserialize, Serialize};
20
21pub const PROTOCOL_VERSION: &str = "1.0";
22
23macro_rules! string_id {
24    ($name:ident) => {
25        #[derive(
26            Clone, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
27        )]
28        #[serde(transparent)]
29        pub struct $name(pub String);
30
31        impl $name {
32            pub fn new(value: impl Into<String>) -> Self {
33                Self(value.into())
34            }
35
36            pub fn as_str(&self) -> &str {
37                &self.0
38            }
39        }
40
41        impl std::ops::Deref for $name {
42            type Target = str;
43            fn deref(&self) -> &Self::Target {
44                &self.0
45            }
46        }
47
48        impl std::borrow::Borrow<str> for $name {
49            fn borrow(&self) -> &str {
50                &self.0
51            }
52        }
53
54        impl std::fmt::Display for $name {
55            fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56                self.0.fmt(formatter)
57            }
58        }
59    };
60}
61
62string_id!(CommandId);
63string_id!(EventId);
64string_id!(SessionId);
65string_id!(RunId);
66string_id!(WorkspaceId);
67
68#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
69pub struct CommandEnvelope {
70    pub protocol_version: String,
71    pub command_id: CommandId,
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub session_id: Option<SessionId>,
74    pub command: Command,
75}
76
77impl CommandEnvelope {
78    pub fn new(command_id: CommandId, session_id: Option<SessionId>, command: Command) -> Self {
79        Self {
80            protocol_version: PROTOCOL_VERSION.to_owned(),
81            command_id,
82            session_id,
83            command,
84        }
85    }
86}
87
88#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
89#[serde(tag = "type", content = "payload")]
90pub enum Command {
91    #[serde(rename = "session.create")]
92    SessionCreate { workspace_id: WorkspaceId },
93    #[serde(rename = "session.fork")]
94    SessionFork { source_session_id: SessionId },
95    #[serde(rename = "session.resume")]
96    SessionResume,
97    #[serde(rename = "session.suspend")]
98    SessionSuspend,
99    #[serde(rename = "session.close")]
100    SessionClose,
101    #[serde(rename = "message.send")]
102    MessageSend {
103        content: String,
104        #[serde(default, skip_serializing_if = "Vec::is_empty")]
105        images: Vec<arabica_model::ImageInput>,
106    },
107    #[serde(rename = "run.cancel")]
108    RunCancel { run_id: RunId },
109    #[serde(rename = "context.read")]
110    ContextRead { path: String },
111    #[serde(rename = "context.search")]
112    ContextSearch { query: String },
113    #[serde(rename = "context.update")]
114    ContextUpdate { path: String, content: String },
115    #[serde(rename = "context.delete")]
116    ContextDelete { path: String },
117    #[serde(rename = "context.set_disclosure")]
118    ContextSetDisclosure { level: DisclosureLevel },
119}
120
121#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
122#[serde(rename_all = "snake_case")]
123pub enum DisclosureLevel {
124    Glance,
125    Overview,
126    Detail,
127}
128
129#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
130pub struct ContextEntry {
131    pub path: String,
132    pub content: String,
133}
134
135#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
136#[serde(rename_all = "snake_case")]
137pub enum OutputStream {
138    Stdout,
139    Stderr,
140}
141
142#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
143#[serde(rename_all = "snake_case")]
144pub enum SessionStatus {
145    Active,
146    Suspended,
147    Closed,
148}
149
150#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
151#[serde(rename_all = "snake_case")]
152pub enum RunStatus {
153    Pending,
154    Running,
155    WaitingForTool,
156    Finished,
157    Failed,
158    Cancelled,
159}
160
161/// Provider- and runner-neutral retention semantics for one tool interaction.
162/// Concrete runners classify their own tools; Runtime memory policy consumes
163/// this typed event and never parses tool arguments.
164#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
165#[serde(rename_all = "snake_case")]
166pub enum ToolInteractionKind {
167    /// Planning work that changes or reports the agent's structured plan.
168    Plan,
169    Inspection,
170    Mutation,
171    /// A single ordered runner action that changes state and then validates
172    /// the resulting state before returning successfully.
173    MutationWithValidation,
174    Build,
175    Dependency,
176    Validation,
177    #[default]
178    Generic,
179}
180
181/// Whether a tool call was allowed to run.
182#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
183#[serde(rename_all = "snake_case")]
184pub enum ToolPermissionOutcome {
185    Allowed,
186    Denied,
187    /// The run was cancelled while the decision was pending.
188    Cancelled,
189}
190
191/// How long a permission decision applies.
192#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
193#[serde(rename_all = "snake_case")]
194pub enum ToolPermissionScope {
195    /// This call only.
196    Once,
197    /// Every later call to the same tool in this Session.
198    Session,
199}
200
201/// Who or what produced a permission decision.
202#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
203#[serde(rename_all = "snake_case")]
204pub enum ToolPermissionSource {
205    /// The host's configured policy, without asking anyone.
206    Policy,
207    /// A person, through the host's approver.
208    User,
209    /// An earlier `Session`-scoped decision for the same tool.
210    SessionRule,
211    /// No approver was configured or reachable, so the gate failed closed.
212    ApproverUnavailable,
213}
214
215#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
216#[serde(rename_all = "snake_case")]
217pub enum ModelResponseRejectionReason {
218    OutputLength,
219    ContentFilter,
220    ToolCallsWithoutItem,
221    StopWithToolCall,
222    EmptyOutput,
223    TerminalControllerViolation,
224}
225
226#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
227#[serde(rename_all = "snake_case")]
228pub enum AgentLoopTerminationReason {
229    NoStateProgress,
230    ModelStepLimit,
231}
232
233/// Runtime-owned terminal control policy, recorded in canonical Events so
234/// experiments can prove that memory arms used identical control.
235#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
236#[serde(rename_all = "snake_case")]
237pub enum TerminalControllerPolicy {
238    #[default]
239    AdvisoryV18,
240    TypedCompletionV1,
241    /// Strict typed completion for Providers that only guarantee
242    /// `tool_choice=auto`. Runtime exposes only `runtime_complete` and adds a
243    /// fixed control message, but never treats the call as Provider-forced.
244    TypedCompletionAutoV1,
245    /// Completion for Providers that only support `tool_choice=auto` and may
246    /// emit assistant text beside one valid function call. The tool call is
247    /// authoritative; co-emitted text is retained as evidence and ignored.
248    TypedCompletionAutoV2,
249}
250
251impl TerminalControllerPolicy {
252    pub const fn is_typed(self) -> bool {
253        matches!(
254            self,
255            Self::TypedCompletionV1 | Self::TypedCompletionAutoV1 | Self::TypedCompletionAutoV2
256        )
257    }
258}
259
260#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
261#[serde(rename_all = "snake_case")]
262pub enum TerminalControllerState {
263    Working,
264    CompletionRequired,
265    Completed,
266    Failed,
267}
268
269#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
270#[serde(rename_all = "snake_case")]
271pub enum TerminalControllerTransitionReason {
272    ValidationSucceeded,
273    StateProgress,
274    ToolError,
275    ProviderError,
276    DeterministicHardStop,
277    CompletionAccepted,
278    CompletionViolation,
279}
280
281#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
282#[serde(tag = "type", content = "payload")]
283pub enum Event {
284    #[serde(rename = "context.run.resolved")]
285    ContextRunResolved { snapshot: ContextRunSnapshot },
286    #[serde(rename = "context.request.exposed")]
287    ContextRequestExposed {
288        model_step: usize,
289        decision_id: String,
290        context_ids: Vec<String>,
291        #[serde(default)]
292        folded_ids: Vec<String>,
293    },
294    #[serde(rename = "context.item.unfolded")]
295    ContextItemUnfolded {
296        call_id: String,
297        decision_id: String,
298        context_id: String,
299    },
300    #[serde(rename = "context.call.started")]
301    ContextCallStarted {
302        call_id: String,
303        decision_id: String,
304        context_id: String,
305    },
306    #[serde(rename = "context.call.rejected")]
307    ContextCallRejected {
308        call_id: String,
309        decision_id: String,
310        context_id: Option<String>,
311    },
312    #[serde(rename = "session.created")]
313    SessionCreated { workspace_id: WorkspaceId },
314    #[serde(rename = "session.forked")]
315    SessionForked { source_session_id: SessionId },
316    #[serde(rename = "session.resumed")]
317    SessionResumed,
318    #[serde(rename = "session.suspended")]
319    SessionSuspended,
320    #[serde(rename = "session.closed")]
321    SessionClosed,
322    #[serde(rename = "run.scheduled")]
323    RunScheduled,
324    #[serde(rename = "run.started")]
325    RunStarted,
326    #[serde(rename = "message.accepted")]
327    MessageAccepted {
328        content: String,
329        #[serde(default, skip_serializing_if = "Vec::is_empty")]
330        images: Vec<arabica_model::ImageInput>,
331    },
332    /// Model selected for one call, recorded before provider invocation.
333    /// Contains only a public model identifier and bounded routing metadata.
334    #[serde(rename = "model.route.selected")]
335    ModelRouteSelected {
336        model_step: usize,
337        decision_id: String,
338        policy_id: String,
339        policy_version: u64,
340        /// Content hash of the effective policy pinned for this run.
341        #[serde(default)]
342        policy_fingerprint: String,
343        /// Stable aliases and model IDs; excludes credentials and endpoints.
344        #[serde(default)]
345        model_registry_snapshot: String,
346        model_alias: Option<String>,
347        reason: String,
348    },
349    #[serde(rename = "model.route.explained")]
350    ModelRouteExplained {
351        model_step: usize,
352        desired_model_alias: String,
353        selected_model_alias: String,
354        rule_id: Option<String>,
355        reason: String,
356        fallback_reason: Option<String>,
357    },
358    /// Immediate call-level measurement. Run quality is evaluated separately
359    /// after downstream tool outcomes or terminal task evidence are available.
360    #[serde(rename = "model.call.observed")]
361    ModelCallObserved {
362        model_step: usize,
363        decision_id: String,
364        elapsed_ms: u64,
365        provider_succeeded: bool,
366        #[serde(default)]
367        outcome: ModelCallOutcome,
368        usage: Option<RuntimeUsage>,
369    },
370    /// Exact provider-neutral request immediately before wire encoding.
371    #[serde(rename = "model.request.prepared")]
372    ModelRequestPrepared {
373        model_step: usize,
374        request: RuntimeRequest,
375    },
376    /// One exact ordered item from a provider-neutral model response.
377    #[serde(rename = "model.response.item")]
378    ModelResponseItem {
379        model_step: usize,
380        item_index: usize,
381        item: RuntimeItem,
382    },
383    /// Completion metadata for the preceding ordered response items.
384    #[serde(rename = "model.response.completed")]
385    ModelResponseCompleted {
386        model_step: usize,
387        finish_reason: Option<FinishReason>,
388        usage: RuntimeUsage,
389        /// Exact provider envelope. This remains private runtime evidence and
390        /// is not required to participate in short-memory projection.
391        #[serde(default, skip_serializing_if = "Option::is_none")]
392        provider_state: Option<ProviderResponseState>,
393    },
394    /// Typed audit evidence explaining why an otherwise losslessly recorded
395    /// provider response could not be executed or accepted as terminal.
396    #[serde(rename = "model.response.rejected")]
397    ModelResponseRejected {
398        model_step: usize,
399        reason: ModelResponseRejectionReason,
400        finish_reason: Option<FinishReason>,
401        tool_call_count: usize,
402        final_output_present: bool,
403    },
404    /// Additive audit evidence for the narrow normalization permitted by
405    /// `TypedCompletionAutoV2`. The structured completion call remains the
406    /// only source of terminal success.
407    #[serde(rename = "model.response.normalized")]
408    ModelResponseNormalized {
409        model_step: usize,
410        policy: TerminalControllerPolicy,
411        ignored_assistant_text: bool,
412    },
413    #[serde(rename = "tool.call.requested")]
414    ToolCallRequested {
415        call_id: String,
416        name: String,
417        arguments: serde_json::Value,
418        #[serde(default, skip_serializing_if = "Option::is_none")]
419        provider_state: Option<ProviderState>,
420    },
421    /// Monotonic duration of an actual runner invocation, excluding approval waits.
422    #[serde(rename = "tool.execution.observed")]
423    ToolExecutionObserved {
424        call_id: String,
425        elapsed_ms: u64,
426        outcome: ModelCallOutcome,
427    },
428    #[serde(rename = "tool.call.classified")]
429    ToolCallClassified {
430        call_id: String,
431        kind: ToolInteractionKind,
432    },
433    /// Current structured plan snapshot for replay and ACP plan updates.
434    #[serde(rename = "plan.updated")]
435    PlanUpdated {
436        plan_id: String,
437        entries: Vec<PlanEntry>,
438    },
439    #[serde(rename = "plan.delegation.observed")]
440    PlanDelegationObserved {
441        model_step: usize,
442        model_alias: String,
443        succeeded: bool,
444        elapsed_ms: u64,
445        usage: Option<RuntimeUsage>,
446    },
447    /// Runtime is asking the host's approver whether this call may run. The
448    /// tool name and arguments are in the matching `tool.call.requested`.
449    #[serde(rename = "tool.call.permission_requested")]
450    ToolCallPermissionRequested { call_id: String },
451    /// The decision for one call. It follows `tool.call.permission_requested`
452    /// when someone was asked, and stands alone when policy decided directly.
453    /// Policy is keyed by tool name, never by `tool.call.classified`.
454    #[serde(rename = "tool.call.permission_resolved")]
455    ToolCallPermissionResolved {
456        call_id: String,
457        outcome: ToolPermissionOutcome,
458        scope: ToolPermissionScope,
459        source: ToolPermissionSource,
460    },
461    #[serde(rename = "tool.call.reused")]
462    ToolCallReused {
463        call_id: String,
464        source_call_id: String,
465        fingerprint: String,
466        repeat_count: usize,
467    },
468    #[serde(rename = "tool.call.loop_blocked")]
469    ToolCallLoopBlocked {
470        call_id: String,
471        fingerprint: String,
472        repeat_count: usize,
473    },
474    #[serde(rename = "tool.call.completed")]
475    ToolCallCompleted {
476        call_id: String,
477        name: String,
478        result: String,
479        is_error: bool,
480    },
481    #[serde(rename = "agent.progress.advisory")]
482    AgentProgressAdvisory {
483        model_step: usize,
484        consecutive_no_progress_steps: usize,
485        message: String,
486    },
487    #[serde(rename = "agent.loop.terminated")]
488    AgentLoopTerminated {
489        model_step: usize,
490        reason: AgentLoopTerminationReason,
491        consecutive_no_progress_steps: usize,
492    },
493    /// Auditable Runtime terminal-controller state. This event is derived only
494    /// from typed Provider and Runner outcomes, never an external verifier.
495    #[serde(rename = "terminal.control.transition")]
496    TerminalControlTransition {
497        model_step: usize,
498        policy: TerminalControllerPolicy,
499        from: TerminalControllerState,
500        to: TerminalControllerState,
501        reason: TerminalControllerTransitionReason,
502    },
503    #[serde(rename = "command.output")]
504    CommandOutput { stream: OutputStream, chunk: String },
505    #[serde(rename = "run.completed")]
506    RunCompleted { output: Option<String> },
507    #[serde(rename = "run.failed")]
508    RunFailed { message: String },
509    #[serde(rename = "run.cancelled")]
510    RunCancelled,
511    #[serde(rename = "context.read")]
512    ContextRead { entry: ContextEntry },
513    #[serde(rename = "context.search.result")]
514    ContextSearchResult { entries: Vec<ContextEntry> },
515    #[serde(rename = "context.updated")]
516    ContextUpdated { entry: ContextEntry },
517    #[serde(rename = "context.deleted")]
518    ContextDeleted { path: String },
519    #[serde(rename = "context.disclosure.set")]
520    ContextDisclosureSet { level: DisclosureLevel },
521    #[serde(rename = "error")]
522    Error { code: ErrorCode, message: String },
523}
524
525/// One durable item in the agent's current plan.
526#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
527pub struct PlanEntry {
528    pub id: String,
529    pub content: String,
530    pub status: PlanEntryStatus,
531}
532
533#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
534#[serde(rename_all = "snake_case")]
535pub enum PlanEntryStatus {
536    #[default]
537    Pending,
538    InProgress,
539    Completed,
540}
541
542#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
543#[serde(rename_all = "snake_case")]
544pub enum ModelCallOutcome {
545    Succeeded,
546    Failed,
547    Cancelled,
548    #[default]
549    Unknown,
550}
551
552impl Event {
553    /// Model exchange events are canonical audit/runtime facts but can contain
554    /// system prompts, disclosed memory, and provider reasoning state. They
555    /// must not cross the ordinary client event transport boundary.
556    pub const fn is_client_visible(&self) -> bool {
557        !matches!(
558            self,
559            Self::ContextRunResolved { .. }
560                | Self::ContextRequestExposed { .. }
561                | Self::ContextItemUnfolded { .. }
562                | Self::ContextCallStarted { .. }
563                | Self::ContextCallRejected { .. }
564                | Self::ModelRequestPrepared { .. }
565                | Self::ModelRouteSelected { .. }
566                | Self::ModelCallObserved { .. }
567                | Self::ModelResponseItem { .. }
568                | Self::ModelResponseCompleted { .. }
569                | Self::ModelResponseRejected { .. }
570                | Self::ModelResponseNormalized { .. }
571        )
572    }
573}
574
575#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
576#[serde(rename_all = "snake_case")]
577pub enum ErrorCode {
578    InvalidCommand,
579    ProtocolVersionMismatch,
580    SessionNotFound,
581    InvalidSessionState,
582    RunNotFound,
583    RuntimeFailure,
584    RunnerFailure,
585    /// A restore snapshot's Events do not form a session that can be
586    /// reconstructed: a non-contiguous sequence, or a forked session (Phase
587    /// 2 restores only sessions with no parent).
588    InvalidSnapshot,
589}
590
591#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
592pub struct EventEnvelope {
593    pub protocol_version: String,
594    pub event_id: EventId,
595    pub command_id: CommandId,
596    pub workspace_id: WorkspaceId,
597    pub session_id: SessionId,
598    #[serde(skip_serializing_if = "Option::is_none")]
599    pub run_id: Option<RunId>,
600    pub sequence: u64,
601    pub occurred_at_ms: u64,
602    pub event: Event,
603}
604
605#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
606pub struct EventMetadata {
607    pub event_id: EventId,
608    pub command_id: CommandId,
609    pub workspace_id: WorkspaceId,
610    pub session_id: SessionId,
611    pub run_id: Option<RunId>,
612    pub sequence: u64,
613    pub occurred_at_ms: u64,
614}
615
616/// A command rejected before it can produce a session-scoped event.
617#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
618pub struct CommandFailure {
619    pub protocol_version: String,
620    pub command_id: CommandId,
621    pub code: ErrorCode,
622    pub message: String,
623}
624
625impl CommandFailure {
626    pub fn new(command_id: CommandId, code: ErrorCode, message: impl Into<String>) -> Self {
627        Self {
628            protocol_version: PROTOCOL_VERSION.to_owned(),
629            command_id,
630            code,
631            message: message.into(),
632        }
633    }
634}
635
636#[derive(JsonSchema)]
637pub struct ProtocolSchemaDocument {
638    pub command: CommandEnvelope,
639    pub event: EventEnvelope,
640    pub failure: CommandFailure,
641}
642
643/// Export the complete protocol schema used by code generators and hosts.
644pub fn protocol_schema() -> Schema {
645    schema_for!(ProtocolSchemaDocument)
646}
647
648impl EventEnvelope {
649    pub fn new(metadata: EventMetadata, event: Event) -> Self {
650        Self {
651            protocol_version: PROTOCOL_VERSION.to_owned(),
652            event_id: metadata.event_id,
653            command_id: metadata.command_id,
654            workspace_id: metadata.workspace_id,
655            session_id: metadata.session_id,
656            run_id: metadata.run_id,
657            sequence: metadata.sequence,
658            occurred_at_ms: metadata.occurred_at_ms,
659            event,
660        }
661    }
662}
663
664#[cfg(test)]
665mod tests {
666    use super::*;
667
668    #[test]
669    fn command_wire_shape_is_stable() {
670        let command = CommandEnvelope::new(
671            CommandId::new("command-1"),
672            Some(SessionId::new("session-1")),
673            Command::MessageSend {
674                images: Vec::new(),
675                content: "hello".to_owned(),
676            },
677        );
678
679        let value = serde_json::to_value(&command).expect("command serializes");
680        assert_eq!(value["protocol_version"], "1.0");
681        assert_eq!(value["command"]["type"], "message.send");
682        assert_eq!(value["command"]["payload"]["content"], "hello");
683        assert_eq!(
684            serde_json::from_value::<CommandEnvelope>(value).expect("command deserializes"),
685            command
686        );
687    }
688
689    #[test]
690    fn blend_events_deserialize_older_records_with_unknown_new_fields() {
691        let route: Event = serde_json::from_value(serde_json::json!({
692            "type": "model.route.selected",
693            "payload": {
694                "model_step": 1,
695                "decision_id": "run:1",
696                "policy_id": "legacy",
697                "policy_version": 1,
698                "model_alias": "fast",
699                "reason": "default"
700            }
701        }))
702        .expect("legacy route event deserializes");
703        assert!(
704            matches!(route, Event::ModelRouteSelected { policy_fingerprint, model_registry_snapshot, .. }
705            if policy_fingerprint.is_empty() && model_registry_snapshot.is_empty())
706        );
707
708        let observed: Event = serde_json::from_value(serde_json::json!({
709            "type": "model.call.observed",
710            "payload": {
711                "model_step": 1,
712                "decision_id": "run:1",
713                "elapsed_ms": 9,
714                "provider_succeeded": true,
715                "usage": null
716            }
717        }))
718        .expect("legacy observation event deserializes");
719        assert!(matches!(
720            observed,
721            Event::ModelCallObserved {
722                outcome: ModelCallOutcome::Unknown,
723                usage: None,
724                ..
725            }
726        ));
727    }
728
729    #[test]
730    fn event_carries_causation_and_ordering_metadata() {
731        let event = EventEnvelope::new(
732            EventMetadata {
733                event_id: EventId::new("event-1"),
734                command_id: CommandId::new("command-1"),
735                workspace_id: WorkspaceId::new("workspace-1"),
736                session_id: SessionId::new("session-1"),
737                run_id: Some(RunId::new("run-1")),
738                sequence: 3,
739                occurred_at_ms: 1_000,
740            },
741            Event::CommandOutput {
742                stream: OutputStream::Stdout,
743                chunk: "done".to_owned(),
744            },
745        );
746
747        let value = serde_json::to_value(event).expect("event serializes");
748        assert_eq!(value["sequence"], 3);
749        assert_eq!(value["event_id"], "event-1");
750        assert_eq!(value["occurred_at_ms"], 1_000);
751        assert_eq!(value["event"]["type"], "command.output");
752    }
753}