Skip to main content

codewhale_protocol/
op.rs

1//! `Op`-in API in `crates/protocol` (issue #5261, Phase A1 of the
2//! core/protocol extraction spec).
3//!
4//! The TUI engine already had an internal channel (`Op` in
5//! `crates/tui/src/core/ops.rs` with `tx_op` / `rx_op` and `tx_steer`).
6//! This protocol file formalizes that channel so TUI, CLI, app-server, and
7//! tests share one serializable API. The wire is `OpEnvelope` + `Op`;
8//! transports that already speak JSON (app-server, tests) can send the
9//! envelope directly, while in-process callers continue to use the typed
10//! enum.
11//!
12//! Parity is compile-enforced from the engine side:
13//! `crates/tui/src/core/protocol_parity.rs` matches every engine `Op`
14//! variant exhaustively into a protocol `Op` (`protocol_covers_engine_ops`).
15//!
16//! What is deliberately stripped at this boundary:
17//!
18//! - `mpsc` / `oneshot` reply channels (`GetSessionSnapshot`,
19//!   `GetProviderRuntimeStatus`, `BootstrapMcp`, `RetryMcpServer`,
20//!   `ReloadMcp`). Over the wire the reply is an `EventMsg` or a response
21//!   frame, not a channel.
22//! - `Arc<HookExecutor>` on `SendMessage`: hooks are host configuration, not
23//!   turn input.
24//! - Resolved provider routes and clients. Only the non-secret receipt
25//!   (`model`, `model_provider`) crosses; the engine re-resolves.
26//! - `Ruleset`, transcript `Message`s, and `SystemPrompt` cross as
27//!   `serde_json::Value` from their own `Serialize` until typed in a later
28//!   phase.
29//!
30//! `Steer` and `Cancel` have no engine `Op` twin on purpose: the engine
31//! carries them on `tx_steer` and the cancellation token. They are protocol
32//! operations regardless, because every out-of-process client needs them.
33
34use std::path::PathBuf;
35
36use serde::{Deserialize, Serialize};
37use serde_json::Value;
38
39/// Accept `engine_schedule_id` on the wire for compatibility, then discard it.
40///
41/// Deserialization is the out-of-process boundary: the engine's own
42/// `Op::ContinueGoal` travels an in-process channel and never reaches here, so
43/// anything this sees was supplied by a caller who must not be able to set it.
44/// Returning `None` sends such a request down the ordinary host-injected path
45/// instead of letting it consume a pending engine schedule.
46fn drop_engine_owned_schedule_id<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
47where
48    D: serde::Deserializer<'de>,
49{
50    Option::<u64>::deserialize(deserializer)?;
51    Ok(None)
52}
53
54use crate::ids::{SessionId, ThreadId};
55use crate::runtime::DynamicToolSpec;
56
57/// Every `Op` is paired with the ids that route it. This is the
58/// `Op`-in half of the `Op`-in / `EventMsg`-out contract.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct OpEnvelope {
61    /// Monotonic `op:<n>` for dedup / tracing within a session.
62    pub op_id: String,
63    pub thread_id: ThreadId,
64    pub session_id: SessionId,
65    pub op: Op,
66}
67
68/// Token-limit facts for a route. `None` is unknown, never zero.
69#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
70pub struct RouteLimits {
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub context_tokens: Option<u64>,
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub input_tokens: Option<u64>,
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub output_tokens: Option<u64>,
77}
78
79/// Compaction policy derived from a provider route. Twin of the engine's
80/// `CompactionConfig`.
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct CompactionPolicy {
83    pub enabled: bool,
84    pub token_threshold: u64,
85    pub model: String,
86    /// `supported | unsupported | unknown`.
87    #[serde(default = "default_capability_state")]
88    pub image_input: String,
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub effective_context_window: Option<u32>,
91    #[serde(default)]
92    pub cache_summary: bool,
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    pub focus: Option<String>,
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub runtime_cost_owner: Option<String>,
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub workspace: Option<PathBuf>,
99}
100
101fn default_capability_state() -> String {
102    "unknown".to_string()
103}
104
105/// Operations that can be submitted to the core engine. This is the
106/// protocol view of `crates/tui/src/core/ops::Op` — same lifecycle,
107/// same provenance gate — but serializable and free of `mpsc` / `oneshot`
108/// fields. In-process callers convert at the boundary; out-of-process
109/// callers send the JSON directly.
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111#[serde(tag = "kind", rename_all = "snake_case")]
112pub enum Op {
113    /// Drive one model turn: `role=user` content plus the resolved route
114    /// receipt the engine will freeze at the client-freeze boundary. Headless
115    /// and TUI must produce byte-identical `MessageRequest`s for identical
116    /// `Op::SendMessage` payloads.
117    SendMessage {
118        content: String,
119        /// Effective mode for this turn (`"plan" | "agent" | "operate"` etc).
120        #[serde(default = "default_mode")]
121        mode: String,
122        /// Optional explicit route/model the caller resolved already (mirrors
123        /// `ResolvedRuntimeRoute` in `crates_tui::route_runtime`). `None` means
124        /// "use the thread's current route".
125        #[serde(default, skip_serializing_if = "Option::is_none")]
126        model: Option<String>,
127        #[serde(default, skip_serializing_if = "Option::is_none")]
128        model_provider: Option<String>,
129        /// Tool restriction from slash-command frontmatter.
130        #[serde(default)]
131        allowed_tools: Option<Vec<String>>,
132        /// Runtime-supplied dynamic tools for this turn only.
133        #[serde(default)]
134        dynamic_tools: Vec<DynamicToolSpec>,
135        /// Structural input provenance — only `external_user` may inherit
136        /// YOLO/auto-approval authority (mirrors `UserInputProvenance`).
137        #[serde(default = "default_provenance")]
138        provenance: String,
139        /// Compaction policy carried atomically with the route receipt.
140        /// Boxed only to keep the enum small; the wire shape is unchanged.
141        #[serde(default, skip_serializing_if = "Option::is_none")]
142        compaction: Option<Box<CompactionPolicy>>,
143        #[serde(default, skip_serializing_if = "Option::is_none")]
144        goal_objective: Option<String>,
145        #[serde(default, skip_serializing_if = "Option::is_none")]
146        goal_token_budget: Option<u32>,
147        /// `active | paused | complete | blocked`.
148        #[serde(default = "default_goal_status")]
149        goal_status: String,
150        /// `"off" | "low" | "medium" | "high" | "max"`; `None` = provider default.
151        #[serde(default, skip_serializing_if = "Option::is_none")]
152        reasoning_effort: Option<String>,
153        #[serde(default)]
154        reasoning_effort_auto: bool,
155        #[serde(default)]
156        auto_model: bool,
157        #[serde(default)]
158        allow_shell: bool,
159        #[serde(default)]
160        trust_mode: bool,
161        #[serde(default)]
162        auto_approve: bool,
163        /// `auto | bypass | suggest | never`.
164        #[serde(default = "default_approval_mode")]
165        approval_mode: String,
166        #[serde(default)]
167        translation_enabled: bool,
168        #[serde(default, skip_serializing_if = "Option::is_none")]
169        verbosity: Option<String>,
170    },
171
172    /// Steer an in-flight turn with additional user content (drains into
173    /// the turn loop's `rx_steer` channel).
174    Steer {
175        content: String,
176    },
177
178    /// Re-check and dispatch a goal continuation (synthetic turn that
179    /// continues the same logical goal run).
180    ContinueGoal {
181        #[serde(default)]
182        dynamic_tools: Vec<DynamicToolSpec>,
183        /// Engine-owned coalescing token; direct callers send `None`.
184        ///
185        /// Enforced, not merely documented: the engine mints these on an
186        /// in-process channel (`tx_op.try_send`) and they never cross serde,
187        /// so any value arriving through deserialization came from outside.
188        /// The IDs are predictable per-session counters, and a matching guess
189        /// is treated as an already-delayed internal token -- it would consume
190        /// the pending schedule and skip the host-injected quiet period. Wire
191        /// input is therefore always dropped to `None`.
192        #[serde(
193            default,
194            skip_serializing_if = "Option::is_none",
195            deserialize_with = "drop_engine_owned_schedule_id"
196        )]
197        engine_schedule_id: Option<u64>,
198    },
199
200    /// Execute a local composer shell command without a model turn.
201    RunShellCommand {
202        command: String,
203        #[serde(default = "default_mode")]
204        mode: String,
205        #[serde(default)]
206        allow_shell: bool,
207        #[serde(default)]
208        trust_mode: bool,
209        #[serde(default)]
210        auto_approve: bool,
211        #[serde(default = "default_approval_mode")]
212        approval_mode: String,
213    },
214
215    /// Set goal status without dispatching a model turn.
216    SetGoalStatus {
217        status: String,
218        #[serde(default)]
219        clear: bool,
220    },
221
222    /// Set (or replace) the active goal objective and start goal work.
223    SetGoalObjective {
224        objective: String,
225        #[serde(default, skip_serializing_if = "Option::is_none")]
226        token_budget: Option<u32>,
227    },
228
229    Cancel,
230    Shutdown,
231
232    /// Describe the exact request the next turn would send without sending it
233    /// (`/dryrun` / `/preview-request`, #1004). Headless and TUI must render
234    /// identical manifests for identical inputs.
235    PreviewOutboundRequest {
236        #[serde(default)]
237        json: bool,
238        #[serde(default)]
239        base_prompt_only: bool,
240        #[serde(default = "default_mode")]
241        mode: String,
242        #[serde(default)]
243        allow_shell: bool,
244        #[serde(default)]
245        trust_mode: bool,
246        #[serde(default)]
247        auto_approve: bool,
248        #[serde(default = "default_approval_mode")]
249        approval_mode: String,
250        #[serde(default)]
251        allowed_tools: Option<Vec<String>>,
252        #[serde(default)]
253        dynamic_tools: Vec<DynamicToolSpec>,
254        #[serde(default = "default_provenance")]
255        provenance: String,
256        /// The model selector the user chose (`auto` when auto routing).
257        #[serde(default)]
258        requested_model: String,
259        #[serde(default)]
260        requested_reasoning: String,
261        #[serde(default)]
262        auto_model: bool,
263        #[serde(default)]
264        hypothetical_prompt_supplied: bool,
265        /// Model-facing text of the hypothetical next message, when the host
266        /// planner resolved one.
267        #[serde(default, skip_serializing_if = "Option::is_none")]
268        hypothetical_prompt: Option<String>,
269        /// Why no exact next turn exists, when it does not.
270        #[serde(default, skip_serializing_if = "Option::is_none")]
271        unresolved: Option<String>,
272    },
273
274    ListSubAgents,
275    CancelSubAgent {
276        agent_id: String,
277    },
278    FollowUpSubAgent {
279        agent_id: String,
280        text: String,
281    },
282
283    ChangeMode {
284        #[serde(default = "default_mode")]
285        mode: String,
286        #[serde(default)]
287        allow_shell: bool,
288        #[serde(default)]
289        trust_mode: bool,
290        #[serde(default)]
291        auto_approve: bool,
292        #[serde(default = "default_approval_mode")]
293        approval_mode: String,
294        #[serde(default, skip_serializing_if = "Option::is_none")]
295        configured_sandbox_mode: Option<String>,
296    },
297
298    SetModel {
299        model: String,
300        #[serde(default = "default_mode")]
301        mode: String,
302        #[serde(default, skip_serializing_if = "Option::is_none")]
303        route_limits: Option<RouteLimits>,
304    },
305
306    SetCompaction {
307        config: CompactionPolicy,
308    },
309
310    /// Replace the live user permission rules (`Ruleset` serialized).
311    SetPermissionRuleset {
312        ruleset: Value,
313    },
314
315    SetStreamChunkTimeout {
316        timeout_secs: u64,
317    },
318
319    SetSubagentRuntimeConfig {
320        enabled: bool,
321        max_subagents: u64,
322        launch_concurrency: u64,
323        max_spawn_depth: u32,
324        api_timeout_secs: u64,
325        heartbeat_timeout_secs: u64,
326    },
327
328    /// `SearchProvider` in snake_case.
329    SetSearchProvider {
330        provider: String,
331    },
332
333    /// Replace the engine's merged Fleet roster. Only the roster's identity
334    /// crosses: member ids in precedence order plus the load state.
335    SetFleetRoster {
336        member_ids: Vec<String>,
337        #[serde(default)]
338        exact_selection: bool,
339        #[serde(default, skip_serializing_if = "Option::is_none")]
340        load_error: Option<String>,
341    },
342
343    /// Sync engine session state (resume/load). `messages` are transcript
344    /// `Message`s and `system_prompt` a `SystemPrompt`, both serialized.
345    SyncSession {
346        #[serde(default, skip_serializing_if = "Option::is_none")]
347        engine_session_id: Option<String>,
348        messages: Vec<Value>,
349        #[serde(default, skip_serializing_if = "Option::is_none")]
350        system_prompt: Option<Value>,
351        #[serde(default)]
352        system_prompt_override: bool,
353        model: String,
354        workspace: PathBuf,
355        #[serde(default = "default_mode")]
356        mode: String,
357    },
358
359    /// Run context compaction on one exact provider route.
360    CompactContext {
361        id: String,
362        model: String,
363        model_provider: String,
364        compaction: CompactionPolicy,
365    },
366
367    CancelCompaction {
368        id: String,
369    },
370
371    /// Request a session snapshot; the reply travels out-of-band.
372    GetSessionSnapshot,
373    /// Request provider concurrency state; the reply travels out-of-band.
374    GetProviderRuntimeStatus,
375    /// Populate the engine-owned MCP pool once at boot; reply out-of-band.
376    BootstrapMcp,
377    RetryMcpServer {
378        name: String,
379    },
380    ReloadMcp {
381        config_path: PathBuf,
382    },
383
384    PurgeContext,
385    EditLastTurn {
386        new_message: String,
387    },
388    SetAdvisorEnabled {
389        enabled: bool,
390    },
391}
392
393fn default_mode() -> String {
394    "agent".to_string()
395}
396
397fn default_provenance() -> String {
398    "external_user".to_string()
399}
400
401fn default_goal_status() -> String {
402    "active".to_string()
403}
404
405fn default_approval_mode() -> String {
406    "suggest".to_string()
407}
408
409/// Every wire tag `Op` can carry, in declaration order.
410pub const OP_KINDS: &[&str] = &[
411    "send_message",
412    "steer",
413    "continue_goal",
414    "run_shell_command",
415    "set_goal_status",
416    "set_goal_objective",
417    "cancel",
418    "shutdown",
419    "preview_outbound_request",
420    "list_sub_agents",
421    "cancel_sub_agent",
422    "follow_up_sub_agent",
423    "change_mode",
424    "set_model",
425    "set_compaction",
426    "set_permission_ruleset",
427    "set_stream_chunk_timeout",
428    "set_subagent_runtime_config",
429    "set_search_provider",
430    "set_fleet_roster",
431    "sync_session",
432    "compact_context",
433    "cancel_compaction",
434    "get_session_snapshot",
435    "get_provider_runtime_status",
436    "bootstrap_mcp",
437    "retry_mcp_server",
438    "reload_mcp",
439    "purge_context",
440    "edit_last_turn",
441    "set_advisor_enabled",
442];
443
444impl Op {
445    #[must_use]
446    pub fn is_send_message(&self) -> bool {
447        matches!(self, Self::SendMessage { .. })
448    }
449
450    #[must_use]
451    pub fn kind_str(&self) -> &'static str {
452        match self {
453            Self::SendMessage { .. } => "send_message",
454            Self::Steer { .. } => "steer",
455            Self::ContinueGoal { .. } => "continue_goal",
456            Self::RunShellCommand { .. } => "run_shell_command",
457            Self::SetGoalStatus { .. } => "set_goal_status",
458            Self::SetGoalObjective { .. } => "set_goal_objective",
459            Self::Cancel => "cancel",
460            Self::Shutdown => "shutdown",
461            Self::PreviewOutboundRequest { .. } => "preview_outbound_request",
462            Self::ListSubAgents => "list_sub_agents",
463            Self::CancelSubAgent { .. } => "cancel_sub_agent",
464            Self::FollowUpSubAgent { .. } => "follow_up_sub_agent",
465            Self::ChangeMode { .. } => "change_mode",
466            Self::SetModel { .. } => "set_model",
467            Self::SetCompaction { .. } => "set_compaction",
468            Self::SetPermissionRuleset { .. } => "set_permission_ruleset",
469            Self::SetStreamChunkTimeout { .. } => "set_stream_chunk_timeout",
470            Self::SetSubagentRuntimeConfig { .. } => "set_subagent_runtime_config",
471            Self::SetSearchProvider { .. } => "set_search_provider",
472            Self::SetFleetRoster { .. } => "set_fleet_roster",
473            Self::SyncSession { .. } => "sync_session",
474            Self::CompactContext { .. } => "compact_context",
475            Self::CancelCompaction { .. } => "cancel_compaction",
476            Self::GetSessionSnapshot => "get_session_snapshot",
477            Self::GetProviderRuntimeStatus => "get_provider_runtime_status",
478            Self::BootstrapMcp => "bootstrap_mcp",
479            Self::RetryMcpServer { .. } => "retry_mcp_server",
480            Self::ReloadMcp { .. } => "reload_mcp",
481            Self::PurgeContext => "purge_context",
482            Self::EditLastTurn { .. } => "edit_last_turn",
483            Self::SetAdvisorEnabled { .. } => "set_advisor_enabled",
484        }
485    }
486}
487
488/// Build a headless `SendMessage` envelope with fresh ids. This is the
489/// one-line helper every headless caller (CLI `exec`, app-server, tests)
490/// uses so TUI and headless start a session identically.
491#[must_use]
492pub fn headless_send_message_op(thread_id: ThreadId, content: impl Into<String>) -> OpEnvelope {
493    OpEnvelope {
494        op_id: format!("op-{}", uuid::Uuid::new_v4()),
495        thread_id: thread_id.clone(),
496        session_id: SessionId::new(),
497        op: Op::SendMessage {
498            content: content.into(),
499            mode: default_mode(),
500            model: None,
501            model_provider: None,
502            allowed_tools: None,
503            dynamic_tools: Vec::new(),
504            provenance: default_provenance(),
505            compaction: None,
506            goal_objective: None,
507            goal_token_budget: None,
508            goal_status: default_goal_status(),
509            reasoning_effort: None,
510            reasoning_effort_auto: false,
511            auto_model: false,
512            allow_shell: false,
513            trust_mode: false,
514            auto_approve: false,
515            approval_mode: default_approval_mode(),
516            translation_enabled: false,
517            verbosity: None,
518        },
519    }
520}
521
522#[cfg(test)]
523mod tests {
524    use super::*;
525    use serde_json::json;
526
527    fn policy() -> CompactionPolicy {
528        CompactionPolicy {
529            enabled: true,
530            token_threshold: 100_000,
531            model: "deepseek-chat".into(),
532            image_input: "unknown".into(),
533            effective_context_window: Some(128_000),
534            cache_summary: true,
535            focus: None,
536            runtime_cost_owner: None,
537            workspace: None,
538        }
539    }
540
541    /// One instance of every variant, in declaration order.
542    fn every_variant() -> Vec<Op> {
543        vec![
544            headless_send_message_op(ThreadId::new(), "hello").op,
545            Op::Steer {
546                content: "more".into(),
547            },
548            Op::ContinueGoal {
549                dynamic_tools: vec![],
550                // Engine-owned: deliberately not round-trippable. See
551                // `wire_supplied_engine_schedule_id_is_dropped`.
552                engine_schedule_id: None,
553            },
554            Op::RunShellCommand {
555                command: "ls".into(),
556                mode: "agent".into(),
557                allow_shell: true,
558                trust_mode: false,
559                auto_approve: false,
560                approval_mode: "suggest".into(),
561            },
562            Op::SetGoalStatus {
563                status: "paused".into(),
564                clear: false,
565            },
566            Op::SetGoalObjective {
567                objective: "ship".into(),
568                token_budget: Some(10),
569            },
570            Op::Cancel,
571            Op::Shutdown,
572            Op::PreviewOutboundRequest {
573                json: true,
574                base_prompt_only: false,
575                mode: "plan".into(),
576                allow_shell: false,
577                trust_mode: false,
578                auto_approve: false,
579                approval_mode: "auto".into(),
580                allowed_tools: Some(vec!["read_file".into()]),
581                dynamic_tools: vec![],
582                provenance: "external_user".into(),
583                requested_model: "auto".into(),
584                requested_reasoning: "high".into(),
585                auto_model: true,
586                hypothetical_prompt_supplied: true,
587                hypothetical_prompt: Some("hi".into()),
588                unresolved: None,
589            },
590            Op::ListSubAgents,
591            Op::CancelSubAgent {
592                agent_id: "a1".into(),
593            },
594            Op::FollowUpSubAgent {
595                agent_id: "a1".into(),
596                text: "go".into(),
597            },
598            Op::ChangeMode {
599                mode: "operate".into(),
600                allow_shell: true,
601                trust_mode: true,
602                auto_approve: false,
603                approval_mode: "bypass".into(),
604                configured_sandbox_mode: Some("workspace-write".into()),
605            },
606            Op::SetModel {
607                model: "m".into(),
608                mode: "agent".into(),
609                route_limits: Some(RouteLimits {
610                    context_tokens: Some(1),
611                    input_tokens: None,
612                    output_tokens: None,
613                }),
614            },
615            Op::SetCompaction { config: policy() },
616            Op::SetPermissionRuleset {
617                ruleset: json!({"rules": []}),
618            },
619            Op::SetStreamChunkTimeout { timeout_secs: 30 },
620            Op::SetSubagentRuntimeConfig {
621                enabled: true,
622                max_subagents: 4,
623                launch_concurrency: 2,
624                max_spawn_depth: 1,
625                api_timeout_secs: 60,
626                heartbeat_timeout_secs: 10,
627            },
628            Op::SetSearchProvider {
629                provider: "brave".into(),
630            },
631            Op::SetFleetRoster {
632                member_ids: vec!["scout".into()],
633                exact_selection: false,
634                load_error: None,
635            },
636            Op::SyncSession {
637                engine_session_id: Some("s".into()),
638                messages: vec![json!({"role": "user", "content": []})],
639                system_prompt: None,
640                system_prompt_override: false,
641                model: "m".into(),
642                workspace: PathBuf::from("/ws"),
643                mode: "agent".into(),
644            },
645            Op::CompactContext {
646                id: "cmp-1".into(),
647                model: "m".into(),
648                model_provider: "deepseek".into(),
649                compaction: policy(),
650            },
651            Op::CancelCompaction { id: "cmp-1".into() },
652            Op::GetSessionSnapshot,
653            Op::GetProviderRuntimeStatus,
654            Op::BootstrapMcp,
655            Op::RetryMcpServer { name: "fs".into() },
656            Op::ReloadMcp {
657                config_path: PathBuf::from("/tmp/mcp.json"),
658            },
659            Op::PurgeContext,
660            Op::EditLastTurn {
661                new_message: "again".into(),
662            },
663            Op::SetAdvisorEnabled { enabled: true },
664        ]
665    }
666
667    #[test]
668    fn every_variant_is_listed_once() {
669        let kinds: Vec<&str> = every_variant().iter().map(Op::kind_str).collect();
670        assert_eq!(kinds, OP_KINDS, "OP_KINDS must list every variant in order");
671    }
672
673    #[test]
674    fn wire_supplied_engine_schedule_id_is_dropped() {
675        // The engine mints these on an in-process channel, so a value arriving
676        // through serde came from an out-of-process caller. Honouring it would
677        // let a guessed counter consume the pending schedule and skip the
678        // host-injected quiet period.
679        let op: Op = serde_json::from_value(json!({
680            "kind": "continue_goal",
681            "dynamic_tools": [],
682            "engine_schedule_id": 3,
683        }))
684        .expect("continue_goal with a wire-supplied schedule id still parses");
685        match op {
686            Op::ContinueGoal {
687                engine_schedule_id, ..
688            } => assert_eq!(
689                engine_schedule_id, None,
690                "engine_schedule_id must never be settable from the wire"
691            ),
692            other => panic!("expected ContinueGoal, got {other:?}"),
693        }
694    }
695
696    #[test]
697    fn every_variant_round_trips_and_tags_by_kind() {
698        for op in every_variant() {
699            let value = serde_json::to_value(&op).unwrap();
700            assert_eq!(value["kind"], op.kind_str(), "{op:?}");
701            let back: Op = serde_json::from_value(value).unwrap();
702            assert_eq!(back, op);
703        }
704    }
705
706    #[test]
707    fn op_envelope_roundtrip() {
708        let env = headless_send_message_op(ThreadId::new(), "hello");
709        let json = serde_json::to_string(&env).unwrap();
710        let back: OpEnvelope = serde_json::from_str(&json).unwrap();
711        assert_eq!(back.thread_id, env.thread_id);
712        assert!(back.op.is_send_message());
713    }
714
715    #[test]
716    fn minimal_send_message_json_still_parses_with_defaults() {
717        // The pre-A1 wire shape: only `content` plus the tag.
718        let op: Op = serde_json::from_value(json!({
719            "kind": "send_message",
720            "content": "hello"
721        }))
722        .unwrap();
723        let Op::SendMessage {
724            mode,
725            provenance,
726            goal_status,
727            approval_mode,
728            ..
729        } = op
730        else {
731            panic!("expected send_message");
732        };
733        assert_eq!(mode, "agent");
734        assert_eq!(provenance, "external_user");
735        assert_eq!(goal_status, "active");
736        assert_eq!(approval_mode, "suggest");
737    }
738
739    #[test]
740    fn steer_roundtrip() {
741        let op = Op::Steer {
742            content: "more".into(),
743        };
744        let json = serde_json::to_string(&op).unwrap();
745        let back: Op = serde_json::from_str(&json).unwrap();
746        assert_eq!(back.kind_str(), "steer");
747    }
748}