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