Skip to main content

mermaid_cli/domain/
cmd.rs

1//! Everything the reducer asks the outside world to do.
2//!
3//! `Cmd` values are inert data structures. The reducer returns them
4//! alongside each new `State`; `effect::EffectRunner::dispatch` then
5//! turns them into real work (spawning tokio tasks, writing files,
6//! hitting HTTP endpoints, killing processes). The reducer itself
7//! never performs any I/O.
8//!
9//! This is the "effects as data" pattern from Elm/Redux. Three
10//! payoffs this rewrite relies on:
11//!
12//!   1. **Testable reducer.** Assertions are `state, cmds = update(...)
13//!      ; assert_eq!(cmds[0], Cmd::CallModel { … })`. No tokio, no
14//!      mocks, no filesystem.
15//!   2. **Uniform middleware.** Retry, tracing, rate-limiting wrap the
16//!      dispatcher once instead of being re-implemented per adapter.
17//!   3. **Replayable sessions.** `--record` dumps every `Msg`; the
18//!      effects the reducer asked for are fully determined by the Msg
19//!      log + initial state, so `--replay` is a pure fold.
20
21use std::collections::HashMap;
22use std::path::PathBuf;
23
24use crate::app::McpServerConfig;
25use crate::models::ChatMessage;
26use crate::models::ReasoningLevel;
27use crate::models::tool_call::ToolCall as ModelToolCall;
28use crate::runtime::{SafetyMode, TaskStatus};
29use crate::session::ConversationHistory;
30
31use super::state::ApprovalChoice;
32
33use super::compaction::{CompactionArchive, CompactionRecord, CompactionRequest};
34use super::ids::{ToolCallId, TurnId};
35use super::runtime::ManagedProcess;
36
37/// A single side-effect request. Most variants are one-shot; `CallModel`
38/// and `ExecuteTool` spawn long-running tasks inside a per-turn
39/// `TurnScope`.
40// Several variants legitimately carry large payloads (a full
41// `ConversationHistory` / `ChatRequest`). Boxing them would churn ~20
42// construction + match sites for no real gain — `Cmd` values are short-lived
43// and moved, not stored in bulk.
44#[allow(clippy::large_enum_variant)]
45#[derive(Debug, Clone)]
46pub enum Cmd {
47    // ── Model + tool execution (the scope-spawning variants) ────────
48    /// Dispatch the next chat request. Effect runner maps this onto
49    /// `ModelProvider::chat` for the session's active provider.
50    CallModel { turn: TurnId, request: ChatRequest },
51    /// Generate a compact context checkpoint without continuing into
52    /// a normal assistant turn.
53    CompactConversation {
54        turn: TurnId,
55        request: CompactionRequest,
56    },
57    /// Run one tool in parallel with any other tools in the same turn.
58    /// The runner wires `ExecContext::token` to the turn's scope so
59    /// `Cmd::CancelScope` aborts them all at once.
60    ///
61    /// `model_id` is the active session's model id at the moment this
62    /// tool call was emitted. The runner passes it into `ExecContext`
63    /// so tools like `SubagentTool` can spawn children against the
64    /// same provider the parent is using.
65    ExecuteTool {
66        turn: TurnId,
67        call_id: ToolCallId,
68        source: ModelToolCall,
69        model_id: String,
70        /// Effective live safety mode (from `state.session.safety_mode`) at
71        /// the moment this call was emitted. The runner builds the policy
72        /// gate / Auto classifier from this rather than the static config.
73        safety_mode: SafetyMode,
74        /// The user's stated intent for the turn (latest user message),
75        /// passed to the Auto-mode classifier as alignment context.
76        intent: Option<String>,
77    },
78    /// Cancel every task in the given turn's `TurnScope`. After the
79    /// scope drains, the runner emits a `Msg::StreamDone` (with a
80    /// synthetic "cancelled" marker in usage, or a batch of
81    /// `ToolFinished { outcome: Cancelled }` for tools already running)
82    /// so the reducer can transition back to `Idle`.
83    CancelScope(TurnId),
84    /// Ctrl+B: signal the turn's scope to BACKGROUND (not cancel) its running
85    /// work. The scope's background token fires; detachable tools (execute_
86    /// command) move their child to a background process and return. The scope
87    /// is left intact (unlike `CancelScope`).
88    BackgroundScope(TurnId),
89
90    /// Resolve an inline approval prompt: deliver the user's decision to the
91    /// parked tool task via the `ApprovalBroker`. NOT turn-scoped — it's a
92    /// fire-and-forget to the broker (the tool task it unblocks is the
93    /// turn-scoped work).
94    ResolveApproval {
95        call_id: ToolCallId,
96        decision: ApprovalChoice,
97    },
98
99    // ── Persistence ─────────────────────────────────────────────────
100    /// Save the current conversation to disk. No-op if unchanged since
101    /// last save (effect-side idempotence).
102    SaveConversation(ConversationHistory),
103    /// Persist the raw messages removed by a compaction, then the compacted
104    /// (message-stripped) conversation. Both are written by ONE effect task,
105    /// archive first — only overwriting the conversation if the archive
106    /// persisted — so a failed/lagging archive can never lose messages while
107    /// the stripped conversation is saved over the old one.
108    SaveCompactionArchive {
109        archive: CompactionArchive,
110        record: CompactionRecord,
111        conversation: ConversationHistory,
112    },
113    /// Persist a daemon-visible background process record.
114    SaveProcess(ManagedProcess),
115    /// Persist the active model ID as `last_used_model`.
116    PersistLastModel(String),
117    /// Persist reasoning level tied to a specific model ID.
118    PersistReasoningFor {
119        model_id: String,
120        level: ReasoningLevel,
121    },
122    /// Persist (or clear, when `num_ctx` is `None`) a per-model Ollama `num_ctx`
123    /// override set via `/context <n>`/`max`/`auto`.
124    PersistOllamaNumCtxFor {
125        model_id: String,
126        num_ctx: Option<u32>,
127    },
128    /// Persist the Ollama RAM-offload toggle (`/context offload on|off`).
129    PersistOllamaOffload(bool),
130    /// Re-stat `MERMAID.md` (cheap); emits `Msg::InstructionsChanged`
131    /// only when the mtime moved or the file appeared/disappeared.
132    RefreshInstructions,
133    /// Re-scan the memory directories (cheap); emits `Msg::MemoryChanged`.
134    RefreshMemory,
135    /// List saved memories; emits `Msg::RuntimeText` with the rendered list.
136    ListMemory,
137    /// Save free-text to private memory; emits `Msg::MemoryChanged` + status.
138    RememberMemory { text: String },
139    /// Delete a memory by name/id; emits `Msg::MemoryChanged` + status.
140    ForgetMemory { id: String },
141    /// Model-assisted prune of duplicate/obsolete memories, reversible via a
142    /// checkpoint. Emits `Msg::RuntimeText` (the report) + `Msg::MemoryChanged`.
143    ConsolidateMemory { model_id: String },
144    /// Load a specific conversation by ID and emit
145    /// `Msg::ConversationLoaded`. Reducer consumes that event to
146    /// replace the current session.
147    LoadConversation(String),
148    /// Scan the conversations directory for the /load picker. Emits
149    /// `Msg::ConversationsListed` with one `ConversationSummary` per
150    /// saved session (newest first). The reducer transitions to
151    /// `UiMode::ConversationList` and the render shows the picker.
152    ListConversations,
153    /// List durable daemon/runtime tasks.
154    ListRuntimeTasks { limit: usize },
155    /// Load one durable daemon/runtime task and its timeline.
156    LoadRuntimeTask { id: String },
157    /// List durable daemon/runtime background processes.
158    ListRuntimeProcesses { limit: usize },
159    /// Print one durable process log into the conversation.
160    ShowRuntimeProcessLogs { id: String },
161    /// Stop a durable process by pid.
162    StopRuntimeProcess { id: String },
163    /// Restart a durable process using its recorded command/cwd.
164    RestartRuntimeProcess { id: String },
165    /// Open a URL, path, or process target.
166    OpenRuntimeTarget { target: String },
167    /// Show listening ports.
168    ShowRuntimePorts,
169    /// List pending approval records.
170    ListRuntimeApprovals,
171    /// Mark one approval as approved or denied.
172    DecideRuntimeApproval { id: String, decision: String },
173    /// List restore checkpoints.
174    ListRuntimeCheckpoints { limit: usize },
175    /// List installed plugins.
176    ListRuntimePlugins,
177    /// Update one durable task's status.
178    UpdateRuntimeTaskStatus {
179        id: String,
180        status: TaskStatus,
181        final_report: Option<String>,
182    },
183    /// Create a shadow checkpoint for explicit paths.
184    CreateRuntimeCheckpoint { paths: Vec<PathBuf> },
185    /// Restore files from a shadow checkpoint.
186    RestoreRuntimeCheckpoint { id: String },
187    /// Show provider/model capability information.
188    ShowRuntimeModelInfo { model: String },
189
190    // ── MCP lifecycle ───────────────────────────────────────────────
191    /// Start every configured MCP server; each one emits
192    /// `Msg::McpServerReady` or `Msg::McpServerErrored` as it comes up.
193    InitMcpServers(HashMap<String, McpServerConfig>),
194    /// Stop a running server (e.g. config was removed, or app quit).
195    StopMcpServer { name: String },
196
197    // ── Ollama helpers ──────────────────────────────────────────────
198    /// `ollama pull <model>` with progress → `Msg::ModelPullFinished`.
199    PullOllamaModel { model: String },
200
201    // ── UI side-effects (cross-process) ─────────────────────────────
202    /// `xdg-open` / `open` / `start` on a file path. Used by the
203    /// image-paste preview and the "open in editor" affordance.
204    OpenInSystem(PathBuf),
205
206    // ── Status line ─────────────────────────────────────────────────
207    /// Schedule `Msg::StatusDismiss` after `ms` milliseconds. Reducer
208    /// uses this to self-clear transient status lines.
209    DismissStatusAfter { ms: u64 },
210
211    // ── Attachments ─────────────────────────────────────────────────
212    /// Persist a pasted image to a temp file so the TUI can open it
213    /// via `OpenInSystem`. Emits no follow-up Msg on success; failure
214    /// is a log-and-drop.
215    WriteImageToTemp {
216        path: PathBuf,
217        bytes: Vec<u8>,
218        format: String,
219    },
220
221    /// Read the system clipboard on a blocking task. The per-platform
222    /// dispatch (xclip / wl-paste / pngpaste / PowerShell) can block
223    /// for hundreds of ms on macOS via osascript, so it never runs on
224    /// the reducer thread. Emits `Msg::Paste(Paste::Image|Text)` on
225    /// success; `Msg::TransientStatus` when the clipboard is empty or
226    /// the read fails.
227    ReadClipboard,
228
229    /// Write text to the system clipboard on a blocking task (mirrors
230    /// `ReadClipboard`'s per-platform dispatch). Used by in-app drag-select
231    /// copy. Emits a `Msg::TransientStatus` ("Copied N chars" / failure).
232    CopyToClipboard(String),
233
234    // ── Terminal lifecycle ──────────────────────────────────────────
235    /// Exit the main loop. No reply message — the loop observes
236    /// `state.should_exit` after the reducer returns and breaks out.
237    Exit,
238    /// Write the OSC 2 terminal-title sequence. Reducer diffs
239    /// against `ui.last_title_dispatched` so this only fires on
240    /// actual title changes, not every frame.
241    SetTerminalTitle(String),
242}
243
244/// Inputs a model needs to generate a turn. Built by the reducer from
245/// `Session` + `Settings` + current `MERMAID.md` context. Pure data —
246/// no provider-specific knowledge here (that's in
247/// `providers::model::*::chat`).
248#[derive(Debug, Clone)]
249pub struct ChatRequest {
250    pub model_id: String,
251    pub messages: Vec<ChatMessage>,
252    pub system_prompt: String,
253    /// `MERMAID.md` content to suffix onto the system prompt. `None` if
254    /// no file was loaded for this project.
255    pub instructions: Option<String>,
256    pub reasoning: ReasoningLevel,
257    pub temperature: f32,
258    pub max_tokens: usize,
259    /// Tool definitions advertised to the model. Combination of the
260    /// built-in tool set + any advertised MCP tools from `McpState`.
261    pub tools: Vec<ToolDefinition>,
262    /// Per-model Ollama `num_ctx` override (`/context <n>`/`max`), or `None` to
263    /// auto-fit. The one provider-specific knob that rides on the request, the
264    /// same way `reasoning` does — so a live `/context` change applies on the
265    /// next turn without rebuilding the cached provider. Ignored by non-Ollama
266    /// providers.
267    pub ollama_num_ctx: Option<u32>,
268    /// Live Ollama RAM-offload toggle (`/context offload on|off`). Rides on the
269    /// request like `ollama_num_ctx` so a toggle applies on the next turn without
270    /// rebuilding the cached provider (whose `config` is frozen at startup).
271    /// `None` falls back to the persisted `[ollama] allow_ram_offload`. Ignored
272    /// by non-Ollama providers.
273    pub ollama_allow_ram_offload: Option<bool>,
274}
275
276/// Provider-agnostic tool definition sent in the request. Concrete
277/// adapters (`providers::model::ollama`, etc.) translate this into
278/// whatever wire shape their API expects.
279#[derive(Debug, Clone)]
280pub struct ToolDefinition {
281    pub name: String,
282    pub description: String,
283    pub input_schema: serde_json::Value,
284}
285
286impl ToolDefinition {
287    /// Wire shape: `{type: "function", function: {name, description,
288    /// parameters}}`. This is the OpenAI / Ollama Chat Completions
289    /// format; Anthropic and Gemini adapters translate further from
290    /// here. Single-canonical-shape keeps adapters from drifting.
291    pub fn to_openai_json(&self) -> serde_json::Value {
292        serde_json::json!({
293            "type": "function",
294            "function": {
295                "name": self.name,
296                "description": self.description,
297                "parameters": self.input_schema,
298            }
299        })
300    }
301}
302
303impl Cmd {
304    /// Human-readable tag, for tracing + replay logs. Stable across
305    /// refactors (tests assert against it).
306    pub fn tag(&self) -> &'static str {
307        match self {
308            Cmd::CallModel { .. } => "call_model",
309            Cmd::CompactConversation { .. } => "compact_conversation",
310            Cmd::ExecuteTool { .. } => "execute_tool",
311            Cmd::CancelScope(_) => "cancel_scope",
312            Cmd::BackgroundScope(_) => "background_scope",
313            Cmd::ResolveApproval { .. } => "resolve_approval",
314            Cmd::SaveConversation(_) => "save_conversation",
315            Cmd::SaveCompactionArchive { .. } => "save_compaction_archive",
316            Cmd::SaveProcess(_) => "save_process",
317            Cmd::PersistLastModel(_) => "persist_last_model",
318            Cmd::PersistReasoningFor { .. } => "persist_reasoning_for",
319            Cmd::PersistOllamaNumCtxFor { .. } => "persist_ollama_num_ctx_for",
320            Cmd::PersistOllamaOffload(_) => "persist_ollama_offload",
321            Cmd::RefreshInstructions => "refresh_instructions",
322            Cmd::RefreshMemory => "refresh_memory",
323            Cmd::ListMemory => "list_memory",
324            Cmd::RememberMemory { .. } => "remember_memory",
325            Cmd::ForgetMemory { .. } => "forget_memory",
326            Cmd::ConsolidateMemory { .. } => "consolidate_memory",
327            Cmd::LoadConversation(_) => "load_conversation",
328            Cmd::ListConversations => "list_conversations",
329            Cmd::ListRuntimeTasks { .. } => "list_runtime_tasks",
330            Cmd::LoadRuntimeTask { .. } => "load_runtime_task",
331            Cmd::ListRuntimeProcesses { .. } => "list_runtime_processes",
332            Cmd::ShowRuntimeProcessLogs { .. } => "show_runtime_process_logs",
333            Cmd::StopRuntimeProcess { .. } => "stop_runtime_process",
334            Cmd::RestartRuntimeProcess { .. } => "restart_runtime_process",
335            Cmd::OpenRuntimeTarget { .. } => "open_runtime_target",
336            Cmd::ShowRuntimePorts => "show_runtime_ports",
337            Cmd::ListRuntimeApprovals => "list_runtime_approvals",
338            Cmd::DecideRuntimeApproval { .. } => "decide_runtime_approval",
339            Cmd::ListRuntimeCheckpoints { .. } => "list_runtime_checkpoints",
340            Cmd::ListRuntimePlugins => "list_runtime_plugins",
341            Cmd::UpdateRuntimeTaskStatus { .. } => "update_runtime_task_status",
342            Cmd::CreateRuntimeCheckpoint { .. } => "create_runtime_checkpoint",
343            Cmd::RestoreRuntimeCheckpoint { .. } => "restore_runtime_checkpoint",
344            Cmd::ShowRuntimeModelInfo { .. } => "show_runtime_model_info",
345            Cmd::InitMcpServers(_) => "init_mcp_servers",
346            Cmd::StopMcpServer { .. } => "stop_mcp_server",
347            Cmd::PullOllamaModel { .. } => "pull_ollama_model",
348            Cmd::OpenInSystem(_) => "open_in_system",
349            Cmd::DismissStatusAfter { .. } => "dismiss_status_after",
350            Cmd::WriteImageToTemp { .. } => "write_image_to_temp",
351            Cmd::ReadClipboard => "read_clipboard",
352            Cmd::CopyToClipboard(_) => "copy_to_clipboard",
353            Cmd::Exit => "exit",
354            Cmd::SetTerminalTitle(_) => "set_terminal_title",
355        }
356    }
357
358    /// True iff this command needs to run inside a `TurnScope` so it
359    /// can be cancelled by `Cmd::CancelScope`. The effect runner uses
360    /// this to decide between "spawn into `JoinSet`" and "spawn detached".
361    pub fn is_turn_scoped(&self) -> bool {
362        matches!(
363            self,
364            Cmd::CallModel { .. } | Cmd::CompactConversation { .. } | Cmd::ExecuteTool { .. }
365        )
366    }
367
368    /// For traces + the `--record` file — some `Cmd` payloads are huge
369    /// (think `ChatRequest::messages`). This returns a compact
370    /// identifier that doesn't dump the full payload.
371    pub fn summary(&self) -> String {
372        match self {
373            Cmd::CallModel { turn, request } => format!(
374                "call_model(turn={}, model={}, msgs={})",
375                turn,
376                request.model_id,
377                request.messages.len()
378            ),
379            Cmd::CompactConversation { turn, request } => format!(
380                "compact_conversation(turn={}, model={}, trigger={}, msgs={})",
381                turn,
382                request.chat.model_id,
383                request.trigger.as_str(),
384                request.chat.messages.len()
385            ),
386            Cmd::ExecuteTool {
387                turn,
388                call_id,
389                source,
390                ..
391            } => format!(
392                "execute_tool(turn={}, call={}, fn={})",
393                turn, call_id, source.function.name
394            ),
395            Cmd::CancelScope(turn) => format!("cancel_scope(turn={})", turn),
396            Cmd::BackgroundScope(turn) => format!("background_scope(turn={})", turn),
397            Cmd::ResolveApproval { call_id, decision } => {
398                format!("resolve_approval(call={}, {:?})", call_id, decision)
399            },
400            Cmd::SaveConversation(c) => format!("save_conversation(id={})", c.id),
401            Cmd::SaveCompactionArchive {
402                archive, record, ..
403            } => format!(
404                "save_compaction_archive(conversation={}, id={})",
405                archive.conversation_id, record.id
406            ),
407            Cmd::SaveProcess(p) => format!("save_process(id={}, pid={})", p.id, p.pid),
408            Cmd::PersistLastModel(m) => format!("persist_last_model({})", m),
409            Cmd::PersistReasoningFor { model_id, level } => {
410                format!("persist_reasoning_for({}, {:?})", model_id, level)
411            },
412            Cmd::PersistOllamaNumCtxFor { model_id, num_ctx } => {
413                format!("persist_ollama_num_ctx_for({}, {:?})", model_id, num_ctx)
414            },
415            Cmd::PersistOllamaOffload(enabled) => {
416                format!("persist_ollama_offload({})", enabled)
417            },
418            Cmd::RefreshInstructions => "refresh_instructions".to_string(),
419            Cmd::RefreshMemory => "refresh_memory".to_string(),
420            Cmd::ListMemory => "list_memory".to_string(),
421            Cmd::RememberMemory { .. } => "remember_memory".to_string(),
422            Cmd::ForgetMemory { .. } => "forget_memory".to_string(),
423            Cmd::ConsolidateMemory { .. } => "consolidate_memory".to_string(),
424            Cmd::LoadConversation(id) => format!("load_conversation({})", id),
425            Cmd::ListConversations => "list_conversations".to_string(),
426            Cmd::ListRuntimeTasks { limit } => format!("list_runtime_tasks(limit={})", limit),
427            Cmd::LoadRuntimeTask { id } => format!("load_runtime_task({})", id),
428            Cmd::ListRuntimeProcesses { limit } => {
429                format!("list_runtime_processes(limit={})", limit)
430            },
431            Cmd::ShowRuntimeProcessLogs { id } => format!("show_runtime_process_logs({})", id),
432            Cmd::StopRuntimeProcess { id } => format!("stop_runtime_process({})", id),
433            Cmd::RestartRuntimeProcess { id } => format!("restart_runtime_process({})", id),
434            Cmd::OpenRuntimeTarget { target } => format!("open_runtime_target({})", target),
435            Cmd::ShowRuntimePorts => "show_runtime_ports".to_string(),
436            Cmd::ListRuntimeApprovals => "list_runtime_approvals".to_string(),
437            Cmd::DecideRuntimeApproval { id, decision } => {
438                format!("decide_runtime_approval({}, {})", id, decision)
439            },
440            Cmd::ListRuntimeCheckpoints { limit } => {
441                format!("list_runtime_checkpoints(limit={})", limit)
442            },
443            Cmd::ListRuntimePlugins => "list_runtime_plugins".to_string(),
444            Cmd::UpdateRuntimeTaskStatus { id, status, .. } => {
445                format!("update_runtime_task_status({}, {})", id, status)
446            },
447            Cmd::CreateRuntimeCheckpoint { paths } => {
448                format!("create_runtime_checkpoint(n={})", paths.len())
449            },
450            Cmd::RestoreRuntimeCheckpoint { id } => format!("restore_runtime_checkpoint({})", id),
451            Cmd::ShowRuntimeModelInfo { model } => format!("show_runtime_model_info({})", model),
452            Cmd::InitMcpServers(m) => format!("init_mcp_servers(n={})", m.len()),
453            Cmd::StopMcpServer { name } => format!("stop_mcp_server({})", name),
454            Cmd::PullOllamaModel { model } => format!("pull_ollama_model({})", model),
455            Cmd::OpenInSystem(p) => format!("open_in_system({})", p.display()),
456            Cmd::DismissStatusAfter { ms } => format!("dismiss_status_after({}ms)", ms),
457            Cmd::WriteImageToTemp {
458                path,
459                format,
460                bytes,
461            } => format!(
462                "write_image_to_temp(path={}, fmt={}, n={})",
463                path.display(),
464                format,
465                bytes.len()
466            ),
467            Cmd::ReadClipboard => "read_clipboard".to_string(),
468            Cmd::CopyToClipboard(t) => format!("copy_to_clipboard(n={})", t.chars().count()),
469            Cmd::Exit => "exit".to_string(),
470            Cmd::SetTerminalTitle(t) => format!("set_terminal_title({})", t),
471        }
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478
479    #[test]
480    fn turn_scoped_variants_marked_correctly() {
481        let request = ChatRequest {
482            model_id: "m".to_string(),
483            messages: vec![],
484            system_prompt: String::new(),
485            instructions: None,
486            reasoning: ReasoningLevel::Medium,
487            temperature: 0.7,
488            max_tokens: 4096,
489            tools: vec![],
490
491            ollama_num_ctx: None,
492            ollama_allow_ram_offload: None,
493        };
494        assert!(
495            Cmd::CallModel {
496                turn: TurnId(1),
497                request,
498            }
499            .is_turn_scoped()
500        );
501        assert!(
502            !Cmd::SaveConversation(ConversationHistory::new("/p".to_string(), "m".to_string()))
503                .is_turn_scoped()
504        );
505        assert!(!Cmd::RefreshInstructions.is_turn_scoped());
506        assert!(!Cmd::Exit.is_turn_scoped());
507    }
508
509    #[test]
510    fn cmd_tags_are_stable() {
511        assert_eq!(Cmd::Exit.tag(), "exit");
512        assert_eq!(Cmd::RefreshInstructions.tag(), "refresh_instructions");
513        assert_eq!(Cmd::CancelScope(TurnId(1)).tag(), "cancel_scope");
514    }
515
516    #[test]
517    fn cmd_summary_includes_identifying_fields() {
518        let c = Cmd::CancelScope(TurnId(42));
519        let s = c.summary();
520        assert!(s.contains("turn#42"));
521    }
522}