Skip to main content

multicast_workflows/
lib.rs

1//! Durable Code Mode workflows attached to a multicast CLI as first-party commands.
2//!
3//! A workflow is a Code Mode program with a name, a description, and an input
4//! schema. Workflows come from two sources and share one shape:
5//!
6//! - **Shipped** workflows are compiled into the binary by the CLI author with
7//!   [`Workflows::shipped`]. Each becomes an ordinary top-level command, so it
8//!   appears in help, `--llms`, skills, MCP tools, and the tool catalog.
9//! - **Saved** workflows are promoted at runtime from a completed execution
10//!   with `workflows save NAME --from EXECUTION_ID`, and run with
11//!   `workflows run NAME`.
12//!
13//! [`Workflows::attach`] adds the shipped commands and a `workflows` group to
14//! a [`Cli`]. [`Workflows::attach_hosted`] uses a platform adapter instead of
15//! the default native SQLite store. Every run is a durable execution: a run that
16//! reaches an action needing approval stops with [`PAUSED_EXIT_CODE`] and its
17//! execution identifier, and `workflows approve`, `workflows reject`, and
18//! `workflows resume` continue it later, including from a new process.
19//!
20//! Workflows call the CLI's own commands through a connector built from the
21//! CLI's commands before lifecycle commands are attached. `codemode.workflows`
22//! composes immutable workflow handles, including bounded recursive calls.
23//!
24//! Input is validated against the workflow's schema before the execution
25//! starts; invalid input runs no command. The schema checker supports a
26//! bounded keyword set (see [`check_schema`]) and rejects any other validation
27//! keyword at attach or save time.
28//!
29//! With the default `native` feature, the local store holds an exclusive SQLite
30//! lock, so two processes of the
31//! same CLI cannot run workflows against one store at the same time.
32//!
33//! # Maintaining a catalog
34//!
35//! Every run of a named workflow is recorded in a run ledger beside the store,
36//! tagged with the workflow's version: a digest of its program and input
37//! schema. The ledger outlives the store's history pruning and feeds four
38//! read-only commands:
39//!
40//! - `workflows doctor` reports only what needs action: saved workflows that
41//!   call commands the CLI no longer has, workflows whose current version keeps
42//!   failing, runs interrupted mid-flight, and runs awaiting a decision. Each
43//!   finding names the command that resolves it. Informational notices
44//!   (never run, stale, duplicate, lost) appear only with `--all`. Exit code 1
45//!   means at least one error or warning.
46//! - `workflows stats` reports runs and success rate per workflow for its
47//!   current version, separate from runs of earlier versions.
48//! - `workflows failures` groups failed runs by cause: the step that was
49//!   executing and the error message with values (numbers, identifiers,
50//!   quoted text) removed. A group is active until the workflow next succeeds.
51//! - `workflows trace` shows one execution's steps, where it stopped, its
52//!   error, console output, and status timeline, with large values truncated.
53//!
54//! Ledger write failures are reported on stderr and never fail a run.
55//!
56//! # Hosted workflows
57//!
58//! Build with `default-features = false` and supply a [`WorkflowHost`] for
59//! execution, atomic SQL storage, timers, and fixtures. The standalone Cloudflare
60//! extension supplies `CloudflareWorkflowHost` with Durable Object SQLite and
61//! alarms. Hosts without a filesystem accept fixture JSON directly. The shared
62//! lifecycle, validation, diagnostics, retry, and trigger commands are unchanged.
63//!
64//! # Agent archetypes
65//!
66//! [`Workflows::archetype`] ships task guidance and a scope of commands and
67//! workflows as a top-level activation command. Operators can also persist
68//! definitions with `archetypes save` and retrieve their guidance with
69//! `archetypes activate`. Activation is advisory and executes no scoped command;
70//! all tools remain callable. Shipped guidance is also published as MCP prompts
71//! and in `--llms-full`; saved guidance stays behind activation.
72//!
73//! # Serving a CLI
74//!
75//! The native `serve` function replaces a CLI's `serve()` call: it attaches the default
76//! workflows, and `cli --codemode` serves the Code Mode lifecycle tools over
77//! stdio against the CLI's own commands. `ServeWorkflows` is its method
78//! form: an existing entry point changes `cli.serve()` to
79//! `cli.serve_workflows()`.
80
81mod archetypes;
82pub use archetypes::ARCHETYPES_GROUP_NAME;
83mod authority;
84pub use authority::{WorkflowAuthority, WorkflowBindings};
85
86mod database;
87mod diagnostics;
88mod fixtures;
89mod host;
90mod ledger;
91mod schema;
92#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
93mod serve;
94mod triggers;
95
96use std::collections::BTreeMap;
97use std::path::PathBuf;
98use std::sync::{Arc, OnceLock};
99use std::time::Duration;
100
101use async_trait::async_trait;
102use multicast::cli::Cli;
103use multicast::command::{
104    CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
105};
106use multicast::output::CommandResult;
107use multicast::schema::{FieldMeta, FieldType};
108use multicast::tool::ToolCatalog;
109#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
110use multicast_codemode::MulticastConnector;
111use multicast_codemode::{
112    CodeModeRunOptions, CodeModeService, ExecutionState, ExecutionStatus, LogEntryState,
113    RetryPolicy, Snippet, normalize_code, sanitize_namespace,
114};
115#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
116use multicast_codemode_local::LocalExecutorOptions;
117use serde_json::{Map, Value, json};
118use tokio::sync::OnceCell;
119
120pub use database::{WorkflowDatabase, WorkflowSql};
121pub use fixtures::{FixtureCall, FixtureContract, MAX_FIXTURE_BYTES, WorkflowFixture};
122pub use host::{WorkflowDatabaseKind, WorkflowHost};
123pub use multicast_codemode::WorkflowLimits;
124pub use schema::{check_supported as check_schema, validate as validate_input};
125#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
126pub use serve::{
127    CODEMODE_FLAG, ServeWorkflows, codemode_service, is_codemode_request, serve, serve_attached,
128};
129pub use triggers::{TriggerReceipt, TriggerRequest, TriggerSchedule, WorkflowTriggers};
130
131/// Process exit code for a workflow run awaiting approval or host reconciliation.
132///
133/// The value is `EX_TEMPFAIL`: the run is incomplete, not failed, and a later
134/// `workflows approve`, `workflows reject`, or `workflows resume` continues it.
135pub const PAUSED_EXIT_CODE: i32 = 75;
136
137/// True while a run is still making progress on its own: running, or paused only to wait for
138/// child workflows that are not themselves stopped for approval. A child wait is not a stop for
139/// the caller, so returning there would end the process and strand the child mid-call.
140fn still_working(state: &ExecutionState) -> bool {
141    match state.status {
142        ExecutionStatus::Running => true,
143        ExecutionStatus::Paused => {
144            state.workflow_wait.is_some()
145                && state
146                    .workflow_children
147                    .iter()
148                    .all(|child| child.pending.is_empty())
149        }
150        _ => false,
151    }
152}
153
154/// Name of the command group that manages workflows.
155pub const GROUP_NAME: &str = "workflows";
156
157/// Interval between execution snapshots while a run is in progress.
158const POLL_INTERVAL: Duration = Duration::from_millis(20);
159
160/// Returns the default workflow store for a CLI.
161///
162/// The store is `$XDG_DATA_HOME/incurs/<cli>/workflows.sqlite`, falling back
163/// to `~/.local/share` when `XDG_DATA_HOME` is unset or empty.
164#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
165pub fn default_store_path(cli_name: &str) -> PathBuf {
166    let data_home = std::env::var("XDG_DATA_HOME")
167        .ok()
168        .filter(|value| !value.is_empty())
169        .map(PathBuf::from)
170        .unwrap_or_else(|| {
171            dirs::home_dir()
172                .unwrap_or_default()
173                .join(".local")
174                .join("share")
175        });
176    data_home
177        .join("incurs")
178        .join(cli_name)
179        .join("workflows.sqlite")
180}
181
182/// A workflow compiled into the CLI binary.
183#[derive(Debug, Clone)]
184struct ShippedWorkflow {
185    name: String,
186    description: String,
187    input_schema: Value,
188    code: String,
189}
190
191/// Builder for the workflows attached to one CLI.
192#[derive(Debug, Clone, Default)]
193pub struct Workflows {
194    shipped: Vec<ShippedWorkflow>,
195    archetypes: Vec<archetypes::ShippedArchetype>,
196    store_path: Option<PathBuf>,
197    retry: RetryPolicy,
198    limits: multicast_codemode::WorkflowLimits,
199    approve_local: bool,
200}
201
202impl Workflows {
203    /// Creates a builder with no shipped workflows and the default store.
204    pub fn new() -> Self {
205        Self::default()
206    }
207
208    /// Sets finite budgets shared by every descendant of one root execution.
209    pub fn with_workflow_limits(
210        mut self,
211        limits: multicast_codemode::WorkflowLimits,
212    ) -> Result<Self, String> {
213        limits.check()?;
214        self.limits = limits;
215        Ok(self)
216    }
217
218    /// Ships a workflow with the binary as a top-level command.
219    ///
220    /// `code` is an async JavaScript function that receives the validated
221    /// input object, for example `async (input) => cli.sum(input)`.
222    /// `input_schema` must be an object schema; each property becomes a
223    /// command option.
224    pub fn shipped(
225        mut self,
226        name: impl Into<String>,
227        description: impl Into<String>,
228        input_schema: Value,
229        code: impl Into<String>,
230    ) -> Self {
231        self.shipped.push(ShippedWorkflow {
232            name: name.into(),
233            description: description.into(),
234            input_schema,
235            code: code.into(),
236        });
237        self
238    }
239
240    /// Ships an agent archetype with the binary as a top-level command.
241    ///
242    /// An archetype focuses an agent on one kind of task. `summary` says what
243    /// it is for and becomes the command description; `instructions` is
244    /// guidance for an agent doing that task; `scope` names the commands of
245    /// this CLI and the shipped workflows the task uses. Activating it returns
246    /// the guidance and the scoped contracts. Activation is advisory: no other
247    /// command is hidden or refused.
248    pub fn archetype<I, S>(
249        mut self,
250        name: impl Into<String>,
251        summary: impl Into<String>,
252        instructions: impl Into<String>,
253        scope: I,
254    ) -> Self
255    where
256        I: IntoIterator<Item = S>,
257        S: Into<String>,
258    {
259        self.archetypes.push(archetypes::ShippedArchetype {
260            name: name.into(),
261            summary: summary.into(),
262            instructions: instructions.into(),
263            scope: scope.into_iter().map(Into::into).collect(),
264        });
265        self
266    }
267
268    /// Overrides the durable store location. See `default_store_path`.
269    pub fn store_path(mut self, path: impl Into<PathBuf>) -> Self {
270        self.store_path = Some(path.into());
271        self
272    }
273
274    /// Enables bounded transient retries for host-declared read-only or idempotent commands.
275    ///
276    /// The default permits one attempt. Uncertain writes pause for reconciliation;
277    /// increasing the budget never grants permission to repeat an unsafe command.
278    pub fn retry_policy(mut self, policy: RetryPolicy) -> Self {
279        self.retry = policy;
280        self
281    }
282
283    /// Lets workflows call this CLI's own commands without pausing for approval.
284    ///
285    /// For a host whose commands act only on the local machine, where the operator
286    /// already chose to run the workflow. Results are still logged, never re-run
287    /// on replay, and remote tools keep the default policy.
288    pub fn approve_local_commands(mut self) -> Self {
289        self.approve_local = true;
290        self
291    }
292
293    /// Adds shipped workflow commands and the `workflows` group to a CLI.
294    ///
295    /// Fails when a workflow name collides with an existing command, when a
296    /// shipped schema uses an unsupported keyword or is not an object schema,
297    /// or when shipped code references a command the CLI does not have.
298    /// References are found by scanning for `namespace.method` and
299    /// `namespace["method"]`, so the same text inside a string or comment is
300    /// checked too.
301    pub fn attach(self, cli: Cli) -> Result<Cli, String> {
302        self.attach_with_triggers(cli).map(|(cli, _)| cli)
303    }
304
305    /// Attaches commands and returns a durable host-trigger admission boundary.
306    ///
307    /// A webhook adapter authenticates and authorizes its caller before enqueueing.
308    /// The host calls [`WorkflowTriggers::tick`] to deliver queued and scheduled work.
309    pub fn attach_with_triggers(self, cli: Cli) -> Result<(Cli, WorkflowTriggers), String> {
310        self.attach_inner(cli, None)
311    }
312
313    /// Attaches every workflow command using host-owned execution and storage.
314    /// Returns the same trigger API as the native host; the host supplies its
315    /// authentication boundary, timer lifetime, and durable wakeups.
316    pub fn attach_hosted(
317        self,
318        cli: Cli,
319        host: Arc<dyn WorkflowHost>,
320    ) -> Result<(Cli, WorkflowTriggers), String> {
321        self.attach_inner(cli, Some(host))
322    }
323
324    fn attach_inner(
325        self,
326        cli: Cli,
327        host: Option<Arc<dyn WorkflowHost>>,
328    ) -> Result<(Cli, WorkflowTriggers), String> {
329        let catalog = cli.try_tool_catalog().map_err(|error| error.to_string())?;
330        let cli_name = catalog.name().to_string();
331        let namespace = sanitize_namespace(&cli_name);
332        for group_name in [GROUP_NAME, ARCHETYPES_GROUP_NAME] {
333            if cli.has_command(group_name) {
334                return Err(format!(
335                    "CLI '{cli_name}' already has a '{group_name}' command"
336                ));
337            }
338        }
339        let mut shipped = BTreeMap::new();
340        for workflow in &self.shipped {
341            if workflow.name == GROUP_NAME
342                || workflow.name == ARCHETYPES_GROUP_NAME
343                || cli.has_command(&workflow.name)
344            {
345                return Err(format!(
346                    "Workflow '{}' collides with an existing command",
347                    workflow.name
348                ));
349            }
350            if shipped.contains_key(&workflow.name) {
351                return Err(format!("Workflow '{}' is shipped twice", workflow.name));
352            }
353            check_object_schema(&workflow.input_schema)
354                .map_err(|error| format!("Workflow '{}': {error}", workflow.name))?;
355            for method in referenced_methods(&workflow.code, &namespace) {
356                if catalog.get(&method).is_none() {
357                    return Err(format!(
358                        "Workflow '{}' calls {namespace}.{method}, which is not a command of '{cli_name}'",
359                        workflow.name
360                    ));
361                }
362            }
363            shipped.insert(workflow.name.clone(), workflow.clone());
364        }
365        let mut shipped_archetypes = BTreeMap::new();
366        for archetype in &self.archetypes {
367            let name = &archetype.name;
368            if name == GROUP_NAME
369                || name == ARCHETYPES_GROUP_NAME
370                || cli.has_command(name)
371                || shipped.contains_key(name)
372            {
373                return Err(format!(
374                    "Archetype '{name}' collides with an existing command"
375                ));
376            }
377            if shipped_archetypes.contains_key(name) {
378                return Err(format!("Archetype '{name}' is shipped twice"));
379            }
380            archetypes::check_definition(
381                name,
382                &archetype.summary,
383                &archetype.instructions,
384                &archetype.scope,
385            )?;
386            shipped_archetypes.insert(name.clone(), archetype.clone());
387        }
388        for archetype in shipped_archetypes.values() {
389            for entry in &archetype.scope {
390                if shipped_archetypes.contains_key(entry) {
391                    return Err(format!(
392                        "Archetype '{}' scopes archetype '{entry}'; an archetype scopes commands and workflows only",
393                        archetype.name
394                    ));
395                }
396                if catalog.get(entry).is_none() && !shipped.contains_key(entry) {
397                    return Err(format!(
398                        "Archetype '{}' scopes '{entry}', which is not a command or shipped workflow of '{cli_name}'",
399                        archetype.name
400                    ));
401                }
402            }
403        }
404        let store_path = if host.is_some() {
405            PathBuf::new()
406        } else {
407            #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
408            {
409                self.store_path
410                    .unwrap_or_else(|| default_store_path(&cli_name))
411            }
412            #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
413            {
414                return Err("A workflow host is required; use Workflows::attach_hosted".into());
415            }
416        };
417        let state = Arc::new(State {
418            catalog,
419            host,
420            store_path,
421            shipped,
422            archetypes: shipped_archetypes,
423            archetype_store: OnceLock::new(),
424            retry: self.retry,
425            limits: self.limits,
426            approve_local: self.approve_local,
427            service: OnceCell::new(),
428            ledger: OnceLock::new(),
429        });
430
431        let mut cli = cli;
432        for workflow in self.shipped {
433            let options_fields = schema_fields(&workflow.input_schema);
434            let mut def = CommandDef::build(
435                workflow.name.clone(),
436                ShippedHandler {
437                    state: state.clone(),
438                    name: workflow.name.clone(),
439                },
440            )
441            .description(workflow.description.clone())
442            .mcp_input_schema(workflow.input_schema.clone())
443            .done();
444            def.options_fields = options_fields;
445            cli = cli.command(workflow.name, def);
446        }
447        for archetype in &self.archetypes {
448            cli = cli
449                .command(
450                    archetype.name.clone(),
451                    archetypes::shipped_command(state.clone(), archetype),
452                )
453                .prompt_guide(multicast::prompt::PromptGuide::new(
454                    archetype.name.clone(),
455                    archetype.summary.clone(),
456                    archetype.instructions.clone(),
457                    archetype.scope.clone(),
458                ));
459        }
460        let triggers = WorkflowTriggers::new(state.clone());
461        Ok((
462            cli.group(group(state.clone()))
463                .group(archetypes::group(state)),
464            triggers,
465        ))
466    }
467}
468
469/// Requires an object input schema whose keywords the checker supports.
470fn check_object_schema(schema: &Value) -> Result<(), String> {
471    check_schema(schema).map_err(|errors| errors.join("; "))?;
472    if schema.get("type").and_then(Value::as_str) != Some("object") {
473        return Err("input schema must have type 'object'".into());
474    }
475    Ok(())
476}
477
478/// Returns every method of `namespace` the code references.
479fn referenced_methods(code: &str, namespace: &str) -> Vec<String> {
480    let mut methods = Vec::new();
481    let bytes = code.as_bytes();
482    let mut start = 0;
483    while let Some(offset) = code[start..].find(namespace) {
484        let index = start + offset;
485        start = index + namespace.len();
486        let before = code[..index].chars().next_back();
487        if before.is_some_and(|ch| is_identifier_char(ch) || ch == '.') {
488            continue;
489        }
490        let rest = &code[start..];
491        if let Some(after_dot) = rest.strip_prefix('.') {
492            let method: String = after_dot
493                .chars()
494                .take_while(|ch| is_identifier_char(*ch))
495                .collect();
496            if !method.is_empty() {
497                methods.push(method);
498            }
499        } else if let Some(after_bracket) = rest.strip_prefix('[') {
500            let Some(quote) = after_bracket
501                .chars()
502                .next()
503                .filter(|ch| *ch == '"' || *ch == '\'')
504            else {
505                continue;
506            };
507            let literal = &after_bracket[1..];
508            if let Some(end) = literal.find(quote)
509                && literal[end + 1..].starts_with(']')
510            {
511                methods.push(literal[..end].to_string());
512            }
513        }
514        let _ = bytes;
515    }
516    methods
517}
518
519fn is_identifier_char(ch: char) -> bool {
520    ch == '_' || ch == '$' || ch.is_alphanumeric()
521}
522
523/// Converts the properties of an object schema to command options.
524fn schema_fields(schema: &Value) -> Vec<FieldMeta> {
525    let required: Vec<&str> = schema
526        .get("required")
527        .and_then(Value::as_array)
528        .map(|names| names.iter().filter_map(Value::as_str).collect())
529        .unwrap_or_default();
530    schema
531        .get("properties")
532        .and_then(Value::as_object)
533        .map(|properties| {
534            properties
535                .iter()
536                .map(|(name, property)| {
537                    let field_type = match primary_type(property) {
538                        Some("boolean") => FieldType::Boolean,
539                        Some("integer" | "number") => FieldType::Number,
540                        Some("array") => FieldType::Array(Box::new(FieldType::Value)),
541                        Some("object") => FieldType::Value,
542                        _ => FieldType::String,
543                    };
544                    let mut meta = field(
545                        name,
546                        field_type,
547                        required.contains(&name.as_str()),
548                        property.get("description").and_then(Value::as_str),
549                    );
550                    meta.default = property.get("default").cloned();
551                    meta
552                })
553                .collect()
554        })
555        .unwrap_or_default()
556}
557
558/// The first non-null type a property schema declares.
559fn primary_type(schema: &Value) -> Option<&str> {
560    match schema.get("type")? {
561        Value::String(name) => Some(name),
562        Value::Array(names) => names
563            .iter()
564            .filter_map(Value::as_str)
565            .find(|name| *name != "null"),
566        _ => None,
567    }
568}
569
570/// Builds command field metadata with leaked static strings.
571fn field(
572    name: &str,
573    field_type: FieldType,
574    required: bool,
575    description: Option<&str>,
576) -> FieldMeta {
577    let name: &'static str = Box::leak(name.to_string().into_boxed_str());
578    FieldMeta {
579        name,
580        cli_name: multicast::schema::to_kebab(name),
581        description: description.map(|text| &*Box::leak(text.to_string().into_boxed_str())),
582        field_type,
583        required,
584        default: None,
585        alias: None,
586        deprecated: false,
587        env_name: None,
588    }
589}
590
591/// State shared by every workflow command of one CLI.
592struct State {
593    /// Commands of the CLI before workflow commands were attached.
594    catalog: ToolCatalog,
595    #[cfg_attr(
596        not(all(feature = "native", not(target_arch = "wasm32"))),
597        allow(dead_code)
598    )]
599    store_path: PathBuf,
600    shipped: BTreeMap<String, ShippedWorkflow>,
601    /// Archetypes compiled into the CLI binary.
602    archetypes: BTreeMap<String, archetypes::ShippedArchetype>,
603    /// Saved archetypes, opened on first use.
604    archetype_store: OnceLock<Result<archetypes::ArchetypeStore, String>>,
605    retry: RetryPolicy,
606    limits: multicast_codemode::WorkflowLimits,
607    approve_local: bool,
608    host: Option<Arc<dyn WorkflowHost>>,
609    service: OnceCell<Arc<dyn CodeModeService>>,
610    /// Run ledger, or `None` when it could not be opened.
611    ledger: OnceLock<Option<ledger::Ledger>>,
612}
613
614/// A workflow resolved for listing or running.
615struct Resolved {
616    name: String,
617    description: String,
618    origin: &'static str,
619    input_schema: Option<Value>,
620    code: String,
621}
622
623impl Resolved {
624    fn version(&self) -> String {
625        ledger::version(&self.code, self.input_schema.as_ref())
626    }
627
628    fn summary(&self) -> Value {
629        json!({
630            "name": self.name,
631            "description": self.description,
632            "origin": self.origin,
633            "version": self.version(),
634            "inputSchema": self.input_schema,
635        })
636    }
637}
638
639/// Identifies the named workflow an execution runs, for the ledger.
640struct RunTag {
641    workflow: String,
642    origin: &'static str,
643    version: String,
644}
645
646impl State {
647    /// Opens the durable store and Code Mode actor on first use.
648    async fn service(&self) -> Result<&dyn CodeModeService, String> {
649        self.service
650            .get_or_try_init(|| async {
651                let service: Arc<dyn CodeModeService> = if let Some(host) = &self.host {
652                    host.service_with_limits(self.catalog.clone(), self.retry, self.limits.clone())
653                } else {
654                    #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
655                    {
656                        if let Some(parent) = self.store_path.parent() {
657                            std::fs::create_dir_all(parent).map_err(|error| {
658                                format!("Cannot create workflow store directory: {error}")
659                            })?;
660                        }
661                        let service = multicast_codemode_local::spawn_codemode_with_limits(
662                            &self.store_path,
663                            LocalExecutorOptions::default(),
664                            vec![Arc::new({
665                                let connector = MulticastConnector::new(self.catalog.clone())
666                                    .with_retry_policy(self.retry);
667                                if self.approve_local {
668                                    connector.with_policy_resolver(Arc::new(LocalApproval))
669                                } else {
670                                    connector
671                                }
672                            })],
673                            self.limits.clone(),
674                        )?;
675                        Ok(Arc::new(service) as Arc<dyn CodeModeService>)
676                    }
677                    #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
678                    {
679                        Err("A workflow host is required".into())
680                    }
681                }?;
682                let definitions = self
683                    .shipped
684                    .iter()
685                    .map(|(name, w)| {
686                        (
687                            name.clone(),
688                            multicast_codemode::WorkflowDefinition {
689                                source: multicast_codemode::normalize_code(&w.code),
690                                input: w.input_schema.clone(),
691                                output: Value::Bool(true),
692                                bindings: serde_json::json!({}),
693                            },
694                        )
695                    })
696                    .collect();
697                service.install_workflows(definitions).await?;
698                Ok(service)
699            })
700            .await
701            .map(Arc::as_ref)
702    }
703
704    async fn sleep(&self, milliseconds: u64) {
705        if let Some(host) = &self.host {
706            host.sleep(milliseconds).await;
707            return;
708        }
709        #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
710        tokio::time::sleep(Duration::from_millis(milliseconds)).await;
711    }
712
713    async fn settle(
714        &self,
715        service: &dyn CodeModeService,
716        mut state: ExecutionState,
717    ) -> Result<ExecutionState, String> {
718        while still_working(&state) {
719            self.sleep(POLL_INTERVAL.as_millis() as u64).await;
720            state = service.execution(state.id.clone()).await?;
721        }
722        Ok(state)
723    }
724
725    /// Opens the run ledger on first use; reports and disables it on failure.
726    fn ledger(&self) -> Option<&ledger::Ledger> {
727        self.ledger
728            .get_or_init(|| {
729                let opened = if let Some(host) = &self.host {
730                    host.database(WorkflowDatabaseKind::Ledger)
731                        .and_then(ledger::Ledger::from_database)
732                } else {
733                    #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
734                    {
735                        let path = ledger::ledger_path(&self.store_path);
736                        path.parent()
737                            .map_or(Ok(()), std::fs::create_dir_all)
738                            .map_err(|error| {
739                                format!("Cannot create workflow ledger directory: {error}")
740                            })
741                            .and_then(|()| ledger::Ledger::open(&path))
742                    }
743                    #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
744                    {
745                        Err("A workflow host is required".into())
746                    }
747                };
748                match opened {
749                    Ok(ledger) => Some(ledger),
750                    Err(message) => {
751                        eprintln!("warning: workflow ledger unavailable: {message}");
752                        None
753                    }
754                }
755            })
756            .as_ref()
757    }
758
759    /// Records an execution's current state in the ledger, if it tracks it.
760    fn record(&self, state: &ExecutionState) {
761        if let Some(ledger) = self.ledger() {
762            warn_ledger(ledger.record(state, state.updated_at));
763        }
764    }
765
766    /// Shipped workflows and the saved workflows they do not shadow.
767    async fn catalog_workflows(&self) -> Result<Vec<Resolved>, String> {
768        let mut workflows: Vec<Resolved> = self.shipped.values().map(shipped_resolved).collect();
769        for snippet in self.service().await?.snippets().await? {
770            if !self.shipped.contains_key(&snippet.name) {
771                workflows.push(saved_resolved(snippet));
772            }
773        }
774        Ok(workflows)
775    }
776
777    /// Finds a workflow by name, shipped workflows first.
778    async fn resolve(&self, name: &str) -> Result<Option<Resolved>, String> {
779        if let Some(workflow) = self.shipped.get(name) {
780            return Ok(Some(shipped_resolved(workflow)));
781        }
782        let snippets = self.service().await?.snippets().await?;
783        Ok(snippets
784            .into_iter()
785            .find(|snippet| snippet.name == name)
786            .map(saved_resolved))
787    }
788
789    /// Validates input, starts a durable execution, and waits for it to settle.
790    async fn run(&self, workflow: &Resolved, input: Value, ctx: &CommandContext) -> CommandResult {
791        let code = match program(workflow, input) {
792            Ok((_, code)) => code,
793            Err(message) => return error("INVALID_INPUT", message),
794        };
795        let tag = RunTag {
796            workflow: workflow.name.clone(),
797            origin: workflow.origin,
798            version: workflow.version(),
799        };
800        self.start(code, Some(tag), ctx).await
801    }
802
803    /// Starts a durable execution of a complete program and waits for it to settle.
804    ///
805    /// A tagged run is recorded in the ledger; an ad hoc program is not.
806    async fn start(
807        &self,
808        code: String,
809        tag: Option<RunTag>,
810        ctx: &CommandContext,
811    ) -> CommandResult {
812        let result = async {
813            let service = self.service().await?;
814            let mut options = run_options(ctx);
815            options.workflow = tag
816                .as_ref()
817                .map(|tag| multicast_codemode::WorkflowIdentity {
818                    name: tag.workflow.clone(),
819                    version: tag.version.clone(),
820                });
821            let state = service.execute(code, options).await?;
822            // Announce the identifier before waiting, so a run interrupted by a
823            // crash can still be found and resumed.
824            if !result_only(ctx) {
825                eprintln!("workflow execution {} started", state.id);
826            }
827            if let Some(tag) = &tag
828                && let Some(ledger) = self.ledger()
829            {
830                warn_ledger(ledger.start(&ledger::RunStart {
831                    execution_id: &state.id,
832                    workflow: &tag.workflow,
833                    origin: tag.origin,
834                    version: &tag.version,
835                    at: state.created_at,
836                }));
837            }
838            let state = self.settle(service, state).await?;
839            self.record(&state);
840            Ok::<_, String>(state)
841        }
842        .await;
843        match result {
844            Ok(state) if result_only(ctx) && state.status == ExecutionStatus::Completed => {
845                ok(state.result.clone().unwrap_or(Value::Null))
846            }
847            Ok(state) => outcome(&state),
848            Err(message) => error("WORKFLOW_HOST_ERROR", message),
849        }
850    }
851}
852
853/// Validates input and builds the program shared by execution and fixture checks.
854fn program(workflow: &Resolved, input: Value) -> Result<(Value, String), String> {
855    let input = match &workflow.input_schema {
856        Some(schema) => {
857            let input = normalize_input(schema, input);
858            validate_input(schema, &input).map_err(|errors| {
859                format!(
860                    "Invalid input for workflow '{}': {}",
861                    workflow.name,
862                    errors.join("; ")
863                )
864            })?;
865            input
866        }
867        None => input,
868    };
869    let code = format!(
870        "async () => {{ const input = {input}; return await ({})(input); }}",
871        normalize_code(&workflow.code)
872    );
873    Ok((input, code))
874}
875
876/// Reports a ledger failure without failing the command.
877fn warn_ledger(result: Result<(), String>) {
878    if let Err(message) = result {
879        eprintln!("warning: {message}");
880    }
881}
882
883fn shipped_resolved(workflow: &ShippedWorkflow) -> Resolved {
884    Resolved {
885        name: workflow.name.clone(),
886        description: workflow.description.clone(),
887        origin: "shipped",
888        input_schema: Some(workflow.input_schema.clone()),
889        code: workflow.code.clone(),
890    }
891}
892
893fn saved_resolved(snippet: Snippet) -> Resolved {
894    Resolved {
895        name: snippet.name,
896        description: snippet.description,
897        origin: "saved",
898        input_schema: snippet.input_schema,
899        code: snippet.code,
900    }
901}
902
903fn run_options(ctx: &CommandContext) -> CodeModeRunOptions {
904    CodeModeRunOptions {
905        request: ctx.request.clone(),
906        ..CodeModeRunOptions::default()
907    }
908}
909
910/// Polls an execution until it leaves the running state.
911/// Adapts CLI option values to the workflow's input schema.
912///
913/// The CLI delivers object and array options as JSON text and reports absent
914/// optional options as null. Object values are parsed, string array items are
915/// parsed when the item schema is not a string, and nulls are dropped for
916/// optional properties that do not accept null. Everything else is passed
917/// through for validation to judge.
918fn normalize_input(schema: &Value, input: Value) -> Value {
919    let Value::Object(fields) = input else {
920        return input;
921    };
922    let properties = schema.get("properties").and_then(Value::as_object);
923    let required: Vec<&str> = schema
924        .get("required")
925        .and_then(Value::as_array)
926        .map(|names| names.iter().filter_map(Value::as_str).collect())
927        .unwrap_or_default();
928    let mut normalized = Map::new();
929    for (name, value) in fields {
930        let property = properties.and_then(|properties| properties.get(&name));
931        let Some(property) = property else {
932            normalized.insert(name, value);
933            continue;
934        };
935        if value.is_null() && !required.contains(&name.as_str()) && !accepts_null(property) {
936            continue;
937        }
938        normalized.insert(name, coerce(property, value));
939    }
940    Value::Object(normalized)
941}
942
943fn coerce(schema: &Value, value: Value) -> Value {
944    match (primary_type(schema), value) {
945        (Some("object" | "array"), Value::String(text)) => {
946            serde_json::from_str(&text).unwrap_or(Value::String(text))
947        }
948        (Some("array"), Value::Array(items)) => {
949            let item_schema = schema.get("items");
950            let parse = item_schema
951                .and_then(primary_type)
952                .is_some_and(|item_type| item_type != "string");
953            Value::Array(
954                items
955                    .into_iter()
956                    .map(|item| match item {
957                        Value::String(text) if parse => {
958                            serde_json::from_str(&text).unwrap_or(Value::String(text))
959                        }
960                        other => other,
961                    })
962                    .collect(),
963            )
964        }
965        (_, value) => value,
966    }
967}
968
969fn accepts_null(schema: &Value) -> bool {
970    match schema.get("type") {
971        Some(Value::String(name)) => name == "null",
972        Some(Value::Array(names)) => names.iter().any(|name| name == "null"),
973        _ => true,
974    }
975}
976
977/// Pending approvals of an execution, as reported to callers.
978fn pending(state: &ExecutionState) -> Vec<Value> {
979    let mut actions:Vec<Value>=state.log.iter().filter(|entry|entry.state==LogEntryState::Pending && entry.requires_approval).map(|entry|json!({"seq":entry.seq,"method":format!("{}.{}",entry.connector,entry.method),"arguments":entry.arguments})).collect();
980    for child in &state.workflow_children {
981        for seq in &child.pending {
982            actions.push(json!({"executionId":child.id,"seq":seq}));
983        }
984    }
985    actions
986}
987
988/// Selects logical result projection without changing execution or failure semantics.
989fn result_only(ctx: &CommandContext) -> bool {
990    ctx.options
991        .get("result_only")
992        .and_then(Value::as_bool)
993        .unwrap_or(false)
994}
995
996/// Maps an execution snapshot to a command result.
997fn outcome(state: &ExecutionState) -> CommandResult {
998    let id = &state.id;
999    match state.status {
1000        ExecutionStatus::Completed => {
1001            let mut data = json!({
1002                "executionId": id,
1003                "status": "completed",
1004                "result": state.result.clone().unwrap_or(Value::Null),
1005            });
1006            if !state.workflow_children.is_empty() {
1007                data["children"] = json!(state.workflow_children);
1008            }
1009            ok(data)
1010        }
1011        ExecutionStatus::Paused => CommandResult::Ok {
1012            data: json!({
1013                "executionId": id,
1014                "status": "paused",
1015                "pending": pending(state),
1016                "children":state.workflow_children,
1017                "childWait":state.workflow_wait,
1018                "error": state.error,
1019                "recoveryRequired": state.log.iter().any(|entry| entry.state == LogEntryState::Executing),
1020            }),
1021            cta: None,
1022            exit_code: Some(PAUSED_EXIT_CODE),
1023        },
1024        ExecutionStatus::Running => ok(json!({"executionId": id, "status": "running"})),
1025        ExecutionStatus::Error => error(
1026            "WORKFLOW_FAILED",
1027            format!(
1028                "Workflow execution {id} failed: {}",
1029                state.error.as_deref().unwrap_or("unknown error")
1030            ),
1031        ),
1032        ExecutionStatus::Rejected => error(
1033            "WORKFLOW_REJECTED",
1034            format!("Workflow execution {id} was rejected"),
1035        ),
1036        ExecutionStatus::Cancelled => error(
1037            "WORKFLOW_CANCELLED",
1038            format!("Workflow execution {id} was cancelled"),
1039        ),
1040        ExecutionStatus::RolledBack => error(
1041            "WORKFLOW_ROLLED_BACK",
1042            format!("Workflow execution {id} was rolled back"),
1043        ),
1044    }
1045}
1046
1047fn ok(data: Value) -> CommandResult {
1048    CommandResult::Ok {
1049        data,
1050        cta: None,
1051        exit_code: None,
1052    }
1053}
1054
1055fn error(code: &str, message: impl Into<String>) -> CommandResult {
1056    CommandResult::Error {
1057        code: code.into(),
1058        message: message.into(),
1059        retryable: false,
1060        exit_code: None,
1061        cta: None,
1062    }
1063}
1064
1065/// Opt-in logical projection; transports retain their required protocol envelopes.
1066fn result_only_field() -> FieldMeta {
1067    field(
1068        "result_only",
1069        FieldType::Boolean,
1070        false,
1071        Some("Return only the completed value; pauses and failures retain diagnostics"),
1072    )
1073}
1074
1075fn string_arg<'a>(values: &'a Value, name: &str) -> Option<&'a str> {
1076    values.get(name).and_then(Value::as_str)
1077}
1078
1079/// Reads an optional JSON value supplied as text on the CLI or as JSON over MCP.
1080fn json_option(values: &Value, name: &str) -> Result<Option<Value>, String> {
1081    match values.get(name) {
1082        None | Some(Value::Null) => Ok(None),
1083        Some(Value::String(text)) => serde_json::from_str(text)
1084            .map(Some)
1085            .map_err(|error| format!("--{name} is not valid JSON: {error}")),
1086        Some(value) => Ok(Some(value.clone())),
1087    }
1088}
1089
1090/// Runs one shipped workflow from its command options.
1091struct ShippedHandler {
1092    state: Arc<State>,
1093    name: String,
1094}
1095
1096#[async_trait]
1097impl CommandHandler for ShippedHandler {
1098    async fn run(&self, ctx: CommandContext) -> CommandResult {
1099        let Some(workflow) = self.state.shipped.get(&self.name) else {
1100            return error("WORKFLOW_NOT_FOUND", format!("No workflow '{}'", self.name));
1101        };
1102        let input = match &ctx.options {
1103            Value::Object(_) => ctx.options.clone(),
1104            _ => json!({}),
1105        };
1106        self.state
1107            .run(&shipped_resolved(workflow), input, &ctx)
1108            .await
1109    }
1110}
1111
1112/// One subcommand of the `workflows` group.
1113#[derive(Clone, Copy)]
1114enum Action {
1115    List,
1116    Show,
1117    Run,
1118    Exec,
1119    Save,
1120    Publish,
1121    Delete,
1122    Approve,
1123    Reject,
1124    Resume,
1125    Cancel,
1126    Status,
1127    Doctor,
1128    Stats,
1129    Failures,
1130    Trace,
1131    Capture,
1132    Check,
1133}
1134
1135struct GroupHandler {
1136    state: Arc<State>,
1137    action: Action,
1138}
1139
1140#[async_trait]
1141impl CommandHandler for GroupHandler {
1142    async fn run(&self, ctx: CommandContext) -> CommandResult {
1143        match self.dispatch(&ctx).await {
1144            Ok(result) => result,
1145            Err(message) => error("WORKFLOW_HOST_ERROR", message),
1146        }
1147    }
1148}
1149
1150impl GroupHandler {
1151    async fn dispatch(&self, ctx: &CommandContext) -> Result<CommandResult, String> {
1152        let state = &self.state;
1153        let args = &ctx.args;
1154        let options = &ctx.options;
1155        Ok(match self.action {
1156            Action::List => ok(Value::Array(
1157                state
1158                    .catalog_workflows()
1159                    .await?
1160                    .iter()
1161                    .map(Resolved::summary)
1162                    .collect(),
1163            )),
1164            Action::Show => {
1165                let name = string_arg(args, "name").unwrap_or_default();
1166                match state.resolve(name).await? {
1167                    Some(workflow) => {
1168                        let mut data = workflow.summary();
1169                        data["code"] = Value::String(workflow.code);
1170                        ok(data)
1171                    }
1172                    None => not_found(name),
1173                }
1174            }
1175            Action::Run => {
1176                let name = string_arg(args, "name").unwrap_or_default();
1177                let input = match json_option(options, "input") {
1178                    Ok(input) => input.unwrap_or_else(|| json!({})),
1179                    Err(message) => return Ok(error("INVALID_INPUT", message)),
1180                };
1181                match state.resolve(name).await? {
1182                    Some(workflow) => state.run(&workflow, input, ctx).await,
1183                    None => not_found(name),
1184                }
1185            }
1186            Action::Exec => {
1187                let code = string_arg(args, "code").unwrap_or_default().to_string();
1188                state.start(code, None, ctx).await
1189            }
1190            Action::Save | Action::Publish => {
1191                let name = string_arg(args, "name").unwrap_or_default();
1192                if state.shipped.contains_key(name) {
1193                    return Ok(error(
1194                        "WORKFLOW_SHIPPED",
1195                        format!("'{name}' is a shipped workflow and cannot be replaced"),
1196                    ));
1197                }
1198                let input_schema = match json_option(options, "input_schema") {
1199                    Ok(schema) => schema,
1200                    Err(message) => return Ok(error("INVALID_SCHEMA", message)),
1201                };
1202                if let Some(schema) = &input_schema
1203                    && let Err(errors) = check_schema(schema)
1204                {
1205                    return Ok(error("INVALID_SCHEMA", errors.join("; ")));
1206                }
1207                if matches!(self.action, Action::Publish) {
1208                    let code = string_arg(options, "code").unwrap_or_default();
1209                    if name.trim().is_empty() || code.trim().is_empty() {
1210                        return Ok(error(
1211                            "INVALID_WORKFLOW",
1212                            "Name and callable code must not be empty",
1213                        ));
1214                    }
1215                    let description = string_arg(options, "description").unwrap_or_default();
1216                    let snippet = state
1217                        .service()
1218                        .await?
1219                        .publish_snippet(
1220                            name.to_string(),
1221                            description.to_string(),
1222                            code.to_string(),
1223                            input_schema,
1224                        )
1225                        .await?;
1226                    return Ok(ok(saved_resolved(snippet).summary()));
1227                }
1228                let from = string_arg(options, "from").unwrap_or_default();
1229                let description = string_arg(options, "description").unwrap_or_default();
1230                let snippet = state
1231                    .service()
1232                    .await?
1233                    .save_snippet(
1234                        name.to_string(),
1235                        description.to_string(),
1236                        from.to_string(),
1237                        input_schema,
1238                    )
1239                    .await?;
1240                ok(saved_resolved(snippet).summary())
1241            }
1242            Action::Delete => {
1243                let name = string_arg(args, "name").unwrap_or_default();
1244                if state.shipped.contains_key(name) {
1245                    return Ok(error(
1246                        "WORKFLOW_SHIPPED",
1247                        format!("'{name}' is a shipped workflow and cannot be deleted"),
1248                    ));
1249                }
1250                let deleted = state
1251                    .service()
1252                    .await?
1253                    .delete_snippet(name.to_string())
1254                    .await?;
1255                if deleted {
1256                    if let Some(ledger) = state.ledger() {
1257                        warn_ledger(ledger.forget(name));
1258                    }
1259                    ok(json!({"name": name, "deleted": true}))
1260                } else {
1261                    not_found(name)
1262                }
1263            }
1264            Action::Approve | Action::Reject => {
1265                let id = string_arg(args, "execution_id")
1266                    .unwrap_or_default()
1267                    .to_string();
1268                let service = state.service().await?;
1269                let current = service.execution(id.clone()).await?;
1270                let actions = pending(&current);
1271                let selected: Vec<&Value> = actions
1272                    .iter()
1273                    .filter(|action| {
1274                        options
1275                            .get("seq")
1276                            .and_then(Value::as_u64)
1277                            .is_none_or(|seq| action["seq"].as_u64() == Some(seq))
1278                    })
1279                    .collect();
1280                let action = match selected.as_slice() {
1281                    [single] => *single,
1282                    [] => {
1283                        return Ok(error(
1284                            "NO_PENDING_ACTION",
1285                            format!("Workflow execution {id} has no matching pending action"),
1286                        ));
1287                    }
1288                    _ => {
1289                        return Ok(error(
1290                            "AMBIGUOUS_PENDING_ACTION",
1291                            "Pass the child execution ID and --seq shown by status",
1292                        ));
1293                    }
1294                };
1295                let seq = action["seq"].as_u64().unwrap_or_default();
1296                let target = action["executionId"].as_str().unwrap_or(&id).to_string();
1297                let next = if matches!(self.action, Action::Approve) {
1298                    service.approve(target, seq, run_options(ctx)).await?
1299                } else {
1300                    service.reject(target, seq).await?
1301                };
1302                let _ = state.settle(service, next).await?;
1303                let settled = service.execution(id).await?;
1304                state.record(&settled);
1305                outcome(&settled)
1306            }
1307            Action::Resume => {
1308                let id = string_arg(args, "execution_id")
1309                    .unwrap_or_default()
1310                    .to_string();
1311                let service = state.service().await?;
1312                let next = service.resume(id, run_options(ctx)).await?;
1313                let settled = state.settle(service, next).await?;
1314                state.record(&settled);
1315                outcome(&settled)
1316            }
1317            Action::Cancel => {
1318                let id = string_arg(args, "execution_id")
1319                    .unwrap_or_default()
1320                    .to_string();
1321                let cancelled = state.service().await?.cancel(id).await?;
1322                state.record(&cancelled);
1323                if cancelled.status == ExecutionStatus::Cancelled {
1324                    ok(json!({ "executionId": cancelled.id, "status": "cancelled" }))
1325                } else {
1326                    outcome(&cancelled)
1327                }
1328            }
1329            Action::Status => {
1330                let id = string_arg(args, "execution_id")
1331                    .unwrap_or_default()
1332                    .to_string();
1333                let current = state.service().await?.execution(id).await?;
1334                state.record(&current);
1335                outcome(&current)
1336            }
1337            Action::Doctor => state.doctor(options).await?,
1338            Action::Stats => state.stats(string_arg(args, "name")).await?,
1339            Action::Failures => {
1340                let all = options.get("all").and_then(Value::as_bool).unwrap_or(false);
1341                state.failures(string_arg(args, "name"), all).await?
1342            }
1343            Action::Trace => {
1344                let id = string_arg(args, "execution_id").unwrap_or_default();
1345                let full = options
1346                    .get("full")
1347                    .and_then(Value::as_bool)
1348                    .unwrap_or(false);
1349                state.trace(id, full).await?
1350            }
1351            Action::Capture | Action::Check => {
1352                let name = string_arg(args, "name").unwrap_or_default();
1353                let Some(workflow) = state.resolve(name).await? else {
1354                    return Ok(not_found(name));
1355                };
1356                let result = if matches!(self.action, Action::Capture) {
1357                    let input = json_option(options, "input")?.unwrap_or_else(|| json!({}));
1358                    state
1359                        .capture_fixture(
1360                            &workflow,
1361                            input,
1362                            string_arg(options, "from").unwrap_or_default(),
1363                        )
1364                        .await
1365                } else {
1366                    state
1367                        .check_fixture(
1368                            &workflow,
1369                            string_arg(options, "fixture").unwrap_or_default(),
1370                        )
1371                        .await
1372                };
1373                match result {
1374                    Ok(data) => ok(data),
1375                    Err(message) => error("WORKFLOW_FIXTURE_FAILED", message),
1376                }
1377            }
1378        })
1379    }
1380}
1381
1382fn not_found(name: &str) -> CommandResult {
1383    error("WORKFLOW_NOT_FOUND", format!("No workflow named '{name}'"))
1384}
1385
1386/// Builds the `workflows` command group.
1387fn group(state: Arc<State>) -> Cli {
1388    let read_only = McpAnnotations {
1389        read_only_hint: Some(true),
1390        destructive_hint: Some(false),
1391        idempotent_hint: Some(true),
1392        open_world_hint: Some(false),
1393        title: None,
1394    };
1395    let effectful = McpAnnotations {
1396        read_only_hint: Some(false),
1397        destructive_hint: Some(false),
1398        idempotent_hint: Some(false),
1399        open_world_hint: Some(false),
1400        title: None,
1401    };
1402    let destructive = McpAnnotations {
1403        destructive_hint: Some(true),
1404        ..effectful.clone()
1405    };
1406    let execution_arg = || {
1407        field(
1408            "execution_id",
1409            FieldType::String,
1410            true,
1411            Some("Workflow execution identifier"),
1412        )
1413    };
1414    let name_arg = || field("name", FieldType::String, true, Some("Workflow name"));
1415    let optional_name_arg = || {
1416        field(
1417            "name",
1418            FieldType::String,
1419            false,
1420            Some("Workflow name; omit for every workflow"),
1421        )
1422    };
1423    let seq_option = || {
1424        field(
1425            "seq",
1426            FieldType::Number,
1427            false,
1428            Some("Pending action sequence; defaults to the only pending action"),
1429        )
1430    };
1431    let command = |action: Action,
1432                   description: &str,
1433                   annotations: &McpAnnotations,
1434                   args: Vec<FieldMeta>,
1435                   options: Vec<FieldMeta>| {
1436        let mut def = CommandDef::build(
1437            "",
1438            GroupHandler {
1439                state: state.clone(),
1440                action,
1441            },
1442        )
1443        .description(description)
1444        .mcp(McpCommandOptions {
1445            enabled: true,
1446            annotations: Some(annotations.clone()),
1447            ..McpCommandOptions::default()
1448        })
1449        .destructive(annotations.destructive_hint == Some(true))
1450        .done();
1451        def.args_fields = args;
1452        def.options_fields = options;
1453        def
1454    };
1455    let named = |def: CommandDef, name: &str| {
1456        let mut def = def;
1457        def.name = name.to_string();
1458        def
1459    };
1460
1461    let commands = [
1462        (
1463            "capture",
1464            command(
1465                Action::Capture,
1466                "Export a completed workflow's observations for review as a regression fixture",
1467                &read_only,
1468                vec![name_arg()],
1469                vec![
1470                    field(
1471                        "from",
1472                        FieldType::String,
1473                        true,
1474                        Some("Completed execution identifier"),
1475                    ),
1476                    field(
1477                        "input",
1478                        FieldType::Value,
1479                        false,
1480                        Some("Exact workflow input as a JSON object"),
1481                    ),
1482                ],
1483            ),
1484        ),
1485        (
1486            "check",
1487            command(
1488                Action::Check,
1489                "Check current workflow code against a reviewed fixture without invoking host commands",
1490                &read_only,
1491                vec![name_arg()],
1492                vec![field(
1493                    "fixture",
1494                    FieldType::String,
1495                    true,
1496                    Some("Reviewed fixture JSON, or a file path on native hosts"),
1497                )],
1498            ),
1499        ),
1500        (
1501            "list",
1502            command(
1503                Action::List,
1504                "List shipped and saved workflows",
1505                &read_only,
1506                vec![],
1507                vec![],
1508            ),
1509        ),
1510        (
1511            "show",
1512            command(
1513                Action::Show,
1514                "Show a workflow's description, input schema, and program",
1515                &read_only,
1516                vec![name_arg()],
1517                vec![],
1518            ),
1519        ),
1520        (
1521            "run",
1522            command(
1523                Action::Run,
1524                "Run a shipped or saved workflow with JSON input",
1525                &effectful,
1526                vec![name_arg()],
1527                vec![
1528                    field(
1529                        "input",
1530                        FieldType::Value,
1531                        false,
1532                        Some("Workflow input as a JSON object"),
1533                    ),
1534                    result_only_field(),
1535                ],
1536            ),
1537        ),
1538        (
1539            "exec",
1540            command(
1541                Action::Exec,
1542                "Run a Code Mode program in the workflow store so it can be saved",
1543                &effectful,
1544                vec![field(
1545                    "code",
1546                    FieldType::String,
1547                    true,
1548                    Some("Async JavaScript function calling this CLI's commands"),
1549                )],
1550                vec![result_only_field()],
1551            ),
1552        ),
1553        (
1554            "publish",
1555            command(
1556                Action::Publish,
1557                "Publish a callable workflow without executing it",
1558                &effectful,
1559                vec![name_arg()],
1560                vec![
1561                    field(
1562                        "code",
1563                        FieldType::String,
1564                        true,
1565                        Some("Async function accepting the run input"),
1566                    ),
1567                    field(
1568                        "description",
1569                        FieldType::String,
1570                        true,
1571                        Some("What the workflow does"),
1572                    ),
1573                    field(
1574                        "input_schema",
1575                        FieldType::Value,
1576                        false,
1577                        Some("JSON Schema checked before each run"),
1578                    ),
1579                ],
1580            ),
1581        ),
1582        (
1583            "save",
1584            command(
1585                Action::Save,
1586                "Save a completed execution's program as a workflow",
1587                &effectful,
1588                vec![name_arg()],
1589                vec![
1590                    field(
1591                        "from",
1592                        FieldType::String,
1593                        true,
1594                        Some("Completed execution identifier"),
1595                    ),
1596                    field(
1597                        "description",
1598                        FieldType::String,
1599                        true,
1600                        Some("What the workflow does"),
1601                    ),
1602                    field(
1603                        "input_schema",
1604                        FieldType::Value,
1605                        false,
1606                        Some("JSON Schema for the workflow's input"),
1607                    ),
1608                ],
1609            ),
1610        ),
1611        (
1612            "delete",
1613            command(
1614                Action::Delete,
1615                "Delete a saved workflow",
1616                &destructive,
1617                vec![name_arg()],
1618                vec![],
1619            ),
1620        ),
1621        (
1622            "approve",
1623            command(
1624                Action::Approve,
1625                "Approve a paused workflow's pending action and continue it",
1626                &effectful,
1627                vec![execution_arg()],
1628                vec![seq_option()],
1629            ),
1630        ),
1631        (
1632            "reject",
1633            command(
1634                Action::Reject,
1635                "Reject a paused workflow's pending action",
1636                &effectful,
1637                vec![execution_arg()],
1638                vec![seq_option()],
1639            ),
1640        ),
1641        (
1642            "resume",
1643            command(
1644                Action::Resume,
1645                "Continue a workflow interrupted while running",
1646                &effectful,
1647                vec![execution_arg()],
1648                vec![],
1649            ),
1650        ),
1651        (
1652            "cancel",
1653            command(
1654                Action::Cancel,
1655                "Drop an interrupted or paused workflow run without running any more of it",
1656                &destructive,
1657                vec![execution_arg()],
1658                vec![],
1659            ),
1660        ),
1661        (
1662            "status",
1663            command(
1664                Action::Status,
1665                "Show a workflow execution's current status",
1666                &read_only,
1667                vec![execution_arg()],
1668                vec![],
1669            ),
1670        ),
1671        (
1672            "doctor",
1673            command(
1674                Action::Doctor,
1675                "Report workflows and runs that need action; exits 1 when any do",
1676                &read_only,
1677                vec![],
1678                vec![
1679                    field(
1680                        "all",
1681                        FieldType::Boolean,
1682                        false,
1683                        Some("Also report informational notices"),
1684                    ),
1685                    field(
1686                        "stale_days",
1687                        FieldType::Number,
1688                        false,
1689                        Some("Days without a run before a workflow is stale (default 30)"),
1690                    ),
1691                ],
1692            ),
1693        ),
1694        (
1695            "stats",
1696            command(
1697                Action::Stats,
1698                "Show run counts and success rate per workflow version",
1699                &read_only,
1700                vec![optional_name_arg()],
1701                vec![],
1702            ),
1703        ),
1704        (
1705            "failures",
1706            command(
1707                Action::Failures,
1708                "Group failed runs by cause; shows causes not yet followed by a success",
1709                &read_only,
1710                vec![optional_name_arg()],
1711                vec![field(
1712                    "all",
1713                    FieldType::Boolean,
1714                    false,
1715                    Some("Include causes already followed by a success"),
1716                )],
1717            ),
1718        ),
1719        (
1720            "trace",
1721            command(
1722                Action::Trace,
1723                "Show an execution's steps, failure point, error, and console output",
1724                &read_only,
1725                vec![execution_arg()],
1726                vec![field(
1727                    "full",
1728                    FieldType::Boolean,
1729                    false,
1730                    Some("Show arguments, results, and console output untruncated"),
1731                )],
1732            ),
1733        ),
1734    ];
1735    let mut group = Cli::create(GROUP_NAME)
1736        .description("Run, save, and continue durable workflows built from this CLI's commands");
1737    for (name, def) in commands {
1738        group = group.command(name, named(def, name));
1739    }
1740    group
1741}
1742
1743/// Policy for `Workflows::approve_local_commands`: this CLI's own commands run
1744/// without approval and are logged for replay; everything else keeps the default.
1745#[derive(Debug, Clone, Copy)]
1746struct LocalApproval;
1747
1748impl multicast_codemode::ToolPolicyResolver for LocalApproval {
1749    fn resolve(
1750        &self,
1751        origin: multicast_codemode::ToolOrigin,
1752        annotations: &multicast_codemode::ToolAnnotations,
1753    ) -> multicast_codemode::ToolPolicy {
1754        let policy = multicast_codemode::DefaultToolPolicyResolver.resolve(origin, annotations);
1755        if origin == multicast_codemode::ToolOrigin::Local {
1756            multicast_codemode::ToolPolicy {
1757                requires_approval: false,
1758                ..policy
1759            }
1760        } else {
1761            policy
1762        }
1763    }
1764}
1765
1766#[cfg(test)]
1767mod tests {
1768    use super::*;
1769
1770    #[test]
1771    fn local_approval_skips_only_local_commands() {
1772        use multicast_codemode::{ReplayPolicy, ToolAnnotations, ToolOrigin, ToolPolicyResolver};
1773        let write = ToolAnnotations {
1774            read_only: Some(false),
1775            destructive: Some(true),
1776            ..ToolAnnotations::default()
1777        };
1778        let local = LocalApproval.resolve(ToolOrigin::Local, &write);
1779        assert!(!local.requires_approval);
1780        assert_eq!(local.replay, ReplayPolicy::Log);
1781        assert!(
1782            LocalApproval
1783                .resolve(ToolOrigin::RemoteMcp, &write)
1784                .requires_approval
1785        );
1786        assert!(
1787            LocalApproval
1788                .resolve(ToolOrigin::OpenApi, &write)
1789                .requires_approval
1790        );
1791    }
1792
1793    #[tokio::test]
1794    async fn completed_outcome_retains_child_diagnostics() {
1795        use multicast_codemode::RuntimeStore;
1796        let store = Arc::new(multicast_codemode::MemoryStore::default());
1797        let runtime = multicast_codemode::CodeModeRuntime::new(store.clone());
1798        let id = runtime.begin("return 42", vec![], 1).await.unwrap();
1799        let mut state = store.get_execution(&id).await.unwrap().unwrap();
1800        state.status = ExecutionStatus::Completed;
1801        state.result = Some(json!(42));
1802        state
1803            .workflow_children
1804            .push(multicast_codemode::WorkflowChild {
1805                id: "child-fixed".into(),
1806                parent: id,
1807                reference: None,
1808                status: ExecutionStatus::Completed,
1809                pending: vec![],
1810                error: None,
1811            });
1812        let CommandResult::Ok { data, .. } = outcome(&state) else {
1813            panic!("expected completion")
1814        };
1815        assert_eq!(data["result"], 42);
1816        assert_eq!(data["children"][0]["id"], "child-fixed");
1817        assert_eq!(data["children"][0]["status"], "completed");
1818    }
1819
1820    #[test]
1821    fn finds_dot_and_bracket_references() {
1822        let code = r#"async (i) => { await math.sum(i); await math["product"](i); await math['x'](i); notmath.y(); a.math.z(); }"#;
1823        assert_eq!(referenced_methods(code, "math"), ["sum", "product", "x"]);
1824    }
1825
1826    #[test]
1827    fn normalizes_cli_text_for_structured_properties() {
1828        let schema = json!({
1829            "type": "object",
1830            "properties": {
1831                "filter": {"type": "object"},
1832                "ids": {"type": "array", "items": {"type": "integer"}},
1833                "names": {"type": "array", "items": {"type": "string"}},
1834                "label": {"type": "string"},
1835                "note": {"type": ["string", "null"]}
1836            },
1837            "required": ["label"]
1838        });
1839        let input = json!({
1840            "filter": "{\"a\":1}",
1841            "ids": ["1", "2"],
1842            "names": ["1"],
1843            "label": "{\"a\":1}",
1844            "note": null,
1845            "absent": null
1846        });
1847        assert_eq!(
1848            normalize_input(&schema, input),
1849            json!({
1850                "filter": {"a": 1},
1851                "ids": [1, 2],
1852                "names": ["1"],
1853                "label": "{\"a\":1}",
1854                "note": null,
1855                "absent": null
1856            })
1857        );
1858        let dropped = normalize_input(&schema, json!({"label": "x", "filter": null}));
1859        assert_eq!(dropped, json!({"label": "x"}));
1860    }
1861}
1862
1863#[cfg(test)]
1864mod settle_tests {
1865    use super::*;
1866
1867    fn state(status: &str, wait: bool, child_pending: Vec<u64>) -> ExecutionState {
1868        let mut v = json!({
1869            "id": "exec", "code": "", "status": status, "log": [], "result": null, "error": null,
1870            "logs": [], "connectors": [], "created_at": 0, "updated_at": 0,
1871        });
1872        if wait {
1873            v["workflow_wait"] = json!({"children": ["child"], "settle": false});
1874            v["workflow_children"] = json!([{"id": "child", "parent": "exec", "reference": null,
1875                "status": if child_pending.is_empty() { "running" } else { "paused" },
1876                "pending": child_pending, "error": null}]);
1877        }
1878        serde_json::from_value(v).unwrap()
1879    }
1880
1881    #[test]
1882    fn a_run_waiting_on_its_child_workflow_is_still_working() {
1883        assert!(still_working(&state("running", false, vec![])));
1884        assert!(
1885            still_working(&state("paused", true, vec![])),
1886            "a child wait must not end the caller"
1887        );
1888    }
1889
1890    #[test]
1891    fn approval_pauses_and_finished_runs_stop_the_wait() {
1892        assert!(
1893            !still_working(&state("paused", false, vec![])),
1894            "a plain approval pause returns"
1895        );
1896        assert!(
1897            !still_working(&state("paused", true, vec![3])),
1898            "a child waiting for approval returns"
1899        );
1900        assert!(!still_working(&state("completed", false, vec![])));
1901    }
1902}