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