#![cfg(all(feature = "native", not(target_arch = "wasm32")))]
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use serde_json::{Value, json};
fn binary() -> &'static Path {
static BINARY: OnceLock<PathBuf> = OnceLock::new();
BINARY.get_or_init(|| {
let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
let output = Command::new(env!("CARGO"))
.args(["build", "--locked", "--example", "workflow_math"])
.arg("--manifest-path")
.arg(manifest)
.args(["--message-format", "json"])
.stderr(Stdio::inherit())
.output()
.unwrap();
assert!(output.status.success(), "example build failed");
String::from_utf8(output.stdout)
.unwrap()
.lines()
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
.filter(|message| {
message["reason"] == "compiler-artifact"
&& message["target"]["name"] == "workflow_math"
})
.find_map(|message| message["executable"].as_str().map(PathBuf::from))
.expect("Cargo reported no workflow_math executable")
})
}
struct Fixture {
dir: tempfile::TempDir,
}
impl Fixture {
fn new() -> Self {
Self {
dir: tempfile::tempdir().unwrap(),
}
}
fn log_path(&self) -> PathBuf {
self.dir.path().join("commands.log")
}
fn command(&self, args: &[&str]) -> Command {
let mut command = Command::new(binary());
command
.args(args)
.env("MATH_WORKFLOW_STORE", self.dir.path().join("store.sqlite"))
.env("MATH_COMMAND_LOG", self.log_path())
.env_remove("MATH_SLOW_MS");
command
}
fn run(&self, args: &[&str]) -> (i32, Value) {
self.run_env(&[], args)
}
fn run_env(&self, env: &[(&str, &str)], args: &[&str]) -> (i32, Value) {
let mut all = args.to_vec();
all.extend(["--format", "json"]);
let output: Output = self
.command(&all)
.envs(env.iter().copied())
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
let value = serde_json::from_str(&stdout)
.unwrap_or_else(|_| panic!("non-JSON stdout for {args:?}: {stdout}"));
(output.status.code().unwrap(), value)
}
fn commands_run(&self) -> Vec<String> {
std::fs::read_to_string(self.log_path())
.unwrap_or_default()
.lines()
.map(str::to_string)
.collect()
}
}
fn execution_id(value: &Value) -> String {
value["executionId"].as_str().unwrap().to_string()
}
#[test]
fn reviewed_fixtures_check_without_command_effects_across_processes() {
let fixture = Fixture::new();
let (code, run) = fixture.run(&["add-three", "--a", "1", "--b", "2", "--c", "3"]);
assert_eq!(code, 0);
let (code, mut baseline) = fixture.run(&[
"workflows",
"capture",
"add-three",
"--from",
&execution_id(&run),
"--input",
r#"{"a":1,"b":2,"c":3}"#,
]);
assert_eq!(code, 0, "{baseline}");
assert_eq!(baseline["expected"], json!({"sum":6}));
assert_eq!(
baseline["calls"],
json!([
{"method":"sum","arguments":{"left":1,"right":2},"result":{"sum":3}},
{"method":"sum","arguments":{"left":3,"right":3},"result":{"sum":6}},
])
);
let file = fixture.dir.path().join("reviewed.json");
std::fs::write(&file, serde_json::to_vec(&baseline).unwrap()).unwrap();
let (code, checked) = fixture.run(&[
"workflows",
"check",
"add-three",
"--fixture",
file.to_str().unwrap(),
]);
assert_eq!(code, 0, "{checked}");
assert_eq!(checked["passed"], true);
baseline["expected"]["sum"] = json!(7);
std::fs::write(&file, serde_json::to_vec(&baseline).unwrap()).unwrap();
let (code, failed) = fixture.run(&[
"workflows",
"check",
"add-three",
"--fixture",
file.to_str().unwrap(),
]);
assert_eq!(code, 1);
assert_eq!(failed["code"], "WORKFLOW_FIXTURE_FAILED");
assert!(
failed["message"]
.as_str()
.unwrap()
.contains("result differs")
);
assert_eq!(fixture.commands_run(), ["sum", "sum"]);
}
#[test]
fn shipped_workflow_runs_as_a_command() {
let fixture = Fixture::new();
let (code, value) = fixture.run(&["add-three", "--a", "1", "--b", "2", "--c", "3"]);
assert_eq!(code, 0);
assert_eq!(value["status"], "completed");
assert_eq!(value["result"], json!({"sum": 6}));
assert_eq!(fixture.commands_run(), ["sum", "sum"]);
}
#[test]
fn invalid_input_runs_no_command() {
let fixture = Fixture::new();
let (code, value) = fixture.run(&[
"workflows",
"run",
"add-three",
"--input",
r#"{"a":1,"b":"x","c":3}"#,
]);
assert_eq!(code, 1);
assert_eq!(value["code"], "INVALID_INPUT");
let (code, value) = fixture.run(&[
"workflows",
"run",
"add-three",
"--input",
r#"{"a":1,"b":2,"c":3,"extra":true}"#,
]);
assert_eq!(code, 1);
assert_eq!(value["code"], "INVALID_INPUT");
assert!(fixture.commands_run().is_empty());
let (code, value) = fixture.run(&[
"workflows",
"run",
"add-three",
"--input",
r#"{"a":1,"b":2,"c":3}"#,
]);
assert_eq!(code, 0, "{value}");
assert_eq!(value["result"], json!({"sum": 6}));
assert_eq!(fixture.commands_run(), ["sum", "sum"]);
}
#[test]
fn approval_pause_continues_only_through_a_decision() {
let fixture = Fixture::new();
let (code, paused) = fixture.run(&["sum-and-note", "--left", "2", "--right", "3"]);
assert_eq!(code, multicast_workflows::PAUSED_EXIT_CODE);
assert_eq!(paused["status"], "paused");
assert_eq!(
paused["pending"],
json!([{"seq": 1, "method": "math.note", "arguments": {"text": "5"}}])
);
assert_eq!(fixture.commands_run(), ["sum"]);
let id = execution_id(&paused);
let (code, _) = fixture.run(&["workflows", "resume", &id]);
assert_eq!(code, 1);
assert_eq!(fixture.commands_run(), ["sum"]);
let (code, done) = fixture.run(&["workflows", "approve", &id]);
assert_eq!(code, 0, "{done}");
assert_eq!(done["status"], "completed");
assert_eq!(done["result"], json!({"sum": 5}));
assert_eq!(fixture.commands_run(), ["sum", "note"]);
}
#[test]
fn rejection_ends_the_workflow_without_the_action() {
let fixture = Fixture::new();
let (_, paused) = fixture.run(&["sum-and-note", "--left", "2", "--right", "3"]);
let (code, value) = fixture.run(&["workflows", "reject", &execution_id(&paused)]);
assert_eq!(code, 1);
assert_eq!(value["code"], "WORKFLOW_REJECTED");
assert_eq!(fixture.commands_run(), ["sum"]);
}
#[test]
fn saved_execution_becomes_a_reusable_workflow() {
let fixture = Fixture::new();
let (code, executed) = fixture.run(&[
"workflows",
"exec",
"async () => math.sum({ left: 4, right: 5 })",
]);
assert_eq!(code, 0, "{executed}");
let (code, saved) = fixture.run(&[
"workflows",
"save",
"nine",
"--from",
&execution_id(&executed),
"--description",
"Adds four and five",
]);
assert_eq!(code, 0, "{saved}");
assert_eq!(saved["origin"], "saved");
let (code, listed) = fixture.run(&["workflows", "list"]);
assert_eq!(code, 0);
let names: Vec<(&str, &str)> = listed
.as_array()
.unwrap()
.iter()
.map(|item| {
(
item["name"].as_str().unwrap(),
item["origin"].as_str().unwrap(),
)
})
.collect();
assert!(names.contains(&("nine", "saved")), "{names:?}");
assert!(names.contains(&("add-three", "shipped")), "{names:?}");
let (code, ran) = fixture.run(&["workflows", "run", "nine"]);
assert_eq!(code, 0, "{ran}");
assert_eq!(ran["result"], json!({"sum": 9}));
assert_eq!(fixture.commands_run(), ["sum", "sum"]);
let (code, value) = fixture.run(&[
"workflows",
"save",
"add-three",
"--from",
&execution_id(&executed),
"--description",
"Shadow",
]);
assert_eq!(code, 1);
assert_eq!(value["code"], "WORKFLOW_SHIPPED");
let (code, _) = fixture.run(&["workflows", "delete", "nine"]);
assert_eq!(code, 0);
let (code, value) = fixture.run(&["workflows", "run", "nine"]);
assert_eq!(code, 1);
assert_eq!(value["code"], "WORKFLOW_NOT_FOUND");
}
#[test]
fn workflows_cannot_call_workflow_commands() {
let fixture = Fixture::new();
for code in [
r#"async () => math["add-three"]({ a: 1, b: 2, c: 3 })"#,
"async () => math.workflows_list({})",
] {
let (exit, value) = fixture.run(&["workflows", "exec", code]);
assert_eq!(exit, 1, "{value}");
assert_eq!(value["code"], "WORKFLOW_FAILED");
assert!(
value["message"].as_str().unwrap().contains("not found"),
"{value}"
);
}
assert!(fixture.commands_run().is_empty());
}
fn kill_slow_sum(fixture: &Fixture) -> String {
let mut child = fixture
.command(&["slow-sum", "--left", "2", "--right", "3"])
.env("MATH_SLOW_MS", "60000")
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut stderr = BufReader::new(child.stderr.take().unwrap());
let mut announcement = String::new();
stderr.read_line(&mut announcement).unwrap();
let id = announcement
.strip_prefix("workflow execution ")
.and_then(|rest| rest.strip_suffix(" started\n"))
.unwrap_or_else(|| panic!("unexpected announcement: {announcement}"))
.to_string();
let deadline = Instant::now() + Duration::from_secs(30);
while !fixture.commands_run().contains(&"slow".to_string()) {
assert!(Instant::now() < deadline, "slow command never started");
std::thread::sleep(Duration::from_millis(20));
}
child.kill().unwrap();
child.wait().unwrap();
id
}
#[test]
fn killed_run_resumes_in_a_new_process() {
let fixture = Fixture::new();
let id = kill_slow_sum(&fixture);
let (code, status) = fixture.run(&["workflows", "status", &id]);
assert_eq!(code, 0);
assert_eq!(status["status"], "running");
let (code, resumed) = fixture.run(&["workflows", "resume", &id]);
assert_eq!(code, 0, "{resumed}");
assert_eq!(resumed["status"], "completed");
assert_eq!(resumed["result"], json!({"sum": 5}));
assert_eq!(fixture.commands_run(), ["slow", "slow", "sum"]);
}
struct McpSession {
child: std::process::Child,
stdin: std::process::ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
next_id: u64,
}
impl McpSession {
fn start(fixture: &Fixture, args: &[&str]) -> Self {
let mut child = fixture
.command(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());
let mut session = Self {
child,
stdin,
stdout,
next_id: 0,
};
session.request(json!({"method": "initialize", "params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "workflows-test", "version": "1"}
}}));
session.send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
session
}
fn send(&mut self, message: Value) {
writeln!(self.stdin, "{message}").unwrap();
self.stdin.flush().unwrap();
}
fn request(&mut self, request: Value) -> Value {
self.next_id += 1;
let id = json!(self.next_id);
let mut message = request;
message["jsonrpc"] = json!("2.0");
message["id"] = id.clone();
self.send(message);
let mut line = String::new();
loop {
line.clear();
assert_ne!(
self.stdout.read_line(&mut line).unwrap(),
0,
"MCP server exited"
);
let response: Value = serde_json::from_str(&line).unwrap();
if response["id"] == id {
return response;
}
}
}
}
impl Drop for McpSession {
fn drop(&mut self) {
self.child.kill().ok();
self.child.wait().ok();
}
}
fn mcp(fixture: &Fixture, requests: &[Value]) -> Vec<Value> {
let mut session = McpSession::start(fixture, &["--mcp"]);
requests
.iter()
.map(|request| session.request(request.clone()))
.collect()
}
fn call(name: &str, arguments: Value) -> Value {
json!({"method": "tools/call", "params": {
"name": "call_write_tool",
"arguments": {"name": name, "arguments": arguments}
}})
}
fn text_json(response: &Value) -> Value {
serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap()
}
#[test]
fn shipped_workflow_is_an_mcp_tool() {
let fixture = Fixture::new();
let responses = mcp(
&fixture,
&[
json!({"method": "tools/call", "params": {
"name": "get_tool_details", "arguments": {"name": "add-three"}
}}),
call("add-three", json!({"a": 1, "b": 2, "c": 3})),
call(
"workflows_run",
json!({"name": "add-three", "input": {"a": 1, "b": 2}}),
),
],
);
let details = text_json(&responses[0]);
assert_eq!(details["inputSchema"]["required"], json!(["a", "b", "c"]));
assert_eq!(responses[1]["result"]["isError"], false, "{}", responses[1]);
let ran = text_json(&responses[1]);
assert_eq!(ran["status"], "completed");
assert_eq!(ran["result"], json!({"sum": 6}));
assert_eq!(responses[2]["result"]["isError"], true, "{}", responses[2]);
assert_eq!(text_json(&responses[2])["code"], "INVALID_INPUT");
assert_eq!(fixture.commands_run(), ["sum", "sum"]);
}
fn findings(report: &Value) -> Vec<(String, String, String)> {
report["findings"]
.as_array()
.unwrap()
.iter()
.map(|finding| {
(
finding["severity"].as_str().unwrap().to_string(),
finding["check"].as_str().unwrap().to_string(),
finding["workflow"].as_str().unwrap().to_string(),
)
})
.collect()
}
fn finding(severity: &str, check: &str, workflow: &str) -> (String, String, String) {
(severity.into(), check.into(), workflow.into())
}
#[test]
fn a_new_catalog_is_healthy_and_quiet() {
let fixture = Fixture::new();
let (code, report) = fixture.run(&["workflows", "doctor"]);
assert_eq!(code, 0, "{report}");
assert_eq!(report["healthy"], true);
assert_eq!(report["findings"], json!([]));
assert_eq!(report["notices"], 4);
let (code, report) = fixture.run(&["workflows", "doctor", "--all"]);
assert_eq!(code, 0, "{report}");
let found = findings(&report);
assert_eq!(found.len(), 4, "{report}");
assert!(
found
.iter()
.all(|(severity, check, _)| severity == "notice" && check == "never-run")
);
}
#[test]
fn repeated_failures_group_by_cause_until_a_success() {
let fixture = Fixture::new();
let mut last = String::new();
for numerator in ["5", "7", "9"] {
let (code, value) =
fixture.run(&["ratio", "--left", numerator, "--right", "0", "--by", "0"]);
assert_eq!(code, 1, "{value}");
last = value["message"]
.as_str()
.unwrap()
.split_whitespace()
.nth(2)
.unwrap()
.to_string();
}
let (code, report) = fixture.run(&["workflows", "doctor"]);
assert_eq!(code, 1, "{report}");
assert_eq!(findings(&report), [finding("error", "failing", "ratio")]);
assert_eq!(report["findings"][0]["executionId"], last);
let (code, failures) = fixture.run(&["workflows", "failures", "ratio"]);
assert_eq!(code, 0);
let causes = failures["causes"].as_array().unwrap();
assert_eq!(causes.len(), 1, "{failures}");
assert_eq!(causes[0]["count"], 3);
assert_eq!(causes[0]["step"], "math.divide");
assert_eq!(
causes[0]["message"],
"DIVISION_BY_ZERO: Cannot divide # by zero"
);
assert_eq!(
causes[0]["sample"],
"DIVISION_BY_ZERO: Cannot divide 9 by zero"
);
let (code, trace) = fixture.run(&["workflows", "trace", &last]);
assert_eq!(code, 0);
assert_eq!(trace["workflow"], "ratio");
assert_eq!(trace["failedAt"], json!({"seq": 1, "call": "math.divide"}));
let calls: Vec<&str> = trace["steps"]
.as_array()
.unwrap()
.iter()
.map(|step| step["call"].as_str().unwrap())
.collect();
assert_eq!(calls, ["math.sum", "math.divide"]);
assert_eq!(
trace["steps"][1]["arguments"],
json!({"numerator": 9, "denominator": 0})
);
let (code, _) = fixture.run(&["ratio", "--left", "1", "--right", "2", "--by", "3"]);
assert_eq!(code, 0);
let (code, report) = fixture.run(&["workflows", "doctor"]);
assert_eq!(code, 0, "{report}");
let (_, failures) = fixture.run(&["workflows", "failures"]);
assert_eq!(failures["causes"], json!([]));
assert_eq!(failures["resolvedHidden"], 1);
let (_, stats) = fixture.run(&["workflows", "stats", "ratio"]);
assert_eq!(stats[0]["runs"], 4);
assert_eq!(stats[0]["completed"], 1);
assert_eq!(stats[0]["failed"], 3);
assert_eq!(stats[0]["successRate"], 0.25);
}
#[test]
fn a_single_failure_is_a_warning() {
let fixture = Fixture::new();
let (code, _) = fixture.run(&["ratio", "--left", "1", "--right", "1", "--by", "0"]);
assert_eq!(code, 1);
let (code, report) = fixture.run(&["workflows", "doctor"]);
assert_eq!(code, 1, "{report}");
assert_eq!(findings(&report), [finding("warning", "failed", "ratio")]);
}
#[test]
fn doctor_reports_saved_workflows_that_drifted_from_the_cli() {
let fixture = Fixture::new();
let (_, paused) = fixture.run(&[
"workflows",
"exec",
"async () => { const total = await math.sum({ left: 1, right: 1 }); await math.note({ text: 'x' }); return total; }",
]);
let (code, done) = fixture.run(&["workflows", "approve", &execution_id(&paused)]);
assert_eq!(code, 0, "{done}");
let (code, _) = fixture.run(&[
"workflows",
"save",
"noted",
"--from",
&execution_id(&done),
"--description",
"Notes",
]);
assert_eq!(code, 0);
let (code, report) = fixture.run(&["workflows", "doctor"]);
assert_eq!(code, 0, "{report}");
let without_note = [("MATH_WITHOUT_NOTE", "1")];
let (code, report) = fixture.run_env(&without_note, &["workflows", "doctor"]);
assert_eq!(code, 1, "{report}");
assert_eq!(
findings(&report),
[finding("error", "missing-command", "noted")]
);
assert!(
report["findings"][0]["message"]
.as_str()
.unwrap()
.contains("math.note")
);
let (_, executed) = fixture.run_env(&without_note, &["workflows", "exec", "async () => 1"]);
let (code, saved) = fixture.run_env(
&without_note,
&[
"workflows",
"save",
"sum-and-note",
"--from",
&execution_id(&executed),
"--description",
"One",
],
);
assert_eq!(code, 0, "{saved}");
let (code, report) = fixture.run(&["workflows", "doctor"]);
assert_eq!(code, 1, "{report}");
assert_eq!(
findings(&report),
[finding("warning", "shadowed", "sum-and-note")]
);
}
#[test]
fn doctor_reports_duplicate_saved_programs_as_notices() {
let fixture = Fixture::new();
let (_, executed) = fixture.run(&[
"workflows",
"exec",
"async () => math.sum({ left: 1, right: 2 })",
]);
for name in ["three", "also-three"] {
let (code, _) = fixture.run(&[
"workflows",
"save",
name,
"--from",
&execution_id(&executed),
"--description",
"Three",
]);
assert_eq!(code, 0);
}
let (code, report) = fixture.run(&["workflows", "doctor"]);
assert_eq!(code, 0, "{report}");
let (_, report) = fixture.run(&["workflows", "doctor", "--all"]);
let found = findings(&report);
assert!(
found.contains(&finding("notice", "duplicate", "three")),
"{found:?}"
);
assert!(
found.contains(&finding("notice", "duplicate", "also-three")),
"{found:?}"
);
}
#[test]
fn doctor_reports_interrupted_and_waiting_runs() {
let fixture = Fixture::new();
let interrupted = kill_slow_sum(&fixture);
let (_, paused) = fixture.run(&["sum-and-note", "--left", "2", "--right", "3"]);
let waiting = execution_id(&paused);
let (code, report) = fixture.run(&["workflows", "doctor"]);
assert_eq!(code, 1, "{report}");
let found = report["findings"].as_array().unwrap();
assert_eq!(found.len(), 2, "{report}");
let by_check = |check: &str| found.iter().find(|item| item["check"] == check).unwrap();
assert_eq!(by_check("interrupted")["executionId"], interrupted);
assert_eq!(
by_check("interrupted")["hint"],
format!("workflows resume {interrupted}, or workflows cancel {interrupted} to drop it")
);
assert_eq!(by_check("awaiting-decision")["executionId"], waiting);
assert!(
by_check("awaiting-decision")["message"]
.as_str()
.unwrap()
.contains("math.note")
);
let (code, _) = fixture.run(&["workflows", "resume", &interrupted]);
assert_eq!(code, 0);
let (code, _) = fixture.run(&["workflows", "approve", &waiting]);
assert_eq!(code, 0);
let (code, report) = fixture.run(&["workflows", "doctor"]);
assert_eq!(code, 0, "{report}");
}
#[test]
fn cancel_drops_an_interrupted_run_without_running_it_again() {
let fixture = Fixture::new();
let interrupted = kill_slow_sum(&fixture);
let slow_before = fixture
.commands_run()
.iter()
.filter(|name| *name == "slow")
.count();
let (code, cancelled) = fixture.run(&["workflows", "cancel", &interrupted]);
assert_eq!(code, 0, "{cancelled}");
let (code, report) = fixture.run(&["workflows", "doctor"]);
assert_eq!(code, 0, "a cancelled run needs no action: {report}");
let slow_after = fixture
.commands_run()
.iter()
.filter(|name| *name == "slow")
.count();
assert_eq!(
slow_after, slow_before,
"cancel must not run the program again"
);
}
#[test]
fn doctor_marks_runs_lost_with_the_store() {
let fixture = Fixture::new();
let (_, paused) = fixture.run(&["sum-and-note", "--left", "2", "--right", "3"]);
let id = execution_id(&paused);
for entry in std::fs::read_dir(fixture.dir.path()).unwrap() {
let path = entry.unwrap().path();
let name = path.file_name().unwrap().to_str().unwrap().to_string();
if name.starts_with("store.sqlite") {
std::fs::remove_file(path).unwrap();
}
}
let (code, report) = fixture.run(&["workflows", "doctor", "--all"]);
assert_eq!(code, 0, "{report}");
let lost: Vec<&Value> = report["findings"]
.as_array()
.unwrap()
.iter()
.filter(|item| item["check"] == "lost")
.collect();
assert_eq!(lost.len(), 1, "{report}");
assert_eq!(lost[0]["executionId"], id);
let (_, stats) = fixture.run(&["workflows", "stats", "sum-and-note"]);
assert_eq!(stats[0]["lost"], 1);
let (code, trace) = fixture.run(&["workflows", "trace", &id]);
assert_eq!(code, 0, "{trace}");
assert_eq!(trace["status"], "lost");
}
#[test]
fn codemode_server_runs_programs_against_cli_commands() {
let fixture = Fixture::new();
let mut session = McpSession::start(&fixture, &["--codemode"]);
let tools = session.request(json!({"method": "tools/list", "params": {}}));
let mut names: Vec<&str> = tools["result"]["tools"]
.as_array()
.unwrap()
.iter()
.map(|tool| tool["name"].as_str().unwrap())
.collect();
names.sort_unstable();
assert_eq!(
names,
[
"codemode_cancel",
"codemode_decide",
"codemode_execute",
"codemode_execution",
"codemode_search"
]
);
let started = session.request(json!({"method": "tools/call", "params": {
"name": "codemode_execute",
"arguments": {"code": "math.sum({ left: 2, right: 3 })"}
}}));
assert_eq!(started["result"]["isError"], false, "{started}");
let id = text_json(&started)["id"].as_str().unwrap().to_string();
let deadline = Instant::now() + Duration::from_secs(20);
let execution = loop {
let read = session.request(json!({"method": "tools/call", "params": {
"name": "codemode_execution", "arguments": {"id": id}
}}));
let execution = text_json(&read);
if execution["status"] != "running" {
break execution;
}
assert!(Instant::now() < deadline, "execution never finished");
std::thread::sleep(Duration::from_millis(50));
};
assert_eq!(execution["status"], "completed", "{execution}");
assert_eq!(execution["result"], json!({"sum": 5}));
assert_eq!(fixture.commands_run(), ["sum"]);
let search = session.request(json!({"method": "tools/call", "params": {
"name": "codemode_search", "arguments": {"query": "workflows"}
}}));
let found = search["result"]["content"][0]["text"].as_str().unwrap();
assert!(!found.contains("workflows_run"), "{found}");
}
#[test]
fn published_workflows_accept_fresh_inputs_without_publication_effects() {
let fixture = Fixture::new();
let schema = r#"{"type":"object","properties":{"left":{"type":"integer"},"right":{"type":"integer"}},"required":["left","right"],"additionalProperties":false}"#;
let publish = |name: &str, schema: &str| {
fixture.run(&[
"workflows",
"publish",
name,
"--description",
"Add fresh inputs",
"--code",
"async (input) => math.sum(input)",
"--input-schema",
schema,
])
};
let (exit, published) = publish("fresh", schema);
assert_eq!(exit, 0, "{published}");
assert!(fixture.commands_run().is_empty());
for (input, expected) in [
(r#"{"left":2,"right":3}"#, 5),
(r#"{"left":8,"right":9}"#, 17),
] {
let (exit, run) = fixture.run(&["workflows", "run", "fresh", "--input", input]);
assert_eq!(exit, 0, "{run}");
assert_eq!(run["result"], json!({"sum": expected}));
}
let (exit, invalid) = publish("fresh", r#"{"type":"object","unsupported":true}"#);
assert_eq!(exit, 1, "{invalid}");
assert_eq!(invalid["code"], "INVALID_SCHEMA");
let (exit, shipped) = publish("add-three", schema);
assert_eq!(exit, 1);
assert_eq!(shipped["code"], "WORKFLOW_SHIPPED");
let (exit, run) = fixture.run(&[
"workflows",
"run",
"fresh",
"--input",
r#"{"left":20,"right":1}"#,
]);
assert_eq!(exit, 0, "{run}");
assert_eq!(run["result"], json!({"sum":21}));
assert_eq!(fixture.commands_run(), ["sum", "sum", "sum"]);
}
#[test]
fn result_only_preserves_values_failures_pauses_and_fresh_workflow_inputs() {
let fixture = Fixture::new();
for (source, expected) in [
("async () => false", json!(false)),
("async () => 0", json!(0)),
("async () => null", Value::Null),
("async () => ({answer:42})", json!({"answer":42})),
] {
let output = fixture
.command(&[
"workflows",
"exec",
source,
"--result-only",
"--format",
"json",
])
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stdout)
);
assert_eq!(
serde_json::from_slice::<Value>(&output.stdout).unwrap(),
expected
);
assert!(
output.stderr.is_empty(),
"completed result-only executions must not announce metadata"
);
}
let (exit, failed) = fixture.run(&[
"workflows",
"exec",
"async () => { throw new Error('deliberate failure'); }",
"--result-only",
]);
assert_eq!(exit, 1);
assert_eq!(failed["code"], "WORKFLOW_FAILED");
let (exit, paused) = fixture.run(&[
"workflows",
"exec",
"async () => math.note({message:'approval'})",
"--result-only",
]);
assert_eq!(exit, 75);
assert_eq!(paused["status"], "paused");
assert!(paused["executionId"].is_string());
let (exit, published) = fixture.run(&[
"workflows",
"publish",
"predicate",
"--description",
"Compare fresh inputs",
"--code",
"async (input) => input.answer === 42",
]);
assert_eq!(exit, 0, "{published}");
for (input, expected) in [(r#"{"answer":42}"#, true), (r#"{"answer":41}"#, false)] {
let (exit, value) = fixture.run(&[
"workflows",
"run",
"predicate",
"--input",
input,
"--result-only",
]);
assert_eq!(exit, 0);
assert_eq!(value, json!(expected));
}
}