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 (`GetSubAgentSettlement`, `GetSessionSnapshot`,
19//!   `GetContextBudget`, `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/// Per-turn authority payload carried by [`Op::SendMessage`]. Serializable
106/// twin of `crates/tui/src/core/ops::TurnSpec`; extracted from the enum arm so
107/// new per-turn fields accrete here instead of widening the variant. The
108/// `SendMessage(TurnSpec)` newtype keeps the internally-tagged wire shape
109/// byte-identical: `{"kind":"send_message", ...fields}`.
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111pub struct TurnSpec {
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub profile_constitution: Option<serde_json::Value>,
114    #[serde(
115        default,
116        rename = "maxOutputTokens",
117        alias = "max_output_tokens",
118        skip_serializing_if = "Option::is_none"
119    )]
120    pub max_output_tokens: Option<std::num::NonZeroU32>,
121    pub content: String,
122    #[serde(default, skip_serializing_if = "Vec::is_empty")]
123    pub images: Vec<crate::runtime::RuntimeImageInput>,
124    /// Effective mode for this turn (`"plan" | "agent" | "operate"` etc).
125    #[serde(default = "default_mode")]
126    pub mode: String,
127    /// Optional explicit route/model the caller resolved already (mirrors
128    /// `ResolvedRuntimeRoute` in `crates_tui::route_runtime`). `None` means
129    /// "use the thread's current route".
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub model: Option<String>,
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub model_provider: Option<String>,
134    /// Tool restriction from slash-command frontmatter.
135    #[serde(default)]
136    pub allowed_tools: Option<Vec<String>>,
137    /// Runtime-supplied dynamic tools for this turn only.
138    #[serde(default)]
139    pub dynamic_tools: Vec<DynamicToolSpec>,
140    /// Structural input provenance — only `external_user` may inherit
141    /// YOLO/auto-approval authority (mirrors `UserInputProvenance`).
142    #[serde(default = "default_provenance")]
143    pub provenance: String,
144    /// Compaction policy carried atomically with the route receipt.
145    /// Boxed only to keep the enum small; the wire shape is unchanged.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub compaction: Option<Box<CompactionPolicy>>,
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub goal_objective: Option<String>,
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub goal_token_budget: Option<u32>,
152    /// `active | paused | complete | blocked`.
153    #[serde(default = "default_goal_status")]
154    pub goal_status: String,
155    /// `"off" | "low" | "medium" | "high" | "max"`; `None` = provider default.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub reasoning_effort: Option<String>,
158    #[serde(default)]
159    pub reasoning_effort_auto: bool,
160    #[serde(default)]
161    pub auto_model: bool,
162    #[serde(default)]
163    pub allow_shell: bool,
164    #[serde(default)]
165    pub trust_mode: bool,
166    #[serde(default)]
167    pub auto_approve: bool,
168    /// `auto | bypass | suggest | never`.
169    #[serde(default = "default_approval_mode")]
170    pub approval_mode: String,
171    #[serde(default)]
172    pub translation_enabled: bool,
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub verbosity: Option<String>,
175}
176
177/// Operations that can be submitted to the core engine. This is the
178/// protocol view of `crates/tui/src/core/ops::Op` — same lifecycle,
179/// same provenance gate — but serializable and free of `mpsc` / `oneshot`
180/// fields. In-process callers convert at the boundary; out-of-process
181/// callers send the JSON directly.
182#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
183#[serde(tag = "kind", rename_all = "snake_case")]
184pub enum Op {
185    /// Drive one model turn: `role=user` content plus the resolved route
186    /// receipt the engine will freeze at the client-freeze boundary. Headless
187    /// and TUI must produce byte-identical `MessageRequest`s for identical
188    /// `Op::SendMessage` payloads.
189    SendMessage(TurnSpec),
190
191    /// Steer an in-flight turn with additional user content (drains into
192    /// the turn loop's `rx_steer` channel).
193    Steer {
194        content: String,
195    },
196
197    /// Re-check and dispatch a goal continuation (synthetic turn that
198    /// continues the same logical goal run).
199    ContinueGoal {
200        #[serde(default)]
201        dynamic_tools: Vec<DynamicToolSpec>,
202        /// Engine-owned coalescing token; direct callers send `None`.
203        ///
204        /// Enforced, not merely documented: the engine mints these on an
205        /// in-process channel (`tx_op.try_send`) and they never cross serde,
206        /// so any value arriving through deserialization came from outside.
207        /// The IDs are predictable per-session counters, and a matching guess
208        /// is treated as an already-delayed internal token -- it would consume
209        /// the pending schedule and skip the host-injected quiet period. Wire
210        /// input is therefore always dropped to `None`.
211        #[serde(
212            default,
213            skip_serializing_if = "Option::is_none",
214            deserialize_with = "drop_engine_owned_schedule_id"
215        )]
216        engine_schedule_id: Option<u64>,
217    },
218
219    /// Execute a local composer shell command without a model turn.
220    RunShellCommand {
221        command: String,
222        #[serde(default = "default_mode")]
223        mode: String,
224        #[serde(default)]
225        allow_shell: bool,
226        #[serde(default)]
227        trust_mode: bool,
228        #[serde(default)]
229        auto_approve: bool,
230        #[serde(default = "default_approval_mode")]
231        approval_mode: String,
232    },
233
234    /// Set goal status without dispatching a model turn.
235    SetGoalStatus {
236        status: String,
237        #[serde(default)]
238        clear: bool,
239        #[serde(default, skip_serializing_if = "Option::is_none")]
240        goal_id: Option<String>,
241    },
242
243    /// Set (or replace) the active goal objective and start goal work.
244    SetGoalObjective {
245        objective: String,
246        #[serde(default, skip_serializing_if = "Option::is_none")]
247        token_budget: Option<u32>,
248        #[serde(default, skip_serializing_if = "Option::is_none")]
249        goal_id: Option<String>,
250    },
251
252    Cancel,
253    Shutdown,
254
255    /// Describe the exact request the next turn would send without sending it
256    /// (`/dryrun` / `/preview-request`, #1004). Headless and TUI must render
257    /// identical manifests for identical inputs.
258    PreviewOutboundRequest {
259        #[serde(default)]
260        json: bool,
261        #[serde(default)]
262        base_prompt_only: bool,
263        #[serde(default = "default_mode")]
264        mode: String,
265        #[serde(default)]
266        allow_shell: bool,
267        #[serde(default)]
268        trust_mode: bool,
269        #[serde(default)]
270        auto_approve: bool,
271        #[serde(default = "default_approval_mode")]
272        approval_mode: String,
273        #[serde(default)]
274        allowed_tools: Option<Vec<String>>,
275        #[serde(default)]
276        dynamic_tools: Vec<DynamicToolSpec>,
277        #[serde(default = "default_provenance")]
278        provenance: String,
279        /// The model selector the user chose (`auto` when auto routing).
280        #[serde(default)]
281        requested_model: String,
282        #[serde(default)]
283        requested_reasoning: String,
284        #[serde(default)]
285        auto_model: bool,
286        #[serde(default)]
287        hypothetical_prompt_supplied: bool,
288        /// Model-facing text of the hypothetical next message, when the host
289        /// planner resolved one.
290        #[serde(default, skip_serializing_if = "Option::is_none")]
291        hypothetical_prompt: Option<String>,
292        /// Why no exact next turn exists, when it does not.
293        #[serde(default, skip_serializing_if = "Option::is_none")]
294        unresolved: Option<String>,
295    },
296
297    ListSubAgents,
298    /// Inspect live children and pending handbacks at the Engine's idle
299    /// boundary. The host owns the response channel; it is not wire input.
300    GetSubAgentSettlement,
301    CancelSubAgent {
302        agent_id: String,
303    },
304    FollowUpSubAgent {
305        agent_id: String,
306        text: String,
307    },
308
309    ChangeMode {
310        #[serde(default = "default_mode")]
311        mode: String,
312        #[serde(default)]
313        allow_shell: bool,
314        #[serde(default)]
315        trust_mode: bool,
316        #[serde(default)]
317        auto_approve: bool,
318        #[serde(default = "default_approval_mode")]
319        approval_mode: String,
320        #[serde(default, skip_serializing_if = "Option::is_none")]
321        configured_sandbox_mode: Option<String>,
322    },
323
324    SetModel {
325        model: String,
326        #[serde(default = "default_mode")]
327        mode: String,
328        #[serde(default, skip_serializing_if = "Option::is_none")]
329        route_limits: Option<RouteLimits>,
330    },
331
332    SetCompaction {
333        config: CompactionPolicy,
334    },
335
336    /// Legacy serialized permission-update operation, retained for wire
337    /// compatibility. The in-process runtime now publishes directly through
338    /// its shared policy store instead of queuing a second replacement.
339    SetPermissionRuleset {
340        ruleset: Value,
341    },
342
343    SetStreamChunkTimeout {
344        timeout_secs: u64,
345    },
346
347    SetSubagentRuntimeConfig {
348        enabled: bool,
349        max_subagents: u64,
350        launch_concurrency: u64,
351        max_spawn_depth: u32,
352        api_timeout_secs: u64,
353        heartbeat_timeout_secs: u64,
354    },
355
356    /// `SearchProvider` in snake_case.
357    SetSearchProvider {
358        provider: String,
359    },
360
361    /// Replace the engine's merged Fleet roster. Only the roster's identity
362    /// crosses: member ids in precedence order plus the load state.
363    SetFleetRoster {
364        member_ids: Vec<String>,
365        #[serde(default)]
366        exact_selection: bool,
367        #[serde(default, skip_serializing_if = "Option::is_none")]
368        load_error: Option<String>,
369    },
370
371    /// Sync engine session state (resume/load). `messages` are transcript
372    /// `Message`s and `system_prompt` a `SystemPrompt`, both serialized.
373    SyncSession {
374        #[serde(default, skip_serializing_if = "Option::is_none")]
375        engine_session_id: Option<String>,
376        messages: Vec<Value>,
377        #[serde(default, skip_serializing_if = "Option::is_none")]
378        system_prompt: Option<Value>,
379        #[serde(default)]
380        system_prompt_override: bool,
381        model: String,
382        workspace: PathBuf,
383        #[serde(default = "default_mode")]
384        mode: String,
385    },
386
387    /// Rewind an unchanged conversation. `expected` is the complete observed
388    /// session snapshot; a receiver must compare it before changing history.
389    /// The success/refusal receipt travels out-of-band.
390    RewindConversation {
391        expected: Value,
392        messages: Vec<Value>,
393    },
394
395    /// Run context compaction on one exact provider route.
396    CompactContext {
397        id: String,
398        model: String,
399        model_provider: String,
400        compaction: CompactionPolicy,
401    },
402
403    CancelCompaction {
404        id: String,
405    },
406
407    /// Request a session snapshot; the reply travels out-of-band.
408    GetSessionSnapshot,
409    /// Request the live context-window budget for the session's route; the
410    /// reply travels out-of-band.
411    GetContextBudget,
412    /// Request provider concurrency state; the reply travels out-of-band.
413    GetProviderRuntimeStatus,
414    /// Populate the engine-owned MCP pool once at boot; reply out-of-band.
415    BootstrapMcp,
416    RetryMcpServer {
417        name: String,
418    },
419    ReloadMcp {
420        config_path: PathBuf,
421    },
422
423    PurgeContext,
424    EditLastTurn {
425        new_message: String,
426    },
427    SetAdvisorEnabled {
428        enabled: bool,
429    },
430}
431
432fn default_mode() -> String {
433    "agent".to_string()
434}
435
436fn default_provenance() -> String {
437    "external_user".to_string()
438}
439
440fn default_goal_status() -> String {
441    "active".to_string()
442}
443
444fn default_approval_mode() -> String {
445    "suggest".to_string()
446}
447
448/// Every wire tag `Op` can carry, in declaration order.
449pub const OP_KINDS: &[&str] = &[
450    "send_message",
451    "steer",
452    "continue_goal",
453    "run_shell_command",
454    "set_goal_status",
455    "set_goal_objective",
456    "cancel",
457    "shutdown",
458    "preview_outbound_request",
459    "list_sub_agents",
460    "get_sub_agent_settlement",
461    "cancel_sub_agent",
462    "follow_up_sub_agent",
463    "change_mode",
464    "set_model",
465    "set_compaction",
466    "set_permission_ruleset",
467    "set_stream_chunk_timeout",
468    "set_subagent_runtime_config",
469    "set_search_provider",
470    "set_fleet_roster",
471    "sync_session",
472    "rewind_conversation",
473    "compact_context",
474    "cancel_compaction",
475    "get_session_snapshot",
476    "get_context_budget",
477    "get_provider_runtime_status",
478    "bootstrap_mcp",
479    "retry_mcp_server",
480    "reload_mcp",
481    "purge_context",
482    "edit_last_turn",
483    "set_advisor_enabled",
484];
485
486impl Op {
487    #[must_use]
488    pub fn is_send_message(&self) -> bool {
489        matches!(self, Self::SendMessage(_))
490    }
491
492    #[must_use]
493    pub fn kind_str(&self) -> &'static str {
494        match self {
495            Self::SendMessage(_) => "send_message",
496            Self::Steer { .. } => "steer",
497            Self::ContinueGoal { .. } => "continue_goal",
498            Self::RunShellCommand { .. } => "run_shell_command",
499            Self::SetGoalStatus { .. } => "set_goal_status",
500            Self::SetGoalObjective { .. } => "set_goal_objective",
501            Self::Cancel => "cancel",
502            Self::Shutdown => "shutdown",
503            Self::PreviewOutboundRequest { .. } => "preview_outbound_request",
504            Self::ListSubAgents => "list_sub_agents",
505            Self::GetSubAgentSettlement => "get_sub_agent_settlement",
506            Self::CancelSubAgent { .. } => "cancel_sub_agent",
507            Self::FollowUpSubAgent { .. } => "follow_up_sub_agent",
508            Self::ChangeMode { .. } => "change_mode",
509            Self::SetModel { .. } => "set_model",
510            Self::SetCompaction { .. } => "set_compaction",
511            Self::SetPermissionRuleset { .. } => "set_permission_ruleset",
512            Self::SetStreamChunkTimeout { .. } => "set_stream_chunk_timeout",
513            Self::SetSubagentRuntimeConfig { .. } => "set_subagent_runtime_config",
514            Self::SetSearchProvider { .. } => "set_search_provider",
515            Self::SetFleetRoster { .. } => "set_fleet_roster",
516            Self::SyncSession { .. } => "sync_session",
517            Self::RewindConversation { .. } => "rewind_conversation",
518            Self::CompactContext { .. } => "compact_context",
519            Self::CancelCompaction { .. } => "cancel_compaction",
520            Self::GetSessionSnapshot => "get_session_snapshot",
521            Self::GetContextBudget => "get_context_budget",
522            Self::GetProviderRuntimeStatus => "get_provider_runtime_status",
523            Self::BootstrapMcp => "bootstrap_mcp",
524            Self::RetryMcpServer { .. } => "retry_mcp_server",
525            Self::ReloadMcp { .. } => "reload_mcp",
526            Self::PurgeContext => "purge_context",
527            Self::EditLastTurn { .. } => "edit_last_turn",
528            Self::SetAdvisorEnabled { .. } => "set_advisor_enabled",
529        }
530    }
531}
532
533/// Build a headless `SendMessage` envelope with fresh ids. This is the
534/// one-line helper every headless caller (CLI `exec`, app-server, tests)
535/// uses so TUI and headless start a session identically.
536#[must_use]
537pub fn headless_send_message_op(thread_id: ThreadId, content: impl Into<String>) -> OpEnvelope {
538    OpEnvelope {
539        op_id: format!("op-{}", uuid::Uuid::new_v4()),
540        thread_id: thread_id.clone(),
541        session_id: SessionId::new(),
542        op: Op::SendMessage(TurnSpec {
543            profile_constitution: None,
544            max_output_tokens: None,
545            content: content.into(),
546            images: Vec::new(),
547            mode: default_mode(),
548            model: None,
549            model_provider: None,
550            allowed_tools: None,
551            dynamic_tools: Vec::new(),
552            provenance: default_provenance(),
553            compaction: None,
554            goal_objective: None,
555            goal_token_budget: None,
556            goal_status: default_goal_status(),
557            reasoning_effort: None,
558            reasoning_effort_auto: false,
559            auto_model: false,
560            allow_shell: false,
561            trust_mode: false,
562            auto_approve: false,
563            approval_mode: default_approval_mode(),
564            translation_enabled: false,
565            verbosity: None,
566        }),
567    }
568}
569
570#[cfg(test)]
571mod tests {
572    use super::*;
573    use serde_json::json;
574
575    fn policy() -> CompactionPolicy {
576        CompactionPolicy {
577            enabled: true,
578            token_threshold: 100_000,
579            model: "deepseek-chat".into(),
580            image_input: "unknown".into(),
581            effective_context_window: Some(128_000),
582            cache_summary: true,
583            focus: None,
584            runtime_cost_owner: None,
585            workspace: None,
586        }
587    }
588
589    /// One instance of every variant, in declaration order.
590    fn every_variant() -> Vec<Op> {
591        vec![
592            headless_send_message_op(ThreadId::new(), "hello").op,
593            Op::Steer {
594                content: "more".into(),
595            },
596            Op::ContinueGoal {
597                dynamic_tools: vec![],
598                // Engine-owned: deliberately not round-trippable. See
599                // `wire_supplied_engine_schedule_id_is_dropped`.
600                engine_schedule_id: None,
601            },
602            Op::RunShellCommand {
603                command: "ls".into(),
604                mode: "agent".into(),
605                allow_shell: true,
606                trust_mode: false,
607                auto_approve: false,
608                approval_mode: "suggest".into(),
609            },
610            Op::SetGoalStatus {
611                goal_id: None,
612                status: "paused".into(),
613                clear: false,
614            },
615            Op::SetGoalObjective {
616                goal_id: None,
617                objective: "ship".into(),
618                token_budget: Some(10),
619            },
620            Op::Cancel,
621            Op::Shutdown,
622            Op::PreviewOutboundRequest {
623                json: true,
624                base_prompt_only: false,
625                mode: "plan".into(),
626                allow_shell: false,
627                trust_mode: false,
628                auto_approve: false,
629                approval_mode: "auto".into(),
630                allowed_tools: Some(vec!["read_file".into()]),
631                dynamic_tools: vec![],
632                provenance: "external_user".into(),
633                requested_model: "auto".into(),
634                requested_reasoning: "high".into(),
635                auto_model: true,
636                hypothetical_prompt_supplied: true,
637                hypothetical_prompt: Some("hi".into()),
638                unresolved: None,
639            },
640            Op::ListSubAgents,
641            Op::GetSubAgentSettlement,
642            Op::CancelSubAgent {
643                agent_id: "a1".into(),
644            },
645            Op::FollowUpSubAgent {
646                agent_id: "a1".into(),
647                text: "go".into(),
648            },
649            Op::ChangeMode {
650                mode: "operate".into(),
651                allow_shell: true,
652                trust_mode: true,
653                auto_approve: false,
654                approval_mode: "bypass".into(),
655                configured_sandbox_mode: Some("workspace-write".into()),
656            },
657            Op::SetModel {
658                model: "m".into(),
659                mode: "agent".into(),
660                route_limits: Some(RouteLimits {
661                    context_tokens: Some(1),
662                    input_tokens: None,
663                    output_tokens: None,
664                }),
665            },
666            Op::SetCompaction { config: policy() },
667            Op::SetPermissionRuleset {
668                ruleset: json!({"rules": []}),
669            },
670            Op::SetStreamChunkTimeout { timeout_secs: 30 },
671            Op::SetSubagentRuntimeConfig {
672                enabled: true,
673                max_subagents: 4,
674                launch_concurrency: 2,
675                max_spawn_depth: 1,
676                api_timeout_secs: 60,
677                heartbeat_timeout_secs: 10,
678            },
679            Op::SetSearchProvider {
680                provider: "brave".into(),
681            },
682            Op::SetFleetRoster {
683                member_ids: vec!["scout".into()],
684                exact_selection: false,
685                load_error: None,
686            },
687            Op::SyncSession {
688                engine_session_id: Some("s".into()),
689                messages: vec![json!({"role": "user", "content": []})],
690                system_prompt: None,
691                system_prompt_override: false,
692                model: "m".into(),
693                workspace: PathBuf::from("/ws"),
694                mode: "agent".into(),
695            },
696            Op::RewindConversation {
697                expected: json!({"session_id": "s", "messages": []}),
698                messages: vec![],
699            },
700            Op::CompactContext {
701                id: "cmp-1".into(),
702                model: "m".into(),
703                model_provider: "deepseek".into(),
704                compaction: policy(),
705            },
706            Op::CancelCompaction { id: "cmp-1".into() },
707            Op::GetSessionSnapshot,
708            Op::GetContextBudget,
709            Op::GetProviderRuntimeStatus,
710            Op::BootstrapMcp,
711            Op::RetryMcpServer { name: "fs".into() },
712            Op::ReloadMcp {
713                config_path: PathBuf::from("/tmp/mcp.json"),
714            },
715            Op::PurgeContext,
716            Op::EditLastTurn {
717                new_message: "again".into(),
718            },
719            Op::SetAdvisorEnabled { enabled: true },
720        ]
721    }
722
723    #[test]
724    fn every_variant_is_listed_once() {
725        let kinds: Vec<&str> = every_variant().iter().map(Op::kind_str).collect();
726        assert_eq!(kinds, OP_KINDS, "OP_KINDS must list every variant in order");
727    }
728
729    #[test]
730    fn wire_supplied_engine_schedule_id_is_dropped() {
731        // The engine mints these on an in-process channel, so a value arriving
732        // through serde came from an out-of-process caller. Honouring it would
733        // let a guessed counter consume the pending schedule and skip the
734        // host-injected quiet period.
735        let op: Op = serde_json::from_value(json!({
736            "kind": "continue_goal",
737            "dynamic_tools": [],
738            "engine_schedule_id": 3,
739        }))
740        .expect("continue_goal with a wire-supplied schedule id still parses");
741        match op {
742            Op::ContinueGoal {
743                engine_schedule_id, ..
744            } => assert_eq!(
745                engine_schedule_id, None,
746                "engine_schedule_id must never be settable from the wire"
747            ),
748            other => panic!("expected ContinueGoal, got {other:?}"),
749        }
750    }
751
752    #[test]
753    fn every_variant_round_trips_and_tags_by_kind() {
754        for op in every_variant() {
755            let value = serde_json::to_value(&op).unwrap();
756            assert_eq!(value["kind"], op.kind_str(), "{op:?}");
757            let back: Op = serde_json::from_value(value).unwrap();
758            assert_eq!(back, op);
759        }
760    }
761
762    #[test]
763    fn op_envelope_roundtrip() {
764        let env = headless_send_message_op(ThreadId::new(), "hello");
765        let json = serde_json::to_string(&env).unwrap();
766        let back: OpEnvelope = serde_json::from_str(&json).unwrap();
767        assert_eq!(back.thread_id, env.thread_id);
768        assert!(back.op.is_send_message());
769    }
770
771    #[test]
772    fn minimal_send_message_json_still_parses_with_defaults() {
773        // The pre-A1 wire shape: only `content` plus the tag.
774        let op: Op = serde_json::from_value(json!({
775            "kind": "send_message",
776            "content": "hello"
777        }))
778        .unwrap();
779        let Op::SendMessage(TurnSpec {
780            mode,
781            provenance,
782            goal_status,
783            approval_mode,
784            ..
785        }) = op
786        else {
787            panic!("expected send_message");
788        };
789        assert_eq!(mode, "agent");
790        assert_eq!(provenance, "external_user");
791        assert_eq!(goal_status, "active");
792        assert_eq!(approval_mode, "suggest");
793    }
794
795    #[test]
796    fn steer_roundtrip() {
797        let op = Op::Steer {
798            content: "more".into(),
799        };
800        let json = serde_json::to_string(&op).unwrap();
801        let back: Op = serde_json::from_str(&json).unwrap();
802        assert_eq!(back.kind_str(), "steer");
803    }
804}